#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define inp(data_name) freopen(data_name,"r",stdin);
#define out(data_name) freopen(data_name,"w",stdout);
#define name "main"
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define FORD(i,a,b) for(int i=(b);i>=(a);--i)
#define N 2'00'000
vector<int>pos[27],serve2;
int total[27]={},cnt[27]={},times=0;
string s;
int n;
int BIT[N+2]={};
void upd(int id,int val){
for(;id<=n;id+=id&-id) BIT[id]+=val;
}
int Get(int id){
int sum=0;
for(;id;id-=id&-id) sum+=BIT[id];
return sum;
}
int32_t main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin>>n>>s; s='#'+s;
FOR(i,1,2*n) total[s[i]-'a']++;
LL ans=0;
int cur=n;
FOR(i,1,2*n){
++cnt[s[i]-'a'];
if (cnt[s[i]-'a']>total[s[i]-'a']/2){
++cur;
if (i<n+1) ans+=(cur-i);
serve2.push_back({pos[s[i]-'a'][cnt[s[i]-'a']-total[s[i]-'a']/2-1]});
}
else {
++times;
pos[s[i]-'a'].push_back(times);
}
}
cur=0;
for(auto&x:serve2) {
ans+=Get(n)-Get(x);
upd(x,1);
++cur;
}
printf("%lld",ans);
}
# | 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... |