poj2533&&hdu1087 最長上升子序列問題

題目鏈接:
http://poj.org/problem?id=2533
http://acm.hdu.edu.cn/showproblem.php?pid=1087

最長上升子序列問題:
思路1:dp[i]表示以i結尾的最長上升子序列
轉移方程:dp[i]=max{dp[j]+1};
思路2:dp[i]表示長度爲i的最小元素

升序排列:
iterator lower_bound( const key_type &key ): 返回一個迭代器,指向鍵值>= key的第一個元素。
iterator upper_bound( const key_type &key ):返回一個迭代器,指向鍵值> key的第一個元素。
區間 前閉後開。[first,last)。 所有元素均小於key則返回key的地址。

代碼1:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1005;
int a[N],dp[N];
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    int Max=0;
    for(int i=1;i<=n;i++)
    {
        dp[i]=1;
        for(int j=1;j<i;j++)if(a[j]<a[i]){
            dp[i]=max(dp[i],dp[j]+1);
        }
        Max=max(dp[i],Max);
    }
    printf("%d\n",Max);
    return 0;
}

代碼2:

#include<cstdio>
#include<algorithm>
#include<cstring>
#define inf 1<<30
using namespace std;
const int N=500005;
struct node{
    int a,b;
}st[N];
int dp[N];
bool cmp(node n1,node n2){
    return n1.a<n2.a;
}

int main()
{
    int n;int ca=1;
    while(scanf("%d",&n)!=EOF)
    {
        fill(dp,dp+n+1,inf);
        for(int i=1;i<=n;i++)
            scanf("%d%d",&st[i].a,&st[i].b);
        sort(st+1,st+n+1,cmp);
        for(int i=1;i<=n;i++){
            *lower_bound(dp+1,dp+n+1,st[i].b)=st[i].b;
        }
        int ans=lower_bound(dp+1,dp+n+1,inf)-dp-1;
        printf("Case %d:\n",ca++);
        if(ans>1)
        printf("My king, at most %d roads can be built.\n\n",lower_bound(dp+1,dp+n+1,inf)-dp-1);
        else
            printf("My king, at most 1 road can be built.\n\n");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章