Rectangles
-
描述
-
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. 样例输入
-
148 1416 2829 1214 8
样例输出
-
2
思路:与最长子序列相似,一定要注意将矩形的长度和宽度调整好。
#include<stdio.h> #include<algorithm> using namespace std; int dp[110]; struct Rectangle { int w; int h; }r[110]; int max(int x,int y) { return x>y?x:y; } bool contains(Rectangle r1,Rectangle r2) { if(r1.w>r2.w && r1.h>r2.h) return true; if(r1.w>=r2.w && r1.h>r2.h) return true; if(r1.w>r2.w && r1.h>=r2.h) return true; return false; } int comp(Rectangle r1,Rectangle r2) { if(r1.w!=r2.w) return r1.w<r2.w; return r1.h<r2.h; } int main() { int t,n,i,j,m,a,b; scanf("%d",&t); while(t--) { m=1; scanf("%d",&n); for(i=0;i<=n;i++) dp[i]=1; for(i=0;i<n;i++) { scanf("%d%d",&a,&b); if(a>b) { r[i].w=b; r[i].h=a; } else { r[i].w=a; r[i].h=b; } } sort(r,r+n,comp); for(i=0;i<n;i++) for(j=i+1;j<n;j++) { if(contains(r[j],r[i])) { dp[j]=max(dp[j],dp[i]+1); m=max(dp[j],m); } } printf("%d\n",m); } return 0; }
-
The first line of input gives a single integer, 1 ≤ T ≤10, the number of test cases. Then follow, for each test case: