Codeforces Round #723 (Div. 2) D. Kill Anton

D. Kill Anton

题意

给出一个只有 4 4 4 个字母组成的字符串 S S S,请对这个字符串重新排列得到字符串 T T T,使得对字符串 T T T 需要做最多次变换得到字符串 S S S 。每次变换可以交换相邻的两个字母。

题解

  • T T T S S S 的变换过程,一定不会交换相邻相同的字母;
  • T T T S S S 的变换次数等于从 S S S T T T 的变换次数;
  • T T T 一定是相同的字母连续出现,一共有 4 4 4 种字母,所以一共有 4 ! = 24 4!=24 4!=24 种可能的答案,选出变换次数最多的即可。
  • 变换次数等于逆序对个数。

代码

#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 = 1e5 + 5;
char s[maxn], t[maxn], ans[maxn];
map<char, int> mp;
ll n, c[10], dis;
void add(int pos, int x) {
    
    
    while (pos < 10) c[pos] += x, pos += pos & -pos;
}
ll getsum(int pos) {
    
    
    ll ans = 0;
    while (pos) ans += c[pos], pos -= pos & -pos;
    return ans;
}
bool check() {
    
    
    ll d = 0;
    memset(c, 0, sizeof(c));
    rep(i, 1, n) {
    
    
        d += i - 1 - getsum(mp[s[i]]);
        add(mp[s[i]], 1);
    }
    if (d < dis) return 0; 
    dis = d;
    return 1;
}
int main() {
    
    
    int T;
    scanf("%d", &T);
    while (T--) {
    
    
        scanf("%s", s + 1);
        n = strlen(s + 1);
        dis = 0;
        vector<int> cnt(26);
        rep(i, 1, n) cnt[s[i] - 'A']++;
        char D[5] = "ANOT";
        do {
    
    
            int m = 0;
            for (int i = 0; i < 4; ++i) {
    
    
                mp[D[i]] = i + 1;
                rep(_, 1, cnt[D[i] - 'A']) t[++m] = D[i];
            }
            if (check()) rep(i, 1, n) ans[i] = t[i];
        } while (next_permutation(D, D + 4));
        ans[n + 1] = 0;
        printf("%s\n", ans + 1);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43860866/article/details/117635555
今日推荐