Mai intai trebuie sa te autentifici.
Cod sursa(job #944729)
Utilizator | Data | 29 aprilie 2013 16:52:50 | |
---|---|---|---|
Problema | Trie | Scor | 5 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 1.91 kb |
#include <fstream>
#include <vector>
#include <string.h>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
struct nod {
long v[27], nr, nctr;
void init()
{
for (char ii='a';ii!='z';ii++)
v[ii-'a']=0;
}
};
char s[25];
nod ng;
vector <nod> tr;
short op;
long ls, y;
void adauga(long x, long poz)
{
if(poz == ls)
tr[x].nr++;
else
{
y=tr[x].v[s[poz]-'a'];
if (y==0)
{
y=tr.size();
tr.push_back(ng);
}
tr[x].v[s[poz]-'a']=y;
adauga(y,poz+1);
}
tr[x].nctr++;
}
void sterge(long x, long poz)
{
if (poz==ls)
tr[x].nr--;
else
{
y=tr[x].v[s[poz]-'a'];
sterge(y,poz+1);
}
tr[x].nctr--;
}
void query1(long x, long poz)
{
if (poz==ls)
cout<<tr[x].nr<<'\n';
else
{
y=tr[x].v[s[poz]-'a'];
if (y==0)
cout<<"0\n";
else
query1(y,poz+1);
}
}
void query2(long x, long poz)
{
if (poz==ls)
cout<<poz<<"\n";
else
{
y=tr[x].v[s[poz]-'a'];
if ((y==0)||(tr[y].nctr==0))
cout<<poz<<"\n";
else
query2(y,poz+1);
}
}
int main()
{
// tr.push_back(ng);
tr.push_back(ng);
tr[0].nctr=1;//=tr[1].nctr=1;
int ct=0;
while(cin>>op>>s)
{
++ct;
ls=strlen(s);
if(op == 0)
adauga(1, 0);
else if(op == 1)
sterge(1, 0);
else if(op == 2)
query1(1, 0);
else query2(1, 0);
/* cout<<ct<<"\n";
for(int i = 0 ; i < tr.size(); ++i)
cout<<"Elementele nodului "<<i<<" sunt nr = "<<tr[i].nr<<" "<<tr[i].nctr<<"\n";
cout<<"\n";
*/ }
cin.close();
cout.close();
return 0;
}