题解 | #红和蓝#
红和蓝
https://www.nowcoder.com/practice/34bf2aaeb61f47be980b9ec0ab238c36
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { static int f[]; static int[] color; static List<List<Integer>> Graph; //以上三个数组或集合第一个值,均为空,因为根节点是从1开始而不是0开始 public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); f = new int[n+1]; color = new int[n+1]; Graph = new ArrayList<>(); for (int i = 0; i <= n; i++) { Graph.add(new ArrayList<>()); } for (int i = 0; i < n-1; i++) { int a = in.nextInt(); int b = in.nextInt(); // 双向边,防止死循环 Graph.get(a).add(b); Graph.get(b).add(a); } //System.out.println(Graph); dfs1(1, 0); // 如果有节点未被配对,说明无答案 for (int i = 1; i < n + 1; i++) { if (f[i] == 0){ System.out.println(-1); return; } } color[1] = 1; dfs2(1, 0); for (int i = 1; i < n + 1; i++) { if (color[i] == 1){ System.out.print("R"); }else { System.out.print("B"); } } } public static void dfs1(int u, int father){ for (int i = 0; i < Graph.get(u).size(); i++) { int v = Graph.get(u).get(i); // father是u的父节点,也就是v的爷爷节点 // 因为Graph保存的是双向边,uv已经考虑过了,vu就需要过滤掉,防止死循环 if (v == father) continue; dfs1(v, u); // dfs自底向上递归 // 如果uv还未配对,则将它们配对 if (f[u] == 0 && f[v] == 0){ f[u] = v; f[v] = u; } } } public static void dfs2(int u, int father){ for (int i = 0; i < Graph.get(u).size(); i++) { int v = Graph.get(u).get(i); if (v == father) continue; if (f[u] == v){ // 配对成功的设置为相同颜色 color[v] = color[u]; }else { // 没有配对,需要更换另一种颜色 color[v] = color[u] ^ 1; // 异或即可切换数字代表不同颜色 } dfs2(v, u); //dfs 自顶向下递归遍历 } } }