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 file(name) if (fopen(name".inp", "r")) { freopen(name".inp", "r", stdin); freopen(name".out", "w", stdout); }
#define FOR(i, a, b) for(int i = (a); i <= (b); ++i)
#define REV(i, b, a) for(int i = (b); i >= (a); --i)
#define REP(i, n) for(int i = 0; i < (n); ++i)
#define ll long long
#define fi first
#define se second
#define int long long
using namespace std;
const int N = 2e5 + 5;
int cnt, node;
int n;
int l[2 * N], r[2 * N];
int st[2 * N], ed[2 * N];
int a[N];
struct BIT {
int tree[N];
void add(int x, int v){
while(x <= n){
tree[x] += v;
x += x & -x;
}
}
int query(int x){
int ret = 0;
while(x) ret += tree[x], x -= x & -x;
return ret;
}
} bit;
void read_tree(int v){
int x; cin >> x;
st[v] = cnt;
if(x == 0){
l[v] = ++node;
read_tree(node);
r[v] = ++node;
read_tree(node);
}
else a[cnt++] = x;
ed[v] = cnt;
}
int dfs(int v){
if(ed[v] - st[v] == 1){
bit.add(a[st[v]], 1);
return 0;
}
int ls = ed[l[v]] - st[l[v]];
int rs = ed[r[v]] - st[r[v]];
int ans1 = 0, ans2 = 0;
if(ls < rs){
ans1 += dfs(l[v]);
FOR(i, st[l[v]], ed[l[v]] - 1) {
bit.add(a[i], -1);
}
ans1 += dfs(r[v]);
FOR(i, st[l[v]], ed[l[v]] - 1) {
ans2 += bit.query(a[i]);
}
FOR(i, st[l[v]], ed[l[v]] - 1) {
bit.add(a[i], 1);
}
}
else {
ans1 += dfs(r[v]);
FOR(i, st[r[v]], ed[r[v]] - 1) {
bit.add(a[i], -1);
}
ans1 += dfs(l[v]);
FOR(i, st[r[v]], ed[r[v]] - 1) {
ans2 += ls - bit.query(a[i]);
}
FOR(i, st[r[v]], ed[r[v]] - 1) {
bit.add(a[i], 1);
}
}
return ans1 + min(ls * rs - ans2, ans2);
}
void solve(int tc) {
cin >> n;
read_tree(0);
cout << dfs(0) << '\n';
return;
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int tc = 1;
// cin >> tc;
for(int i = 1; i <= tc; ++i) solve(tc);
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... |
# | 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... |