Cod sursa(job #1072834)

Utilizator IeewIordache Bogdan Ieew Data 4 ianuarie 2014 22:53:04
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
#include <fstream>
#include <stdio.h>
#include <string.h>

using namespace std;

#define DEBUG false

#if DEBUG
#include <iostream>
#define INFILE "/Users/biordach/Documents/Xcode Projects/training/training/trie.in"
#define __OUT cout
#else
#define INFILE "trie.in"
#define OUTFILE "trie.out"
ofstream __OUT(OUTFILE);
#endif

#define SIZE 30

struct node{
    int prefix, words;
    node* nodes[SIZE];
}*trie;

void readInput();
void solve();
void printOutput();
node* createNode();

int main(int argc, const char * argv[])
{
    trie = createNode();
    readInput();
//  solve();
//  printOutput();

#if DEBUG == false
    __OUT.close();
#endif
    
    return 0;
}

node* createNode(){
    node* q = new node;
    q->prefix = q->words = 0;
    for(int i=0;i<SIZE; i++)
    {
        q->nodes[i] = NULL;
    }
    return q;
}

void addToTrie(char *s){
    node* q = trie;
    int len = strlen(s);
    
    for(int i=0; i < len; i++) {
        int x = s[i] - 'a';
        if(!q->nodes[x]){
            node* newNode = createNode();
            q->nodes[x] = newNode;
        }
        q = q->nodes[x];
        q->prefix ++ ;
    }
    q->words ++;
}

void removeFromTrie(char* s) {
    node* q = trie;
    int len = strlen(s);
    
    for(int i=0; i < len; i++) {
        int x = s[i] - 'a';
        q = q->nodes[x];
        q->prefix --;
    }
    q->words --;
}

void printApparitions(char* s){
    node* q = trie;
    int len = strlen(s);
   //  __OUT<<s<<'\n';
    for(int i=0; i < len; i++) {
        int x = s[i] - 'a';
        q = q->nodes[x];
        if(q == NULL){
            __OUT<<0<<'\n';
            return;
        }
    }
    __OUT<<q->words<<'\n';
}

void printLongestPrefix(char* s){
    // __OUT<<s<<'\n';
    node* q = trie;
    int len = strlen(s);
    
    for(int i=0; i < len; i++) {
       //  __OUT<<s[i];
        int x = s[i] - 'a';
        if(q->nodes[x] == NULL || q->nodes[x]->prefix == 0){
            __OUT<<i<<'\n';
            return;
        }
        q = q->nodes[x];
    }
    __OUT<<len<<'\n';
}

void readInput(){
    FILE *f = fopen(INFILE, "r");
    int op;
    char s[32];
    while(fscanf(f, "%d %s", &op, s) != -1){
        if(op == 0){
            addToTrie(s);
        } else if(op == 1){
            removeFromTrie(s);
        } else if(op == 2){
            printApparitions(s);
        } else printLongestPrefix(s);
    }
    fclose(f);
}

void solve(){
}

void printOutput(){
}