Kruskal HDOJ 1233 还是畅通工程
2015-05-18 20:23
393 查看
题目传送门
/* 最小生成树之kruskal算法--并查集(数据结构)实现 建立一个结构体,记录两点和它们的距离,依照距离升序排序 不连通就累加距离,即为最小生成树的长度 */ #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> using namespace std; const int MAXN = 5e3 + 10; const int INF = 0x3f3f3f3f; int rt[MAXN]; struct Node { int u, v, w; }node[MAXN]; bool cmp(Node x, Node y) {return x.w < y.w;} int Find(int x) {return (rt[x] == -1) ? x : rt[x] = Find (rt[x]);} void Union(int x, int y) { x = Find (x); y = Find (y); if (x > y) rt[y] = x; else if (x < y) rt[x] = y; } bool same(int x, int y) {return (Find (x) == Find (y));} int main(void) //HDOJ 1233 还是畅通工程 { //freopen ("inB.txt", "r", stdin); int n, m; while (~scanf ("%d", &n) && n) { m = n * (n - 1) / 2; memset (rt, -1, sizeof (rt)); for (int i=1; i<=m; ++i) { scanf ("%d%d%d", &node[i].u, &node[i].v, &node[i].w); } sort (node+1, node+1+m, cmp); int sum = 0; for (int i=1; i<=m; ++i) { int x = node[i].u; int y = node[i].v; int w = node[i].w; if (!same (x, y)) {Union (x, y); sum += w;} } printf ("%d\n", sum); } }
相关文章推荐
- HDOJ 1233 还是畅通工程(最小生成树--kruskal)
- HDOJ 题目1233还是畅通工程(最小生成树,kruskal模板)
- hdoj-1233 还是畅通工程【最小生成树--kruskal】
- HDU 1233 还是畅通工程(最小生成树 Prim+Kruskal)
- HDOJ -- 1233 还是畅通工程
- HDOJ 1233.还是畅通工程
- hdoj1233 还是畅通工程
- HDOJ 1233 还是畅通工程 最小生成树 kruskal && prim
- HDU 1233 还是畅通工程(最小生成树kruskal)
- hdu 1233 还是畅通工程(最小生成树的Prim和Kruskal两种算法的c++实现)(prim算法详解)
- HDU 1233 还是畅通工程(最小生成树Kruskal)
- hdu 1233 还是畅通工程(最小生成树,prim,kruskal)
- hdoj1233 还是畅通工程
- HDOJ 题目1233 还是畅通工程(最小生成树,模板)
- HDOJ 1233 还是畅通工程
- (ZJU-2006复试)-HDOJ-1233-还是畅通工程
- hdoj 1233 还是畅通工程
- hdu 1233 还是畅通工程(最小生成树的Prim和Kruskal两种算法的c++实现)(prim算法详解)
- hdoj1233 还是畅通工程(Prime || Kruskal)
- hdoj 1233 还是畅通工程