Cod sursa(job #2453823)

Utilizator vlad.ulmeanu30Ulmeanu Vlad vlad.ulmeanu30 Data 6 septembrie 2019 10:36:48
Problema Trie Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>
#define lll long long
#define pii pair<int,int>
#define pll pair<lll,lll>
#define fi first
#define se second
#define vi vector<int>
#define pb push_back
#define sz(a) (int)(a).size()
#define inf (INT_MAX/2-1)
#define infl (1LL<<61)
#define aaa system("pause");
#define dbg(x) cerr<<(#x)<<": "<<x<<'\n',aaa
#define dbga(x,n) cerr<<(#x)<<"[]: ";for(int _=0;_<n;_++)cerr<<x[_]<<' ';cerr<<'\n',aaa
#define sigma 26

using namespace std;

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

struct nod {
  int amt, fii;
  nod* dad;
  nod* son[sigma];
  nod() {
    amt = 0; fii = 0; dad = NULL;
    for (int i = 0; i < sigma; i++) son[i] = NULL;
  }
};

nod* root;

void tclean (nod* u, char ch) {
  if (u->amt == 0 && u->fii == 0 && u != root && u->dad != NULL) {
    u->dad->fii--;
    u->dad->son[ch-'a'] = NULL;
    delete u;
  }
}

void tshift (nod* u, int l, string &s, int way) {
  int i = s[l] - 'a';
  if (l == sz(s)) {
    u->amt += way;
    tclean(u, s[l-1]);
    return;
  }
  if (u->son[i] == NULL) {
    u->son[i] = new nod;
    u->son[i]->dad = u;
    u->fii++;
  }
  tshift (u->son[i], l+1, s, way);
  tclean(u, s[l]);
}

int tcount (nod* u, int l, string &s) {
  if (u == NULL) return 0;
  if (l == sz(s)) return u->amt;
  return tcount(u->son[s[l]-'a'], l+1, s);
}

int tpref (nod* u, int l, string &s) {
  if (u == NULL) return l-1;
  return tpref(u->son[s[l]-'a'], l+1, s);
}

int main () {
  root = new nod;
  int op; string s;
  fin >> op >> s;
  while (!fin.eof()) {
    if (op == 0) tshift(root, 0, s, 1);
    else if (op == 1) tshift(root, 0, s, -1);
    else if (op == 2) fout << tcount(root, 0, s) << '\n';
    else fout << tpref(root, 0, s) << '\n';
    fin >> op >> s;
  }
  return 0;
}