CH2401 送礼物(双向dfs)
生活随笔
收集整理的這篇文章主要介紹了
CH2401 送礼物(双向dfs)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
CH2401 送禮物
描述
作為懲罰,GY被遣送去幫助某神牛給女生送禮物(GY:貌似是個好差事)但是在GY看到禮物之后,他就不這么認為了。某神牛有N個禮物,且異常沉重,但是GY的力氣也異常的大(-_-b),他一次可以搬動重量和在w(w<=2^31-1)以下的任意多個物品。GY希望一次搬掉盡量重的一些物品,請你告訴他在他的力氣范圍內一次性能搬動的最大重量是多少。
輸入格式
第一行兩個整數,分別代表W和N。
以后N行,每行一個正整數表示G[i],G[i]<= 2^31-1。
輸出格式
僅一個整數,表示GY在他的力氣范圍內一次性能搬動的最大重量。
樣例輸入
20 5 7 5 4 18 1樣例輸出
19數據范圍與約定
- 對于20%的數據 N<=26
對于40%的數據 W<=2^26
對于100%的數據 N<=45 W<=2^31-1
- 對于20%的數據 N<=26
- 1. 將禮物分成兩半,首先在前一半中暴力搜索出所有情況,記錄,排序,去重,然后搜后一半禮物,對于后一半每一個可以達到的重量值t,都在前一半搜過的情況中二分查找W-t中數值最大的,然后更新答案,
- 2. 優化搜索順序,將禮物重量降序排列后再分半,搜索
- 3. 選取適當的折半劃分點,據lyd大佬所說,在N/2+2處搜索速度最快
代碼:
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <cctype> 5 #include <cmath> 6 using namespace std; 7 8 inline long long read() 9 { 10 long long x(0),f(1); char ch; 11 while(!isdigit(ch=getchar())) if(ch=='-') f=-1; 12 while(isdigit(ch)) x=x*10+ch-'0',ch=getchar(); 13 return f*x; 14 } 15 #define res register int 16 int g[50],n,half,tot; 17 unsigned int a[20000000],W,ans; 18 19 #define max(a,b) (a>b?a:b) 20 21 void dfs1(int x,unsigned int sum) 22 { 23 if(x==half) { 24 a[++tot]=sum; return ; 25 } 26 dfs1(x+1,sum); 27 if(sum+g[x]<=W) dfs1(x+1,sum+g[x]); 28 } 29 30 inline void calc(unsigned int val) 31 { 32 unsigned int rest=W-val; 33 int l=1,r=tot; 34 while(l<r) 35 { 36 int mid=(l+r+1)>>1; 37 if(a[mid]<=rest) l=mid; 38 else r=mid-1; 39 } 40 ans=max(ans,val+a[l]); 41 } 42 43 void dfs2(int x,unsigned int sum) 44 { 45 if(x==n+1) { 46 calc(sum); 47 return; 48 } 49 dfs2(x+1,sum); 50 if(sum+g[x]<=W) dfs2(x+1,sum+g[x]); 51 52 } 53 54 int main() 55 { 56 // W=read(); n=read(); 57 cin>>W>>n; 58 for(res i=1 ; i<=n ; i++) scanf("%d",&g[i]);//g[i]=read(); 59 sort(g+1,g+n+1); 60 reverse(g+1,g+n+1); 61 half=n/2+3; 62 dfs1(1,0); 63 sort(a+1,a+tot+1); 64 tot=unique(a+1,a+tot+1)-a-1; 65 dfs2(half,0); 66 printf("%lld\n",ans); 67 return 0; 68 } View Code?
轉載于:https://www.cnblogs.com/wmq12138/p/10386678.html
總結
以上是生活随笔為你收集整理的CH2401 送礼物(双向dfs)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微服务架构:如何用十步解耦你的系统?
- 下一篇: Unity 之命名规范(一)