现在的位置: 首页 > 综合 > 正文

字典树 统计难题

2012年03月30日 ⁄ 综合 ⁄ 共 694字 ⁄ 字号 评论关闭
#include <stdio.h>
#include
<string.h>
#include
<stdlib.h>

#define MAX 26

struct Trie {
Trie
*next[MAX];
int v;
};

Trie
*root;

void creattrie(char *str)
{
Trie
*p, *q;
int t, len, i, j;

p
= root;
len
= strlen(str);

for (i = 0; i < len; i++) {
t
= str[i] - 'a';
if(p->next[t] == NULL) {
q
= new Trie;
q
->v = 1;
for (j = 0; j < MAX; j++)
q
->next[j] = NULL;
p
->next[t] = q;
p
= p->next[t];
}
else {
p
->next[t]->v++;
p
= p->next[t];
}
// p->v = -1;
}
}

int findtrie(char *str)
{
int i, j, len, t;
Trie
*p;
p
= root;
len
= strlen(str);

for (i = 0; i < len; i++) {
t
= str[i] - 'a';
p
= p->next[t];
if(p == NULL)
return 0;

}
return p->v;
}

int main( )
{
int i;
char str[20],ch[20];
root
= new Trie;

for (i = 0; i < MAX; i++)
root
->next[i] = NULL;

while(gets(str) && str[0] != '\0'){
creattrie(str);
}
while(scanf("%s",ch) != EOF)
printf(
"%d\n",findtrie(ch));
return 0;
}



  

抱歉!评论已关闭.