HDU 1251 统计难题

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1251

解题思路:

一个简单的字典树问题。

实现代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;

const int N=27;

struct node{
    int cnt;
    node* childs[N];
    node(){
        cnt=0;
        for(int i=0;i<N;i++)
            childs[i]=NULL;
    }
};

node *root=new node();
node *current,*newnode;

void insert(char *str){
    current=root;
    for(int i=0;i<strlen(str);i++){
        int m=str[i]-'a';
        if(current->childs[m]!=NULL){
            current=current->childs[m];
            ++(current->cnt);
        }else{
            newnode=new node;
            ++(newnode->cnt);
            current->childs[m]=newnode;
            current=newnode;
        }
    }
}

int search(char *str){
    current=root;
    for(int i=0;i<strlen(str);i++){
        int m=str[i]-'a';
        if(current->childs[m]==NULL)
            return 0;
        current=current->childs[m];
    }
    return current->cnt;
}

int main()  
{  
    char str[20];  
    while(gets(str),strcmp(str,""))  
    insert(str);  
    while(gets(str)!=NULL)  
    printf("%d
",search(str));  
    return 0;  
}  
原文地址:https://www.cnblogs.com/IKnowYou0/p/6654472.html