Codeforces 1037C Equalize 贪心

题目链接

http://codeforces.com/contest/1037/problem/C

题意

给定两个只有0,1组成的字符串a和b。
操作如下:
将第i个字符的值取反,代价为1.
交换第i个字符和第j个字符的值,代价为abs(i-j).
求使得a等于b的最少代价。

题解

贪心。
假设第i位和第j位不同。
如果i+1=j,那么交换是最优的,代价为1.
否则,代价2是最优的,即分别取反.

AC代码

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+7;

string a,b;
struct node
{
    int id;
    int v;
    int vis;
    node(){}
    node(int id,int v,int vis):id(id),v(v),vis(vis){}
}s[maxn];

int main()
{
    int n;
    ios::sync_with_stdio(false);
    while(cin>>n)
    {
        cin>>a>>b;
        int cnt=0;
        for(int i=0;i<n;i++)
        {
            if(a[i]!=b[i])
            {
                s[++cnt]=node(i,a[i]-'0',0);
            }
        }

       // cout<<"cnt="<<cnt<<endl;
        int ans=0;
        for(int i=1;i<cnt;i++)
        {
            if(s[i].vis) continue;
            if(s[i].v+s[i+1].v==1 && s[i].id+1==s[i+1].id)
            {
                ans+=1;
                s[i].vis=1;
                s[i+1].vis=1;
            }
            else
            {
                ans++;
                s[i].vis=1;
            }
        }
       // cout<<"ans="<<ans<<endl;
        if(s[cnt].vis==0) ans++;
        if(cnt==0) ans=0;
        cout<<ans<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值