-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtrie.cpp
executable file
·117 lines (111 loc) · 2.21 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
108
109
110
111
112
113
114
115
116
117
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
typedef long double ld;
#define MOD 1000000007
#define INF 1000000000000000000
#define endll "\n"
#define pb push_back
#define forn(i,n) for(i=0;i<n;i++)
#define forab(i,a,b) for(i=a;i<=b;i++)
#define vpll vector<pair<ll,ll>>
#define pll pair<ll,ll>
#define vll vector<ll>
#define ff first
#define ss second
#define bs binary_search
#define lb lower_bound
#define ub upper_bound
#define test ll t;cin>>t; while(t--)
#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
ll k=0;
struct node
{
char ch;
ll val;
struct node* child[26];
bool last;
node()
{
last=false;
ll i;
forn(i,26)
{
child[i]=NULL;
}
}
};
void trieconstruct(node* root,string &s)
{
ll i;
node* temp=root;
forn(i,s.length())
{
ll x=s[i]-'A';
if(temp->child[x]==NULL)
{
node* newnode=new node();
newnode->ch=s[i];
newnode->val=k++;
temp->child[x]=newnode;
}
temp=temp->child[x];
}
temp->last=true;
}
bool prefixtriematch(node* root, string s)
{
node* temp=root;
ll i;
forn(i,s.length())
{
ll x=s[i]-'A';
if(temp->child[x]==NULL)
return false;
temp=temp->child[x];
}
return true;
}
bool searchaword(string s,node* root)
{
node* temp=root;
ll i;
forn(i,s.length())
{
ll x=s[i]-'A';
if(temp->child[x]==NULL)
return false;
temp=temp->child[x];
}
return temp->last;
}
void dfs(node* root)
{
ll i;
for(i=0;i<26;i++)
{
if(root->child[i]!=NULL)
{
cout<<root->val<<"->"<<root->child[i]->val<<":"<<root->child[i]->ch<<endll;
dfs(root->child[i]);
}
}
}
int main()
{
fast_io;
node* root;
root=new node();
root->val=k++;
ll i,n;
string s;
cin>>n;
forn(i,n)
{
cin>>s;
trieconstruct(root,s);
}
dfs(root);
return 0;
}