算法模板:主席树模板

pascal主席树模板 

//主席树模板
var
	i,n,m,total,ans,x,y,z:longint;
	root:array[0..100000]of longint;
	t:array[0..4000000,1..3]of longint;
procedure inw(x,y:longint;l,r:int64;z:longint);
var
	mid:int64;
begin
	if l<>r then
	begin
		mid:=(l+r)div 2;
		if z<=mid then
		begin
			if t[x,2]>0 then t[y,2]:=t[x,2];
			inc(total);
			t[y,1]:=total;
			if t[x,1]>0 then t[t[y,1]]:=t[t[x,1]];
			inw(t[x,1],t[y,1],l,mid,z);
		end
		else
		begin
			if t[x,1]>0 then t[y,1]:=t[x,1];
			inc(total);
			t[y,2]:=total;
			if t[x,2]>0 then t[t[y,2]]:=t[t[x,2]];
			inw(t[x,2],t[y,2],mid+1,r,z);
		end;
		t[y,3]:=0;
		if t[y,1]>0 then t[y,3]:=t[t[y,1],3];
		if t[y,2]>0 then t[y,3]:=t[y,3]+t[t[y,2],3];
	end
	else inc(t[y,3]);
end;
procedure find(x,y:longint;l,r:int64;tc:longint);
var
	mid:int64;
begin
	if l<>r then
	begin
		mid:=(l+r)div 2;
        	if t[y,1]<>0 then
		begin
			if tc+t[t[y,1],3]-t[t[x,1],3]>=z then find(t[x,1],t[y,1],l,mid,tc)
			else find(t[x,2],t[y,2],mid+1,r,tc+t[t[y,1],3]-t[t[x,1],3]);
		end
		else find(t[x,2],t[y,2],mid+1,r,tc);
	end
	else ans:=l;
end;
begin
	assign(input,'sf_chairmantree.in');reset(input);
	assign(output,'sf_chairmantree.out');rewrite(output);
	readln(n,m);
	for i:=1 to n do
	begin
		read(x);
		inc(total);
		root[i]:=total;
                t[root[i]]:=t[root[i-1]];
		inw(root[i-1],root[i],1,maxlongint,x);
	end;
	for i:=1 to m do
	begin
		readln(x,y,z);
		ans:=0;
		find(root[x-1],root[y],1,maxlongint,0);
		writeln(ans);
	end;
	close(input);
	close(output);
end.

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值