Binary Transformations 题解

问题 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值