Cod sursa(job #2633604)

Utilizator Alex_tz307Lorintz Alexandru Alex_tz307 Data 7 iulie 2020 21:26:41
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>
#define CH (*s - 'a')

using namespace std;

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

struct Trie {
	int cnt, nrfii;
	Trie *fiu[26];
	Trie() {
		cnt = nrfii = 0;
		memset (fiu, 0, sizeof(fiu));
	}
};

Trie * T = new Trie;

void Insert (Trie *nod, char *s) {
	if (*s == '\n') {
		nod -> cnt ++;
		return;
	}
	if (nod -> fiu[CH] == 0) {
		nod -> fiu[CH] = new Trie;
		nod -> nrfii ++;
	}
	Insert (nod -> fiu[CH], s + 1);
}

int Delete (Trie *nod, char *s) {
	if (*s == '\n')
		nod -> cnt --;
	else
    if (Delete (nod -> fiu[CH], s + 1) ) {
			nod -> fiu[CH] = 0;
			nod -> nrfii --;
		}
	if (nod -> cnt == 0 && nod -> nrfii == 0 && nod != T ) {
		delete nod;
    return 1;
	}
	return 0;
}

int Count (Trie *nod, char *s) {
	if (*s == '\n')
		return nod -> cnt;
	if (nod -> fiu[CH])
		return Count (nod -> fiu[CH], s + 1);
	return 0;
}

int Preffix (Trie *nod, char *s, int k) {
	if (*s == '\n' || nod -> fiu[CH] == 0 )
		return k;
	return Preffix (nod -> fiu[CH], s + 1, k + 1);
}

int main() {
	short op;
  char s[32];
  while (fin.getline (s, sizeof(s))) {
    s[strlen(s)] = '\n';
    if (s[0] == '0')
      Insert (T, s + 2);
    if (s[0] == '1')
      Delete (T, s + 2);
    if (s[0] == '2')
      fout << Count (T, s + 2) << '\n';
    if (s[0] == '3')
      fout << Preffix (T, s + 2, 0) << '\n';
  }
	return 0;
}