Cod sursa(job #1830914)

Utilizator Bodo171Bogdan Pop Bodo171 Data 17 decembrie 2016 11:32:37
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
string s;
int ind,tip,where;
struct Trie
{
    int sons,cnt;
    Trie *son[26];
    Trie()
    {
       sons=0,cnt=0;
       //memset(son,0,sizeof(son));
       for(int idx=0;idx<26;idx++)
        son[idx]=0;
    }
};
Trie *rad=new Trie,*cpy;
void inserts(Trie *node)
{
    node=rad;
    for(ind=0;ind<s.size();ind++)
    {
        if(s[ind]==' ')
         {node->cnt++;return;}
        where=s[ind]-'a';
        if(node->son[where]==0)
        {
            node->son[where]=new Trie;
            node->sons++;
        }
        node=node->son[where];
    }
}
bool del(Trie *node,int ind)
{
    if(s[ind]==' ')
        node->cnt--;
    else
    {
        int whereD=s[ind]-'a';
        if(del(node->son[whereD],ind+1))
        {
            node->son[whereD]=0;
            node->sons--;
        }
    }
     if(node->sons==0&&node->cnt==0&&node!=rad)
    {
        delete node;
        return 1;
    }
    return 0;
}
int pref(Trie *node)
{
    for(ind=0;ind<s.size();ind++)
    {
        where=s[ind]-'a';
        if(s[ind]==' '||node->son[where]==0)
            return ind;
        node=node->son[where];
    }
    return 0;
}
int query(Trie *node)
{
     for(ind=0;ind<s.size();ind++)
     {
         if(s[ind]==' ') return node->cnt;
         where=s[ind]-'a';
         if(node->son[where]==0) return 0;
         node=node->son[where];
     }
}
int main()
{
    ifstream f("trie.in");
    ofstream g("trie.out");
    while(f>>tip)
    {
        f>>s;s+=' ';
        if(tip==0) inserts(rad);
        if(tip==1) del(rad,0);
        if(tip==2) g<<query(rad)<<'\n';
        if(tip==3) g<<pref(rad)<<'\n';
    }
    return 0;
}