Cod sursa(job #1137977)

Utilizator vyrtusRadu Criuleni vyrtus Data 9 martie 2014 14:39:11
Problema Trie Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <fstream>
#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#define p pair<int,string>

using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");

struct trie {
    int word;
    int prefix;
    trie *edge[26];
   trie () {   word = prefix = 0;
    memset(edge , 0 , sizeof(edge));}
};

trie *T = new trie;
string s;
p num;

p des(string l)
{
    p ret;
    ret.first = (int)toupper(l[0]) - 48;
    l.erase(0,2);
    ret.second = l;
    return ret;
}

void addword(trie *nod, string wd, int r)
{
    if (r == wd.length()) {nod->word += 1; return;}

    if (nod->edge[wd[r] - 'a' ] == 0 )
    {
        nod ->edge[wd[r] - 'a' ] = new trie;
        nod->prefix++;
    }
   addword(nod->edge[wd[r] - 'a'],wd,r+1);
}

int delword(trie *nod, string wd, int r)
{
    if (r == wd.length() ) nod->word -=1;
      else
    if (delword(nod->edge[wd[r] - 'a'],wd,r+1))
    {
        nod->edge[wd[r] - 'a'] = 0;
        nod->prefix--;
    }
    if (nod->word == 0 && nod->prefix == 0 && nod != T)
    {        delete nod; return 1;   }
    return 0;
}

int nword(trie *nod,string wd, int r)
{
    if (r == wd.length()) { return nod->word; }

    if (nod->edge[wd[r] - 'a'] )
       return nword(nod->edge[wd[r] - 'a'],wd,r+1);
    return 0;
}

int npref(trie *nod,string wd , int r , int k)
{
    if ((r == wd.length() )|| (nod->edge[wd[r] - 'a'] == 0))
          return k;
    return npref(nod->edge[wd[r] - 'a'],wd,r+1,k+1);
}

int main()
{

    while (!f.eof())
    {
            getline(f,s);
        num = des(s);
         switch (num.first)
         {
         case 0 : addword(T,num.second,0); break;
         case 1 : delword(T,num.second,0); break;
         case 2 : g << (nword(T,num.second,0)) << "\n"; break;
         case 3 : g << (npref(T,num.second,0,0)) << "\n"; break;
         }
    }
    return 0;
}