题目
输出格式:
输出全省畅通需要的最低成本。
输入样例:
4
1 2 1 1
1 3 4 0
1 4 1 1
2 3 3 0
2 4 2 1
3 4 5 0
输出样例:
3
代码
#include <cstdio>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;
const int maxn = 1e2+5;
int fa[maxn];
void init() {
for(int i = 1; i < maxn; ++i) {
fa[i] = i;
}
}
int find(int i) {
if(fa[i] != i) {
fa[i] = find(fa[i]);
}
return fa[i];
}
void merge(int a, int b) {
int f1 = find(a);
int f2 = find(b);
fa[f1] = f2;
}
struct edge{
int f, t, w;
edge(int f, int t, int w) : f(f), t(t), w(w) {}
};
bool operator<(const edge& a, const edge& b){
return a.w > b.w;
}
int main(void)
{
priority_queue<edge> que;
init();
int n;
scanf("%d", &n);
int t = n*(n-1)/2;
int a1, a2, w, b;
while(t--) {
scanf("%d%d%d%d", &a1, &a2, &w, &b);
if(b) {
merge(a1, a2);
} else {
que.push(edge(a1, a2, w));
}
}
set<int> st;
for(int i = 1; i <= n; ++i) {
st.insert(find(i));
}
int p = st.size();
int ans = 0;
while(p != 1) {
auto x = que.top(); que.pop();
if(find(x.f) != find(x.t)) {
merge(x.f, x.t);
ans += x.w;
--p;
}
}
printf("%d\n", ans);
return 0;
}