1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<stack> #include<queue> #include<set> #include<map>
using namespace std; typedef long long ll; const int maxn = 5e4+5; const int inf = 0x3f3f3f3f; const ll INF = 1e18; const ll mod = 1e9+7;
#define for1(i,n) for(int i=1;i<=n;i++) #define forn(i,n) for(int i=0;i<n;i++) #define m_p(x,y) make_pair(x,y)
inline int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } typedef pair<int,int> pii; struct node{ int uu, vv, ww; }; vector<node> e; int fa[maxn]; bool vis[(int)5e5+5]; inline int find(int x){ return (x==fa[x]? x : fa[x]=find(fa[x])); } bool cmp(node a, node b){ return a.ww > b.ww; } void init(int n){ for1(i,n){ fa[i] = i; } memset(vis,0,sizeof vis); e.clear(); } int main(){ int t=read(); while(t--){ int n=read(), m=read(), k=read(); init(n); ll ans = 0; for1(i,m){ int u=read(), v=read(), w=read(), c=read(); if(c==0){ u = find(u), v=find(v); if(u != v) fa[u] = v; ans += 1ll*w; } else e.push_back({u,v,w}); } sort(e.begin(),e.end(),cmp); forn(i,e.size()){ int u = e[i].uu, v=e[i].vv; u = find(u), v = find(v); if(u != v){ vis[i] = 1; ans += 1ll*e[i].ww; fa[u] = v; k--; } if(k<=0) break; } forn(i,e.size()) if(!vis[i] && k>0){ ans += 1ll*e[i].ww; k--; } bool flag = 1; int tmp = find(1); for(int i=2;flag && i<=n;i++){ int f = find(i); if(f != tmp) flag = 0; } if(!flag) ans = -1; printf("%lld\n",ans); } return 0; }
|