CF1295C Obtain The String

思路:

容易证明贪心性质。首先预处理得到一个二维表格a[i][j]表示从字符串s的i位置开始到结尾,其中第一次出现字符j的位置。然后贪心构造t即可。

实现:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 100005;
 4 int a[N][30];
 5 int main()
 6 {
 7     int n; cin >> n;
 8     while (n--)
 9     {
10         string s, t;
11         cin >> s >> t;
12         set<char> st{s.begin(), s.end()};
13         bool flg = true;
14         for (auto it: t)
15         {
16             if (!st.count(it)) { flg = false; break; }
17         }
18         if (!flg) { cout << -1 << endl; continue; }
19         int n = s.length(), m = t.length();
20         for (int i = 0; i < 26; i++) a[n][i] = -1;
21         for (int i = n - 1; i >= 0; i--)
22         {
23             for (int j = 0; j < 26; j++)
24             {
25                 a[i][j] = a[i + 1][j];
26             }
27             a[i][s[i] - 'a'] = i;
28         }
29         int cur = 0, p = 0, res = 0;
30         while (cur < m)
31         {
32             if (a[p][t[cur] - 'a'] == -1)
33             {
34                 p = a[0][t[cur] - 'a'] + 1;
35                 res++;
36             }
37             else p = a[p][t[cur] - 'a'] + 1;
38             cur++;
39         }
40         cout << res + 1 << endl;
41     }
42     return 0;
43 }

猜你喜欢

转载自www.cnblogs.com/wangyiming/p/12284082.html