D - Good Tuple Problem atcoder abc 327

发布时间 2023-11-10 09:36:49作者: lightsong

D - Good Tuple Problem

https://atcoder.jp/contests/abc327/tasks/abc327_d

 

思路

https://www.zhihu.com/question/292465499

判断二分图

的常见方法是染色法:用两种颜色,对所有顶点逐个染色,且相邻顶点染不同的颜色

如果发现相邻顶点染了同一种颜色,就认为此图不为二分图

当所有顶点都被染色,且没有发现同色的相邻顶点,就退出

 

Code

https://atcoder.jp/contests/abc327/submissions/47406923

#include<cstdio>
#include<iostream>
#include<vector>

using namespace std;
int n,m,color[200010], a[200010], b[200010];
vector<int> edge[200010];


int dfs(int x,int c){
    color[x]=c

;
    for(int i=0;i<edge[x].size();i++){
        int v=edge[x][i];
        if(color[v]==color[x]){
            return 0;
        }
        if(color[v]==0 && !dfs(v,-c)){
            return 0;
        }
    }
    return 1;
}
void solve(){
    for(int i=1;i<=n;i++){
        if(color[i]==0){
            if(!dfs(i,1)){
                printf("No");
                return ;
            }
        }
    }
    printf("Yes");
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++){
        cin >> a[i];
    }
    
    for(int i=1;i<=m;i++){
        cin >> b[i];
    }

    for(int i=1;i<=m;i++){
        int x,y;
        x = a[i];
        y = b[i];
//        scanf("%d%d",&x,&y);
        edge[x].push_back(y);
        edge[y].push_back(x);
    }
    solve();
    return 0;
}