码迷,mamicode.com
首页 > 其他好文 > 详细

Tries 树

时间:2015-02-24 10:15:55      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

head 头指针

#include <map>
#include <set>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <complex>
#include <cstring>
#include <iostream>
#include <algorithm>

#define REP(i,N) for (int i = 0;i < (N);i++)
#define REP_1(i,N) for (int i = 1;i < (N);i++)
#define REP_2(i,be,en) for (int i = (be);i < (en);i++)
#define DWN(i,N) for (int i = (N);i >= 0;i--)
#define DWN_1(i,N) for (int i = (N);i >= 1;i--)
#define DWN_2(i,en,be) for (int i = (en);i >= (be);i--)
#define INF 0x3f3f3f3f
#define MAXN 28
#define FR(N) freopen((N),"r",stdin)
#define FW(N) freopen((N),"w",stdout)
#define GETS(ch) fgets((ch),MAXN,stdin);
using namespace std;

typedef long long LL;
typedef map<string,int> MINT;
typedef vector<int> VINT;
int n,m;
char ch[MAXN];

class Node {
    public:
        char c;
        int num[26];
        Node* next[26];
        Node() {
            REP(i,26) {
                next[i] = NULL;
                num[i] = 0;
            }
        }
} *head;

void Insert(Node* head,char* s) {
    int len = strlen(s) - 1;
    Node* temp = head;
    int i = 0;
    while (i < len) {
        while (i < len && temp -> next[s[i] - a] != NULL) {
            temp -> next[s[i] - a] -> num[s[i] - a]++;
            temp = temp -> next[s[i++] - a];
        }
        if (i == len) break;
        Node* q = new Node;
        q -> c = s[i];
        q -> num[s[i] - a] = 1;
        temp = temp -> next[s[i] - a] = q;
        i++;
    }
}

int Find(Node* head,char* s) {
    int len = strlen(s) - 1;
    int i = 0;
    while (i < len) {
        if (head -> next[s[i] - a] == NULL) return 0;
        else head = head -> next[s[i++] - a];
    }
    return head -> num[s[i - 1] - a];
}

int main () {
    //FR("1.txt");
    cin >> n;
    getchar();
    head = new Node;
    REP(i,n) {
        GETS(ch);
        Insert(head,ch);
    }
    cin >> m;
    getchar();
    REP(i,m) {
        GETS(ch);
        cout << Find(head,ch) << endl;
    }
}

 

Tries 树

标签:

原文地址:http://www.cnblogs.com/xiaoshanshan/p/4298495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!