Codeforces Round #429 (Div. 1) D. Destiny(主席树)

解决Leha面临的查询难题,寻找区间内出现次数超过特定比例的最小整数。使用主席树进行高效查询,针对每个查询输出答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 lr 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;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值