Today I was learning Trie from topcoder tutorial Topcoder Trie Tutorial.
I am having confusion in countPrefixes function in topcoder tutorial , i am not able to understand last line of this function.
return countWords(edges[k], prefix)
If someone can explain use of above line.
So i modified countPrefixes function and have written this code for trie following topcoder tutorial . Not sure it is correct way of implementing or not.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
const int MOD=1000000007;
const int INF= int(1e9),ALPHA=26;
string s;
int n;
struct Trie {
int words,prefixes;
Trie *edges[ALPHA];
Trie() {
words=0;
prefixes=0;
for(int i=0;i<ALPHA;i++) {
edges[i]=NULL;
}
}
};
Trie root;
void addword(Trie *vertex,int cur) {
if(cur==n) {
vertex->words=vertex->words+1;
} else {
vertex->prefixes=vertex->prefixes+1;
if(vertex->edges[s[cur]-'a']==NULL) {
vertex->edges[s[cur]-'a']=new Trie;
}
addword(vertex->edges[s[cur]-'a'],cur+1);
}
}
int countWords(Trie *vertex , int cur) {
if(cur==n) {
return vertex->words;
} else if(vertex->edges[s[cur]-'a']==NULL) {
return 0;
} else {
return countWords(vertex->edges[s[cur]-'a'],cur+1);
}
}
int countPrefixes(Trie *vertex , int cur) {
if(cur==n) {
return vertex->prefixes+vertex->words ;
} else if(vertex->edges[s[cur]-'a']==NULL) {
return 0;
} else {
return countPrefixes(vertex->edges[s[cur]-'a'],cur+1);
}
}
int main()
{
ios_base::sync_with_stdio(false);
int q;
cin>>q;
while(q--) {
cin>>s;
n=s.size();
addword(&root,0);
}
cin>>q;
while(q--) {
cin>>s;
n=s.size();
cout<<countWords(&root,0)<<" "<<countPrefixes(&root,0)<<endl;
}
return 0;
}