C. Equalize(贪心)

题面如下:

在这里插入图片描述

思路 or 题解

一共有两组操作
选择 a 串 两个不同的位置,交换一下,代价是abs(i - j)

选择 a 串 一个位置进行反转(异或1)
1 - > 0
0 -> 1

可以发现什么?
如果使用第一个操作,那么代价只能是 1

用反证法:
如果代价 大于 1
我们可以完全只用 操作2 进行, 代价是2, 不会比 操作1 要差
所以可以证明 只有代价为 1 的时候才会使用 操作1

所以我们记录两串不同的位置
进行贪心

AC代码如下

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <cmath>
#include <map>
#include <unordered_map>
#include <bitset>
#include <set>
#include <random>
#include <ctime>
#include <queue>
#include <stack>
#include <climits>
#define buff                     \
    ios::sync_with_stdio(false); \
    cin.tie(0);
//#define int long long
//#define ll long long
#define PII pair<int, int>
#define px first
#define py second
typedef std::mt19937 Random_mt19937;
Random_mt19937 rnd(time(0));
using namespace std;
const int N = 100009;
int n;
string a, b;
vector<int> v1, v0;
void solve()
{
    cin >> n >> a >> b;
    a = '#' + a, b = '#' + b;
    for (int i = 1; i <= n; i++)
    {
        if (a[i] == b[i])
            continue;
        if (a[i] == '1')
            v1.push_back(i);
        else
            v0.push_back(i);
    }
    int ans = 0;
    while (v0.size() && v1.size())
    {
        int x = v0.back(), y = v1.back();
        v0.pop_back(), v1.pop_back();
        if (abs(x - y) == 1)
            ans++;
        else
        {
            ans++;
            if (x > y)
                v1.push_back(y);
            else
                v0.push_back(x);
        }
    }
    ans += v1.size() + v0.size();

    cout << ans << '\n';
}
int main()
{
    buff;
    solve();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Joanh_Lan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值