Tries 树

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;
    }
}

 

转载于:https://www.cnblogs.com/xiaoshanshan/p/4298495.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值