POJ 1751 Highways

时间:2019-10-10 20:45:28   收藏:0   阅读:106

题目链接:http://poj.org/problem?id=1751

题目大意:

1.给出n个城市的坐标,以及m行,是a,b两个城市已经连通。需要求出联通所有城市的最小距离。

题解思路:

1.Kruscal。

2.注意在初始化时,已经联通的点,要联通它们的父亲节点。

技术图片
 1 #include<stdio.h>
 2 #include<math.h>
 3 #include<algorithm>
 4 const int MAXN = 755;
 5 using namespace std;
 6 
 7 int x[MAXN], y[MAXN], cnt;
 8 int pre[MAXN];
 9 
10 struct Edge
11 {
12     int from, to;
13     double val;
14 }edge[MAXN * (MAXN - 1) / 2];
15 
16 bool cmp(Edge a, Edge b)
17 {
18     return a.val < b.val;
19 }
20 
21 int find(int x)
22 {
23     if(pre[x] == x)
24         return x;
25     else
26     {
27         int root = find(pre[x]);
28         pre[x] = root;
29         return pre[x];
30     }
31 }
32 
33 int main()
34 {
35     int n;
36     scanf("%d", &n);
37     for(int i = 1; i <= n; i ++)
38         pre[i] = i;
39     for(int i = 1; i <= n; i ++)
40         scanf("%d%d", &x[i], &y[i]);
41     for(int i = 1; i < n; i ++)
42     {
43         for(int j = i + 1; j <= n; j ++)
44         {
45             edge[++ cnt].from = i;
46             edge[cnt].to = j;
47             edge[cnt].val = sqrt(1.0 * (x[i] - x[j]) * (x[i] - x[j]) + 1.0 * (y[i] - y[j]) * (y[i] - y[j]));
48         }
49     }
50     int m;
51     scanf("%d", &m);
52     for(int i = 1; i <= m; i ++)
53     {
54         int a, b;
55         scanf("%d%d", &a, &b);
56         int xx = find(a), yy = find(b);
57         if(xx != yy)
58             pre[yy] = xx;
59     }
60     sort(edge + 1, edge + 1 + cnt, cmp);
61     for(int i = 1; i <= cnt; i ++)
62     {
63         int xx = find(edge[i].from), yy = find(edge[i].to);
64         if(xx != yy)
65         {
66             pre[yy] = xx;
67             printf("%d %d\n", edge[i].from, edge[i].to);
68         }
69     }
70     return 0;
71 } 
View Code

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!