Cod sursa(job #1111243)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 18 februarie 2014 18:58:44
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.75 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>
#include <memory.h>

using namespace std;

const char infile[] = "trie.in";
const char outfile[] = "trie.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 100005;
const int oo = 0x3f3f3f3f;
const int SIGMA = 26; /// English alphabet size

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

struct Trie {
    int fr;
    int sz;
    Trie *sons[SIGMA];
    Trie() {
        fr = 0;
        sz = 0;
        memset(sons, 0, sizeof(sons));
    }
};

char s[SIGMA];
int op, Ans;
Trie *Root = new Trie();

void Insert(Trie *Node, const char *p) {
    if(!*p) {
        ++ Node -> fr;
        return;
    }
    int son = *p - 'a';
    if(!Node -> sons[son])
        Node -> sons[son] = new Trie();
    ++ Node -> sons[son] -> sz;
    Insert(Node -> sons[son], p + 1);
}

void Remove(Trie *Node, const char *p) {
    if(!*p) {
        -- Node -> fr;
        return;
    }
    int son = *p - 'a';
    Remove(Node -> sons[son], p + 1); /// It is guaranteed that the word exist in the trie at the moment the remove
                                      /// function is called
    -- Node -> sons[son] -> sz;
    if(!Node -> sons[son] -> sz)
        Node -> sons[son] = 0;
}

int Frequency(Trie *Node, const char *p) {
    if(!*p)
        return Node -> fr;
    int son = *p - 'a';
    if(Node -> sons[son])
        return Frequency(Node -> sons[son], p + 1);
    return 0;
}

int LongestCommonPrefix(Trie *Node, const char *p) {
    if(!*p)
        return 0;
    int son = *p - 'a';
    if(Node -> sons[son])
        return 1 + LongestCommonPrefix(Node -> sons[son], p + 1);
    return 0;
}

int main() {
    while(fin >> op >> s) {
        switch(op) {
            case 0:
                Insert(Root, s);
                break;
            case 1:
                Remove(Root, s);
                break;
            case 2:
                fout << Frequency(Root, s) << '\n';
                break;
            case 3:
                fout << LongestCommonPrefix(Root, s) << '\n';
                break;
        }
    }
    fin.close();
    fout.close();
    return 0;
}