TLE状态
#include <iostream>
#include <string>
#include <fstream>
#include <set>
class dr_tree
{
private:
typedef struct node
{
bool flag;
node* next[26];
node()
{
flag=false;
for(int i=0;i!=26;i++){
next[i]=NULL;
}
}
} node_t;
public:
dr_tree()
{
root_=new node_t();
}
bool insert(std::string& str)
{
node_t* n_tmp=root_;
int idx;
int size_=str.size();
for(int i=0;i!=size_;i++){
idx=str[i]-'a';
if(n_tmp->next[idx]==NULL){
n_tmp->next[idx]=new node_t();
}
n_tmp=n_tmp->next[idx];
}
n_tmp->flag=true;
return true;
}
int query(std::string& str)
{
int num(0);
node_t* n_tmp1=root_;
node_t* n_tmp2=query(n_tmp1,str,num);
query_set_.clear();
return num;
}
~dr_tree()
{
}
private:
node_t* query(node_t* n,std::string &str,int& num)
{
if(n==NULL){
return NULL;
}
bool flag=false;
node_t* tmp;
int num_tmp(0);
for(int i=0;i!=26;i++){
if((n->next[i]!=NULL)&&(i+'a'==str[0])){
if((tmp=test_str(n->next[i],str))!=NULL){
query(tmp,num_tmp);
num+=num_tmp;
}
}
query(n->next[i],str,num);
}
return NULL;
}
node_t* test_str(node_t* n,std::string & str)
{
int idx;
for(int i=1;i!=str.size();i++){
idx=str[i]-'a';
if(n->next[idx]!=NULL){
n=n->next[idx];
}else{
return NULL;
}
}
return n;
}
int query(node_t* n,int & num)
{
if(n==NULL){
return 0;
}
if(n->flag==true){
if(query_set_.insert(n).second){
num++;
}
}
for(int i=0;i!=26;i++){
query(n->next[i],num);
}
}
node_t* root_;
std::set<node_t*> query_set_;
};
int p,q;
std::string str;
dr_tree tree;
int main()
{
//std::fstream std::cin("1.txt");
std::cin>>p;
for(int i=0;i!=p;i++){
std::cin>>str;
tree.insert(str);
}
std::cin>>q;
for(int i=0;i!=q;i++){
std::cin>>str;
std::cout<<tree.query(str)<<std::endl;
}
}