Submission #520378

#TimeUsernameProblemLanguageResultExecution timeMemory
520378Alex_tz307Ekoeko (COCI21_ekoeko)C++17
110 / 110
13 ms3540 KiB
#include <bits/stdc++.h>

using namespace std;

const int kN = 1e5;
int n, aib[1 + kN], p[kN + 1];

void update(int x) {
  for (int i = x; i <= n; i += i & -i) {
    ++aib[i];
  }
}

int query(int x) {
  int ans = 0;
  for (int i = x; i > 0; i = i & (i - 1)) {
    ans += aib[i];
  }
  return ans;
}

void testCase() {
  string a;
  cin >> n >> a;
  vector<int> pos[26];
  for (int i = 0; i < 2 * n; ++i) {
    pos[a[i] - 'a'].emplace_back(i);
  }
  vector<bool> seq(2 * n);
  for (int i = 0; i < 26; ++i) {
    for (int j = pos[i].size() / 2; j < (int)pos[i].size(); ++j) {
      seq[pos[i][j]] = true;
    }
  }
  string s = "$", t = "$";
  int64_t ans = 0;
  int cnt2 = 0;
  for (int i = 0; i < 2 * n; ++i) {
    if (!seq[i]) {
      ans += cnt2;
      s += a[i];
    } else {
      ++cnt2;
      t += a[i];
    }
  }
  vector<int> inS[26], inT[26];
  for (int i = 1; i <= n; ++i) {
    inS[s[i] - 'a'].emplace_back(i);
  }
  for (int i = 1; i <= n; ++i) {
    inT[t[i] - 'a'].emplace_back(i);
  }
  for (int i = 0; i < 26; ++i) {
    for (int j = 0; j < (int)inT[i].size(); ++j) {
      int poz = inT[i][j];
      p[poz] = inS[i][j];
    }
  }
  for (int i = n; i > 0; --i) {
    ans += query(p[i]);
    update(p[i]);
  }
  cout << ans << '\n';
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int tests = 1;
  for (int tc = 0; tc < tests; ++tc) {
    testCase();
  }
  return 0;
}
#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...