#include <iostream>
#define SIZE 1001
using namespace std;
int main()
{
int i, j, n, top, temp;
int stack[SIZE];
cin >> n;
top = 0;
/* 第一个元素可能为0 */
stack[0] = -1;
for (i = 0; i < n; i++)
{
cin >> temp;
/* 比栈顶元素大数就入栈 */
if (temp > stack[top])
{
stack[++top] = temp;
}
else
{
int low = 1, high = top;
int mid;
/* 二分检索栈中>=temp的第一个数的下标 */
while(low <= high)
{
mid = (low + high) / 2;
if (temp > stack[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
/* 用temp替换 */
stack[low] = temp; //这个下标的前一个数即为小于temp的最大的数
}
}
/* 最长序列数就是栈的大小 */
cout << top << endl;
//system("pause");
return 0;
}
用algorithm里的lower_bound函数找下界实现:#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
int stack[1005];
int n,top=0,temp;
cin>>n;
stack[0]=-1;
for(int i=0;i<n;i++)
{
cin>>temp;
if(temp>stack[top])
stack[++top]=temp;
else
{
int loc=lower_bound(stack,stack+top,temp)-stack; //返回第一个>=temp的数的下标,则这个数的前一个数就是<temp的下标最大的数
stack[loc]=temp;
}
}
cout<<top<<endl;
return 0;
}