hdu 1863 畅通工程(最小生成树,kruskal)
2016-06-13 20:16
330 查看
#include <cstdio> #include <algorithm> using namespace std; struct node { int u,v,w; }; node e[5005]; int f[101]; int n,m; bool cmp(node& a , node& b) { return a.w < b.w; } int getf(int x) { if(x == f[x]) return x; else { f[x] = getf(f[x]); return f[x]; } } int merges(int x, int y) { int t1,t2; t1 = getf(x); t2 = getf(y); if(t1 != t2) { f[t2] = t1; return 1; } return 0; } int main() { while(scanf("%d %d",&m,&n) && m) { for(int i = 1; i <= m; ++i) scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].w); sort(e+1,e+m+1,cmp); for(int i = 1; i <= n; ++i) f[i] = i; int sum = 0, counts = 0,flag = 0; for(int i = 1; i <= m; ++i) { if(merges(e[i].u,e[i].v)) { ++counts; sum += e[i].w; } if(counts == n-1) { flag = 1; break; } } if(flag) printf("%d\n",sum); else printf("?\n"); } return 0; }
上边的代码15ms,
下边的0ms
#include <iostream> #include <algorithm> using namespace std; int n,m; int f[101],u[5005],v[5005],w[5005],r[5005]; bool cmp(const int& i, const int& j) { return w[i] < w[j]; } int getf(int x) { return f[x] == x ? x:(f[x] = getf(f[x])); } int main() { int sum,counts; while((cin >> m >> n) && m) { sum = 0; counts = 0; for(int i = 0; i < m; ++i) cin >> u[i] >> v[i] >> w[i]; for(int i = 0; i < m; ++i) r[i] = i; for(int i = 0; i <= n; ++i) f[i] = i; sort(r,r+m,cmp); for(int i = 0; i < m; ++i) { int e = r[i]; int x = getf(u[e]); int y = getf(v[e]); if(x != y) { ++counts; sum += w[e]; f[y] = x; } } if(counts == n-1) cout << sum << endl; else cout << "?" << endl; } return 0; }
相关文章推荐
- June 11th 模拟赛C T1 Sandcas Solution
- apache https配置
- html之间传递参数
- postmessage/cors跨域postMessage、xhr2和xmldomain
- 古代猪文 [Bzoj 1951,Sdoi 2010]
- Filter编程:(2)Filter进阶
- hdu1052(田忌赛马题解)
- bzoj 4028 [HEOI2015]公约数数列
- 欢迎使用CSDN-markdown编辑器
- Android Activity全局数据共享
- RFID射频卡超市购物结算系统
- Jquery获取和修改img的src值的方法
- LeenCode——归并问题的处理( Merge Two Sorted Lists&&Given two sorted integer arrays nums1 and nums2, merge n)
- 用递归方法求阶乘2
- Android ANR 分析解决方法
- 生产者-消费者
- Linux 下 ascii 的查看方式
- opencv2.4.10【附加的依赖项】
- windows下编译及使用libevent
- 自己动手写RTP服务器——关于RTP协议