您的位置:首页 > 其它

hiho1014: Trie树

2015-10-10 21:08 162 查看
Trie树,并不难理解,但带数组的结构体比较神奇也是字典树的精髓,感觉好厉害!

看了大神的代码,好赞!!

我是大神的trie树~

然而我的改了n多遍第一个样例总是2,不明白,求大神指点,唉,改了一下午,忧伤……

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cstring>
#include<cmath>
#define L 10+1
//每个单词的长度
using namespace std;

struct T{
int num;
T* next[26];
T(){
num=0;
int i;
for(i=0;i<26;i++)
next[i]=NULL;
}
}t;
void In(char str[]){
T* p=&t;
for(int i=0;str[i];i++){
int a=str[i]-'a';
if(p->next[a]==NULL)
p->next[a]=new T;
p=p->next[a];
p->num++;
}
}
int find(char str[]){
T* p=&t;
for(int i=0;str[i];i++){
int a=str[i]-'a';
if(p->next[a]==NULL)return 0;
p=p->next[a];
}
return p->num;
}
int main(){
int n,m;
char str[L];
for(scanf("%d",&n);n--;)
scanf("%s",str),In(str);
for(scanf("%d",&m);m--;)
scanf("%s",str),printf("%d\n",find(str));
return 0;
}
我是ac代码

以上是ac代码……以下是我的wa代码……心塞……

#include <iostream>
#include <string>
#include <stdio.h>
#include <stack>
#include <stdlib.h>
using namespace std;

#define max 26

typedef struct TrieNode
{
bool isStr;
int num=0;
struct TrieNode *next[max];   //儿子分支
}Trie;

void insert(Trie *root,const char *s)
{
if (root==NULL||*s=='\0') {
return;
}
int i;
Trie *p=root;
while (*s!='\0') {
if (p->next[*s-'a']==NULL) {
Trie *temp=(Trie *)malloc(sizeof(Trie));
for (i=0; i<max; i++) {
temp->next[i]=NULL;
}
temp->isStr=false;
temp->num++;
p->next[*s-'a']=temp;
p=p->next[*s-'a'];
}
else
{
p->num++;
p=p->next[*s-'a'];
}
s++;
}
p->isStr=true;   //单词结束的地方标记此处可以构成一个单词
}

int search(Trie *root,const char *s)
{
if (root==NULL||*s=='\0') {
return 0;
}
Trie *p=root;
int x=10000;
while (*s!='\0') {
x=p->num;
//cout<<x<<endl;
p=p->next[*s-'a'];
//cout<<*s<<endl;
if (p==NULL) {
return 0;
}
//x=p->num;
s++;
}
return x;
}

void del(Trie *root)
{
int i;
for (i=0; i<max; i++) {
if (root->next[i]!=NULL) {
del(root->next[i]);
}
}
free(root);
}

int main()
{
int i;
int n,m;
cin>>n;
Trie *root=(Trie *)malloc(sizeof(Trie));
for (i=0; i<26; i++) {
root->next[i]=NULL;
}
root->isStr=false;
root->num=0;
for (i=0; i<n; i++) {
char s[101];
scanf("%s",s);
//cout<<s<<endl;
insert(root, s);
}
Trie *r=root;
for (i=0; i<max; i++) {
if (r->next[i]!=NULL) {
cout<<i<<" ";
}
}
cout<<endl;
cout<<root->num<<endl;
cin>>m;
for (i=0; i<m; i++) {
char s[101];
scanf("%s",s);
cout<<search(root,s)<<endl;
}
del(root);
return 0;
}


痛痛痛!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: