专栏文章

题解:P13894 [蓝桥杯 2023 省 C] 填充

P13894题解参与者 8已保存评论 10

文章操作

快速查看文章及其快照的属性,并进行相关操作。

当前评论
10 条
当前快照
1 份
快照标识符
@mio2zfr7
此快照首次捕获于
2025/12/02 12:31
3 个月前
此快照最后确认于
2025/12/02 12:31
3 个月前
查看原文

题解:P13894 [蓝桥杯 2023 省 C] 填充

思路

很简单的贪心。
我们可以用一个循环把所有 str[i]==str[i-1] 的子串找出来。然后统计 ? 的个数,每遇到一次 ? 就让他和上一位相等即可。
CPP
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+1;
string str;
int ans=0;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	cin>>str;
	for(int i=1;i<str.size();i++){
        if(str[i]==str[i-1]){
            ans++;
            i++;
        }else if(str[i]=='?'){
            ans++;
            i++;
        }
    }
    cout<<ans<<endl;
    return 0;
}
结果炸了……
为什么呢?
因为还有一种情况:
CPP
 被遗忘了
    |
    V
1 ? ? 0 0
  |   ^
  |---|
  V 到这一位
 跳过
所以我们还需要统计 str[i-1]=='?' 的情况。

代码

CPP
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+1;
string str;
int ans=0;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	cin>>str;
	for(int i=1;i<str.size();i++){
        if(str[i]==str[i-1]){
            ans++;
            i++;
        }else if(str[i]=='?'){
            ans++;
            i++;
        }else if(str[i-1]=='?'){
            ans++;
            i++;
        }
    }
    cout<<ans<<endl;
    return 0;
}

评论

10 条评论,欢迎与作者交流。

正在加载评论...