UVA1401 Remember the Word

这是一个关于组合问题的编程挑战,要求将一个长字符串分割成给定单词集合中的单词,计算所有可能的分割方式数量。由于限制条件,必须使用模20071027后的结果。解决方案涉及到使用Trie数据结构进行优化,通过递归计算每个位置的分割方案,避免了暴力枚举的高复杂度。

https://vjudge.net/problem/UVA-1401
Neal is very curious about combinatorial problems, and now here comes a problem about words. Knowing that Ray has a photographic memory and this may not trouble him, Neal gives it to Jiejie.
Since Jiejie can’t remember numbers clearly, he just uses sticks to help himself. Allowing for Jiejie’s
only 20071027 sticks, he can only record the remainders of the numbers divided by total amount of
sticks.
The problem is as follows: a word needs to be divided into small pieces in such a way that each
piece is from some given set of words. Given a word and the set of words, Jiejie should calculate the
number of ways the given word can be divided, using the words in the set.
Input
The input file contains multiple test cases. For each test case: the first line contains the given word
whose length is no more than 300 000.
The second line contains an integer S, 1 ≤ S ≤ 4000.
Each of the following S lines contains one word from the set. Each word will be at most 100
characters long. There will be no two identical words and all letters in the words will be lowercase.
There is a blank line between consecutive test cases.
You should proceed to the end of file.
Output
For each test case, output the number, as described above, from the task description modulo 20071027.

题意:又一个长字符串和s个单词,求这个长字符串由这s个单词拼成的方案数。
思路:白书Trie第一道例题
递推:设f(i):从下标i开始的子字符串拼成的方案数,则f(i)=Σf(i+len(x)),len(x)为下标i开始的符合的单词的长度。
如果暴力枚举单词的话,复杂度为3 * 10^5 * 4000 * 100完全不能实现
把单词组织在trie上的话,每路过一个单词结点,f[i]+=f[i+len],复杂度仅为3 * 10^5 * 100

#include<bits/stdc++.h>
using namespace std;
#define mod 20071027

char s[300000+100];
int f[300000+100];
int n;
int kase;
char p[120];

struct Trie{
	int ch[4000*100][26];
	int val[4000*100];
	int sz;
	void init(){sz=1;memset(ch[0],0,sizeof(ch[0]));}
	int idx(char c){return c-'a';}

	void insert(char *s,int v)
	{
		int u=0,n=strlen(s);
		for(int i=0;i<n;i++)
		{
			int c=idx(s[i]);
			if(!ch[u][c])
			{
				memset(ch[sz],0,sizeof(ch[sz]));
				val[sz]=0;
				ch[u][c]=sz++;
			}
			u=ch[u][c];
		}
		val[u]=v;
	}

	void find(char *s,int pos)
	{
		int u=0;
		for(int i=0;s[i];i++)
		{
			int c=idx(s[i]);
			if(!ch[u][c])return;
			u=ch[u][c];
			if(val[u])f[pos]+=f[pos+i+1],f[pos]%=mod;
		}
	}
}T;

int main()
{
	//freopen("input.in","r",stdin);
	while(~scanf("%s",s))
	{
		kase++;
		cin>>n;
		T.init();
		while(n--)
		{
			scanf("%s",p);
			T.insert(p,1);
		}
		n=strlen(s);
		f[n]=1;
		for(int i=n-1;i>=0;i--)
		{
			f[i]=0;
			T.find(s+i,i);
		}
		printf("Case %d: %d\n",kase,f[0]);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值