Codeforces 1303E. Erase Subsequences 代码(dp 字符串压缩一维状态优化)

https://codeforces.com/contest/1303/problem/E

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn = 405;
 4 int dp[maxn][maxn];
 5 bool check(string s,string t){
 6     int indx = 0;
 7     for(int i = 0;i<s.length();i++){
 8         if(t[indx] == s[i]) indx++;
 9     }
10     if(indx == t.length()) return true;
11     return false;
12 }
13 bool check(string s,string t1,string t2){
14     memset(dp,-1,sizeof(dp));
15     dp[0][0] = 0;
16     for(int i = 0;i<s.length();i++){
17         for(int j = 0;j<=t1.size();j++){
18             if(dp[i][j]<0) continue;
19             if(j<t1.size() && s[i] == t1[j]){
20                 dp[i+1][j+1] = max(dp[i+1][j+1],dp[i][j]);
21             }
22             if(dp[i][j]<t2.size() && s[i] == t2[dp[i][j]]){
23                 dp[i+1][j] = max(dp[i+1][j],dp[i][j]+1);
24             }
25             dp[i+1][j] = max(dp[i+1][j],dp[i][j]);
26         }
27     }
28     if(dp[s.length()][t1.length()] == t2.length()) return true;
29     return false;
30 }
31 void solve(){
32     string s,t;
33     cin>>s>>t;
34     if(check(s,t)){
35         cout<<"YES"<<endl;
36         return;
37     }
38     for(int i = 0;i<t.length()-1;i++){
39         string t1 = t.substr(0,i+1);
40         string t2 = t.substr(i+1,t.size());
41         if(check(s,t1,t2)){
42             cout<<"YES"<<endl;
43             return;
44         }
45     }
46     cout<<"NO"<<endl;
47     return;
48 }
49 int main(){
50     int t;
51     cin>>t;
52     while(t--){
53         solve();
54     }
55     return 0;
56 }
View Code

猜你喜欢

转载自www.cnblogs.com/AaronChang/p/12357832.html