解題思路
將所有字串反轉插入 trie,節點分別累計兩種顏色在此結束的位置數。原字串的嚴格後綴,恰是反轉後字串的嚴格前綴。
逐一走訪每個反轉字串,在尚未讀完前把當前節點的異色終點數加進答案。同內容的多個位置已由次數保留,每個短字串位置與長字串位置的有序對只在長字串走訪時被計一次;不計最後節點便排除了等長相同字串。
總字數 M≤300000,時間與空間 O(M+n),包括 Python trie 字典、字串及分詞緩衝。答案 O(n²) 需 64 位元。
Step-by-step animation
自訂小例:輸入 0 a、1 ba、1 a。
步驟 1 / 3
步驟 1:建樹
輸入 0 a、1 ba、1 a。
a:0×1,1×1
ab:1×1
- 位置數
- 3
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n;
cin >> n;
vector<pair<int, string>> a(n);
struct N {
map<char, int> g;
ll e[2] = {0, 0};
};
vector<N> tr(1);
for (auto &[c, s] : a) {
cin >> c >> s;
reverse(s.begin(), s.end());
int v = 0;
for (char x : s) {
if (!tr[v].g.count(x)) {
int z = tr.size();
tr[v].g[x] = z;
tr.emplace_back();
}
v = tr[v].g[x];
}
tr[v].e[c]++;
}
ll ans = 0;
for (auto [c, s] : a) {
int v = 0;
for (char x : s) {
ans += tr[v].e[1 - c];
v = tr[v].g[x];
}
}
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。