博客
关于我
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 sysbench测试安装及命令
查看>>
mysql Timestamp时间隔了8小时
查看>>
Mysql tinyint(1)与tinyint(4)的区别
查看>>
MySQL Troubleshoting:Waiting on query cache mutex
查看>>
mysql union orderby 无效
查看>>
mysql v$session_Oracle 进程查看v$session
查看>>
mysql where中如何判断不为空
查看>>
MySQL Workbench 使用手册:从入门到精通
查看>>
MySQL Workbench 数据库建模详解:从设计到实践
查看>>
MySQL Workbench 数据建模全解析:从基础到实践
查看>>
mysql workbench6.3.5_MySQL Workbench
查看>>
MySQL Workbench安装教程以及菜单汉化
查看>>
MySQL Xtrabackup 安装、备份、恢复
查看>>
mysql [Err] 1436 - Thread stack overrun: 129464 bytes used of a 286720 byte stack, and 160000 bytes
查看>>
MySQL _ MySQL常用操作
查看>>
MySQL – 导出数据成csv
查看>>
MySQL —— 在CentOS9下安装MySQL
查看>>
MySQL —— 视图
查看>>
mysql 不区分大小写
查看>>
mysql 两列互转
查看>>