题解:P13677 [GCPC 2023] Loop Invariant
Money_and_money · · 题解
这是我的第一篇题解,给个通过吧!
理解题意:
我们输入一个字符串,需要通过分割字符串使其能成为新的平衡的串并与原来的不同。
解题思路:
我们需要寻找最小序列,使其括号刚好配对。我们需要找到第一个平衡序列,将原序列从长度
代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.size();
int cnt = 0; //计算括号数量,帮助我们找到序列
int d = 0; // 第一个平衡字符串的长度就是这个
for (int i = 0; i < n; i++) {
if (s[i] == '(') {
cnt++;
} else {
cnt--;
}
// 当计数器为0时,说明平衡,找到了
if (cnt == 0) {
d = i + 1;
break;
}
}
// 是否可以找到平衡序列?这里需要仔细判断
//一、无法分割
//二、计算新序列并判断
if (d == n) {
cout << "no" << endl;
} else {
// 计算序列
string t = s.substr(d) + s.substr(0, d);
if (t == s) {
cout << "no" << endl;
} else { //成功
cout << t << endl;
}
}
return 0;
}
完美AC:
AC Record