[CF125E]MST Company

codeforces

description

给出一张\(n\)\(m\)条边的无向图,求一棵满足\(1\)号点度数恰好为\(k\)的最小生成树,并输出方案。
\(1\le k\le n\le5000,m\le100000\)

sol

二分一个权值,给每条连接\(1\)号点的边的边权加上这个权值,跑最小生成树即可。
输出方案有点恶心,需要合理控制同边权的边的选取。

code

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int gi(){
	int x=0,w=1;char ch=getchar();
	while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
	if (ch=='-') w=0,ch=getchar();
	while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
	return w?x:-x;
}
const int N = 1e5+5;
struct edge{
	int u,v,w,id;
	bool operator < (const edge &b) const
		{return w==b.w?u<b.u:w<b.w;}
}E[N];
int n,m,k,fa[N],vis[N],ans,tot;
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
int solve(int c){
	for (int i=1;i<=m;++i) if (E[i].u==1) E[i].w+=c;
	sort(E+1,E+m+1);tot=0;
	for (int i=1;i<=n;++i) fa[i]=i;
	for (int i=1;i<=m;++i)
		if (find(E[i].u)!=find(E[i].v)){
			fa[find(E[i].u)]=find(E[i].v);
			tot+=E[i].u==1;
		}
	for (int i=1;i<=m;++i) if (E[i].u==1) E[i].w-=c;
	return tot;
}
void getans(int c){
	for (int i=1;i<=m;++i) if (E[i].u==1) E[i].w+=c;
	sort(E+1,E+m+1);tot=ans=0;
	for (int i=1;i<=n;++i) fa[i]=i;
	for (int i=1;i<=m;++i)
		if (find(E[i].u)!=find(E[i].v)&&tot+(E[i].u==1)<=k){
			fa[find(E[i].u)]=find(E[i].v);
			++ans;tot+=E[i].u==1;vis[i]=1;
		}else vis[i]=0;
	if (ans<n-1||tot<k) {puts("-1");return;}
	printf("%d\n",n-1);
	for (int i=1;i<=m;++i) if (vis[i]) printf("%d ",E[i].id);
	puts("");
}

int main(){
	n=gi();m=gi();k=gi();
	for (int i=1;i<=m;++i){
		int u=gi(),v=gi(),w=gi();
		if (u>v) swap(u,v);
		E[i]=(edge){u,v,w,i};
	}
	int L=-N,R=N,P=1e9;
	while (L<=R){
		int mid=L+R>>1;
		if (solve(mid)>=k) P=mid,L=mid+1;else R=mid-1;
	}
	if (P==1e9) return puts("-1"),0;
	getans(P);
	return 0;
}
posted @ 2018-08-06 21:56  租酥雨  阅读(280)  评论(0编辑  收藏  举报