[POI2014]KUR-Couriers
题目描述
Byteasar works for the BAJ company, which sells computer games.
The BAJ company cooperates with many courier companies that deliver the games sold by the BAJ company to its customers.
Byteasar is inspecting the cooperation of the BAJ company with the couriers.
He has a log of successive packages with the courier company that made the delivery specified for each package.
He wants to make sure that no courier company had an unfair advantage over the others.
If a given courier company delivered more than half of all packages sent in some period of time, we say that it dominated in that period.
Byteasar wants to find out which courier companies dominated in certain periods of time, if any.
Help Byteasar out!
Write a program that determines a dominating courier company or that there was none.
给一个数列,每次询问一个区间内有没有一个数出现次数超过一半
输入格式
The answers to successive queries should be printed to the standard output, one per line.
(Thus a total of lines should be printed.) Each line should hold a single integer: the number of the courier company that dominated in the corresponding time period, or if there was no such company.
输入 #1
7 5
1 1 3 2 3 4 3
1 3
1 4
3 7
1 7
6 6
输出 #1
1
0
3
0
4
一道比较裸的主席树板子题,跟区间第k大有点相似,这里还不要离散化;
就是比较区间权值与(r-l+1)/2的大小,如果大于,说明区间内有数的出现次数大于一半,这个时候要先遍历左区间,再遍历右区间;
代码:
#include<bits/stdc++.h>
using namespace std;
const int M=500100;
int rt[M];
int k;
struct Node{
int l,r,w;
}tree[M*32];
inline int build(int ll,int rr){
int nw=++k;
int md=(ll+rr)>>1;
if(ll<rr){
tree[nw].l=build(ll,md);
tree[nw].r=build(md+1,rr);
}
return nw;
}
inline void add(int &nw,int pr,int ll,int rr,int x){
nw=++k;
tree[nw].l=tree[pr].l,tree[nw].r=tree[pr].r,tree[nw].w=tree[pr].w+1;
if(ll==rr) return;
int md=(ll+rr)>>1;
if(x<=md){
add(tree[nw].l,tree[pr].l,ll,md,x);
}
else{
add(tree[nw].r,tree[pr].r,md+1,rr,x);
}
}
inline int query(int pr,int nw,int ll,int rr,int x){
if(ll==rr) return ll;
int md=(ll+rr)>>1;
int ans1=tree[tree[nw].l].w-tree[tree[pr].l].w;
int ans2=tree[tree[nw].r].w-tree[tree[pr].r].w;
if(2*ans1>x) return query(tree[pr].l,tree[nw].l,ll,md,x);
else if(2*ans2>x) return query(tree[pr].r,tree[nw].r,md+1,rr,x);
return 0;
}
int main(){
int n,m;
scanf("%d%d",&n,&m);
rt[0]=build(1,n);
for(int i=1;i<=n;i++){
int x;
scanf("%d",&x);
add(rt[i],rt[i-1],1,n,x);
}
for(int i=1;i<=m;i++){
int l,r;
scanf("%d%d",&l,&r);
printf("%d\n",query(rt[l-1],rt[r],1,n,r-l+1));
}
return 0;
}