2021牛客寒假算法基础集训营1 C 红和蓝

在这里插入图片描述
打比赛的时候没来得及看这道题,赛后发现这道题和我之前总结的数组模拟邻接表和图等很有关系。赛后花了蛮长时间理解。

思路:

在这里插入图片描述
判断是否染色后,再用异或的计算,相同为0,不同为一,染上R和B

AC代码:
PS(因为是有两条边,所以e和ne记得开N*2)

#include<bits/stdc++.h>
using namespace std;
const int N=100010;
int n,h[N],e[N*2],ne[N*2],f[N],col[N],idx;
int son,cnt;
int res=0;//能不能染色 
void add(int a,int b)
{
	e[idx]=b;
	ne[idx]=h[a];
	h[a]=idx++;
}
void dfs1(int x,int fa)
{
	int son=0;
	for(int i=h[x];i!=-1;i=ne[i])
	{
		int j=e[i];
		if(j==fa) continue;
		son++;
		dfs1(j,x);
	}
	if(son==0||f[x]==0)
	{
		if(f[fa]!=0)
		{
			res=-1;
			return ;
		}
		f[x]=f[fa]=++cnt;
		
	}
}
void dfs2(int x,int fa)
{
	for(int i=h[x];i!=-1;i=ne[i])
	{
		int j=e[i];
		if(j==fa) continue;
		if(f[x]==f[j]) col[j]=col[x];
		else col[j]=col[x]^1;  //不同出1,相同出0
		dfs2(j,x); 
	}
}
int main()
{
	scanf("%d", &n);
	memset(h,-1,sizeof(h));
	for(int i=1;i<=n-1;i++)
	{
		int a,b;
		cin>>a>>b;
		add(a,b);
		add(b,a); //存两条边; 
	}
	dfs1(1,0);
	if(res==-1||f[0]!=0)
	{
		printf("-1\n");
	}
	else
	{
		dfs2(1,0);
		for(int i=1;i<=n;i++)
		{
			if(col[i]==1) printf("R");
			else printf("B");
		}
	} 
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值