【湖北省赛网络赛】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;
}

posted @ 2021-05-09 12:50  Shayndel  阅读(62)  评论(0编辑  收藏  举报