下午的时候我和yyf已经放弃了这道题,结果吃完饭的时候gby告诉我们他把这道题A了。他看错了数据,已经有思路了没说出来……
其实我们仨都把数据看成十万了。
这道题只有一个测试数据,结果内存消耗竟然快6WK。我在结构体内部申请的指针开到三十就MLE了,开到26勉勉强强过了。
思路:把每一个单词都看成ln(单词的长度)个单词,依次去掉第一位加入树中统计,为了防止统计多次(比如说:ababab),在结构题内加了一个id标记,标记这个节点的x值上次更新时是在第几个单词的,如果不同,x++,如果相同就跳过。
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int mark[30];
struct node
{
node *a[26];
int x;
int id;
};
node *root;
void InsertTree(char *ss,int id)
{
node *cur;
node *s;
cur=root;
while(*ss!='\0')
{
int temp=*ss-'a';
if(cur->a[temp]==NULL)
{
s=(node *)malloc(sizeof(node));
memset(s->a,0,sizeof(s->a));
s->x=1;
s->id=id;
cur->a[temp]=s;
}
cur=cur->a[temp];
if(cur->id!=id)
{
cur->x++;
cur->id=id;
}
ss++;
}
return ;
}
int FindTree(char *ss)
{
int i,ln;
node *cur;
cur=root;
ln=strlen(ss);
for(i=0;i<ln;i++)
{
int temp;
temp=ss[i]-'a';
if(i==ln-1)
{
if(cur->a[temp]==NULL)
return 0;
else
return cur->a[temp]->x;
}
else if(cur->a[temp]!=NULL)
cur=cur->a[temp];
else
return 0;
}
return 0;
}
int main()
{
int n;
scanf("%d",&n);
getchar();
char s[25];
root=(node *)malloc(sizeof(node));
memset(root->a,0,sizeof(root->a));
root->id=0;
root->x=0;
int j=1;
while(n--)
{
gets(s);
j++;
int ln;
ln=strlen(s);
int i;
for(i=0;i<ln;i++)
InsertTree(s+i,j);
}
int m;
scanf("%d",&m);
getchar();
while(m--)
{
gets(s);
printf("%d\n",FindTree(s));
}
return 0;
}