hiho-1014(c++)

20150202

题意:

字典树

代码:

#include 

using namespace std;

struct Tree{
    Tree *child[26];
    int num;
    Tree(){
        num = 0;
        for(int i = 0; i < 26; i++)
            child[i] = NULL;
    }
}*root;

void insertT(char s[]){
    Tree *node = root;
    node->num++;
    for(int i = 0; s[i]; i++){
        int j = s[i] - 'a';
        if(node->child[j] == NULL)
            node->child[j] = new Tree;
        node = node->child[j];
        node->num++;
    }
}

int searchT(char s[]){
    Tree *node = root;
    for(int i = 0; node && s[i]; ++i){
        int j = s[i] - 'a';
        node = node->child[j];
    }
    if(!node) return 0;
    return node->num;
}

int main()
{
    char s[12];
    int n,m;
    root = new Tree;
    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> s;
        insertT(s);
    }
    cin >> m;
    for(int i = 0; i < m; i++){
        cin >> s;
        cout << searchT(s) << endl;
    }
    return 0;
}


你可能感兴趣的:(C++,Algorithm)