Problem p id: 1016
In an infinitely large plane, you can only go forward, left, or right. You cannot go backward. Calculate the total number of steps n (n <= 20.
Process of solving the problem: set F (n) to the total number of solutions in n steps, a (n) to the total number of solutions in n steps, B (n) the total number of steps left or right for the last step of N. It can be introduced as follows: ① F (n) = a (n) + B (n); (obviously) ② A (n) = a (n-1) + B (n-1 ); (Steps n-1, whether forward or left or right, can be taken forward in step n.) ③ B (n) = 2 * a (n-1) + B (n-1 ); (If step N-1 is forward, you can go left or right in step N. Therefore, a (n-1) must be multiplied by 2; if step N-1 is left, it cannot go right. Step n-1 to right cannot go left. Otherwise, the road will collapse. Therefore, B (n-1) does not need to be multiplied by 2) ④ a (n-1) = f (n-2); (regardless of how the N-2 step is taken, can go forward in step N-1) by the above 4 formula available state transfer equation: A [I] = 2 * A [I-1] + A [I-2]; and because: A [0] = 3; A [1] = 7; the problem is solved.
Feeling: I think it's another problem that I have been thinking for a long time and I have drawn some questions that I haven't solved for a long time. I still want to find related algorithms on the Internet. However, after reading other people's algorithms, I quickly understood them. Unlike the previous question, I had to think for a while. This question also gave me a great deal of emotion, and I thought it was very simple after I had done it. However, when I was alone in the face of this problem, many ideas should not come up, DP, DP, or recurrence, various splits, various steps forward from the next step to find the answer. Lack of experience and ability, you still need to work hard to answer questions.
Code:
#include <iostream>#include <stdio.h>#include <string.h>using namespace std;int a[21];void dp(){ a[0]=3; a[1]=7; for(int i=2;i<=19;++i){ a[i]=2*a[i-1]+a[i-2]; }}int main(){ int n; scanf("%d",&n); dp(); while(n--) { int m; scanf("%d",&m); printf("%d\n",a[m-1]); } return 0;}
DP dynamic plan problem P 1016 Number of walking solutions without backward walking