3602020 Technical comprehensive written (2019.8.31) programming that second question "walk"

 

Dynamic programming ideas:

Providing two lengths of the n + dp1 1, dp2 array, dp [i] indicates whether a particular energy to the i-th stop position, dp [i] = 0 indicates not reach, dp [i] = 1 indicates to reach ,

Initial dp1 [1 ... n] = 1, it can be expressed from arbitrary positions,

Walking distance for each Dj, or the left direction may take away the right, the distance Dj completed, the position indicated by DP2 is reachable, i.e., the transfer equation:

if (dp1[j] == 1 && j + d[i] <= n )
  dp2[j + d[i]] = 1;
if (dp1[j] == 1 && j - d[i] >= 1 )
  dp2[j - d[i]] = 1; 

       dp1 = dp2, repeat step 2.
For every step of Di must dp [j] traversed once, a total of N x M times, the time complexity of O (N × M), the spatial complexity of O (N);

#include <the iostream> 
#include <Vector> 
the using namespace STD; 

void get_res (n-int, int m, Vector <int> & D) { 
    Vector <int> DP1 (n-+. 1, 0); 
    Vector <int> DP2 is ( . 1 + n-, 0);    
	// record reason for using two arrays traveled, transferred from dp1 to DP2 is; 
	// is because if calculated only on a DP, then the transfer may be transient 'cover' potential transition point   
	

    for (int I = 0; I <= n-; I ++) 
        DP1 [I] =. 1; 
    for (int I = 0; I <m; I ++) { 
        for (int. 1 = J; J <= n- ; J ++) { 
            DP2 is [J] = 0; // DESCRIPTION dp1 [j] will not be transferred to dp2 [j], after a certain distance to go;! D [I] = 0   
            IF (dp1 [j] == && D + J. 1 [I] <= n-) 
                DP2 is [D + J [I]] =. 1; 
            IF (DP1 [J]. 1 && J == - D [I]> =. 1) 
                DP2 is [J - D [ i]] = 1;
        }
        dp1 = dp2; // End calculated after the copy to the dp1 to dp2, i.e. dp1 updated 
    } 
    int ANS = 0; 
    for (int I =. 1; I <= n-; I ++) { 
        IF (dp2 [I ] ==. 1) 
            ++ ANS; 
    } 
    COUT ANS << << endl; 
} 

int main () { 
    int n-= 0, m = 0; 
    CIN >> >> n-m; 
    Vector <int> D (m, 0 ); 
    for (int I = 0; I <m; I ++) 
        CIN >> D [I]; 
    
    get_res (n-, m, D); 
    return 0; 
}

  

 Reference blog: https://blog.csdn.net/likewind1993/article/details/100176127

 

Guess you like

Origin www.cnblogs.com/liugl7/p/11440575.html