Cod sursa(job #1653598)

Utilizator pas.andreiPopovici Andrei-Sorin pas.andrei Data 16 martie 2016 11:47:36
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.18 kb
#include <cstdio>
#include <fstream>
#include <vector>
#include <queue>
#include <utility>
#include <algorithm>
#include <functional>
#include <string>
#include <cstring>
#include <cmath>
#include <map>
#include <set>
#include <bitset>
#include <stack>
#include <iomanip>
#define MOD 1000000007
#define NMAX 1005
#define MMAX 5005
#define INF (1<<30)

using namespace std;

typedef pair<int, int> pii;

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

struct trie {
    int nrTrm, nrfii;
    trie *fiu[26];

    trie() {
        nrTrm=nrfii=0;
        memset(fiu, 0, sizeof(fiu));
    }
};

trie *root=new trie;
string s;

void insert_word(trie *nod, int pos);
int delete_word(trie *nod, int pos);
int nr_words(trie *nod, int pos);
int prefix_length(trie *nod, int pos);

int main() {
	int n, i, nr, sum=0,win,x, q;
    char ch;

    while (!fin.eof()) {
        fin>>q>>s;

        if(fin.eof()) break;

        if(q==0) insert_word(root, 0);
        else if (q==1) delete_word(root, 0);
        else if (q==2) fout << nr_words(root, 0) << '\n';
        else fout << prefix_length(root, 0) << '\n';

        fin.get(ch);
    }

	return 0;
}

void insert_word(trie *nod, int pos) {
    if(pos == s.size()) {
        ++nod->nrTrm;
        return;
    }

    char ch=s[pos]-'a';
    if(nod->fiu[ch] == NULL) {
        nod->fiu[ch]=new trie;
        ++nod->nrfii;
    }

    insert_word(nod->fiu[ch], pos+1);
}

int delete_word(trie *nod, int pos) {
    char ch = s[pos]-'a';

    if(pos == s.size())
        --nod->nrTrm;
    else if(delete_word(nod->fiu[ch], pos+1)) {
        --nod->nrfii;
        nod->fiu[ch] = NULL;
    }

    if(nod->nrTrm == 0 && nod->nrfii == 0 && nod!=root) {
        delete nod;
        return 1;
    }
    return 0;
}

int nr_words(trie *nod, int pos) {
    if(pos == s.size())
        return nod->nrTrm;
    if(nod->fiu[s[pos]-'a'] != NULL)
        return nr_words(nod->fiu[s[pos]-'a'], pos+1);
    return 0;
}

int prefix_length(trie *nod, int pos) {
    if(pos == s.size() || nod->fiu[s[pos]-'a'] == NULL)
        return pos;

    return prefix_length(nod->fiu[s[pos]-'a'], pos+1);
}