1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| #include <cstdio> #include <iostream> using namespace std;
const int maxn = 1e6+7;
int n,head[maxn],cnt,color[maxn],sonNumber[maxn]; bool isFailed = false;
struct Edge { int from, to; }e[maxn<<1];
inline void add(int u, int v) { e[++cnt].from = head[u]; e[cnt].to = v; head[u] = cnt; }
int calcSon(int nowPoint,int lastPoint) { int sum = 1; for(int i = head[nowPoint];i;i = e[i].from) { int nextPoint = e[i].to; if(nextPoint == lastPoint) continue; sum += calcSon(nextPoint, nowPoint); } return sonNumber[nowPoint] = sum; }
void dfs(int nowPoint, int lastPoint, int nowColor) { if(isFailed) return ; color[nowPoint] = nowColor; int cnt = 0 ; for(int i = head[nowPoint]; i; i = e[i].from) { int nextPoint = e[i].to; if(nextPoint != lastPoint) cnt += sonNumber[nextPoint] & 1; } if(color[nowPoint] == color[lastPoint]) { if(cnt) { isFailed = true; return ; } for(int i = head[nowPoint]; i; i = e[i].from) { int nextPoint = e[i].to; if(nextPoint != lastPoint) dfs(nextPoint, nowPoint, nowColor^1); } } else { if(cnt != 1) { isFailed = true; return ; } for(int i = head[nowPoint]; i ;i = e[i].from) { int nextPoint = e[i].to; if(nextPoint != lastPoint) { if(sonNumber[nextPoint] & 1) dfs(nextPoint, nowPoint, nowColor); else dfs(nextPoint, nowPoint, nowColor^1); } } } }
int main() { scanf("%d", &n); for(int i = 1; i < n; ++i) { int x, y; scanf("%d%d", &x, &y); add(x,y); add(y,x); } sonNumber[1] = calcSon(1, 0); dfs(1,0,1); if(isFailed) printf("-1\n"); else { for(int i = 1; i <= n; ++i) { if (color[i]) printf("B"); else printf("R"); } } return 0; }
|