第七届河南省程序设计大赛——H Rectangles

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/89740924

题目描述:

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

题意很简单,就是有n个矩阵,如果大的套小的看最多能套几层

大的矩阵必须有一边大于小矩阵的一边,并且大矩阵另一边不小于小矩阵的另一边

例如2*2的矩阵大于2*1的矩阵,但是不大于2*1的矩阵

首先将矩阵长的边算作x边,小的算y边,然后将n个矩阵按照x的长短排序若x相同则按照y排序:

ac代码:

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#define INF 99999999
using namespace std;
typedef struct rectangles{
	int x,y;
}rec;
bool cmp(rec c1,rec c2){   //若x相等,则按照y的大小排序 
	if(c1.x==c2.x)return c1.y<c2.y;
	return c1.x<c2.x;
}
int main()
{
	int t,n,book[101];
	cin>>t;
	while(t--){
		cin>>n;
		rec c[n];
		int t1,t2;
		for(int i=0;i<n;i++){
			cin>>t1>>t2;    //将长的一边赋予x,短的赋予y 
			c[i].x=max(t1,t2);
			c[i].y=min(t1,t2);
		}
		sort(c,c+n,cmp);
		fill(book,book+100,1);  //初始化为只能嵌套自己 
		for(int i=1;i<n;i++){
			if(c[i].y==c[i-1].y&&c[i].x==c[i-1].x){  //若与前一个矩阵相等,则能嵌套的数值也和前一个相等 
				book[i]=book[i-1];
				continue;
			}
			int max1=0;
			for(int j=0;j<i;j++){    //在前0-(i-1)个矩阵中找到第i个矩阵能嵌套下且值最大的 
				if(c[j].y<=c[i].y&&book[j]>max1)max1=book[j];
			}
			book[i]=max1+1;
		}
		cout<<book[n-1]<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/89740924
今日推荐