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;
const int MAXN = 20;
int a[MAXN], h[MAXN], c[MAXN], deg[MAXN], n;
map<int, long long> s[MAXN];
vector<int> q;
// dp(v, i) =
// h[v] < i: \sum{dp(u, i)}
// h[v] >= i: max(\sum{dp(u, i)}, c[v] + \sum{dp(u, h[v])})
void cdeg(int v){
if (deg[v]) return;
auto it = s[v].lower_bound(h[v]);
if (it == s[v].end() || it->first != h[v])
it = s[v].emplace_hint(it, h[v], 0);
it->second += c[v];
for (int x = c[v]; it != s[v].begin() && x;){
it--;
if (it->second <= x){
x -= it->second;
it = s[v].erase(it);
}
else{
it->second -= x;
x = 0;
}
}
q.push_back(v);
}
void merge(map<int, long long> &a, map<int, long long> &b){
if (a.size() < b.size()) swap(a, b);
for (const pair<int, long long> &x: b){
a[x.first] += x.second;
}
}
long long pfm(map<int, long long> &hs){
long long p = 0;
for (auto it = hs.rbegin(); it != hs.rend(); it++)
p = it->second = p + it->second;
hs.emplace_hint(hs.end(), INT_MAX, 0);
return p;
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
cin >> n;
for (int i=0; i<n; i++){
cin >> a[i] >> h[i] >> c[i];
a[i]--, deg[a[i]]++;
}
for (int i=0; i<n; i++)
cdeg(i);
long long result = accumulate(c, c + n, 0LL);
while (q.size()){
int v = q.back(); q.pop_back();
merge(s[a[v]], s[v]);
deg[a[v]]--, cdeg(a[v]);
}
for (int i=0; i<n; i++){
if (!deg[i]) continue;
vector<pair<int, int>> cyc;
map<int, long long> hs;
for (int pos = i; deg[pos]; deg[pos] = 0, pos = a[pos]){
merge(hs, s[pos]);
cyc.emplace_back(h[pos], c[pos]);
}
sort(cyc.begin(), cyc.end());
long long max_branch = pfm(hs);
for (int lptr=0, rptr=0; lptr<cyc.size(); lptr=rptr){
long long v = hs.lower_bound(cyc[lptr].first)->second;
for (; rptr < cyc.size() && cyc[lptr].first == cyc[rptr].first; rptr++)
v += cyc[rptr].second;
max_branch = max(max_branch, v);
}
result -= max_branch;
}
cout << result << "\n";
}
Compilation message (stderr)
worst_reporter2.cpp: In function 'int main()':
worst_reporter2.cpp:77:38: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
77 | for (int lptr=0, rptr=0; lptr<cyc.size(); lptr=rptr){
| ~~~~^~~~~~~~~~~
worst_reporter2.cpp:79:25: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
79 | for (; rptr < cyc.size() && cyc[lptr].first == cyc[rptr].first; rptr++)
| ~~~~~^~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |