Cod sursa(job #1410360)

Utilizator mirceadinoMircea Popoveniuc mirceadino Data 31 martie 2015 00:14:14
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#include<algorithm>
#include<bitset>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<deque>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<vector>

using namespace std;

#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "trie";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif

struct node {
    int cnt;
    int end;
    node *f[26];

    node() {
        cnt = end = 0;
        memset(f, 0, sizeof(f));
    }
};

node *root;

void insert(char *word) {
    int i, L = strlen(word), c;
    node *Q = root;

    for(i = 0; i < L; i++) {
        c = word[i] - 'a';

        if(Q->f[c] == NULL)
            Q->f[c] = new node;

        Q = Q->f[c];
        Q->cnt++;
    }

    Q->end++;
}

void erase(char *word) {
    int i, L = strlen(word), c;
    node *Q = root;
    stack<node*> S;

    S.push(root);

    for(i = 0; i < L; i++) {
        c = word[i] - 'a';
        Q = Q->f[c];
        Q->cnt--;
        S.push(Q);
    }

    Q->end--;

    while(S.size() > 1) {
        Q = S.top();
        S.pop();

        if(Q->cnt)
            return;

        S.top()->f[word[S.size() - 1] - 'a'] = 0;
        delete Q;
    }
}

int count(char *word) {
    int i, L = strlen(word), c;
    node *Q = root;

    for(i = 0; i < L; i++) {
        c = word[i] - 'a';

        if(Q->f[c] == NULL)
            return 0;

        Q = Q->f[c];
    }

    return Q->end;
}

int preffix(char *word) {
    int i, L = strlen(word), c;
    node *Q = root;

    for(i = 0; i < L; i++) {
        c = word[i] - 'a';

        if(Q->f[c] == NULL)
            return i;

        Q = Q->f[c];
    }

    return L;
}

int main() {
    int t;
    char word[25];

#ifndef ONLINE_JUDGE
    freopen(inputFile.c_str(), "r", stdin);
    freopen(outputFile.c_str(), "w", stdout);
#endif

    root = new node;

    while(scanf("%d %s\n", &t, &word) + 1) {
        if(t == 0)
            insert(word);
        if(t == 1)
            erase(word);
        if(t == 2)
            printf("%d\n", count(word));
        if(t == 3)
            printf("%d\n", preffix(word));
    }

    return 0;
}