CF1615c C. Menorah

题目链接
题解:
根据题目所给操作观察到:
同一个位置操作一次,当前位置不变,其他位置都会改变
同一个位置操作两次,都不会发生任何变化
两个不同的位置分别操作一次,除这两个位置外的都不会变化并且这两个位置的数会发生交换

这样就有了两种交换方式一种的op为奇数,另一种op为偶数。
op为奇数的前提条件是sa&sb同一位置不同的0和1的个数是否相同,
相同的话则根据之前得出的结论两两交换
op为偶数的前提条件是sa&sb同一位置相同的0和1的个数是否满足s1= s0 + 1;
 

#include <bits/stdc++.h>
using namespace std;

#define fi first
#define se second
#define ve vector
#define all(x) (x).begin(), (x).end()
#define rep(i, a, b) for (int i = a; i < b; i++)
#define per(i, a, b) for (int i = a; i >= b; i--)
using pi = pair<int, int>;

int inline red() {
    int x;
    cin >> x;
    return x;
}

void solve() {
    int n = red();
    string sa, sb;
    cin >> sa >> sb;
    vector<int> a(n), b(n);
    rep(i, 0, n) {
        a[i] = (int)(sa[i] - '0');
        b[i] = (int)(sb[i] - '0');
    }
    int res = 1e9, s0 = 0, s1 = 0, uns0 = 0, uns1 = 0;
    rep(i, 0, n) {
        if (a[i] != b[i]) {
            if (a[i]) {
                uns1++;
            } else {
                uns0++;
            }
        } else {
            if (a[i]) {
                s1++;
            } else {
                s0++;
            }
        }
    }
    if (uns0 == uns1) {
        res = min(res, uns0 + uns1);
    }
    if (s1) {
        s1--;
        if (s1 == s0) {
            res = min(res, s0 + s1 + 1);
        }
    }
    cout << (res == 1e9 ? -1 : res) << '\n';
}
  
int main() {  
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = red();
    while (t--) {  
        solve();
    }  
    return 0;  
}

时间复杂度O(n),空间复杂度O(2n)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值