Comet OJ-Demo Match # 2 Day1 A Wave (DP)

Address: https://cometoj.com/contest/76/problem/A?problem_id=4237

 

 

 

 

 

     Analysis: This problem is relatively simple to solve with DP. I have not understood other solutions. The so-called wave, a single number can not be counted, two numbers must count. In our two-dimensional dp, j = 0 means falling or equal, and j = 1 means rising. i from 0 to n

     Transfer equation:

if(a[i-1]<=a[i])
        {
            dp[i][0]=dp[i-1][1]+1;
        }
        else
            dp[i][1]=dp[i-1][0]+1;
        sum+=dp[i][0]+dp[i][1];

   Take a sample to explain:

   We can write something like this: 0 1

            1       0  1   

            2       0  1  

            3       2  0

            4       1  0

      Sum by sum is the answer. In the first step, starting from i = 1 and rising, dp [1] [1] = dp [0] [0] +1;

                    In the second step, i = 2, 2-> 3 is still rising, but dp [2] [1] ca n’t accept the previous dp [1] [1], because the three rising numbers are not waves, and need to undertake dp [0] [ 1], plus 1 (almost a reset)

                   The third step, i = 3,3-> 2, there is a decline, dp [3] [0] = dp [2] [1] + 1 = 2, here to explain, dp [2] [1] is saved 2-> 3, the 1 in +1 is the new 3-> 2, the original 2-> 3 is connected to 3-> 2, the number is still that number, that is, dp [3] [0] = dp [2 ] [1] + 1 = 2.      

        In general, in this transfer equation, +1 is the current new wave added, and the dp in the previous step is the previous wave connected to this new wave. The number is still the previous dp, but the appearance is different. Yes, so use sum to accumulate.

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long  ll ;
const int maxn = 3e6+10;
int dp[maxn][2];
int a[maxn];
int main()
{
    int n ;
    cin>>n;
    for(int i = 0 ; i< n ;i ++)
        cin>>a[i];
    ll sum = 0 ;
    for(int i = 1 ; i< n ; i++)
    {
        if(a[i-1]<=a[i])
        {
            dp[i][0]=dp[i-1][1]+1;
        }
        else
            dp[i][1]=dp[i-1][0]+1;
        sum+=dp[i][0]+dp[i][1];
    }    cout<<sum<<endl;
}

 

Guess you like

Origin www.cnblogs.com/liyexin/p/12683136.html