您的位置:首页 > 其它

NYOJ 16(矩形嵌套)

2012-08-23 16:54 330 查看

矩形嵌套

时间限制:3000 ms | 内存限制:65535 KB
难度:4

描述有n个矩形,每个矩形可以用a,b来描述,表示长和宽。矩形X(a,b)可以嵌套在矩形Y(c,d)中当且仅当a<c,b<d或者b<c,a<d(相当于旋转X90度)。例如(1,5)可以嵌套在(6,2)内,但不能嵌套在(3,4)中。你的任务是选出尽可能多的矩形排成一行,使得除最后一个外,每一个矩形都可以嵌套在下一个矩形内。

输入第一行是一个正正数N(0<N<10),表示测试数据组数,
每组测试数据的第一行是一个正正数n,表示该组测试数据中含有矩形的个数(n<=1000)
随后的n行,每行有两个数a,b(0<a,b<100),表示矩形的长和宽输出每组测试数据都输出一个数,表示最多符合条件的矩形数目,每组输出占一行样例输入
1
10
1 2
2 4
5 8
6 10
7 9
3 1
5 8
12 10
9 7
2 2

样例输出
5

View Code

//wa
//贪心思想wa,反例:<100 ,1>  <9 6>  <8 3>正确答案是2,若按下面的贪心思想则答案是0
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef struct Node
{
int length,width;
}Node;
Node ch[1005];
int cmp(const void *a,const void *b)
{
Node *c = (Node *)a;
Node *d = (Node *)b;
if(c->length!=d->length)
return d->length - c->length;
else
return d->width - c->width;
}
int main()
{
int i,j,k,t,T;
cin>>T;
int num,a,b;
while(T--)
{
memset(ch,0,sizeof(ch));
cin>>num;
if(num==0)
{
cout<<0<<endl;
continue;
}
for(i=1;i<=num;i++)
{
cin>>a>>b;
if(a<b)
{
a^=b;
b^=a;
a^=b;
}
ch[i].length = a,ch[i].width = b;
}
if(num==1)
{
cout<<1<<endl;
continue;
}
qsort(&ch[i],num,sizeof(Node),cmp);
int cnt = 1;//不是0
for(i=1;i<=num;i++)
if(ch[i].length>=ch[i+1].length&&ch[i].width>=ch[i+1].width)
cnt++;
cout<<cnt<<endl;
}
return 0;
}


#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef struct Node
{
int length,width;
}Node;
Node ch[1005];
int f[1005];
int cmp(const void *a,const void *b)
{
Node *c = (Node *)a;
Node *d = (Node *)b;
if(c->length!=d->length)
return d->length - c->length;
else
return d->width - c->width;
}
int main()
{
int i,j,k,t,T;
cin>>T;
int num,a,b;
while(T--)
{
memset(ch,0,sizeof(ch));
cin>>num;
if(num==0)
{
cout<<0<<endl;
continue;
}
for(i=1;i<=num;i++)
{
cin>>a>>b;
if(a<b)
{
a^=b;
b^=a;
a^=b;
}
ch[i].length = a,ch[i].width = b;
f[i] = 1;
}
if(num==1)
{
cout<<1<<endl;
continue;
}
qsort(&ch[1],num,sizeof(Node),cmp);
int max = 0;
for(i=2;i<=num;i++)
{
for(j=i-1;j>=1;j--)
if(ch[i].length<ch[j].length&&ch[i].width<ch[j].width)//没有等于
//f[i] >?= f[j] + 1;
if(f[i]<(f[j]+1))
f[i] = f[j] + 1;
if(max < f[i])
max = f[i];
}
cout<<max<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: