CodeForces - 1295C Obtain The String (dp + pretreatment greedy)

Topic links: Click here

Title effect: Given a string s and a string t, then z is given a string, the string z is initially empty string, now need to use the configuration rule string z, such that z == t, each rule is times can pick any string s sequence Z added to the string, the cost of a number of operations, how to ask the least number of operations, if not complete the construction, output -1

Topic Analysis: The first wave of pre-dp, greedy and then directly find on the list, mainly two-dimensional pre-dp dp [i] [j], is to include representatives of the i-th position into account, after the first letter appears first j position, when greedy if you want to find a letter ch, of course, is the position in the string s in front of the more the better

Code:

#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;
}

 

Published 577 original articles · won praise 18 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_45458915/article/details/104111797
Recommended