summaryrefslogtreecommitdiffstats
path: root/04-algorithms_on_strings/01-suffix_trees/01-trie/trie.cpp
blob: d5f9483d25956bbe5b01107d3d49167f61fe4430 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <string>
#include <iostream>
#include <vector>
#include <map>

using std::map;
using std::vector;
using std::string;

typedef map<char, int> edges;
typedef vector<edges> trie;

trie build_trie(vector<string> & patterns) {
  trie t;

  size_t node;
  size_t n = 1;
  t.push_back(edges());

  for (size_t i = 0; i < patterns.size(); i++) {
      node = 0;
      const string& pattern = patterns[i];
      for (size_t j = 0; j < pattern.size(); j++) {
          char c = pattern[j];
          int next = t[node][c];
          if (next != 0) {
              node = next;
          } else {
              t[node][c] = n;
              node = n;
              t.push_back(edges());
              n += 1;
          }
      }
  }
  return t;
}

int main() {
  size_t n;
  std::cin >> n;
  vector<string> patterns;
  for (size_t i = 0; i < n; i++) {
    string s;
    std::cin >> s;
    patterns.push_back(s);
  }

  trie t = build_trie(patterns);
  for (size_t i = 0; i < t.size(); ++i) {
    for (const auto & j : t[i]) {
      std::cout << i << "->" << j.second << ":" << j.first << "\n";
    }
  }

  return 0;
}