B 拼凑

基本思路:

https://ac.nowcoder.com/acm/contest/7509/B

参考代码:

可以考虑从后往前建序列自动机,
也就是记录离每个位置往后最近的每个字母的位置,
然后从每个出发,往后依次去匹配模式串就行了,
在匹配完成的情况下得到子串长,然后取最小子串长为答案。

参考代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false); cin.tie(0)
#define int long long
#define ull unsigned long long
#define SZ(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF 0x3f3f3f3f

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}

const int maxn = 1e5 + 10;
string mark = "puleyaknoi";
string str;
int n,nxt[maxn][26];
signed main() {
  IO;
  int t;
  cin >> t;
  while (t--) {
    cin >> str;
    n = SZ(str);
    str = ' ' + str;
    mset(nxt, 0);
    for (int i = 0; i < 26; i++) nxt[n + 1][i] = -1;
    for (int i = n; i >= 1; i--) {
      for (int j = 0; j < 26; j++) nxt[i][j] = nxt[i + 1][j];
      nxt[i][str[i] - 'a'] = i;
    }
    int ans = INF;
    for (int i = 1; i <= n; i++) {
      if (str[i] == mark[0]) {
        int pos = 0, now = nxt[i][mark[pos++] - 'a'];
        while (now != -1 && pos < 10) {
          now = nxt[now][mark[pos++] - 'a'];
        }
        if (now != -1 && pos == 10) ans = min(ans, now - i + 1);
      }
    }
    if (ans == INF) cout << -1 << '\n';
    else cout << ans << '\n';
  }
  return 0;
}