hdu1677: Nested Dolls

hdu1677: http://acm.hdu.edu.cn/showproblem.php?pid=1677
题意:给出m个嵌套娃娃的数据(宽w、高h),求嵌套后最少娃娃数 解法:贪心法+dp:类似最少拦截系统,这个问题其实是用dp求最长子序列的长度,先按宽从小到大排序,则小号可能可以嵌套在大号中,再依次判断后面的h是否比前面的大,若是,则取前面中h较大者(由贪心法可知)。
code:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
struct abc
{
    int w,h;
}v[20002];
bool cmp(abc a,abc b)
{
    if(a.w==b.w)
        return a.h>b.h;
    return a.w<b.w;
}
int main()
{
    int t,m,ans[20002];
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&m);
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&v[i].w,&v[i].h);
        }
        sort(v,v+m,cmp);
        for(int i=0;i<m;i++)
            ans[i]=v[i].h;
        int cout=0;
        for(int i=0;i<m;i++)     //先取一个小的
        {
            int j;
            for(j=0;j<cout;j++)
            {
                if(ans[i]>ans[j])    //看是否有能装上前面已放的娃娃的娃娃
                    break;
            }
            if(j==cout)cout++;     //若没有,则另起炉灶,结果加一
            ans[j]=ans[i];         //加入已处理的这个娃娃i
        }
        printf("%d\n",cout);
    }
}
/*input:
4
3
20 30 40 50 30 40
4
20 30 10 10 30 20 40 50
3
10 30 20 20 30 10
4
10 10 20 30 40 50 39 51
output:
1
2
3
2
*/

posted on 2012-07-25 20:29  acmer-jun  阅读(164)  评论(0编辑  收藏  举报

导航