题解:P17047 [NWERC 2021] 挑袜子 / Knitpicking

· · 题解

模拟 + 贪心 + 分类讨论。

:::info[题意]{open} 选袜子,输出能找出的最多的完整的袜子,如果无论如何都找不出一对,就直接输出 impossible。 :::

:::info[性质]{open}

:::info[具体做法:分类讨论]{open}

  1. 用两个 map 分别统计左右脚库存和任意脚库存。
  2. 遍历有左右库存的袜子:
    • 左右都有 → 标记可配对,答案累加 \max(l, r)。
    • 只有一侧 → 若有任意脚则标记可配对,答案累加该侧库存。
  3. 遍历只有任意脚库存的袜子:
    • 数量 \ge 2 → 标记可配对,答案累加 1。
  4. 若无法配对输出 impossible,否则输出 ans + 1。

:::info[复杂度] 时间复杂度:O(n \log n)。 空间复杂度:O(n)。 :::

:::success[AC code]

#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
map<string, pair<int, int>> a;
map<string, int> cnt;
int n;
int main() {
    cin >> n;
    for (int i = 0; i < n; i++) {
        string op, l_r;
        int k;
        cin >> op >> l_r >> k;
        if (l_r == "left")
            a[op].fi += k;
        else if (l_r == "right")
            a[op].se += k;
        else
            cnt[op] += k;
    }
    bool flag = false;
    long long ans = 0;
    for (auto& p : a) {
        string op = p.fi;
        int l = p.se.fi;
        int r = p.se.se;
        int any = cnt[op];
        if (l > 0 && r > 0) {
            flag = true;
            ans += max(l, r);
        } else if (l > 0 && r == 0) {
            if (any > 0) {
                flag = true;
                ans += l;
            } else {
                ans += l;
            }
        } else if (l == 0 && r > 0) {
            if (any > 0) {
                flag = true;
                ans += r;
            } else {
                ans += r;
            }
        }
    }
    for (auto& p : cnt) {
        string op = p.fi;
        if (a.find(op) == a.end()) {
            if (cnt[op] >= 2) {
                flag = true;
                ans += 1;
            }
        }
    }
    if (!flag)
        cout << "impossible\n";
    else
        cout << ans + 1 << "\n";
    return 0;
}

::: :::warning[提示]{open}