2023CSP-S复赛消消乐题解
2023CSP-S复赛消消乐题解
题意解析:
这道题给出一个长度为
- 若字符串的长度
len <2 则它是不能被消除的。 - 否则,当
len=2 时,若两个字符相等,则这个字符串可以被消除。 - 其它可以被消除的字符串能够按以下方式生成:
- 若有字符串
a,b 可以被消除,则字符串s=a+b 也可以被消除。 - 若有字符串
a 与字符串 。b=b_{1...k}+b_{k+1...n} 均可被消除,则字符串 。s=b_{1...k}+a+b_{k+1...n} 也可以被消除。
- 若有字符串
虽然但是好像貌似没什么用
思路1:
用
- 若栈不为空,且栈顶与下一个等待被压入的元素相同,则弹出栈顶。
- 其他情况将元素压入栈内。
由于时间复杂度达到
#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
int n,ans;
string s;
bool judge(string a){
stack<char>s1;
stack<char>s2;
for(int i=a.size()-1;i>=0;i--){
s1.push(a[i]);
}
s2.push(s1.top());
s1.pop();
while(!s1.empty()){
while(!s1.empty()&&!s2.empty()&&s2.top()==s1.top()){
s1.pop();
s2.pop();
}
if(!s1.empty())s2.push(s1.top()),s1.pop();
}
if(s2.empty()&&s1.empty()){
return true;
}
return false;
}
int main(){
cin>>n;
cin>>s;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j+=2){
if(judge(s.substr(i,j-i+1)))ans++;
}
}
cout<<ans;
return 0;
}
由此延申的第二种做法: DP 。
虽然复杂度相同,但是思路还是有部分差别的。\
对于 dp[i][j] 有以下几种情况:
- 当
i==j时,由于字符串长度为1,所以不可以消除,故dp[i][j]=false。 - 其他情况,若
i==j-1且s[i]==s[j]时,即字符串长度为2且两个字符相同,此时字符串可以被消除,dp[i][j]=true。 - 另外
i<j-1的情况,即字符串长度大于2时,若存在一个整数k ,使得i<k<j 且dp[i][k]==true&&dp[k+1][j]==true,也就是字符串s_{i...j} 可以被分为两个可消除的字符串时,dp[i][j]=true
这样,第二种做法就出来了,通过枚举字符串的长度来解决。\ 代码如下:\ (虽然换了个思路,但是时间复杂度却没有优化,因此还是30分)
#include<iostream>
using namespace std;
int n,ans;
bool dp[10000][10000];
string str;
int main(){
cin>>n;
cin>>str;
fill(&dp[0][0],&dp[0][0]+n*n,false);
for(int i=0;i<n-1;i++)
dp[i][i+1]=(str[i]==str[i+1]);
for(int len=3;len<=n;len++){
for(int i=0;i<n;i++){
int j=len+i-1;
if(str[i]==str[j]&&dp[i+1][j-1]){
dp[i][j]=true;
continue;
}
for(int k=i;k<=j;k++){
if(dp[i][k]&&dp[k+1][j]){
dp[i][j]=true;
}
}
}
}
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(dp[i][j])ans++;
cout<<ans;
return 0;
}
思路3:
既然可以用一个栈来模拟一个字符串被消除的过程,那么,为什么多个栈来模拟多个字符串呢?\
由此,第三种做法——多个栈的模拟。\
通过枚举字符串的起点,在模拟的过程中,若出现栈为空,即从起点到当前字符这一段的字符串可以被消除时,这就是一个答案,由于每次枚举的起点不同,所以,不存在同一个字串被重复计算的的情况。\
这个思路用到了类似前缀和的方法。
代码如下:\
(优化后时间复杂度为
#include<iostream>
#include<stack>
using namespace std;
int n,ans;
string str;
int main(){
cin>>n;
cin>>str;
for(int i=0;i<n;i++){
stack<char>s;
for(int j=i;j<n;j++){
if(!s.empty()&&s.top()==str[j]){
s.pop();
if(s.empty()){
ans++;
}
}else s.push(str[j]);
}
}
cout<<ans;
return 0;
}
思路4:
本来这题到这里就结束了,因为一等奖分数线是150以上,二等奖更不用提。\
好的接下来回归正题:\
思路是用
#include<iostream>
#include<unordered_map>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;
int n,res;
string s;
stack<char>st;
unordered_map<string,int>state_count;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n;
cin>>s;
state_count[""]=1;
for(char ch:s){
if(!st.empty()&&st.top()==ch){
st.pop();
}else{
st.push(ch);
}
string state;
stack<char>temp=st;
while(!temp.empty()){
state.push_back(temp.top());
temp.pop();
}
reverse(state.begin(),state.end());
res+=state_count[state];
state_count[state]++;
}
cout<<res<<endl;
return 0;
}
都有60分了,结束吧~~~\ (至少我想不出别的方法了)