Conclusion: Each time the character is dropped to the outermost optimal, with a tree-like array of statistical answers, the characters placed on the outermost can be considered to disappear, directly in the tree-like array to delete the good.
Perceptual understanding is that throwing characters into the middle increases the number of other characters moving, but it's not right to throw them outside.
#include <iostream>#include<cstring>#include<cstdlib>#include<cstdio>#definell Long Longusing namespacestd;Const intmaxn=500010;intn, x, num;intCNT[MAXN], TREE[MAXN], pos[ -][maxn];ll ans;CharS[MAXN];BOOLV[maxn];inlinevoidAddintXintDelta) { for(; x<=n;x+=x&-x) tree[x]+=Delta;} InlineintQueryintx) {intsum=0; for(; x;x-=x&-x) sum+=tree[x];returnsum;}intMain () {scanf ("%s", s+1); N=strlen (s+1); for(intI=1; i<=n;i++) cnt[x=s[i]-'a']++, pos[x][++pos[x][0]]=i, tree[i]=i&-i; for(intI=0;i< -; i++)if(cnt[i]&1) num++; if(num>1)returnPuts"-1"),0; for(intI=1; i<=n;i++) if(!V[i]) { intx=s[i]-'a', nxt=pos[x][pos[x][0]--]; if(I==NXT) ans+= (query (n)-query (i)) >>1; ElseAns+=query (N)-query (NXT); Add (i,-1); Add (NXT,-1); v[i]=v[nxt]=1; } printf ("%lld\n", ans);}
View Code
Atcoder Regular Contest 088 e-papple Sort (tree array + conclusion)