2021 Niu Ke Winter Holiday Algorithm Basic Training Camp 1 C Problem-Red and Blue

Topic: I
Insert picture description here
looked at this question during the game and thought it was complicated. I thought it was an algorithm of other graph theory. After the game, I only found out that it was written by someone else. It was just a deep search. o(╥﹏╥)o

Solution: It
can be found that the leaf node of the tree must match its parent node, so we search it deeply and simulate the matching process from the bottom up. For the subtree with i as the root node, we first The sub-subtree matches well. If there is a matching relationship between the child nodes adjacent to i, then the i node must match its parent node. If there is only 1 unmatched point, then let him match the i node. If there are more than one, then there must be no solution.
Finally, we paint the root node any color, and then paint the other nodes in turn according to the matching relationship.

Code:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<set>
#define iss ios::sync_with_stdio(false)
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int,int>pii;
const int MAXN=1e5+5;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
struct node
{
    
    
    int to;
    int next;
}e[MAXN<<1];
int cnt=0;
int head[MAXN];
int match[MAXN];
int colar[MAXN];
void add(int u,int v)
{
    
    
    e[cnt].to=v;
    e[cnt].next=head[u];
    head[u]=cnt++;
}
void dfs(int u,int f)
{
    
    
    int num=0;
    for(int i=head[u];i!=-1;i=e[i].next){
    
    
        int v=e[i].to;
        if(v==f) continue;
        dfs(v,u);
        if(!match[v]){
    
    
            num++;
            if(num==1){
    
    
                match[u]=v;
                match[v]=u;
            } 
        }
    }
}
void solve(int u,int f,int co)
{
    
    
    colar[u]=co;
    for(int i=head[u];i!=-1;i=e[i].next){
    
    
        int v=e[i].to;
        if(v==f) continue;
        if(match[u]==v){
    
    
            solve(v,u,co);

        }else{
    
    
            solve(v,u,1-co);
        }
    }
}
int main()
{
    
    
    int n;
    cin>>n;
    memset(head,-1,sizeof head);
    for(int i=1;i<=n-1;i++){
    
    
        int u,v;
        cin>>u>>v;
        add(u,v);
        add(v,u);
    }
    dfs(1,-1);
    for(int i=1;i<=n;i++){
    
    
        if(!match[i]){
    
    
            printf("-1\n");
            return 0;
        }
    }
    solve(1,-1,1);
    for(int i=1;i<=n;i++){
    
    
        printf("%c",colar[i]?'R':'B');
    }
}

Guess you like

Origin blog.csdn.net/weixin_45755679/article/details/113533081