Codeforces - Privatization of Roads in Treeland

题目链接:Codeforces - Privatization of Roads in Treeland


这个图比较特殊,是一颗树。

如果没有坏点,那么这颗树需要多少颜色呢?度数最多的点的值!!!

所以现在有k个坏点,所以答案为第k+1大的度数。

至于怎么染色?每个颜色依次染即可。


AC代码:

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=2e5+10,M=N<<1;
int dag[N],n,k,col[N],res;
int head[N],nex[M],to[M],id[M],tot;
inline void add(int a,int b,int c){
	to[++tot]=b; nex[tot]=head[a]; id[tot]=c; head[a]=tot;
}
int cmp(int a,int b){return a>b;}
void dfs(int x,int fa,int c){
	for(int i=head[x];i;i=nex[i]){
		if(to[i]==fa)	continue;
		c++;	if(c>res)	c-=res;
		col[id[i]]=c;	dfs(to[i],x,c);
	}
}
signed main(){
	cin>>n>>k;
	for(int i=1,x,y;i<n;i++){
		scanf("%d %d",&x,&y);	dag[x]++,dag[y]++;	add(x,y,i),add(y,x,i);
	}
	sort(dag+1,dag+n+1,cmp);	res=dag[k+1];
	dfs(1,1,0);
	cout<<res<<'\n';
	for(int i=1;i<n;i++)	printf("%d ",col[i]);
	return 0;
}
发布了553 篇原创文章 · 获赞 242 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43826249/article/details/104254205
今日推荐