字典树

#include <iostream>
#include <cstdio>
#include <string.h>
#include <malloc.h>
using namespace std;
struct Tire
{
  int count;
  struct Tire *tire[26];       
}*a;
void init()
{
       a=(Tire*)malloc(sizeof(Tire));
       for(int i=0;i<26;i++)
       a->tire[i]=NULL;
}
int insert(char ch[])
{
  int length=strlen(ch);
  Tire *head=a;
  int i,j,k;
  for(int i=0;i<length;++i)
  {
    k=(int)(ch[i]-97);
    if(head->tire[k]==NULL)
    {
      head->tire[k]=new Tire;
      head=head->tire[k];
      head->count=0;
      for(j=0;j<26;++j)
       head->tire[j]=NULL;                       
    }    
    else
     head=head->tire[k];
         
  }  
  head->count++;
  return head->count;  
}

int main()
{
    char s[10],ss[10];
    init();
    int n;
    scanf("%d",&n);
    int max=0,sum=0;
    while(n--)
    {
      scanf("%s",s);
      sum=insert(s); 
      if(sum>max)
      {
        strcpy(ss,s);
        max=sum;           
      }         
    }  
    printf("%s %d\n",ss,max);
}

         

你可能感兴趣的:(c,啊哈算法)