[UOJ #31]【UR #2】猪猪侠再战括号序列
题目大意:给你一个长度为$2n$的括号序列,保证$n$个`(`,$n$个`)`。要求输出一种可行方案,通过小于等于$n$的步数,每次交换区间$[x_i,y_i]$(立即交换),使得最后括号序列合法
题解:找到第一个`)`和最后一个`(`,交换
卡点:看成读入后一起交换
C++ Code:
#include <cstdio>
#include <algorithm>
#include <cstring>
struct _ {
int id;
char need;
} x, y;
char s[100010 << 1];
int n, m;
int ans[100010][2], tmp[2];
int main() {
scanf("%s", s);
n = strlen(s);
x = (_) {0, ')'};
y = (_) {n - 1, '('};
tmp[1] = 0, tmp[0] = n - 1;
int now = 1;
while (x.id < y.id) {
while (s[x.id] != x.need && x.id < y.id) x.id++, tmp[now] += now == 1 ? 1 : -1;
while (s[y.id] != y.need && x.id < y.id) y.id--, tmp[now ^ 1] += now == 1 ? -1 : 1;
if (x.id >= y.id) break;
ans[m][0] = tmp[now], ans[m][1] = tmp[now ^ 1];
if (ans[m][0] > ans[m][1]) std::swap(ans[m][0], ans[m][1]);
m++;
std::swap(x.need, y.need);
now ^= 1;
}
printf("%d\n", m);
for (int i = 0; i < m; i++) printf("%d %d\n", ans[i][0] + 1, ans[i][1] + 1);
}

浙公网安备 33010602011771号