[Valley] Los 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 little difficult to understand, to see the state transition equation it:

dp[i]=dp[i-1]+1(no[i]=no[i-1]+1)

dp[i]=1           (no[i]≠no[i-1]+1)

(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;
        }
    } 
    
    // output 
    COUT ANS << << endl;
     return  0 ; 
}

Guess you like

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