题目链接:https://ac.nowcoder.com/acm/problem/21303
思路:删括号的时候一定要时刻保证左括号数量比右括号多,我们可以定义dp[i][j][k]表示考虑AA前i个匹配了B前j个A被删除部分左括号数-右括号数=k是否可行,
分类讨论转移即可,最后答案就是dp[n][m][0]。
#include <cstdio> #include <map> #include <iostream> #include<cstring> #include<bits/stdc++.h> #define ll long long int #define M 6 using namespace std; inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;} inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;} int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1}; int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1}; const int inf=0x3f3f3f3f; const ll mod=1e9+7; int dp[107][107][107]; int main(){ ios::sync_with_stdio(false); string s,t; cin>>s>>t; int lens=s.length(); int lent=t.length(); dp[0][0][0]=1; for(int i=0;i<lens;i++) for(int j=0;j<=lent;j++) for(int k=0;k<=lens;k++){ if(dp[i][j][k]){ if(!k&&s[i]==t[j]) dp[i+1][j+1][k]=1; if(s[i]=='(') dp[i+1][j][k+1]=1; else if(k) dp[i+1][j][k-1]=1; } } if(dp[lens][lent][0]) cout<<"Possible"<<endl; else cout<<"Impossible"<<endl; }