This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define mp make_pair
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef complex<double> cd;
const int MAXN = 1e5+10;
const int MOD = 1e9+7;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1);
int tree[MAXN];
void upd(int pos, int x, int lim){ for(;pos<=lim;pos+=(pos&-pos)) tree[pos]+=x; }
int query(int pos){
int ret=0;
for(;pos>0;pos-=(pos&-pos)) ret+=tree[pos];
return ret;
}
void solve(){
int n; cin >> n;
string s; cin >> s;
vector<int> freq(26, 0);
for(auto u : s) freq[(int)(u-'a')]++;
string s1="", s2="";
int ans=0, tot=0;
vector<int> occ(26, 0);
for(auto u : s){
occ[(int)(u-'a')]++;
if(occ[(int)(u-'a')]>(freq[(int)(u-'a')]>>1)){
tot++;
s2+=u;
}
else{
ans+=tot;
s1+=u;
}
}
int lim=(int)s2.size();
vector<queue<int>> id(26);
for(int i=0;i<(int)s2.size();i++) id[(int)(s2[i]-'a')].push(i+1);
for(int i=1;i<=(int)s2.size();i++) upd(i, i, lim), upd(i+1, -i, lim);
for(int i=1;i<=(int)s1.size();i++){
int curr=id[(int)(s1[i-1]-'a')].front();
id[(int)(s1[i-1]-'a')].pop();
ans+=max(query(curr)-i, 0);
upd(i, 1, lim);
upd(curr+1, -1, lim);
}
cout << ans << "\n";
}
int32_t main(){
ios_base::sync_with_stdio(false); cin.tie(NULL);
int tt=1;
//~ cin >> tt;
while(tt--) solve();
return 0;
}
# | 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... |