【luogu AT5159】RGB Balls(贪心)

RGB Balls

题目链接:luogu AT5159

题目大意

给你一个 3*n 的字符串,分别有 n 个 R,G,B 字符。
然后你可以把一个 R,G,B 组成一组,费用是它们的最长距离差。
然后你要把字符串弄成 n 组,每个字符都被选到过,然后要他们的费用和最小。
问你有多少种弄的方案满足费用和最小。

思路

我们首先考虑怎样会有最小费用和。

那把最前和最后的贡献分开,就是要前面的晚出现,后面的早出现。
那我们就能放到前面就放,这样是最优的。

那接着考虑统计方案。
发现如果你要作为第三个,前面的两个的出现顺序并不重要。

那我们直接记录六种状态的当前个数((R,G,B,RG,RB,GB)
那然后就能转就转,能三个就三个,每次答案乘可以转过来的个数就可以了。

代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#define ll long long
#define mo 998244353

using namespace std;

int n;
char s[300001];
ll ans, nm[6];//R G B RG RB GB 

int ck(int i) {
	if (s[i] == 'R') return 0;
	if (s[i] == 'G') return 1;
	return 2;
}

int to(int x, int y) {
	if (x > y) swap(x, y);
	if (x == 0 && y == 1) return 3;
	if (x == 0 && y == 2) return 4;
	return 5;
}

void cg(int x, int y) {
	if (nm[x]) nm[x]--, nm[y]++;
}

int main() {
	scanf("%d", &n);
	scanf("%s", s + 1);
	
	ans = 1;
	for (int i = 1; i <= n; i++) ans = ans * i % mo;
	for (int i = 1; i <= 3 * n; i++) {
		int now = ck(i);
		if (nm[5 - now]) ans = ans * nm[5 - now] % mo, nm[5 - now]--;
			else if (nm[(now + 1) % 3] || nm[(now + 2) % 3]) ans = ans * (nm[(now + 1) % 3] + nm[(now + 2) % 3]) % mo, cg((now + 1) % 3, to(now, (now + 1) % 3)), cg((now + 2) % 3, to(now, (now + 2) % 3));
				else nm[now]++;
	}
	
	printf("%lld", ans);
	
	return 0;
} 
原文地址:https://www.cnblogs.com/Sakura-TJH/p/luogu_AT5159.html