Codeforces Round #656 (Div. 3) D. a-Good String(分治)

题目传送
题意:
给定一个字符串s,长度为偶数
我们规定一个字符串叫做c-good,如果它满足以下任意一个条件:

字符串长度是1,且包含字母c
字符串长度大于1,左半边都是c,右半边为c+1-good
字符串长度大于1,右半边都是c,左半边为c+1-good

c+1就表示字符 c+1 = d

例:s="cdbbaaa"是一个a-good字符串
它的右半边全是a;
它的左半边"cdbb"是b-good a+1 = b ,因为:
"cdbb"的右半边全是b;
"cdbb"的左半边是c-good b+1 = c ,因为:
"cd"的左半边是c
"cd"的右半边是d

思路:
分治思想,因为他总是一半一半的下去,这就很类似归并排序。

一直分区间,再判断现在的左右区间的需要修改的数目,然后再递归下去,最后取改动最小值。

开始想错了,我直接贪心了一波,在目前的左右区间中选最少改动的那个区间,再递归另外一区间,实际只是错的

AC代码

#include <bits/stdc++.h>
inline long long read(){char c = getchar();long long x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
const int N = 2e5 + 10;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const int mod = 1e9+7;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
string s;
int solve(int l,int r,char c)
{
    if(l == r) return s[l] != c;//退出递归的条件
    int Mid = (l+r)/2,numl = 0,numr = 0;
    for(int i = l;i <= Mid;i++)
        if(s[i] != c)
            numl++;
    for(int i = Mid+1;i <= r;i++)//暴力找出需要改动的字符数量
        if(s[i] != c)
            numr++;
    return min(numl+solve(Mid+1,r,c+1),numr+solve(l,Mid,c+1));//左右区间都要递归下去哟
}
signed main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    //    freopen("input.txt","r",stdin);
    //    freopen("output.txt","w",stdout);
    int t,n;
    cin >> t;
    while(t--)
    {
        cin >> n;
        cin >> s;
        s = " " + s;//这里是为了使得字符串的第一个英文字符的位置为1
        cout << solve(1,n,'a') << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/moasad/article/details/107443031
今日推荐