Atcoder abc 138 E String of Impurity

1522713-20190819152329580-811025623.png
1522713-20190819152339776-615878134.png
1522713-20190819152347824-352533420.png

思路

這種類似的字符串匹配的問題,可以...

在s中記錄每個字符的出現次數和對應次數的出現位置,然後用t去一一對應

首先,設lop[x][i] 儲存 第i個x + 'a' 對應的字符在s中出現的位置,k代表t中我們要進行搜索的字符的位置

對於這道題,那就是記錄完每個字符的出現位置之後,就枚舉t串的每一個字符c,找出s中與c對應的第一個比c的位置大的位置,那麼 ans += lop[c][j] - k

相反的,如果s中沒有對應c比t中的c位置更大,也就是說,我們要再進行一個循環,這時, ans += lop[c][0] + n - k

自己畫個圖理解理解

代碼

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std ;
string s , t ;
long long sum = 0 ; 
vector<int>c[30] ;
int main () {
    cin >> s >> t ;
    int n = s.size() ;
    int m = t.size() ;
    for(int i = 0 ; i < s.size() ; i ++) {
        c[s[i]-'a'].push_back(i+1) ;
    }
    int x = t[0] - 'a' , j ;
    if(!c[x].size()) {
        puts("-1") ;
        return 0 ;
    }
    int k = c[x][0] ;
    sum += k ;
    for(int i = 1 ; i < m ; i ++) {
        x = t[i] - 'a' ;
        if(!c[x].size()) {
            puts("-1") ;
            return 0 ;
        }
        j = upper_bound(c[x].begin() ,c[x].end(),k) - c[x].begin() ;
        if(j == c[x].end()-c[x].begin() ) {
            sum += c[x][0] + n - k ;
            k = c[x][0] ;
        }else {
            sum += c[x][j] - k ;
            k = c[x][j] ;
        }
    }
    cout << sum <<endl ; 
    return 0 ;
}

在At上輸出long long 要用%lld!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章