题解:P17047 [NWERC 2021] 挑袜子 / Knitpicking
Immortal_Codex · · 题解
模拟 + 贪心 + 分类讨论。
:::info[题意]{open}
选袜子,输出能找出的最多的完整的袜子,如果无论如何都找不出一对,就直接输出 impossible。
:::
:::info[性质]{open}
- 左右库存都有 → 直接配对,取走只数为
\max(l, r) 。 - 只有单侧库存 → 需借助任意脚袜子才能凑对。
-
只有任意脚袜子 → 至少 2 只才能凑一对。
:::info[具体做法:分类讨论]{open}
- 用两个
map分别统计左右脚库存和任意脚库存。 - 遍历有左右库存的袜子:
- 左右都有 → 标记可配对,答案累加
\max(l, r) 。 - 只有一侧 → 若有任意脚则标记可配对,答案累加该侧库存。
- 左右都有 → 标记可配对,答案累加
- 遍历只有任意脚库存的袜子:
- 数量
\ge 2 → 标记可配对,答案累加1 。
- 数量
-
若无法配对输出 impossible,否则输出ans + 1。
:::info[复杂度]
时间复杂度:
:::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}
-
最终答案要 +1,因为题目要求的是取出的袜子总数,而不仅仅是配对对数。