Pagini recente » Statistici pop linda (linda) | Cod sursa (job #1974876) | Cod sursa (job #3216232) | Statistici nayyerani hosein (hosein) | Cod sursa (job #2143206)
#include <iostream>
#include <fstream>
#include <string.h>
#include <malloc.h>
using namespace std;
#define ios ios_base::sync_with_stdio(false);cin.tie(0);
#define setnow clock_t tStart;
#define setTime tStart = clock();
#define time0 (double)(clock() - tStart)/CLOCKS_PER_SEC
#define setin(x) ifstream cin(x);
#define setout(x) ofstream cout(x);
#define NMAX 30
typedef long long ll;
typedef long long int lli;
typedef pair < int, int> dbl;
const int maxInt = 1e9*2;
const lli maxLong = 1e18*2;
struct node{
struct node *child[26];
int words;
node(){
words = 0;
for(int i=0;i<26;i++)child[i]=NULL;
}
};
void insertWord(struct node *root, char* word){
struct node *aux = root;
int length = strlen(word);
for(int i=0;i<length;i++){
if(aux -> child[word[i]-'a'] == NULL){
aux -> child[word[i]-'a'] = new node();
}
aux = aux -> child[word[i]-'a'];
}
aux->words++;
}
int haveChildren(struct node* root){
for(int i=0;i<26;i++){
if(root->child[i])
return(1);
}
return(0);
}
int eraseWord(struct node* *root, char* word){
if(*root == NULL)
return(0);
if(*word){
if(*root != NULL && (*root)->child[*word - 'a'] != NULL &&
eraseWord(&((*root)->child[*word-'a']), word + 1) && (*root) -> words == 0){
if(!haveChildren(*root)){
free(*root);
(*root) = NULL;
return(1);
} else {
return(0);
}
}
}
if(*word == '\0' && (*root)-> words == 1){
if(!haveChildren(*root)){
free(*root);
(*root) = NULL;
return(1);
} else {
(*root) -> words = 0;
return(0);
}
}
if(*word == '\0' && (*root)->words > 1){
(*root)->words--;
return(0);
}
return(0);
}
int findWord(struct node *root, char* word){
struct node *aux = root;
if(root == NULL)
return(0);
int length = strlen(word);
for(int i=0;i<length;i++){
if(aux -> child[word[i]-'a'] == NULL){
return(0);
}
aux = aux -> child[word[i]-'a'];
}
if(aux && aux->words)
return(aux->words);
return(0);
}
int MaxPrefix(struct node *root, char* word){
struct node *aux = root;
int k = 0;
int length = strlen(word);
for(int i=0;i<length;i++){
if(aux->child[word[i]-'a'])
k++;
else break;
aux = aux -> child[word[i]-'a'];
}
return(k);
}
int main(){
ios;
setin("trie.in");
setout("trie.out");
int c;
char str[50];
node *root = new node();
while(cin >> c >> str){
if(c == 0){
insertWord(root, str);
}
if(c == 1){
eraseWord(&root, str);
}
if(c == 2){
cout << findWord(root, str) << '\n';
}
if(c == 3){
cout << MaxPrefix(root, str) << '\n';
}
}
}