2021 Cattle Guest Winter Holiday Algorithm Basic Training Camp 1 C-Red and Blue (Bipartite Coloring)

Topic link: click here~

Topic

  • You got a tree, please dye each vertex red or blue.
  • Requirements: There is one and only one red dot around each red dot, and one and only one blue dot around each blue dot.
  • Finally, output the color of each point, R/B, if not possible, output -1
  • Range 1≤n≤100000

Ideas

  • There is only one red a2 on the side of red a1, so there is only one red a1 on the side of red a2. The two can be bound to a point. The blue point is the same, so the number of points must be even.
  • Then the problem is converted into bipartite graph coloring, there are only two colors, and the adjacent colors are different. Then you can bind up from the leaf node, because each leaf node has only one parent. If the parent has been bound, then there is no such graph.
  • After binding to a point, it can be dyed with dfs.

ac code

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e5 + 5;
int vis[maxn], id[maxn], pre[maxn], col[maxn];
//vis表示节点是否绑定过,id表示节点绑定的编号,pre表示父节点编号,col表示节点颜色
int flag = 0;
vector<int> v[maxn];
void dfs1(int s, int fa){
    for(auto it : v[s]){
        if(it == fa) continue;
        pre[it] = s;
        dfs1(it, s);
        if(flag) return;
    }
    //自下而上绑定
    if(!vis[s]){
        if(vis[pre[s]]){ //如果父亲已经绑定过了,那么节点s就成孤儿了,所以不行
            flag = 1;
            return;
        }
        vis[s] = vis[pre[s]] = 1;
        id[s] = id[pre[s]] = s; //绑定成节点s
    }
}
void dfs2(int s, int fa, int color){
    col[s] = color; //染色
    for(auto it : v[s]){
        if(it == fa) continue;
        if(id[s] == id[it]) dfs2(it, s, color); //绑定同一节点,颜色一样
        else dfs2(it, s, 1 ^ color); //否则是二分图上相邻节点,颜色不同
    }
}
int main(){
    int n; cin >> n;
    for(int i = 1; i < n; i ++){
        int x, y;
        cin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    if(n & 1){ //奇数不行
        puts("-1");
        return 0;
    }
    dfs1(1, 0); //绑定节点
    if(flag == 1){ //绑定失败
        puts("-1");
        return 0;
    }
    dfs2(1, 0, 1);//染色
    for(int i = 1; i <= n; i ++){
        if(col[i]) printf("R");
        else printf("B");
    }
    cout << endl;
    return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_43911947/article/details/113552593