List<Integer>[] tree
保存整颗树。
Map<Integer, Map<Integer, Character>> edge
保存边上的信息。
Map<Long, Integer> map
保存path
字符串的hashcode
及val和
。
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()]);
}
}