题目链接: 点击打开链接
题目大意: 一个矩形长宽均小于另一个矩形就可以嵌套进去,求嵌套矩形序列的最长长度。
思路: LIS
分析:
存放矩形时,长宽,宽长两种组合都存一次。接着对矩形数组按长度排序,最后求最长上升子序列就可以了。
代码:
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 2000 + 10;
int n, dp[maxn];
struct rect{
int a, b;
} rects[maxn];
bool comp(const rect& r1, const rect& r2)
{
return r1.a < r2.a;
}
int solve()
{
for (int i = 1; i <= 2*n; ++i) dp[i] = 1;
for (int i = 2; i <= 2*n; ++i)
for (int j = 1; j < i; ++j)
if (rects[j].a < rects[i].a && rects[j].b < rects[i].b)
dp[i] = max(dp[i], dp[j] + 1);
int ret = 0;
for (int i = 1; i <= 2*n; ++i)
ret = max(ret, dp[i]);
return ret;
}
int main()
{
int N;
scanf("%d", &N);
while (N--) {
scanf("%d", &n);
for (int i = 1; i <= 2 * n; i += 2) {
scanf("%d %d", &rects[i].a, &rects[i].b);
rects[i+1].a = rects[i].b;
rects[i+1].b = rects[i].a;
}
sort(rects+1, rects+2*n, comp);
printf("%d\n", solve());
}
return 0;
}