Pagini recente » Cod sursa (job #1590129) | Cod sursa (job #2684030) | Cod sursa (job #29957) | Cod sursa (job #2921748) | Cod sursa (job #911033)
Cod sursa(job #911033)
#include<iostream>
#include<fstream>
#include<vector>
#include<bitset>
#include<queue>
#include<stack>
#include<iomanip>
#include<string>
#include<algorithm>
#define infile "trie.in"
#define outfile "trie.out"
#define nMax 15
#define INF (1 << 30)
#define pb push_back
#define mkp make_pair
#define pii pair<int, int>
#define ll long long
#define nxt (*it)
#define FOR(i,a,b) for(int i=a; i<=b; ++i)
#define R (*this)
using namespace std;
class Trie{
protected:
int numbWords, numbPreffixes;
bool isRoot;
Trie *edges[26];
public:
Trie(bool root){
numbWords = 0;
numbPreffixes = 0;
isRoot = root;
FOR(i,0,25)
edges[i] = NULL;
}
void insert(char *pWord){
if(*pWord == '\n'){
numbWords ++;
return;
}
numbPreffixes ++;
int index = *pWord - 'a';
if(edges[index] == NULL)
edges[index] = new Trie(false);
edges[index] -> insert(pWord + 1);
}
bool erase(char *pWord){
if(*pWord == '\n')
numbWords --;
else{
int index = *pWord - 'a';
if(edges[index] -> erase(pWord + 1)){
edges[index] = NULL;
numbPreffixes --;
}
}
if(!R.numbPreffixes && !R.numbWords && !isRoot){
delete this;
return true;
}
return false;
}
int countWords(char *pWord){
if(*pWord == '\n')
return numbWords;
int index = *pWord - 'a';
if(edges[index] == NULL)
return 0;
return edges[index] -> countWords(pWord + 1);
}
int countPreffixes(char *pWord){
if(*pWord == '\n')
return numbPreffixes;
int index = *pWord - 'a';
if(edges[index] == NULL)
return 0;
return edges[index] -> countWords(pWord + 1);
}
int countLCS(char *pWord){
int index = *pWord - 'a';
if(*pWord == '\n' || edges[index] == NULL)
return 0;
return edges[index] -> countLCS(pWord + 1) + 1;
}
} *T;
int main(){
freopen(infile, "r", stdin);
freopen(outfile, "w", stdout);
char line[30];
Trie T(true);
fgets( line, 30, stdin );
while(!feof( stdin )){
switch(line[0]){
case '0': T.insert(line + 2); break;
case '1': T.erase(line + 2); break;
case '2': printf("%d\n", T.countWords(line + 2)); break;
case '3': printf("%d\n", T.countLCS(line + 2)); break;
}
fgets( line, 30, stdin );
}
fclose(stdin);
fclose(stdout);
return 0;
}