题解:P12950 [GCJ Farewell Round #1] Untie
动态规划好题。
形式化题意
给一个字符串
状态设计
由于是一个一维字符串,并且每个字符仅与相邻的两个字符有关,于是想到线性动规。
常规地,需要有一维
转移方程
首先,因为两个相邻的字符不能相同,所以
那么就需要从另外两种字符转移:
另外,如果当前考虑的此字符与原字符串中字符不同(
最终还需要考虑第
Accepted Code
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
constexpr int INF = 0x3f3f3f3f;
constexpr int N = 1e3 + 5;
int T, len, idx;
string s;
inline void solve() {
cin >> s;
len = s.size();
int a[N] = {0};
for (int i = 0; i < len; ++i) {
if (s[i] == 'R') a[i] = 0;
else if (s[i] == 'P') a[i] = 1;
else a[i] = 2;
}
int ans = INF;
for (int first = 0; first < 3; ++ first) {
int dp[N][3];
memset(dp, 0x3f, sizeof(dp));
dp[0][first] = (first == a[0] ? 0 : 1);
for (int i = 1; i < len; ++ i) {
for (int c = 0; c < 3; ++ c) {
int cost = (c == a[i] ? 0 : 1);
for (int p = 0; p < 3; ++ p) {
if (p == c) continue;
dp[i][c] = min(dp[i][c], dp[i - 1][p] + cost);
}
}
}
for (int c = 0; c < 3; ++ c) {
if (c == first) continue;
ans = min(ans, dp[len - 1][c]);
}
}
printf("Case #%d: %d\n", ++ idx, ans);
}
int main() {
scanf("%d", &T);
while (T --) solve();
return 0;
}
求个赞