E「水」悠悠碧波

题目地址:

https://ac.nowcoder.com/acm/contest/6226/E

基本思路:

看到前缀后缀就应该能想到算法,我们先求一次数组,然后直接从最后位置类似匹配失败过程往前找每次匹配的前缀作为模式串,然后每次再跑一遍看整段串中是否出现过三次以上的模式串就是了。

参考代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#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 (int)1e18

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');
}

namespace KMP {
    vector<int> next;

    void build(const string &pattern) {
      int n = pattern.length();
      next.resize(n + 1);
      for (int i = 0, j = next[0] = -1; i < n; next[++i] = ++j) {
        while (~j && pattern[j] != pattern[i]) j = next[j];
      }
    }

    vector<int> match(const string &pattern, const string &text) {
      vector<int> res;
      int n = pattern.length(), m = text.length();
      build(pattern);
      for (int i = 0, j = 0; i < m; ++i) {
        while (j > 0 && text[i] != pattern[j]) j = next[j];
        if (text[i] == pattern[j]) ++j;
        if (j == n) res.push_back(i - n + 1), j = next[j];
      }
      return res;
    }
};

string s,t;
signed main() {
  IO;
  cin >> s;
  KMP::build(s);
  vector<int> nxt = KMP::next;
  int sz =nxt.size();
  int tmp = nxt[sz - 1];
  while (tmp != -1){
    t.clear();
    for(int i = 0 ; i < tmp ; i++) t += s[i];
    vector<int> vec = KMP::match(t,s);
    if(vec.size() >= 3) break;
    tmp = nxt[tmp];
  }
  cout << t << '\n';
  return 0;
}