初识字典树

    xiaoxiao2022-07-14  150

    输入

    第一行输入动物名字的数量N(1<= N <= 4000000),接下来的N行输入N个字符串表示动物的名字(字符串的长度不超过10,字符串全为小写字母,并且只有一组测试数据)。

    输出

    输出这些动物中最多的动物的名字与数量,并用空格隔开(数据保证最多的动物不会出现两种以上)。 样例输入

    10 boar pig sheep gazelle sheep sheep alpaca alpaca marmot mole 样例输出 sheep 3

    这道题应该属于字典树中的基础题吧,总算对字典树有了一个大体上的认识。。

    #include<string.h> #include<stdio.h> #include<stdlib.h> typedef struct node { int count; struct node *next[26]; }node; node *T;//头节点 int max; char pre[20]; node *newnode()//构造新节点 { node *q; int i; q=(node*)malloc(sizeof(node)); for(i=0;i<26;i++) q->next[i]=NULL; q->count=0; return q; } void search(char *s)//建立字典树 { node *p; int i,len,k; p=T; len=strlen(s); for(i=0;i<len;i++) { k=s[i]-'a'; if(p->next[k]==NULL) { p->next[k]=newnode();//建立节点 } p=p->next[k]; } p->count++; if(p->count>max) { max=p->count; strcpy(pre,s); } } int main() { int t,i; char s[15]; max=0; memset(pre,0,sizeof(pre)); T=(node*)malloc(sizeof(node)); T->count=0; for(i=0;i<26;i++) T->next[i]=NULL; scanf("%d",&t); while(t--) { scanf("%s",s); search(s); } printf("%s %d\n",pre,max); }
    最新回复(0)