【BZOJ3524】Couriers(主席树)
2024-10-21 06:48:49
题意:给一个长度为n的序列a。1≤a[i]≤n。
m组询问,每次询问一个区间[l,r],是否存在一个数在[l,r]中出现的次数大于(r-l+1)/2。如果存在,输出这个数,否则输出0。
n,m≤500000
思路:这题可以用主席树巧妙地做
询问(x,y)区间时直接输出a[query(x,y)]
首先区间内个数>(r-l+1)/2的数字如果有的话有且只有一个
其次答案数字肯定在数字总和大于一半的一边
这样询问可以做到logn
离散化注意
var t:array[..]of record
l,r,s:longint;
end;
a,b,c,d,root,h:array[..]of longint;
n,m,i,x,y,cnt:longint; procedure swap(var x,y:longint);
var t:longint;
begin
t:=x; x:=y; y:=t;
end; procedure qsort(l,r:longint);
var i,j,mid:longint;
begin
i:=l; j:=r; mid:=a[(l+r)>>];
repeat
while mid>a[i] do inc(i);
while mid<a[j] do dec(j);
if i<=j then
begin
swap(a[i],a[j]);
swap(c[i],c[j]);
inc(i); dec(j);
end;
until i>j;
if l<j then qsort(l,j);
if i<r then qsort(i,r);
end; procedure update(l,r:longint;var p:longint;x:longint);
var mid:longint;
begin
inc(cnt); t[cnt]:=t[p];
p:=cnt; inc(t[p].s);
if l=r then exit;
mid:=(l+r)>>;
if x<=mid then update(l,mid,t[p].l,x)
else update(mid+,r,t[p].r,x);
end; function query(p1,p2,l,r,k:longint):longint;
var mid,t1,t2:longint;
begin
if l=r then exit(l);
t1:=t[t[p2].l].s-t[t[p1].l].s;
t2:=t[t[p2].r].s-t[t[p1].r].s;
mid:=(l+r)>>;
if t1>=k then exit(query(t[p1].l,t[p2].l,l,mid,k))
else if t2>=k then exit(query(t[p1].r,t[p2].r,mid+,r,k))
else exit();
end; begin
assign(input,'bzoj3524.in'); reset(input);
assign(output,'bzoj3524.out'); rewrite(output);
readln(n,m);
for i:= to n do
begin
read(a[i]);
b[i]:=a[i]; c[i]:=i;
end;
qsort(,n);
d[c[]]:=;
for i:= to n do
if a[i]<>a[i-] then d[c[i]]:=d[c[i-]]+
else d[c[i]]:=d[c[i-]]; //离散化
for i:= to n do h[d[i]]:=b[i]; //离散化后还原原数
for i:= to n do
begin
root[i]:=root[i-];
update(,n,root[i],d[i]);
end;
for i:= to m do
begin
readln(x,y);
writeln(h[query(root[x-],root[y],,n,(y-x+) div +)]);
end;
close(input);
close(output);
end.
最新文章
- 通过拦截器Interceptor实现Spring MVC中Controller接口访问信息的记录
- 未能添加对***.dll的引用问题
- nginx.conf各参数的意义
- jbuilder的set!方法重构接口
- Android之layout_alignBottom失效问题
- ie6下 gif动画不动
- POJ1797 Heavy Transportation 【Dijkstra】
- C语言之字符串
- maven详解之结构
- [DFS遍历图]UVA10562 Undraw the Trees
- oracle ORA-02292: 违反完整约束条件
- mysql的定时器
- 在多机器上远程执行JMeter
- swiper,一个页面使用多个轮播
- POI读取Excel(xls、xlsx均可以)——(四)
- jQuery Address全站 AJAX 完整案例详解
- yum update软件包冲突
- RxJS之过滤操作符 ( Angular环境 )
- SP2713 GSS4
- 机器学习入门学习笔记:(一)BP神经网络原理推导及程序实现