Cod sursa(job #2642414)

Utilizator oglindaoglinjoaraJohn Cena oglindaoglinjoara Data 15 august 2020 10:21:31
Problema Trie Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include<bits/stdc++.h>
#define Nmax 2000100
#define mp make_pair
using namespace std;
int x;
string s;
int cnt[Nmax], ending[Nmax];
int NR = 0;
map<pair<int, char>, int > children;

void insert(int nod, string &s, int ind) {
  ++cnt[nod];
  if(ind == s.size()) {
    ++ending[nod];
    return;
  }
  if(!children[mp(nod, s[ind])]) {
    children[mp(nod, s[ind])] = ++NR;
  }
  int ch = children[mp(nod, s[ind])];
  insert(ch, s, ind+1);    
}

void del(int nod, string &s, int ind) {
  --cnt[nod];
  if(ind == s.size()) {
    --ending[nod];
    return;
  }
  del(children[mp(nod, s[ind])], s, ind+1);
}

int count(int nod, string &s, int ind) {
  if(ind == s.size()) {
    return ending[nod];
  }
  if(!children[mp(nod, s[ind])]) return 0;
  return count(children[mp(nod, s[ind])], s, ind+1); 
}

int lp(int nod, string &s, int ind) {
  if(!cnt[nod]) return max(0, ind-1);
  if(ind == s.size() || !children[mp(nod, s[ind])]) {
    return ind;
  }
  return lp(children[mp(nod, s[ind])], s, ind+1);
}

int main() {
  cin.sync_with_stdio(false);
  ifstream fin("trie.in");
  ofstream fout("trie.out");
  while(fin>>x>>s) {
    if(x == 0) insert(0, s, 0);
    if(x == 1) del(0, s, 0);
    if(x == 2) fout<<count(0, s, 0)<<"\n";
    if(x == 3) fout<<lp(0, s, 0)<<"\n";
  }
  
}