题解:P8548 小挖的买花

· · 题解

背景

本人首次写题解

楼上这么说:

很一眼的三维 DP

个人认为,本题可用二维DP,相较于三维DP,二维DP可以优化代码。但要注意的是,本题类似01背包,二维需要逆序遍历,以避免重复计算。
设 dp_{c,f} 中的c表示还剩余c的钱数,f表示还差的新鲜程度,转移的就是 dp_{c-cost,\max(0,f-fr)} ,可以确定转移方程为:

dp_{c,f}=\max(dp_{c,f},dp_{c-cost,\max(0,f-fr)}+be)

解释

### 初始化 可初始化为`-0x3f3f3f3f`,用以代表未被计算过,直接使用`memset`即可,若答案为负数就输出`0`。 ### 边界条件 接下来考虑边界,因为`c = 0`时,找不到任意一株花能使新鲜度为`0`,所以此时`dp[c][j] = 0`,即 $$ 对于\ \forall f \in [1,500]\ ,dp_{0,f}=0 $$ # Code ~~~cpp #include<bits/stdc++.h> using namespace std; int n,q; int dp[501][501]; int t[501][501]; int main(){ scanf("%d%d",&n,&q); memset(dp,-0x3f3f3f3f,sizeof(dp)); for(int i=0;i<=500;i++) dp[i][0]=0; for(int k=1;k<=n;k++){ int cost,fr,be; scanf("%d%d%d",&cost,&fr,&be); for(int f=500;f>=0;f--){ for(int c=500;c>=cost;c--){ dp[c][f]=max(dp[c][f],dp[c-cost][max(0,f-fr)]+be); } } } for(int i=1;i<=q;i++){ int c,f; scanf("%d%d",&c,&f); printf("%d\n",max(0,dp[c][f])); } return 0; } ~~~