奇怪的二分。
考虑给白边的边权加上一个数,这个数越大,MST时选的白边就越少。
注意排序时候,如果边权相等,要先选白边。
/* Forgive me Not */
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 50005, maxm = 100005, inf = 0x3f3f3f3f;
int n, m, k, fa[maxn];
struct edge {
int u, v, w, c;
bool operator < (const edge &x) const {
return w != x.w ? w < x.w : c < x.c;
}
} g[maxm], e[maxm];
inline int iread() {
int f = 1, x = 0; char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return f * x;
}
inline int find(int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
inline int check(int mid) {
int cnt = 0, res = 0;
for(int i = 1; i <= n; i++) fa[i] = i;
for(int i = 1; i <= m; i++) {
e[i] = g[i];
if(!e[i].c) e[i].w += mid;
}
sort(e + 1, e + 1 + m);
for(int i = 1; i <= m; i++) {
int u = find(e[i].u), v = find(e[i].v);
if(u != v) {
res += e[i].w;
if(!e[i].c) cnt++;
fa[u] = v;
}
}
return cnt >= k ? res : -1;
}
int main() {
n = iread(); m = iread(); k = iread();
for(int i = 1; i <= m; i++) {
int u = iread(), v = iread(), w = iread(), c = iread(); u++; v++;
g[i] = (edge){u, v, w, c};
}
int l = -101, r = 101, ans = inf;
while(l <= r) {
int mid = l + r >> 1;
int res = check(mid);
if(res != -1) ans = res - k * mid, l = mid + 1;
else r = mid - 1;
}
printf("%d\n", ans);
return 0;
}