跳到正文

题解

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

Immortal_Codex约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年7月3日
收录
2026年7月6日
更新
2026年11月14日
篇幅
约 4 分钟
获赞
4
题目
P17047

版本

  1. v1当前

模拟 + 贪心 + 分类讨论。


题意

选袜子,输出能找出的最多的完整的袜子,如果无论如何都找不出一对,就直接输出 impossible。

性质
  • 左右库存都有 → 直接配对,取走只数为 max⁡(l,r)\max(l, r) 。
  • 只有单侧库存 → 需借助任意脚袜子才能凑对。
  • 只有任意脚袜子 → 至少 22 只才能凑一对。
具体做法:分类讨论
  1. 用两个 map 分别统计左右脚库存和任意脚库存。
  2. 遍历有左右库存的袜子:
    • 左右都有 → 标记可配对,答案累加 max⁡(l,r)\max(l, r)。
    • 只有一侧 → 若有任意脚则标记可配对,答案累加该侧库存。
  3. 遍历只有任意脚库存的袜子:
    • 数量 ≥2\ge 2 → 标记可配对,答案累加 11。
  4. 若无法配对输出 impossible,否则输出 ans + 1。
复杂度

时间复杂度:O(nlog⁡n)O(n \log n)。 空间复杂度:O(n)O(n)。


AC code
C++
#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;
}
提示
  • 最终答案要 +1,因为题目要求的是取出的袜子总数,而不仅仅是配对对数。
原文