File tree 1 file changed +101
-0
lines changed
1 file changed +101
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+ class trienode {
4
+ public:
5
+ char letter;
6
+ bool eow;// end of word
7
+ trienode** children=new trienode* [26 ];
8
+ trienode ()
9
+ {
10
+ letter=' \0 ' ;
11
+ eow=false ;
12
+ for (int i=0 ;i<26 ;i++)
13
+ children[i]=NULL ;
14
+ }
15
+ };
16
+ void insert (string s,trienode* head)
17
+ {
18
+ trienode* curr= head;
19
+ int i=0 ;
20
+ for (i=0 ;i<s.length ();i++)
21
+ {
22
+ int index =s[i]-' a' ;
23
+ if (curr->children [index ]!=NULL )
24
+ {
25
+ curr=curr->children [index ];
26
+ }
27
+ else
28
+ {
29
+ curr->children [index ]=new trienode ();
30
+ curr->children [index ]->letter =s[i];
31
+ curr=curr->children [index ];
32
+ }
33
+ }
34
+
35
+ if (i==s.length ())
36
+ {
37
+ curr->eow =true ;
38
+ }
39
+
40
+ }
41
+ void dfs (trienode* root,string in)
42
+ { if (root->eow )
43
+ cout<<in<<endl;
44
+
45
+ for (int i=0 ;i<26 ;i++)
46
+ { if (root->children [i])
47
+ dfs (root->children [i],in+root->children [i]->letter );
48
+ }
49
+
50
+ }
51
+ int complete (string search,trienode* head)
52
+ { trienode* curr = head;
53
+ for (int i=0 ;i<search.length ();i++)
54
+ {
55
+ int index =search[i]-' a' ;
56
+ if (curr->children [index ]!=NULL )
57
+ {
58
+ curr=curr->children [index ];
59
+ }
60
+ else
61
+ {
62
+ return 0 ;
63
+ }
64
+ }
65
+ dfs (curr,search);
66
+ return 1 ;
67
+ }
68
+ int main ()
69
+ {int n;
70
+ cin>>n;
71
+ string input;
72
+ trienode* head=new trienode ();
73
+ for (int i=0 ;i<n;i++)
74
+ {
75
+ cin>>input;
76
+ insert (input,head);
77
+ }
78
+ /* for(int i=0;i<26;i++)
79
+ {
80
+ if(head->children[i])
81
+ {
82
+ cout<<head->children[i]->letter<<endl;
83
+ }
84
+ }*/
85
+ int q;
86
+ cin>>q;
87
+ string search;
88
+ int result;
89
+ for (int i=0 ;i<q;i++)
90
+ {
91
+ cin>>search;
92
+ result=complete (search,head);
93
+ if (result==0 )
94
+ {
95
+ cout<<" No suggestions" <<endl;
96
+ insert (search,head);
97
+ }
98
+ }
99
+
100
+ return 0 ;
101
+ }
You can’t perform that action at this time.
0 commit comments