1153 选择子序列
题目来源: Codility
基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题 收藏 关注
长度为N的整数数组A,所有的数均不相同,假设下标从0开始。找到一个最长的数组B,B数组的长度为K,数值范围是0 - N - 1,记录的是A数组的下标。满足A[B[0]] > A[B[1]] > A[B[2]] >...A[B[K]],并且对任意连续的两项B[i]及B[i + 1],满足min(B[i],B[i + 1]) < j < max(B[i],B[i + 1]) 均有A[j] < A[B[i + 1]] ,求最大的K。例如:9, 10, 2, -1, 3, -5, 0, -3, 1, 12, 5, 8, -2, 6, 4。可以选出:12, 10, 3, 1, 0, -3。对应的下标为:9, 1, 4, 8, 6, 7(就是B数组),输出6。
Input
第1行:一个数N,表示A数组的长度。(1 <= N <= 50000)
第2 - N + 1行:每行1个数对应A数组的元素Ai(0 < Ai < 10^9)
Output
输出B数组最长的长度K。
Input示例
15
9
10
2
-1
3
-5
0
-3
1
12
5
8
-2
6
4
Output示例
6
李陶冶 (题目提供者)
不难得出一个 分治法的解法
int dfs(int l,int r){//返回 数组a在下标[l,r]范围内 b数组的最大长度
int pos = a[l ... r]中的最大值的下标
return max(dfs(l,pos-1),dfs(pos+1,r)) + 1;
}
然而关键就在于快速求解pos 这里线段树优化一下即可
每个位置最多被取出来一次 所以O(nlogn)
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<vector>
#include<deque>
#include<queue>
#include<algorithm>
#include<set>
#include<map>
#include<stack>
#include<time.h>
#include<math.h>
#include<list>
#include<cstring>
#include<fstream>
#include<queue>
#include<sstream>
//#include<memory.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair<int,int>
#define INF 1000000007
#define pll pair<ll,ll>
#define pid pair<int,double>
const int N = 50000 + 4;
struct Node{
int maxVal;
int index;
Node(){
maxVal = -INF;
index = -1;
}
Node(int v,int i):maxVal(v),index(i){}
}rmq[4*N];
bool operator <(const Node&a,const Node&b){
return a.maxVal<b.maxVal;
}
int a[N];
void addNode(int k,int l,int r,int pos,int val){
if(l<=pos&&pos<=r){
rmq[k]=max(rmq[k],Node(val,pos));
if(l!=r){
int mid = (r+l)/2;
if(pos<=mid){
addNode(2*k+1,l,mid,pos,val);
}
if(pos>=mid+1){
addNode(2*k+2,mid+1,r,pos,val);
}
}
}
}
Node query(int k,int l,int r,int posL,int posR){
if(posL<=l&&r<=posR){
return rmq[k];
}
Node ans;
if(l!=r){
int mid=(l+r)/2;
if(posL<=mid){
ans=max(ans,query(2*k+1,l,mid,posL,posR));
}
if(posR>=mid+1){
ans=max(ans,query(2*k+2,mid+1,r,posL,posR));
}
}
return ans;
}
int slove(int l,int r,int n){
if(l==r){
return 1;
}
if(l<r){
int ans=0;
int pos = query(0,0,n-1,l,r).index;
ans=max(slove(l,pos-1,n),slove(pos+1,r,n));
return ans+1;
}
return 0;
}
int main()
{
//freopen("/home/lu/Documents/r.txt","r",stdin);
//freopen("/home/lu/Documents/w.txt","w",stdout);
int n;
scanf("%d",&n);
for(int i=0;i<n;++i){
scanf("%d",a+i);
addNode(0,0,n-1,i,a[i]);
}
printf("%d\n",slove(0,n-1,n));
return 0;
}