1515D - Phoenix and Socks.思路清晰 代码简约

文章提供了一段C++代码,用于解决一种优化问题:如何用最少的操作将不同颜色且区分左右脚的袜子配对。代码中定义了变量和数据结构,并通过循环和条件判断来计算解决方案。当左脚袜子比右脚多时,会进行特殊处理,最后输出所需的操作数。
摘要由CSDN通过智能技术生成

题意是有很多种颜色的 的袜子 也分左右脚
让我们用最少操作 完成配对。
也就是要 1 颜色配对 2 左右脚配对。
这题找了很多的题解。。都是思路很费劲。。
在cf提交区看到一种份代码。非常nice 一目了然。。
就放在这里吧。


#include <bits/stdc++.h>
using namespace std;
#define ios ios::sync_with_stdio(0)
#define endl '\n'
#define int long long
#define ar array<int, 2>
#define arr array<int, 3>
const int N = 2e5 + 5, M = 2 * N;
const int inf = 0x3f3f3f3f;
int mod = 998244353; //1e9+7;
int t, n, m, k;
// 规定正负脚  多的为正 少的为负。。特别方便。。
signed main()
{
    ios;
#ifdef DEBUG
    freopen("../1.in", "r", stdin);
#endif
    cin >> t;
    while (t--)
    {
        int l, r;
        cin >> n >> l >> r;
        vector<int> a(n + 1);
        for (int i = 1; i <= n; ++i)
        {
            int x;
            cin >> x;
            if (i <= l)
                a[x]++;
            else
                a[x]--;
        }
        if (l < r)
        {
            swap(l, r);
            for (int i = 1; i <= n; ++i)
                a[i] = -a[i];
        }
        int ans = 0, c = (l - r) >> 1;
        for (int i = 1; i <= n; ++i)
            while (a[i] >= 2 && c)
            {
                c--, a[i] -= 2, ans++;
            }
        for (int i = 1; i <= n; ++i)
            if (a[i] > 0)
                ans += a[i];
        cout << ans << endl;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值