Problem H Rectangles
时间限制:1000 ms | 内存限制:65535 KB
描述
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.
输入
* 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
思路:将所有的整数对进行排序,先按照x从大到小,如果x相等就按y从大到小,然后两个for循环不断进行扫描。
代码:
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <queue>
#include <cstdio>
#include <vector>
#include <cstring>
#include <cctype>
#include <cmath>
#include <string>
#include <map>
#include <set>
#include <stack>
using namespace std;
const int maxn = 200;
int num[200];
struct node
{
int x;
int y;
}R[maxn];
int cmp(const void *p1, const void *p2) {
struct node *a = (node *)p1;
struct node *b = (node *)p2;
if(a->x == b->x)
return a->y - b->y ;
else
return a->x - b->x ;
}
//int cmp(struct node &a, struct node &b)
//{
// if(a.x == b.x)
// return a.y - b.y ;
// else
// return a.x - b.x ;
//}
int main()
{
int T;
scanf("%d", &T);
int N;
while(T--)
{
scanf("%d", &N);
if(!N) break;
int x, y;
for (int i = 0; i < N; ++i)
{
scanf("%d%d", &x, &y);
if(x <= y)
{
R[i].x = x;
R[i].y = y;
}
else
{
R[i].y = x;
R[i].x = y;
}
}
qsort(R,N,sizeof R[0], cmp);
// sort(R,R+N,cmp);
memset(num, 0,sizeof num);
int maxn = 0;
for (int i = 1; i < N; ++i)
{
for (int j = 0; j < i; ++j)
{
if ((R[j].x <= R[i].x && R[j].y < R[i].y) || (R[j].x < R[i].x && R[j].y <= R[i].y))
{
num[i] = max(num[i],num[j]+1);
maxn = max(maxn, num[i]);
}
}
}
cout << maxn+1 << endl;
}
return 0;
}