fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. long long mirrorScore(const string &s) {
  5. int n = s.size();
  6. // stacks[k] will hold unmarked indices i where s[i] == 'a'+k
  7. vector<vector<int>> stacks(26);
  8. long long score = 0;
  9.  
  10. for (int i = 0; i < n; i++) {
  11. char c = s[i];
  12. // compute mirror letter
  13. char m = char('z' - (c - 'a'));
  14. int mi = m - 'a';
  15.  
  16. if (!stacks[mi].empty()) {
  17. // found a mirror-match; use the closest j
  18. int j = stacks[mi].back();
  19. stacks[mi].pop_back();
  20. score += (i - j);
  21. } else {
  22. // no mirror waiting: add this index to its letter-stack
  23. stacks[c - 'a'].push_back(i);
  24. }
  25. }
  26.  
  27. return score;
  28. }
  29.  
  30. int main() {
  31. ios::sync_with_stdio(false);
  32. cin.tie(nullptr);
  33.  
  34. string S;
  35. cin >> S;
  36.  
  37. cout << mirrorScore(S) << "\n";
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0.01s 5312KB
stdin
aczzx
stdout
5