#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define pii pair<ll, ll>
#define fi first
#define se second
const ll N = 2e5 + 5, inf = 1e18;
const int MAXT = 2000005;
int n, m;
string a[N], b[N], c[N];
int L[MAXT], R[MAXT];
int child[2][MAXT][26], cnt;
vector<int> pre[MAXT];
void add(int type, string s, int pos) {
int u = 0;
if (type) reverse(s.begin(), s.end());
for (char ch : s) {
int k = ch - '0';
if (!child[type][u][k]) child[type][u][k] = ++cnt;
u = child[type][u][k];
if (!type) {
if (!L[u]) L[u] = pos;
R[u] = pos;
} else {
pre[u].push_back(pos);
}
}
}
int get0(string s) {
int u = 0;
for (char ch : s) {
int k = ch - '0';
if (!child[0][u][k]) return 0;
u = child[0][u][k];
}
return u;
}
vector<int> get1(string s) {
int u = 0;
reverse(s.begin(), s.end());
for (char ch : s) {
int k = ch - '0';
if (!child[1][u][k]) return {};
u = child[1][u][k];
}
return pre[u];
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++) cin >> b[i] >> c[i];
sort(a + 1, a + n + 1);
for (int i = 1; i <= n; i++) {
add(0, a[i], i);
add(1, a[i], i);
}
for (int i = 1; i <= m; i++) {
int val1 = get0(b[i]);
vector<int> val2 = get1(c[i]);
if (!val1 || L[val1] == 0 || R[val1] == 0 || val2.empty()) {
cout << 0 << '\n';
continue;
}
int it1 = lower_bound(val2.begin(), val2.end(), L[val1]) - val2.begin();
int it2 = upper_bound(val2.begin(), val2.end(), R[val1]) - val2.begin() - 1;
if (it1 > it2) {
cout << 0 << '\n';
} else {
cout << it2 - it1 + 1 << '\n';
}
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |