https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=945
C++版本一
/*
*@Author: STZG
*@Language: C++
*/
//#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
#define endl "\n"
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=100000+10;
const int M=100000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,p,l,r,u,v;
int ans,cnt,flag,temp,sum;
int co[N];
char str;
struct node{};
vector<int>G[N];
bool dfs(int u,int c){
co[u]=c;
for(int i=0,j=G[u].size();i<j;i++){
int v=G[u][i];
if(co[v]==c)return false;
if(co[v]==0&&!dfs(v,-c))return false;
}
return true;
}
void init(){
memset(co,0,sizeof(co));
for(int i=0;i<n;i++)
G[i].clear();
flag=1;
}
int main()
{
#ifdef DEBUG
freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
#endif
//ios::sync_with_stdio(false);
//cin.tie(0);
//cout.tie(0);
//scanf("%d",&t);
while(~scanf("%d",&n)&&n){
scanf("%d",&m);
init();
for(int i=1;i<=m;i++){
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
for(int i=0; i<n; ++i) {
if(co[i] == 0) {
//如果顶点i还没被染色,则染成1
if(!dfs(i,1)) {
flag=0;
break;
}
}
}
if(flag){
printf("BICOLORABLE.\n");
}else{
printf("NOT BICOLORABLE.\n");
}
}
#ifdef DEBUG
printf("Time cost : %lf s\n",(double)clock()/CLOCKS_PER_SEC);
#endif
//cout << "Hello world!" << endl;
return 0;
}
C++版本二
/***********************************************/
int co[250];
struct node{
int v;
node(){}
node(int _v):v(_v){}
};
vector<node>G[250];//邻接表法
int fff=0;
void dfs(int now,int pre)
{
if(~co[now])
{
if(co[pre]!=0) co[now]=-co[pre];
else co[now]=1;//头结点染色
//cout<<"co"<<G[now].size()<<endl;
for(int i=0;i<G[now].size();i++)
{
if(fff==0 && G[now][i].v!=pre)
dfs(G[now][i].v,now);
}
}
else{//染过
if(co[now]==co[pre]){
fff=1;
}
}
}
int main()
{
int n,m;
while(cin>>n && n)
{
fff=0;
mem0(G);
cin>>m;
for(int i=1;i<=m;i++){
int a,b;
cin>>a>>b;
G[a].push_back(node(b));
G[b].push_back(node(a));
}
mem0(co);
dfs(0,0);
//for(int i=0;i<n;i++) cout<<co[i]<<"tt";
if(fff){
cout<<"NOT BICOLORABLE."<<endl;
}
else cout<<"BICOLORABLE."<<endl;
}
return 0;
}
/*
3
3
0 1
1 2
2 0
3
2
0 1
1 2
9
8
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0
*/