POJ 1233 还是畅通工程

来源:互联网 发布:家里网络玩游戏延迟高 编辑:程序博客网 时间:2024/05/21 22:30

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1233

题目:

还是畅通工程

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 23046    Accepted Submission(s): 10254


Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
 

Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
 

Output
对每个测试用例,在1行里输出最小的公路总长度。
 

Sample Input
31 2 11 3 22 3 441 2 11 3 41 4 12 3 32 4 23 4 50
 

Sample Output
35

解题思路:

最小生成树的最基本的题目。对于此类问题,我们可以有两种做法,一种是Prim算法(点的贪心),一种是Kruskal算法(边的贪心)。

解法1代码:

#include <iostream>#include <cstring>#include <cstdio>using namespace std;#define INF 0x7fffffffconst int MAXN = 110;int n, map[MAXN][MAXN], lowcost[MAXN];int Prim(int v){int ans = 0;for(int i = 1; i <= n; i++){lowcost[i] = map[v][i];}lowcost[v] = 0;for(int i = 1; i < n; i++){int min = INF, minpos = 0;for(int j = 1; j <= n; j++){if(lowcost[j] && lowcost[j] < min){min    = lowcost[j];minpos = j;}}ans += min;lowcost[minpos] = 0;for(int j = 1; j <= n; j++){if(lowcost[j] && map[minpos][j] < lowcost[j]){lowcost[j] = map[minpos][j];}}}return ans;}int main(){while(~scanf("%d", &n) && n){memset(map, 0, sizeof(map));memset(lowcost, 0, sizeof(lowcost));int m = n * (n - 1) / 2;while(m--){int a, b, c;scanf("%d%d%d", &a, &b, &c);map[a][b] = map[b][a] = c;}printf("%d\n", Prim(1));}return 0;}

解法2代码:

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>using namespace std;const int MAXN = 100;struct Eage{int start, end, length;};Eage eage[MAXN*MAXN/2];int n, m, set[MAXN];bool cmp(const Eage &a, const Eage &b){return a.length < b.length;}int set_find(int p){if(set[p] < 0) return p;return set[p] = set_find(set[p]);}void join(int p, int q){p = set_find(p);q = set_find(q);if(p != q) set[p] = q;}int Kruskal(){int ans = 0;for(int i = 0; i < m; i++){if(set_find(eage[i].start) != set_find(eage[i].end)){join(eage[i].start, eage[i].end);ans += eage[i].length;}}return ans;}int main(){while(~scanf("%d", &n) && n){memset(set, -1, sizeof(set));memset(eage, 0, sizeof(eage));m = n * (n - 1) / 2;for(int i = 0; i < m; i++){scanf("%d%d%d", &eage[i].start, &eage[i].end, &eage[i].length);}sort(eage, eage + m, cmp);printf("%d\n", Kruskal());}return 0;}


0 0
原创粉丝点击