codeforces 840D 主席树

D. Destiny
time limit per test 2.5 seconds
memory limit per test 512 megabytes
input standard input
output standard output
Once, Leha found in the left pocket an array consisting of n integers, and in the right pocket q queries of the form l r k. If there are queries, then they must be answered. Answer for the query is minimal x such that x occurs in the interval l r strictly more than  times or  - 1 if there is no such number. Help Leha with such a difficult task.

Input
First line of input data contains two integers n and q (1 ≤ n, q ≤ 3·105) — number of elements in the array and number of queries respectively.

Next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — Leha's array.

Each of next q lines contains three integers l, r and k (1 ≤ l ≤ r ≤ n, 2 ≤ k ≤ 5) — description of the queries.

Output
Output answer for each query in new line.

Examples
input
4 2
1 1 2 2
1 3 2
1 4 2
output
1
-1
input
5 3
1 2 1 3 2
2 5 3
1 2 3
5 5 2
output
2
1
2

题意:给N个数·,Q个询问,每个询问找出区间内出现次数大于所给公式的值中最小的那一个。

思路:

①线段树,每个点都建一棵新的线段树,查询时优先处理左子树,比较一下两个点之间新增的节点数是否满足题意即可。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>

using namespace std;

const int N = 3e5+10;
int ls[N*21],rs[N*21],sum[N*21];
int T[N],a[N];

int tot;
int ans;
void update(int& now,int pre,int l,int r,int d)
{
    now=++tot;
    sum[now]=sum[pre]+1;
    ls[now]=ls[pre];
    rs[now]=rs[pre];

    if(l==r)
        return;
    else
    {
        int mid=(l+r)/2;
        if(d<=mid)
            update(ls[now],ls[pre],l,mid,d);
        else
            update(rs[now],rs[pre],mid+1,r,d);
    }
}

void query(int L,int R,int l,int r,int d)
{
    if(sum[R]-sum[L]<=d)
        return ;
    if(l==r)
    {
        if(ans==-1)
            ans=l;
        return ;
    }

    int mid=(l+r)/2;
    if(ans==-1)
        query(ls[L],ls[R],l,mid,d);
    if(ans==-1)
        query(rs[L],rs[R],mid+1,r,d);
}

int main()
{
    int n,q;
    while(~scanf("%d%d",&n,&q))
    {
        tot=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        for(int i=1;i<=n;i++)
        {
            update(T[i],T[i-1],1,n,a[i]);
        }

        while(q--)
        {
            int l,r,k;
            scanf("%d%d%d",&l,&r,&k);
            int vv=(r-l+1)/k;
            ans=-1;
            query(T[l-1],T[r],1,n,vv);
            printf("%d\n",ans);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/c_czl/article/details/85270279