本蒟蒻表示,这题超级无敌究极简单
题目大意:
给你一个由‘+’和‘-’组成的字符串,并选定一个数k,将下标为1到k的数字的方向和符号翻转(方向翻转是指该组的前后顺序翻转),最后求出将数组全部变成‘+’的最小翻转数。
做法:
给你一个样例:+—++-
- 将开头的+翻转,变成---++-
- 将开头的3个-翻转,变成+++++-
- 将开头的5个+翻转,变成------
- 将所有-翻转,变成++++++
可以发现此时的最小翻转数就是它的连续+或连续-的字段数量和。
当然,如果末尾是+号, 那么最后一步就不用了,还要减1。
最后,上代码:
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
for (int x = 1; x <= t; x++) {
string s;
int ans = 0;
cin >> s;
for (int i = 0; i < s.size(); i++) {
if (i != 0&&s[i] != s[i - 1]) ans++;
}
ans++;
if (s[s.size() - 1] == '+') ans--;
printf("Case #%d: %d\n", x, ans);
}
return 0;
}