[Usaco2008 Dec]Secret Message 秘密信息

时间:2023-03-08 22:24:29

2794: [Usaco2008 Dec]Secret Message 秘密信息

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 7  Solved: 3
[Submit][Status][Web Board]

Description

贝茜正在领导奶牛们逃跑.为了联络,奶牛们互相发送秘密信息.
信息是二进制的,共有M(1≤M≤50000)条.反间谍能力很强的约翰已经部分拦截了这些信息,知道了第i条二进制信息的前bi(l《bi≤10000)位.他同时知道,奶牛使用N(1≤N≤50000)条密码.但是,他仅仅了解第J条密码的前cj(1≤cj≤10000)位.
对于每条密码J,他想知道有多少截得的信息能够和它匹配.也就是说,有多少信息和这条密码有着相同的前缀.当然,这个前缀长度必须等于密码和那条信息长度的较小者.
在输入文件中,位的总数(即∑Bi+∑Ci)不会超过500000.

Input

第1行输入N和M,之后N行描述秘密信息,之后M行描述密码.每行先输入一个整数表示信息或密码的长度,之后输入这个信息或密码.所有数字之间都用空格隔开.

Output

共M行,输出每条密码的匹配信息数.

Sample Input

4 5
3 0 1 0
1 1
3 1 0 0
3 1 1 0
1 0
1 1
2 0 1
5 0 1 0 0 1
2 1 1
INPUT DETAILS:
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.

Sample Output

1
3
1
1
2
//0 matches only 010: 1 match 1 matches 1, 100, and 110: 3 matches 01 matches only 010: 1 match 01001 matches 010: 1 match 11 matches 1 and 110: 2 matches

HINT

Source

题解:

   额,trie树乱搞题,用一个size记录有几个儿子,sum记录是尾节点的次数,遍历trie树,如果不是尾节点就加上sum,是尾节点就加上size。

#include<iostream>
#include<cstring>
#include<cstdio>
#define maxn 500005
using namespace std;
int n,m,k,tot,ans;
int size[maxn],sum[maxn];
int son[maxn][];
int a[maxn];
char ch;
void read(int &x){
for (ch=getchar();!isdigit(ch);ch=getchar());
for (x=;isdigit(ch);x=x*+ch-'',ch=getchar());
}
void insert(int k)
{
int p=;
for (int i=; i<=k; p=son[p][a[i]],i++)
{
if (!son[p][a[i]]) son[p][a[i]]=++tot;
size[p]++;
}
sum[p]++;
size[p]++;
}
void workout(int k)
{
int p=; ans=;
for (int i=; i<=k; p=son[p][a[i]],i++)
{
if (!son[p][a[i]]) break;
if (i!=k) ans+=sum[son[p][a[i]]]; else ans+=size[son[p][a[i]]];
}
printf("%d\n",ans);
}
int main()
{
// freopen("sec.in","r",stdin);
// freopen("sec.out","w",stdout);
int k;
read(n); read(m); tot=;
for (int i=; i<=n; i++)
{
read(k); for (int j=; j<=k; j++) read(a[j]);
insert(k);
}
for (int i=; i<=m; i++)
{
read(k);
for (int j=; j<=k; j++) read(a[j]);
workout(k);
}
return ;
}