hdu 5064 Find Sequence(DP,单调性优化)

Find Sequence

Time Limit: 5000/3000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 386    Accepted Submission(s): 126


Problem Description
Give you an positive integer sequence  a1,a2,,ai,,an , and they satisfy  a1+a2++ai++an=M(0<M222) .
We can find new sequence  b1=aid1,b2=aid2,,bx=aidx,,by=aidy,,bt=aidt , where if x != y then  idx!=idy . and this sequence satisfy:
(1)  b1b2bt  
(2)  b2b1b3b2btbt1
We can find many sequences  b1,b2,b3,,bt . But we only want to know maximum t.
 

Input
The first line in the input file is an Integer  T(1T30) .
The first line of each test case contains two integer  n,M(0<M222) .
Then a line have n integer, they represent  a1,a2,,ai,,an .
 

Output
For each test case, output the maximum t.
 

Sample Input
  
  
2 6 19 3 2 1 3 4 6 1 4194304 4194304
 

Sample Output
  
  
5 1
Hint
For the first testcase, The Sequence is 1 2 3 4 6
题意:n个数,和为m(m最大为2的22次方,410万左右),所以n有可能达到410万(序列全为1),但是注意! 去重后最多不超过3000!因为1+2+...+3000为450万

然后用dp[i][j]表示从当前下标为i到j的最大数量,就有dp[i][j]=max(dp[k][i]+1)(k<=i)

但是O(n³)会炸,所以可以用单调性优化,每次k~i只要用前面的就好了,不需要重新计算,可以优化到O(n²)

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define M 3010
#define N 4194310
int a[N];
int dp[M][M];
int main()
{
    int T;
    int n,m;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d %d",&n,&m);
        for(int i=0; i<n; i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        int num=1,cnt=0;
        for(int i=1; i<n; i++)
        {
            if(a[i]==a[i-1]) num++;
            else
            {
                dp[cnt][cnt]=num;
                cnt++;
                num=1;
            }
        }
        dp[cnt][cnt]=num;
        int t=unique(a,a+n)-a;
        for(int i=0;i<t;i++)
            for(int j=i+1;j<t;j++)
               dp[i][j]=1;
        for(int i=0; i<t; i++)
        {
            int k=i,j=i+1;
            while(j<t)
            {
                if(a[i]-a[k]<=a[j]-a[i]&&k>=0)
                {
                    dp[i][j]=max(dp[i][j],dp[k][i]+1);
                    k--;
                }
                else
                {
                    j++;
                    dp[i][j]=max(dp[i][j],dp[i][j-1]);
                }
            }
        }
        int ans=0;
        for(int i=0; i<t; i++)
            for(int j=i; j<t; j++)
                    ans=max(ans,dp[i][j]);
        printf("%d\n",ans);
    }
    return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值