Cod sursa(job #1163040)

Utilizator Mihai22eMihai Ionut Enache Mihai22e Data 1 aprilie 2014 09:35:31
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <fstream>

#include <cstring>
using namespace std;

const int SIGMA = 26;
const int MAX_LEN = 22;

struct Trie {
    int cnt, words;
    Trie *sons[SIGMA];

    Trie() {
        cnt = words = 0;
        for(int i = 0; i < SIGMA; ++i)
            sons[i] = NULL;
    }
};

char s[MAX_LEN];
Trie *root = new Trie;

void insertWord(Trie *node, char s[], int len) {
    for(int i = 0; i < len; ++i) {
        int next = s[i] - 'a';
        
        if(node->sons[next] == NULL)
            node->sons[next] = new Trie;
        node = node->sons[next];
        ++node->words;
    }
    ++node->cnt;
}

void eraseWord(Trie *node, char s[], int len) {
    for(int i = 0; i < len; ++i) {
        int next = s[i] - 'a';

        node = node->sons[next];
        --node->words;
    }
    --node->cnt;
}

int findWord(Trie *node, char s[], int len) {
    for(int i = 0; i < len; ++i) {
        int next = s[i] - 'a';
        
        if(node->sons[next] == NULL)
            return 0;
        node = node->sons[next];
    }

    return node->cnt;
}

int findPrefix(Trie *node, char s[], int len) {
    for(int i = 0; i < len; ++i) {
        int next = s[i] - 'a';

        if(node->sons[next] == NULL)
            return i;
        node = node->sons[next];
        if(node->words == 0)
            return i;
    }

    return len;
}

int main() {
    ifstream f("trie.in");
    ofstream g("trie.out");
    
    int t = 0;
    while(f >> t) {
        f >> s;
        
        int len = strlen(s);
        if(t == 0) 
            insertWord(root, s, len);
        else if(t == 1)
            eraseWord(root, s, len);
        else if(t == 2)
            g << findWord(root, s, len) << "\n";
        else g << findPrefix(root, s, len) << "\n";
    }

    f.close();
    g.close();

    return 0;
}