[Link] https://www.acmicpc.net/problem/16437
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
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
// #include <bits/stdc++.h>
using namespace std;
#define for0(i, n) for(int i = 0; i < n; i++)
#define for1(i, n) for(int i = 1; i < n; i++)
#define fori(s, e) for(int i = s; i < e; i++)
#define endl "\n"
typedef long long ll;
const int INF = 987654321;
const int MAX = 123456;
const int log = 17;
int n;
ll sheep[MAX];
int deg[MAX];
vector<int> bridge;
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n;
bridge.resize(n);
for0(i, n-1) {
char t; int a, p; cin >> t >> a >> p;
p--;
deg[p]++;
sheep[i+1] = t == 'S' ? a : -a;
bridge[i+1] = p;
}
queue<int> q;
for0(i, n) if(deg[i] == 0) q.push(i);
while(!q.empty()) {
int cur = q.front(); q.pop();
if(cur == 0) continue;
int next = bridge[cur];
if(sheep[cur] > 0) sheep[next] += sheep[cur];
if(--deg[next] == 0) q.push(next);
}
cout << sheep[0];
return 0;
}