还是畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 48922 Accepted Submission(s): 22331
Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最小的公路总长度。
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 5Huge input, scanf is recommended.HintHint
Source
Recommend
用kruskal就搞定了,记得要合并各个节点的根。
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 5005;
const int maxm = 101;
struct node{
int x,y,dis;
}a[maxn];
bool cmp(node p, node q){
return p.dis<q.dis;
}
int n,i,j,k,tot,dist;
int root[maxm];
int Find(int p){
while (p != root[p]) p=root[p];
return p;
}
void Merge(int p, int q){
while (p != root[p]) p=root[p];
int z;
while (q != root[q]) {
z = root[q];
root[q] = p;
q = z;
}
root[q] = p;
}
void kruskal(){
for (i=1; i<=k; i++) {
if (Find(a[i].x) != Find(a[i].y)) {
dist += a[i].dis;
Merge(a[i].x,a[i].y);
}
}
}
int main(){
std::ios::sync_with_stdio(false);
while ( cin >> n && n){
k = n*(n-1)/2;
for (i=1; i<=k; i++) cin >> a[i].x >> a[i].y >> a[i].dis;
for (i=1; i<=n; i++) root[i] = i;
sort(a+1,a+k+1,cmp);
tot = dist = 0;
kruskal();
for (i=1; i<=n; i++) if (root[i]==i) tot++;
if (tot!=1) cout << 0 << endl;
else cout << dist << endl;
}
return 0;
}