CodeForces 1295C Obtain The String
字符串DP预处理
题目内容
You are given two strings s and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. 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=ac, s=abcde, you may turn z into following strings in one operation:
z=acace (if we choose subsequence ace);
z=acbcd (if we choose subsequence bcd);
z=acbce (if we choose subsequence bce).
Note that after this operation string s doesn’t change.
Calculate the minimum number of such operations to turn string z into string t.
输入
The first line contains the integer T (1≤T≤100) — the number of test cases.
The first line of each testcase contains one string s (1≤|s|≤105) consisting of lowercase Latin letters.
The second line of each testcase contains one string t (1≤|t|≤105) consisting of lowercase Latin letters.
It is guaranteed that the total length of all strings s and t in the input does not exceed 2⋅105.
输出
For each testcase, print one integer — the minimum number of operations to turn string z into string t. If it’s impossible print −1.
样例输入
3
aabce
ace
abacaba
aax
ty
yyt
样例输出
1
-1
3
解题思路
按照题目数据规模,直接暴力模拟肯定超时,果然第4个点就TLE了。因此这道题目肯定得想一些方法在匹配之前进行预处理。
这里使用一vector存取字符串s中每个字母出现的位置,便于后面构造字符串t时进行位置跳转。
如果t中有s中没有的字母,则不可能完成,输出-1。
用ans记录答案,pos记录当前构造到的位置,如果当前位置后面有当前需要的字母,则向后跳转;否则答案次数加1,从s的首部重新开始找需要的字母。
另外找到pos之后最靠前的位置,需要用到upper_bound进行二分查找,否则直接从头查找也会超时。
A题不容易啊。
AC代码:
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int t;
cin>>t;
while(t--)
{
vector<int> vec[26];
int size[26]={0};
string s,t;
cin>>s>>t;
int len1=s.length(),len2=t.length();
for(int i=0;i<len1;i++)
{
vec[s[i]-'a'].push_back(i);
size[s[i]-'a']++;
}//将s中字母存入vec,每个字母数量存入size
int flag=0;
for(int i=0;i<len2;i++)
if(size[t[i]-'a']==0)
{
flag=1;
break;
}
if(flag==1)
{
cout<<"-1"<<endl;
continue;
}//如果t中有s中没有的字母,则不可能完成
int ans=1,pos=-1;
for(int i=0;i<len2;i++)
{
int ch=t[i]-'a';
if(pos<vec[ch][size[ch]-1])
{
/*for(int j=0;j<=size[ch]-1;j++)
if(vec[ch][j]>pos)
{
pos=vec[ch][j];
break;
}*///超时,要用二分查找
int j=upper_bound(vec[ch].begin(),vec[ch].end(),pos)-vec[ch].begin();
pos=vec[ch][j];
}//如果当前位置后面有当前需要的字母
else
{
ans++;
pos=vec[ch][0];
}//否则次数加1,从s的首部重新开始
}
cout<<ans<<endl;
}
return 0;
}