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
| #include <iostream> #include <algorithm> #define maxn 50010 #define maxm 100010 using namespace std;
int n, m, k;
struct Edge { int fr, to, w, col, _w;
friend bool operator < (const Edge &u, const Edge &v) { if (u.w != v.w) return u.w < v.w; return u.col < v.col; } } e[maxm];
int fa[maxn]; void init_fa(int n) { for (int i = 1; i <= n; ++i) fa[i] = i; }
int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
pair<int, int> check(int x) { for (int i = 1; i <= m; ++i) if (!e[i].col) e[i].w = e[i]._w - x; sort(e + 1, e + m + 1); init_fa(n); pair<int, int> ans = { 0, 0 }; for (int i = 1; i <= m; ++i) { int u = e[i].fr, v = e[i].to, w = e[i].w, col = e[i].col, fu, fv; if ((fu = find(u)) == (fv = find(v))) continue; ans.first += !col; ans.second += w; fa[fv] = fu; } return ans; }
int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
cin >> n >> m >> k; for (int i = 1; i <= m; ++i) { cin >> e[i].fr >> e[i].to >> e[i].w >> e[i].col; ++e[i].fr; ++e[i].to; e[i]._w = e[i].w; } int l = -100, r = 100, mid, ans; while (l <= r) { mid = l + r >> 1; pair<int, int> res = check(mid); if (res.first >= k) ans = res.second + k * mid, r = mid - 1; else l = mid + 1; } cout << ans << "\n"; return 0; }
|