bzoj1030 trie图模板

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
char str[200];
struct node
{
	int son[26];
	int fa, grafa;
	bool isended;
	int value;//仅用于测试
};
node trie[6010];
int tot = 1;
int stack[6010];
int dp[130][7000];
void insert(char *s)
{
	int len = strlen(s);
	int temp = 0;
	for (int i = 0; i < len; i++)
	{
		if (trie[temp].son[s[i] - 'A'] == 0)trie[temp].son[s[i] - 'A'] = tot++;
		temp = trie[temp].son[s[i] - 'A'];
		trie[temp].value = s[i];
		//cout << (char)trie[temp].value << endl;
	}
	trie[temp].isended = true;
}
int getgrafa(int num,int value)
{
	int temp = trie[num].grafa;
	while (temp&&trie[temp].son[value]==0)//在这傻乎乎的用了!temp的条件现在好了.....
	{
		temp = trie[temp].grafa;
		//cout << (char)trie[temp].value << endl;
		//cout << trie[temp].value << endl;
		//cout << temp << endl;
	}
	temp = trie[temp].son[value];
	return temp;
}
void construct()
{
	int head = 0, tail = 1;
	stack[0] = 0;
	while (head != tail)
	{
		int now = stack[head];
		head++;
		for (int i = 0; i < 26; i++)
		{
			if (trie[now].son[i])
			{
				trie[trie[now].son[i]].grafa = (now == 0 ? 0 : getgrafa(now, i));
				stack[tail] = trie[now].son[i];
				tail++;
				trie[trie[now].son[i]].isended |= trie[trie[trie[now].son[i]].grafa].isended;
			}
			else
			{
				trie[now].son[i] = (now == 0 ? 0 : getgrafa(now, i));
			}
		}
	}
}
int main()
{
	
	int n, m;
	scanf("%d%d", &n, &m);
	while (n--)
	{
		scanf("%s", str);
		insert(str);
	}
		construct();
		dp[0][0] = 1;
		for (int i = 0; i <m; i++)
		{
				for (int k = 0; k < tot; k++)
				{
					if (!dp[i][k])
						continue;
					for (int j = 0; j < 26; j++)
					{
						if (trie[trie[k].son[j]].isended == 1)
							continue;
						dp[i + 1][trie[k].son[j]] = (dp[i][k]+dp[i + 1][trie[k].son[j]]) % 10007;
				}
			}
		}
		int ans = 1;
		for (int i = 0; i < m; i++)
		{
			ans = ans * 26;
			ans = ans % 10007;
		}
		for (int i = 0; i < tot; i++)
		{
			//cout << "amount:"<<dp[m][i] << endl;
			ans -= dp[m][i];
			ans = ans % 10007;
		}
		printf("%d\n", (ans + 10007) % 10007);
}

/*char t[7], tt[6], ttt[5]; construct 测试代码
int temp;
scanf("%s", t);
insert(t);
scanf("%s", tt);
insert(tt);
//scanf("%s", ttt);
//insert(ttt);
construct();
cout << endl;
int len = strlen(t);
temp = 0;
for (int i = 0; i < len; i++)
{
	temp = trie[temp].son[t[i] - 'A'];
	cout << (char)(trie[temp].value) << " " << "grafa:" << (char)(trie[trie[temp].grafa].value) << endl;
}
cout << endl;
len = strlen(tt);
temp = 0;
for (int i = 0; i < len; i++)
{
	temp = trie[temp].son[tt[i] - 'A'];
	cout << (char)(trie[temp].value) << " " << "grafa:" << (char)(trie[trie[temp].grafa].value) << endl;
}
cout << "end:" << endl;*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值