删括号
给出两个括号序列 \(s,t\),
问可以对 \(s\) 删去任意次 "()",
问是否可以把 \(s\) 变为 \(t\).
\(dp_{i,j}\) 表示 \(s\) 的前 \(i\) 个括号可以删为 \(t\) 的前 \(j\) 个字符.
代码
| C++ |
|---|
| #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
int __OneWan_2024 = [](){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
return 0;
}();
bool dp[105][105];
int main() {
string s, t;
cin >> s >> t;
s = " " + s;
t = " " + t;
dp[0][0] = true;
int n = s.size(), m = t.size();
int cnt = 0;
for (int i = 1 ; i <= n ; i++) {
if (s[i] == '(') {
cnt++;
} else {
cnt--;
}
if (cnt == 0) {
dp[i][0] = true;
}
if (cnt < 0) {
break;
}
}
for (int i = 1 ; i <= n ; i++) {
for (int j = 1 ; j <= m ; j++) {
if (s[i] == t[j]) {
dp[i][j] = dp[i - 1][j - 1];
}
int cnt = 0, k = i;
while (k >= 1) {
if (s[k] == '(') {
cnt--;
} else {
cnt++;
}
k--;
if (cnt <= 0) {
break;
}
}
if (cnt == 0) {
if (dp[k][j]) {
dp[i][j] = true;
}
}
}
}
cout << (dp[n][m] ? "Possible" : "Impossible");
return 0;
}
|