Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <unordered_map>
- #include <cmath>
- #include <vector>
- using namespace std;
- struct Node {
- int terminate = 0;
- unordered_map<char, int> next;
- };
- int index = 1;
- vector<Node> bor;
- int d;
- int maxLength = 0;
- vector<vector<int>> dp;
- int currentAns;
- void addString(string& str) {
- int currentIndex = 0;
- for (int i = 0; i < str.size(); ++i) {
- if (bor[currentIndex].next.count(str[i]) == 0) {
- Node newNode;
- bor.push_back(newNode);
- bor[currentIndex].next[str[i]] = index;
- index++;
- }
- currentIndex = bor[currentIndex].next[str[i]];
- }
- bor[currentIndex].terminate++;
- }
- void checkBor(int currentIndex) {
- cout << currentIndex << " ";
- for (auto x : bor[currentIndex].next) {
- cout << x.first << " ";
- }
- cout << bor[currentIndex].terminate << "\n";
- for (auto x : bor[currentIndex].next) {
- checkBor(x.second);
- }
- }
- void countCurrentAns(int currentIndex, string& str, int l, int r, int lastL, int lastR, int len, char ch) {
- bool isEnd = true;
- // cout << currentIndex << " " << l << " " << r << " " << lastL << " " << lastR << " " << len << " " << ch << "\n";
- for (int i = l; i <= r; ++i) {
- if (len == 0) {
- if (i == l) {
- dp[len][0] = 0;
- }
- else {
- dp[len][i - l] = dp[len][i - l - 1] + 1;
- }
- isEnd = false;
- }
- else {
- int left = 1e9;
- if (i != l) {
- left = dp[len][i - l - 1] + 1;
- }
- int up = 1e9;
- if (lastL <= i && i <= lastR) {
- up = dp[len - 1][i - lastL] + 1;
- }
- int diag = 1e9;
- if (lastL <= (i - 1) && (i - 1) <= lastR) {
- diag = dp[len - 1][(i - 1) - lastL] + 1;
- if (str[i - 1] == ch) {
- diag--;
- }
- }
- dp[len][i - l] = min(left, min(up, diag));
- if (dp[len][i - l] <= d) {
- isEnd = false;
- }
- }
- // cout << dp[len][i - l] << " ";
- }
- // cout << "\n\n";
- if (r == str.size() && dp[len][r - l] <= d) {
- currentAns += bor[currentIndex].terminate;
- }
- if (!isEnd) {
- for (auto x : bor[currentIndex].next) {
- countCurrentAns(x.second, str, (len <= d ? 0 : l + 1), (r == str.size() ? r : r + 1), l, r, len + 1, x.first);
- }
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- Node root;
- bor.push_back(root);
- string str;
- int n;
- cin >> n;
- for (int i = 0; i < n; ++i) {
- cin >> str;
- addString(str);
- maxLength = max(maxLength, (int)str.size());
- }
- cin >> d;
- dp = vector<vector<int>>(maxLength + 1, vector<int>(d*2 + 1));
- int k;
- cin >> k;
- for (int i = 0; i < k; ++i) {
- cin >> str;
- currentAns = 0;
- countCurrentAns(0, str, 0, min(d, (int)str.size()), -1, -1, 0, '*');
- cout << currentAns << "\n";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement