CF547E Mike and Friends [AC自动机,离线树状数组]

泪湿孤枕 提交于 2020-02-22 19:33:03
#include <cstdio>
#include <queue>
#include <vector>
#define pb emplace_back
using namespace std;

int read() {
  int x = 0;
  char c = getchar();
  while (c < 48) c = getchar();
  while (c > 47) x = x * 10 + (c - 48), c = getchar();
  return x;
}

const int maxn = 2e5 + 52;
const int maxq = 5e5 + 55;

int n, m, len = 0;
char s[maxn];
int fa[maxn], ch[maxn][26], fail[maxn], cnt = 1;
int ed[maxn];

void rs() {
  len = 0;
  char c = getchar();
  while (c == ' ' || c == '\n') c = getchar();
  while (c != ' ' && c != '\n') s[len++] = c, c = getchar();
}

int ins() {
  int p = 1;
  for (int i = 0; i < len; i++) {
    int c = s[i] - 'a';
    if (!ch[p][c]) ch[p][c] = ++cnt, fa[ch[p][c]] = p;
    p = ch[p][c];
  }
  return p;
}

std ::vector<int> g[maxn];
int sz[maxn], dfn[maxn], idx = 0;
void dfs(int u) {
  sz[u] = 1, dfn[u] = ++idx;
  for (int v : g[u]) dfs(v), sz[u] += sz[v];
}

using pii = pair<int, int>;
std ::vector<pii> que[maxn];

int c[maxn];
int low(int x) { return x & -x; }
void add(int x, int y) {
  for (; x <= cnt; x += low(x)) c[x] += y;
}
int qry(int x) {
  int ans = 0;
  for (; x; x ^= low(x)) ans += c[x];
  return ans;
}

int main() {
  // freopen("testdata.in", "r", stdin);
  n = read(), m = read();
  for (int i = 1; i <= n; i++) ed[i] = (rs(), ins());
  std ::queue<int> q;
  for (int i = 0; i < 26; i++)
    if (ch[1][i])
      fail[ch[1][i]] = 1, q.push(ch[1][i]);
    else
      ch[1][i] = 1;
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    for (int i = 0; i < 26; i++)
      if (ch[u][i])
        fail[ch[u][i]] = ch[fail[u]][i], q.push(ch[u][i]);
      else
        ch[u][i] = ch[fail[u]][i];
  }
  for (int i = 2; i <= cnt; i++) g[fail[i]].pb(i);
  dfs(1);

  std ::vector<int> ans(m + 1, 0);
  for (int i = 1; i <= m; i++) {
    int l = read(), r = read(), k = read();
    --l, que[l].pb(-i, k), que[r].pb(i, k);
  }

  for (int i = 1; i <= n; i++) {
    int x = ed[i];
    while (x) {
      add(dfn[x], 1);
      x = fa[x];
    }
    for (auto x : que[i]) {
      int sign = x.first > 0 ? 1 : -1, u = ed[x.second], id = x.first * sign;
      ans[id] += sign * (qry(dfn[u] + sz[u] - 1) - qry(dfn[u] - 1));
    }
  }

  for (int i = 1; i <= m; i++) printf("%d\n", ans[i]);
  return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!