SSL 1720 Surround the Trees

Description

  There are a lot of trees in an area. A peasant wants to buy a rope to surround all these trees. So at first he must know the minimal required length of the rope. However, he does not know how to calculate it. Can you help him?
  The diameter and length of the trees are omitted, which means a tree can be seen as a point. The thickness of the rope is also omitted which means a rope can be seen as a line.
这里写图片描述
  There are no more than 100 trees.

Input

  The input contains one or more data sets. At first line of each input data set is number of trees in this data set, it is followed by series of coordinates of the trees. Each coordinate is a positive integer pair, and each integer is less than 32767. Each pair is separated by blank.

  Zero at line for number of trees terminates the input for your program.

Output

 The minimal length of the rope. The precision should be 10^-2.

题解

 找到最右下角的点,然后暴力枚举其他(n-1)个点。

代码

type
  arr=record
        x,y:longint;
      end;
var
  n,top:longint;
  ans:real;
  e:array [0..501] of arr;
  s:array [0..501] of longint;
function cj(p1,p2,p0:arr):longint;
begin
  cj:=(p1.x-p0.x)*(p2.y-p0.y)-(p2.x-p0.x)*(p1.y-p0.y);
end;

function comp(p1,p2:arr):boolean;
var
  t:longint;
begin
  t:=cj(p1,p2,e[0]);
  if (t>0) or (t=0) and (sqr(p1.x-e[0].x)+sqr(p1.y-e[0].y)<sqr(p2.x-e[0].x)+sqr(p2.y-e[0].y)) then
    exit(true);
  exit(false);
end;

procedure qsort(l,r:longint);
var
  i,j:longint;
  mid,t:arr;
begin
  if l>=r then exit;
  mid:=e[l+random(r-l+1)];
  i:=l; j:=r;
  repeat
    while comp(e[i],mid) do inc(i);
    while comp(mid,e[j]) do dec(j);
    if i<j then
      begin
        t:=e[i]; e[i]:=e[j]; e[j]:=t;
      end;
  until i>=j;
  qsort(l,j);
  qsort(j+1,r);
end;

procedure init;
var
  i:longint;
  t:arr;
begin
  randomize;
  for i:=0 to n-1 do
    begin
      readln(e[i].x,e[i].y);
      if (e[i].y<e[0].y) or (e[i].y=e[0].y) and (e[i].x<e[0].x) then
        begin
          t:=e[i]; e[i]:=e[0]; e[0]:=t;
        end;
    end;
  qsort(1,n-1);
end;

procedure main;
var
  i:longint;
begin
  for i:=1 to 3 do
    s[i]:=i-1;
  top:=3;
  for i:=3 to n-1 do
    begin
      while cj(e[i],e[s[top]],e[s[top-1]])>=0 do dec(top);
      inc(top);
      s[top]:=i;
     end;
  ans:=0;
  if n>1 then
    begin
      s[top+1]:=s[1];
      for i:=1 to top do
        ans:=ans+sqrt(sqr(e[s[i]].x-e[s[i+1]].x)+sqr(e[s[i]].y-e[s[i+1]].y));
    end;
  if n=2 then ans:=sqrt(sqr(e[1].x-e[0].x)+sqr(e[1].y-e[0].y))*2;
  writeln(ans:0:2);
end;

begin
  readln(n);
  while n<>0 do
    begin
      fillchar(e,sizeof(e),0);
      fillchar(s,sizeof(s),0);
      init;
      main;
      readln(n);
    end;
end.

posted @ 2016-09-16 19:45  猪都哭了  阅读(109)  评论(0编辑  收藏  举报