Cod sursa(job #2575082)

Utilizator spartanul300Vasile Andrei spartanul300 Data 6 martie 2020 11:33:03
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>

using namespace std;

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

struct trie
{
    int prefixes,words,next[26];
}zero;

vector <trie> v;
int n_string,t;
char s[30];

void update(int poz_trie, int poz_string, int value)
{
    v[poz_trie].prefixes+=value;

    if(poz_string == n_string)
    {
        v[poz_trie].words+=value;
        return;
    }
    else
    {
        int next_char_ind = (int)(s[poz_string]-'a');
        if(v[poz_trie].next[next_char_ind]==0)
        {
            v.push_back(zero);
            t++;
            v[poz_trie].next[next_char_ind]=t;
        }

        update(v[poz_trie].next[next_char_ind],poz_string+1,value);
    }
}

int query1()
{
    int poz_trie=0,poz_string=0;
    int next_char_ind = (int)(s[poz_string]-'a');

    while(poz_string<n_string && v[poz_trie].next[next_char_ind]!=0)
    {
        poz_trie = v[poz_trie].next[next_char_ind];
        poz_string++;
        next_char_ind = (int)(s[poz_string]-'a');
    }

    if(poz_string==n_string)
    {
        return v[poz_trie].words;
    }
    else return 0;
}

int query2()
{
    int poz_trie=0,poz_string=0;
    int next_char_ind = (int)(s[poz_string]-'a');

    while(poz_string<n_string && v[poz_trie].next[next_char_ind]!=0 && v[v[poz_trie].next[next_char_ind]].prefixes>0)
    {
        poz_trie = v[poz_trie].next[next_char_ind];
        poz_string++;
        next_char_ind = (int)(s[poz_string]-'a');
    }

    return poz_string;
}

int op;
int main()
{
    v.push_back(zero);

    while(f>>op>>s)
    {
        n_string = strlen(s);

        if(op==0)update(0,0,1);
        else if(op==1)update(0,0,-1);
        else if(op==2)g<<query1()<<'\n';
        else g<<query2()<<'\n';
    }
    return 0;
}