Cod sursa(job #1690250)

Utilizator bogdanboboc97Bogdan Boboc bogdanboboc97 Data 14 aprilie 2016 21:49:26
Problema Trie Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define INF numeric_limits<int>::max()
#define int64 long long
#define lsb(x) (-x)&(x)
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
struct trie{
    int pref,cuv;
    trie *next[27];
};
trie* T;
#define code(x) (x-'a')
void ins(string s,int pos,trie* T)
{
    if(T->next[ code(s[pos]) ]==NULL)
        T->next[ code(s[pos]) ]=new trie;
    T=T->next[ code(s[pos]) ];
    T->pref++;
    if(pos==(int)s.size()-1)
        T->cuv++;
    else
        ins(s,pos+1,T);
}
void del(string s,int pos,trie* T)
{
    T=T->next[ code(s[pos]) ];
    T->pref--;
    if(pos==(int)s.size()-1)
        T->cuv--;
    else
        del(s,pos+1,T);
}
int countWords(string s,int pos,trie* T)
{
    if(T->next[ code(s[pos]) ]==NULL)
        return 0;
    T=T->next[ code(s[pos]) ];
    if(pos==(int)s.size()-1)
        return T->cuv;
    else
        return countWords(s,pos+1,T);
}
int pref;
void maxPref(string s,int pos,trie* T)
{
    if(T->next[ code(s[pos]) ]==NULL)
       return;
    T=T->next[ code(s[pos]) ];
    if(T->pref >= 1)
        pref++;
    else
        return;
    if(pos!=(int)s.size()-1)
        maxPref(s,pos+1,T);
}
int main()
{
    T=new trie;
    int t;
    string s;
    while(in>>t>>s)
    {
        if(t==0)
            ins(s,0,T);
        else if(t==1)
            del(s,0,T);
        else if(t==2)
            out<<countWords(s,0,T)<<'\n';
        else{
            pref=0;
            maxPref(s,0,T);
            out<<pref<<'\n';
        }
    }
    return 0;
}