uva 1401 - Remember the Word

本文介绍了一种结合字典树和动态规划的算法实现方法,通过构建字典树存储字符串,并利用动态规划解决特定问题。文章包含完整的代码实现,演示了如何插入字符串到字典树中,以及如何进行查询。

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

一个简单的字典树上的dp;

代码:

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<queue>
 4 #define maxn 400000
 5 #define mod 20071027
 6 using namespace std;
 7 priority_queue<int,vector<int>,greater<int> >q;
 8 struct node
 9 {
10     bool f;
11     node *a[26];
12 } no[maxn];
13 int nonocount;
14 int d[maxn];
15 bool vis[maxn];
16 node *newnode()
17 {
18     node *p=no+nonocount++;
19     p->f=0;
20     for(int i=0; i<26; i++)
21         p->a[i]=NULL;
22     return p;
23 }
24 
25 void insert(char *t)
26 {
27     node *root=no;
28     int l=strlen(t);
29     for(int i=0; i<l; i++)
30     {
31         if(root->a[t[i]-'a']==NULL)
32             root->a[t[i]-'a']=newnode();
33         root=root->a[t[i]-'a'];
34     }
35     root->f=1;
36 }
37 char s[maxn],t[105];
38 int len;
39 void query(int w)
40 {
41     node *root=no;
42     for(int i=w; i<len; i++)
43     {
44         if(root->a[s[i]-'a']==NULL)break;
45         root=root->a[s[i]-'a'];
46         if(root->f)
47         {
48             d[i]+=d[w-1];
49             d[i]=d[i]%mod;
50             if(!vis[i+1])
51             {
52                 vis[i+1]=1;
53                 q.push(i+1);
54             }
55         }
56     }
57     while(!q.empty())
58     {
59         int v=q.top();
60         q.pop();
61         query(v);
62     }
63 }
64 
65 
66 int main()
67 {
68     int n,ca=1;
69     while(scanf("%s",s+1)!=EOF)
70     {
71         s[0]='#';
72         memset(d,0,sizeof d);
73         d[0]=1;
74         memset(vis,0,sizeof vis);
75         vis[1]=1;
76         nonocount=0;
77         node *p=newnode();
78         scanf("%d",&n);
79         for(int i=0; i<n; i++)
80         {
81             scanf("%s",t);
82             insert(t);
83         }
84         len=strlen(s);
85         query(1);
86         printf("Case %d: %d\n",ca++,d[len-1]%mod);
87     }
88     return 0;
89 }
View Code

 

转载于:https://www.cnblogs.com/yours1103/p/3396455.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值