本着学习C++的心态将网上找到的这个代码贴上,不过用这个会超时
#include<iostream>
#include<vector>#include<algorithm>
using namespace std;
class Doll //定义Doll类,包含高度height、宽度width属性
{
public:
Doll(int w, int h) //定义构造函数
{
width = w;
height = h;
}
int width;
int height;
};
bool operator<(Doll d1,Doll d2)
//重载<运算符,后面调用STL中sort函数对Doll进行排序时需要
{
if(d1.width == d2.width) //若width相等,height较小者排序结果为较大
return (d1.height > d2.height);
return (d1.width < d2.width); //width较大者排序结果即为较大
}
int main()
{
int test_num, doll_num; //测试数据组数和每组数据中doll数
cin>>test_num;
vector<int> result; //vector类result用来存储每组测试数据的结果
result.reserve(test_num);
for(int i=0; i<test_num; i++)
{
cin>>doll_num;
vector<Doll> unselected; //unselected存储原始的dolls
vector<Doll> selected; //selected存储从unselected中挑选出组成的nested dolls
unselected.reserve(doll_num);
for(int j=0; j<doll_num; j++)
{
int width, height; //从终端读取测试数据到unselected中
cin>>width>>height;
unselected.push_back(Doll(width, height));
}
sort(unselected.begin(),unselected.end()); //调用STL函数对读入的dolls进行排序
/*
从已排序的dolls中一个一个选出doll放到selected中进行嵌套,
嵌套根据贪心法的原则来进行:每次选出一个doll,若可以套住几个较小的doll,
则让它套在其中最大那个上,把其余较小的留给后续的doll来套;若选出的这个doll
没法套住selected中的其它doll,则把它放到该vector的最后。
*/
for(int k=0; k<unselected.size();k++) //从已排序的dolls中取出第k个doll
{
int left=0,right=selected.size(),mid;
while(left<right)
//通过二分查找,从selected中已有的dolls中找出最大的一个
{ //能被unselected[k]嵌套住的doll
mid = (left+right)/2;
if(unselected[k].height<=selected[mid].height ||
//若selected[mid]不能被unselected[k]嵌套住
unselected[k].width<=selected[mid].width)
//则进入右半边继续进行二分查找
left = mid+1;
else
right = mid;
}
if(left==selected.size())
//查找完毕,若最后left超出selected一位,则表示unselected[k]无法
selected.push_back(unselected[k]);
//嵌套住selected中的任一个doll,因此将它插入到selected末尾
else
selected[left]=unselected[k];
//找到一个可以嵌套的,将selected[left]替换为unselected[k],表示
} //嵌套成功
result.push_back(selected.size()); //最后selected的长度就是nested dolls的总数
}
for(int i=0; i<result.size(); i++)
cout<<result[i]<<endl; //输出结果
return 0;
}
下面这个是我参考上面的代码改的
#include<iostream>
#include<cstring>
using namespace std;
struct Doll{
int width,height;
}doll[20005],selected[20005];
bool cmp(Doll a,Doll b){
if(a.width==b.width)
return a.height>b.height; //这里只可用 >,用 < WA了
return a.width<b.width;
}
int main(){
int t,n,cnt;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d%d",&doll[i].width,&doll[i].height);
sort(doll,doll+n,cmp);
cnt=0;
for(int i=0;i<n;i++){
int left=0,right=cnt,mid;
while(left<right){
mid=(left+right)/2;
if(doll[i].width<=selected[mid].width ||
doll[i].height<=selected[mid].height)
left=mid+1;
else
right=mid;
}
if(left==cnt)
selected[cnt++]=doll[i];
else
selected[left]=doll[i];
}
printf("%d\n",cnt);
}
//system("pause");
return 0;
}