hihoCoder1014 Trie树 [Trie]

Trie模板题
不同的是在建树时同时统计出现次数
模板请看
https://github.com/yyecust/icpctemplate/blob/master/字符串.md#trie

#include <bits/stdc++.h>
using namespace std;
int nextInt()
{
  int x;
  scanf("%d\n", &x);
  return x;
}
string nextLine()
{
  string s;
  getline(cin, s);
  return s;
}
//Trie
const int R = 26;
struct Node
{
  Node(int v) {
    memset(ch, 0, sizeof(ch));
    val = v;
  }
  int ch[R];
  int val;
};
/*
void put(string, int) 将string插入Trie 附加信息为int
int get(string) 返回string的附加信息
void print() 打印Trie
*/
struct Trie {
  vector<Node> tree;
  Trie() {
    Node root(0);
    tree.push_back(root);
  }
  int idx(char ch) {
    return ch - 'a';
  }
  void put(string s)
  {
    int u = 0, n = s.size();
    for (int i = 0; i < n; i++) {
      int c = idx(s[i]);
      if (!tree[u].ch[c]) {
        tree[u].ch[c] = tree.size();
        tree.push_back(Node(0));
      }
      u = tree[u].ch[c];
      tree[u].val++;
    }
  }
  int get(string s) {
    int u = 0;
    for (int i = 0; i < s.size(); i++) {
      int c = idx(s[i]);
      if (!tree[u].ch[c]) return false;
      u = tree[u].ch[c];
    }
    return tree[u].val;
  }
  void print() {
    for (int i = 0; i < tree.size(); i++) {
      for (int j = 0; j < R; j++) {
        cout << tree[i].ch[j] << ' ';
      }
      cout << endl;
    }
  }
};
int main()
{
  //freopen("in.txt", "r", stdin);
  int n = nextInt();
  Trie trie;
  while (n--) {
    string s = nextLine();
    trie.put(s);
  }
  int m = nextInt();
  while (m--) {
    string s = nextLine();
    cout << trie.get(s) << endl;
  }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值