您的位置:首页 > 其它

字典树模板

2015-09-06 18:34 344 查看
字典树

这一个比较简单 现在回顾也挺简单

直接给出模板 有什么不会的直接去模板里理解

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

struct Node {
Node *next[26];
int cnt;
Node() {
for(int i = 0; i < 26; i++) {
next[i] = NULL;
}
cnt = 0;
}
}root;

void add(char *s) {
Node *p = &root;
for(int i = 0; s[i]; i++) {
if(p -> next[s[i] - 'a'] == NULL) {
p -> next[s[i] - 'a'] = new Node();
}
p = p -> next[s[i] - 'a'];
p -> cnt++;
}
}

int cal(char *s) {
Node *p = &root;
for(int i = 0; s[i]; i++) {
if(p -> next[s[i] - 'a'] == NULL) {
return 0;
}
p = p -> next[s[i] - 'a'];
}
return p -> cnt;
}

void Free(Node *p) {
for(int i = 0; i < 26; i++) {
if(p -> next[i] != NULL) {
Free(p -> next[i]);
}
}
free(p);
}

char s[15];
int main() {
while(gets(s)) {
if(strlen(s) == 0) {
break;
}
add(s);
}
while(EOF != scanf("%s",s)) {
printf("%d\n",cal(s));
}
Node *p = &root;
//    free(p);
}


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