C. Best Binary String

题目:样例:

输入
4
??01?
10100
1??10?
0?1?10?10

输出
00011
10100
111101
011110010

思路:

        根据题意, 题目意思是 ‘?’ 字符 该替换何值,使得原字符串,最少操作  翻转任意区间,成升序字符串。有多个答案,打印任意一个即可。这里有多个答案,是因为,替换 ‘?’ 不同的字符,有相同的操作数,所以打印任意一个答案。

        这是一个贪心题,我们根据题意,

我们应该联想到,当原字符串中第一个字符是 ‘?’ 时,我们要最少操作数,就是不操作它这个字符,即刚开始碰到 '?' 时我们应该替换成 '0',

使得它不被操作,当碰到不是 '?' 的时候,就记录相应的值。但是后面的该如何改变呢?

要最少操作数,我们应该联想一下,当碰到有确定的值了,如果该值需要翻转,那么我们紧贴的 '?'跟着一块翻转,就是最少操作数啦,所以我们的 '?' 就应该替换我们之前确认了的值。

代码详解如下:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>
#define endl '\n'
#define int long long
#define YES puts("YES")
#define NO puts("NO")
#define umap unordered_map
#define All(x) (x).begin(),(x).end()
#pragma GCC optimize(3,"Ofast","inline")
#define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 2e6 + 10;

inline void solve()
{
	string s,ans = "";
	
	// 初始计划替换的 值
	char r = '0';
	
	cin >> s;
	
	// 开始检查替换
	for(auto i : s)
	{
		// 如果遇到 ? ,则我们要替换成记录的 r 值
		if(i == '?') ans += r;
		else
		{
			// 如果不是 ? ,记录相应的值
			// 并且更新计划替换值 r 为当前确定的值
			ans += i;
			r = i;
		}
	}
	
	// 输出答案
	cout << ans << endl;
}

signed main()
{
//	freopen("a.txt", "r", stdin);
	___G;
	int _t = 1;
	cin >> _t;
	while (_t--)
	{
		solve();
	}

	return 0;
}

最后提交:

猜你喜欢

转载自blog.csdn.net/hacker_51/article/details/133493184
今日推荐