字典树(trie tree)
来源:互联网 发布:软件开发成本 人月 编辑:程序博客网 时间:2024/05/06 20:27
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
int i,j,k,len;
string str;char temp[15],temp1[15];
map <string,int> mymap;
while(gets(temp))
{
if(temp[0]=='/n') break;
len=strlen(temp);
if(len==0) break;
for(i=0;i<len;i++)//求出某个字符串的所有前缀,并用MAP存起来
{
for(j=0;j<=i;j++) temp1[j]=temp[j];temp1[j]='/0';
str.assign(temp1);
mymap[str]++;
}
}
while(scanf("%s",&temp)!=EOF)
cout<<mymap[temp]<<endl;//此时直接输出结果即可
return 0;
}
用MAP的特点是代码短,思路简单,很容易实现,但耗时大。下面给出trie版本的。
my code2:
#include<iostream>
using namespace std;
const int kind=26;//字母种类
struct Treenode//树的结点结构
{
int count;//这个附加变量在本题中记录遍历到该结点形成的字符串出现的次数,在不同题中可记录不同的内容。
Treenode *next[kind];//指向儿子结点
Treenode()//每个结点的初始化
{
count=1;
for(int i=0;i<kind;i++)
next[i]=NULL;
}
};
void insert(Treenode *&root,char *word)//向以root为根结点的树中插入串word
{
Treenode *location=root;
int i=0,branch=0;
if(location==NULL) {location=new Treenode();root=location;}
while(word[i])
{
branch=word[i]-'a';
if(location->next[branch]) location->next[branch]->count++;//如果该字符存在,串数量加1
else location->next[branch]=new Treenode();//如果不存在,建新结点
i++;
location=location->next[branch];
}
}
int search(Treenode *root,char *word)//查找,与插入类似
{
Treenode *location=root;
int i=0,branch=0,ans;
if(location==NULL) return 0;
while(word[i])
{
branch=word[i]-'a';
if(!location->next[branch]) return 0;
i++;
location=location->next[branch];
ans=location->count;
}
return ans;
}
int main()
{
char word[10];
char ask[10];
Treenode *root=NULL;
while(gets(word))
{
if(word[0]=='/0') break;
insert(root,word);
}
while(gets(ask))
cout<<search(root,ask)<<endl;
return 0;
}
上述代码中插入和查找可当模板来用了。。。
http://blog.csdn.net/zxjzxj521/article/details/4669130
- 字典树(trie tree)
- Trie-tree (字典树)
- Trie-Tree字典树
- 字典树(Trie Tree)
- 字典树 Trie Tree
- 数据结构--字典树(trie tree)
- 字典树(Trie tree)
- 字典树(Trie tree)
- 字典树(Trie tree)
- 字典树(Trie tree)
- 树学习 ---------字典树(Trie Tree)
- Trie(prefix tree,前缀树,字典树)
- zoj 3228 trie tree(字典树)
- 初识字典树(Trie Tree)
- 208. Implement Trie (Prefix Tree)字典树
- Implement Trie (Prefix Tree) 字典树
- [LeetCode] Implement Trie (Prefix Tree) 实现字典树(前缀树)
- LeetCode Implement Trie (Prefix Tree) 字典树/前缀树
- Oracle SQL Loader
- Oracle SQL的优化
- UVa Problem 704 Colour Hash (色彩缤纷游戏)
- Flash Recovery Area空间不足导致数据库不能打开或hang住 .
- MPLS VPN
- 字典树(trie tree)
- Jquery 和关于 复选框 的问题
- linux下挂载U盘过程
- POJ 1934 Trip DP
- ORA-06519: 检测到活动的自治事务处理,已经回退
- ArcGIS Flex API for 3D—简介
- 材料管理系统中发现的问题
- ArcGIS Flex API for 3D—Papervision3D
- hust 1342 (有上下界的最小流)