问题 F: Binary Transformations
题目描述
There are n bits. Each bit i has a value ai (0 or 1) and an associated cost ci. We can change the value of bit i with a cost computed as the sum of all the costs cj of the bits j such that aj = 1 AFTER bit i is changed. What is the minimum amount that should be paid to set each bit i to a specified value bi.
输入
The first line contains the integer n (1≤n≤5×103) - the number of bits
The second line contains n integers ci (1≤ci≤109) - the costs associated with the bits
The third line contains the original n values of the bits ai - the original values of the bits
The fourth line contains the required n values of the bits bi - the required values of the bits
输出
Print one number - the minimum cost.
样例输入
5
5 2 6 1 5
01110
10011
样例输出
21
题意是说要把a串变为b串
每次改变一位的代价是改变后所有为1的位的代价总和
很简单的贪心
先把1变成0再把0变成1显然是代价最小
并且在1变0的时候优先变价值大的
在0变1的时候优先变价值小的
要考虑的点就是
要把a[i] = 1 && b[i] = 1的位先变成0后变成1
可以很显然把这样的情况归并进1变0和0变1两次情况
考虑到要排序并且要插入
很自然想到可以用set
(代码比较短但是时间复杂度好像高一点)
因为数据范围比较小所以就可以n方过题
于是就考虑枚举要进行1变0再变1的操作个数
因为贪心思想肯定优先变大的
所以排了个序
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5e3+10;
char a[maxn];
char b[maxn];
int c[maxn];
ll tmp;
int n;
vector<int>v;
multiset<int>s1;
multiset<int>s2;
bool cmp(int x,int y){
return x > y;
}
int main (){
scanf("%d",&n);
for (int i=1;i<=n;++i) scanf("%d",&c[i]);
scanf("%s",a+1);
scanf("%s",b+1);
for (int i=1;i<=n;++i) {
if (a[i] == '1' && b[i] == '1') v.push_back(c[i]);
else if (a[i] == '1' && b[i] == '0') s1.insert(c[i]);
else if (a[i] == '0' && b[i] == '1') s2.insert(c[i]);
if (a[i] == '1') tmp += (ll)c[i];
}
sort(v.begin(),v.end(),cmp);
int s = v.size();
ll ans = 0x3f3f3f3f3f3f3f3f;
multiset<int>::iterator it1;
multiset<int>::reverse_iterator it2;
for(int i=0;i<=s;++i){
ll sum = tmp,res = 0;
if (i!=0) {
s1.insert(v[i-1]);
s2.insert(v[i-1]);
}
for (it2 = s1.rbegin();it2 != s1.rend();++it2){
sum -= (*it2);
res += sum;
// cout<<sum<<" "<<res<<endl;
}
for (it1 = s2.begin();it1 != s2.end();++it1){
sum += (*it1);
res += sum;
// cout<<sum<<" "<<res<<endl;
}
ans = min(res,ans);
}
cout<<ans<<endl;
return 0;
}