跳到正文

题解

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

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

文章信息

收录
2025年12月12日
更新
2026年4月25日
篇幅
约 2 分钟
获赞
1
题目
P13186

版本

  1. v1当前

P13186 Revenge of the Pancakes 题解

题目传送门

先看题目:

题目给我们一个字符串(只包括+或-),让我们做如下改动:

  • 从字符串顶取出若干字符(可能全部),将这一组整体翻转(+←\gets-、-←\gets+),然后再放回剩下的字符串上方。
  • 注意:翻动一组字符时,整个组会被整体翻转,而不是单独翻转每一个。
  • 最后要用最少的步数使整个字符串全部变成+。

解题思路:

看起来简单,想起来难,想出来又简单
从下往上(也就是从右往左)遍历字符串,如果当前字符为-就翻转这个字符和它左边的所有字符。示例过程如下表:

层数\改动次数0(原串)12
1+-+
2+-+
3-++
4-++
5+++

AC Coad:

C++
#include<bits/stdc++.h>
using namespace std;
string s;
int t;
void turn(int n){//翻转函数
    for(int j=n;j>=0;j--)
        s[j]=(s[j]=='-')?'+':'-';
}
int main(){
    cin>>t;
    for(int cl=1;cl<=t;cl++){
        int ans=0;
        cin>>s;
        for(int i=s.size();i>=0;i--){//倒序遍历
            if(s[i]=='-'){
                ans++;
                turn(i);
            }
        }
        printf("Case #%d: %d\n",cl,ans);
    }
    return 0;
}
原文