NYOJ7(数论)

解题思路:题意很明确,关键就是求邮局的位置,由于所有住户坐标到该点的距离和最短,其实就是纵横坐标中位数。即先排序,然后计算中位数的序号。接着就容易求出各个住户到邮局的距离之和即可。
View Code
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 struct point{
 7     int x,y;
 8 }p[10005];
 9 
10 int cmp1(point a,point b)
11 {
12     return a.x<b.x;
13 }
14 int cmp2(point a,point b)
15 {
16     return a.y<b.y;
17 }
18 
19 int main()
20 {
21     int n,i,m,a,b,x0,y0;
22     scanf("%d",&m);
23     while(m--)
24     {
25         
26         scanf("%d",&n);
27         for(i=0;i<n;i++)
28             scanf("%d%d",&p[i].x,&p[i].y);
29         sort(p,p+n,cmp1);
30         x0=p[n/2].x;
31         sort(p,p+n,cmp2);
32         y0=p[n/2].y;
33         int sum=0;
34         for(i=0;i<n;i++)
35         {
36             a=x0-p[i].x;
37             b=y0-p[i].y;
38             if(a<0) a=-a;
39             if(b<0) b=-b;
40             sum+=(a+b);
41         }
42         printf("%d\n",sum);
43     }
44     return 0;
45 }
posted @ 2012-04-21 11:18  笑巧  阅读(222)  评论(0编辑  收藏  举报