-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.cpp
107 lines (91 loc) · 2.01 KB
/
trie.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
*/
//---------------------------------------------------------------------------
//--Include's----------------------------------------------------------------
#include "main.h"
//--Define's-----------------------------------------------------------------
//--Struct Define's----------------------------------------------------------
//--Vars---------------------------------------------------------------------
int score[8]={0, 0, 1, 2, 3, 5, 8, 13};
//--Functions----------------------------------------------------------------
trie::trie(trie *p, int ic, int d)
{
int i;
parent=p;
ichr=ic;
depth=d;
end=false;
for (i=0; i<26; i++) childs[i]=NULL;
}
trie::~trie()
{
int i;
for (i=0; i<26; i++) if (childs[i]!=NULL) delete childs[i];
}
void trie::add(int *ilist)
{
if (*ilist==-1)
{
end=true;
return;
}
if (childs[*ilist]==NULL) childs[*ilist]=new trie(this, *ilist, depth+1);
childs[*ilist]->add(ilist+1);
}
bool trie::known(int *ilist)
{
if (*ilist==-1)
{
if (end) return true;
return false;
}
if (childs[*ilist]==NULL) return false;
return childs[*ilist]->known(ilist+1);
}
int trie::knownn(int **ilist, int length)
{
if (depth==length)
{
if (end) return score[length];
return 0;
}
if (childs[**ilist]==NULL) return 0;
return childs[**ilist]->knownn(ilist+1, length);
}
void trie::print(char *buf)
{
int i;
if (end)
{
buf[depth]='\0';
printf("%s\n", buf);
}
for (i=0; i<26; i++)
{
if (childs[i]!=NULL)
{
buf[depth]='A'+i;
childs[i]->print(buf);
}
}
}
int trie::load_from_file(char *filename)
{
FILE *instr=fopen(filename, "r");
char buf[256];
int ibuf[256];
int i, l;
if (instr==NULL) return 0;
while (!feof(instr))
{
fgets(buf, 256, instr);
l=strlen(buf)-1;
if (l!=0)
{
for (i=0; i<l; i++) ibuf[i]=buf[i]-'A';
ibuf[l]=-1;
add(ibuf);
}
}
return 1;
}