Cod sursa(job #2446931)

Utilizator miguelMihail Lavric miguel Data 11 august 2019 12:47:19
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 3.61 kb
/*
░░░░░░░░░░░░░░░░▄▄█▀▀██▄▄░░░░░░░
░░░░░░░░░░░░░▄█▀▀░░░░░░░▀█░░░░░░
░░░░░░░░░░░▄▀░░░░░░░░░░░░░█░░░░░
░░░░░░░░░▄█░░░░░░░░░░░░░░░█░░░░░
░░░░░░░██▀░░░░░░░▄▄▄░░▄░█▄█▄░░░░
░░░░░▄▀░░░░░░░░░░████░█▄██░▀▄░░░
░░░░█▀░░░░░░░░▄▄██▀░░█████░██░░░
░░░█▀░░░░░░░░░▀█░▀█▀█▀▀▄██▄█▀░░░
░░░██░░░░░░░░░░█░░█░█░░▀▀▄█▀░░░░
░░░░█░░░░░█░░░▀█░░░░▄░░░░░▄█░░░░
░░░░▀█░░░░███▄░█░░░░░░▄▄▄▄█▀█▄░░
░░░░░▀██░░█▄▀▀██░░░░░░░░▄▄█░░▀▄░
░░░░░░▀▀█▄░▀▄▄░▄░░░░░░░███▀░░▄██
░░░░░░░░░▀▀▀███▀█▄░░░░░█▀░▀░░░▀█
░░░░░░░░░░░░▄▀░░░▀█▄░░░░░▄▄░░▄█▀
░░░▄▄▄▀▀▀▀▀█▀░░░░░█▄▀▄▄▄▄▄▄█▀▀░░
░▄█░░░▄██▀░░░░░░░░░█▄░░░░░░░░░░░
█▀▀░▄█░░░░░░░░░░░░░░▀▀█▄░░░░░░░░
█░░░█░░░░░░░░░░░░░░░░░░█▄░░░░░░░
*/
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define dbg(x) cout << #x << '=' << x << '\n';
#define ll long long
#define x first
#define y second
#define pi pair <int, int>
#define vi vector <int>
//#define =1e9 =(int)1e9
const ll mod = 1000000007;
const ll nmax=1000003;
//#define int ll
int op, idx;
string s;

struct nod{
    int cnt, fin, next[26];
} init;

vector <nod> v;

void add(string s){
    int cur=0;
    for(int i=0; i<s.size(); i++){
        int c=s[i]-'a';
        if(v[cur].next[c]==0){
            v[cur].next[c]=++idx;
            v.pb(init);
        }
        cur=v[cur].next[c];
        if(i==s.size()-1) v[cur].fin++;
        else v[cur].cnt++;
    }
}

void del(string s){
    int cur=0;
    for(int i=0; i<s.size(); i++){
        int c=s[i]-'a';
        cur=v[cur].next[c];
        if(i==s.size()-1) v[cur].fin--;
        else v[cur].cnt--;
    }
}

int cont(string s){
    int cur=0;
    for(int i=0; i<s.size(); i++){
        int c=s[i]-'a';
        cur=v[cur].next[c];
        if(i==s.size()-1) return v[cur].fin;
        else if(v[cur].cnt==0) return 0;
    }
}

int pref(string s){
    int cur=0, ans=0;
    for(int i=0; i<s.size(); i++){
        int c=s[i]-'a';
        if(cur<=idx) cur=v[cur].next[c];
        if(cur==0 || cur>idx || v[cur].cnt==0) return ans;
        ans++;
    }
    return ans;
}

int32_t main(){
    ios_base :: sync_with_stdio(0); cin.tie(); cout.tie();
    ifstream cin("trie.in");
    ofstream cout("trie.out");
    int xd[26];
    memset(xd, 0, sizeof xd);
    init.cnt=0;
    v.pb(init);
    while(cin>>op>>s){
        if(op==0) add(s);
        else if(op==1) del(s);
        else if(op==2) cout<<cont(s)<<"\n";
        else if(op==3) cout<<pref(s)<<"\n";
    }
}