動物統計加強版
第一次學會使用字典樹,調了4個小時~~,還有待提高。
http://acm.nyist.net/JudgeOnline/problem.php?pid=290
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
int lmax=0;
struct dictree
{
struct dictree *child[26];
int sum;
};
struct dictree *root;
int insert(char *temp)//動態創建樹
{
int len,i,j;
struct dictree *now,*newnode=NULL;
now=root;
len=strlen(temp);
for(i=0;i<len;i++)
{
if(now->child[temp[i]-'a']!=NULL)
now=now->child[temp[i]-'a'];
else
{
newnode=(struct dictree *)malloc(sizeof(struct dictree));
for(j=0;j<26;j++)//注意,這個j還得我很慘,我之前寫的是用變量i來進行賦值的。4個小時,不要再犯這種低級的錯誤.
newnode->child[j]=NULL;
newnode->sum=0;
now->child[temp[i]-'a']=newnode;
now=newnode;
}
}
now->sum++;
if(now->sum>lmax)
{
lmax=now->sum;
return 1;//表示換了
}
return 0;//表示沒有換
}
int main()
{
int i,n,t,len;
char temp[27],aid[27];
root=(struct dictree *)malloc(sizeof(struct dictree));
for(i=0;i<26;i++)
root->child[i]=NULL;
root->sum=0;
scanf("%d",&n);
while(n--)
{
scanf("%s",temp);
t=insert(temp);
if(t==1)
{
len=strlen(temp);
for(i=0;i<len;i++)
aid[i]=temp[i];
aid[i]='\0';
}
}
printf("%s %d\n",aid,lmax);
return 0;
}