【Educational Codeforces Round 81 (Rated for Div. 2) C】Obtain The String


題目鏈接

【題解】

顯然我們得按順序獲得目標t的每個字符。 對於t[0],t[1],t[2],t[3]... 我們可以在s中找到這么一個子序列。 顯然如果找到尾巴還是沒有需要的t[i]。 就得從s[0]開始重新開始順序找。 (然后答案遞增,因為表示要重新開始加一個子序列了) 但是如果這么直接找的話,復雜度是O(|s|*|t|)的 是無法接受的。 所以我們可以另外開一個數組 next[i][j] 表示在i-1位置,如果要找下一個緊接着的j的話,需要到哪個位置找。(這個next數組整體往左偏移了下,便於處理,因為不能包括本身,它的含義是不包括自己的下一個) 這個數組能在O(26*|s|)的時間復雜度內處理出來。 這樣,在遍歷t的每個字符的時候,就能在O(1)的時間內找到t[i]在s中的位置了。 所以算答案的時候復雜度是O(|t|)級別。

【代碼】

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

const int N = 1e5;

int n,x;
string s;
string t;
int _next[N+10][30];

int main(){
    #ifdef LOCAL_DEFINE
        freopen("E:\\rush.txt","r",stdin);
    #endif // LOCAL_DEFINE
    ios::sync_with_stdio(0),cin.tie(0);
    int T;
    cin >> T;
    while (T--){
        cin >> s;
        cin >> t;
        int len = s.size();
        for (int i = 0;i<26;i++) _next[len][i] = -1;
        for (int i = len-1;i>=0;i--){
            for (int j = 0;j < 26;j++) _next[i][j] = _next[i+1][j];
            int key = s[i]-'a';
            _next[i][key] = i+1;
        }
        //cout<<_next[0][0]<<endl;
        len = t.size();
        int ans = 1;
        int cur = 0;
        bool ok = true;
        for (int i = 0;i < len;i++){
            int kk = t[i]-'a';
            if (_next[cur][kk]!=-1){
                cur = _next[cur][kk];
            }else{
                ans++;
                cur = 0;
                if (_next[0][kk]==-1){
                    ok = false;
                    break;
                }
                cur = _next[cur][kk];
            }
            //cout<<cur<<endl;
        }
        if (!ok) cout<<-1<<endl;else
        cout<<ans<<endl;
    }
    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM