CodeForces - 1303E Erase Subsequences(dp)
题目链接:点击查看
题目大意:给出一个字符串 s 和一个字符串 t ,问 t 能否由字符串 s 中两个不重复的子序列构成
题目分析:一开始以为是贪心去写,但写了半天发现过不去第一个样例,仔细思考了半天感觉是一个dp就放弃了,赛后看别人的代码补题,感觉是一个比较经典的dp
首先看完这个题目,字符串的长度最长只有400,显然需要用 n^3 的算法去解决,因为字符串 t 是要由字符串 s 中的两个子序列构成,所以我们很自然的用一层for去枚举字符串 t 的断点,将字符串 t 分为两个子串 t1 和 t2,剩下的我觉得可以贪心,但用dp似乎更简单一些,最朴素的dp是一个 n^3 的dp,稍微说一下就是 dp[ i ][ j ][ k ] ,代表着字符串 s 到了第 i 位,字符串 t1 到了第 j 位,字符串 t2 到了第 k 位时的状态是否存在,最后判断一下 dp[ len_s ][ len_t1 ][ len_t2 ] 是否为 1 即可,但显然如果dp是 n^3 的话总复杂度就到了 n^4 ,我们需要优化,因为这个dp的值只有 0 和 1 ,所以我们可以将其降到二维,随便删掉一维,令该dp的内容变为这一维就好了,我选择删去代表字符串 s 的这一维,这样 dp[ i ][ j ] 就变成了:字符串 t1 到了第 i 位,字符串 t2 到了第 j 位时,在字符串 s 中的最小位置,最后判断是否成立的条件也是 dp[ len_t1 ][ len_t2 ] 的值是否小于等于 len_s
比较简单的dp,转移和初始化就不多啰嗦了,直接看代码吧
代码:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<unordered_map> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=410;int nx[N][26],dp[N][N];string s,t;void get_next() {int n=s.size();for(int i=0;i<26;i++)nx[n][i]=nx[n+1][i]=n;for(int i=n-1;i>=0;i--){for(int j=0;j<26;j++)nx[i][j]=nx[i+1][j];nx[i][s[i]-'a']=i;} }bool solve(string a,string b) {dp[0][0]=-1;for(int i=0;i<=a.size();i++)for(int j=0;j<=b.size();j++){if(i==0&&j==0)continue;dp[i][j]=s.size();if(i)dp[i][j]=min(dp[i][j],nx[dp[i-1][j]+1][a[i-1]-'a']);if(j)dp[i][j]=min(dp[i][j],nx[dp[i][j-1]+1][b[j-1]-'a']);}return dp[a.size()][b.size()]<s.size(); }bool check() {for(int i=0;i<t.size();i++)//枚举断点if(solve(t.substr(0,i),t.substr(i)))return true;return false; }int main() { //#ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); //#endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--){cin>>s>>t;get_next();if(check())puts("YES");elseputs("NO");}return 0; }超强干货来袭 云风专访:近40年码龄,通宵达旦的技术人生
总结
以上是生活随笔为你收集整理的CodeForces - 1303E Erase Subsequences(dp)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: CodeForces - 1303D F
- 下一篇: CodeForces - 1301D T