生活随笔
收集整理的這篇文章主要介紹了
2020ICPC(小米邀请赛2) - Knapsack(贪心+dp)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出 n 個物品,每個物品都有體積和價值,現在問容量為 m 的背包最多可以裝下多少價值的物品
題目分析:本題正解應該是斜率優化dp,然鵝看了大佬們的博客講解后,感覺不是自己可以觸碰的領域,所以用了一種 “投機取巧” 的方法實現本題
直接進行 01 背包時間復雜度是 n * m 級別的,但是每個物品最大的容量是 100,所以考慮大范圍貪心小范圍 dp,貪心決策就是按照每個物品單位體積的價值降序排序,然后貪心取即可,小范圍進行背包選擇最優價值,閾值我設置的是 200,只要在規定的時間復雜度內,閾值可以適當增大
代碼:
?
//#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast","inline","-ffast-math")
//#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e6+100;struct Node
{LL cost,val;void input(){scanf("%lld%lld",&cost,&val);}bool operator<(const Node& t)const{return val*t.cost>t.val*cost;}
}node[N];LL dp[210];int main()
{
#ifndef ONLINE_JUDGE
// freopen("data.in.txt","r",stdin);
// freopen("data.out.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);int n,m;while(scanf("%d%d",&n,&m)!=EOF){memset(dp,0,sizeof(dp));for(int i=1;i<=n;i++)node[i].input();sort(node+1,node+1+n);LL ans=0;int st=1;while(st<=n&&m>=200){ans+=node[st].val;m-=node[st].cost;st++;}for(int i=st;i<=n;i++)for(int j=m;j>=node[i].cost;j--)dp[j]=max(dp[j],dp[j-node[i].cost]+node[i].val);printf("%lld\n",ans+dp[m]);}return 0;
}
?
總結
以上是生活随笔為你收集整理的2020ICPC(小米邀请赛2) - Knapsack(贪心+dp)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。