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;
#ifdef LOCAL
#include "debug.h"
#else
#define debug(...) 42
#endif
const int N = 2e5 + 5;
int n;
int a[N], c[N], lab[N], deg[N];
bool vis[N];
vector<int> g[N], gph[N];
map<int, long long> mp[N];
void dfs(int u) {
for (int v : g[u]) {
dfs(v);
if (mp[u].size() < mp[v].size()) {
mp[u].swap(mp[v]);
}
for (auto [x, y] : mp[v]) {
mp[u][x] += y;
}
}
if (a[u] != -1) {
mp[u][a[u]] += c[u];
for (auto it = mp[u].upper_bound(a[u]); it != mp[u].end(); it = mp[u].erase(it)) {
auto &delta = (*it).second;
if (c[u] < delta) {
delta -= c[u];
break;
}
c[u] -= delta;
}
}
}
vector<int> st, ver;
void DFS(int u) {
ver.push_back(u);
vis[u] = 1;
st.push_back(u);
for (int v : gph[u]) {
if (vis[v]) {
while (1) {
int x = st.back(); st.pop_back();
lab[x] = u;
if (u != x) {
c[u] += c[x];
}
if (a[x] != a[u]) {
a[u] = -1;
}
if (x == v) {
break;
}
}
} else {
DFS(v);
}
}
if (lab[u] == -1) {
st.pop_back();
}
}
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
cin >> n;
long long res = 0;
for (int i = 1; i <= n; ++i) {
int p; cin >> p >> a[i] >> c[i];
a[i] = 1e9 - a[i] + 1;
res += c[i];
gph[p].push_back(i);
}
fill(lab + 1, lab + n + 1, -1);
for (int i = 1; i <= n; ++i) {
if (!vis[i]) {
DFS(i);
for (int u : ver) {
for (int v : gph[u]) {
if (lab[v] == -1) {
g[u].push_back(v);
++deg[v];
}
}
}
for (int u : ver) {
if ((lab[u] == -1 || lab[u] == u) && !deg[u]) {
dfs(u);
for (auto [x, y] : mp[u]) {
res -= y;
}
}
}
ver.clear();
}
}
cout << res;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |