UVALive 3942Remember the Word(字典树 + 简单dp)
来源:互联网 发布:听歌识曲软件最好用 编辑:程序博客网 时间:2024/05/12 06:59
题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1943
题意:给定文本串txt和n个模式串str,问有多少种方法用模式串中的任意几个拼成文本串(可重复用),最后结果模20071027。
思路:利用数组d[i]表示从文本串位置i到文本串末尾可用模式串中的任意几个拼成的种数。这样最后只需要输出d[0]即可。如果直接记忆化搜索的话,肯定会TLE。所以可以考虑对模式串建一棵字典树,每次求d[s]的时候,从txt[s]这个位置从字典树开始搜索,如果当前所在的结点为某个模式串的结点时,d[s] += d[i + 1]。
代码:
#include <iostream>#include <stdio.h>#include <string.h>#include <math.h>#include <algorithm>#include <string>#include <vector>#include <map>#include <queue>#include <stack>using namespace std;#define lson l, m, rt << 1#define rson m + 1, r, rt << 1 | 1#define ceil(x, y) (((x) + (y) - 1) / (y))const int SIZE = 30;const int N = 4e5 + 10;const int M = 3e5 + 10;const int INF = 0x7f7f7f7f;const int MAX_WORD = 1e2 + 10;const double EPS = 1e-9;const int MOD = 20071027;int sz, lens, lent;int ch[N][SIZE];bool ed[N];long long d[M];char txt[M];char str[MAX_WORD];int newnode() { memset(ch[sz], 0, sizeof(ch[sz])); ed[sz] = false; return sz++;}void init() { memset(d, 0, sizeof(d)); sz = 0; newnode();}void insert() { int u = 0; for (int i = 0; i < lens; i++) { int v = str[i] - 'a'; if (!ch[u][v]) ch[u][v] = newnode(); u = ch[u][v]; } ed[u] = true;}void find(int s) { int u = 0; for (int i = s; i < lent; i++) { int v = txt[i] - 'a'; if (!ch[u][v]) return ; u = ch[u][v]; if (ed[u])//如果为某个模式串结尾 d[s] = (d[i + 1] + d[s]) % MOD; } if (ed[u])//如果该模式串本身到文本串结尾,则+1 d[s]++;}int main() { int i_case = 1; while (scanf("%s", txt) != EOF) { lent = strlen(txt); int n; scanf("%d", &n); init(); for (int i = 0; i < n; i++) { scanf("%s", str); lens = strlen(str); insert(); } for (int i = lent - 1; i >= 0; i--)//逆序 find(i); printf("Case %d: %lld\n", i_case++, d[0]); } return 0;}
0 0
- UVALive 3942Remember the Word(字典树 + 简单dp)
- UVALive - 3942 Remember the Word(字典树+dp)
- UVALive 3942 Remember the Word(字典树+dp)
- UVALive 3942 Remember the Word 字典树DP&&前缀树
- uvalive 3942 Remember the Word 字典树+dp
- uvalive 3942 Remember the Word (字典树+DP)
- UVALIVE 3942 Remember the Word 字典树
- uvaLive 3942 Remember the Word 字典树
- UVALive - 3942 Remember the Word(trie + dp)
- Remember the Word - UVaLive 3942 Trie树+dp
- UVALive 3942 Remember the Word(trie + dp)
- LA 3942 - Remember the Word 字典树 dp
- LA 3942 - Remember the Word 字典树+DP
- UVA 1401 & LA 3942 Remember the Word 字典树+DP
- LA 3942 Remember the Word(字典树/树上dp)
- LA 3942 Remember the Word——DP + 字典树
- LA3942 Remember the Word(字典树+DP)
- UVALive - 3942 Remember the Word (Trie)
- JNI 的初步了解
- addActionError() 与addFieldError (),addActionMessage()比较
- linux命令:mkdir
- Unity bundle的制作和使用
- 创业失败
- UVALive 3942Remember the Word(字典树 + 简单dp)
- 常用DDR和NandFlash型号
- VTD-XML——解析xml的最强武器
- Linux命令备忘实例(9)——参数代换xargs
- Oracle_启动报ora-27100:shared memory realm already exists
- uva 1632 阿里巴巴
- nodejs 笔记
- dig命令
- unity3d AssetBundle包加密