选择子序列

长度为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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值