-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.cpp
More file actions
95 lines (87 loc) · 2 KB
/
Trie.cpp
File metadata and controls
95 lines (87 loc) · 2 KB
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
// M M Mehedi Hasan
// From BUBT
#include<bits/stdc++.h>
#define maxl 1020
using namespace std;
int state;
struct node
{
int cnt=0,length=0;
node* next[65];
bool endmark;
node()
{
endmark=false;
for(int i=0; i<=52; i++) next[i]=NULL;
}
} *Tree;
void insertt(string s, int len)
{
node* curr=Tree;
for(int i=0; i<len; i++)
{
int path=0;
if(s[i]>='a' &&s[i]<='z') path=( (int)s[i]-'a'); // 0 to 25
else path=( (int)s[i]-'A')+26; // 26 to start
if(curr->next[path] == NULL)
{
curr->next[path]=new node();
curr=curr->next[path];
curr->length= i+1;
}
else curr=curr->next[path];
}
curr->endmark=true;
curr->cnt++;
}
bool searching(string s, int len )
{
node *curr=Tree;
for(int i=0; i<len; i++)
{
int path=0;
if(s[i]>='a' &&s[i]<='z') path=( (int)s[i]-'a'); //0 to 25
else path=( (int)s[i]-'A')+26; // 26 to start
if( curr->next[path] == NULL ) return false;
else curr=curr->next[path];
}
if(curr->endmark)
{
cout<<"Length "<<curr->length<<endl;
cout<<"Total has "<<curr->cnt<<endl;
}
return curr->endmark;
}
int del(node *curr)
{
for(int i=0; i<=52; i++)
if(curr->next[i] != NULL) del(curr->next[i]);
delete(curr);
}
int main()
{
int n,q;
while( scanf("%d",&n)==1 )
{
getchar();
Tree= new node();
for(int i=0; i<n; i++)
{
string s;
getline(cin,s);
int len=(int)s.size();
insertt(s,len);
}
scanf("%d ",&q);
for(int i=0; i<q; i++)
{
string s;
getline(cin,s);
int len=(int)s.size();
if( searching(s,len) ) printf("Found\n");
else printf("Not Found\n");
}
del(Tree);
}
return 0;
}