WOJ1049-Words

In the courses of C programming, the teacher assigns an amusing problem to Flymouse:
A string consists of several small lowercases. You should divide the string into several parts. Each part is called a word. The teacher hopes that
the number of words is as small as possible. Of course, she will give you a ?dictionary?. Flymouse is puzzled with this problem for a long time.
So he asks for your help again ^_^

输入格式

The input includes several cases. The first line contains a single integer T, the number of test cases. For each test case, the first line contains
the string you are to divide, whose length is not larger than 256, the second line contains a single integer N (1<=N<=100), The following N lines
are the dictionary, which the teacher gives to you. Every line contains a word.You can assure the string in the first line of each test case can
always be divided into several words in the directory.

输出格式

There should be one output line per test case containing the minimum number of parts.

样例输入

1
flymouse
4
fly
up
high
mouse

样例输出

2

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
bool is_houzhui(char *s,char *a,int t){
    int i,j;
    for(i=t,j=strlen(a)-1;j>=0;i--,j--){
        if(s[i]!=a[j]) break;
    }
    if(j<0) return true;
    else return false;
}
int main(){
    int ncase,n,i,j;
    char s[257],a[101][257];
    cin>>ncase;
    while(ncase--){
        getchar();
        cin>>s;
        cin>>n;
        getchar();
        for(i=0;i<n;i++) cin>>a[i];
        int dp[256];
        dp[0]=0; 
        for(i=0;i<strlen(s);i++){
            dp[i+1]=dp[i]+1;
            for(j=0;j<n;j++)
                if(strlen(a[j])<=i+1)
                    if(is_houzhui(s,a[j],i))
                    	dp[i+1]=min(dp[i+1],dp[i-strlen(a[j])+1]+1);
        }
        cout<<dp[strlen(s)]<<endl;
    }
    return 0;
}
//dp[i]表示以i结尾最少可以由多少个单词构成,如果单词j是i的后缀, 
//那么dp[i]=min(dp[i],dp[i-length(word[j])]+1)。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值