Pagini recente » Cod sursa (job #1469191) | Cod sursa (job #1583394) | Cod sursa (job #2819392) | Cod sursa (job #235682) | Cod sursa (job #2664378)
#include<bits/stdc++.h>
#define fore(start,i,end) for(int i = start; i <= end; i++)
#define dbg(x) #x << "=" << x << " "
#define dbg2(x,y) "{" << x << "," << y << "} "
#define dbg3(x,y,k) "{" << x << "," << y << "," << k << "} "
#define dbg4(x,y,k,j) "{" << x << "," << y << "," << k << " , " << j << "} "
#define ll long long
#define f1 first
#define f2 second
#define inf 1000000005
#define debug_st(st) if (true) {cout << #st << " : "; stack<int> s123; while (!s123.empty()) cout << s123.top() << " ", s123.pop(); cout << "\n";}
#define debug_a(a,n) cout << #a << " : "; for(int i = 1; i <= n; i++) cout << a[i] << " "; cout << "\n";
#define debug_m(a,n,m) cout << #a << " :\n"; for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++) cout << a[i][j] << " "; cout << "\n"; }cout << "\n";
#define debug_v(v) cout << #v << " : "; for(auto k : v) cout << k << " "; cout << "\n";
#define debug_s(s) cout << #s << " : "; for (auto k : s) cout << k < " "; cout << "\n";
#define debug_s2(s) cout << #s << " : "; for(auto k : s) cout << dbg2((*k).first,(*k).second); cout << "\n";
#define nmax
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
int tip;
string w;
const int ALF = 26;
struct Trie
{
int nrCuv,nrFii;
Trie* tranzitii[ALF];
Trie()
{
nrCuv = nrFii = 0;
for (int i = 0; i < 26; i++)
tranzitii[i] = nullptr;
}
};
void Add(Trie* nod, string &str , int poz)
{
//cout << poz << " " << str << "\n";
if (poz == str.size())
{
nod -> nrFii++;
nod -> nrCuv++;
return;
}
nod -> nrFii++;
if (nod -> tranzitii[str[poz] - 'a'] == nullptr)
nod -> tranzitii[str[poz] - 'a'] = new Trie();
Add(nod -> tranzitii[str[poz] -'a'] , str , poz + 1);
}
void Erase(Trie* nod, string &str , int poz)
{
if (poz == str.size())
{
nod -> nrFii--;
nod -> nrCuv--;
if (nod -> nrFii == 0 && nod -> nrCuv == 0) {
delete nod;
nod = nullptr;
}
return;
}
nod -> nrFii--;
Erase(nod -> tranzitii[str[poz] - 'a'] , str , poz + 1);
}
void Query(Trie* nod, string &str , int poz)
{
if (poz == str.size())
{
out << nod -> nrCuv << "\n";
return;
}
if (nod -> tranzitii[str[poz] - 'a'] == nullptr)
{
out << "0\n";
return;
}
Query(nod -> tranzitii[str[poz] -'a'] , str , poz + 1);
}
void Prefix(Trie* nod, string &str , int poz)
{
if (poz == str.size())
{
out << poz << "\n";
return;
}
if (nod -> tranzitii[str[poz] - 'a']== nullptr)
{
out << poz << "\n";
return;
}
Prefix(nod -> tranzitii[str[poz] - 'a'] , str , poz + 1);
}
Trie* trie = new Trie();
int main()
{
while (in >> tip >> w)
{
if (tip == 0)
{
Add(trie , w , 0); /// poz adica care trebuie adaugata
}
else if (tip == 1)
{
Erase(trie , w , 0);
}
else if(tip == 2)
{
Query(trie , w, 0);
}
else if(tip == 3)
{
Prefix(trie , w , 0);
}
}
}