Submission #1129447

#TimeUsernameProblemLanguageResultExecution timeMemory
1129447vladiliusSelling RNA Strands (JOI16_selling_rna)C++20
0 / 100
1603 ms217772 KiB
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;
#define pb push_back
#define ff first
#define ss second
const int base = 73;

struct TR{
    struct node{
        int nt[26];
        bool f;
    };
    vector<node> t;
    int cc, S;
    void init(){
        t.pb(node());
        t.pb(node());
        cc = 1;
        S = 0;
    }
    void add(string s){
        int v = 1;
        for (char x: s){
            int y = (x - 'A');
            if (!t[v].nt[y]){
                t[v].nt[y] = ++cc;
                t.pb(node());
            }
            v = t[v].nt[y];
        }
        t[v].f = 1;
        S += (int) s.size();
    }
    vector<int> tin, tout;
    map<ull, vector<int>> mp;
    int timer;
    string s;
    void dfs(int v){
        tin[v] = ++timer;
        if (t[v].f){
            ull h = 0, b = 1;
            for (int i = (int) s.size() - 1; i >= 0; i--){
                h += b * (s[i] - 'A' + 1);
                b *= base;
                mp[h].pb(tin[v]);
            }
        }
        for (int i = 0; i < 26; i++){
            int y = t[v].nt[i];
            if (!y) continue;
            s += ('A' + i);
            dfs(y);
            s.pop_back();
        }
        tout[v] = timer;
    }
    void build(){
        s = "";
        timer = 0;
        tin.resize(S + 1);
        tout.resize(S + 1);
        dfs(1);
    }
    vector<int> :: iterator it1, it2;
    int get(string p, string q){
        int v = 1;
        for (char x: p){
            int y = t[v].nt[x - 'A'];
            if (!y) return 0;
            v = y;
        }
        
        int l = tin[v], r = tout[v];
        ull h = 0, b = 1;
        for (int i = (int) q.size() - 1; i >= 0; i--){
            h += b * (q[i] - 'A' + 1);
            b *= base;
        }
        it1 = lower_bound(mp[h].begin(), mp[h].end(), l);
        it2 = upper_bound(mp[h].begin(), mp[h].end(), r);
        return (int) (it2 - it1);
    }
};

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    
    int n, q; cin>>n>>q;
    TR T; T.init();
    while (n--){
        string s; cin>>s;
        T.add(s);
    }
    T.build();
    while (q--){
        string p, q; cin>>p>>q;
        cout<<T.get(p, q)<<"\n";
    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...