[Ybtoj Chapter 1 Example 4] Passing game [Recursion]

Title description
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here


Problem solving idea
f (i, j) f(i,j)f(i,j ) means that the pass passes through j person in theiiThe number of plans in the hands of i classmates. Obviously, the ball of classmate i will bei − 1 i-1i1 ori + 1 i + 1i+1 is passed, so the recurrence formula can be obtained:f (i, j) = f (i − 1, j − 1) + f (i + 1, j − 1) f(i,j)=f(i- 1,j-1)+f(i+1,j-1)f(i,j)=fi1j1+f(i+1,j1)

PS: Since this question is a ring, 1 and n can be connected, so these two places must be judged specially.


Code

#include<iostream>
#include<cstdio>
using namespace std;
int n,m,f[30][20]; 
int main(){
    
    
	scanf("%d%d",&n,&m);
	f[1][0]=1;
	for(int j=1;j<=m;j++)
	{
    
    
		for(int i=1;i<=n;i++)
		{
    
    
			if(i==n)
				f[i][j]=f[1][j-1]+f[n-1][j-1];
			else if(i==1)
				f[i][j]=f[n][j-1]+f[2][j-1];
			else f[i][j]=f[i-1][j-1]+f[i+1][j-1];
		}
	}
	printf("%d",f[1][m]);
}

Guess you like

Origin blog.csdn.net/kejin2019/article/details/111637596