POJ 1788 Building a New Depot

来源:互联网 发布:网络发包工具 编辑:程序博客网 时间:2024/05/22 23:27

Description 
给出几个坐标点,让你求出将所有的点围起来的篱笆的长度,其中每个点都在篱笆的拐角处,求处最小的篱笆的长度 
Input 
多组输入,每组用例第一行为坐标点个数n,之后n行为每个坐标点的坐标,每组输入后跟一空行,以0结束输入 
Output 
对于每组用例,输出最小的篱笆长度 
Sample Input 

1 1 
1 3 
3 3 
2 1 
3 2 
2 2


Sample Output 
The length of the fence will be 8 units. 
Solution 
由于每个点都是在坐标点出并且在篱笆的拐弯处,所以任意横坐标或者纵坐标上的点都是偶数个的,要求篱笆的长度最小,所以就要求出最近的横坐标或者纵坐标相等的两个点的距离,用sort函数二次排序,用纵坐标横坐标分别进行求和就可以了 

AC代码

#include<cstdio>#include<iostream>#include<algorithm>using namespace std;#define INF (1<<29)#define maxn 100005struct node{    int x,y;}num[maxn];int n;int cmp1(node a,node b){    if(a.x==b.x)        return a.y<b.y;    return a.x<b.x;}int cmp2(node a,node b){    if(a.y==b.y)        return a.x<b.x;    return a.y<b.y;}int main(){    while(scanf("%d",&n),n)    {        for(int i=0;i<n;i++)            scanf("%d%d",&num[i].x,&num[i].y);        int ans=0;//初始化         sort(num,num+n,cmp2);//按纵坐标升序排         for(int i=0;i<n;i+=2)               ans+=num[i+1].x-num[i].x;//累加纵坐标相同两点间距         sort(num,num+n,cmp1);//按横坐标升序排         for(int i=0;i<n;i+=2)            ans+=num[i+1].y-num[i].y;;//累加横坐标相同两点间距         printf("The length of the fence will be %d units.\n",ans);      }    return 0;}