CodeForces - 1295C Obtain The String(dp预处理+贪心)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1295C Obtain The String(dp预处理+贪心)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個字符串 s 和一個字符串 t ,再給出一個字符串 z ,初始時字符串 z 為空串,現在需要利用規則構造字符串 z ,使得 z == t ,規則就是每次可以挑選字符串?s 的任意子序列添加到字符串 z 后面,代價是一次操作數,問如何才能操作數最少,如果不能完成構造,輸出 -1
題目分析:先dp預處理一波,然后直接貪心找就行了,dp預處理主要是用二維dp [ i ] [ j ],代表的是包含第 i 個位置在內,后面第一次出現字母 j 的位置,貪心的時候如果想要找某個字母 ch ,當然是在字符串 s 中的位置越靠前越好了
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<queue> #include<map> #include<set> #include<sstream> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=1e5+100;int dp[N][30];//dp[i][j]:包含第 i 個位置在內,后面第一次出現字母 j 的位置char s[N],t[N]; int main() { // freopen("input.txt","r",stdin); // ios::sync_with_stdio(false);int w;cin>>w;while(w--){scanf("%s%s",s+1,t+1);int len1=strlen(s+1),len2=strlen(t+1);for(int i=0;i<26;i++)dp[len1+1][i]=inf;for(int i=len1;i>=0;i--){for(int j=0;j<26;j++)dp[i][j]=dp[i+1][j];if(i==0)break;int pos=s[i]-'a';dp[i][pos]=i;}int ans=1,cur=0;for(int i=1;i<=len2;i++){int to=t[i]-'a';if(dp[0][to]==inf){ans=-1;break;}if(dp[cur][to]==inf){cur=0;ans++;}cur=dp[cur][to]+1;}printf("%d\n",ans);}return 0; }?
總結
以上是生活随笔為你收集整理的CodeForces - 1295C Obtain The String(dp预处理+贪心)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1295B I
- 下一篇: CodeForces - 1295D S