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 rstrictly more than times or - 1 if there is no such number. Help Leha with such a difficult task.
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 answer for each query in new line.
4 2 1 1 2 2 1 3 2 1 4 2
1 -1
5 3 1 2 1 3 2 2 5 3 1 2 3 5 5 2
2 12
一开始想不到怎么搞,因为树的权值无法同时代表着次数和具体的值,如果暴力找感觉会很慢。然而其实并不会,因为一个区间出现的总数是固定的,如果每个链出现的次数多,那么别的链访问的次数就少了,所以只要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[N],a[N]; 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 ); } }