hdu3478(二分图着色)

本文深入探讨了二分图的概念及其判别方法,通过深度优先搜索(DFS)算法实现对图的遍历,判断其是否为二分图。文章提供了详细的代码示例,展示了如何使用邻接表存储图数据结构,并利用DFS进行图的二分性验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解题思路:

https://www.cnblogs.com/kkkkahlua/p/7660024.html

简单说就是只要不是二分图就有可能出现在任何地方,是的话,那未来的行动模式就确定了。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
struct node 
{
	int v,next;
}s[1000009];
int head[100009],cnt,color[100009];
int n,m,st;
void add(int u,int v)
{
	s[cnt].v=v;
	s[cnt].next=head[u];
	head[u]=cnt++;
	
	s[cnt].v=u;
	s[cnt].next=head[v];
	head[v]=cnt++;	
}
bool dfs(int p,int c)
{
	int t;
	color[p]=c;
	for(int i=head[p];i!=-1;i=s[i].next)
	{
		t=s[i].v;
		if(!color[t])
		{
			if(!dfs(t,-c))
			{
				return false;
			}
		}else
		{
			if(color[t]!=-color[p])
			{
				return false;
			}
		}
	}
	return true;
}
int main()
{
	//freopen("t.txt","r",stdin);
	int T,ca=1,u,v;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d%d",&n,&m,&st);
		cnt=0;
		fill(head,head+n,-1);
		fill(color,color+n,0);
		for(int i=0;i<m;i++)
		{
			scanf("%d%d",&u,&v);
			add(u,v);
		}
		if(!dfs(st,1))
		{
			printf("Case %d: YES\n",ca++);
		}else
		{
			printf("Case %d: NO\n",ca++);
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值