洛谷P2619 [国家集训队]Tree I
思路:
很显然的最小生成树,但是强制我们用 n e e d need need条白色的边。我们可以二分一个值 x x x,让所有的白色边都加上 x x x。这样就能够让白边靠前或者靠后。最终的答案就是最小生成树求出来的权值减去加上的总和。
代码:
#include<bits/stdc++.h>
#define fi first
#define se second
#define ll long long
#define mp make_pair
#define pb push_back
#define ls x<<1
#define rs x<<1|1
#define lson x<<1,l,mid
#define rson x<<1|1,mid+1,r
#define pii pair<int,int>
#define all(x) x.begin(),x.end()
#define cl(x,y) memset(x,y,sizeof(x))
#define nxtp(a,n) next_permutation(a+1,a+n+1)
#define mem(x,y,n) memset(x,y,sizeof(int)*(n+5))
const int N=1e6+10;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
const double eps=1e-8;
const double pi=acos(-1);
const double INF=1e18;
using namespace std;
struct edge
{
int u,v,w,w2,col;
}e[N];
int n,m,fa[N],ans,k;
int find(int x)
{
if(fa[x]!=x)
fa[x]=find(fa[x]);
return fa[x];
}
int kruskal()
{
ans=0;
int i,tot=0,cnt=0;
for(i=1;i<=n;i++)
fa[i]=i;
sort(e+1,e+m+1,[](edge x,edge y){
if(x.w2==y.w2)
return x.col<y.col;
return x.w2<y.w2;
});
for(i=1;i<=m;i++)
{
int t1=find(e[i].u),t2=find(e[i].v);
if(t1==t2)
continue;
if(e[i].col==0)
cnt++;
fa[t1]=t2;
ans+=e[i].w2;
tot++;
if(tot==n-1)
break;
}
return cnt;
}
int check(int x)
{
int i;
for(i=1;i<=m;i++)
if(e[i].col==0)
e[i].w2=e[i].w+x;
return kruskal()>=k;
}
int main()
{
#ifdef ChuTian
freopen("in.in","r",stdin);
freopen("out.out","w",stdout);
#endif
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int i;
cin>>n>>m>>k;
for(i=1;i<=m;i++)
{
cin>>e[i].u>>e[i].v>>e[i].w>>e[i].col;
e[i].w2=e[i].w;
e[i].u++;
e[i].v++;
}
int l=-100,r=100,sum,res;
while(l<=r)
{
int mid=(l+r)/2;
if(check(mid))
{
l=mid+1;
sum=mid;
res=ans;
}
else
r=mid-1;
}
cout<<res-sum*k<<endl;
return 0;
}