看到前缀就要想到字典树!
看到前缀就要想到字典树!
看到前缀就要想到字典树!
#include <cstdio> #include <iostream> #define N 500001 int n, m, k, cnt; int a[N], val[N], num[N], next[N][2]; inline int read() { int x = 0, f = 1; char ch = getchar(); for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1; for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0'; return x * f; } inline void insert() { int i, now = 0; for(i = 1; i <= k; i++) { if(!next[now][a[i]]) next[now][a[i]] = ++cnt; now = next[now][a[i]]; num[now]++; } val[now]++; } inline int query() { int i, now = 0, ans = 0; for(i = 1; i <= k; i++) { if(!next[now][a[i]]) return ans; now = next[now][a[i]]; ans += val[now]; } return ans + num[now] - val[now]; } int main() { int i, j; n = read(); m = read(); for(i = 1; i <= n; i++) { k = read(); for(j = 1; j <= k; j++) a[j] = read(); insert(); } for(i = 1; i <= m; i++) { k = read(); for(j = 1; j <= k; j++) a[j] = read(); printf("%d ", query()); } return 0; }