【BZOJ3940】【Usaco2015 Feb】Censoring

本文介绍了如何利用AC自动机解决Usaco2015 Feb竞赛中的Censoring题目,通过建立AC自动机并进行匹配,实现对模式串的删除操作,达到O(∑|S|)的时间复杂度。
摘要由CSDN通过智能技术生成

【题目链接】

【思路要点】

  • 对模式串的集合建立AC自动机,让主串在上面匹配,每遇到一个模式串的末尾便将其删去即可。
  • 时间复杂度 O(|S|) 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值