HDU-2846Repository(字典树)

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;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值