RMQ

开始学线段树啦,先贴个最简单的RMQ吧~神牛勿喷

code:

Program RMQ;

const 	N=10;
		M=5;
		filename='RMQ';
		
Type 
	TNode=record
		l,r,m:longint;
	end;

var
	a:Array[1..N] of longint;
	node:array[1..4*N] of TNode;
	i,c,x,y,l,r:longint;
	
	Procedure openfile;
	begin
		assign(input,filename+'.in');
		assign(output,filename+'.out');
		reset(input); rewrite(output);
	end;
	
	Procedure closefile;
	begin
		close(input); close(output);
	end;
	
	Function Getmin(x,y:longint):longint;
	begin
		if x<y then exit(x) else exit(y);
	end;
	
	Procedure build(x,ll,rr:longint);
	var	
		mid:longint;
	begin
		with node[x] do
			begin
				l:=ll;
				r:=rr;
				if ll=rr then begin m:=a[ll]; exit; end;
				mid:=(ll+rr) shr 1;
				build(2*x,ll,mid);
				build(2*x+1,mid+1,rr);
				m:=Getmin(node[2*x].m,node[2*x+1].m);
			end;
	end;
	
	Function Find(x,ll,rr:longint):longint;
	var	
		mid:longint;
	begin
		with node[x] do
			begin
				if (ll=l) and (rr=r) then exit (m);
				mid:=(l+r) shr 1;
				if rr<=mid then	exit(find(2*x,ll,rr));
				if ll>mid then	exit(find(2*x+1,ll,rr));
				exit(getmin(find(2*x,ll,mid),find(2*x+1,mid+1,rr)));
			end;
	end;

	Procedure Modify(x,t:longint);
	var	
		mid:longint;
	begin
		with node[x] do	
			begin
				if l=r then 
					begin
						m:=a[t];
						exit;
					end;
				mid:=(l+r) shr 1;
				if t<=mid then modify(2*x,t) else modify(2*x+1,t);
				m:=getmin(node[2*x].m,node[2*x+1].m);
			end;
	end;
	
Procedure main;
begin
	for i:=1 to n do read(a[i]);
	build(1,1,n);
	for i:=1 to m do 
		begin
			read(c);
			if c=1 then 
				begin
					readln(l,r);
					writeln(find(1,l,r));
				end;
			if c=2  then
				begin
					readln(x,y);
					a[x]:=y;
					modify(1,x);
				end;
		end;
end;

begin
	openfile;
	main;
	closefile;
end.

posted on 2012-02-06 16:09  爱宝宝  阅读(152)  评论(0编辑  收藏  举报

导航