Created
March 16, 2018 17:44
-
-
Save henrybear327/e0f1f781eeaab0a165faf4af05c38662 to your computer and use it in GitHub Desktop.
Throwing a Party
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
struct Data { | |
int p; | |
int w; | |
}; | |
typedef pair<int, int> ii; | |
void solve() | |
{ | |
int n, w; | |
scanf("%d %d", &n, &w); | |
Data inp[n]; | |
inp[0].p = -1; | |
inp[0].w = w; | |
int inDegree[n]; | |
memset(inDegree, 0, sizeof(inDegree)); | |
for (int i = 1; i < n; i++) { | |
int p; | |
scanf("%d %d", &p, &w); | |
p--; | |
inp[i].p = p; | |
inp[i].w = w; | |
inDegree[p]++; | |
} | |
queue<int> q; | |
ii dp[n]; // first: pick, second: not picked | |
for (int i = 0; i < n; i++) { | |
dp[i].first = inp[i].w; | |
dp[i].second = 0; | |
} | |
for (int i = 0; i < n; i++) { | |
if (inDegree[i] == 0) | |
q.push(i); | |
} | |
// self is picked = sum of child not picked | |
// self is not picked = sum of max(child picked, child not picked) | |
while (q.size() > 0) { // bottom up, start from the leaves | |
int cur = q.front(); | |
q.pop(); | |
if (cur == -1) // root | |
continue; | |
int p = inp[cur].p; | |
inDegree[p]--; | |
if (inDegree[p] == 0) | |
q.push(p); | |
dp[p].first += dp[cur].second; | |
dp[p].second += max(dp[cur].first, dp[cur].second); | |
} | |
printf("%d\n", max(dp[0].first, dp[0].second)); | |
} | |
int main() | |
{ | |
int ncase; | |
scanf("%d", &ncase); | |
while (ncase--) | |
solve(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment