权限题
传送门:https://szkopul.edu.pl/problemset/problem/Cs38m8lWFnOfDskXf43HR3lN/site/?key=statement
Description
给一个长度为n的序列a。1≤a[i]≤n。
m组询问,每次询问一个区间[l,r],是否存在一个数在[l,r]中出现的次数大于(r-l+1)/2。如果存在,输出这个数,否则输出0。
Input
第一行两个数n,m。
第二行n个数,a[i]。
接下来m行,每行两个数l,r,表示询问[l,r]这个区间。
Output
m行,每行对应一个答案。
Sample Input
7 5
1 1 3 2 3 4 3
1 3
1 4
3 7
1 7
6 6
Sample Output
1
0
3
0
4
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=5e5+5;
struct node{
int ls,rs,sum;
}tree[maxn*20];
int m,n,tot;
int root[maxn];
inline void update(int pre,int &cur,int L,int R,int x)
{
cur=++tot;
tree[cur]=tree[pre];
tree[cur].sum++;
if(L==R) return;
int mid=L+R>>1;
if(x<=mid) update(tree[pre].ls,tree[cur].ls,L,mid,x);
else update(tree[pre].rs,tree[cur].rs,mid+1,R,x);
}
inline int query(int pre,int cur,int L,int R,int k)
{
if(L==R){
if(tree[cur].sum-tree[pre].sum>k) return L;
else return 0;
}
int mid=L+R>>1;
if(tree[tree[cur].ls].sum-tree[tree[pre].ls].sum>k)
return query(tree[pre].ls,tree[cur].ls,L,mid,k);
else if(tree[tree[cur].rs].sum-tree[tree[pre].rs].sum>k)
return query(tree[pre].rs,tree[cur].rs,mid+1,R,k);
else return 0;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
int x;
scanf("%d",&x);
update(root[i-1],root[i],1,n,x);
}
for(int i=1;i<=m;i++){
static int l,r,ans;
scanf("%d%d",&l,&r);
ans=query(root[l-1],root[r],1,n,(r-l+1)/2);
printf("%d\n",ans);
}
return 0;
}