CF1440A Buy the String 题解

Content

\(t\) 组询问,每组询问给出一个长度为 \(n\)\(0/1\) 串,你可以花 \(h\) 的代价把 \(0\) 修改成 \(1\) 或者把 \(1\) 修改成 \(0\),也可以花 \(c_x\) 的代价删除一个 \(x\in[0,1]\)。求使得 \(0/1\) 串为空的最小代价。

数据范围:\(1\leqslant t\leqslant 10,1\leqslant n,c_0,c_1,h\leqslant 1000\)

Solution

\(x\) 在字符串中出现的次数为 \(cnt_x\),那么我们很明显地发现,把所有的 \(0\) 删掉的最小代价是 \(c_0\times\min(cnt_0,cnt_1+h)\),把所有的 \(1\) 删掉的最小代价是 \(c_1\times\min(cnt_1,cnt_0+h)\)。为什么呢?因为你要把所有的 \(0\) 改成 \(1\) 或者把所有的 \(1\) 改成 \(0\),都需要额外的代价,所以我们取最小值就可以使得代价最小。

Code

int t, n, c0, c1, h, a[1007];

int main() {
	t = Rint;
	while(t--) {
		n = Rint, c0 = Rint, c1 = Rint, h = Rint;
		int cnt0 = 0, cnt1 = 0, ans = 0;
		F(i, 1, n) {scanf("%1d", &a[i]); cnt0 += (a[i] == 0), cnt1 += a[i];}
		ans = cnt0 * min(c0, c1 + h) + cnt1 * min(c1, c0 + h);
		printf("%d\n", ans);
	}
	return 0;
}
posted @ 2021-12-16 14:51  Eason_AC  阅读(17)  评论(0)    收藏  举报