2025-09-12 14:50:25 -03:00

157 lines
3.2 KiB
C++

/* Problem URL: https://codeforces.com/problemset/problem/633/C */
#include <bits/stdc++.h>
using namespace std;
#define V vector
#define rmin(a, b) a = min(a, b)
#define rmax(a, b) a = max(a, b)
#define rep(i, lim) for (size_t i = 0; i < (lim); i++)
#define nrep(i, s, lim) for (size_t i = s; i < (lim); i++)
#define repv(i, v) for (auto &i : (v))
#define fillv(v) for (auto &itr_ : (v)) { cin >> itr_; }
#define sortv(v) sort(v.begin(), v.end())
#define all(v) (v).begin(), (v).end()
using vi = vector<int>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using vvvvi = vector<vvvi>;
using ll = long long;
using vl = vector<ll>;
using vvl = vector<vl>;
using vvvl = vector<vvl>;
using vvvvl = vector<vvvl>;
template<class v>
auto operator<<(ostream &os, const vector<v> &vec)->ostream& {
os << vec[0];
for (size_t i = 1; i < vec.size(); i++) {
os << ' ' << vec[i];
}
os << '\n';
return os;
}
template<class v>
auto operator>>(istream &is, vector<v> &vec)->istream& {
for (auto &i : vec) {
is >> i;
}
return is;
}
template<class v>
auto operator<<(ostream &os, const vector<vector<v>> &vec)->ostream& {
for (auto &i : vec) {
os << i[0];
for (size_t j = 1; j < i.size(); j++) {
os << ' ' << i[j];
}
os << '\n';
}
return os;
}
template<class v>
auto operator>>(istream &is, vector<vector<v>> &vec)->istream& {
for (auto &i : vec) {
for (auto &j : i) {
is >> j;
}
}
return is;
}
struct hashed_string {
static vl p;
static ll m;
static ll b;
vl hash;
hashed_string(string &a) {
while (p.size() <= a.size()) {
p.push_back(((__int128)p.back() * b) % m);
}
hash.resize(a.size() + 1);
rep(i, a.size()) {
hash[i + 1] = ((__int128)hash[i] * b + tolower(a[i])) % m;
}
}
ll gethash(int l, int r) {
return ((hash[r + 1] - (__int128)hash[l] * p[r - l + 1]) % m + m) % m;
}
};
vl hashed_string::p = {1};
ll hashed_string::m = (1LL << 61) - 1;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll hashed_string::b = uniform_int_distribution<ll>(1, m - 1)(rng);
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
string a;
cin >> a;
int m;
cin >> m;
unordered_map<ll, int> hashes;
V<string> msg(m);
int v = 0;
for (auto &i : msg) {
cin >> i;
hashed_string tmp(i);
hashes[tmp.hash.back()] = v;
v++;
}
reverse(all(a));
hashed_string rev(a);
vi dp(n + 1, -1);
vi aux(n + 1, -1);
dp[0] = 0;
for (size_t i = 1; i <= n; i++) {
if (dp[i - 1] == -1) {
continue;
}
size_t lim = min(n - i + 1, (size_t)1000);
rep(j, lim) {
ll hash = rev.gethash(n - i - j, n - i);
if (hashes.count(hash)) {
aux[i + j] = hashes[hash];
dp[i + j] = i;
}
}
}
stack<int> s;
size_t i = dp.size() - 1;
while (i > 0) {
s.push(aux[i]);
i = dp[i] - 1;
}
while (!s.empty()) {
cout << msg[s.top()] << ' ';
s.pop();
}
cout << '\n';
}