解題報告 CodeForces - 1295C Obtain The String

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 zz into following strings in one operation:

  1. z=acace (if we choose subsequence ace);
  2. z=acbcd (if we choose subsequence bcd);
  3. 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\leq T\leq 100) — the number of test cases.

The first line of each testcase contains one string s (1\leq |s|\leq 10^{5}) consisting of lowercase Latin letters.

The second line of each testcase contains one string t (1\leq |t|\leq 10^{5}) 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\cdot 10^{5}.

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.

Example

Input

3
aabce
ace
abacaba
aax
ty
yyt

Output

1
-1
3

題意:

給定兩個字符串 s 和 t ,字符串 z 開始爲空字符串,每次操作可以在 s 中選一個子序列(區別於子串)拼接在 z 後邊,最終將z變爲 t 

輸入: T 組樣例,每組樣例有兩行,第一行爲字符串 s ,第二行爲字符串 t

輸出:空字符串 z 變爲 t 的最小步數

思路:

1.看到這道題我想起了dp的經典題目攔截導彈,於是自然而然的往dp的方向想了。(其實和攔截導彈沒啥關係)

2.dp[i][j]表示位置 i 及之後 j 最近一次出現的位置,如果恰好出現在位置 i 上則dp[i][j] = i ;否則dp[i][j] = dp[i+1][j]

3.按照字符串 t 中字母的順序逐個查找,pos指字符串 s 中選擇序列的位置,開始從 s 的第一位即下標爲0的位置開始查找,如果某個序列可以一次選中,則將pos移向 s 串中該字母最近一次出現的位置也就是剛剛處理好的dp數組;否則ans++進行下一次的序列選擇,pos移動回0

 

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define maxn 100005
#define mod 998244353
int ca,dp[maxn][35];
string s,t;

int main()
{
    cin>>ca;
    while(ca--)
    {
        cin>>s>>t;
        int ls=s.length();
        int lt=t.length();
        for(int i=0;i<26;i++)
        {
            dp[ls][i]=inf;
        }
        for(int i=ls-1;i>=0;i--)
        {
            for(int j=0;j<26;j++)
            {
                if(s[i]-'a'==j)dp[i][j]=i;
                else dp[i][j]=dp[i+1][j];
            }
        }
        int pos=0,ans=1;
		for(int i=0;i<lt;i++)
        {
            int tmp=t[i]-'a';
            if(dp[0][tmp]==inf)
            {
                ans=-1;
                break;
            }
            if(dp[pos][tmp]==inf)
            {
                pos=0;
                ans++;
            }
            pos=dp[pos][tmp]+1;
        }
        cout<<ans<<endl;
    }
    return 0;
}

 

 

發佈了10 篇原創文章 · 獲贊 1 · 訪問量 1218
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章