踹shu_Trie树

【USACO Dec08】密信

Description

贝茜正在领导奶牛们逃跑.为了联络,奶牛们互相发送秘密信息. 
信息是二进制的,共有M(1≤M≤50000)条.反间谍能力很强的约翰已经部分拦截了这些信息,知道了第i条二进制信息的前bi(1<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

Sample Output





2

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: 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 

















cnt记录有多少个单词以此为前缀,stop记录有多少个单词以此结尾,另外,因为同学的代码比我的快,于是写了读入优化来优化常数

附上AC代码,主要为自己以后复习,也供参看
#include 
#include 
const int MAXN=500001;
struct node {
	int stop,cnt,next[2];
} T[MAXN];
int n,m,tot;
 
inline int read(){
	char x=getchar();int ans=0;
	while(x<'0'||x>'9')x=getchar();
	while(x>='0'&&x<='9')ans=ans*10+x-'0',x=getchar();
	return ans;
}
 
inline void add(int len) {
	int p=0;
	for(int i=1,x; i<=len; i++) {
		x=read();
		if(T[p].next[x]==0)T[p].next[x]=++tot;
		p=T[p].next[x];
		T[p].cnt++;
	}
	T[p].stop++;
}
 
inline int query(int len) {
	int ans=0,p=0;
	for(int i=1,x; i<=len; i++) {
		x=read();
		if(!T[p].next[x]) {
			for(i++; i<=len; i++)x=read();
			return ans;
		}
		p=T[p].next[x];
		ans+=T[p].stop;
	}
	return ans-T[p].stop+T[p].cnt;
}
 
int main() {
	n=read(),m=read();
	for(int i=1; i<=n; i++)add(read());
	for(int i=1; i<=m; i++)printf("%d\n",query(read()));
	return 0;
}









你可能感兴趣的:(Trie)