博客
关于我
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/

你可能感兴趣的文章
mysql 往字段后面加字符串
查看>>
mysql 快照读 幻读_innodb当前读 与 快照读 and rr级别是否真正避免了幻读
查看>>
MySQL 快速创建千万级测试数据
查看>>
mysql 快速自增假数据, 新增假数据,mysql自增假数据
查看>>
MySql 手动执行主从备份
查看>>
Mysql 批量修改四种方式效率对比(一)
查看>>
mysql 批量插入
查看>>
Mysql 报错 Field 'id' doesn't have a default value
查看>>
MySQL 报错:Duplicate entry 'xxx' for key 'UNIQ_XXXX'
查看>>
Mysql 拼接多个字段作为查询条件查询方法
查看>>
mysql 排序id_mysql如何按特定id排序
查看>>
Mysql 提示:Communication link failure
查看>>
mysql 插入是否成功_PDO mysql:如何知道插入是否成功
查看>>
Mysql 数据库InnoDB存储引擎中主要组件的刷新清理条件:脏页、RedoLog重做日志、Insert Buffer或ChangeBuffer、Undo Log
查看>>
mysql 数据库中 count(*),count(1),count(列名)区别和效率问题
查看>>
mysql 数据库备份及ibdata1的瘦身
查看>>
MySQL 数据库备份种类以及常用备份工具汇总
查看>>
mysql 数据库存储引擎怎么选择?快来看看性能测试吧
查看>>
MySQL 数据库操作指南:学习如何使用 Python 进行增删改查操作
查看>>
MySQL 数据库的高可用性分析
查看>>