跳到正文

题解

题解:P13186 [GCJ 2016 Qualification] Revenge of the Pancakes

likj123约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年7月25日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 2 分钟
题目
P13186

版本

  1. v1当前

这是一道比较简单的贪心,就是让我们把饼全部变成 + 就可以了。我们可以从饼的底部开始检查每个饼的状态,因为翻转会影响顶部连续的饼,所以从底部开始可以确保每次翻转后,下方的煎饼状态不会被后续破坏。至于反转,直接用一个变量就可以了,先定义一个 char 类型的变量 bing⁡\operatorname{bing} 把它赋值为 + 之后从下往上检查,如果当前状态和 bing⁡\operatorname{bing} 不符,就反转,bing⁡\operatorname{bing} 也取反(+ 变 - 或者 - 变 +),因为翻转会改变上方所有煎饼的状态。

AC 代码

C++
#include <bits/stdc++.h>
using namespace std;
int main() {
    int tt; 
    cin >> tt;
    for (int t = 1; t <= tt; ++t) {
        string s; 
        cin >> s; 
        int n = s.size(); // 饼的高度
        int cnt = 0; // 初始化
        char bing = '+'; // 初始化
        for (int i = n - 1; i >= 0; i--) {
            if (s[i] != bing) {
                cnt++; // 需要执行一次翻转操作
                bing = bing == '+' ? '-' : '+'; // 切换目标状态
            }
        }
        cout << "Case #" << t << ": " << cnt << '\n';
    }
    return 0; 
}
原文