问题描述:给出一个整数串,取出其最长的上升的子序列的长度。
思路:这是一个dp(动态规划)问题,解决问题的难点在于给出的数组的大小(最大为1000000);普通的用二维数组解决的话,肯定会超时,因此,我们寻找另一种解决问题的状态转移方程。
我们假设:f(i)存放的是长度为i时的上升的子序列的最后一个数字(即子序列的数字的最大值),然后就有以下状态转移方程:如果a[i+1]>f(i)时,f(i+1)=a[i+1];如果a[i+1]<=f(i)时,便使用a[i+1]替换掉f数组中的第一个大于或等于a[i+1]的值。具体步骤见后面的图片。
代码如下:
#include<cstdio>
#include<cstring>
int a[222222];
int b[222222];
int find(int x,int y,int n){
int start=x;
int end=y;
int sign;
while(start<=end){
if(b[(start+end)/2]==n){sign=(start+end)/2;break;}
if(b[(start+end)/2]>n){
end=(start+end)/2-1;
}
if(b[(start+end)/2]<n){
start=(start+end)/2+1;
}
}
if(start>end)sign=start;
return sign;
}
int main(){
int number;
while((scanf("%d",&number))!=EOF){
memset(b,0,sizeof(b));
for(int i=0;i<number;i++){
scanf("%d",&a[i]);
}
int b1=0;
for(int i=0;i<number;i++){
if(i==0){b[i]=a[i];b1++;}
else{
if(b[b1-1]<a[i]){b[b1]=a[i];b1++;}
else if(b[0]>=a[i])b[0]=a[i];
else{
int sign=find(0,b1-1,a[i]);
b[sign]=a[i];
}
}
}
int count=0;
for(int i=0;b[i]!=0;i++){
//printf("%d ",b[i]);
count++;
}
printf("%d\n",count);
}
return 0;
}
原题描述:
B - Stock Exchange
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Submit
Status
Practice
POJ 3903
Description
The world financial crisis is quite a subject. Some people are more relaxed while others are quite anxious. John is one of them. He is very concerned about the evolution of the stock exchange. He follows stock prices every day looking for rising trends. Given a sequence of numbers p1, p2,...,pn representing stock prices, a rising trend is a subsequence pi1 < pi2 < ... < pik, with i1 < i2 < ... < ik. John’s problem is to find very quickly the longest rising trend.
Input
Each data set in the file stands for a particular set of stock prices. A data set starts with the length L (L ≤ 100000) of the sequence of numbers, followed by the numbers (a number fits a long integer).
White spaces can occur freely in the input. The input data are correct and terminate with an end of file.
Output
The program prints the length of the longest rising trend.
For each set of data the program prints the result to the standard output from the beginning of a line.
Sample Input
6
5 2 1 4 5 3
3
1 1 1
4
4 3 2 1
Sample Output
3
1
1
Hint
There are three data sets. In the first case, the length L of the sequence is 6. The sequence is 5, 2, 1, 4, 5, 3. The result for the data set is the length of the longest rising trend: 3.