hdu1875 畅通工程再续 暴力+基础最小生成树

  1 #include<cstdio>
  2 #include<cmath>
  3 #include<algorithm>
  4 using namespace std;
  5 
  6 const int maxn = 100005;
  7 const int L = 100;
  8 const int R = 100000;
  9 int t, n, m, ans;
 10 double total;
 11 struct node
 12 {
 13     int x, y;
 14     int cost;
 15 }pot[maxn];
 16 int fa[maxn];
 17 int px[maxn], py[maxn];
 18 
 19 int cal()
 20 {
 21     int i, j, tx, ty, len, pos;
 22     pos = 0;
 23     for (i = 0; i<n; i++)
 24     {
 25         for (j = i + 1; j<n; j++)
 26         {
 27             tx = px[i] - px[j];
 28             ty = py[i] - py[j];
 29             len = tx*tx + ty*ty;
 30             if (len >= L&&len <= R)
 31             {
 32                 pot[pos].x = i;
 33                 pot[pos].y = j;
 34                 pot[pos].cost = len;
 35                 pos++;
 36             }
 37         }
 38     }
 39     return pos;
 40 }
 41 
 42 void init()
 43 {
 44     total = 0.0;
 45     ans = n - 1;
 46     for (int i = 0; i <= n; i++)
 47     {
 48         fa[i] = i;
 49     }
 50 }
 51 
 52 bool cmp(node a, node b)
 53 {
 54     return a.cost<b.cost;
 55 }
 56 
 57 int find(int x)
 58 {
 59     if (x != fa[x])
 60         return fa[x] = find(fa[x]);
 61     return fa[x];
 62 }
 63 
 64 int join(int x, int y)
 65 {
 66     int flag = 0;
 67     if (x != y)
 68     {
 69         ans--;
 70         fa[x] = y;
 71         flag = 1;
 72     }
 73     return flag;
 74 }
 75 
 76 int main()
 77 {
 78     scanf("%d", &t);
 79     while (t--)
 80     {
 81         scanf("%d", &n);
 82         init();
 83         for (int i = 0; i<n; i++)
 84         {
 85             scanf("%d %d", &px[i], &py[i]);
 86         }
 87         int len = cal();
 88         if (len<n - 1)
 89         {
 90             printf("oh!\n");
 91             continue;
 92         }
 93         sort(pot, pot + len, cmp);
 94         for (int i = 0; i<len; i++)
 95         {
 96             int fx, fy;
 97             fx = find(pot[i].x);
 98             fy = find(pot[i].y);
 99             if (join(fx, fy) == 1)
100             {
101                 total += sqrt(pot[i].cost*1.0);
102             }
103         }
104         if (ans != 0)
105         {
106             printf("oh!\n");
107             continue;
108         }
109         printf("%.1lf\n", total * 100);
110     }
111     return 0;
112 }

 

posted @ 2017-07-25 09:26  ouyang_wsgwz  阅读(110)  评论(0编辑  收藏  举报