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;
#define int long long
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<vector<int>> adj(n+1);
vector<map<int,int>> DP(n+1);
vector<int> H(n+1);
vector<int> C(n+1);
vector<int> p(n+1);
vector<int> ind(n+1);
for(int i=1;i<=n;i++){
int a;
cin>>a>>H[i]>>C[i];
adj[a].emplace_back(i);
ind[a]++;p[i]=a;
}
queue<int> q;
vector<bool> visited(n+1);
for(int i=1;i<=n;i++)if(ind[i]==0)q.emplace(i);
while(!q.empty()){
auto x = q.front();q.pop();
visited[x]=true;
DP[x][0]=C[x];
DP[x][H[x]]=-C[x];
DP[x][H[x]+1]=C[x];
for(int&i:adj[x]){
if(DP[x].size()<DP[i].size())swap(DP[x],DP[i]);
for(auto[a,b]:DP[i]){
DP[x][a]+=b;
if(DP[x][a]==0)DP[x].erase(a);
}
}
auto iter = DP[x].find(H[x]);
while(iter!=DP[x].end()){
if(iter->second>0)break;
int val = iter->second;
iter = DP[x].erase(iter);iter--;
iter->second+=val;
}
if(--ind[p[x]]==0)q.emplace(p[x]);
}
int ans = 0;
for(int par=1;par<=n;par++){
if(visited[par])continue;
function<void(int)> dfs = [&](int x){
if(visited[x])return;
visited[x]=true;
DP[x][0]=C[x];
DP[x][H[x]]=-C[x];
DP[x][H[x]+1]=C[x];
for(int&i:adj[x])if(i!=par){
dfs(i);
if(DP[x].size()<DP[i].size())swap(DP[x],DP[i]);
for(auto[a,b]:DP[i]){
DP[x][a]+=b;
if(DP[x][a]==0)DP[x].erase(a);
}
}
};
dfs(par);
auto curr = DP[par];
int currans = 1e15;
int currsum = 0;
if(curr[0]==0)continue;
for(auto[a,b]:curr){
currsum+=b;
currans = min(currans,currsum);
}
ans+=currans;
}
cout << ans << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |