九度:1017<并查集><Kruskal><MST>
来源:互联网 发布:报表软件架构 编辑:程序博客网 时间:2024/05/23 02:04
浙大2006年研究生机试
畅通工程:最小生成树
#include <stdio.h>#include <iostream>#include <algorithm>#include <string.h>using namespace std;struct Road{int s;int e;int len;bool operator < (const Road & A) const{return len < A.len;}};int fa[110];int Getfa(int x){if ( x == fa[x])return x;fa[x] = Getfa(fa[x]);return fa[x];}int main(){#ifdef ONLINE_JUDGE#else freopen("E:\\in.txt", "r", stdin);#endifint n;while(scanf("%d", &n) && n){int i, nr = n*(n-1)/2;for(i=1; i<=n; i++){fa[i] = i;}Road rb[10000];for(i=0; i<nr; i++){scanf("%d %d %d", &rb[i].s, &rb[i].e, &rb[i].len);}sort(rb, rb+nr);int ans=0;for(i=0; i<nr; i++){if(Getfa(rb[i].s) != Getfa(rb[i].e)){//村未连通fa[Getfa(rb[i].s)] = Getfa(rb[i].e);//则连通ans += rb[i].len;}}cout << ans << endl;}//whilereturn 0;}
第二次做
#include <stdio.h>#include <algorithm>#define SIZE 101#define MAXSIZE 100*99/2+10using namespace std;int fa[SIZE];struct Edge{ int a, b; int cost; bool operator < (const Edge& A) const{ return cost < A.cost; }};int Getfa(int x){ if(x == fa[x]) return x; else fa[x] = Getfa(fa[x]); return fa[x];}int main(){#ifdef ONLINE_JUDGE#elsefreopen("E:\\in.txt", "r", stdin);//freopen("E:\\out.txt", "w", stdout);#endif int n; while(scanf("%d", &n) && n) { int num = n*(n-1)/2; Edge edge[MAXSIZE]; for(int i=1; i<=n; i++) { fa[i]=i; } for(int i=0; i<num; i++) { scanf("%d%d%d", &edge[i].a,&edge[i].b, &edge[i].cost); } sort(edge, edge+num); int x, y, ans=0; for(int i=0;i<num;i++) { x=Getfa(edge[i].a); y=Getfa(edge[i].b); if(x != y){ fa[x] = y; ans += edge[i].cost; } } printf("%d\n", ans); } return 0;}
0 0
- 九度:1017<并查集><Kruskal><MST>
- MST&&并查集
- POJ 1861 Network [最小生成树算法MST-kruskal 数据结构-并查集 union-find sets]
- [图论]连接岛屿问题(MST.Kruskal算法 并查集)
- 图 之 MST(最小生成树 — kruskal算法 )并查集实现
- kruskal+ 并查集
- Kruskal+并查集
- Kruskal + 并查集
- 并查集&MST题集
- 并查集&MST题集
- 并查集&MST题集
- 并查集&MST题集
- 并查集&MST爬坑中。。。。
- 并查集&MST题集
- 并查集&MST题集
- Kruskal算法 (并查集)
- poj3522 并查集+kruskal
- hdu1233 并查集+Kruskal
- Java网页抓取
- 九度:1014<排序>
- div的横向与纵向排列
- 给你个机会让你坐庄你会怎么玩?——浅谈坐庄和涨停
- LEx YACC 3
- 九度:1017<并查集><Kruskal><MST>
- 05——android项目的启动过程及安装过程笔记
- cocos2d-x 2.2.2 创建项目
- POJ2081:Recaman's Sequence
- Ubuntu安装及ubuntu系统使用菜岛教程
- 九度:1024<并查集>
- 图像处理实用资源
- 杭电OJ 1029:Ignatius and the Princess IV
- PHP读取CURL模拟登录时生成Cookie文件