字典树

hihocoder字典树

#include <iostream>
#include <string.h>
#include <string>
#include <algorithm>
using namespace std;

struct Node
{
    bool isLeaf;
    Node * next[26];
};

void Build(Node* root, string item)
{
    Node* p = root;
    int length = item.length();
    for (int i = 0; i < length; i++)
    {
        int id = item[i] - 'a';
        if (p->next[id] == NULL)
        {
            p->next[id] = new Node();
        }
        p = p->next[id];
    }
    p->isLeaf = true;
}

bool Check(Node* root, string item)
{
    Node* p = root;
    int length = item.length();
    for (int i = 0; i < length; i++)
    {
        int id = item[i] - 'a';
        if (p->next[id] == NULL)
        {
            return false;
        }
        p = p->next[id];
    }
    return p->isLeaf;
}

int main()
{
    int N;
    cin >> N;
    Node * root = new Node();
    string word;
    int result = 0;
    for (int i = 0; i < N; i++)
    {
        cin >> word;
        Build(root, word);
        reverse(word.begin(), word.end());
        result += Check(root, word) ? 1 : 0;
    }
    cout << result << endl;
    return 0;
}

点赞