#include<bits/stdc++.h>
#define LL long long
#define pii pair<int,int>
#define all(x) x.begin(),x.end()
#define mem(a, b) memset(a,b,sizeof(a))
using namespace std;
const int maxn = 2e5 + 5;
const int MOD = 1e9 + 7;
inline int read() {
int s = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-') f = -1;ch = getchar();}
while (ch >= '0' && ch <= '9') {s = (s << 1) + (s << 3) + ch - '0';ch = getchar();}
return s * f;
}
inline void write(int x) {
if (x < 0) x = -x, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
int n,tree[maxn];
char mp[maxn];
queue<int>g[30];
int lowbit(int x) { return x&(-x);}
void modify(int x,int val){
for(int i=x;i<=n;i+=lowbit(i)) tree[i]+=val;
}
int getsum(int x){
int ans=0;
for(int i=x;i>0;i-=lowbit(i)){
ans+=tree[i];
}return ans;
}
int main(){
scanf("%d",&n);
scanf("%s",mp+1);
for(int i=1;i<=n;i++) g[mp[i]-'a'].push(i);
LL ans=0;
for(int i=n;i>=1;i--){
int x=g[mp[i]-'a'].front();
g[mp[i]-'a'].pop();
ans+=(i-getsum(x)-1);
modify(x,1);
}
printf("%lld\n",ans);
return 0;
}
codeforces edu96-E. String Reversal (逆序对+思维)
最新推荐文章于 2022-01-20 14:49:47 发布