zoukankan      html  css  js  c++  java
  • 二分图判断(模板)

    //判断图G是否为二分图,可以用染色法。
    //从一点开始,把他邻接的点图为与其不同的颜色,那么只要bfs一圈一圈图。如果图的时候遇到颜色相同,
    //表明2个点相连,所以不是;
    #include<stdio.h>
    #include<string.h>
    #include<queue>
    using namespace std;
    #define maxn 210
    int map[maxn][maxn],color[maxn];
    int bfs(int u,int n)
    {
        int i;
        queue<int>q;
        q.push(u);
        color[u]=1;
        while(!q.empty())
        {
            int v=q.front();
            q.pop();
            for(i=1;i<=n;i++)
            {
                if(color[i]==-1&&map[v][i])
                {
                    q.push(i);
                    color[i]=!color[v];
                }
                if(color[i]==color[v]&&map[v][i])
                    return 0;
            }
        }
        return 1;
    }
    int main()
    {
        int i,j,n,m;
        while(scanf("%d%d",&n,&m)!=EOF)
        {
            memset(color,-1,sizeof(color));
            memset(map,0,sizeof(map));
            for(i=0;i<m;i++)
            {
                int x,y;
                scanf("%d%d",&x,&y);
                map[x][y]=map[y][x]=1;
            }
            int flag=1;
            for(i=1;i<=n;i++)
            {
                if(color[i]==-1&&!bfs(i,n))
                {
                    flag=0;
                    break;
                }
            }
            if(flag)
                printf("YES
    ");
            else printf("NO
    ");
        }
    }
  • 相关阅读:
    数组的反转和二维数组
    初识数组
    Python学习笔记-Day8
    Python学习笔记-Day7
    Python学习笔记-Day6
    Python学习笔记-Day5
    Python学习笔记-Day4
    Python学习笔记-Day3
    Python学习笔记-Day2
    Python学习笔记-Day1
  • 原文地址:https://www.cnblogs.com/sweat123/p/4675829.html
Copyright © 2011-2022 走看看