nyoj monotonically increasing subsequence (2)

Monotonically increasing subsequence (2)

Time Limit: 1000 ms | Memory Limit: 65535 KB
Difficulty: 4
 
describe

Given an integer sequence {a 1 , a 2 ..., a n } (0<n<=100000), find the longest subsequence with monotonically increasing and find its length.

For example, the longest monotonically increasing subsequence of 1 9 10 5 11 2 13 is 1 9 10 11 13 with a length of 5.

 
enter
There are multiple sets of test data (<=7)
The first line of each set of test data is an integer n represents a total of n integers in the sequence, and the next line contains n integers, representing all elements in the sequence. Each integer The numbers are separated by spaces (0<n<=100000).
Data ends with EOF.
The input data is guaranteed to be legal (all int integers)!
output
For each set of test data output the length of the longest increasing subsequence of the integer array, each output occupies one row.
sample input
7
1 9 10 5 11 2 13
2
2 -1
Sample output
5
1

#include <iostream>
#include <cstring>
using namespace std;

const int INF=0x3f3f3f3f;
int a[100005];

int main()
{
int t;
while(cin>>t)
{
memset(a,0,sizeof(a));
int num,top=0;
a[0]=-INF;
for(int i=0;i<t;++i)
{
cin>>num;
if(num>a[top])
a[++top]=num;
else
{
int left=1,right=top;
while(left<=right)
{
int mid=(left+right)/2;
if(num>a[mid])
left=mid+1;
else
right=mid-1;
}
a[left]=num;
}
}
/* for(int i=0;i<t;++i)
cout<<a[i]<<" ";
cout<<endl;*/
cout<<top<<endl;
}
return 0;
}

 

Array a starts from 1 unit, and 0 unit is not used.

The first number must be pushed into the stack, and determine the relationship between the current input number and the number of the top element of the stack.

If it is greater than the number of the top element of the stack, push it to the stack,

If it is less than the number of the top element of the stack, find the position of the first element in the previous sequence that is greater than the current number,

Replace the element at that position with this element.

The resulting sequence is a monotonically increasing ordered sequence.

 

It's interesting to think about it for yourself. .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324990041&siteId=291194637