Pagini recente » Cod sursa (job #115600) | Cod sursa (job #666763) | Cod sursa (job #554567) | Cod sursa (job #1946104) | Cod sursa (job #1065133)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <queue>
#include <deque>
#include <map>
#include <cmath>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
#define ll long long
#define pb push_back
#define mp make_pair
#define sz size
#define x first
#define y second
#define nmax
#define inf
#define Sigma 27
struct Trie{
int countWord, countPrefix;
Trie *son[Sigma];
Trie(){
countWord = 0; countPrefix = 0;
for(int i=0; i<Sigma; ++i) son[i] = NULL;
}
};
Trie *root = new Trie;
string S;
void add(int pos, Trie *node){
if (pos == (int)S.sz()){
//cout << S << " " << node->countWord<< "\n";
node->countWord++;// here it`s an word
//cout << node->countWord << "\n";
return;
}
int letter = S[pos] - 'a';
if (node->son[letter] == NULL){// new appereance
Trie *newNode = new Trie();
node->son[letter] = newNode;
newNode->countPrefix++;
add(pos+1, newNode);
}else{
node->son[letter]->countPrefix++;
add(pos+1, node->son[letter]);
}
}
void del(int pos, Trie *node){
if (pos == (int)S.sz()){
node->countWord--;
}else{
int letter = S[pos] - 'a';
node->son[letter]->countPrefix--;
del(pos+1, node->son[letter]);
}
}
int countOcc(int pos, Trie *node){
if (pos == (int)S.sz()){
return node->countWord;
}else{
int letter = S[pos] - 'a';
if (node->son[letter] == NULL || node->son[letter]->countPrefix == 0)
return 0;
else return countOcc(pos+1, node->son[letter]);
}
}
int lcp(int pos, Trie *node, int x){
if (pos == (int)S.sz() || node->son[ S[pos]-'a' ] == NULL || node->son[ S[pos]-'a' ]->countPrefix==0){
return x;
}else{
return lcp(pos+1, node->son[ S[pos]-'a' ], x+1);
}
}
int main(){
for(; getline(f, S); ){
switch( S[0] ){
case '0':// add a new word
add(2, root);
break;
case '1':// delete occurrence of a word
del(2, root);
break;
case '2':// number of occurrence of a word
g << countOcc(2, root) << "\n";
break;
case '3':
g << lcp(2, root, 0) << "\n";
break;
}
}
f.close();
g.close();
return 0;
}