题目描述
Given N (4 <= N <= 100) rectangles and the lengths of their sides ( integers in the range 1..1,000), write a program that finds the maximum K for which there is a sequence of K of the given rectangles that can "nest", (i.e., some sequence P1, P2, ..., Pk, such that P1 can completely fit into P2, P2 can completely fit into P3, etc.).
A rectangle fits inside another rectangle if one of its sides is strictly smaller than the other rectangle's and the remaining side is no larger. If two rectangles are identical they are considered not to fit into each other. For example, a 2*1 rectangle fits in a 2*2 rectangle, but not in another 2*1 rectangle.
The list can be created from rectangles in any order and in either orientation.
输入
The first line of input gives a single integer, 1 ≤ T ≤10, the number of test cases. Then follow, for each test case:
* Line 1: a integer N , Given the number ofrectangles N<=100
* Lines 2..N+1: Each line contains two space-separated integers X Y, the sides of the respective rectangle. 1<= X , Y<=5000
输出
Output for each test case , a single line with a integer K , the length of the longest sequence of fitting rectangles.
样例输入
1 4 8 14 16 28 29 12 14 8
样例输出
2
题意:输入矩形的长宽,嵌套条件是矩形A的长和宽得严格小于矩形B||长相等时,宽得严格小于||宽相等时,长得严格小于。输出最多能够嵌套的矩形个数。
思路:将矩形长和宽排序后,按照短边求最长上升子序列。
#include<stdio.h>
#include<string.h>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 110;
#define inf 0x3f3f3f3f
int book[maxn][maxn],n,dp[maxn];
struct node{
int x,y;
}vis[maxn];
int cmp(struct node a,struct node b)
{
if(a.x == b.x )
return a.y < b.y ;
return a.x < b.x ;
}
int main()
{
int tx,ty;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(book,0,sizeof(book));
memset(dp,0,sizeof(dp));
for(int i = 0; i < n; i ++)
{
scanf("%d%d",&tx,&ty);
if(tx < ty)
{
int t = tx;
tx = ty;
ty = t;
}
vis[i].x = tx;
vis[i].y = ty;
}
sort(vis,vis+n,cmp);
for(int i = 0; i < n; i ++)
{
dp[i] = 1;
for(int j = 0; j < i; j ++)
{
int x1 = vis[j].x ;
int x2 = vis[i].x ;
int y1 = vis[j].y ;
int y2 = vis[i].y ;
if((x1 == x2&&y1 < y2)||(y1 == y2&&x1 < x2)||(x1 < x2&&y1 < y2))
dp[i] = max(dp[i],dp[j]+1);
}
}
int ans = 0;
for(int i = 0;i < n; i ++)
{
ans = max(ans,dp[i]);
}
printf("%d\n",ans);
}
return 0;
}