1. 程式人生 > >HDU 1004字典樹

HDU 1004字典樹

#include<cstdio>
#include<cstring>
int n,nn,max,maxi;
char st[1100][20];
struct node{
    node *ch[26];int s;
    node(){
        for (int i=0;i<=25;++i) ch[i]=NULL;
        s=0;
    }
};
node *tree;
void insert1(char st[],int z){
    node *p=tree;
    for (int i=0;i<nn;++i) {
        if
(p->ch[st[i]-'a']==NULL) { node *p1=new node(); p->ch[st[i]-'a']=p1; } p=p->ch[st[i]-'a']; } p->s++; } void dfs(node *p){ node *p1; for (int i=0;i<=25;++i){ if (p->ch[i]!=NULL){ p1=p->ch[i]; if
(p1->s>0){ if (max<p1->s) max = p1->s; } dfs(p1); } } } int quest(char st[]){ node *p=tree; for (int i=0;i<nn;++i) { if (p->ch[st[i]-'a']->s) { return p->ch[st[i]-'a']->s; } p=p->ch[st[i]-'a'
]; } return 0; } int main(){ freopen("hdu1004.in","r",stdin); //freopen("hdu1004.out","w",stdout); while (1){ scanf("%d",&n); if (n==0) break; tree=new node(); for (int i=1;i<=n;++i){ scanf("%s",st[i]); nn=strlen(st[i]); insert1(st[i],i); } max=0; //dfs(tree); for (int i=1;i<=n;++i){ //printf("%d\n",quest(st[i])); int x=quest(st[i]); //printf("%d\n",x); if (max < x) { max = x; maxi = i; } } // printf("%d",max); printf("%s\n",st[maxi]); //printf("\n"); } return 0; }