Bzoj2654:tree
题目
Sol
神题!
二分所有的白边减去一个值,这样做\(kruskal\)就会多选一些白边
就这样
二分范围为\([-101, 101]\)!!!
# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
# define File(a) freopen(a".in", "r", stdin), freopen(a".out", "w", stdout)
using namespace std;
typedef long long ll;
const int _(5e4 + 5);
IL int Input(){
RG int x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
}
int n, m, need, fa[_], mst, ans = 1e9;
struct Edge{
int u, v, w, type;
IL bool operator <(RG Edge B) const{
return w != B.w ? w < B.w : type < B.type;
}
} edge[_ << 1];
IL int Find(RG int x){
return fa[x] == x ? x : fa[x] = Find(fa[x]);
}
IL int Check(RG int mid){
for(RG int i = 1; i <= m; ++i)
if(!edge[i].type) edge[i].w -= mid;
RG int num = 0, tot = 0; mst = 0;
for(RG int i = 1; i <= n; ++i) fa[i] = i;
sort(edge + 1, edge + m + 1);
for(RG int i = 1; i <= m; ++i){
RG int fx = Find(edge[i].u), fy = Find(edge[i].v);
if(fx == fy) continue;
fa[fx] = fy, mst += edge[i].w, ++tot;
if(!edge[i].type) ++num;
}
for(RG int i = 1; i <= m; ++i)
if(!edge[i].type) edge[i].w += mid;
return num >= need;
}
int main(RG int argc, RG char *argv[]){
n = Input(), m = Input(), need = Input();
for(RG int i = 1; i <= m; ++i)
edge[i] = (Edge){Input() + 1, Input() + 1, Input(), Input()};
RG int l = -101, r = 101;
while(l <= r){
RG int mid = (l + r) >> 1;
if(Check(mid)) ans = mid, r = mid - 1;
else l = mid + 1;
}
Check(ans);
printf("%d\n", mst + need * ans);
return 0;
}