其实这题算动态规划有点牵强,因为它最大的难点和突破点在于把问题进行转化。我的做法是,先数出字符串的总数total和'A'的数目anum,然后只要在字符串中找出长度为anum的连续一段,它的'A'数最多就行了(假设是maxnum,则最后结果就是anum-maxnum)。找这个包含最多'A'的段才用到动态规划,其实挺简单的,就是循环一次记录从每个点起始往右长度为anum的段中'a'的数目即可。
/* * hdu3819/win.cpp * Created on: 2012-10-29 * Author : ben */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <iostream> #include <algorithm> #include <queue> #include <set> #include <map> #include <stack> #include <string> #include <vector> #include <deque> #include <list> #include <functional> #include <numeric> #include <cctype> using namespace std; const int MAXN = 100005; char str[MAXN]; int anum, total, ans[MAXN]; int main() { #ifndef ONLINE_JUDGE freopen("data.in", "r", stdin); #endif int T; scanf("%d", &T); getchar(); for(int t = 1; t <= T; t++) { printf("Case %d: ", t); gets(str); total = strlen(str); anum = count(str, str + total, 'A'); if(anum <= 1) { puts("0"); continue; } fill(ans, ans + MAXN, 0); ans[0] = count(str, str + anum, 'A'); for(int i = 1; i < total; i++) { ans[i] = ans[i - 1]; if(str[i - 1] == 'A') { ans[i]--; } if(str[(i + anum - 1) % total] == 'A') { ans[i]++; } } int result = *max_element(ans, ans + total); printf("%d\n", anum - result); // printf("anum = %d, total = %d\n", anum, total); } return 0; }