HDU 1829 A Bug's Life

本文介绍了一种使用广度优先搜索(BFS)算法来判断一个图是否为二分图的方法,并通过一个具体的编程实现案例进行说明。该方法适用于竞赛编程及图论问题解决。

看别人都用并查集。。我用的是bfs

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <queue>
#include <ctime>
#include <set>
#define ll long long
#define MK make_pair
#define PB push_back
#define SZ(x) ((int)(x).size())
#define FOR(it,c) for ( __typeof((c).begin()) it=(c).begin(); it!=(c).end(); it++ )
using namespace std;

int n,m,st[2013];
vector<int> vec[2013];

bool bfs(int i){
    queue<int> q;
    q.push(i);
    while(!q.empty()){
        int u=q.front();q.pop();
        FOR(v,vec[u])
            if(!st[*v]){
                q.push(*v);
                st[*v]=-st[u];
            }
            else if(st[*v]==st[u]) return false;
    }
    return true;
}

int main(){
#ifndef ONLINE_JUDGE
    freopen("a.in","r",stdin);
    freopen("a.out","w",stdout);
#endif
    int t,ca=0;
    cin>>t;
    while(t--){
        cout<<"Scenario #"<<++ca<<':'<<endl;
        memset(st,0,sizeof(st));
        cin>>n>>m;
        for(int i=0;i<m;i++){
            int a,b;scanf("%d%d",&a,&b);
            vec[a].PB(b);
            vec[b].PB(a);
        }
        bool ok=true;
        for(int i=1;i<=n&&ok;i++)
            if(!st[i]){
                st[i]=1;
                if(!bfs(i)) ok=false;
            }
        if(ok) puts("No suspicious bugs found!");
        else puts("Suspicious bugs found!");
        puts("");
        for(int i=1;i<=n;i++) vec[i].clear();
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值