Pagini recente » Cod sursa (job #2290448) | Cod sursa (job #1944939) | Cod sursa (job #3276314) | Cod sursa (job #1215122) | Cod sursa (job #2094332)
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
const int NLIM = 2e6 + 10;
vector< int > graph[NLIM];
int graphSize = 1;
char nodChar[NLIM];
int nodCnt[NLIM];
int parent[NLIM];
string s;
void add( )
{
int nod = 0;
for( int i = 0; i < s.size(); ++i )
{
// find next node:
bool found = 0;
for( int j = 0; j < graph[nod].size() && !found; ++j )
{
int nnod = graph[nod][j];
if( nodChar[nnod] == s[i] )
{
nod = nnod;
found = 1;
}
}
if( !found )
{
// add new node
graph[nod].push_back( graphSize );
nodChar[graphSize] = s[i];
parent[graphSize] = nod;
nod = graphSize;
++graphSize;
}
}
++nodCnt[nod];
}
void del( )
{
int nod = 0;
for( int i = 0; i < s.size(); ++i )
{
// find next node:
bool found = 0;
for( int j = 0; j < graph[nod].size() && !found; ++j )
{
int nnod = graph[nod][j];
if( nodChar[nnod] == s[i] )
{
nod = nnod;
found = 1;
}
}
}
// nod
nodCnt[nod] -= 1;
if( nodCnt[nod] == 0 )
{
while( graph[nod].size() == 0 )
{
int pnod = parent[nod];
// find and delete nod:
bool found = 0;
for( int j = 0; j < graph[pnod].size() && !found; ++j )
{
int nnod = graph[pnod][j];
if( nnod = nod )
{
// delete node from graph
graph[pnod].erase( graph[pnod].begin() + j );
found = 1;
}
}
nod = pnod;
}
}
}
int cnt( )
{
int nod = 0;
for( int i = 0; i < s.size(); ++i )
{
// find next node:
bool found = 0;
for( int j = 0; j < graph[nod].size() && !found; ++j )
{
int nnod = graph[nod][j];
if( nodChar[nnod] == s[i] )
{
nod = nnod;
found = 1;
}
}
if( !found )
{
nod = 0;
break;
}
}
return nodCnt[nod];
}
int pref()
{
int nod = 0;
int len = 0;
for( int i = 0; i < s.size(); ++i )
{
// find next node:
bool found = 0;
for( int j = 0; j < graph[nod].size() && !found; ++j )
{
int nnod = graph[nod][j];
if( nodChar[nnod] == s[i] )
{
nod = nnod;
found = 1;
}
}
if( found )
len = i + 1;
if( !found )
break;
}
return len;
}
ifstream fcin("trie.in");
ofstream fcout("trie.out");
//ofstream fcout2("ts.txt");
int main()
{
nodChar[0] = '-';
//cout << "wa";
while( !cin.eof() )
{
int t = -2;
fcin >> t >> s;
//cout << t << "\n";
if( t == -2 )
break;
if( t == 0 )
{
add();
}
else if( t == 1 )
{
del();
}
else if( t == 2 )
{
fcout << cnt() << "\n";
}
else
{
fcout << pref() << "\n";
}
//if( t == 2 || t == 3 )
//fcout2 << t << " " << s << "\n";
}
/*/
for( int i = 0; i < graphSize; ++i )
{
cout << i << "(" << nodChar[i] << "): ";
for( int j = 0; j < graph[i].size(); ++j )
{
cout << graph[i][j] << "(" << nodChar[graph[i][j]] << ") ";
}
cout << "\n";
}
//*/
}