浙大上机题--继续畅通工程
作者:互联网
题目链接
要先计算连通分支的个数,最终只有一个连通分支即可
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 5010;
struct node {
int wei, x, y, sta;
bool operator < (const node& t) const {
return wei < t.wei;
}
}e[N];
int f[110];
int getf(int x) {
if (x != f[x]) f[x] = getf(f[x]);
return f[x];
}
void merge(int x, int y) {
int tx = getf(x);
int ty = getf(y);
if (tx != ty) {
f[ty] = tx;
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
int n;
while (cin >> n && n) {
for (int i = 1; i <= n; i++) f[i] = i;
int num = n * (n - 1) / 2;
int cnt = 0, dis = 0;
for (int i = 0; i < num; i++) {
cin >> e[i].x >> e[i].y >> e[i].wei >> e[i].sta;
if (e[i].sta == 1) merge(e[i].x, e[i].y);
}
for (int i = 1; i <= n; i++) {
if (f[i] == i)
cnt++;
}
if (cnt == 1) {
cout << 0 << endl;
} else {
sort(e, e + num);
for (int i = 0; i < num; i++) {
if (getf(e[i].x) == getf(e[i].y)) continue;
merge(e[i].x, e[i].y);
dis += e[i].wei;
if (--cnt == 1) {
cout << dis << endl;
break;
}
}
}
}
return 0;
}
标签:cnt,const,上机,ty,--,wei,浙大,int,getf 来源: https://blog.csdn.net/weixin_43438720/article/details/123581732