C++ Dynamic Programming - Solving the passing problem

  [ Problem description]
  During physical education class, Xiaoman's teacher often took the students to play games together. This time, the teacher took the students to play the passing game together.
  The rules of the game are as follows: n students stand in a circle, and one of them holds a ball in his hand. When the teacher blows the whistle, he starts to pass the ball. Each student can pass the ball to the two students on his left and right. One (either left or right), when the teacher blows the whistle again, the passing of the ball stops. At this time, the student who holds the ball and fails to pass it is the loser, and he will perform a show for everyone.
  The clever Xiaoman raised an interesting question: how many different ways of passing the ball can make the ball passed from Xiaoman's hands, and after m times of passing, return to Xiaoman's hands. The two methods of passing the ball are considered different methods if and only if the sequence of the students receiving the ball in the order of receiving the ball is different in the two methods. For example, there are three classmates No. 1, No. 2, and No. 3, and assuming that Xiaoman is No. 1, the way to return the ball to Xiaoman after passing the ball three times is 1->2->3->1 and 1->3 ->2->1, 2 types in total.

input format

  A total of one line, there are two integers n and m separated by spaces (3<=n<=30, 1<=m<=30).

output format

  There is one line of t, and there is an integer, indicating the number of methods that meet the meaning of the question.

sample input

3 3

sample output

2

Data Size and Conventions

  40% of the data satisfies: 3<=n<=30, 1<=m<=20
  100% of the data satisfies: 3<=n<=30, 1<=m<=30

The dynamic programming code is as follows


#include<bits/stdc++.h>
using namespace std;
int n,m,f[35][35];
int main()
{ // Enter the number of people and the number of passes cin>>n>>m; // When there is only one person, there is only one case of passing the ball once f[1][0]=1; // find out the case of i passes for(int i=1;i<=m;i++) // find out The case of person j passing the ball for(int j=1;j<=n;j++) // When j person passes the ball i times, the number of types is j-1 person, and the i-1 ball is passed +j+1 person, The sum of the number of balls i-1 times f[j][i]=f[j-1==0?n:j-1][i-1]+f[j%n+1][i- 1]; // Output the planting tree of the first person passing the ball m times cout<<f[1][m]; return 0; }













Guess you like

Origin blog.csdn.net/weixin_53064820/article/details/129944108