Cod sursa(job #3289772)

Utilizator pacelaaaCiurea Pavel pacelaaa Data 28 martie 2025 14:19:17
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ( "trie.in" );
ofstream fout ( "trie.out" );

#define cin fin
#define cout fout
#define FR( a, b ) for( int a = 0; a < (int) b; a ++ )
#define FOR( a, c, b) for( int a = c; a < (int) b; a ++ )

struct noduri {
  int frecv, nrcopii;
  noduri* children[26];

  noduri() {
    frecv = 0;
    FR( i, 26 )
      children[i] = NULL;
  }
};

noduri* root = new noduri;

void inserare( noduri* nod, string s, int poz ) {
  if( poz == s.size() ) {
    nod->frecv++;
    return;
  }

  if( nod->children[s[poz] - 'a'] == NULL ) {
    nod->children[s[poz]-'a'] = new noduri;
    nod->nrcopii++;
  }
  inserare( nod->children[s[poz] - 'a'], s, poz + 1 );
}

int distrugere( noduri* nod, string s, int poz ) {
  if( poz == s.size() ) {
    if( nod->nrcopii == 0 && nod->frecv == 1 ) {
      delete nod;
      return 1;
    }
    nod->frecv--;
    return 0;
  }

  if( distrugere( nod->children[s[poz]-'a'], s, poz + 1 ) == 1 ) {
    nod->nrcopii--;
    nod->children[s[poz] - 'a'] = NULL;
    if( nod->nrcopii == 0 && nod->frecv == 0 && nod != root ) {
      delete nod;
      return 1;
    }
  }
  return 0;
}

int nraparitii( noduri* nod, string s, int poz ) {
  if( poz == s.size() )
    return nod->frecv;

  return nraparitii( nod->children[s[poz] - 'a'], s, poz + 1);
}

int prefix( noduri* nod, string s, int poz ) {
  if( nod->children[s[poz]-'a'] == nullptr )
    return poz;

  return prefix( nod->children[s[poz]-'a'], s, poz + 1);
}

int main()
{
    int cerinta;
    string s;

    while( cin >> cerinta ) {
      cin >> s;
      if( cerinta == 0 )
        inserare( root, s, 0 );
      else if ( cerinta == 1 )
        distrugere( root, s, 0 );
      else if ( cerinta == 2 )
        cout << nraparitii(root, s, 0 ) << '\n';
      else
        cout << prefix( root, s, 0 ) << '\n';
    }

    return 0;
}