Cod sursa(job #2525880)

Utilizator cyg_TheoPruteanu Theodor cyg_Theo Data 17 ianuarie 2020 22:47:21
Problema Trie Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>

using namespace std;

const int SMAX = 23;
const int AL = 30;

struct node{
	int nxt[AL];
	int leaf=0;
	int nrw=0;
};

vector <node> trie;

void add_string(char *s){
	int nod=0;
	int n=strlen(s);
	for(int k=0;k<n;++k){
		int c=s[k]-'a';
		if(trie[nod].nxt[c]==0){
			trie[nod].nxt[c]=trie.size();
			trie.emplace_back();
		}
		nod=trie[nod].nxt[c];
		trie[nod].nrw++;
	}
	trie[nod].leaf++;
}

int find(char *s){
	int nod=0;
	int n=strlen(s);
	for(int k=0;k<n;++k){
		int c=s[k]-'a';
		nod=trie[nod].nxt[c];
	}
	return nod;
}

int length=0;

void deleted(char *s){
	int nod=0;
	int n=strlen(s);
	for(int k=0;k<n;++k){
		int c=s[k]-'a';
		nod=trie[nod].nxt[c];		
		trie[nod].nrw--;
	}
	trie[nod].leaf--;
}

void find_root(char *s){
	int nod=0;	
	int n=strlen(s);
	for(int k=0;k<n;++k){
		int c=s[k]-'a';
		nod=trie[nod].nxt[c];
		if(trie[nod].nrw<=0)
			break;
		length++;
	}
}

int main(){
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);

	int x;
	char s[SMAX];

	trie.emplace_back();

	while(scanf("%d %s",&x,s)!=EOF){
		if(x==0)
			add_string(s);
		if(x==1)
			deleted(s);
		if(x==2)
			printf("%d\n",trie[find(s)].leaf);
		if(x==3){
			length=0;
			find_root(s);
			printf("%d\n",length);
		}
	}
	return 0;
}