Happy Birthday UVA - 12002(LIS变形)

这题和HDU4640非常像。

思路:预处理求以i点为起点的最长上升子序列和最长下降子序列.(求法可以直接n^2)

依次枚举i,以i为起点的最长上升+比a[i]小的最长下降 。或者以i为起点的最长下降+比a[i]大的最长上升,都是满足题意的。

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e3+7;
int n;
int a[maxn];
struct LIS //模板,可以取等时用upper_bound,不取等时用lower_bound
{
    int n, s[maxn];
    void init () { n = 0; }
    int find (int x) { return upper_bound(s, s + n, x) - s; }
    void modify(int pos, int val) { s[pos] = val; n = max(n, pos+1); }
}in, de;
int f[maxn],g[maxn];
int main()
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
    #endif
    while(~scanf("%d",&n)&&n)
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        memset(f,0,sizeof(f));
        memset(g,0,sizeof(g));
        for(int i=n;i>=1;i--)
        {
            f[i]=g[i]=1;
            for(int j=n;j>i;j--)
            {
                if(a[i]<=a[j])
                {
                    f[i]=max(f[i],f[j]+1);//最长上升
                }
                if(a[j]<=a[i])
                {
                    g[i]=max(g[j]+1,g[i]);//最长下降
                }
            }
        }
        int ans=0;
        for(int i=1;i<=n;i++)
        {
            //printf("%d %d\n",f[i],g[i]);
            ans=max(max(g[i],f[i]),ans);
            for(int j=i+1;j<=n;j++)
            {
                if(a[i]>a[j])
                {
                    ans=max(ans,f[i]+g[j]);
                }
                else if(a[j]>a[i])
                {
                    ans=max(ans,f[j]+g[i]);
                }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/82822556