首页 > 其他 > 详细

[Trie]hihoCoder 1014 Trie树

时间:2015-06-18 21:54:38      阅读:169      评论:0      收藏:0      [点我收藏+]

 

#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
  
using namespace std;
  
int t,n;
bool ok;
string str;
  
struct Trie 
{ 
    Trie *next[26]; 
    int num;
}; 
  
void insert(Trie * root ,string str){
    int len=str.length();
    Trie * p= root;
    for(int i=0;i<len;++i){
        if(p->next[ str[i]-‘a‘ ] ==NULL){
            Trie * temp=new Trie;
            temp->num=0;
            for(int j=0;j<26;++j){
                temp->next[j]=NULL;
            }
            p->next[ str[i]-‘a‘ ]=temp;
        }
        p=p->next[ str[i]-‘a‘ ];
        p->num++;
    }
    
}
void del(Trie * root){
    Trie*temp=root;
    for(int i=0;i<26;++i){
        if(temp->next[i]!=NULL){
            del(temp->next[i]);
        }
    }
    delete(root);
}
int cal(Trie* root,string str){
	int len=str.length();
	Trie* p = root;
	for(int i=0;i<len;++i){
		p=p->next[str[i]-‘a‘];
		if(p==NULL)return 0;
	}
	return p->num;
}
int main()
{

        Trie *root=new Trie;
        root->num=0;
        for(int i=0;i<26;++i){
            root->next[i]=NULL;
        }
        
        cin>>n;
        while(n--){
            cin>>str;
            insert(root,str);
        }
        cin>>n;
        while(n--){
            cin>>str;
            cout<<cal(root,str)<<endl;
        }
    return 0;
}          

  

[Trie]hihoCoder 1014 Trie树

原文:http://www.cnblogs.com/bruce27/p/4586815.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!