首页 > 代码库 > hdu 1875 畅通工程再续

hdu 1875 畅通工程再续

 

kruskal实现~~

  1 #include<iostream>  2 #include<cmath>  3 #include<algorithm>  4 #include<cstdio>  5 using namespace std;  6 #define maxn 300  7 int par[maxn];  8 int pos;  9 int n,cnt; 10 double len; 11 struct node 12 { 13     int x; 14     int y; 15     double w;//!!!可以不开方 16 }; 17 node e[maxn * (maxn - 1) / 2]; 18 int cmp(const node &a , const node &b) 19 { 20     return a.w < b.w; 21 }; 22 struct p 23 { 24     int x; 25     int y; 26 }po[maxn]; 27 void init() 28 { 29     for(int i = 1; i <= n+5; i++) 30         par[i] = i; 31     pos = 0; 32     len = 0.0; 33     cnt = 0; 34 } 35 int Find(int x) 36 { 37     int k,j,r; 38     r = x; 39     while(par[r] != r) 40         r = par[r]; 41     k = x; 42     while(k != r) 43     { 44         j = par[k]; 45         par[k] = r; 46         k = j; 47     } 48     return r; 49 } 50 int Merge(int x,int y) 51 { 52     int a = Find(x); 53     int b = Find(y); 54     if(a != b) 55     { 56         par[a] = par[b]; 57         return 1; 58     } 59     return 0; 60 } 61 void input() 62 { 63     int u,v; 64     for(int i = 1; i <= n; i++) 65         scanf("%d%d",&po[i].x,&po[i].y); 66 } 67  68 void make() 69 { 70     double dist; 71     for(int i = 1; i <= n; i++) 72     { 73         for(int j = i + 1; j <= n; j++) 74         { 75             dist = (po[i].x - po[j].x) * (po[i].x - po[j].x) + (po[i].y - po[j].y) * (po[i].y - po[j].y); 76             if(dist >= 100 && dist <= 1000000) 77             { 78                 e[pos].x = i; 79                 e[pos].y = j; 80                 e[pos].w = sqrt(dist); 81                 pos++; 82             } 83         } 84     } 85     sort(e,e+pos,cmp); 86     for(int i = 0; i < pos; i++) 87     { 88         if(Merge(e[i].x,e[i].y)) 89         { 90             Merge(e[i].x,e[i].y); 91             len += e[i].w; 92             cnt++; 93         } 94     } 95 } 96 int main() 97 { 98     freopen("input.txt","r",stdin); 99     int t;100     scanf("%d",&t);101     while(t--)102     {103         scanf("%d",&n);104         init();105         input();106         make();107         if(cnt < n - 1) printf("oh!\n");108         else printf("%.1lf\n",len * 100);109     }110 111     return 0;112 }