Bicoloring UVA - 10004 二分图判断

\(\color{#0066ff}{题目描述}\)

多组数据,n=0结束,每次一个n,m,之后是边,问你是不是二分图

\(\color{#0066ff}{输入样例}\)

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

\(\color{#0066ff}{输出样例}\)

NOT BICOLORABLE.
BICOLORABLE.
BICOLORABLE.

\(\color{#0066ff}{题解}\)

二分图染色法

看能否用两种颜色染色,使相邻两点颜色不同

#include<cstdio>
#include<queue>
#include<vector>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cctype>
#include<cmath>
#define _ 0
#define LL long long
#define Space putchar(' ')
#define Enter putchar('\n')
#define fuu(x,y,z) for(int x=(y),x##end=z;x<=x##end;x++)
#define fu(x,y,z)  for(int x=(y),x##end=z;x<x##end;x++)
#define fdd(x,y,z) for(int x=(y),x##end=z;x>=x##end;x--)
#define fd(x,y,z)  for(int x=(y),x##end=z;x>x##end;x--)
#define mem(x,y)   memset(x,y,sizeof(x))
#ifndef olinr
inline char getc()
{
    static char buf[100001],*p1=buf,*p2=buf;
    return (p1==p2)&&(p2=(p1=buf)+fread(buf,1,100001,stdin),p1==p2)? EOF:*p1++;
}
#else
#define getc() getchar()
#endif
template<typename T>inline void in(T &x)
{
    int f=1; char ch; x=0;
    while(!isdigit(ch=getc()))(ch=='-')&&(f=-f);
    while(isdigit(ch)) x=x*10+(ch^48),ch=getc();
    x*=f;
}
int T;
struct node
{
    int to;
    node *nxt;
};
typedef node* nod;
nod s[105050];
nod head[555];
int col[555];
int n,m,top;
inline void add(int from,int to)
{
    static node st[105050],*tail=st;
    nod t=top? s[top--]:tail++;
    t->to=to;
    t->nxt=head[from];
    head[from]=t;
}
inline bool dfs(int x,int c)
{
    col[x]=c;
    for(nod i=head[x];i;i=i->nxt)
    {
        if(~col[i->to])
        {
            if(col[i->to]!=(c^1)) return false;
        }
        else return dfs(i->to,c^1);
    }
    return true;
}
int main()
{
    while(1)
    {
        in(n);
        if(!n) break;
        in(m);
        fu(i,0,n) head[i]=NULL,col[i]=-1;
        int x,y;
        fuu(i,1,m) in(x),in(y),add(x,y),add(y,x);
        printf(dfs(1,0)? "BICOLORABLE.":"NOT BICOLORABLE."),Enter;
        fu(i,0,n) for(nod j=head[i];j;j=j->nxt) s[++top]=j; 
    }   
    return ~~(0^_^0);
}

猜你喜欢

转载自www.cnblogs.com/olinr/p/10045867.html
今日推荐