Krustral 变形。。。。。。
代码如下:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <cmath> 5 6 struct distance 7 { 8 int u,v; 9 double w; 10 }d[1000000]; 11 12 struct point 13 { 14 int x,y; 15 }p[1000]; 16 17 int f[1000]; 18 int n; 19 int num; 20 21 bool cmp(const distance& a,const distance& b) 22 { 23 if(a.w == b.w) 24 return a.u < b.u; 25 return a.w < b.w; 26 } 27 28 double dis(point a,point b) 29 { 30 return sqrt(1.0*(a.x - b.x) * (a.x - b.x) + 1.0 * (a.y - b.y) * (a.y - b.y)); 31 } 32 33 int find(int x) 34 { 35 if(x == f[x]) 36 return x; 37 f[x] = find(f[x]); 38 return f[x]; 39 } 40 41 void Krustral() 42 { 43 double sum = 0; 44 int k = 0; 45 for(int i = 0;i < num;i ++) 46 { 47 int fa = find(d[i].u); 48 int fb = find(d[i].v); 49 if(fa != fb) 50 { 51 f[fa] = fb; 52 sum += d[i].w; 53 k ++; 54 } 55 if(k == n -1) 56 break; 57 } 58 59 printf("%.2lf\n",sum); 60 } 61 62 int main() 63 { 64 while(scanf("%d",&n) == 1) 65 { 66 num = 0; 67 for(int i = 1;i <= n;i ++) 68 { 69 scanf("%d%d",&p[i].x,&p[i].y); 70 for(int j = 1;j < i;j ++) 71 { 72 d[num].u = i; 73 d[num].v = j; 74 75 d[num ++].w = dis(p[i],p[j]); 76 } 77 } 78 79 std::sort(d,d + num,cmp); 80 for(int i = 0;i <= n;i ++) 81 { 82 f[i] =i; 83 } 84 int on; 85 scanf("%d",&on); 86 for(int i = 0;i < on;i ++) 87 { 88 int a,b; 89 scanf("%d%d",&a,&b); 90 f[find(a)] = find(b); 91 } 92 93 Krustral(); 94 } 95 return 0; 96 }