Cod sursa(job #1973590)

Utilizator GeorginskyGeorge Georginsky Data 25 aprilie 2017 14:55:45
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#define E '\n'
using namespace std;

struct Trie{
    Trie *sons[26];
    int words, numOfSons;
    Trie(){
        memset(sons, 0, sizeof(sons));
        words=numOfSons=0;
    }
};
Trie *root=new Trie;

void _insert_(char *word, Trie *node=root){
    if(*word==E){
        node->words++;
        return;
    }
    if(!(node->sons[*word-'a'])){
        node->sons[*word-'a']=new Trie;
        node->numOfSons++;
    }
    _insert_(word+1, node->sons[*word-'a']);
}

bool _delete_(char *word, Trie *node=root){
    if(*word==E)node->words--;
    else if(_delete_(word+1, node->sons[*word-'a'])){
        node->sons[*word-'a']=0;
        node->numOfSons--;
    }
    if(node!=root&&!(node->words)&&!(node->numOfSons)){
        delete node;
        return true;
    }
    return false;
}

int query(char *word, Trie *node=root){
    if(*word==E)return node->words;
    if(node->sons[*word-'a'])return query(word+1, node->sons[*word-'a']);
    return 0;
}

int lcp(char *word, Trie *node=root, int length=0){
    if(!(node->sons[*word-'a'])||*word==E)return length;
    return lcp(word+1, node->sons[*word-'a'], length+1);
}

int main(){
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
    char q[23];
    while(fgets(q, 23, stdin)){
        if(q[0]=='0')_insert_(q+2);
        else if(q[0]=='1')_delete_(q+2);
        else if(q[0]=='2')cout<<query(q+2)<<"\n";
        else if(q[0]=='3')cout<<lcp(q+2)<<"\n";
    }
    return 0;
}