Cod sursa(job #928669)

Utilizator memaxMaxim Smith memax Data 26 martie 2013 16:54:31
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include<iostream>
#include<string>
#include<fstream>
using namespace std;

class letter{
      public:
      int count, words;
      letter * next[28];
      letter(){
               count=0; words=0;
               for(int i=0; i<28; i++) next[i]=0;
               }
      };

void add(string s, letter *root);
void del(string s, letter *root);
int many(string s, letter *root);
int pref(string s, letter *root);

int main(){
    letter *root = new letter; 
    int i; string s;
    ifstream cinr("trie.in");
    ofstream cour("trie.out");
    cinr >> i >> s;
    while(cinr.good()){
                       if(i==0) add(s, root);
                       if(i==1) del(s, root);
                       if(i==2) cour << many(s, root) << "\n";
                       if(i==3) cour << pref(s, root) << "\n";
                       cinr >> i >> s;
                       }
    cinr.close(); cour.close();
    }

void add(string s, letter *root){
     letter *curr=root;
     for(int i=0; i<s.size(); i++){
             int k; k=s[i]-'a';
             if(curr->next[k]==0){
                                  letter *aux = new letter;
                                  curr->next[k]=aux;
                                  }
             curr=curr->next[k];
             curr->words++;
             }
     curr->count++;
     }
     
void del(string s, letter *root){
     letter *curr=root;
     for(int i=0; i<s.size(); i++){
             curr=curr->next[s[i]-'a'];
             curr->words--;
             }
     curr->count--;
     }

int many(string s, letter *root){
    letter *curr=root;
     for(int i=0; i<s.size(); i++){
             int k; k=s[i]-'a';
             if(curr->next[k]==0) return(0);
             curr=curr->next[k];
             }
    return(curr->count);
    }

int pref(string s, letter *root){
    letter *curr=root;
    int ans=0;
     for(int i=0; i<s.size(); i++){
             int k; k=s[i]-'a';
             if(curr->next[k]==0) return(ans);
             curr=curr->next[k];
             if(curr->words==0) return(ans);
             ans++;
             }
     return(ans);
    }