WOJ1049-Words

来源:互联网 发布:wps vb编辑器下载 编辑:程序博客网 时间:2024/06/18 17:41

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.

样例输入

1flymouse4flyuphighmouse

样例输出

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)。


原创粉丝点击