Cod sursa(job #1472042)

Utilizator eu3neuomManghiuc Teodor-Florin eu3neuom Data 16 august 2015 00:20:02
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <iostream>
#include <fstream>
#include <cstring>

#define CH (*s - 'a')

using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

struct Trie{
    int cnt, nr_son;
    Trie *son[26];
    Trie(){
        cnt = nr_son = 0;
        memset(son, 0, sizeof(son));
    }
};

Trie *T = new Trie;

void ins(Trie *node, char *s){
    if(*s == '\000'){
        node -> cnt++;
        return;
    }
    if(node -> son[CH] == 0){
        node -> son[CH] = new Trie;
        node -> nr_son++;
    }
    ins(node -> son[CH], s + 1);
}

int del(Trie *node, char *s){
    if(*s == '\000'){
        node -> cnt--;
    } else {
        if(del(node -> son[CH], s + 1)){
            node -> son[CH] = 0;
            node -> nr_son--;
        }
    }
    if(node -> cnt == 0 && node -> nr_son == 0 && node != T){
        delete node;
        return 1;
    }
    return 0;
}

int number(Trie *node, char *s){
    if(*s == '\000'){
        return node -> cnt;
    }
    if(node -> son[CH]){
        return number(node -> son[CH], s + 1);
    }
    return 0;
}

int prefix(Trie *node, char *s, int k){
    if(*s == '\000' || !node -> son[CH]){
        return k;
    }
    return prefix(node -> son[CH], s + 1, k + 1);
}

int main(){
    char line[32];
    while(fin.getline(line, 30, '\n')){
        if(line[0] == '0'){
            ins(T, line + 2);
        }
        if(line[0] == '1'){
            del(T, line + 2);
        }
        if(line[0] == '2'){
            fout << number(T, line + 2) << "\n";
        }
        if(line[0] == '3'){
            fout << prefix(T, line + 2, 0) << "\n";
        }
    }
    return 0;
}