Problem Description
有一个很长的由小写字母组成字符串。为了便于对这个字符进行分析,需要将它划分成若干个部分,每个部分称为一个单词。出于减少分析量的目的,我们希望划分出的单词越少越好。你就是来完成这一划分工作的。
Input
输入有多组数据,每组数据第1行为一个字符串(字符串长度不超过100)
第2行一个整数n,表示单词的个数。(n<=100)
第3至n+2行,每行列出一个单词。
Output
对于每组输入数据,输出一个整数,表示字符串可以被划分成的最少的单词数。
Sample Input
realityour
5
real
reality
it
your
our
Sample Output
有一个很长的由小写字母组成字符串。为了便于对这个字符进行分析,需要将它划分成若干个部分,每个部分称为一个单词。出于减少分析量的目的,我们希望划分出的单词越少越好。你就是来完成这一划分工作的。
Input
输入有多组数据,每组数据第1行为一个字符串(字符串长度不超过100)
第2行一个整数n,表示单词的个数。(n<=100)
第3至n+2行,每行列出一个单词。
Output
对于每组输入数据,输出一个整数,表示字符串可以被划分成的最少的单词数。
Sample Input
realityour
5
real
reality
it
your
our
Sample Output
2
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define Max 105
char str[Max][Max];
char article[Max];
struct node
{
int num;
node *child[26];
};
node *head;
int ans,t;
void insert(char s[])
{
node *root=head,*p;
int i,len=strlen(s);
for(i=0;i<len;i++)
{
int index=s[i]-'a';
if(root->child[index]==NULL)
{
p=(node *)calloc(1,sizeof(node));
p->num=0;
root->child[index]=p;
}
root=root->child[index];
}
root->num++;
}
node* find(node *root,char s[])
{
//printf("%s\n",s);
int i,len=strlen(s),index=0;
node *p=root;
for(i=0;i<len;i++)
{
index=s[i]-'a';
if(p->child[index]==NULL) return NULL;
else p=p->child[index];
}
return p;
}
void dfs(node *root,int cnt,int st)
{
if(root->num==1)
{
ans=(ans>cnt?cnt:ans);
return;
}
int i;
for(i=st+1;i<t;i++)
{
node *p=find(root,str[i]);
if(p!=NULL)
{
dfs(p,cnt+1,i);
}
else dfs(root,cnt,i);
}
}
int main()
{
//freopen("b.txt","r",stdin);
int i;
while(scanf("%s",article)==1)
{
ans=1<<16;
head=(node *)calloc(1,sizeof(node));
insert(article);
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%s",str[i]);
find(head,str[i]);
}
dfs(head,0,-1);
printf("%d\n",ans);
}
return 0;
}