bzoj 1590: [Usaco2008 Dec]Secret Message 秘密信息

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

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

HINT 

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 

Source 

Gold

题解:

比较裸的trie树,用p[x].cnt表示在x结尾的串的个数,这样只能算出长度不大于当前串的方案数,所以再设p[x].sum表示x子树的和。

总的方案就是路径上的cnt累加再加上sum

#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
struct node
{
	int Next[2],cnt,sum;
	void init()
	{
		cnt=sum=0;
		memset(Next,-1,sizeof(Next));
	}
}p[500005];
int n,m,i,j,x,a[10005],b[10005],tot;
inline void read(int&a){char c;while(!(((c=getchar())>='0')&&(c<='9')));a=c-'0';while(((c=getchar())>='0')&&(c<='9'))(a*=10)+=c-'0';}
void update(int len)
{
	int x=0,k=0;
	for(int i=1;i<=len;i++)
	{
		int j=a[i];
		if(p[x].Next[j]==-1)
		{
			p[x].Next[j]=++tot;
			p[tot].init();
		}
		x=p[x].Next[j];b[++k]=x;
	}
	p[x].cnt++;
	for(int i=1;i<k;i++) p[b[i]].sum++;
}
int solve(int len)
{
	int x=0,ans=0;
	for(int i=1;i<=len;i++)
	{
		int j=a[i];
		if(p[x].Next[j]==-1) return ans;
		x=p[x].Next[j];
		ans+=p[x].cnt;
	}
	return ans+p[x].sum;
}
int main()
{
	read(n),read(m);
	p[0].init();
	for(i=1;i<=n;i++)
	{
		read(x);
		for(j=1;j<=x;j++) read(a[j]);
		update(x);
	}
	for(i=1;i<=m;i++)
	{
		read(x);
		for(j=1;j<=x;j++) read(a[j]);
		printf("%d\n",solve(x));
	}
	return 0;
}

  

 

posted @ 2016-09-11 09:46  lwq12138  阅读(418)  评论(0编辑  收藏  举报