Unique Vision Programming Contest 2024 D - Gomamayo Sequence 【贪心】

该篇文章描述了一个问题,给定一个由0和1组成的字符串S,需要通过一次或多次操作使其满足只有一个整数i使得S的第i个和第i+1个字符相同。每个操作的成本是固定的,目标是最小化总成本。文章提供了使用动态规划求解此问题的代码片段。
摘要由CSDN通过智能技术生成

Problem Statement

You are given a string S of length N consisting of 0 and 1.

A string T of length N consisting of 0 and 1 is a good string if and only if it satisfies the following condition:

  • There is exactly one integer i such that 1≤i≤N−1 and the i-th and
    (i+1)-th characters of T are the same.

For each i=1,2,…,N, you can choose whether or not to perform the following operation once:

  • If the i-th character of S is 0, replace it with 1, and vice versa. The cost of this operation, if performed, is C i C_i Ci.

Find the minimum total cost required to make S a good string.

Constraints

2 ≤ N ≤ 1 0 5 2 \leq N \leq 10^5 2N105
S is a string of length N consisting of 0 and 1.
1 ≤ C i ≤ 1 0 9 1 \leq C_i \leq 10^9 1Ci109
N and C i C_i Ci are integers.

Code

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

typedef long long ll;
ll c[200005];
ll cost_pre[2][200005];
ll cost_suf[2][200005];
ll inf = 0x3fffffffffffffff;

int main() {
	int n;
	string s;
	cin>>n;
	cin>>s;
	
	for (int i=0;i<n;i++)
		cin>>c[i];
	
	if (s[0]=='0')
		cost_pre[0][0]=0, cost_pre[1][0]=c[0];
	else
		cost_pre[0][0]=c[0], cost_pre[1][0] = 0;
	for (int i=1;i<n;i++) {
		if (s[i]=='0') {
			cost_pre[0][i] = cost_pre[1][i-1];
			cost_pre[1][i] = cost_pre[0][i-1]+c[i];
		} else {
			cost_pre[0][i] = cost_pre[1][i-1]+c[i];
			cost_pre[1][i] = cost_pre[0][i-1];
		}
	}
	
	if (s[n-1]=='0')
		cost_suf[0][n-1]=0, cost_suf[1][n-1]=c[n-1];
	else
		cost_suf[0][n-1]=c[n-1], cost_suf[1][n-1]=0;
	for (int i=n-2;i>=0;i--) {
		if (s[i]=='0') {
			cost_suf[0][i] = cost_suf[1][i+1];
			cost_suf[1][i] = cost_suf[0][i+1]+c[i];
		} else {
			cost_suf[0][i] = cost_suf[1][i+1]+c[i];
			cost_suf[1][i] = cost_suf[0][i+1];
		}
	}
	
	ll ans = inf;
	for (int i=0;i<n-1;i++) {
		ans = min(ans, min(cost_pre[0][i]+cost_suf[0][i+1], cost_pre[1][i]+cost_suf[1][i+1]));
	}
	cout << ans << endl;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值