Codeforces D. a-Good String ( dfs / 暴力) (Round #656 Div.3)

传送门

题意: 字符串如果长度=1 并且为’a’ ;当长度>1时, 需要满足一半全是a,另一半必须为b-good 字符串 ,依次类推下去,这就是 a -good 字符串。
你可以选择某个字符并将它改变,题目需找到最小的选择数使得初始字符串变成一个a - good。
在这里插入图片描述
思路:

  • 比赛的时候想成二分+递归判断被卡了一个小时,呜呜呜太菜了。
  • 看了别人的题解才知道原来直接dfs所有的情况,计算出不同的字符数再求个min就好。
  • 详情看代码,不过还有一种暴力搜索的解法

代码实现:

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int  inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9 + 7;
const int  N = 2e5 + 5;

int t, n;
string s;

int dfs(string s, char c){
    int len = s.size();
    if(!len) return 0;
    if(len == 1) return c != s[0];//只有不同才会修改
    string s1(s.begin(), s.begin() + len / 2);//将字符串分成两半
    string s2(s.begin() + len / 2, s.end());
    int cnt1 = 0, cnt2 = 0; //分别统计左右两边和c不同的字符数
    for(int i = 0; i < len / 2; i ++){
        if(s1[i] != c) cnt1 ++;
        if(s2[i] != c) cnt2 ++;
    }
    return min(dfs(s1, c + 1) + cnt2, dfs(s2, c + 1) + cnt1); //接着dfs需要修改次数小的那一边
}

signed main (){
    IOS;
    cin >> t;
    while(t --){
        cin >> n >> s;
        cout << dfs(s, 'a') << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Satur9/article/details/107429091