Just write down the status, and then just transfer it, no more.
Tips:
1. People hired on the third day can only work on the fourth day
2. The money earned that day can be used to recruit people
#include<bits/stdc++.h> using namespace std; int dp[41][101][41][4][2]; int n,x,y,z,A,B; int bes=1008610086; int dfs (int rs, int jq, int sy, int l, int sd) { int f=0; if(l==3) rs++,l=0,f=1; if(jq>=A&&sy>=B) return 0; if(rs>40||jq>40||sy>40) return 1008610086; if(dp[rs][jq][sy][l][f]!=1008610086) return dp[rs][jq][sy][l][f]; int &ans=dp[rs][jq][sy][l][f]; for(int i=0;i<=rs-f;i++){ if(sy>=B&&i) continue; if(l){ ans=min(ans,dfs(rs,jq+i*x,sy+(rs-f-i)*y,l+1,sd+1)+1); } else{ ans=min(ans,dfs(rs,jq+i*x,sy+(rs-f-i)*y,0,sd+1)+1); if(jq+i*x>=z) ans=min(ans,dfs(rs,jq+i*x-z,sy+(rs-f-i)*y,1,sd+1)+1); } } return ans; } int main(){ scanf("%d%d%d%d%d%d",&n,&x,&y,&z,&A,&B); for(int i=0;i<=40;i++) for(int j=0;j<=100;j++) for(int k=0;k<=40;k++) for(int l=0;l<=3;l++) dp[i][j][k][l][0]=dp[i][j][k][l][1]=1008610086; int ans=dfs(n,0,0,0,0); printf("%d\n",ans); return 0; }