zoom笔试有点难 ,这里参考牛客大佬写的答案,做下记录
1.有一颗有根树 根节点为1号节点 每个节点为红色或蓝色 假设第i个节点的权值为从根节点到该节点红蓝节点的数量之差 请你返回所有节点的权值之和
输入
第一行输入n个节点,第二行为每个节点的颜色,接下来n-1行为a、b节点之间有连接:
5
RBBRB
1 5
2 5
1 3
5 4
输出
3
思路:创建出图,然后dfs回溯计算。路径要从节点1开始。重点是构图的这种方式,图的题目做的太少了。
class ListNdoe {
long val;
ListNdoe next;
public ListNdoe(long val, ListNdoe next) {
this.val = val; //每个节点权值,即每个节点路径上红蓝色之差
this.next = next;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int root = 0;
int n = sc.nextInt();
System.out.println(n);
int[] color = new int[n];//每个节点的颜色
ListNdoe[] graph = new ListNdoe[n];//记录每个节点会和哪几个节点有连接关系
for (int i = 0;i < n;i++) {
graph[i] = new ListNdoe(0,null);
}
sc.nextLine();
String str = sc.nextLine();
System.out.println(str);
for (int i = 0;i < n;i++) {
if (str.charAt(i) == 'R') {
color[i] = 1;//1代表红色
}
}
for (int i = 0;i < n - 1;i++) { //把各个节点根据关系组合起来
// 题目条件从1开始计,为了和数组下标对齐,都减1