跳到正文

题解

题解:P12950 [GCJ Farewell Round #1] Untie

Orange714约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月11日
收录
2025年12月12日
更新
2026年9月19日
篇幅
约 3 分钟
获赞
2
题目
P12950

版本

  1. v1当前

动态规划好题。

形式化题意

给一个字符串 ss,首尾相连形成一个环,由 RR,PP,SS 三种字符组成。现在要使 ss 中没有任意两个相邻的字符相同,至少要改变几个字符?

状态设计

由于是一个一维字符串,并且每个字符仅与相邻的两个字符有关,于是想到线性动规。

常规地,需要有一维 ii,表示考虑到了第 ii 个字符。考虑到此字符需要与左右两个字符不同,并且仅有 33 种不同的字符,所以想到设计第二维 jj 取 [0,2][0, 2],分别表示 33 种不同的字符。

转移方程

首先,因为两个相邻的字符不能相同,所以 dpi,jdp_{i, j} 不能从 dpi−1,jdp_{i - 1, j} 转移。

那么就需要从另外两种字符转移:

dpi,j=min0≤k≤2,k≠j{dpi−1,k}dp_{i, j} = min_{0 \le k \le 2, k\not=j}\{dp_{i - 1, k}\}

另外,如果当前考虑的此字符与原字符串中字符不同(j≠s[i]j \not= s[i]),代表需要改变此字符,所以需要加一。

最终还需要考虑第 nn 个字符与第 11 个字符间的关系,复制第 11 个字符到字符串尾即可。

Accepted Code

C++
#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;
}

求个赞

原文