【LOJ】#2432. 「POI2014」代理商 Couriers
题解
建出一个主席树,因为出现大于区间一半的数只能有一个,就看看左右区间的增加有没有大于一半,如果有就走向那个子树,如果没有那么返回0
代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <set>
#include <cmath>
#include <bitset>
#include <queue>
#define enter putchar('\n')
#define space putchar(' ')
//#define ivorysi
#define pb push_back
#define mo 974711
#define pii pair<int,int>
#define mp make_pair
#define fi first
#define se second
#define MAXN 500005
#define eps 1e-12
using namespace std;
typedef long long int64;
typedef double db;
template<class T>
void read(T &res) {
res = 0;char c = getchar();T f = 1;
while(c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while(c >= '0' && c <= '9') {
res = res * 10 - '0' + c;
c = getchar();
}
res = res * f;
}
template<class T>
void out(T x) {
if(x < 0) {x = -x;putchar('-');}
if(x >= 10) out(x / 10);
putchar('0' + x % 10);
}
int N,M;
int a[MAXN];
struct node {
int lc,rc;
int siz;
}tr[MAXN * 80];
int Ncnt,rt[MAXN];
void Insert(int x,int &y,int L,int R,int pos) {
y = ++Ncnt;
tr[y] = tr[x];
tr[y].siz++;
if(L == R) return;
int mid = (L + R) >> 1;
if(pos <= mid) Insert(tr[x].lc,tr[y].lc,L,mid,pos);
else Insert(tr[x].rc,tr[y].rc,mid + 1,R,pos);
}
int check(int L,int R) {
int k = ((R - L + 1) / 2) + 1;
int Lrt = rt[L - 1],Rrt = rt[R];
int l = 1,r = N;
while(l < r) {
int mid = (l + r) >> 1;
if(tr[tr[Rrt].lc].siz - tr[tr[Lrt].lc].siz >= k) {
Lrt = tr[Lrt].lc;Rrt = tr[Rrt].lc;
r = mid;
}
else if(tr[tr[Rrt].rc].siz - tr[tr[Lrt].rc].siz >= k) {
Lrt = tr[Lrt].rc;Rrt = tr[Rrt].rc;
l = mid + 1;
}
else {return 0;}
}
return l;
}
void Solve() {
read(N);read(M);
for(int i = 1 ; i <= N ; ++i) read(a[i]);
for(int i = 1 ; i <= N ; ++i) Insert(rt[i - 1],rt[i],1,N,a[i]);
int l,r;
for(int i = 1 ; i <= M ; ++i) {
read(l);read(r);
out(check(l,r));enter;
}
}
int main() {
#ifdef ivorysi
freopen("f1.in","r",stdin);
#endif
Solve();
}