洛谷P2736 [USACO3.4]“破鑼搖滾”樂隊 Raucous Rockers
阿新 • • 發佈:2020-11-23
題目
https://www.luogu.com.cn/problem/P2736
思路
一道簡單的DP題,注意到狀態的轉移比較複雜,推薦使用記憶化搜尋。注意遞迴返回條件的優先順序順序(我寫掛了2次TAT)。
程式碼
#include<cstdlib> #include<algorithm> using namespace std; int dp[21][21][21],n,m,t,a[21]; int dfs(int step,int remain,int id){ int r1=0,r2=0; if(step>n||id>m) return 0; if(dp[step][remain][id]!=-1) return dp[step][remain][id]; if(a[step]>t) return dfs(step+1,remain,id); if(a[step]>remain){ r1=dfs(step+1,remain,id); if(id<m) r2=dfs(step+1,t-a[step],id+1)+1; } else{ r1=dfs(step+1,remain,id); r2=dfs(step+1,remain-a[step],id)+1; } dp[step][remain][id]=max(r1,r2); return dp[step][remain][id]; } int main(){ int i,j,k,ans; scanf("%d%d%d",&n,&t,&m); for(i=1;i<=n;i++) scanf("%d",&a[i]); for(i=1;i<=n;i++) for(j=0;j<=20;j++) for(k=1;k<=m;k++) dp[i][j][k]=-1; ans=dfs(1,t,1); printf("%d",ans); //system("pause"); return 0; }