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
2≤N≤105
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
1≤Ci≤109
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;
}