UVALive 3942 Remember the Word(字典树 + 简单dp)
2015-09-09 00:04
423 查看
题目链接: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]。
代码:
题意:给定文本串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 [SIZE]; bool ed ; 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; }
相关文章推荐
- 用python求回数
- C#中的浅复制和深复制
- Nginx 学习笔记(一)
- 程序员应该扪心自问的10个问题
- 以身说法——卓天网络教你为什么做全网营销,怎么做好全网营销
- C#实现在线更新软件
- 定制Ubuntu LiveCD
- Ubuntu12.04安装JDK1.7
- Ubuntu 14.04编译安装Apache
- Ubuntu 14.10下编译安装MySQL 5.6.23
- JSP小数取整
- linux 服务器架设
- [苏州园区腾飞创新园/微往招聘]Java高级工程师、IOS研发工程师、Android研发工程师招聘!
- iOS textView 高度自适应
- 网站代码优化--HTML代码的6基本写法教程
- 浅析为什么要用企业网站模板建站
- mac os安装xcode时的问题
- Json转换为java对象
- centos win xp双系统 安装手记 9660 grldr U盘安装
- 使用Dom4j解析XML