Cod sursa(job #2231286)

Utilizator mihai.alphamihai craciun mihai.alpha Data 13 august 2018 17:48:43
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>

using namespace std;

FILE *fin = fopen("trie.in", "r"), *fout = fopen("trie.out", "w");

struct trie  {
    int cnt, nrfii;
    trie *fii[26];
};

trie *t = new trie{};

#define ch *s - 'a'

void push(trie *nod, char *s)  {
    if(*s == '\n')  {
        nod -> cnt++;
        return;
    }
    if(nod -> fii[ch] == 0)  {
        nod -> fii[ch] = new trie{};
        nod -> nrfii++;
    }
    push(nod -> fii[ch], s + 1);
}

bool pop(trie *nod, char *s)  {
    if(*s == '\n')
        nod -> cnt--;
    else if(pop(nod -> fii[ch], s + 1))  {
        nod -> fii[ch] = 0;
        nod -> nrfii--;
    }
    if(nod -> nrfii == 0 && nod -> cnt == 0 && nod != t)  {
        delete nod;
        return 1;
    }
    return 0;
}

int ans;

int count(trie *nod, char *s)  {
    if(*s == '\n')  {
        return nod -> cnt;
    }
    if(nod -> fii[ch] == 0)  {
        return 0;
    }
    return count(nod -> fii[ch], s + 1);
}

int pref(trie *nod, char *s)  {
    if(*s == '\n')
        return ans;
    if(nod -> fii[ch] == 0)
        return ans;
    ans++;
    pref(nod -> fii[ch], s + 1);
}

int main()  {
    int op;
    char s[27];
    fscanf(fin, "%d ", &op);
    fgets(s, 27, fin);
    while(!feof(fin))  {
        switch(op)  {
            case 0:
            push(t, s);
            break;
            case 1:
            pop(t, s);
            break;
            case 2:
            fprintf(fout, "%d\n", count(t, s));
            break;
            case 3:
            ans = 0;
            fprintf(fout, "%d\n", pref(t, s));
            break;
        }
        fscanf(fin, "%d ", &op);
        fgets(s, 27, fin);
    }
    fclose(fin), fclose(fout);
    return 0;
}