Cod sursa(job #2741942)

Utilizator Uriesu_IuliusUriesu Iulius Uriesu_Iulius Data 19 aprilie 2021 19:50:14
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>

using namespace std;

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

struct trieNode
{
    trieNode *children[26];
    int cnt, pref;
};
trieNode *root;

void init(trieNode *p)
{
    int i;
    for(i=0; i<26; i++)
        p->children[i]=NULL;
    p->cnt=0;
    p->pref=0;
}

void insertKey(char s[25], int val)
{
    int i, l=strlen(s);
    trieNode *p=root;
    for(i=0; i<l; i++)
    {
        if(p->children[s[i]-'a']==NULL)
        {
            trieNode *q = new trieNode;
            init(q);
            p->children[s[i]-'a']=q;
        }
        p=p->children[s[i]-'a'];
        p->pref+=val;
        if(i==l-1)
            p->cnt+=val;
    }
}

int searchKey(char s[25])
{
    int i, l=strlen(s);
    trieNode *p=root;
    for(i=0; i<l; i++)
    {
        p=p->children[s[i]-'a'];
        if(p==NULL)
            return 0;
    }
    return p->cnt;
}

int longestCommonPrefix(char s[25])
{
    int i, l=strlen(s);
    trieNode *p=root;
    int ans=0;
    for(i=0; i<l; i++)
    {
        p=p->children[s[i]-'a'];
        if(p==NULL)
            return ans;
        if(p->pref==0)
            return ans;
        ans++;
    }
    return ans;
}

int main()
{
    int op;
    char s[25];
    root = new trieNode;
    init(root);
    while(fin >> op >> s)
    {
        if(op==0)
            insertKey(s, 1);
        else if(op==1)
            insertKey(s, -1);
        else if(op==2)
            fout << searchKey(s) << '\n';
        else
            fout << longestCommonPrefix(s) << '\n';
    }
    return 0;
}