数据结构--字典树(trie tree)
来源:互联网 发布:小米盒子软件 2017 编辑:程序博客网 时间:2024/05/21 15:38
#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;
}
上述代码中插入和查找可当模板来用了。。。
- 数据结构--字典树(trie tree)
- 字典树(trie tree)
- Trie-tree (字典树)
- Trie-Tree字典树
- 字典树(Trie Tree)
- 字典树 Trie Tree
- 字典树(Trie tree)
- 字典树(Trie tree)
- 字典树(Trie tree)
- 字典树(Trie tree)
- 数据结构001 - Trie树(Trie tree)
- 树学习 ---------字典树(Trie Tree)
- Trie(prefix tree,前缀树,字典树)
- zoj 3228 trie tree(字典树)
- 初识字典树(Trie Tree)
- 208. Implement Trie (Prefix Tree)字典树
- Implement Trie (Prefix Tree) 字典树
- 数据结构 - Trie树(字典树)
- sqlite3 学习 记录
- 更改电源管理方式
- VS2005快捷键大全
- MFC For WinCE不支持的类
- 关于pixel shaders ,vertex shaders,以及HLSH杂谈
- 数据结构--字典树(trie tree)
- 更改盘符
- fso获取图片宽度和高度的类,支持JPG,GIF,PNG,BMP
- 修改BOOT文件。更改系统启动菜单的时间
- Asp.Net 控件开发之资源文件处理
- 关闭IDE通道检测
- 关闭某些端口.
- 随写
- 什么是嵌入式编程,什么是ARM 如何学习