uva1401 - Remember the Word 前缀树DP

UVA - 1401:Remember the Word UVA-1401:Remember the Word 来源:UVA 标签:字符串->Trie,动态规划 参考资料: 相似题目: 题目 Neal is very curious about combinatorial problems, and now here comes a problem about words. Knowing that... 阅读详情

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$ \le$S$ \le$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.

Sample Input 

abcd 
4 
a 
b 
cd 
ab

Sample Output 

Case 1: 2

  给一个字符串和一些单词,这个字符串由这些单词组成的情况有多少种。

  若正着推,dp[i]代表前i个字母能由单词组成的情况有多少种,那么dp[i]=sum{dp[i-len],str[i-len+1]...str[i]是一个单词}。如果对于每个i都枚举一遍所有单词会超时,用前缀树找从s[i]开始到结尾的这个路径,中途若遇到单词标记就可以进行一次dp,若位置str[j]被标记,则更新sum[j]=(sum[j]+sum[i-1])%MOD。注意这是用前面的状态更新后面的状态。若倒着推,设dp[i]为后i个字母能由单词组成的情况有多少种,dp倒着进行,则sum[i]=(sum[i]+sum[j+1])%MOD,比较符合一般DP的思路。

  可以在前缀树查找的过程中完成dp,也可以查找的时候把点记下来,查找完后再dp。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAXN 300010
#define MAXNODE 400010
#define MOD 20071027
#define INF 0x3f3f3f3f
using namespace std;
int N,sum[MAXN];
char str[MAXN];
struct Tire{
    int ch[MAXNODE][26];
    int val[MAXNODE];
    int sz;
    Tire(){
        memset(ch,0,sizeof(ch));
        memset(val,0,sizeof(val));
        sz=1;
    }
    int get_id(char c){
        return c-'a';
    }
    void insert(char *s,int v){
        int u=0;
        for(int i=0;s[i];i++){
            int c=get_id(s[i]);
            if(!ch[u][c]) ch[u][c]=sz++;
            u=ch[u][c];
        }
        val[u]=1;
    }
    void query(char *s){
        int u=0;
        for(int i=1;s[i];i++){
            int u=0;
            for(int j=i;s[j];j++){
                int c=get_id(s[j]);
                if(!ch[u][c]) break;
                u=ch[u][c];
                if(val[u]) sum[j]=(sum[j]+sum[i-1])%MOD;
            }
        }
    }
};
int main(){
    freopen("in.txt","r",stdin);
    while(scanf("%s",str+1)!=EOF){
        scanf("%d",&N);
        Tire tire;
        char s[110];
        for(int i=1;i<=N;i++){
            scanf("%s",s);
            tire.insert(s,1);
        }
        tire.query(str);
        printf("%d\n",sum[strlen(str+1)]);
    }
    return 0;
}



告别第三方工具!用Windows自带蓝牙玩转BLE设备调试(保姆级图文教程) 本文详细介绍了如何利用Windows自带的蓝牙功能进行BLE设备调试,无需第三方工具。从硬件准备、系统配置到实战操作,提供保姆级图文教程,帮助开发者高效完成设备发现、数据交互等全流程调试工作。特别适合物联网开发者和智能硬件爱好者。 阅读详情

相关推荐

电机传动机构的转矩与惯量折算

参考《工业运动控制》

庐州牧 1万+

UVA - 1401-------trie&&dp

Remember the Word UVA - 1401(传送门) 题意: 给你一个字典。和一个模式串。 现在要求你按照字典分割模式串。 求: 方案数。 思路: 很容易想到递推的思想。 一般思路: 先

qq_45377553的博客 176

第六章 汇川技术InoProShop入门之modbusTCP从站协议解读

摘要:ModbusTCP从站协议是Modbus协议在TCP/IP网络上的扩展,作为服务器端被动响应主站请求。它采用MBAP+PDU帧结构,通过IP地址和502端口实现网络通信,支持标准功能码(如读/写寄存器、线圈)。相比传统串行Modbus,具有高速传输、远距离通信优势。从站需解析请求、执行操作并返回响应,同时处理错误校验和并发连接。该协议广泛应用于智能传感器、PLC等工业设备,实现高效可靠的主从数据交互。

zyfucking2010的博客 1449

uva 1401 字典树模板

f[i] += f[j] i

chromosome24k的博客 250

