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
分析:k很小,只有2到5,然后我们考虑将l 到 r的数排序后,设 p =
,那么答案一定是第k*p个数,因为如果答案出现多于p次那么一定会跨越一个边界,因为k很小所以我们顶多试5次,直接用主席树求解就可以了.

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define N 300005
using namespace std;
struct Thing
{
int ls,rs,sum = 0;
}tr[N*30];
int n,q,p,cnt,a[N],rt[N];
bool flag;
void Build(int &node,int l,int r)
{
node = ++cnt;
tr[node].sum = 0;
if(l == r) return;
int mid = (l+r)>>1;
Build(tr[node].ls,l,mid);
Build(tr[node].rs,mid+1,r);
}
void Insert(int pre,int &node,int l,int r,int pos)
{
node = ++cnt;
tr[node] = tr[pre];
tr[node].sum++;
if(l == r) return;
int mid = (l+r)>>1;
if(pos <= mid) Insert(tr[pre].ls,tr[node].ls,l,mid,pos);
else Insert(tr[pre].rs,tr[node].rs,mid+1,r,pos);
}
int Query(int pre,int node,int l,int r,int k)
{
if(l == r)
{
flag = (tr[node].sum - tr[pre].sum) > p;
return l;
}
int cmp = tr[tr[node].ls].sum - tr[tr[pre].ls].sum,mid = (l+r)>>1;
if(cmp >= k)return Query(tr[pre].ls,tr[node].ls,l,mid,k);
else return Query(tr[pre].rs,tr[node].rs,mid+1,r,k-cmp);
}
int main()
{
scanf("%d%d",&n,&q);
for(int i = 1;i <= n;i++) scanf("%d",&a[i]);
Build(rt[0],1,n);
for(int i = 1;i <= n;i++) Insert(rt[i-1],rt[i],1,n,a[i]);
for(int i = 1;i <= q;i++)
{
int l,r,k,ans;
scanf("%d%d%d",&l,&r,&k);
p = (r - l + 1)/k,ans = -1;
if(!p)
{
cout<<Query(rt[l-1],rt[r],1,n,1)<<endl;
continue;
}
flag = false;
for(int j = p;j <= (r - l + 1);j += p)
{
int t = Query(rt[l-1],rt[r],1,n,j);
if(flag)
{
ans = t;
break;
}
}
cout<<ans<<endl;
}
}