题解:P13022 [GCJ 2021 Qualification] Moons and Umbrellas

· · 题解

题意概述

给定字符串 S,包含 \texttt{C},\texttt{J},\texttt{?}。可以将 \texttt{?} 改为 \texttt{C} 或 \texttt{J}。出现 \texttt{CJ} 费用 x 元,出现 \texttt{JC} 费用 y 元。求最小费用。

分析

可以设计 DP 来解决。

状态

代码

#include<bits/stdc++.h>
using namespace std;
int t;
int f[1010][2]; 
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin >> t;
    for(int i = 1;i <= t;i++){
        memset(f,0x3f,sizeof f);
        cout << "Case #" << i << ": ";
        int x,y;
        char s[1010];
        cin >> x >> y;
        cin >> s+1;
        int len = strlen(s+1);
        if(s[1]=='C'){
            f[1][0] = 0;
        }
        else if(s[1]=='J'){
            f[1][1] = 0;
        }
        else{
            f[1][0] = 0;
            f[1][1] = 0;
        }
        for(int i = 2;i <= len;i++){
            if(s[i]=='C'){
                f[i][0] = min(f[i-1][1]+y,f[i-1][0]);
            }
            else if(s[i]=='J'){
                f[i][1] = min(f[i-1][0]+x,f[i-1][1]);
            }
            else{
                f[i][0] = min(f[i-1][0],f[i-1][1]+y);
                f[i][1] = min(f[i-1][0]+x,f[i-1][1]);
            }
        }
        cout << min(f[len][0],f[len][1]);
        cout << '\n'; 
    }
    return 0;
}