Pagini recente » Cod sursa (job #15704) | Cod sursa (job #2977055) | Cod sursa (job #537754) | Cod sursa (job #2744006) | Cod sursa (job #2871332)
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct Node{
int nrSons , nrWords;
Node *alpha[26];
Node(){
nrSons = nrWords = 0;
for(int i = 0 ; i < 26 ; ++i)
alpha[i] = 0;
}
};
Node *root = new Node;
char s[21];
int type;
int w;
void insertNode(Node *crawl , char *s){
if(*s == '\0'){
++crawl -> nrWords;
return;
}
else{
if(!crawl -> alpha[*s - 'a'])
++crawl -> nrSons , crawl -> alpha[*s - 'a'] = new Node;
insertNode(crawl -> alpha[*s - 'a'] , s + 1);
}
}
bool deleteNode(Node *crawl , char *s){
if(*s == '\0'){
--crawl -> nrWords;
}
else if(deleteNode(crawl -> alpha[*s - 'a'] , s + 1)){
crawl -> alpha[*s - 'a'] = 0;
--crawl -> nrSons;
}
if(crawl -> nrWords == 0 && crawl -> nrSons == 0 && crawl != root){
delete crawl;
return 1;
}
return 0;
}
int nrAp(Node *crawl , char *s){
if(*s == '\0')
return crawl -> nrWords;
else if(crawl -> alpha[*s - 'a'])
return nrAp(crawl -> alpha[*s - 'a'] , s + 1);
return 0;
}
int prefix(Node *crawl , char *s , int k){
if(!crawl -> alpha[*s - 'a'] or *s == '\0')
return k;
return prefix(crawl -> alpha[*s - 'a'] , s + 1 , k + 1);
}
int main(){
while(f >> type){
f >> s;
if(type == 0)
insertNode(root , s);
else if(type == 1)
deleteNode(root , s);
else if(type == 2)
g << nrAp(root , s) << "\n";
else if(type == 3)
w = 0 , g << prefix(root , s , w) << "\n";
}
return 0;
}