hdu 1829 A Bug's Life

本文介绍了一种通过构建图模型并运用广度优先搜索(BFS)算法来判断是否存在虫子之间的同性恋关系的方法。核心思路是利用二分图的特性,即若存在奇数长度的环则表明可能存在同性恋关系。

题目大意:给出一些虫子之间的关系,看是否有同性恋。

对于任意两个虫子,若有关系则在这两个节点之间连边,如果有同性恋,则肯定会有奇数步的回路,若没有,则不存在同性恋。(二分图的判定)

#include <stdio.h>
#include <queue>
using namespace std;
#define maxn 2010
int color[maxn];
queue < int > Que;
vector < int > g[maxn];
bool bfs(int s)           //bfs染色
{
     while (!Que.empty()) Que.pop();
     Que.push(s);
     color[s] = 0;
     int num = 1;
	 int i;
     while (!Que.empty())
	 {
		int pre = Que.front();
        Que.pop();
        for (i = 0; i < g[pre].size(); i ++)
		{
			int k =g[pre][i];
            if (color[pre] == color[k])
				return false; 
            if (color[k] == -1)
			{
				num ++;
			    color[k] = color[pre]^1;
                Que.push(k);             
            }
         }      
     }
     return true;
}
int main()
{
	int t;
	int i,j;
	int x,y;
	scanf("%d",&t);
	int sum=0;
	int n,m;
	int flag;
	while(t--)
	{
		flag=0;
		sum++;
		memset(color,-1,sizeof(color));
		scanf("%d%d",&n,&m);
		for(i=1;i<=n;i++) g[i].clear();
		for(i=1;i<=m;i++)
		{
			scanf("%d%d",&x,&y);
			g[x].push_back(y);
			g[y].push_back(x);
		}
		for(i=1;i<=n;i++)
			if(color[i]==-1&&!bfs(i))
			{
				flag=1;
				break;
			}
		printf("Scenario #%d:\n",sum);
		if(flag) printf("Suspicious bugs found!\n");
		else printf("No suspicious bugs found!\n");
		printf("\n");
	}
	return 0;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值