[CSP-S 2023] 消消乐 & CF1223F 题解
我们称一个字符串是可消除的,当且仅当可以对这个字符串进行若干次操作,使之成为一个空字符串。其中每次操作可以从字符串中删除两个相邻的相同字符,操作后剩余字符串会拼接在一起。
You are trying to push array elements to the stack in the order
. Moreover, if the stack is empty or the element at the top of this stack is not equal to the current element, then you just push the current element to the top of the stack. Otherwise, you don't push the current element to the stack and, moreover, pop the top element of the stack. If after this process the stack remains empty, the array s is considered stack exterminable.
空串合法
如果合法,那么 合法
如果合法,那么 合法
题意是可以相互转化的。和括号匹配很像,区别是不分左右
sol 1
设
剩下的问题是计算
考虑维护一个哈希表
时间复杂度
sol 2
结论:模拟 CF 题意,
证明:如果
用哈希表维护
code
#include <bits/stdc++.h>
#include <bits/extc++.h>
using namespace std; using namespace __gnu_pbds; using namespace __gnu_cxx;
#define For(i,x,y,...) for(int i=x,##__VA_ARGS__;i<=(y);++i)
#define rFor(i,x,y,...) for(int i=x,##__VA_ARGS__;i>=(y);--i)
#define Rep(i,x,y,...) for(int i=x,##__VA_ARGS__;i<(y);++i)
#define pb emplace_back
#define sz(a) int((a).size())
#define all(a) begin(a),end(a)
#define fi first
#define se second
typedef long long LL; typedef vector<int> Vi; typedef pair<int,int> Pii;
auto ckmax=[](auto &x,auto y) { return x<y ? x=y,true : false; };
auto ckmin=[](auto &x,auto y) { return y<x ? x=y,true : false; };
sfmt19937 mt(chrono::steady_clock::now().time_since_epoch().count());
int rnd(int l,int r) { return uniform_int_distribution<>(l,r)(mt); }
template<typename T=int>T read() { T x; cin>>x; return x; }
typedef unsigned long long uLL;
const int N = 2e6+5;
int n,tp;
uLL pre[N],hsh[N];
char s[N],stk[N];
gp_hash_table<uLL,int> cnt;
signed main() {
#ifdef D
freopen("in","r",stdin); freopen("out","w",stdout);
#endif
ios::sync_with_stdio(0);cin.tie(0);
cin>>n>>s+1;
For(i,1,n) {
if( tp && stk[tp] == s[i] ) --tp;
else stk[++tp] = s[i], pre[tp] = pre[tp-1] * 131 + stk[tp];
hsh[i] = pre[tp];
}
LL ans = 0;
cnt[0] = 1; For(i,1,n) ans += cnt[hsh[i]], ++cnt[hsh[i]];
cout<<ans;
return 0;
}
sol 3
注意到消除满足“结合律”(先消哪里无所谓),不满足“交换律”(不能交换字符再消),可以(?)联想到矩阵乘法
引理:
,其中 是单位矩阵
对于每种字符,随机一个矩阵
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)