H

 avatar
meda
c_cpp
a month ago
1.9 kB
25
Indexable
#include<bits/stdc++.h>
#define ll long long
#define endl "\n"
using namespace std;
template<class T>
void printff(vector<T>& v) {
  for (auto k : v) cout << k << " ";
  cout << endl;
}
struct Trie{
    struct Node{
        Node *ch[26];
        int prefix;
        int end;
        int val;
        Node(){
            prefix = end = val = 0;
            memset(ch, 0, sizeof(ch));
        }
    };
    Node *root = new Node();
    void insert(string &s){
        Node *current = root;
        for (char c : s){
            int idx = c - 'a';
            if (current->ch[idx] == 0)
                current->ch[idx] = new Node();
            current = current->ch[idx];
            current->prefix++;
        }
        current->end++;
    }
    void pre(Node * current){
        int mn = 1e9;
        for(int i = 0; i < 26; i++){
            if(current->ch[i] != 0){
                pre(current -> ch[i]);
                mn = min(mn, current -> ch[i] -> val);
            }
        }
        if(current -> end){
            current -> val = 0;
        }else{
            if(mn == 1e9) current -> val = 0;
            else current -> val = mn + 1;
        }
    }
    int count(string s){
        Node *current = root;
        for (char c : s){
            int idx = c - 'a';
            if (current->ch[idx] == 0)
                return -1;
            current = current->ch[idx];
        }
        return current->val;
    }
};
void SOLVE() {
   int n, m; cin >> n >> m;
   Trie tree;
   for(int i = 0; i < n; i++){
    string s; cin >> s;
    tree.insert(s);
   }
   tree.pre(tree.root);

   for(int i = 0; i < m; i++){
    string s; cin >> s;
    cout << tree.count(s) << endl;
   }
}
int main() {
  ios_base::sync_with_stdio(false); 
  cin.tie(NULL); 
  cout.tie(NULL);
  int tc = 1; //cin >> tc;
  while(tc--) SOLVE();
  return 0;
}
Leave a Comment