Educational Codeforces Round 96 (Rated for Div. 2) E. String Reversal

E. String Reversal

题意

给出一个由小写字母组成的字符串,如果通过交换相邻字母的操作将这个字符串翻转,最少需要多少次操作。

题解

  • 对于相同的字母,原本在左边的,一定会通过交换操作放到左边;
  • 找到原始字符串的每个字母翻转后对应的位置,得到一个长度为 n n n 的排列;
  • 排列的逆序对个数即为最少的操作次数;
  • 因为每次交换操作一定会使这个排列的逆序对个数减少 1 1 1 ,最终翻转完成后逆序对个数为 0 0 0

代码

#include<bits/stdc++.h>
#define rep(i, a, n) for (int i = a; i <= n; ++i)
#define per(i, a, n) for (int i = n; i >= a; --i)
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 5;
char s[maxn], t[maxn];
int a[maxn], c[maxn];
void add(int pos, int x) {
    
    
    while (pos < maxn) c[pos] += x, pos += pos & -pos;
}
int getsum(int pos) {
    
    
    int ans = 0;
    while (pos) ans += c[pos], pos -= pos & -pos;
    return ans;
}
int main() {
    
    
    int n;
    scanf("%d%s", &n, s + 1);
    memcpy(t, s, sizeof(s));
    reverse(t + 1, t + 1 + n);
    queue<int> q[26];
    rep(i, 1, n) q[s[i] - 'a'].push(i);
    rep(i, 1, n) {
    
    
        a[i] = q[t[i] - 'a'].front();
        q[t[i] - 'a'].pop();
    }
    ll ans = 0;
    rep(i, 1, n) {
    
    
        ans += i - 1 - getsum(a[i]);
        add(a[i], 1);
    }
    printf("%lld\n", ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43860866/article/details/117674317