# 还是畅通工程

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

Problem Description

Input

Output

Sample Input
3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0

Sample Output
3 5
Hint
Hint
Huge input, scanf is recommended.

Source

1.克鲁斯卡尔 elog2e

/*
* xrq.cpp
*
*  Created on: 2015年11月19日
*      Author: xiongmao
*/
#include<stdio.h>
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<cmath>
#include<stack>
#include<queue>
#include<set>
#define PI acos(-1.0)
#define E  exp(1.0)
#define len(a) (int)strlen(a)
#define mem0(a) (memset(a,0,sizeof(a)))
#define mem1(a) (memset(a,-1,sizeof(a)))
using namespace std;
__int64 gcd(__int64 a, __int64 b) {
return b ? gcd(b, a % b) : a;
}
__int64 lcm(__int64 a, __int64 b) {
return a / gcd(a, b) * b;
}
int inf = 999999;
int fa[5010];
int n, m;
struct node {
int u, v, w;
} q[5010];
void make_set() {
for (int i = 1; i <= n; i++) {
fa[i] = i;
}
}
int Find(int x) {
if (x != fa[x])
fa[x] = Find(fa[x]);
return fa[x];

}
bool cmp(node x, node y) {
return x.w < y.w;
}
int kru() {
int ans = 0, cnt = 0;
make_set();
sort(q + 1, q + m + 1, cmp); //排序要从起始地址，到终止地址此题中i是从1开始的，
for (int i = 1; i <= m; i++) {
int fx = Find(q[i].u);
int fy = Find(q[i].v);
if (fx != fy) {
fa[fx] = fy;
ans += q[i].w;
cnt++;
}
}
return ans;
}
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
while (scanf("%d", &n) != EOF && n) {
m = n * (n - 1) / 2;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &q[i].u, &q[i].v, &q[i].w);
}
printf("%d\n", kru());
}
return 0;
}

2.普里姆 v^2

#include <iostream>
using namespace std;
#define MAX 999999
int map[100][100], dis[100]; //以节点i为终点的最小边权值；
int vis[100];
int n;
void prim() {
int i, j, k, min, sum = 0;
for (i = 1; i <= n; i++)
dis[i] = map[i][1]; //因为节点1已经默认进入最小树，所以初始化应该是节点1到节点i的值；
vis[1] = 1;
for (i = 2; i <= n; i++) {
min = MAX;
k = i;
for (j = 2; j <= n; j++) //找出最小边权值；
if (!vis[j] && dis[j] < min) {
min = dis[j];
k = j;
}
sum += min; //累加权值；
vis[k] = 1; //标记节点k加入生成树；
for (j = 2; j <= n; j++) //更新权值；
if (map[j][k] < dis[j])
dis[j] = map[j][k];
}
printf("%d\n", sum);
}
int main() {
int i, x, y, d;
while (scanf("%d", &n) != EOF && n) {
for (i = 1; i <= n; i++) {
map[i][i] = 0;
vis[i] = 0;
}
for (i = 0; i < n * (n - 1) / 2; i++) {
scanf("%d %d %d", &x, &y, &d);
map[x][y] = map[y][x] = d;
}
prim();
}
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：hdu 1233 最小生成树 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)