Cod sursa(job #1891411)

Utilizator DobosDobos Paul Dobos Data 23 februarie 2017 23:35:24
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <bits/stdc++.h>
#define C (*s - 'a')

using namespace std;

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


struct trie{
    int wo,pf;
    trie *edge[26];

    trie(){
        wo = pf = 0;
        memset (edge,0,sizeof( edge ));
    }

};

trie *T = new trie;


void addw(trie *nod, char *s){
    if(*s < 'a'){
        nod ->wo++; return;
    }
    if(nod -> edge[C] == 0){
        nod -> edge[C] = new trie;
        nod -> pf ++;
    }
    addw(nod ->edge[C], s + 1);
}

int deletew(trie *nod,char *s){
    if(*s < 'a'){
        nod ->wo--;
    } else if(deletew(nod ->edge[C],s + 1)){
        nod ->edge[C] = 0;
        nod ->pf --;
    }
    if(nod->wo == 0 && nod ->pf == 0 && nod != T){
        delete nod; return 1;
    }
    return 0;
}

int queryw(trie *nod,char *s){
     if(*s < 'a')
        return nod ->wo;
     queryw(nod ->edge[C], s + 1);
}

int querys(trie *nod,char *s,int l){
    if(nod ->edge[C] == 0 || *s < 'a')
        return l;
    return querys(nod ->edge[C],s + 1,l + 1);
}

int main()
{
    ios :: sync_with_stdio(false);
    char S[32];
    while(fin.getline(S,sizeof(S))){

        if(S[0] == '0')
            addw(T,S + 2);
        if(S[0] == '1')
            deletew(T,S + 2);
        if(S[0] == '2')
           fout << queryw(T,S + 2) << "\n";
        if(S[0] == '3')
           fout << querys(T,S + 2,0) << "\n";
    }

    return 0;
}