硬件学习笔记(器件篇)—— 磁珠与磁环

因为有这些差别,所有经常会让人们觉得他们并不是一类器件,但实际上他们的原理是一样的。我们使用磁珠是为了利用损耗消耗高频能量,所以如果我们理解了磁珠是如何消耗高频能量的,我们就能理解磁珠的工作原理。

y_u_yu_yu_的博客 1万+

海康威视HiTools实战:5分钟搞定工业镜头选型(附避坑指南)

本文详细解析了海康威视HiTools在工业镜头选型中的应用,通过五步操作流程帮助用户快速匹配适合的镜头型号。文章深入探讨了工业视觉系统的核心参数,包括焦距、视野、景深和畸变控制,并提供了光源搭配和系统集成的实战指南,助力提升机器视觉检测精度与效率。

u0v1w2x3的博客 1078

uva 1401

Neal is very curious about combinatorial problems, and now here comes a problem about words. Knowingthat Ray has a photographic memory and this may not trouble him, Neal gives it to Jiejie.Since Jieji...

weixin_30414155的博客 178

【Telephony】Telephony总纲!Phone进程流程(AOSP)

整个Framework层的Telephony框架运行在一个叫做Phone(com.android.phone)的进程中。 Phone进程启动的过程中,会初始化非常多的分支功能,SIM卡流程初始化就是其中之一,所以我觉得有必要写一下Phone进程的框架

weixin_44513784的博客 1984

LA 3942 Remember the Word(前缀树&树上DP)

                                                                                  3942 - Remember the Word     Neal is very curious about combinatorial problems, and now here comes a problem abou...

weixin_34266504的博客 149

从零到一:使用阿里云百炼搭建企业级 AI Agent 完全实战手册(2026超详细版)

本文是一份企业级AI Agent构建手册,主要面向企业技术负责人、AI产品经理和后端开发工程师。手册详细介绍了如何在阿里云百炼平台上搭建企业智能体应用的全流程,包括环境准备、知识库构建、智能体创建、工具集成、工作流编排等核心环节。重点内容包括: 准备工作:阿里云账号注册、百炼服务开通、免费额度领取、API Key管理 知识库构建:文档格式要求、内容优化原则、RAG系统搭建 智能体开发:Agent创建、工具集成、复杂业务工作流设计 生产部署:多渠道接入、监控运维、安全治理 成本控制:Token预算管理、选型决

u010323587的专栏 1170

Anaconda+清华源加速PyTorch GPU环境安装与CUDA版本匹配指南

深度学习环境管理常面临依赖冲突与下载缓慢问题,通过虚拟环境隔离与镜像源加速可显著提升效率。Anaconda利用conda机制创建独立Python环境,避免包版本冲突;清华源通过国内镜像同步大幅提高下载速度。GPU版PyTorch安装需严格匹配CUDA、cuDNN与显卡驱动版本,否则易出现CUDA不可用错误。该方案适用于图像分割、目标检测等需多版本PyTorch并存的场景,能快速搭建稳定GPU训练环境。本文详解Anaconda安装、清华源配置及PyTorch GPU版安装全流程。

weixin_30522983的博客 241

uva1401

#include <iostream> #include <istream> #include <sstream> #include <vector> #include <stack> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <cstring&gt

小刀刺大熊 162

4.4 直流无刷电机(BLDC):控制器硬件设计

摘要 本文详细阐述了直流无刷电机(BLDC)控制器的硬件设计要点。控制器硬件主要包括微处理器单元、功率驱动模块、信号检测电路、通信接口和电源管理模块。在微处理器选型方面,分析了ARM Cortex-M系列、DSP等架构的适用场景,并对比了不同处理器的性能参数。功率驱动模块设计重点包括栅极驱动电路、逆变桥热管理和电流保护机制。信号检测部分介绍了位置传感器接口和模拟信号调理技术。此外,还讨论了通信接口设计、电源管理方案以及硬件布局与EMC设计规范。最后强调了硬件测试验证的重要性,包括故障注入测试等验证方法。整体

技术工作者 190

UVA1401 Remember the Word

思路 用trie树优化dp 设f[i]表示到第i个的方案数,则有\(f[i]=\sum_{x}f[i+len[x]]\)(x是s[i,n]的一个前缀),所以需要快速找出所有前缀,用Trie树即可 代码 #include <cstdio> #include <algorithm> #include <cstring> using namespace std; co...

