hdu 1277Trie树

这题本来以为得DFA的,仔细审题以后发现,题目说每个关键字前4个字母不同(这意味着每个关键字结束的节点都是不同的),而且长度不超过60,马上醒悟,只要用所有的关键字建一棵Trie树,然后把主串跑一遍就可以了,复杂度为主串长度*60,肯定能过啊。。。

/*

 * hdu1277/win.cpp

 * Created on: 2012-11-6

 * Author    : ben

 */

#include <cstdio>

#include <cstdlib>

#include <cstring>

#include <cmath>

#include <ctime>

#include <iostream>

#include <algorithm>

#include <queue>

#include <set>

#include <map>

#include <stack>

#include <string>

#include <vector>

#include <deque>

#include <list>

#include <functional>

#include <numeric>

#include <cctype>

using namespace std;

const int child_num = 10;

const int MAXM = 60100;

const int MAXN = 10100;

char str[MAXM];

bool flags[MAXN];

const char base = '0';

typedef struct TrieNode {

    //子节点指针

    struct TrieNode *child[child_num];

    int num;

}TrieNode;

const int MAX_NODE_NUM = 300000;

TrieNode mymemory[MAX_NODE_NUM];

int cur_node_num = 0;

vector<int> ans;

inline TrieNode* newTrieNode() {

    //如需动态分配内存,则下句可改为TrieNode* node = new TrieNode();

    TrieNode* node = &mymemory[cur_node_num++];

    //初始化

    node->num = 0;

    memset(node->child, 0, sizeof(node->child));

    return node;

}

void insert_to_trie(TrieNode *root, const char *s, const int len, int num) {

    TrieNode *p = root;

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

        if (p->child[s[i] - base] == NULL) {

            p->child[s[i] - base] = newTrieNode();

        }

        p = p->child[s[i] - base];

    }

    p->num = num;

}

void work(TrieNode *p, char *s) {

    for(int i = 0; i < 60; i++) {

        if(p->num > 0) {

            ans.push_back(p->num);

            return ;

        }

        if(p->child[s[i] - base] == NULL) {

            return ;

        }

        p = p->child[s[i] - base];

    }

}

int main() {

#ifndef ONLINE_JUDGE

    freopen("data.in", "r", stdin);

#endif

    int M, N, t;

    scanf("%d%d", &M, &N);

    char temp[100];

    str[0] = 0;

    for(int i = 0; i < M; i++) {

        scanf("%s", temp);

        strcat(str, temp);

    }

    TrieNode *root = newTrieNode();

    for(int i = 0; i < N; i++) {

        scanf(" [Key No. %d] %s", &t, temp);

        insert_to_trie(root, temp, strlen(temp), t);

    }

    memset(flags, false, sizeof(flags));

    int len = strlen(str);

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

        work(root, str + i);

    }

    printf("Found key:");

    for(int i = 0, len = ans.size(); i < len; i++) {

        printf(" [Key No. %d]", ans[i]);

    }

    putchar('\n');

   return 0;

}

你可能感兴趣的:(trie)