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>
#pragma GCC optimize("O3,unroll-loops")
#define pb push_back
#define F first
#define S second
#define ld long double
#define all(a) a.begin(),a.end()
#define pii pair <int,int>
#define PII pair<pii , pii>
#define int long long
#define sz(v) (int)v.size()
#define rep(i , a , b) for(int i=a;i <= (b);i++)
#define per(i , a , b) for(int i=a;i >= (b);i--)
#define deb(x) cout <<#x << " : " << x << "\n" ;
using namespace std ;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int maxn = 6e5+10 , lg = 48, inf = 1e9+10 , mod = 998244353 ;
int fen[maxn] , n , cnt , sb[maxn] , l[maxn] , r[maxn] ;;
void upd(int x , int w){
while(x <= n+4){
fen[x] += w ;
x += x&-x ;
}
}
int que(int x){
int ans =0 ;
while(x){
ans += fen[x] ;
x -= x&-x ;
}
return ans ;
}
int bui(){
int a;
cin >> a;
if(a != 0){
sb[a] =1 ;
return a;
}
cnt++;
int id = cnt - 1;
l[id] = bui();
r[id] = bui() ;
sb[id] = sb[l[id]] + sb[r[id]];
if(sb[l[id]] < sb[r[id]])swap(l[id],r[id]) ;
return id ;
}
int sm = 0 , ans =0 ;
void rem(int v){
if(v <= n){
upd(v , -1) ;
}else{
rem(l[v]) ;
rem(r[v]) ;
}
}
void add(int v){
if(v <= n){
sm += que(n)-que(v);
upd(v , 1) ;
}else{
add(l[v]);
add(r[v]);
}
}
void dfs(int v){
if(v <= n){
upd(v , 1) ;
return ;
}
dfs(r[v]) ;
rem(r[v]) ;
dfs(l[v]) ;
sm = 0;
add(r[v]) ;
ans += min(sm , sb[l[v]] * sb[r[v]] - sm) ;
}
signed main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n ;
cnt = n + 1 ;
int rt= bui() ;
dfs(rt) ;
cout << ans << '\n' ;
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... |