Cod sursa(job #1513688)

Utilizator dutzulBodnariuc Dan Alexandru dutzul Data 29 octombrie 2015 20:50:46
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <fstream>
#include <iostream>

using namespace std;


struct TreeNode
{
    int chr;
    int freq;
    int number_of_str;
    TreeNode* next[26];

    TreeNode()
    {
        chr=freq=number_of_str=0;
        for(int i=0; i<26; ++i) next[i]=NULL;
    }
} Trie;


void add(string word,TreeNode* Head,int pos)
{
    int N=word.size();

    while (pos<N)
    {
        int ch=word[pos]-'a';

        if (Head->next[ch]==NULL) Head->next[ch]=new TreeNode();
        Head=Head->next[ch];
        ++Head->number_of_str;
        ++pos;
    }

    Head->freq++;
}

void erase(string word,TreeNode* Head,int pos)
{
    int N=word.size();

    while (pos<N)
    {
        int ch=word[pos]-'a';
        Head=Head->next[ch];
        --Head->number_of_str;
        ++pos;
    }

    Head->freq--;
}

int print_number_app(string word,TreeNode* Head,int pos)
{
    int N=word.size();

    while (pos<N)
    {
        int ch=word[pos]-'a';
        if (Head->next[ch]==NULL) return 0;
        Head=Head->next[ch];
        ++pos;
    }

    return Head->freq;
}

int print_longest_preff(string word,TreeNode* Head,int pos)
{
    int N=word.size();

    while (pos<N)
    {
        int ch=word[pos]-'a';
        if (Head->next[ch]==NULL) return pos;
        Head=Head->next[ch];
        if (Head->number_of_str==0) return pos;
        ++pos;
    }

    return pos;
}

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

int main()
{
    TreeNode* Head=new TreeNode();
    int type;
    string str;

    while (f>>type)
    {
        f>>str;

        if (type==0) add(str,Head,0);
        if (type==1) erase(str,Head,0);
        if (type==2) g<<print_number_app(str,Head,0)<<'\n';
        if (type==3) g<<print_longest_preff(str,Head,0)<<'\n';
    }

    return 0;
}