Zoom笔试题

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
          
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值