POJ 3903 Stock Exchange

Stock Exchange
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 2954   Accepted: 1082

Descriptionios

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.

Inputui

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.

Outputspa

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 Inputcode

6 
5 2 1 4 5 3 
3  
1 1 1 
4 
4 3 2 1

Sample Outputblog

3 
1 
1
題目大意:最長上升子序列。
解題方法:這題因爲數據較大,不能採用常規的DP方法來解答,那樣時間複雜度爲O(n^2),應採用二分,時間複雜度爲n * logn。
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    int n, low, mid, high, nLen;
    int num[100005];
    int Stack[100005];
    while(scanf("%d", &n) != EOF)
    {
        nLen = 0;
        Stack[0] = -1;
        for (int i = 1; i <= n; i++)
        {
            scanf("%d", &num[i]);
        }
        for (int i = 1; i <= n; i++)
        {
            if (num[i] > Stack[nLen])
            {
                Stack[++nLen] = num[i];
            }
            else
            {
                low = 1;
                high = nLen;
                while(low <= high)
                {
                    mid = (low + high) / 2;
                    if (Stack[mid] < num[i])
                    {
                        low = mid + 1;
                    }
                    else
                    {
                        high = mid - 1;
                    }
                }
                Stack[low] = num[i];
            }
        }
        printf("%d\n", nLen);
    }
    return 0;
}
相關文章
相關標籤/搜索