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;
const int N = (1e5 + 5) * 2;
int n, cnt[26];
long long ans;
string str;
vector<char> strv;
vector<int> indx[26], v;
void up(int* Tree, int index, int s, int e, int num)
{
if (s == num and e == num) {
Tree[index] = 1;
return;
}
if (num < s or num > e) {
return;
}
int mid = (s + e) >> 1;
up(Tree, 2 * index, s, mid, num);
up(Tree, 2 * index + 1, mid + 1, e, num);
Tree[index] = Tree[2 * index] + Tree[2 * index + 1];
}
int query(int* Tree, int index, int s,
int e, int qs, int qe)
{
if (qs <= s and e <= qe) {
return Tree[index];
}
if (s > qe or e < qs) {
return 0;
}
int mid = (s + e) >> 1;
return query(Tree, 2 * index, s,
mid, qs, qe)
+ query(Tree, 2 * index + 1,
mid + 1, e, qs, qe);
}
int main(){
ios_base::sync_with_stdio(false);cin.tie(NULL);
cin >> n;
cin >> str;
n *= 2;
for(auto c : str) cnt[c - 'a']++;
for(int i = 0; i < n; i++){
if(cnt[str[i] - 'a'] > 0){
strv.push_back(str[i]);
cnt[str[i] - 'a'] -= 2;
}
}
for(int i = 0, m = strv.size(); i < m; i++) strv.push_back(strv[i]);
for(int i = 0; i < n; i++) indx[strv[i] - 'a'].push_back(i + 1);
for(int i = 0; i < 26; i++) reverse(indx[i].begin(), indx[i].end());
int mx=0;
for(int i = 0; i < n; i++){
v.push_back(indx[str[i] - 'a'].back());
indx[str[i] - 'a'].pop_back();
mx = max(mx, v[i]);
}
int Tree[6 * mx];
memset(Tree, 0, sizeof(Tree));
for(auto i : v){
ans += query(Tree, 1, 1, mx, i + 1, mx);
up(Tree, 1, 1, mx, i);
}
cout << 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... |