-
Notifications
You must be signed in to change notification settings - Fork 14
/
q4002.java
70 lines (58 loc) · 2.06 KB
/
q4002.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.*;
import java.util.*;
public class Main {
public static int M;
public static int[] money = new int[100001], leader = new int[100001], parent = new int[100001];
public static ArrayList<ArrayList<Integer>> load = new ArrayList<>(100001);
public static PriorityQueue<Integer>[] pq = new PriorityQueue[100001];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
int root = -1;
for (int i=0;i<pq.length;i++) pq[i] = new PriorityQueue<>(Comparator.reverseOrder());
for (int i=0;i<100001;i++) load.add(new ArrayList<>());
for (int i=0;i<parent.length;i++) parent[i] = i;
for (int i=1;i<=N;i++) {
st = new StringTokenizer(br.readLine());
int boss = Integer.parseInt(st.nextToken());
money[i] = Integer.parseInt(st.nextToken());
if (money[i] <= M)
pq[i].offer(money[i]);
leader[i] = Integer.parseInt(st.nextToken());
if (boss == 0) root = i;
else load.get(boss).add(i);
}
dfs(root, -1);
System.out.println(answer);
}
public static int find (int node) {
if (parent[node] == node) return node;
return parent[node] = find(parent[node]);
}
public static void union (int n1, int n2) {
int p1 = find(n1);
int p2 = find(n2);
if (pq[p1].size() > pq[p2].size()) {
int temp = p1;
p1 = p2;
p2 = temp;
}
parent[p1] = p2;
pq[p2].addAll(pq[p1]);
money[p2] += money[p1];
while(money[p2] > M) {
money[p2] -= pq[p2].poll();
}
}
public static long answer = 0;
public static void dfs (int node, int prev) {
for (int go : load.get(node)) {
dfs(go, node);
union(node, go);
}
answer = Math.max(answer, pq[find(node)].size() * (long) leader[node]);
}
}