Submission #850477

#TimeUsernameProblemLanguageResultExecution timeMemory
850477serifefedartarEkoeko (COCI21_ekoeko)C++17
110 / 110
22 ms5740 KiB
#include <bits/stdc++.h>
using namespace std;
 
#define fast ios::sync_with_stdio(0);cin.tie(0);
#define s second
#define f first
typedef long long ll;
const ll MOD = 1e9 + 7;
const ll LOGN = 20;
const ll MAXN = 2e5 + 5;

vector<int> occ[26];
vector<int> leftV, rightV;
ll fen[MAXN];
void update(int k) {
    while (k < MAXN) {
        fen[k]++;
        k += k&-k;
    }
}

ll query(int k) {
    ll res = 0;
    while (k >= 1) {
        res += fen[k];
        k -= k&-k;
    }
    return res;
}

int main() {
    fast
    int n;
    string s;
    cin >> n >> s;
    s = "#" + s;

    for (int i = 1; i <= 2*n; i++)
        occ[s[i]-'a'].push_back(i);

    for (int i = 0; i < 26; i++) {
        int q = occ[i].size() / 2;
        for (int j = 0; j < q; j++)
            leftV.push_back(occ[i][j]);
        for (int j = q; j < 2*q; j++)
            rightV.push_back(occ[i][j]);
    }

    sort(leftV.begin(), leftV.end());
    sort(rightV.begin(), rightV.end());
    
    vector<int> occ2[26];
    for (int i = n-1; i >= 0; i--) {
        occ2[s[leftV[i]] - 'a'].push_back(i+1);
    }

    vector<int> inv;
    for (auto u : rightV) {
        int ch = s[u] - 'a';
        inv.push_back(occ2[ch].back());
        occ2[ch].pop_back();
    }

    ll ans = 0;
    for (int i = 0; i < n; i++) {
        ans += i - query(inv[i]);
        update(inv[i]);
    }

    memset(fen, 0, sizeof(fen));
    for (auto u : rightV)
        leftV.push_back(u);

    for (int i = 0; i < 2*n; i++) {
        ans += i - query(leftV[i]);
        update(leftV[i]);
    }

    cout << ans << "\n"; 
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...