标签:数据结构-字典树
banana band bee absolute acm ba b band abc
2 3 1 0
#include <iostream> #include <cstdio> #include <vector> #include <cstring> #include <string> using namespace std; struct edge{ int u , v , letter , sum; edge(int a = 0 , int b = 0 , int c = 0 , int d = 0){ u = a , v = b , letter = c , sum = d; } }; vector<edge> e; vector<int> head , next; void add(int u , int v , int letter , int sum){ e.push_back(edge(u , v , letter , sum)); next.push_back(head[u]); head[u] = next.size()-1; head.push_back(-1); } void addLibrary(string s){ int u = 0 , index = 0; while(index < s.length()){ int Next = head[u]; while(Next != -1){ if(e[Next].letter == s[index]-'a') break; Next = next[Next]; } if(Next == -1) break; e[Next].sum++; index++; u = e[Next].v; } while(index < s.length()){ add(u , head.size() , s[index]-'a' , 1); index++; u = head.size()-1; } } int query(string s){ int u = 0 , index = 0 , Next; while(index < s.length()){ Next = head[u]; while(Next != -1){ if(e[Next].letter == s[index]-'a') break; Next = next[Next]; } if(Next == -1) return 0; index++; u = e[Next].v; } return e[Next].sum; } int main(){ string dic; head.push_back(-1); while(getline(cin , dic)){ if(dic.length() == 0) break; addLibrary(dic); } while(cin >> dic){ printf("%d\n" , query(dic)); } return 0; }
标签:数据结构-字典树
原文地址:http://blog.csdn.net/u011836218/article/details/32727289