Remember the Word UVALive - 3942 背单词 字典树+dp

本文探讨了一种使用前缀树(Trie)解决组合问题的方法,具体为给定一个单词和一组单词集,计算该单词能以多少种方式被这组单词集中的单词分解。通过构建前缀树加速查找过程,避免了直接枚举带来的效率问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接 

     Neal is very curious about combinatorial problems, and now here comes a problem about words. Know- ing 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.

分析:d(i)表示从第i字符开始的字符串(即后缀S【i,len】)的分解方案数,则d(i) = sum{ d(i + len(x) | 单词x是S【i,len】的前缀}。直接枚举会超时.应将所有的单词组成一棵前缀树Trie,然后查找。 

#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int  N = 4000*100 +5,SIZE = 26, MOD = 20071027; 

struct Trie{
	int ch[N][SIZE];
	int val[N];
	int sz;  // 结点总数
	// 初始时只有一个根结点	
	void clear(){ 
		sz = 1;
		memset(ch[0],0,sizeof(ch[0]));
	}
	// 字符c的编号
	int idx(char c){
		return c - 'a';
	}
	// 插入字符串s,附加信息为v。注意v必须非0,因为0代表“本结点不是单词结点”
	void insert(const 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])); //新建一个size节点 
				val[sz] = 0; // 中间结点的附加信息为0
				ch[u][c] = sz++; // //指向新建的子节点idx = size
			}
			u = ch[u][c];
		}
		val[u] = v; // 字符串的最后一个字符的附加信息为v
	} 
	// 找字符串s的长度不超过len的前缀
	void find_prefixes(const char *s,int len,vector<int>& ans){	
		int u = 0;	
		for(int i = 0; i < len; i++){
			if( s[i] == '\0') break;
			int c = idx(s[i]);
			if( !ch[u][c]) break; //找不到对应的char 
			u = ch[u][c];
			if( val[u])
				ans.push_back(val[u]); // 找到一个前缀
		}		
	}
};

const int TEXT =  300000 +5, WORD = 100 +5;
char text[TEXT], word[WORD];
Trie trie;
int d[TEXT];
int main(int argc, char** argv) {
	int kase = 0;
	while( scanf("%s", text) == 1){
		int n;
		scanf("%d",&n);
		trie.clear();
		while( n--){
			scanf("%s",word);
			trie.insert(word, strlen(word)); //附加信息为插入字符串的长度 
		}
		int len = strlen(text);
		memset(d, 0, sizeof(d));
		d[len] = 1;
		for(int i = len - 1; i >= 0; i--){
			vector<int> p;
			trie.find_prefixes(text+i, len-i, p);
			for(int j = 0; j < p.size(); j++)
				d[i] = (d[i] + d[i+p[j]]) % MOD;
		}
		printf("Case %d: %d\n",++kase, d[0]);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值