[] Dynamic programming longest consecutive numbers

Original title Portal

Thinking


Chouchou da wind code

Despite being an entry-level water problem, n <10000, violence can live, but if n <100000000, we need a great dynamic programming played QAQ.

The use of DP, I made an O (n) algorithm.

DP [i] denotes the i-th to the next sequential number from the length of a sequential number of digital interrupted.

Ha appreciated somewhat difficult to see the state transition equation it:
DP [I] DP = [-I. 1] + 1'd (NO [I] = NO [I-. 1] + 1'd)
DP [I] =. 1 (NO [I] NO ≠ [-I. 1] + 1'd)
(NO [] array representing the input)

We also need to record a tans even the length of the current number, if tans> ans, ans will set tans, even if the number of interrupted, the tans reset to 1.

The rest is water code QAQ.

Code


#include<iostream>
#include<cstdio>

using namespace std;

const int MAX=10001;
int dp[MAX],no[MAX];
int n,ans=1,tans; 

int main()
{
    //初始化
    dp[1]=1;
    //freopen("testdata(3).txt","r",stdin);
    //读入
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>no[i];
    }
    
    //装叉走起
    for(int i=2;i<=n;i++)
    {
        if(no[i]==no[i-1]+1)
        {
            dp[i]=dp[i-1]+1;
            tans++;
            if(tans>ans)
            {
                ans=tans;
            }
        }
        else
        {
            dp[i]=1;
            tans=1;
        }
    }
    
    //输出
    cout<<ans<<endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/gongdakai/p/11031417.html