1. 程式人生 > >[BZOJ1590] [Usaco2008 Dec]Secret Message 秘密信息(字典樹)

[BZOJ1590] [Usaco2008 Dec]Secret Message 秘密信息(字典樹)

clu har pro iostream digi git secret 秘密 class

傳送門

看到前綴就要想到字典樹!

看到前綴就要想到字典樹!

看到前綴就要想到字典樹!

#include <cstdio>
#include <iostream>
#define N 500001

int n, m, k, cnt;
int a[N], val[N], num[N], next[N][2];

inline int read()
{
	int x = 0, f = 1;
	char ch = getchar();
	for(; !isdigit(ch); ch = getchar()) if(ch == ‘-‘) f = -1;
	for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - ‘0‘;
	return x * f;
}

inline void insert()
{
	int i, now = 0;
	for(i = 1; i <= k; i++)
	{
		if(!next[now][a[i]])
			next[now][a[i]] = ++cnt;
		now = next[now][a[i]];
		num[now]++;
	}
	val[now]++;
}

inline int query()
{
	int i, now = 0, ans = 0;
	for(i = 1; i <= k; i++)
	{
		if(!next[now][a[i]])
			return ans;
		now = next[now][a[i]];
		ans += val[now];
	}
	return ans + num[now] - val[now];
}

int main()
{
	int i, j;
	n = read();
	m = read();
	for(i = 1; i <= n; i++)
	{
		k = read();
		for(j = 1; j <= k; j++) a[j] = read();
		insert();
	}
	for(i = 1; i <= m; i++)
	{
		k = read();
		for(j = 1; j <= k; j++) a[j] = read();
		printf("%d\n", query());
	}
	return 0;
}

  

[BZOJ1590] [Usaco2008 Dec]Secret Message 秘密信息(字典樹)