Pagini recente » Cod sursa (job #447738) | Cod sursa (job #798074) | Cod sursa (job #2026362) | Cod sursa (job #2583303) | Cod sursa (job #1410360)
#include<algorithm>
#include<bitset>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<deque>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<vector>
using namespace std;
#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "trie";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif
struct node {
int cnt;
int end;
node *f[26];
node() {
cnt = end = 0;
memset(f, 0, sizeof(f));
}
};
node *root;
void insert(char *word) {
int i, L = strlen(word), c;
node *Q = root;
for(i = 0; i < L; i++) {
c = word[i] - 'a';
if(Q->f[c] == NULL)
Q->f[c] = new node;
Q = Q->f[c];
Q->cnt++;
}
Q->end++;
}
void erase(char *word) {
int i, L = strlen(word), c;
node *Q = root;
stack<node*> S;
S.push(root);
for(i = 0; i < L; i++) {
c = word[i] - 'a';
Q = Q->f[c];
Q->cnt--;
S.push(Q);
}
Q->end--;
while(S.size() > 1) {
Q = S.top();
S.pop();
if(Q->cnt)
return;
S.top()->f[word[S.size() - 1] - 'a'] = 0;
delete Q;
}
}
int count(char *word) {
int i, L = strlen(word), c;
node *Q = root;
for(i = 0; i < L; i++) {
c = word[i] - 'a';
if(Q->f[c] == NULL)
return 0;
Q = Q->f[c];
}
return Q->end;
}
int preffix(char *word) {
int i, L = strlen(word), c;
node *Q = root;
for(i = 0; i < L; i++) {
c = word[i] - 'a';
if(Q->f[c] == NULL)
return i;
Q = Q->f[c];
}
return L;
}
int main() {
int t;
char word[25];
#ifndef ONLINE_JUDGE
freopen(inputFile.c_str(), "r", stdin);
freopen(outputFile.c_str(), "w", stdout);
#endif
root = new node;
while(scanf("%d %s\n", &t, &word) + 1) {
if(t == 0)
insert(word);
if(t == 1)
erase(word);
if(t == 2)
printf("%d\n", count(word));
if(t == 3)
printf("%d\n", preffix(word));
}
return 0;
}