This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
int main(){
int N;
cin >> N;
vector<vector<int>> E(N);
for (int i = 0; i < N - 1; i++){
int X, Y;
cin >> X >> Y;
X--;
Y--;
E[X].push_back(Y);
E[Y].push_back(X);
}
int M;
cin >> M;
vector<int> A(M), B(M), C(M);
for (int i = 0; i < M; i++){
cin >> A[i] >> B[i] >> C[i];
A[i]--;
B[i]--;
}
vector<int> p(N, -1);
vector<vector<int>> c(N);
vector<int> d(N, 0);
queue<int> Q;
Q.push(0);
vector<int> bfs;
while (!Q.empty()){
int v = Q.front();
Q.pop();
bfs.push_back(v);
for (int w : E[v]){
if (w != p[v]){
p[w] = v;
c[v].push_back(w);
d[w] = d[v] + 1;
Q.push(w);
}
}
}
vector<vector<int>> path(M);
vector<vector<int>> id(N);
for (int i = 0; i < M; i++){
int u = A[i], v = B[i];
while (d[u] > d[v]){
path[i].push_back(u);
u = p[u];
}
while (d[v] > d[u]){
path[i].push_back(v);
v = p[v];
}
while (u != v){
path[i].push_back(u);
path[i].push_back(v);
u = p[u];
v = p[v];
}
path[i].push_back(u);
id[u].push_back(i);
}
reverse(bfs.begin(), bfs.end());
vector<int> dp(N, 0);
for (int v : bfs){
for (int w : id[v]){
vector<bool> in_path(N, false);
for (int x : path[w]){
in_path[x] = true;
}
int sum = 0;
for (int x : path[w]){
for (int y : c[x]){
if (!in_path[y]){
sum += dp[y];
}
}
}
dp[v] = max(dp[v], sum + C[w]);
}
int sum = 0;
for (int w : c[v]){
sum += dp[w];
}
dp[v] = max(dp[v], sum);
}
cout << dp[0] << endl;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |