1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| #include <bits/stdc++.h>
using namespace std; #define ll long long const int N = 1e6 + 10; const int INF = 0x3f3f3f3f; typedef pair<int, int> pii;
ll h1[N], p1[N], h2[N], p2[N], h3[N], p3[N], h4[N], p4[N]; ll m1 = 998244353, m2 = 1e9 + 7; ll P1 = 233, P2 = 3993;
void init(string s, int n, ll h[], ll p[], ll P, ll mod) { p[0] = 1; for (int i = 1; i <= n; i++) { h[i] = (h[i - 1] * P % mod + s[i] - 'a' + 1) % mod; p[i] = p[i - 1] * P % mod; } }
ll hsh(int l, int r, ll h[], ll p[], ll mod) { return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod; }
ll hsh(int l, int r) { return hsh(l, r, h1, p1, m1) * 2000000000ll + hsh(l, r, h2, p2, m2); }
ll hshr(int l, int r) { return hsh(l, r, h3, p3, m1) * 2000000000ll + hsh(l, r, h4, p4, m2); }
int n, m; int vis[N];
bool ck(int l, int n) { int mid = (l + n) / 2; if ((n - l + 1) & 1) { if (n - l + 1 == 1)return true; return hsh(l, mid - 1) == hshr(1, (n - l + 1) / 2); } else { return hsh(l, mid) == hshr(1, (n - l + 1) / 2); } }
int tot; int ch[N][30], cnt[N];
void ini() { tot = 0; memset(ch, 0, sizeof(ch)); memset(cnt, 0, sizeof(cnt)); }
void ins(string s) { int rt = 0; for (int i = 1; s[i]; i++) { int c = s[i] - 'a'; if (!ch[rt][c])ch[rt][c] = ++tot; rt = ch[rt][c]; cnt[rt] += vis[i]; } }
int qry(string t) { int rt = 0; for (int i = 1; t[i]; i++) { int c = t[i] - 'a'; if (!ch[rt][c])return 0; rt = ch[rt][c]; } return cnt[rt]; }
string s, rs; vector<string> v1, v2;
ll cal(vector<string> &v1, vector<string> &v2, int flg) { ini(); ll ans = 0; for (string s: v1) { rs = s; reverse(rs.begin(), rs.end()); s = '0' + s; rs = '0' + rs; int le = s.length() - 1; fill(vis, vis + le + 1, 0); init(s, le, h1, p1, P1, m1); init(s, le, h2, p2, P2, m2); init(rs, le, h3, p3, P1, m1); init(rs, le, h4, p4, P2, m2); for (int j = 2; j <= le; j++) { if (ck(j, le))vis[j - 1] = 1; } vis[le] = flg; ins(s); } for (string t: v2) { reverse(t.begin(), t.end()); t = '0' + t; ans += qry(t); } return ans; }
int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; for (int i = 1; i <= n; i++) { cin >> s; v1.push_back(s); } cin >> m; for (int i = 1; i <= m; i++) { cin >> s; v2.push_back(s); } ll ans = 0; ans += cal(v1, v2, 1); for(string& s:v1){ reverse(s.begin(), s.end()); } for(string& s:v2){ reverse(s.begin(), s.end()); } ans += cal(v2, v1, 0); cout << ans; return 0; }
|