题解:P13186 [GCJ 2016 Qualification] Revenge of the Pancakes
Zjb_nhzx_2021 · · 题解
P13186 Revenge of the Pancakes 题解
题目传送门
先看题目:
题目给我们一个字符串(只包括+或-),让我们做如下改动:
- 从字符串顶取出若干字符(可能全部),将这一组整体翻转(
+\gets -、-\gets +),然后再放回剩下的字符串上方。 - 注意:翻动一组字符时,整个组会被整体翻转,而不是单独翻转每一个。
- 最后要用最少的步数使整个字符串全部变成
+。解题思路:
看起来简单,想起来难,想出来又简单\ 从下往上(也就是从右往左)遍历字符串,如果当前字符S_i 为-就从字符串顶取出i 个字符进行翻转。示例过程如下表:
| 层数\改动次数 | 0(原串) | 1 | 2 |
|---|---|---|---|
| 1 | + |
- |
+ |
| 2 | + |
- |
+ |
| 3 | - |
+ |
+ |
| 4 | - |
+ |
+ |
| 5 | + |
+ |
+ |
AC Code:
#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;
}