Cod sursa(job #1674238)

Utilizator Vele_GeorgeVele George Vele_George Data 4 aprilie 2016 15:20:58
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>
#include <vector>
#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] = NULL;
    }
};
nod *root = new nod();

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

void sterge(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'] = NULL;
            return;
        }

        p = p->next[s[i] - 'a'];
        --p->tr;
    }
}
int nr_aparitii(string s)
{
    nod *p = root;

    for(int i =0; i<s.size(); i++)
        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'] == NULL)
            return i;
        p = p->next[s[i] - 'a'];
    }



}

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

    int act;
    string s;

    while (f >> act >> s)
    {
        if (act == 0) adauga(s);
        else
        if (act == 1) sterge(s);
        else
        if (act == 2) g << nr_aparitii(s) << "\n";
        else g << prefix(s) << "\n";

    }

    f.close();
    g.close();
    return 0;
}