1083 Alvinzh's youth memory I thought
Medium problem, dynamic planning.
Simplify the test instructions, take the number on a ring, the number is not adjacent, take the sum of the maximum value.
Ring bad, can be solved into a column number, then the answer should be the following two cases of the larger.
①: Take the first point, you can get the maximum value for the treasure [1,n-1] the maximum value.
②: Do not take the first point, can get the maximum value for the treasure [2,n] the maximum value.
Dynamic programming, state transition equation:\ (Dp[i] = max (dp[i-1], dp[i-2] + v[i])
Analysis
Time complexity:\ (O (n) \).
Reference Code
////Created by Alvinzh on 2017/12/4.//Copyright (c) alvinzh. All rights reserved.//#include <cstdio>#include <iostream>#define MAX (A, b) a > B? a:busing namespaceStdintNintv[100005];/*int dp[100005];int MaxValue (int left, int. right){Dp[left] = V[left];dp[left+1] = max (V[left], v[left+1]);for (int i = left+2; I <= right; i++)Dp[i] = max (dp[i-1], dp[i-2] + v[i]);return dp[right];}*///Optimize codeintMaxValue (intLeftintright) {intLasttwo =0, LaStone =0; for(inti = left; I <= right; i++) {inttemp = LaStone; LaStone = Max (LaStone, Lasttwo + v[i]); Lasttwo = temp; }returnLaStone;}intMain () { while(~SCANF ("%d", &n)) { for(inti =1; I <= N; i++) scanf ("%d", &v[i]);if(n = =1) printf ("%d\n", v[1]);Elseprintf"%d\n", Max (MaxValue (1+ I-1), MaxValue (2, n))); }}
2016-level algorithm final simulation practice race-b.alvinzh Youth Memory I