二部图(不存在奇数环的图)



Catch
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2040    Accepted Submission(s): 995


Problem Description
A thief is running away!
We can consider the city where he locates as an undirected graph in which nodes stand for crosses and edges stand for streets. The crosses are labeled from 0 to N–1.
The tricky thief starts his escaping from cross S. Each moment he moves to an adjacent cross. More exactly, assume he is at cross u at the moment t. He may appear at cross v at moment t + 1 if and only if there is a street between cross u and cross v. Notice that he may not stay at the same cross in two consecutive moment.
The cops want to know if there’s some moment at which it’s possible for the thief to appear at any cross in the city.

 

Input
The input contains multiple test cases:
In the first line of the input there’s an integer T which is the number of test cases. Then the description of T test cases will be given.
For any test case, the first line contains three integers N (≤ 100 000), M (≤ 500 000), and S. N is the number of crosses. M is the number of streets and S is the index of the cross where the thief starts his escaping.
For the next M lines, there will be 2 integers u and v in each line (0 ≤ u, v < N). It means there’s an undirected street between cross u and cross v.


 

Output
For each test case, output one line to tell if there’s a moment that it’s possible for the thief to appear at any cross. Look at the sample output for output format.


Sample Input
2
3 3 0
0 1
0 2
1 2
2 1 0
0 1
 

Sample Output
Case 1: YES
Case 2: NO

判断是否存在奇数环(等价于判断是否为二部图)

#include
#include
#include
#include
using namespace std;
const int maxx=1e6+10;
int t,n,m,s,index;
int head[100010],color[100010];
struct A{
    int u,v;
    int next;
}f[maxx];
void build(int u,int v)
{
    f[index].u=u;
    f[index].v=v;
    f[index].next=head[u];
    head[u]=index++;
}
bool bfs(int start)
{
    queue Q;
    Q.push(start);
    color[start]=1;
    while(!Q.empty())
    {
        int q=Q.front();
        Q.pop();
        for(int i=head[q];i!=-1;i=f[i].next)
        {
            int to=f[i].v;
            if(color[to]==0)
            {
                color[to]=-color[q];
                Q.push(to);
            }
            else if(color[to]==color[q])
            {
                return true;
            }
        }
    }
    return false;
}
int main()
{
    int cas=1;
 scanf("%d",&t);
 while(t--)
    {
        index=0;
        memset(head,-1,sizeof(head));
        memset(color,0,sizeof(color));
        int a,b;
        scanf("%d %d %d",&n,&m,&s);
        for(int j=0;j         {
            scanf("%d %d",&a,&b);
            build(a,b);
            build(b,a);
        }
        if(bfs(s))
            printf("Case %d: YES\n",cas++);
        else
            printf("Case %d: NO\n",cas++);
    }
 return 0;
}

你可能感兴趣的:(二分图)