ホームに戻る
Trie木

// Trie木は探索木です。
// 例えば、最大k文字からなる最長l文字のn個の文字列があります。
// O(nkl)でTrie木を作っておくとO(l)でその文字列があるかどうかを判定します。
// 見つかった場合に固有の値を設定したり得たりすることもできます。
// また、探索の途中においてもそこまでの文字列があるかを判定できます。
// Trie木は文字列以外の探索にも利用できます。

// 以下の例は26個の小文字アルファベットを使ったTrie木の例です。
// addで文字列を登録し関数fで探索を行っています。

#include <algorithm>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <list>

using namespace std;

typedef long long ll;

#define sz size()
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define all(c) (c).begin(), (c).end()
#define rep(i,a,b) for(ll i=(a);i<(b);++i)
#define clr(a, b) memset((a), (b) ,sizeof(a))
#define ctos(d) string(1,d)
#define print(x) cout<<#x<<" = "<<x<<endl;

#define MOD 1000000007

struct Trie {
  ll t;
  Trie* next[26];
  Trie() : t(0) {for (int i = 0; i < 26; i++) next[i] = (Trie*)0;}
};

Trie *root;

void add(string s){
  Trie *now = root;
  rep(i, 0, s.sz) {
    ll a = s[i] - 'a';
    if (now->next[a] == NULL) {
      now->next[a] = new Trie();
    }
    now = now->next[a];
  }
  now->t += 1;
}

ll f(string s) {
  ll ret = 0;
  Trie *now = root;
  rep(i, 0, s.sz) {
    ll a = s[i] - 'a';
    if (now->next[a] == NULL)break;
    now = now->next[a];
    ret += now->t;
  }
  return ret;
}

int main() {
  string s[4] = {"abc", "abcd", "a", "abd"};
  root = new Trie();
  rep(i, 0, 4) {
    add(s[i]);
  }
  cout << f("abcd") << endl;
  return 0;
}
inserted by FC2 system