-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
101 lines (75 loc) · 2.14 KB
/
main.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <algorithm>
#include <iostream>
#include <vector>
struct Vertex {
int index;
int galleons;
int galleonSum;
int numNodes;
int timeSum;
};
std::vector<Vertex> vertices;
std::vector<std::vector<std::pair<int, int>>> outEdges;
void dfs(int vertex) {
int galleonSum = vertices[vertex].galleons;
int numNodes = 1;
int timeSum = 0;
for (auto child : outEdges[vertex]) {
dfs(child.first);
numNodes += vertices[child.first].numNodes;
galleonSum += vertices[child.first].galleonSum;
timeSum += 2 * child.second + vertices[child.first].timeSum;
}
vertices[vertex].numNodes = numNodes;
vertices[vertex].galleonSum = galleonSum;
vertices[vertex].timeSum = timeSum;
}
long getMaxGold(int vertexId, int startTime) {
std::sort(outEdges[vertexId].begin(), outEdges[vertexId].end(),
[](std::pair<int, int> a, std::pair<int, int> b) {
long numNodesA = vertices[a.first].numNodes;
long numNodesB = vertices[b.first].numNodes;
long timeA = 2 * a.second + vertices[a.first].timeSum;
long timeB = 2 * b.second + vertices[b.first].timeSum;
;
return timeA * numNodesB < timeB * numNodesA;
});
long totalGold = vertices[vertexId].galleons - startTime;
for (auto child : outEdges[vertexId]) {
// We only start when we reach the child
startTime += child.second;
totalGold += getMaxGold(child.first, startTime);
startTime += child.second + vertices[child.first].timeSum;
}
return totalGold;
}
void testcase() {
int n;
std::cin >> n;
vertices.clear();
vertices.resize(n + 1);
vertices[0] = {0, 0, -1, 1, -1};
for (int i = 0; i < n; i++) {
int temp;
std::cin >> temp;
vertices[i + 1] = {i + 1, temp, -1, 1, -1};
}
outEdges.clear();
outEdges.resize(n + 1);
for (int i = 0; i < n; i++) {
int u, v, l;
std::cin >> u >> v >> l;
outEdges[u].push_back(std::make_pair(v, l));
}
dfs(0);
std::cout << getMaxGold(0, 0) << "\n";
}
int main() {
std::ios_base::sync_with_stdio(false);
int t;
std::cin >> t;
for (int i = 0; i < t; i++) {
testcase();
}
return 0;
}