Advertisement
erek1e

POI Task Letters

Jun 22nd, 2023
642
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. void update(vector<int> &fenwick, int index, int value) {
  7.     while (index < fenwick.size()) {
  8.         fenwick[index] += value;
  9.         index += index & -index;
  10.     }
  11. }
  12. int getSum(const vector<int> &fenwick, int index) {
  13.     int sum = 0;
  14.     while (index) {
  15.         sum += fenwick[index];
  16.         index -= index & -index;
  17.     }
  18.     return sum;
  19. }
  20.  
  21. int main() {
  22.     int n; cin >> n;
  23.     string s, t; cin >> s >> t;
  24.     vector<int> positions[26];
  25.     for (int i = n-1; i >= 0; --i) positions[s[i]-'A'].push_back(i);
  26.    
  27.     vector<int> fenwick(1+n);
  28.  
  29.     long long moves = 0;
  30.     for (int i = 0; i < n; ++i) {
  31.         int cur = positions[t[i]-'A'].back();
  32.         positions[t[i]-'A'].pop_back();
  33.         moves = moves + (cur+getSum(fenwick, n-cur))-i;
  34.         update(fenwick, n-cur, +1);
  35.     }
  36.     cout << moves << endl;
  37.     return 0;
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement