[ZJOI 2008] 泡泡堂BNB

本文详细解析了洛谷1034题的贪心算法解决方案,通过将两个数组升序排序,根据当前最弱或最强的元素进行匹配打击,实现了最优解。介绍了具体算法步骤及时间复杂度分析。

[题目链接]

         https://www.lydsy.com/JudgeOnline/problem.php?id=1034

[算法]

         考虑贪心

         首先将两个数组升序排序 

         若当前最弱的 > 对方当前最弱的,打

         若当前最强的 > 对方当前最强的,打

         否则用最弱的去打对方最强的

         时间复杂度 : O(NlogN)

[代码]

         

#include<bits/stdc++.h>
using namespace std;
#define MAXN 100010
typedef long long LL;

int n;
LL a[MAXN] , b[MAXN];

template <typename T> inline void chkmax(T &x,T y) { x = max(x , y); }
template <typename T> inline void chkmin(T &x,T y) { x = min(x , y); }
template <typename T> inline void read(T &x)
{
    T f = 1; x = 0;
    char c = getchar();
    for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
    for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
    x *= f;
}
inline LL solve(LL *a,LL *b)
{
    LL ret = 0;
    int al = 1 , bl = 1 , ar = n , br = n;
    while (al <= ar && bl <= br)
    {
        if (a[al] > b[bl]) 
        {
            ret += 2;    
            ++al;
            ++bl;
        } else if (a[ar] > b[br])
        {
            ret += 2;
            --ar;
            --br;
        } else
        {
            if (a[al] == b[br]) ++ret;
            ++al; --br;
        }
    }    
    return ret;
}

int main()
{
    
    read(n);
    for (int i = 1; i <= n; i++) read(a[i]);
    for (int i = 1; i <= n; i++) read(b[i]);
    sort(a + 1,a + n + 1);
    sort(b + 1,b + n + 1);
    LL ans1 = solve(a , b) , ans2 = solve(b , a);
    printf("%lld %lld\n",ans1 , 2 * n - ans2);
    
    return 0;
}

 

转载于:https://www.cnblogs.com/evenbao/p/9832215.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值