1 条题解

  • 0
    @ 2026-7-18 23:01:35

    更好的阅读体验

    link

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

    讲细一点。

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

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

    #include <bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    const int N = 1e5 + 10;
    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;
    }
    
    • 1

    信息

    ID
    11729
    时间
    2000ms
    内存
    1024MiB
    难度
    10
    标签
    递交数
    3
    已通过
    1
    上传者