传送门
题意
给你一些白边和一些黑边,让你随便选,但是白边不超过k条
分析
阅读理解,读懂就行了
黑边肯定是必选的,然后我们去把所有的白边按照边权进行排序即可
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 500010;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {
char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}
while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
struct Node{
int x,y,z;
};
int p[N];
int n,m,k;
bool st[N];
vector<Node> e;
bool cmp(Node A,Node B){
return A.z > B.z;
}
int find(int x){
if(x != p[x]) p[x] = find(p[x]);
return p[x];
}
int main() {
int T;
read(T);
while(T--){
e.clear();
read(n),read(m),read(k);
for(int i = 0;i <= max(n,m);i++) p[i] = i,st[i] = 0;
ll res = 0;
int num = 0;
for(int i = 1;i <= m;i++) {
int x,y,z,st;
read(x),read(y),read(z),read(st);
if(!st){
x = find(x),y = find(y);
if(x != y) num++;
res = res + 1ll * z;
p[x] = y;
}
else e.pb({x,y,z});
}
sort(all(e),cmp);
for(int i = 0;i < e.size() && k;i++){
int x = find(e[i].x),y = find(e[i].y);
if(x != y){
res = res + 1ll * e[i].z;
num++;
k--;
p[x] = y;
st[i] = 1;
}
}
for(int i = 0;i < e.size() && k;i++){
if(!st[i]) res = res + 1ll * e[i].z,k--;
}
if(num != n - 1) puts("-1");
else printf("%lld\n",res);
}
return 0;
}