codeforces 840D 主席树

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.

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.

Example
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

一开始想不到怎么搞,因为树的权值无法同时代表着次数和具体的值,如果暴力找感觉会很慢。然而其实并不会,因为一个区间出现的总数是固定的,如果每个链出现的次数多,那么别的链访问的次数就少了,所以只要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 );
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值