hdu 1251(字典树找前缀个数)

/*

   问题如题目
       典型的字典树,可以当模板

     指针的运用;

     申请空间;

*/







#include <stdio.h>

#include <string.h>

#include <stdlib.h>

struct node

{

    struct node *child[26];//指针,先申请一个地址,后面用到再申请空间

    int num;

};

struct node *root;

void insert(char *temp)

{

    struct node *cur;

    cur = root;

    int len = strlen(temp);

    for(int i =0;i < len; i++)

    {

        if(cur->child[temp[i] - 'a'] != 0){

            cur = cur->child[temp[i] - 'a'];

            cur->num ++;

        }

        else{

                struct node *newnode = new struct node ; //***

                //申请空间 == newnode=(struct node *)malloc(sizeof(struct node));   



                cur->child[temp[i] - 'a'] = newnode;

                for(int j =0;j < 26; j++){

                    newnode->child[j] = 0;

                }

                newnode->num = 1;

                cur = newnode;

        }



    }

}



int find(char *temp)

{

    struct node *cur;

    cur = root;

    int len = strlen(temp);

    if(!len) return 0;          //***

    for(int i =0;i < len; i++)

    {

        if(cur->child[temp[i] - 'a']){

            cur = cur->child[temp[i] - 'a'];

        }

        else

            return 0;

    }

    return cur->num;

}





int main()

{

    int i,j,n,len;

    char temp[20];

    root=(struct node *)malloc(sizeof(struct node));   

    for(i =0;i < 26; i++)  

        root->child[i] = 0;



    while(gets(temp) && strcmp(temp,"")!=0)

    {

        insert(temp);        

    }

    while(scanf("%s",temp)!=EOF)

    {

        printf("%d\n",find(temp));

    }

    return 0;

}





你可能感兴趣的:(HDU)