牛客 红和蓝 ###K //K
题目链接:https://ac.nowcoder.com/acm/contest/9981/C
思路: 先dfs一次把每个节点和父节点并成一对同颜色的,最终所有的点都可以配对上即是可以染色的,否则是不能成功染色的
然后再跑一次dfs 处理颜色, 在每个节点的时候判断 和子节点是否是同一对,不是的话就让子节点的颜色和当前节点的颜色取反即可
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e5+10; 4 const int mod=1e9+7; 5 #define ll long long 6 #define pi pair<int,int> 7 #define fi first 8 #define sc second 9 #define pb push_back 10 vector<int>E[maxn]; 11 int p[maxn],col[maxn]; 12 int tot; 13 int f; 14 15 void dfs(int u,int fa) 16 { 17 for(auto &v:E[u]) 18 { 19 if(v==fa) 20 continue; 21 dfs(v,u); 22 } 23 if(p[u]) return; 24 if(p[fa]) f=1; 25 p[u]=p[fa]=++tot; 26 } 27 28 void dfs22(int u,int fa) 29 { 30 for(auto &v:E[u]) 31 { 32 if(v==fa) 33 continue; 34 if(p[v]==p[u]) col[v]=col[u]; 35 else col[v]=col[u]^1; 36 dfs22(v,u); 37 } 38 } 39 40 int main() 41 { 42 ios::sync_with_stdio(0); 43 cin.tie(0); 44 int n; 45 cin>>n; 46 for(int i=1;i<n;i++) 47 { 48 int x,y; 49 cin>>x>>y; 50 E[x].pb(y); 51 E[y].pb(x); 52 } 53 p[0]=1; 54 dfs(1,0); 55 if(f) 56 { 57 cout<<-1<<'\n'; 58 return 0; 59 } 60 dfs22(1,0); 61 for(int i=1;i<=n;i++) 62 { 63 if(col[i])cout<<'R'; 64 else cout<<'B'; 65 } 66 cout<<'\n'; 67 68 69 70 }

浙公网安备 33010602011771号