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>
#define int long long
using namespace std;
const int N = 2e5 + 42, INF = 1e18 + 42;
int n, h[N], cost[N], par[N];
bool vu[N], root[N], act[N];
vector<int> adj[N], path, id[N];
multiset<pair<int, int>> DFS(int i, int pre) {
vu[i] = true;
multiset<pair<int, int>> ans;
for(int j : adj[i])
if(j != pre) {
multiset<pair<int, int>> fils = DFS(j, i);
if(ans.size() < fils.size())
swap(ans, fils);
for(auto p : fils)
ans.insert(p);
}
for(int j : id[i]) {
ans.insert({0, cost[j]});
ans.insert({h[j]+1, cost[j]});
}
for(int j : id[i]) {
int suppr = cost[j];
while(suppr) {
auto it = ans.lower_bound({h[j]+1, 0});
it--;
if((*it).second <= suppr) {
suppr -= (*it).second;
ans.erase(it);
} else {
auto copy = (*it);
ans.erase(it);
ans.insert({copy.first, copy.second - suppr});
suppr = 0;
}
}
}
return ans;
}
void dfs(int i) {
if(act[i]) {
root[i] = true;
int j = path.size();
while(path[j-1] != i) {
id[i].push_back(j);
j--;
}
return;
}
if(vu[i])
return;
path.push_back(i);
vu[i] = act[i] = true;
dfs(par[i]);
act[i] = false;
path.pop_back();
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for(int i = 0; i < n; i++) {
cin >> par[i] >> h[i] >> cost[i];
par[i]--;
if(i != par[i])
adj[par[i]].push_back(i);
}
for(int i = 0; i < n; i++)
id[i].push_back(i);
for(int i = 0; i < n; i++)
dfs(i);
int ans = 0;
for(int i = 0; i < n; i++)
if(root[i]) {
multiset<pair<int, int>> slope = DFS(i, i);
for(auto p : slope)
if(p.first == 0)
ans += p.second;
else
break;
}
cout << ans;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |