长度为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。#include<iostream> #include<vector> #include<stack> using namespace std; struct TreeNode { pair<int,int> num; TreeNode* left; TreeNode* right; TreeNode(pair<int,int> tnum) { num=tnum; left=NULL; right=NULL; } }; TreeNode* buildTree(TreeNode* root,vector<int> &nums) { int n=nums.size(); stack<TreeNode*> st; for(int i=0;i<n;i++) { TreeNode* tmp=new TreeNode(make_pair(nums[i],i)); while(!st.empty()&&st.top()->num.first<nums[i]) { st.pop(); } if(st.empty()) { st.push(tmp); tmp->left=root; root=tmp; } else { tmp->left=st.top()->right; st.top()->right=tmp; st.push(tmp); } } return root; } void getHeight(TreeNode* root,int &h,int curh) { if(root==NULL) { if(curh>h) h=curh; } else { getHeight(root->left,h,curh+1); getHeight(root->right,h,curh+1); } } int main() { int n; cin>>n; vector<int> nums(n,0); for(int i=0;i<n;i++) { cin>>nums[i]; } TreeNode* root=NULL; root=buildTree(root,nums); int res=0; getHeight(root,res,0); cout<<res<<endl; return 0; }