Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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);
- }
- bool 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 true;
- }
- return false;
- }
- 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 >> op) {
- fin >> s;
- s[strlen(s)] = '\n';
- if(op == 0)
- Insert(T, s);
- if(op == 1)
- Delete(T, s);
- if(op == 2)
- fout << Count(T, s) << '\n';
- if(op == 3)
- fout << Preffix(T, s, 0) << '\n';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement