字典树

 

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

const int kind = 26;
struct node{
    int num;
    bool terminal;
    node *next[26];
    node(){
        num = 1;
        terminal = false;
        memset(next, 0, sizeof(next));
    }
};

string s1, s2;

void Insert(node *root, string s1){
    node *p = root;
    int index;
    int len = s1.length();
    for(int i = 0; i < len; i++){
        index = s1[i] - 'a';
        if(p -> next[index] == NULL){
            p -> next[index] = new node();
        }
        else{
            p -> next[index] -> num++;
        }
        p = p -> next[index];
    }
    p ->terminal = true;
}

int Find(node *root, string s2){
    node *p = root;
    int i, index;
    int len = s2.length();
    for(i = 0; i < len; i++){
        index = s2[i] - 'a';
        if(p->next!=NULL){
            if(i == len - 1){
                return p->next[index]->num;
            }
        }
        else{
            return 0;
        }
        p = p->next[index];
    }
    return 0;
}

int main()
{
    node *root = new node();
    while(getline(cin, s1) && !s1.empty()){
        Insert(root, s1);
    }
    while(getline(cin, s2)){
        int k = Find(root, s2);
        printf("%d\n", k);
    }
    return 0;
}


 

你可能感兴趣的:(字典树)