題意:
略
分析:
狀態:f[i][ch],前i組以ch結尾所得的最小cnt
狀態轉移:f[i][ch] = min(f[i][ch], f[i-1][chp]+cost(i, chp, ch)),其中cost(i, chp, ch)表示第i組變成目標的花費
Code:
#include <set>
#include <map>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <cstdio>
#include <bitset>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
#define REPI(i, s, e) for(int i = (s); i <= (e); i ++)
#define REPD(i, e, s) for(int i = (e); i >= (s); i --)
const int MAXCH = 128;
const int MAXN = 1000;
const int INF = 0x3f3f3f3f;
char str[MAXN+1];
vector<string> part;
int k, f[MAXN][MAXCH+1], hash[MAXCH+1], hash1[MAXCH+1];
void input(void)
{
scanf("%d %s", &k, str);
}
void split(int final)
{
int idx = 0;
string tmp;
part.erase(part.begin(), part.end());
REPI(i, 1, final) {
tmp.clear();
REPI(j, 1, k) {
tmp += str[idx ++];
}
part.push_back(tmp);
}
}
int cost(int idx, int pre, int cur)
{
string l, r, m;
REPI(i, 0, k-1) {
if( cur == part[idx][i] ) {
r += part[idx][i];
}
else if( pre == part[idx][i] ) {
l += part[idx][i];
}
else {
m += part[idx][i];
}
}
int len = m.length();
strcpy(str, m.c_str());
sort(str, str+len);
m.clear();
REPI(i, 0, len-1) {
m += str[i];
}
string ans;
ans += l, ans += m, ans += r;
if( pre == cur && !m.length() ) {
return 0;
}
int p = ans[0], rst = 1;
len = ans.length()-1;
REPI(i, 1, len) {
if( p != ans[i] ) {
rst += 1;
p = ans[i];
}
}
if( l.length() ) {
rst -= 1;
}
return rst;
}
int process(void)
{
int final = strlen(str)/k;
REPI(i, 0, final) {
memset(f[i], 0x3F, sizeof(f[i]));
}
split(final);
memset(hash, 0, sizeof(hash));
REPI(i, 0, k-1) {
hash[part[0][i]] = 1;
}
REPI(i, 'a', 'z') {
if( !hash[i] ) {
continue;
}
f[1][i] = cost(0, '#', i);
}
REPI(i, 2, final) {
memset(hash, 0, sizeof(hash));
REPI(j, 0, k-1) {
hash[part[i-1][j]] = 1;
}
REPI(ch, 'a', 'z') {
if( !hash[ch] ) {
continue;
}
memset(hash1, 0, sizeof(hash1));
REPI(j, 0, k-1) {
hash1[part[i-2][j]] = 1;
}
REPI(chp, 'a', 'z') {
if( !hash1[chp] ) {
continue;
}
f[i][ch] = min(f[i][ch], f[i-1][chp]+cost(i-1, chp, ch));
}
}
}
int rst = INF;
REPI(i, 'a', 'z') {
rst = min(rst, f[final][i]);
}
return rst;
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int cas;
scanf("%d", &cas);
REPI(k, 1, cas) {
input();
printf("%d\n", process());
}
return 0;
}