#include<algorithm>
#include<iostream>
#include<vector>
#include<string>
#include<random>
#include<cmath>
#include<stack>
#include<map>
#include <iomanip>
#include <queue>
#include <set>
using namespace std;
using ll = long long;
using ull = unsigned long long;
ll mod = 1e9 + 7;
ll pv(ll a, ll b) {
if (b == 0)return 1;
ll res = (pv(a, b / 2));
if (b % 2) {
return (((res * res) % mod) * (a % mod)) % mod;
}
else {
return (res * res) % mod;
}
}
ll gcd(ll a, ll b) {
while (b) {
a %= b;
swap(a, b);
}
return a;
}
vector<vector<ll>>gp, adj;
vector<ll>dist, x, vis, vis1;
ll ans = 0;
void dfs(ll u, ll p) {
for (ll& x : adj[u]) {
if (x != p) {
dist[x] += dist[u];
dfs(x, u);
}
}
}
void dfs1(ll u) {
vis[u] = 1;
ans += x[u];
for (ll& x : gp[u]) {
if (vis[x] == 0) {
dfs1(x);
}
}
}
void solve() {
ll n, s; cin >> n >> s;
adj = gp = vector<vector<ll>>(n);
vector<ll> p(n);
vis = vis1 = dist = x = vector<ll>(n);
for (ll i = 0; i < n; i++) {
cin >> x[i] >> p[i];
p[i]--;
if (p[i] == -1)continue;
gp[p[i]].push_back(i);
adj[i].push_back(p[i]);
}
dist = x;
for (ll i = 0; i < n; i++) {
if (p[i] == 0) {
dfs(i, -1);
}
}
for (ll i = 0; i < n; i++) {
if (dist[i] > 0) {
dfs1(i);
}
}
cout << ans << endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll _ = 1;
//cin >> _;
while (_--) {
solve();
}
}
# | 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... |