https://www.luogu.com.cn/problem/P1056
考点:贪心、排序
题意:
有M行N列的格子,D只长度为2的虫子(可横可竖),横向纵向分别可以切K,L刀,问怎样切可以切死最多的虫子。
。。。
其实原题是用走廊拆开上课交头接耳的学生,不知道为啥我觉得翻译成上面的文字更好理解。
这个题的主要坑点是这一句:
就是说不仅要最优切法,而且要按行列号升序输出。
解法:
很基础的贪心+排序。输入数据的时候,每条“虫子”都砍一刀,记录在该位置砍了一刀,最后看看哪个位置砍的刀数最多,那么这个位置就要优先选择。以横向砍为例,排序后就确定了前K个要砍的位置,然后给这K个再按行号升序排序,就可以输出了。
总共4次排序,数据量不大,可以接受。
#include <bits/stdc++.h>
using namespace std;
using PII = pair<int,int>;
int M,N,K,L,D;
PII RowCut[1005]; // 某行砍了多少刀
PII ColCut[1005]; // 某列砍了多少刀
// 某一行(列)被砍的刀数越多,说明在这个地方设置走廊的效果越好,排个序,从高到低取K(L)个
int main() {
cin >> M >> N >> K >> L >> D;
for (int i = 0; i < D; i++) {
int a,b,c,d; cin >> a >> b >> c >> d;
if (a == c) {
ColCut[min(b, d)].first++;
} else {
RowCut[min(a, c)].first++;
}
}
// second保存行列号
for (int i = 1; i < M; i++) RowCut[i].second = i;
for (int i = 1; i < N; i++) ColCut[i].second = i;
// 按照被切数降序排序
sort(RowCut + 1, RowCut + M, [](PII &a, PII &b){
return a.first != b.first ? a.first > b.first : a.second < b.second;
});
sort(ColCut + 1, ColCut + N, [](PII &a, PII &b){
return a.first != b.first ? a.first > b.first : a.second < b.second;
});
// 按行号升序
sort(RowCut + 1, RowCut + 1 + K, [](PII &a, PII &b){
return a.second != b.second ? a.second < b.second : a.first > b.first;
});
sort(ColCut + 1, ColCut + 1 + L, [](PII &a, PII &b){
return a.second != b.second ? a.second < b.second : a.first > b.first;
});
for (int i = 1; i <= K; i++) {
if (i != K) cout << RowCut[i].second << " ";
else cout << RowCut[i].second << endl;
}
for (int i = 1; i <= L; i++) {
if (i != L) cout << ColCut[i].second << " ";
else cout << ColCut[i].second;
}
return 0;
}
这题没有任何难度,卡了是因为没仔细读题!!