hdu 1051 (greedy algorithm, how a little modification turn 15ms to 0ms)

the 2 version are essentially the same, except version 2 search from the larger end, which reduce the search time in extreme condition from linear to constant, so be faster.
version 1

#include <cstdio>
#include <algorithm>

struct LWPair{
    int l,w;
};

int main() {
    //freopen("input.txt","r",stdin);
    const int MAXSIZE=5000, MAXVAL=10000;
    LWPair sticks[MAXSIZE];
    int store[MAXSIZE];
    int ncase, nstick, length,width, tmp, time, i,j;
    if(scanf("%d",&ncase)!=1) return -1;
    while(ncase-- && scanf("%d",&nstick)==1) {
        for(i=0;i<nstick;++i) scanf("%d%d",&sticks[i].l,&sticks[i].w);
        std::sort(sticks,sticks+nstick,[](const LWPair &lhs, const LWPair &rhs) { return lhs.l>rhs.l || lhs.l==rhs.l && lhs.w>rhs.w; });
        for(time=-1,i=0;i<nstick;++i) {
            tmp=sticks[i].w;
            for(j=0;j<=time && store[j]<tmp;++j) ; //search from left to right
            if(j>time) { store[++time]=tmp; }
            else { store[j]=tmp; }
        }
        printf("%d\n",time+1);
    }
    return 0;
}

version 2

#include <cstdio>
#include <algorithm>

struct LWPair{
    int l,w;
};

int main() {
    //freopen("input.txt","r",stdin);
    const int MAXSIZE=5000, MAXVAL=10000;
    LWPair sticks[MAXSIZE];
    int store[MAXSIZE];
    int ncase, nstick, length,width, tmp, time, i,j;
    if(scanf("%d",&ncase)!=1) return -1;
    while(ncase-- && scanf("%d",&nstick)==1) {
        for(i=0;i<nstick;++i) scanf("%d%d",&sticks[i].l,&sticks[i].w);
        std::sort(sticks,sticks+nstick,[](const LWPair &lhs, const LWPair &rhs) { return lhs.l>rhs.l || lhs.l==rhs.l && lhs.w>rhs.w; });
        for(time=-1,i=0;i<nstick;++i) {
            tmp=sticks[i].w;
            for(j=time;j>=0 && store[j]>=tmp;--j) ; // search from right to left
            if(j==time) { store[++time]=tmp; }
            else { store[j+1]=tmp; }
        }
        printf("%d\n",time+1);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值