南陽acm290-動物園統計(字典樹)

 
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int max=0;
char ans[20];
struct node//結點
{
	int count;
	struct node *next[26];//每個結點有26個分支
};
struct node *root;//根結點
struct node *newset()
{
	struct node *p;
	p=(struct node *)malloc(sizeof(struct node));//動態分配內存
    for(int i=0;i<26;i++)
	{
		p->next[i]=NULL;//結點置空
	}
	p->count=0;//計數器的值置爲0
	return p;
}
void insert(char *s)//插入
{
	struct node *p;
    p=root;
	int len=strlen(s);
	for(int i=0;i<len;i++)
	{
		if(p->next[s[i]-'a']==NULL)//判斷是否爲空
			p->next[s[i]-'a']=newset();
         p=p->next[s[i]-'a'];
	}
	p->count++;
	if(p->count>max)
	{	max=p->count;
	strcpy(ans,s);//保存最長的字符串
	}
}
int main()
{
	int n;
	char chr[12];
	root=newset();
	scanf("%d",&n);
	while(n--)
	{
     scanf("%s",chr);
	 insert(chr);
	}
	printf("%s %d\n",ans,max);
	return 0;
}         
        


發佈了74 篇原創文章 · 獲贊 8 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章