Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 102400/204800 K (Java/Others)
Total Submission(s): 18471 Accepted Submission(s): 6036
一道挺好的学习字典树的题、这里我在做题过程中遇到了这样的几个问题,也许大家会跟我犯一样的毛病:
1、PE、在有gets和scanf同时使用的时候,由于某些原因自动输出一个换行符、getchar可解决之。
2、TLE、MLE、尝试换成C++提交、尝试开大数组,这里测试数据是很令人心酸的。(也别过分离谱的开大数组)
3、WA、这里我提供一组数据,也许你就WA在这里:
START
from fiwo
hello difh
mars riwosf
earth fnnvk
like fiiwj
END
START
difh, i'm fiwo riwosf.
i fiiwj fnnvk!fn f fnn
END
这里先详解处理输入部分:
while(~scanf("%s",b))
{
if(strcmp(b,"START")==0)continue;
if(strcmp(b,"END")==0)break;
scanf("%s",a);
creat(a);//用a来找b
}
getchar();
while(gets(c))
{
if(strcmp(c,"START")==0)continue;
if(strcmp(c,"END")==0)break;
memset(str,'\0',sizeof(str));
for(int i=0;i
然后强调一下刚才说的第三点如何处理、字典树的作用是查找前缀、如果只找到了前缀就输出的话,是一定会wa的、所以我们这里在初始化的时候,加上一个标记变量,在creat的时候的最后一个字母处给标记赋值,当find的时候 ,如果查到的地方的标记有赋值,那么就输出,否则就相当于没有找到、
同时,在给标记赋值的同时,给节点strcpy一下映射的单词、
这里贴上处理代码:
void creat(char *str)
{
int len=strlen(str);
tree *p=&root,*q;
for(int i=0;inext[id]==NULL)
{
q=(tree *)malloc(sizeof(root));
for(int j=0;j<26;j++)
{
q->next[j]=NULL;
}
p->next[id]=q;
}
p=p->next[id];
if(i==len-1)//如果creat到了最后一个字母;
{
p->flag=1;//标记上为1
strcpy(p->la,b);//strcpy一下b
}
}
}
int find(char *str)
{
int len=strlen(str);
tree *p=&root;
for(int i=0;inext[id];
if(p==NULL)
return 0;
}
if(p->flag==1)//光找到前缀是不行的。
printf("%s",p->la);
else
return 0;
return 1;
}
然后是完整的AC代码:
#include
#include
#include
#include
using namespace std;
#define maxn 26//只包含小写字母、
typedef struct tree
{
int flag;
tree *next[maxn];
char la[30];
}tree;
tree root;
char b[10000000];
char c[10000000];
char str[1000];
void creat(char *str)
{
int len=strlen(str);
tree *p=&root,*q;
for(int i=0;inext[id]==NULL)
{
q=(tree *)malloc(sizeof(root));
for(int j=0;j<26;j++)
{
q->next[j]=NULL;
}
p->next[id]=q;
}
p=p->next[id];
if(i==len-1)
{
p->flag=1;
strcpy(p->la,b);
}
}
}
int find(char *str)
{
int len=strlen(str);
tree *p=&root;
for(int i=0;inext[id];
if(p==NULL)
return 0;
}
if(p->flag==1)
printf("%s",p->la);
else
return 0;
return 1;
}
int main()
{
char a[20];
for(int i=0;i<26;i++)
{
root.flag=0;
root.next[i]=NULL;
}
while(~scanf("%s",b))
{
if(strcmp(b,"START")==0)continue;
if(strcmp(b,"END")==0)break;
scanf("%s",a);
creat(a);
}
getchar();
while(gets(c))
{
if(strcmp(c,"START")==0)continue;
if(strcmp(c,"END")==0)break;
memset(str,'\0',sizeof(str));
for(int i=0;i