博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Almost Sorted Array(o(nlgn)求解LIS)
阅读量:4477 次
发布时间:2019-06-08

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

Almost Sorted Array

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 10562    Accepted Submission(s): 2449

Problem Description
We are all familiar with sorting algorithms: quick sort, merge sort, heap sort, insertion sort, selection sort, bubble sort, etc. But sometimes it is an overkill to use these algorithms for an almost sorted array.
We say an array is sorted if its elements are in non-decreasing order or non-increasing order. We say an array is almost sorted if we can remove exactly one element from it, and the remaining array is sorted. Now you are given an array 
a1,a2,,an, is it almost sorted?
 

 

Input
The first line contains an integer 
T indicating the total number of test cases. Each test case starts with an integer n in one line, then one line with n integers a1,a2,,an.
1T2000
2n105
1ai105
There are at most 20 test cases with n>1000.
 
Output
For each test case, please output "`YES`" if it is almost sorted. Otherwise, output "`NO`" (both without quotes).
 

 

Sample Input
3
3
2 1 7
3
3 2 1
5
3 1 4 1 5
 

 

Sample Output
YES
YES
NO
 

 

Source
 

 

Recommend
hujie
onlgn求解LIS的基本思想是,用dp[i]保存长度为i的最长子序列的最大值的最小值。 遍历数组,如果a >= dp[len],接到后面,否则,在dp中寻找第一个大于这a的数,把他替换掉,原因很好想,要想使得序列足够长,那么dp[i]越小越好。
#include 
#include
#include
using namespace std;const int maxn = 100000 + 5;int n, val[maxn];int cnt1, cnt2, dp[maxn];int main() { int t; int a, temp; scanf("%d", &t); while(t --) { cnt1 = 0, cnt2 = 0; memset(dp, 0, sizeof dp); scanf("%d", &n); for(int i = 0; i < n; i ++) scanf("%d", &val[i]); for(int i = 0; i < n; i ++) { if(val[i] >= dp[cnt1]) dp[++ cnt1] = val[i]; else { temp = upper_bound(dp + 1, dp + 1 + cnt1, val[i]) - dp; dp[temp] = val[i]; } } memset(dp, 0, sizeof dp); for(int i = n - 1; i >= 0; i --) { if(val[i] >= dp[cnt2]) dp[++ cnt2] = val[i]; else { temp = upper_bound(dp + 1, dp + 1 + cnt2, val[i]) - dp; dp[temp] = val[i]; } } if(cnt1 >= n - 1 || cnt2 >= n - 1) printf("YES\n"); else printf("NO\n"); } return 0;}

 

转载于:https://www.cnblogs.com/bianjunting/p/11586531.html

你可能感兴趣的文章
情人节——爱心代码
查看>>
Java冒泡排序
查看>>
FastDFS 双tracker负载均衡 及多组存储配置
查看>>
Windows10 MySQL8.0.12 非安装版配置启动
查看>>
火狐的调试利器-----Firebug
查看>>
浏览器的页面渲染
查看>>
PHP 配置文件中open_basedir选项作用
查看>>
Linux下redis的安装
查看>>
bzoj 1208 宠物收养所
查看>>
算法笔记
查看>>
javascript基础、语法
查看>>
HDU 1301(MST)
查看>>
[LeetCode] SUM4
查看>>
安防摄像机手机直播方案介绍
查看>>
安防摄像头云端录像计划快捷配置-LiveNVR Onvif/RTSP流媒体服务
查看>>
包装类
查看>>
[转载]Spring学习4-面向切面(AOP)之aspectj注解方式
查看>>
201621123047 《Java程序设计》第10周学习总结
查看>>
no crontab for root 解决方案
查看>>
IAP 协议
查看>>