Pagini recente » Cod sursa (job #1940176) | Rating ValiNet Romania (valinetromania) | Rating Bujor Alexandru-Ionut (al3x_buj) | Cod sursa (job #1467545) | Cod sursa (job #883072)
Cod sursa(job #883072)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
const int sigma= 26;
const int lmax= 20;
struct tn{
int v[sigma];
int d, dp;
tn(){
for (int i= 0; i<sigma; ++i){
v[i]= -1;
}
d= 0; dp= 0;
}
};
vector <tn> tr;
queue <int> q;
char ch[lmax+4];
void tr_ins(int x, int i){
if (ch[i]==0){
++tr[x].d;
}else{
if (tr[x].v[ch[i]-'a']==-1){
if (q.empty()){
tr[x].v[ch[i]-'a']= tr.size();
tr.push_back(tn());
}else{
tr[x].v[ch[i]-'a']= q.front();
q.pop();
}
}
tr_ins(tr[x].v[ch[i]-'a'], i+1);
}
++tr[x].dp;
}
int tr_del(int x, int i){
if (ch[i]==0){
--tr[x].d;
}else{
if (tr_del(tr[x].v[ch[i]-'a'], i+1)){
tr[x].v[ch[i]-'a']= -1;
}
}
--tr[x].dp;
if (tr[x].dp==0){
q.push(x);
tr[x]= tn();
return 1;
}
return 0;
}
int tr_que(int x, int i){
if (ch[i]==0){
return tr[x].d;
}else if (tr[x].v[ch[i]-'a']!=-1){
return tr_que(tr[x].v[ch[i]-'a'], i+1);
}else{
return 0;
}
}
int tr_que_pre(int x, int i, int k){
if (ch[i]==0){
return k;
}else if (tr[x].v[ch[i]-'a']!=-1){
return tr_que_pre(tr[x].v[ch[i]-'a'], i+1, k+1);
}else{
return k;
}
}
int main(){
tr.push_back(tn());
while (fin.getline(ch, lmax+4).eof()==0){
if (ch[0]=='0'){
tr_ins(0, 2);
}else if (ch[0]=='1'){
tr_del(0, 2);
}else if (ch[0]=='2'){
fout<<tr_que(0, 2)<<"\n";
}else{
fout<<tr_que_pre(0, 2, 0)<<"\n";
}
}
return 0;
}