2023 CSP-S T2消消乐 题解
1. 问题转化
-
可消除子串栈模拟为空(类似“括号匹配”,把
'('')'匹配换成相同字母匹配) -
等价于:两个位置的前缀栈状态相同,它们之间的子串就可消除
例如:acca
前缀栈状态:
位置0:[]
位置1:[a]
位置2:[a, c]
位置3:[a]
位置4:[]
因为位置1处理完时的状态和位置3的状态相同,所以到的子串("cc")为可消除子串
同理到的子串("acca")也为可消除子串
2. 前缀状态的维护
用什么数据结构来维护前缀栈状态哈希表
用 base 进制哈希
设此时的前缀栈状态为
则当前的哈希值
为了快速计算哈希值,我们可以预处理的值(处理到n + 1就够了,因为深度最多n + 1)
注意:我们可以不用保存每一个前缀栈的状态,我们可以维护一个当前的哈希值h和当前深度depth
-
压栈:(深度指压入后栈的大小)
-
弹栈:(深度指压入后栈的大小)
3. 统计答案
我们用一个cnt数组统计每个哈希值出现的数量
扫每个位置,更新栈和 h,然后 ans += cnt[h],再 cnt[h]++
注意:cnt在这里要定义成unorder_map
AC Code
#include <bits/stdc++.h>
using namespace std;
#define ull unsigned long long
const int base = 121;
const int N = 2e6 + 10;
stack<char> st;
ull pbase[N];
unordered_map<ull, int> cnt;
int n;
string s;
ull h = 0;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> s;
pbase[0] = 1;
for (int i = 1; i <= n; i++) pbase[i] = pbase[i-1] * base;
long long ans = 0;
cnt[0] = 1;
for (int i = 0; i < n; i++) {
char c = s[i];
if (!st.empty() && st.top() == c) {
h -= c * pbase[st.size()];
st.pop();
} else {
h += c * pbase[st.size() + 1];
st.push(c);
}
ans += cnt[h];
cnt[h]++;
}
cout << ans;
return 0;
}