Pagini recente » Cod sursa (job #58964) | Cod sursa (job #2471260) | Cod sursa (job #1841245) | Cod sursa (job #247553) | Cod sursa (job #1236129)
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>
using namespace std;
const char infile[] = "trie.in";
const char outfile[] = "trie.out";
ifstream fin(infile);
ofstream fout(outfile);
const int MAXN = 25;
const int oo = 0x3f3f3f3f;
typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;
const inline int min(const int &a, const int &b) { if( a > b ) return b; return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b; return a; }
const inline void Get_min(int &a, const int b) { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b) { if( a < b ) a = b; }
class Trie {
private:
static const int SIGMA = 26;
static const char firstLetter = 'a';
struct Node {
vector <Node*> sons;
int endings;
int visits;
Node() {
sons.resize(SIGMA, NULL);
endings = visits = 0;
}
} *Root;
public:
Trie() {
Root = new Node();
}
Node *&getRoot() {
return Root;
}
void insertString(Node *&n, char *s) {
if(!*s) {
++ n->endings;
return;
}
int son = *s - firstLetter;
if(!n->sons[son])
n->sons[son] = new Node();
++ n->sons[son]->visits;
insertString(n->sons[son], s + 1);
}
void removeString(Node *&n, char *s) {
if(!*s) {
-- n->endings;
return;
}
int son = *s - firstLetter;
removeString(n->sons[son], s + 1);
if(!-- n->sons[son]->visits) {
delete n->sons[son];
n->sons[son] = NULL;
}
}
int getTimes(Node *&n, char *s) {
if(!*s)
return n->endings;
int son = *s - firstLetter;
return getTimes(n->sons[son], s + 1);
}
int getLongestPrefix(Node *&n, char *s, int level) {
if(!*s)
return level;
int son = *s - firstLetter;
if(!n->sons[son])
return level;
return getLongestPrefix(n->sons[son], s + 1, level + 1);
}
};
int op;
char s[MAXN];
int main() {
Trie T;
while(fin >> op >> s) {
switch(op) {
case 0:
T.insertString(T.getRoot(), s);
break;
case 1:
T.removeString(T.getRoot(), s);
break;
case 2:
fout << T.getTimes(T.getRoot(), s) << '\n';
break;
case 3:
fout << T.getLongestPrefix(T.getRoot(), s, 0) << '\n';
break;
}
}
fin.close();
fout.close();
return 0;
}