题目链接:https://nanti.jisuanke.com/t/42580
#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int mod = 1e9 + 7;
int fa[50000 + 50];
int n, m, k;
int get(int x) {
if (x == fa[x])
return x;
return fa[x] = get(fa[x]);
}
void merge(int x, int y) {
fa[get(x)] = get(y);
}
struct Edge {
int u, v, w;
bool vis;
Edge() {
u = v = w = 0;
vis = false;
}
Edge(int uu, int vv, int ww) {
u = uu, v = vv, w = ww;
vis = false;
}
};
vector<Edge> white;
bool cmp(const Edge x, const Edge y) {
if (x.w == y.w)
return false;
return x.w > y.w;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
ll ans = 0;
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= n; i++) {
fa[i] = i;
}
white.clear();
for (int i = 1; i <= m; i++) {
int u, v, w, c;
scanf("%d%d%d%d", &u, &v, &w, &c);
if (c == 0) {
ans += w;
if (get(u) != get(v))
merge(u, v);
}
else {
white.push_back(Edge(u, v, w));
}
}
sort(white.begin(), white.end(), cmp);
int blk = 0;//连通块的个数
for (int i = 1; i <= n; i++) {
if (get(i) == i)
blk++;
}
int cnt = 0;//添加的边的个数
for (int i = 0; i < white.size(); i++) {
if (!white[i].vis) {
if (get(white[i].u) != get(white[i].v)) {
white[i].vis = true;
merge(white[i].u, white[i].v);
ans += white[i].w;
blk--, cnt++;
if (blk == 1 || cnt == k)
break;
}
}
}
if (blk > 1) {
printf("-1\n");
continue;
}
if (cnt < k) { //blk == 1
for (int i = 0; i < white.size(); i++) {
if (!white[i].vis) {
white[i].vis = true;
ans += white[i].w;
cnt++;
if (cnt == k)
break;
}
}
}
printf("%lld\n", ans);
}
return 0;
}