CF 1295C Obtain The String

4 篇文章 0 订阅

题目链接: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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逃夭丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值