洛谷 P2922 / bzoj1590【Trie】

#include <bits/stdc++.h>

using namespace std;

const int N = 1e6 + 10;
struct Node
{
  int next[2];
  Node ()
  {
    memset (next, 0, sizeof next);
  }
} z[N];
int ans[N], cnt[N], nd, cnt2[N];
vector <int> a[N], b[N];

void cls()
{
  nd = 0;
  for (int i = 0; i < N; i ++)
    z[i] = Node();
  memset (cnt, 0, sizeof cnt);
}

void insert(vector <int> &a)
{
  int len = a.size(), now = 0;
  for (int i = 0; i < len; i ++)
  {
    if (!z[now].next[a[i]])
      z[now].next[a[i]] = ++ nd, now = nd;
    else
      now = z[now].next[a[i]];
    cnt2[now] ++;
  }
  cnt[now] ++;
}

int query(vector <int> &a)
{
  int len = a.size(), now = 0, ans = 0;
  for (int i = 0; i < len; i ++)
  {
    if (!z[now].next[a[i]])
      return ans;
    else
      now = z[now].next[a[i]];
    ans += cnt[now];
  }
  return ans - cnt[now] + cnt2[now];
}

int main()
{
  int n, m;
  cin >> n >> m;
  cls();
  for (int i = 1; i <= n; i ++)
  {
    int tot;
    cin >> tot;
    for (int j = 1; j <= tot; j ++)
    {
      int x;
      cin >> x;
      a[i].push_back(x);
    }
    insert(a[i]);
  }
  for (int i = 1; i <= m; i ++)
  {
    int tot;
    cin >> tot;
    for (int j = 1; j <= tot; j ++)
    {
      int x;
      cin >> x;
      b[i].push_back(x);
    }
    ans[i] = query(b[i]);
  }
  for (int i = 1; i <= m; i ++)
    cout << ans[i] << '\n';
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值