Pagini recente » Cod sursa (job #2842797) | Cod sursa (job #1668182) | Cod sursa (job #53159) | Cod sursa (job #3151899) | Cod sursa (job #579311)
Cod sursa(job #579311)
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <list>
#include <set>
#include <map>
using namespace std;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
#define pb push_back
#define sz size()
#define SORT(x) sort(x.begin(), x.end())
#define REVERSE(x) reverse(x.begin(), x.end())
#define REP(x, hi) for (int x=0; x<(hi); x++)
#define FOR(x, lo, hi) for (int x=(lo); x<(hi); x++)
#define FORALL(it,x) for (typeof(x.begin()) it=x.begin(); it!=x.end(); it++)
#define INFILE "trie.in"
#define OUTFILE "trie.out"
ifstream fin (INFILE);
ofstream fout (OUTFILE);
#define CHARNR 26
struct nod{
int val, prefs;
nod* next[CHARNR];
nod() : val(0), prefs(0)
{
memset( next, NULL, sizeof(next));
}
};
int getval(char c)
{
return int(c)-int('a');
}
void add(nod* t[], char w[])
{
int pos = getval(w[0]);
if( t[pos]==NULL )
{
t[pos] = new nod();
}
if( strlen(w)==1 )
t[pos]->val++;
else
{
t[pos]->prefs++;
add( t[pos]->next, w+1);
}
}
void remove(nod* t[], char w[])
{
int pos = getval(w[0]);
if( strlen(w)==1 )
{
t[pos]->val--;
if( t[pos]->prefs==0 && t[pos]->val==0 )
{
delete t[pos];
t[pos] = NULL;
}
}
else
{
t[pos]->prefs--;
remove(t[pos]->next, w+1);
if( t[pos]->prefs==0 && t[pos]->val==0 )
{
delete t[pos];
t[pos] = NULL;
}
}
}
int wordcount(nod *t[], char w[])
{
int pos = getval(w[0]);
if( t[pos]==NULL )
return 0;
if( strlen(w)==1 )
return t[pos]->val;
else
return wordcount(t[pos]->next, w+1);
}
int getprefix(nod* t[], char w[])
{
int pos = getval(w[0]);
if( strlen(w)==0 || t[pos]==NULL || (t[pos]->prefs==0 && t[pos]->val==0) )
return 0;
return 1 + getprefix(t[pos]->next, w+1);
}
int main()
{
char c, word[32];
nod* trie[CHARNR] = {NULL};
while( fin >> c >> word)
{
switch(c) {
case '0':
add(trie, word);
break;
case '1':
remove(trie, word);
break;
case '2':
fout << wordcount(trie, word) << endl;
break;
case '3':
fout << getprefix(trie, word) << endl;
break;
default:
break;
}
}
return 0;
}