考虑如何才能最优。
每次一定把当前最小值移动到边界上,那么看它向左还是向右移更优。
用树状数组维护一下即可,复杂度 \(\mathcal O\rm (nlogn)\)
#include<bits/stdc++.h> #define ri register signed #define p(i) ++i namespace IO{ char buf[1<<21],*p1=buf,*p2=buf; #define gc() p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?(-1):*p1++ struct nanfeng_stream{ template<typename T>inline nanfeng_stream &operator>>(T &x) { ri f=1;x=0;register char ch=gc(); while(!isdigit(ch)) {if (ch=='-') f=0;ch=gc();} while(isdigit(ch)) {x=(x<<1)+(x<<3)+(ch^48);ch=gc();} return x=f?x:-x,*this; } }cin; } using IO::cin; namespace nanfeng{ #define FI FILE *IN #define FO FILE *OUT template<typename T>inline T cmax(T x,T y) {return x>y?x:y;} template<typename T>inline T cmin(T x,T y) {return x>y?y:x;} typedef long long ll; static const int N=1e5+7; int *a[N],vis[N],num[N],l[N],r[N],mx,n; ll ans; struct BIT{ #define lowbit(x) ((x)&-(x)) int c[N]; inline void update(int x,int k) {for (ri i(x);i<=n;i+=lowbit(i)) c[i]+=k;} inline int query(int x) { int res(0); for (ri i(x);i;i-=lowbit(i)) res+=c[i]; return res; } }B; inline int main() { //FI=freopen("nanfeng.in","r",stdin); //FO=freopen("nanfeng.out","w",stdout); cin >> n; for (ri i(1);i<=n;p(i)) cin >> num[i],p(vis[num[i]]),mx=cmax(mx,num[i]); for (ri i(1);i<=mx;p(i)) { if (!vis[i]) continue; a[i]=new int[vis[i]+1]; l[i]=1; } for (ri i(1);i<=n;p(i)) a[num[i]][p(r[num[i]])]=i,B.update(i,1); for (ri i(1);i<=mx;p(i)) { if (!vis[i]) continue; while(l[i]<=r[i]) { int x1=a[i][l[i]],x2=a[i][r[i]]; int d1=B.query(x1-1),d2=B.query(n)-B.query(x2); if (d1<d2) { ans+=d1; B.update(x1,-1); p(l[i]); } else { ans+=d2; B.update(x2,-1); --r[i]; } //printf("ans=%lld\n",ans); } } printf("%lld\n",ans); return 0; } } int main() {return nanfeng::main();}