Cod sursa(job #579332)

Utilizator cosmyoPaunel Cosmin cosmyo Data 12 aprilie 2011 07:03:33
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <fstream>
#include <string>
#include <vector>
#define f first
#define s second
using namespace std;

vector<int> trie, trieSum;
vector<vector<pair<int, int> > > t;
string word;

inline int get_edge(int root, char c) {
    int i;
    for(i = 0; i < t[root].size(); ++i)
        if(t[root][i].s == c)
            return t[root][i].f;

    return -1;
}

inline void add(const string &word, int val) {
    string :: const_iterator it;
    int root = 0;

    for(it = word.begin(); it != word.end(); ++it) {
        int next = get_edge(root, *it);

        if(next == -1) {
            next = trie.size();
            trie.push_back(0);
            trieSum.resize(trie.size());
            t.resize(trie.size());
            t[root].push_back(make_pair(next, *it));
        }

        trieSum[root] += val;
        root = next;
    }

    trie[root] += val;
}

inline int query(const string &word) {
    string :: const_iterator it;
    int root = 0;
    for(it = word.begin(); it != word.end(); ++it) {
        int next = get_edge(root, *it);
        if(next == -1)
            return 0;
        root = next;
    }

    return trie[root];
}

inline int lcp(const string &word) {
    string :: const_iterator it;
    int root = 0, LastLength = 0, Length = 0;
    for(it = word.begin(); it != word.end(); ++it){
        root = get_edge(root, *it);
        if(root == -1)
            return LastLength;
        ++Length;
        if(trie[root] || trieSum[root])
            LastLength = Length;
    }

    return LastLength;
}

int main() {
    ifstream fin("trie.in");
    ofstream fout("trie.out");
    int op;
    trie.reserve(500005);    trie.resize(1);
    trieSum.reserve(500005);    trieSum.resize(1);
    t.reserve(500005);  t.resize(1);
    while(fin >> op >> word) {
        if(op == 0)
            add(word, 1);
        if(op == 1)
            add(word, -1);
        if(op == 2)
            fout << query(word) << '\n';
        if(op == 3)
            fout << lcp(word) << '\n';

    }

    fin.close();
    fout.close();
    return 0;
}