10004 - Bicoloring***

本文介绍了一种使用深度优先搜索(DFS)算法来判断一个无向图是否可以被二分染色的方法。该算法适用于强连通图,通过递归地为每个节点分配两种不同的颜色,并检查相邻节点的颜色是否不同,以此来判断图是否可以进行有效的二分染色。

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

/* 极简单一题,但是没有解出。 题目要求:图是强连通的,无向 要求对图中节点染色,只有两种颜色可以选择 判断是否存在一种情况使相邻的两节点颜色都不同 思路: 深度优先搜索 */ #include <cstdio> #include <cstring> int n,m; bool graph[210][210]; int color[210]; bool dfs(int k,int c) { for(int i=1;i<=n;i++) { if(graph[k][i]==1) { if(color[i]==c) return false; else if(color[i]==-1) { color[i]=1-c; if(!dfs(i,1-c)) return false; } } } return true; } int main() { //freopen("data.in","r",stdin); int u,v; while(1) { scanf("%d",&n); if(n==0) break; memset(graph,false,sizeof(graph)); memset(color,-1,sizeof(color)); scanf("%d",&m); if(m==0) break; for(int i=0;i<m;i++) { scanf("%d %d",&u,&v); u++;v++; graph[u][v]=graph[v][u]=1; } color[1]=0; //the graph will be strongly connected if(!dfs(1,0)) printf("NOT BICOLORABLE.\n"); else printf("BICOLORABLE.\n"); } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值