凸包----扫除法

Program GrahamScan;

const
	filename='GrahamScan.';

Type Tpoint=record
		x,y		:		Extended;
end;
	
var
	p,b			:		array[1..1000000] of Tpoint;
	n,m			:		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;
	
	Procedure Init;
	var
		i		:		longint;
	begin
		readln(n);
		for i:=1 to n do readln(p[i].x,p[i].y);
	end;
	
	Procedure Print;
	var	
		i		:		longint;
	begin
		for i:=1 to m do writeln(b[i].x,' ',b[i].y);	
	end;
	
	Procedure Qsort(l,r:longint);
	var	
		i,j		:		longint;
		m,t		:		Tpoint;
	begin
		i:=l; j:=r; m:=p[(i+j) shr 1];
		repeat
			while (p[i].y<m.y) or (p[i].y=m.y) and (p[i].x<m.x) do inc(i);
			while (p[j].y>m.y) or (p[j].y=m.y) and (p[j].x>m.x) do dec(j);
			if i<=j then 
				begin
					t:=p[i]; p[i]:=p[j]; p[j]:=t; 
					inc(i); dec(j);
				end;
		until i>j;
		if i<r then Qsort(i,r);
		if l<j then Qsort(l,j);
	end;
	
	Function cross(a,b,c:Tpoint):Extended;
	begin
		exit((b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x));
	end;
	
	Procedure Main;
	var	
		i,k		:		longint;
	begin
		m:=0;
		for i:=1 to n do 
			begin
				while (m>1) and (cross(b[m-1],b[m],p[i])<0) do	dec(m);
				inc(m); b[m]:=p[i];
			end;
		k:=m;
		for i:=n-1 downto 1 do	
			begin
				while (m>k) and (cross(b[m-1],b[m],p[i])<0) do dec(m);
				inc(m); b[m]:=p[i];
			end;
		if n>1 then dec(m);
	end;
	
begin
	openfile;
	Init;
	Qsort(1,n);
	main;
	print;
	closefile;
end.

posted on 2012-02-14 13:39  爱宝宝  阅读(136)  评论(0编辑  收藏  举报

导航