Cod sursa(job #1674819)

Utilizator Vele_GeorgeVele George Vele_George Data 4 aprilie 2016 21:19:35
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <iostream>
#include <fstream>
#include <map>
#include <cstring>

using namespace std;


struct nod
{
    int tr, fin;
    nod*next[26];

    nod(){
        tr = 0;
        fin = 0;
        for(int i=0; i<26; i++) next[i] =0;
    }
};

nod * root = new nod();

void add(string s)
{
    nod *p = root;
    for(int i=0; i<s.size(); i++)
    {
        if (p->next[s[i] - 'a'] == 0) p->next[s[i] - 'a'] = new nod();
        p = p->next[s[i] - 'a'];
        ++p->tr;
    }
    ++p->fin;
}

void del(string s)
{
    nod *p = root;
    for(int i=0; i<s.size(); i++)
    {
        if(p->next[s[i] - 'a']->tr == 1)
        {
            delete(p->next[s[i] - 'a']);
            p->next[s[i] - 'a'] = 0;
            return;
        }
        p = p->next[s[i] - 'a'];
        --p->tr;
    }
    --p->fin;
}

int occ(string s)
{
    nod *p = root;
    for(int i=0; i<s.size(); i++)
    {
        if (p->next[s[i] - 'a'] == 0) return 0;
        p = p->next[s[i] - 'a'];
    }
    return p->fin;
}

int prefix(string s)
{
    nod *p = root;
    for(int i=0; i<=s.size(); i++)
    {
        if (p->next[s[i] - 'a'] == 0) return i;
        p = p->next[s[i] - 'a'];
    }
    return s.size();
}




int main()
{
    ifstream f("trie.in");
    ofstream g("trie.out");

    int act;
    string s;
    while(f >> act >> s)
    {
        if (act == 0) add(s);
        else
        if (act == 1) del(s);
        else
        if (act == 2) g << occ(s) << "\n";
        else
        if (act == 3) g << prefix(s) << "\n";
    }

   // cout << root->next['a'];
    f.close();
    g.close();
    return 0;
}