Strings of Impurity

· · 题解

更好的阅读体验

link

不懂为什么都写平衡树,明明 set 就好了啊,思路跟平衡树差不多,实现起来较为简单。

讲细一点。

一个显然的贪心策略是不断的选当前第一个能选的,不能选了就重置。

用一个 set 记录每个字母出现的位置就好。

int n, m, k;
int s[N];
string s1, s2;
int cnt[N];
vector<int> t;
set<int> p[N];
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> s1 >> s2;
    n = s1.size(), m = s2.size();
    s1 = " " + s1, s2 = " " + s2;
    for(int i = 1; i <= n; i ++) {
        s[i] = s1[i] - 'a';
        cnt[s[i]] ++;
        p[s[i]].insert(i);
    }
    for(int i = 1; i <= m; i ++) {
        int x = s2[i] - 'a';
        if(cnt[x]) t.push_back(x);
    }
    if(t.size() != m) {
        cout << -1 << '\n';
        return 0;
    }
    int cur = 0, now = -1;
    k = 1;
    while(cur < t.size()) {
        auto it = p[t[cur]].lower_bound(now + 1);
        if(it == p[t[cur]].end()) {
            now = -1;
            k ++;
            continue;
        }
        cur ++;
        now = *it;
    }
    cout << (LL)(k - 1) * n + now << '\n';
    return 0;
}