zoukankan      html  css  js  c++  java
  • 宝石迷阵-2019头条笔试题

    List<Integer>[] tree保存整颗树。

    Map<Integer, Map<Integer, Character>> edge保存边上的信息。

    Map<Long, Integer> map保存path字符串的hashcodeval和

    char c = sc.next().charAt(0);读取字符。

    import java.util.*;
    public class Main {
        static int[] val, ans;
        static List<Integer>[] tree;
        static int P = 131;
        static Map<Integer, Map<Integer, Character>> edge;
        static Map<Long, Integer> dfs(int root) {
            Map<Long, Integer> map = new HashMap<>(); // path : val
            map.put(0L, val[root]); // 加入当前节点的val
            for(int son: tree[root]) { 
                Map<Long, Integer> smap = dfs(son);
                for(long k : smap.keySet()) {
                    long key = k*P + edge.get(root).get(son);
                    map.put(key, map.getOrDefault(key, 0) + smap.get(k));
                }
            }
            for(long key : map.keySet()) //选择val和最大的path 的val和。
                ans[root] = Math.max(ans[root], map.get(key));
            return map;
        }
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt(), q = sc.nextInt();
            val = new int[n+1];
            tree = new List[n+1];
            ans = new int[n+1];
            for(int i=1; i <= n; i++) {
                val[i] = sc.nextInt();
                tree[i] = new ArrayList<>();
            }
            edge = new HashMap<>(); 
            for(int i=1; i < n; i++) {
                int a = sc.nextInt(), b = sc.nextInt();
                char c = sc.next().charAt(0);
                tree[a].add(b);
                if(!edge.containsKey(a)) edge.put(a, new HashMap<>());
                edge.get(a).put(b, c);
            }
            dfs(1);
            while(q-- > 0) 
                System.out.println(ans[sc.nextInt()]);
        }
    }
    
  • 相关阅读:
    React父组件调用子组件
    ES6数组操作
    ant design mobile入坑记
    vue
    图片上传七牛
    CSS
    CSS矩形、三角形等
    使用POST下载文件
    http https协议
    前端网络必备知识
  • 原文地址:https://www.cnblogs.com/lixyuan/p/13042914.html
Copyright © 2011-2022 走看看