直到做了EOJ3544“小迷妹在哪”
我才意識到我一直都把01揹包中dp數組的含義理解錯了
我之前一直以爲一個容量爲10的揹包,dp[10]表示的是揹包爲空的狀態,dp[0]表示的是沒有空間的狀態;
因爲之前做的題對這個方向沒有實際的差別,就一直沒發現這個錯誤,直到這道題。
這道題把揹包剩餘空間作爲了價值的一部分,因此就有了方向上的差別,如果理解錯了就會wa
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,T;
struct per
{
int a,t;
bool operator<(const per&c)const{
return a*c.t>t*c.a;
}
}p[100010];
int dp[310];
int main()
{
scanf("%d %d",&n,&T);
for(int i=0;i<n;i++){
scanf("%d %d",&p[i].a,&p[i].t);
}
sort(p,p+n);
memset(dp,0,sizeof(dp));
int ans = 0;
for(int i=0;i<n;i++){
for(int v = T;v>=p[i].t;v--){
dp[v] = max(dp[v],dp[v-p[i].t]+(T-v)*p[i].a); //差別就在這個地方
ans = max(ans,dp[v]);
}
}
printf("%d\n",ans);
return 0;
}
dp[v]表示的應當是已經使用了v空間,而不是剩餘空間是v
另外這道題還需要注意的是,需要對物品進行性價比排序,即
bool operator<(const per&c)const{
return a*c.t>t*c.a;
}