ABC088B - Card Game for Two

GitHub跳转原题关系图返回列表

降序排序后,Alice 取偶数位 Bob 取奇数位,输出分差。

OJ: atcoder

题目 ID: abc088_b

难度:入门

标签:贪心排序c++haskell

日期: 2026-07-10 16:11

题意

NN 张牌,Alice 和 Bob 轮流取最大的牌,Alice 先手。求 Alice 总分 - Bob 总分。

思路

降序排序后 Alice 取偶数位、Bob 取奇数位,差即为答案。

代码

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-07-10 16:11
 * update_at: 2026-07-10 16:11
 */
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n; cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) cin >> a[i];

    sort(a.rbegin(), a.rend());

    int alice = 0, bob = 0;
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0) alice += a[i];
        else            bob   += a[i];
    }
    cout << alice - bob << '\n';

    return 0;
}
haskell
{-
 Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 rainboy的学习导航网站: https://idx.roj.ac.cn
 create_at: 2026-07-10 16:16
 update_at: 2026-07-10 16:16
-}
import Data.List (sort)

main = do
    input <- getContents
    let (_:xs) = map read (words input) :: [Int]
        ys = reverse (sort xs)
        alice = sum [ y | (i,y) <- zip [0..] ys, even i ]
        bob   = sum [ y | (i,y) <- zip [0..] ys, odd  i ]
    print $ alice - bob

复杂度

时间复杂度 O(NlogN)O(N \log N),空间复杂度 O(N)O(N)

总结

贪心取最大 + 交替分配。