这道题感觉就是greedy的题。但是还是看了解题报告。知道做法后实现很简单,只需要注意测试数据中有左端点的x坐标大于右端点的x坐标的情况,调换下即可。
贪心的策略是按照x从左往右扫描,如果某一列(某一个x值)对应(被覆盖)的墙的个数cnt大于k,那么需要从这些墙中删掉cnt - k 个。删除的顺序是将墙按照右端点的x值从大到小的顺序排序,按顺序删除。
这样做的大致思路是因为对每个“覆盖墙”我们不用考虑其左端点(因为左边的所有列已经是满足条件的),右端点大的覆盖的右边的x多,所以先删除。这不是个证明。证明请参考其他资料。
因为墙的个数很少(100个以下),所以实现的时候都是最naive的方法逐个扫描判断是否覆盖当前x。因为每次都需要墙是按照右端点x值排序,所以提前一次把墙排序好。
thestoryofsnow | 1230 | Accepted | 164K | 0MS | C++ | 1946B |
/*
ID: thestor1
LANG: C++
TASK: poj1230
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>
using namespace std;
const int MAXN = 100;
class Wall
{
public:
int x1, x2, y;
bool removed;
Wall() : removed(false) {}
Wall(int x1, int x2, int y) : x1(x1), x2(x2), y(y), removed(false) {}
inline bool operator> (const Wall &rhs) const
{
return x2 > rhs.x2 || (x2 == rhs.x2 && x1 >= rhs.x1);
}
};
int main()
{
Wall walls[MAXN];
int T;
scanf("%d", &T);
for (int t = 0; t < T; ++t)
{
int n, k;
scanf("%d%d", &n, &k);
for (int i = 0; i < n; ++i)
{
scanf("%d%d%d%d", &walls[i].x1, &walls[i].y, &walls[i].x2, &walls[i].y);
if (walls[i].x1 > walls[i].x2)
{
int t = walls[i].x1;
walls[i].x1 = walls[i].x2;
walls[i].x2 = t;
}
walls[i].removed = false;
}
sort(walls, walls + n, std::greater<Wall>());
// printf("[debug]walls:\n");
// for (int i = 0; i < n; ++i)
// {
// printf("[%d]%d->%d\n", i, walls[i].x1, walls[i].x2);
// }
int nremoved = 0;
for (int x = 0; x <= 100; ++x)
{
int cnt = 0;
for (int i = 0; i < n; ++i)
{
// if the wall is not removed
if (!walls[i].removed)
{
if (walls[i].x1 <= x && walls[i].x2 >= x)
{
cnt++;
}
}
}
// if some walls need to be removed
if (cnt > k)
{
nremoved += cnt - k;
for (int i = 0; i < n; ++i)
{
// if the wall is not removed
if (cnt > k && !walls[i].removed)
{
if (walls[i].x1 <= x && walls[i].x2 >= x)
{
walls[i].removed = true;
// printf("wall [%d]%d->%d removed for x: %d\n", i, walls[i].x1, walls[i].x2, x);
cnt--;
}
}
}
}
}
printf("%d\n", nremoved);
}
return 0;
}