Cod sursa(job #2405543)

Utilizator alexilasiAlex Ilasi alexilasi Data 14 aprilie 2019 17:12:56
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("trie.in");
ofstream fout ("trie.out");

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

int n;
char s[30];
vector <trie> v;

void update(int poz_trie, int poz_string, int value)
{
    v[poz_trie].prefixes += value;
    if(!s[poz_string])
    {
        v[poz_trie].words += value;
        return;
    }
    int next_character = int(s[poz_string] - 'a');
    if(!v[poz_trie].next[next_character])
    {
        v.push_back(zero);
        v[poz_trie].next[next_character] = ++n;
    }
    update(v[poz_trie].next[next_character], poz_string + 1, value);
}

int query1()
{
    int m = strlen(s);
    int poz_trie = 0, i;
    for(i=0; i<m; i++)
    {
        int next_character = int(s[i] - 'a');
        if(!v[poz_trie].next[next_character])
            break;
        poz_trie = v[poz_trie].next[next_character];
    }
    if(i == m) return v[poz_trie].words;
    else return 0;
}

int query2()
{
    int m = strlen(s);
    int poz_trie = 0, i;
    for(i=0; i<m; i++)
    {
        int next_character = int(s[i] - 'a');
        if(!v[poz_trie].next[next_character] || !v[v[poz_trie].next[next_character]].prefixes)
            break;
        poz_trie = v[poz_trie].next[next_character];
    }
    return i;
}

int main()
{
    int type;
    v.push_back(zero);
    while(fin >> type >> s)
    {
        if(type == 0) update(0, 0, 1);
        else if(type == 1) update(0, 0, -1);
        else if(type == 2) fout << query1() << '\n';
        else if(type == 3) fout << query2() << '\n';
    }
    return 0;
}