您的位置:首页 > 其它

codeforces 840D 主席树

2017-11-10 23:51 309 查看
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 rstrictlymore than  times or  - 1 if there isno such number. Help Leha with such a difficult task.InputFirst line of input data contains two integers n and q (1 ≤ n, q ≤ 3·105) — number of elements inthe 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.OutputOutput answer for each query in new line.ExampleInput
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一开始想不到怎么搞,因为树的权值无法同时代表着次数和具体的值,如果暴力找感觉会很慢。然而其实并不会,因为一个区间出现的总数是固定的,如果每个链出现的次数多,那么别的链访问的次数就少了,所以只要sum[you]-sum[zuo]<k 我们就不访问了,树的下标是具体的值,权值的出现的次数,就很简单了#include <bits/stdc++.h>using namespace std;const int N = 3e5+10;int ls[N*21],rs[N*21],sum[N*21];int T,a;int tot;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 ;int mid=(l+r)>>1;if(d<=mid) update(ls[now],ls[pre],l,mid,d);else update(rs[now],rs[pre],mid+1,r,d);}int ans;void query(int zuo,int you,int l,int r,int d){if(sum[you]-sum[zuo]<d) return ;if(l==r){if(ans==-1)ans=l;return ;}int mid=(l+r)>>1;query(ls[zuo],ls[you],l,mid,d);query(rs[zuo],rs[you],mid+1,r,d);}int main(){int n,q;tot=0;scanf("%d%d",&n,&q);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)/k;ans=-1;query(T[l-1],T[r],1,n,vv);printf("%d\n",ans );}}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: