BZOJ1590 [Usaco2008 Dec]Secret Message 秘密信息

时间:2023-03-09 17:09:34
BZOJ1590 [Usaco2008 Dec]Secret Message 秘密信息

建立一颗trie树,记录下来每个点以它为结尾的字符串的个数cnt,和它的子树内有多少字符串size

于是查询的时候就只需要把沿途的cnt加起来,再加上最后的size就好了

 /**************************************************************
Problem: 1590
User: rausen
Language: C++
Result: Accepted
Time:320 ms
Memory:3892 kb
****************************************************************/ #include <cstdio> using namespace std; inline int read(); struct trie {
trie *son[];
int sz, tail; #define Len (1 << 16)
void* operator new(size_t) {
static trie *mempool, *c;
if (c == mempool)
mempool = (c = new trie[Len]) + Len;
c -> son[] = c -> son[] = NULL;
c -> sz = , c -> tail = ;
return c++;
}
#undef Len void insert(int x) {
++this -> sz;
if (x == ) {
++this -> tail;
return;
}
int t = read();
if (!this -> son[t]) this -> son[t] = new()trie;
this -> son[t] -> insert(x - );
} int query(int x) {
if (x == ) return this -> sz;
int t = read();
if (!this -> son[t]) {
while (--x) read();
return this -> tail;
}
return this -> son[t] -> query(x - ) + this -> tail;
}
} *t; int n, m; int main() {
int i;
n = read(), m = read();
t = new()trie;
for (i = ; i <= n; ++i) t -> insert(read());
for (i = ; i <= m; ++i) printf("%d\n", t -> query(read()));
return ;
} inline int read() {
static int x;
static char ch;
x = , ch = getchar();
while (ch < '' || '' < ch)
ch = getchar();
while ('' <= ch && ch <= '') {
x = x * + ch - '';
ch = getchar();
}
return x;
}