#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#define MAX_V 100005
#define INF 0x3f3f3f3f
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 105;
int V;
int f[maxn];
int x[maxn], y[maxn];
struct edge {
int u, v;
int cost;
friend bool operator < (edge e1, edge e2) {
return e1.cost > e2.cost;
}
};
priority_queue<edge> pq;
void init(int x)
{
for(int i = 0; i <= x; i++) {
f[i] = i;
}
}
int getf(int x)
{
if(x != f[x])
f[x] = getf(f[x]);
return f[x];
}
void unions(int x, int y)
{
x = getf(x);
y = getf(y);
if(x != y)
f[y] = x;
}
bool same(int x, int y) {
return getf(x) == getf(y);
}
int kruskal() {
int res = 0;
while(!pq.empty()) {
edge e = pq.top();
pq.pop();
if(!same(e.u, e.v)) {
unions(e.u, e.v);
res += e.cost;
}
}
return res;
}
int main()
{
int n, m;
while( cin >> n && n) {
int a, b, c, k;
edge e;
init(maxn);
for(int i = 0; i < n * (n - 1) / 2; i++) {
scanf("%d %d %d %d", &a, &b, &c, &k);
if(k) {
unions(a, b);
}
else {
e.u = a, e.v = b, e.cost = c;
pq.push(e);
}
}
int ans = kruskal();
cout << ans << endl;
while(!pq.empty()) {
pq.pop();
}
}
return 0;
}
kruskal优先队列形式
最新推荐文章于 2024-11-29 17:46:49 发布