hdu3998 最长上升子序列及其个数 dp或dp+最大流

时间:2021-02-14 20:40:36

Sequence

Problem Description

There is a sequence X (i.e. x[1], x[2], …, x[n]). We define increasing subsequence of X
as x[i1], x[i2],…,x[ik], which satisfies follow conditions:
1) x[i1] < x[i2],…,

Input

The input file have many cases. Each case will give a integer number n.The next line will
have n numbers.

Output

The output have two line. The first line is s and second line is num.

Sample Input

4
3 6 2 5

Sample Output

2
2

思路1:dp
dp[i]表示以a[i]为末尾的最长上升子序列长度。跑一边最长上升子序列。计算出结果len。
再扫一遍dp数组,如果dp[i]==len,那么必定存在以a[i]为末尾,长度为len的子序列。于是逆向访问,如果这个序列的每个元素没有被其他满足dp[i]==len的序列占用,则满足题意。

代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=505;
int dp[N],vis[N],a[N];
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        memset(vis,0,sizeof(vis));
        int len=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);
            }
            len=max(len,dp[i]);
        }
        int res=0;
        for(int i=1;i<=n;i++){
            if(dp[i]==len)res++;
        }
        for(int i=1;i<=n;i++)if(dp[i]==len){
            int l=len-1;
            vis[i]=1;
            for(int j=i-1;j>=1;j--)//逆向访问
            {
                if(dp[j]==l&&!vis[j]) vis[j]=1,l--;
            }
            if(l>0) res--;//序列不存在
        }
        printf("%d\n%d\n",len,res);
    }
    return 0;
}

思路2:dp
dp[i]表示长度个i的上升子序列中,末尾元素的最小值。不存在则为inf(无穷大)
用o(nlogn)算法来计算最长上升子序列,然后把计算过的数删去。直到最长上升子序列不为len。

代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define inf 1<<30
const int N=505;
int dp[N],vis[N],a[N];
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=1;i<=n;i++)scanf("%d",&a[i]);
        memset(vis,0,sizeof(vis));
        int maxl=0,ans=0;
        while(1){
            int len=0,pos;
            fill(dp,dp+n+1,inf);
            for(int i=1;i<=n;i++){
                if(vis[i])continue;
                pos=lower_bound(dp+1,dp+n+1,a[i])-dp;
                dp[pos]=a[i];
                if(pos>len) len++,vis[i]=1;
            }
            if(len>maxl) maxl=len,ans++;
            else if(len==maxl)ans++;
            else break;
        }
        printf("%d\n%d\n",maxl,ans);
    }
    return 0;
}

思路3:dp+最大流
待补充。