P2922 [USACO08DEC]Secret Message G
题目
思路
这·是·蓝·题?!
这不是裸的trie吗,感觉最多去到绿色
跟这题几乎一样,甚至更简单,对trie求前缀和即可,水题,不细讲
代码
#include <iostream>
#include <cstdio>
#define nn 1000010
using namespace std;
int read() {
int re = 0;
char c = getchar();
while(c < '0' || c > '9')c = getchar();
while(c >= '0' && c <= '9')
re = (re << 1) + (re << 3) + c - '0',
c = getchar();
return re;
}
int trie[nn][3] , cnt[nn] , sum[nn];
void insert() {
int siz = read();
int p = 1;
static int top = 1;
for(int i = 1 ; i <= siz ; i++) {
int tmp = read();
if(trie[p][tmp] == 0)
trie[p][tmp] = ++top;
p = trie[p][tmp];
}
cnt[p]++;
}
void dfs(int p) {
if(p == 0)return;
dfs(trie[p][0]);
dfs(trie[p][1]);
sum[p] = sum[trie[p][0]] + sum[trie[p][1]] + cnt[p];
}
void query() {
int res = 0;
int siz = read();
int p = 1;
for(int i = 1 ; i <= siz ; i++) {
int tmp = read();
if(p == 0)
continue;
res += cnt[p];
p = trie[p][tmp];
}
res = res + sum[p];
// cout << sum[p] << endl;
printf("%d\n" , res);
return;
}
int main() {
// freopen("P2922_2.in" , "r" , stdin);
// freopen("output.txt" , "w" , stdout);
int n , m;
m = read();
n = read();
for(int i = 1 ; i <= m ; i++)
insert();
dfs(1);
for(int i = 1 ; i <= n ; i++)
query();
return 0;
}