做了几道Trie了,这个题做过之后,让我对Trie又有的许多新的认识,真正的理解了插入和查询的整个过程。
// File Name: hdu1251.cpp
// Author: Toy
// Created Time: 2013年05月08日 星期三 09时17分28秒
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cctype>
#include <cmath>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <utility>
#include <bitset>
#define L(x) x << 1
#define R(x) x << 1 | 1
using namespace std;
const int sigma_size = 26;
const int maxnode = 10 * 50000 + 10;
string s, tt;
bool flag;
struct Trie {
int ch[maxnode][sigma_size];
int val[maxnode];
int sz;
void clear ( ) { sz = 1; memset ( ch[0], 0, sizeof ( ch[0] ) ); }
int idx ( char c ) { return c - 'a'; }
void insert ( string s, int v ) {
int u = 0, n = s.length ();
for ( int i = 0; i < n; ++i ) {
int c = idx ( s[i] );
if ( !ch[u][c] ) {
memset ( ch[sz], 0, sizeof ( ch[sz] ) );
val[sz] = 0;
ch[u][c] = sz++;
}
val[u]++;
u = ch[u][c];
}
val[u]++;
}
void find ( string s ) {
flag = 1;
int u = 0, n = s.length ();
for ( int i = 0; i < n; ++i ) {
if ( s[i] == '\0' ) {
flag = 0;
break;
}
int c = idx ( s[i] );
if ( !ch[u][c] ) {
flag = 0;
break;
}
u = ch[u][c];
}
if ( flag ) cout << val[u] << endl;
else cout << "0" << endl;
}
}trie;
int main ( ) {
trie.clear();
while ( getline ( cin, s ) ) {
if ( s != "" ) trie.insert ( s, 1 );
else {
while ( getline ( cin, tt ) ) {
trie.find ( tt );
}
}
}
return 0;
}