posts - 24,  comments - 0,  trackbacks - 0
今天做了几道最小生成树的初级题,不过只学习了Kruskal,感觉挺好用的
hdu上的练手题
1301
1233
1863
1162
1879
1875
1102
摸板:http://acm.hdu.edu.cn/showproblem.php?pid=1233
 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 using namespace std;
 5 #define N 10000
 6 int u[N], v[N], w[N], r[N], p[N];
 7 int cmp(int i, int j) {return w[i] < w[j];}
 8 int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }
 9 int n,m;
10 int kruskal()
11 {
12     int ans=0;
13     for(int i = 0; i <=n; ++i) p[i] = i;
14     for(int i = 0; i < m; ++i) r[i] = i;
15     sort(r,r+m,cmp);
16     for(int i = 0, cnt  = 0; i < m && cnt < n - 1++i)
17     {
18         int e = r[i]; int x  = find(u[e]); int y = find(v[e]);
19         if(x != y){ ans += w[e]; cnt++; p[x] = y; }
20     }
21     return ans;
22 }
23 int main()
24 {
25     while(scanf("%d"&n),n)
26     {
27         m=0;
28         char c[2];
29         for(int i = 0; i < n - 1++i)
30         {
31             int cnt;
32             scanf("%s%d", c, &cnt);
33             for(int j = 0; j < cnt; ++j)
34             {
35                 int we;char cc[2];
36                 scanf("%s%d", cc, &we);
37                 u[m] = c[0- 'A';
38                 v[m] = cc[0- 'A';
39                 w[m] = we;
40                 m++;
41             }
42         }
43         int ans = kruskal();
44         printf("%d\n", ans);
45     }
46     return 0;
47 }
48 
posted on 2011-09-12 21:40 ACSeed 阅读(200) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2011年9月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

常用链接

留言簿(1)

随笔档案

偶像的Blog

搜索

  •  

最新评论

阅读排行榜

评论排行榜