博客
关于我
AcWing 1014. 登山JAVA(最长单调子序列 单调栈)
阅读量:343 次
发布时间:2019-03-04

本文共 1516 字,大约阅读时间需要 5 分钟。

时间复杂度:

O(nlogn)

//单调栈问题//分别计算从左向右和从右向左的最长上升子序列,分别存储到两个数组中import java.util.*; class Main{    static int n = 0, N = 1010;    static int[] nums = new int[N];    static int[] left = new int[N], right = new int[N];    static int bs(int[] max, int len, int num){//找到从左到右第一个大于num的数字        int l = 0, r = len;        while(l < r){            int mid = l + r >> 1;//+1防止mid不变造成死循环。            if(max[mid] < num)l = mid + 1;            else r = mid;        }        return l;    }    public static void main(String[] args)throws Exception{        Scanner sc = new Scanner(System.in);        int m = sc.nextInt();        for(int i = 1; i <= m; ++i)nums[i] = sc.nextInt();        int[] st = new int[N];//单调栈        int tt = -1;        for(int i = 1; i <= m; ++i){            if(tt == -1)st[++tt] = nums[i];            if(tt >= 0 && st[tt] > nums[i]){                int index = bs(st, tt, nums[i]);                st[index] = nums[i];            }            if(st[tt] < nums[i])st[++tt] = nums[i];            left[i] = tt + 1;        }        tt = -1;        for(int i = m; i >= 1; --i){            if(tt == -1)st[++tt] = nums[i];            if(tt >= 0 && st[tt] > nums[i]){                int index = bs(st, tt, nums[i]);                st[index] = nums[i];            }            if(st[tt] < nums[i])st[++tt] = nums[i];            right[i] = tt + 1;        }        int max = 0;        for(int i = 1; i <= m; ++i){            max = Math.max(max, left[i] + right[i] - 1);        }        System.out.print(max);            }}

 

转载地址:http://dfre.baihongyu.com/

你可能感兴趣的文章
myeclipse配置springmvc教程
查看>>
MyEclipse配置SVN
查看>>
MTCNN 人脸检测
查看>>
MyEcplise中SpringBoot怎样定制启动banner?
查看>>
MyPython
查看>>
MTD技术介绍
查看>>
MySQL
查看>>
MySQL
查看>>
mysql
查看>>
MTK Android 如何获取系统权限
查看>>
MySQL - 4种基本索引、聚簇索引和非聚索引、索引失效情况、SQL 优化
查看>>
MySQL - ERROR 1406
查看>>
mysql - 视图
查看>>
MySQL - 解读MySQL事务与锁机制
查看>>
MTTR、MTBF、MTTF的大白话理解
查看>>
mt_rand
查看>>
mysql -存储过程
查看>>
mysql /*! 50100 ... */ 条件编译
查看>>
mysql 1045解决方法
查看>>
mudbox卸载/完美解决安装失败/如何彻底卸载清除干净mudbox各种残留注册表和文件的方法...
查看>>