poj3903 Stock Exchange最大上升子序列

來源:互聯網
上載者:User

標籤:stl   動態規劃   

轉載請註明出處:http://blog.csdn.net/u012860063

題目連結:http://poj.org/problem?id=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

第一種:http://blog.csdn.net/u012860063/article/details/34086819

代碼如下:

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int a[100047],dp[100047],n;int bin(int size,int k){    int l = 1,r = size;    while(l<=r)    {        int mid = (l+r)/2;        if(k>dp[mid])            l = mid+1;        else            r = mid-1;    }    return l;}int LIS(int *a){    int i,j,ans=1;    dp[1] = a[1];    for(i = 2; i<=n; i++)    {        if(a[i]<=dp[1])            j = 1;        else if(a[i]>dp[ans])            j = ++ans;        else            j = bin(ans,a[i]);        dp[j] = a[i];    }    return ans;}int main(){int i;while(~scanf("%d",&n)){for(i = 1; i <= n; i++){scanf("%d",&a[i]);}int ans = LIS(a);printf("%d\n",ans);}return 0;}

第二種使用了:lower_bound

代碼如下:

#include<cstdio>#include<algorithm>using namespace std;#define INF 0x3fffffffint a[100047],dp[100047];int main(){int t,i;while(scanf("%d",&t)!=EOF){for(i = 0; i <= t; i++)dp[i]=INF;for(i = 0; i < t; i++){scanf("%d",&a[i]);}for(i = 0; i < t; i++){*lower_bound(dp,dp+t,a[i])=a[i];}printf("%d\n",lower_bound(dp,dp+t,INF)-dp);}return 0;}

附上解釋的圖片一張:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.