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 rep(i,a,b) for(int i=(a); i<(b); ++i)
#define all(x) x.begin(),x.end()
#define sz(x) int(x.size())
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vvi;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;
ordered_multiset nums[int(4e5)];
int main(){
cin.tie(NULL),cin.sync_with_stdio(false);
int n; cin >> n;
int m = n*2-2;
int cc = 0;
vvi adj(m+1);
auto build = [&](int& at, auto&& build) -> int {
int v; cin >> v;
if (v==0){
int my = at;
adj[my].push_back(build(--at,build));
adj[my].push_back(build(--at,build));
return my;
}else{
at++;
return v-1;
}
};
build(m,build);
auto dfs = [&](int at, auto&& dfs) -> array<ll,2> {
if (at<n){
nums[cc].insert(at);
return {0,cc++};
}else{
array<ll,2> inds;
ll ans = 0;
rep(i,0,2){
auto ret = dfs(adj[at][i],dfs);
ans += ret[0];
inds[i] = ret[1];
}
ll minext = 1e18;
if (sz(nums[inds[0]]) < sz(nums[inds[1]])) swap(inds[0],inds[1]);
{
//
ll extl = 0, extr = 0;
for(auto c : nums[inds[1]]){
auto v = nums[inds[0]].lower_bound(c);
int smaller = nums[inds[0]].order_of_key(*v);
extl += sz(nums[inds[0]]) - smaller;
extr += smaller;
}
minext = min(extl, extr);
}
// merge small into large
for(auto c : nums[inds[1]]) nums[inds[0]].insert(c);
return {ans + minext, inds[0]};
}
};
cout << dfs(n*2-2,dfs)[0] << '\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... |
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |