zoukankan      html  css  js  c++  java
  • hdu 1051 (greedy algorithm, how a little modification turn 15ms to 0ms) 分类: hdoj 2015-06-18 12:54 29人阅读 评论(0) 收藏

    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
    ",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
    ",time+1);
        }
        return 0;
    }

    版权声明:本文为博主原创文章,未经博主允许不得转载。// p.s. If in any way improment can be achieved, better performance or whatever, it will be well-appreciated to let me know, thanks in advance.

  • 相关阅读:
    Nginx + FastCGI 程序(C/C++)搭建高性能web service的demo
    微服务架构
    异常点/离群点检测算法——LOF
    多边形区域填充算法--递归种子填充算法
    Java 关于容器集合等数据结构详情图解,一目了然
    平衡小车项目解读日志
    &lt;LeetCode OJ&gt; 101. Symmetric Tree
    【JVM】模板解释器--字节码的resolve过程
    hexo博客的相关配置
    【LeetCode】Find Minimum in Rotated Sorted Array 解题报告
  • 原文地址:https://www.cnblogs.com/qeatzy/p/4716224.html
Copyright © 2011-2022 走看看