现在的位置: 首页 > 综合 > 正文

poj3636 Nested Dolls

2017年11月16日 ⁄ 综合 ⁄ 共 2289字 ⁄ 字号 评论关闭

分析:偏序关系。如果采用poj1065的方法超时,所以用一个数组D[2100],吧每个偏序链的末端 保存起来,不断更新。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
int w,h;
}doll[21000],D[2100];

int cmp(node x,node y)
{
if(x.w!=y.w)
return x.w<y.w;
else 
return x.h>y.h;
}/*
int cmp(const void *x,const void *y)
{
if( ((struct node*)x)->l != ((struct node *)y)->l)
return ((struct node *)x)->l-((struct node*)y)->l;
else
        return ((struct node*)x)->w-((struct node *)y)->w;
}*/
int main()
{
  int t,i,j;
  scanf("%d",&t);
  while(t--)
  {
 int n,i,j,ans=0;
 bool flag;
 scanf("%d",&n);
      for(i=0;i<n;i++)
 {
 //cin>>doll[i].w>>doll[i].h;
 scanf("%d %d",&doll[i].w,&doll[i].h);
 }
 sort(doll,doll+n,cmp);//Ϊʲô²»¶Ô£¡£¡£¡£¡£¡£¡£¡
  // qsort(a,n,sizeof(a[0]),cmp);
 /*for(i=0;i<n;i++)
 cout<<doll[i].w<<"***"<<doll[i].h<<endl;*/
 for(i=0;i<n;i++)
 {
 flag=false;
 for(j=0;j<ans;j++)
 {
 if(doll[i].w>D[j].w && doll[i].h>D[j].h)
 {
 D[j]=doll[i];
 flag=true;
 break;
 }
 }
 if(flag==false) 
 D[ans++]=doll[i];
 }
 printf("%d\n",ans);
  }
  return 0;
}

//c++做法,思想是一样的

#include<iostream>
#include<cstdio>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
struct doll
{
int w,h;
};
vector<doll>a;
vector<doll>b;
int cmp(doll x,doll y)
{
return x.w<y.w||x.w==y.w&&x.h>y.h;
}
int main()
{
int t;
cin>>t;
while(t--)
{
      int n;
 scanf("%d",&n);
      doll d;
 a.clear(),b.clear();
 for(int i=0;i<n;i++)
 {
 scanf("%d %d",&d.w,&d.h);
 a.push_back(d);
 }
 sort(a.begin(),a.end(),cmp);
 for(int i=0;i<n;i++)
 {
 bool flag=false;
 for(int j=0;j<b.size();j++)
 {
 if(a[i].w>b[j].w&&a[i].h>b[j].h)
 {
 b[j].w=a[i].w;
 b[j].h=a[i].h;
 flag=true;
 break;
 }
 }
 if(flag==false)
 {
 b.push_back(a[i]);
 }
 }
 printf("%d\n",b.size());
}
//system("pause");
return 0;
}

/***********************************************

二分法优化:

 二分 果然厉害,瞬间 从563减少到172,将近减少400ms,

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
int w,h;
}doll[21000];
int D[2100];
int cmp(node x,node y)
{
   if(x.w!=y.w)
      return x.w<y.w;
   else 
      return x.h>y.h;
}
int main()
{
    int t,i,j;
    scanf("%d",&t);
    while(t--)
{
      int n,i,j;
      bool flag;
       scanf("%d",&n);
      for(i=0;i<n;i++)
 {
         //cin>>doll[i].w>>doll[i].h;
         scanf("%d %d",&doll[i].w,&doll[i].h);
 }
      sort(doll,doll+n,cmp);
 int len=0,l=0,r,mid;
      for(i=0;i<n;i++)
 {
          l=0,r=len;
          while(l<r)//¶þ·ÖÓÅ»¯
 {
 mid=(l+r)/2;
 if(D[mid]>=doll[i].h)
 l=mid+1;
 else
 r=mid;
 }
          if(len==l)
 len++;
          D[l]=doll[i].h;
 }
      printf("%d\n",len);
}
  return 0;
}

抱歉!评论已关闭.