-
Notifications
You must be signed in to change notification settings - Fork 0
/
BitonicOrdering.cc
88 lines (79 loc) · 1.93 KB
/
BitonicOrdering.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#ifndef LOCAL
#pragma GCC optimize(2)
#endif
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef vector<ll> vi;
typedef pair<ll,ll> ii;
#define pb push_back
#define fst first
#define snd second
#define ALL(cont) cont.begin(), cont.end()
#define mset(a,b) memset(a,b,sizeof(a));
#define fore(i, a, b) for (int i = a, almo5t = b; i < almo5t; ++i)
#define SZ(x) ((int)x.size())
#define FIN ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define oper sum
#define NEUT 0
int sum(int a, int b){
return a+b;
}
struct STree { // segment tree for min over integers
vector<int> st;int n;
STree(int n): st(4*n+5,NEUT), n(n) {}
void init(int k, int s, int e, int *a){
if(s+1==e){st[k]=a[s];return;}
int m=(s+e)/2;
init(2*k,s,m,a);init(2*k+1,m,e,a);
st[k]=oper(st[2*k],st[2*k+1]);
}
void upd(int k, int s, int e, int p, int v){
if(s+1==e){st[k]=v;return;}
int m=(s+e)/2;
if(p<m)upd(2*k,s,m,p,v);
else upd(2*k+1,m,e,p,v);
st[k]=oper(st[2*k],st[2*k+1]);
}
int query(int k, int s, int e, int a, int b){
if(s>=b||e<=a)return NEUT;
if(s>=a&&e<=b)return st[k];
int m=(s+e)/2;
return oper(query(2*k,s,m,a,b),query(2*k+1,m,e,a,b));
}
void init(int *a){init(1,0,n,a);}
void upd(int p, int v){upd(1,0,n,p,v);}
int query(int a, int b){return query(1,0,n,a,b);}
}; // usage: STree rmq(n);rmq.init(x);rmq.upd(i,v);rmq.query(s,e);
int main()
{
FIN;
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#else
#define endl '\n'
#endif
int n;cin>>n;
int ex[n];
ll arr[n];
map<ll,int> ind;
fore(i,0,n){
ex[i] = 1;
cin>>arr[i];
ind[arr[i]] = i;
}
STree rmq(n);
rmq.init(ex);
sort(arr,arr+n);
ll ans = 0;
fore(i,0,n){
int idx = ind[arr[i]];
rmq.upd(idx,0);
ll izq = rmq.query(0,idx);
ll der = rmq.query(idx,n);
ans += min(izq,der);
}
cout<<ans<<endl;
return 0;
}