weixin_33836874的博客 167

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

UVa1401 Remember the Word(DP+Trie树)

题目给定一个字符串集合有几种方式拼成一个字符串。 dp[i]表示stri...strlen-1的方案数 dp[len]=1 dp[i]=∑dp[j](stri...strj-1∈SET) 用集合的字符串构造一棵Trie树,然后就可以在线性时间判断哪几个前缀字符串在集合里。 1 #include<cstdio> 2 #include<cstri...

dengliugong3918的博客 143

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Uva1401 Remember the Word

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 Jie...

叶上初阳_285557的博客 247

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

【Trie】 UVA1401 Remember the Word

【代码】【Trie】 UVA1401 Remember the Word。

2401_89382924的博客 569

Uva1401 - Remember the Word

#include #define maxn 100010 #define INF (int)(1e9) #define MOD 20071027 #define maxnode 500010 #define sigma_size 30 typedef long long ll; using namespace std; int dp[maxnode]; char str[max

421

uva 1401Remember the Word(trie树+dp)

题意:给一个由s个单词组成的字典和一个长字符串。把这个字符串分解成若干个单词的连接(单词可重复使用),有多少种方法? 思路:令d(x)表示从字符i开始的字符串(即后缀s[i....L])的分解方案数,则d(i)=sum{d+len(x) | 单词x是s[i...L]的前缀}。          所以可以先把单词写入trie树,然后从从后往前在长串的每个位置找前缀即可。 #include #i

AC之路 457

uva 1401 - Remember the Word(字典树+dp)

题目链接:uva 1401 - Remember the Word 题目大意:给出一个由S个不同单词组成的字典和一个长字符串。吧这个字符串分解成若干个单词的连接,有多少种方法。 解题思路:dp(i) = sum{ dp(i+len(x))}, 单词x为S[i...L]的前缀。 #include #include #include using namespace std; c

不慌不忙、不急不躁 927

UVA 1401 Remember the Word(DP+字典树Trie)

UVA 1401 Remember the Word(DP+字典树Trie) https://vjudge.net/problem/UVA-1401 题意:         给你一个由N个单词组成的词典,和一个字符串S。问你S由N中的单词组成的方法有多少种?字典中的单词可以重复使用但是不可重叠。 分析:         我们令d[i]=x表示S串的后缀[i,L-1]串有多少种构成方式

qq_36782366的博客 269

Uva 1401 Remember the Word 字典树+DP

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

colorfulshark 594

【Trie+dp】UVA1401 Remember the Word

这道题目由于S较为长,所以暴力枚举一定是超时的 所以考虑f[i]表示从i-L(后缀)的方案数 那么就可以推出 f[i]=sum{f[i+len(suf)],suf是i-L的一个前缀} 然后就可以在字典树上求这个前缀了 代码 #include<bits/stdc++.h> using namespace std; const int mod=20071027; const int maxn=3e5+5; char str[maxn],s[maxn]; int n,f[max..

andyc_03的博客 143

uva 1401 - Remember the Word(DP+Tire树,5级)

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 Ji

nealgavin的专栏 695

Uva1401 Remember the Word 字典树trie

题意翻译 Uva1401 Remember the Word (记单词) 翻译 题目描述 Neal 对有关组合的问题很感兴趣,现在他有一个关于单词的有趣问题要解决: 他知道大佬Ray的记忆力像存储器一样好,这样的问题肯定难不倒他,于是Neal把问题给了蒟蒻Jiejie。Jiejie经常记不住数字,他就用火柴棒来帮助自己记忆。Jiejie最多只能用20071027根火柴棒(因为他...

pxlsdz的博客 477

UVa 1401 Remember the Word

Trie+DP 大白书上的字典树训练题。 题意是说一个字符串可能有多少种小串组成。 例如 abcd  4 a b cd ab abcd=a+b+cd;abcd=ab+cd; 递推为:从最后一位往前,dp[i]=dp[i]+dp[i+ len[x]]  x为输入时的顺序,附加到节点中。是 i~strlen(S)的前缀。S[1,2,3,…,i,…len]

自己选择的路,跪着也要走完。 1349
上一篇: uva11525 - Permutation 线段树加速康托展开
下一篇: uva11732 - strcmp() Anyone? 前缀树
小小小小葱
博客等级 码龄14年 22粉丝 266原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值