Pagini recente » Cod sursa (job #292914) | Istoria paginii runda/testround | Cod sursa (job #2716098) | Cod sursa (job #2963863) | Cod sursa (job #831345)
Cod sursa(job #831345)
#include <fstream>
#include <cassert>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
const int sigma= 26;
const int lmax= 20;
struct tn{
tn *son[sigma];
int d, ns;
tn(){
for (int i= 0; i<sigma; ++i){
son[i]= 0;
}
d= 0; ns= 0;
}
};
tn *tr= new tn;
char ch[lmax+4];
void tr_ins(tn *x, char *s){
if (*s==0){
++x->d;
}else{
if (x->son[*s-'a']==0){
++x->ns;
x->son[*s-'a']= new tn;
}
tr_ins(x->son[*s-'a'], s+1);
}
}
int tr_del(tn *x, char *s){
if (*s==0){
--x->d;
}else{
if (tr_del(x->son[*s-'a'], s+1)){
x->son[*s-'a']= 0;
--x->ns;
}
}
if (x->ns==0&& x->d==0&& x!=tr){
delete x;
return 1;
}else{
return 0;
}
}
int tr_q(tn *x, char *s){
if (*s==0){
return x->d;
}else if (x->son[*s-'a']!=0){
return tr_q(x->son[*s-'a'], s+1);
}else{
return 0;
}
}
int tr_qp(tn *x, char *s, int k){
if (*s==0){
return k;
}else if (x->son[*s-'a']!=0){
return tr_qp(x->son[*s-'a'], s+1, k+1);
}else{
return k;
}
}
int main(){
while (!fin.getline(ch, lmax+4).eof()){
if (ch[0]=='0'){
tr_ins(tr, ch+2);
}else if (ch[0]=='1'){
tr_del(tr, ch+2);
}else if (ch[0]=='2'){
fout<<tr_q(tr, ch+2)<<"\n";
}else{
fout<<tr_qp(tr, ch+2, 0)<<"\n";
}
}
return 0;
}