【2021湖北省赛线上赛】D-WA

题目链接:

https://ac.nowcoder.com/acm/contest/15167/D

题意:

给一个长度为n的字符串,可以修改其中k个非a字母,问修改之后为aa的字串最多是多少,并输出修改后的字符串

解题思路:

观察可得,只有当连续非a字符串填满的时候,我们才可以额外获得一个合法答案,因此我们要尽量先填小的。统计序列中连续非a的字母长度和位置,根据长度进行升序排序,进行填充。要注意的是,对于开头或者结尾是非a的放到排序的末尾,因为这类字符串是不会获得额外字符串的。

代码实现:

#include <bits/stdc++.h>
#define Mid ((l + r) / 2)
#define lson (rt << 1)
#define rson (rt << 1 | 1)
using namespace std;
int read() {
	char c; int num, f = 1;
	while(c = getchar(),!isdigit(c)) if(c == '-') f = -1; num = c - '0';
	while(c = getchar(), isdigit(c)) num = num * 10 + c - '0';
	return f * num;
}
struct node {
	int len, st;
} a[500009];
int n, k, tot = 1;
char c[500009];
bool cmp(node a, node b) {
	if(a.st == 1 || a.st + a.len - 1 == n) return 0;
	if(b.st == 1 || b.st + a.len - 1 == n) return 1;
	return a.len < b.len;
}
signed main()
{
	n = read(); k = read();
	scanf("%s", c + 1);
	a[1].st = 1;
	for(int i = 1; i <= n; i++) {
		if(c[i] == 'a') {
			if(a[tot].len != 0) tot++, a[tot].st = i + 1;
			else a[tot].st = i + 1;
		} else a[tot].len++;
	}
	if(a[tot].len == 0) tot--;
	sort(a + 1, a + 1 + tot, cmp);
	for(int i = 1; i <= tot && k; i++) {
		for(int j = a[i].st; j <= a[i].st + a[i].len - 1 && k; j++) {
			c[j] = 'a';
			k--;
		}
	}
	int ans = 0;
	for(int i = 2; i <= n; i++)
		if(c[i] == 'a' && c[i - 1] == 'a') 
			ans++;
	printf("%d\n%s\n", ans, c + 1);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值