D. a-Good String
题意:
定义一个串为
c
−
好
串
c-好串
c−好串:
∣
s
∣
=
1
,
s
=
c
|s|=1,s=c
∣s∣=1,s=c
∣
s
∣
>
1
|s|>1
∣s∣>1 ,左半部分全为
c
c
c,右半部分为
(
c
+
1
)
好
串
(c+1)好串
(c+1)好串,或者左半部分为
(
c
+
1
)
好
串
)
(c+1)好串)
(c+1)好串),右半部分为
c
−
好
串
c-好串
c−好串
思路:
分治
code:
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define eps 1e-6
using namespace std;
const int maxn = 2e6 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll n, m;
string s;
int dfs(int l, int r, char c){
if(l == r) return s[l] != c;
int mid = (l + r) >> 1;
int x = 0, y = 0;
for(int i = l; i <= mid; ++i) x += s[i] != c;
for(int i = mid + 1; i <= r; ++i) y += s[i] != c;
x += dfs(mid + 1, r, c + 1);
y += dfs(l, mid, c + 1);
return min(x, y);
}
void work()
{
cin >> n;
cin >> s;s="@"+s;
cout << dfs(1, n, 'a') << endl;
}
int main()
{
ios::sync_with_stdio(0);
int TT;cin>>TT;while(TT--)
work();
return 0;
}