poj 1598 Excuses, Excuses! trie

 思路:

把所有的单词存到字典树中,然后把句子中的字母全改成小写的,就剥离句子中的单词,在字典树中查找

View Code
#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

struct trie{
int flag;
char ch;
trie *next[26];
trie()
{
flag=0;
memset(next,0,sizeof(next));
}
};

int Max,ar[25];
char s[100],str[25][100];

void init(trie *root)
{
int x,i;
trie *p=root;
for (i=0;s[i];i++)
{
x=s[i]-'a';
if(p->next[x]==NULL)p->next[x]=new trie;
p=p->next[x];
}
p->flag=1;
}

int judge(char *tmp,trie *root)
{
int x,i;
trie *p=root;
for (i=0;tmp[i];i++)
{
x=tmp[i]-'a';
if(p->next[x]==NULL)return 0;
p=p->next[x];
}
return p->flag;
}

void solve(int k,trie *root)
{
int i,j,sum,len=strlen(str[k]);
char tmp[100],t[100];
strcpy(t,str[k]);
for (i=0;i<len;i++)
{
if(t[i]>='A'&&t[i]<='Z')
t[i]+=32;
}
i=j=sum=0;
while (i<len)
{
if(t[i]>='a'&&t[i]<='z')
{
while(t[i]>='a'&&t[i]<='z')
tmp[j++]=t[i++];
tmp[j]='\0';
sum+=judge(tmp,root);
j=0;
}
i++;
}
ar[k]=sum;
if(sum>Max)Max=sum;
}

int main()
{
int n,m,i,l=1;
while (scanf("%d%d",&n,&m)!=EOF)
{
trie *root=new trie;
Max=-1;
for (i=0;i<n;i++)
{
scanf("%s",s);
init(root);
}
getchar();
for (i=0;i<m;i++)
{
gets(str[i]);
solve(i,root);
}
printf("Excuse Set #%d\n",l++);
for (i=0;i<m;i++)
{
if(ar[i]==Max)
printf("%s\n",str[i]);
}
printf("\n");
}
return 0;
}



posted @ 2011-11-16 18:52  104_gogo  阅读(228)  评论(0编辑  收藏  举报