【BZOJ3940】【Usaco2015 Feb】Censoring

【题目链接】

【思路要点】

  • 对模式串的集合建立AC自动机,让主串在上面匹配,每遇到一个模式串的末尾便将其删去即可。
  • 时间复杂度 O ( | S | )

【代码】


#include<bits/stdc++.h>

using namespace std;
const int MAXN = 100005;
template <typename T> void chkmax(T &x, T y) {x = max(x, y); }
template <typename T> void chkmin(T &x, T y) {x = min(x, y); } 
template <typename T> void read(T &x) {
  x = 0; int f = 1;
  char c = getchar();
  for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
  for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
  x *= f;
}
template <typename T> void write(T x) {
  if (x < 0) x = -x, putchar('-');
  if (x > 9) write(x / 10);
  putchar(x % 10 + '0');
}
template <typename T> void writeln(T x) {
  write(x);
  puts("");
}
struct ACAutomaton {
  struct Node {
      int child[26];
      int fail, cnt;
  } a[MAXN];
  int root, size;
  void insert(char *s) {
      int now = root;
      int len = strlen(s + 1);
      for (int i = 1; i <= len; i++) {
          int tmp = s[i] - 'a';
          if (a[now].child[tmp] == 0) a[now].child[tmp] = ++size;
          now = a[now].child[tmp];
      }
      a[now].cnt = len;
  }
  void init() {
      static int q[MAXN];
      int l = 0, r = -1;
      for (int i = 0; i < 26; i++)
          if (a[root].child[i]) {
              q[++r] = a[root].child[i];
              a[a[root].child[i]].fail = root;
          }
      while (l <= r) {
          int tmp = q[l++];
          for (int i = 0; i < 26; i++)
              if (a[tmp].child[i]) {
                  q[++r] = a[tmp].child[i];
                  a[a[tmp].child[i]].fail = a[a[tmp].fail].child[i];
              } else a[tmp].child[i] = a[a[tmp].fail].child[i];
      }
  }
  void calc(char *s) {
      int len = strlen(s + 1);
      static int pos[MAXN];
      static char ans[MAXN];
      int anslen = 0;
      for (int i = 1; i <= len; i++) {
          int tmp = s[i] - 'a';
          anslen++;
          ans[anslen] = s[i];
          pos[anslen] = a[pos[anslen - 1]].child[tmp];
          anslen -= a[pos[anslen]].cnt;
      }
      for (int i = 1; i <= anslen; i++)
          printf("%c", ans[i]);
  }
} ACAM;
char s[MAXN], t[MAXN];
int main() {
  scanf("\n%s", s + 1);
  int n; read(n);
  for (int i = 1; i <= n; i++) {
      scanf("\n%s", t + 1);
      ACAM.insert(t);
  }
  ACAM.init();
  ACAM.calc(s);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39972971/article/details/80897368