UVA Live-3942 Remember the Word(trie树入门题)

【题目链接】
http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=22109

【解题报告】
trie树入门题目。我们知道给定字符串和给定的S个单词,求把这个字符串分解成若干个单词的方案数。
不难想到递推求解。
dp[i]表示text[i..LEN]这个字符串可以分解成若干个单词的方案数

    dp[i]=sum( dp[i+len(x)] )(x表示一个可以作为i~LEN的前缀的单词)

初始化使dp[len]=1,表示如果字符串text[i..LEN]可以表示为一个单词时,方案数为1.

如何查找单词前缀?可以预处理单词,构造一颗trie树,保存的结点信息为单词长度,然后枚举字符串的数位i,遍历trie树查找即可。

【参考代码】

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int mod=20071027;
const int maxnode=4*1e5+10;

char text[300000+10];
int n;
int dp[300000+10];
vector<int>P;

struct TRIE{
    int ch[maxnode][26];
    int val[maxnode];
    int sz;
    void clear(){ sz=1; memset( ch,0,sizeof(ch) ); }
    int idx( char c){ return c-'a'; }

    void insert( char* s, int v )
    {
        int L=strlen(s),u=0;
        for( int i=0; i<L; i++ )
        {
            int c=idx(s[i]);
            if( !ch[u][c] )
            {
                val[sz]=0;
                ch[u][c]=sz++;
            }
            u=ch[u][c];
        }
        val[u]=v;
    }

    void find_pre( const char* S )
    {
        int L=strlen(S),u=0;
        for( int i=0; i<L; i++ )
        {
            if(S[i]=='\0')break;
            int c=idx(S[i]);
            if(!ch[u][c])break;
            if(val[ch[u][c]] )P.push_back(val[ch[u][c]]);
            u=ch[u][c];
        }
    }

}trie;


int main()
{
      int kase=0;
    while(~scanf("%s",text))
    {
        scanf("%d",&n);
        trie.clear();
        memset( dp,0,sizeof(dp) );
        for( int i=1; i<=n;i++ )
        {
            char word[100+10];
            scanf("%s",word);
            int v=strlen(word);
            trie.insert( word, v );
        }
        int L=strlen(text);
        dp[L]=1;
        for( int i=L-1; i>=0; i-- )
        {
            P.clear();
            trie.find_pre( text+i );
            for( int j=0; j<P.size(); j++ )
            {
                dp[i]=(dp[i]+dp[i+P[j]])%mod;
            }
        }
        printf("Case %d: %d\n",++kase,dp[0]);
    }

    return 0;
}
微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码 微信小程序毕业设计期末大作业项目源码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值