Problem F
FEWEST FLOPS
A common way to uniquely encode a string is by replacing its consecutive repeating characters (or “chunks”) by the number of times the character occurs followed by the character itself. For example, the string “aabbbaabaaaa” may be encoded as “2a3b2a1b4a”. (Note for this problem even a single character “b” is replaced by “1b”.)
Suppose we have a string S and a number k such that k divides the length of S. Let S1 be the substring of S from 1 to k, S2 be the substring of S from k + 1 to 2k, and so on. We wish to rearrange the characters of each block Si independently so that the concatenation of those permutations S’ has as few chunks of the same character as possible. Output the fewest number of chunks.
For example, let S be “uuvuwwuv” and k be 4. Then S1 is “uuvu” and has three chunks, but may be rearranged to “uuuv” which has two chunks. Similarly, S2 may be rearranged to “vuww”. Then S’, or S1S2, is “uuuvvuww” which is 4 chunks, indeed the minimum number of chunks.
Program Input
The input begins with a line containing t (1 ≤ t ≤ 100), the number of test cases. The following t lines contain an integer k and a string S made of no more than 1000 lowercase English alphabet letters. It is guaranteed that k will divide the length of S.
Program Output
For each test case, output a single line containing the minimum number of chunks after we rearrange S as described above.
INPUT
2 5 helloworld 7 thefewestflops
OUTPUT
8
题意:给定一个字符串和一个k,保证字符串长度是k的倍数。没段是len/k,每段里面字符的位置可以调换,然后最后整个字符串字符全部相同的一段为一块,问转换之后最少有几块。
思路:dp+贪心,首先相同的字符肯定是放在一起最优,那么对于每段的字符串,只要考虑前后即可,因为只有前后才有组合的可能,所以定义dp[i][j]为第i块,和第i - 1块的最后字符为j,先预处理每一段的字母个数,那么状态转移为:如果当前开头字符可以等于j,那么块数相加少1,如果不可以等于,那么就不少1。
代码:
#include <stdio.h>
#include <string.h>
#define INF 0x3f3f3f3f
#define min(a,b) ((a)<(b)?(a):(b))
const int N = 1005;
int t, k, have[N][26], num[N], len, dp[N][26];
char str[N];
void init() {
len = strlen(str);
memset(have, 0, sizeof(have));
memset(num, 0, sizeof(num));
for (int i = 0; i < len; i += k) {
for (int j = i; j < i + k; j++) {
if (have[i][str[j] - 'a'] == 0)
num[i]++;
have[i][str[j] - 'a']++;
}
}
}
int solve() {
int ans = INF, i;
memset(dp, INF, sizeof(dp));
for (i = 0; i < 26; i++) {
if (have[0][i])
dp[0][i] = num[0];
if (len - k == 0)
ans = min(dp[0][i], ans);
}
for (i = k; i < len; i += k) {
for (int j = 0; j < 26; j++) {
if (have[i - k][j]) {
for (int kk = 0; kk < 26; kk++) {
if (!have[i][kk]) continue;
if (have[i][j] && (num[i] == 1 || j != kk))
dp[i][kk] = min(dp[i][kk], dp[i - k][j] + num[i] - 1);
else
dp[i][kk] = min(dp[i][kk], dp[i - k][j] + num[i]);
if (i == len - k) ans = min(dp[i][kk], ans);
}
}
}
}
return ans;
}
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d%s", &k, str);
init();
printf("%d\n", solve());
}
return 0;
}