您的位置:首页 > 其它

POJ - 3903 Stock Exchange(LIS最长上升子序列问题)

2015-08-12 20:37 465 查看
E - LIS
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u

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.

题解:LIS最长上升子序列问题 给出一个序列,从左到右的顺序选出尽量多的整数,组成一个上升子序列。

#include<cstdio>
int a[100001], f[100001];
int main()
{
int n, k, l, r, mid;
while (scanf("%d",&n)==1)
{
for (int i = 0; i < n; i++)
scanf("%d",&a[i]);
k = 0;
f[0] = -1;             //赋初值,小于0即可
for (int i = 0; i < n; i++)
{
if (a[i] > f[k])
{
k++;
f[k] = a[i];         //每找到一个就保存到f【】数组里
}
else
{
l = 1, r = k;
while (l<=r)          //判断此时的a[i]和f数组中各个值大小关系,直到找到最优值
{
mid = (l + r) / 2;
if (a[i] > f[mid])
l = mid + 1;
else
r = mid - 1;
}
f[l] = a[i];
}
}
printf("%d\n",k);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: