题目链接:https://codeforces.com/problemset/problem/1295/C
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.
Input
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.
Output
For each testcase, print one integer — the minimum number of operations to turn string z into string t. If it’s impossible print −1.
Example
input
3
aabce
ace
abacaba
aax
ty
yyt
output
1
-1
3
题意
给定两个字符串 s 和 t,一个空字符串z
每次可以取 s 的任意一个子序列加到 z 后面
问至少要取多少次才能让 z 等价于 t
思路
取的是 s 的子序列,其实就是问你 字符串 t 有多少个字符串 s 的子序列组成
子序列只需保证位置的递增性即可,不用考虑是否相邻
题目要求只是小写字母,所以我们分别保存这26个字母出现的位置
然后依次匹配字符串 t 中字符在 s 中的位置 如果可以服从递增,那就说明是一条子序列
不服从,就说明是另一条。
保证最优性,t 中字符应该在满足递增性的情况下,优先匹配 s 中最早出现的位置,
所以就 二分。
对了,输出 -1 的情况,就是 t 中存在 s 中没有的小写字母,可以开一个 nmb数组 记录每个小写字母出现的次数
暴力模拟,应该会 TL
#include<bits/stdc++.h>
using namespace std;
int main() {
int T;
cin>>T;
while(T--){
vector<int> v[30];
int num[30]={0};
string s,t;
cin>>s>>t;
for(int i = 0;i<s.length();i++){
v[s[i]-'a'].push_back(i);
++num[s[i]-'a'];
}
int ans = 1;
int p = -1;
for(int i = 0;i<t.length();i++){
if(!num[t[i]-'a']){
ans = -1;
break;
}
else if(p>=v[t[i]-'a'][num[t[i]-'a']-1]){
++ans;
p = v[t[i] - 'a'][0];
}
else
p = v[t[i]-'a'][upper_bound(v[t[i]-'a'].begin(),v[t[i]-'a'].end(),p)-v[t[i]-'a'].begin()];
}
cout<<ans<<endl;
}
return 0;
}