Cod sursa(job #1844780)

Utilizator raduaxel1Dilirici Radu raduaxel1 Data 10 ianuarie 2017 14:19:02
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
#define CAR 26

using namespace std;

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

struct TRIE
{
    int val;
    int term;
    TRIE *next[CAR];
};

TRIE *cap;
TRIE *nod;

int N, i, op;
string s;

void ADD()
{
    nod=cap;
    for (i=0; i<N; i++)
    {
        if (nod->next[s[i]-'a']==NULL)
          nod->next[s[i]-'a']=new TRIE;
        nod=nod->next[s[i]-'a'];
        nod->val++;
        if (i==N-1)
          nod->term++;
    }
}

void SUBSTRACT_APP()
{
    TRIE *x;
    nod=cap;
    for (i=0; i<N; i++)
    {
        x=nod;
        nod=nod->next[s[i]-'a'];
        nod->val--;
        if (nod->val==0)
        {
            x->next[s[i]-'a']=NULL;
            break;
        }
        if (i==N-1)
          nod->term--;
    }
}

void WRITE_APP()
{
    nod=cap;
    for (i=0; i<N; i++)
    {
        nod=nod->next[s[i]-'a'];
        if (nod==NULL)
          break;
    }
    if (nod!=NULL)
      fout << nod->term << '\n';
    else
      fout << 0 << '\n';
}

void LONGEST_PREFIX()
{
    nod=cap;
    i=-1;
    while (nod!=NULL && i<N)
    {
        i++;
        nod=nod->next[s[i]-'a'];
    }
    fout << i << '\n';
}

int main()
{
    cap=new TRIE;
    while (fin >> op)
    {
        fin >> s;
        N=s.size();
        if (op==0)
          ADD();
        if (op==1)
          SUBSTRACT_APP();
        if (op==2)
          WRITE_APP();
        if (op==3)
          LONGEST_PREFIX();
    }
    fin.close();
    fout.close();
    return 0;
}