题目描述
DESCRIPTION
Bessie is leading the cows in an attempt to escape! To do this, the cows are sending secret binary messages to each other.
Ever the clever counterspy, Farmer John has intercepted the first () bits of each of () of these secret binary messages.
He has compiled a list of () partial codewords that he thinks the cows are using. Sadly, he only knows the first () bits of codeword .
For each codeword , he wants to know how many of the intercepted messages match that codeword (i.e., for codeword , how many times does a message and the codeword have the same initial bits). Your job is to compute this number.
The total number of bits in the input (i.e., the sum of the and the ) will not exceed .
INPUT FORMAT
Line : Two integers: and .
Lines : Line describes intercepted code with an integer followed by space-separated 0
's and 1
's.
Lines : Line describes codeword with an integer followed by space-separated 0
's and 1
's.
OUTPUT FORMAT
Lines : Line : The number of messages that the -th codeword could match.
SAMPLE INPUT
1 | 4 5 |
SAMPLE OUTPUT
1 | 1 |
HINT
Four messages; five codewords.
The intercepted messages start with 010
, 1
, 100
, and 110
.
The possible codewords start with 0
, 1
, 01
, 01001
, and 11
.
0
matches only 010
: match
1
matches 1
, 100
, and 110
: matches
01
matches only 010
: match
01001
matches 010
: match
11
matches 1
and 110
: matches
题目大意
贝茜正在领导奶牛们逃跑.为了联络,奶牛们互相发送秘密信息.
信息是二进制的,共有 ( ) 条,反间谍能力很强的约翰已经部分拦截了这些信息,知道了第 条二进制信息的前 ( ) 位,他同时知道,奶牛使用 ( ) 条暗号.但是,他仅仅知道第 条暗号的前 ( ) 位。
对于每条暗号 ,他想知道有多少截得的信息能够和它匹配。也就是说,有多少信息和这条暗号有着相同的前缀。当然,这个前缀长度必须等于暗号和那条信息长度的较小者。
在输入文件中,位的总数 ( 即 ) 不会超过 。
题解
这是一道经典的字典树统计问题
按照拦截到的信息建立 树,并在建树的过程中统计多少条消息经过当前节点(),有多少条消息截止于当前节点()
对于每一个查询,沿着字典树向下走,将途径节点的 累加,查询的过程中可能出现以下两种终止情况,(假设终止于节点 )
-
如果再往下走就没有与该信息相符的节点时,说明没有比该信息长且前缀为该信息的消息,这时直接输出答案 即可.
-
如果询问的消息已经遍历完,那么 包含的消息必定有与查询的消息相同的前缀,也有可能刚好在此处终结,因此在加上 的同时还要减去 ,答案为 .
代码实现
1 |
|