Obtain The String(二分)

You are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation:

z=acacez=acace (if we choose subsequence aceace);
z=acbcdz=acbcd (if we choose subsequence bcdbcd);
z=acbcez=acbce (if we choose subsequence bcebce).
Note that after this operation string ss doesn’t change.

Calculate the minimum number of such operations to turn string zz into string tt.

Input
The first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.

The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.

The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.

It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.

Output
For each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it’s impossible print −1−1.

Example
Input
3
aabce
ace
abacaba
aax
ty
yyt
Output
1
-1
3
思路:因为要使操作次数尽可能少,所以我们要对每个字母,贪心的取位置在前面的。
一共有26个字母,所以数据量很小。每次我们用upper_bound找出符合条件的最前面的那个,一直这么找下去。只要从头来一遍,ans++。
代码如下:

#include<bits/stdc++.h>
#define ll long long
using namespace std;

string s,t;
vector<int> p[30];

inline void dfs(int &i,int &num)
{
	if(i==t.length()) return ;
	if(p[t[i]-'a'].size()==0)
	{
		i=-1;
		return ;
	}
	int pos=upper_bound(p[t[i]-'a'].begin(),p[t[i]-'a'].end(),num)-p[t[i]-'a'].begin();
	if(pos==p[t[i]-'a'].size()) return ;
	num=p[t[i]-'a'][pos];
	dfs(i+=1,num);
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		for(int i=0;i<30;i++) p[i].clear();
		cin>>s>>t;
		int len=s.length();
		for(int i=0;i<len;i++) p[s[i]-'a'].push_back(i);
		int ans=0;
		len=t.length();
		int pos=p[t[0]-'a'][0];
		if(p[t[0]-'a'].size()==0) 
		{
			cout<<"-1"<<endl;
			continue;
		}
		for(int i=0;i<len;)
		{
			if(p[t[i]-'a'].size()==0) 
			{
				cout<<"-1"<<endl;
				break;
			}
			pos=p[t[i]-'a'][0];
			i++;
			ans++;
			dfs(i,pos);
			if(i==-1)
			{
				cout<<"-1"<<endl;
				break;
			}
			else if(i==len) cout<<ans<<endl;
		}
	}
}

努力加油a啊,(o)/~

发布了414 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/starlet_kiss/article/details/104159754