B26 双向DFS 送礼物
视频链接:127 双向DFS 送礼物_哔哩哔哩_bilibili
//双向DFS+二分: N=2^23=8*10^6, N*logN=2^23*23=2*10^8 #include <iostream> #include <algorithm> using namespace std; int n,m; int g[46]; //存储所有物品的重量 int w[1<<23]; //存储能凑出来的重量 int ans,cnt; //w的个数为cnt //搜索第u个数,当前和为s void dfs1(int u,int s){ if(u==n/2){w[cnt++]=s; return;} //边界 dfs1(u+1,s); //不选g[u] if(g[u]<=m-s) dfs1(u+1,s+g[u]);//选g[u] } void dfs2(int u,int s){ if(u==n){ //找完了n个点,二分一下 ans=max(ans,*(upper_bound(w,w+cnt,m-s)-1)+s); return; } dfs2(u+1,s); //不选g[u] if(g[u]<=m-s) dfs2(u+1,s+g[u]);//选g[u] } int main(){ cin>>m>>n; //m重量上限, n个礼物 for(int i=0; i<n; i++) cin>>g[i]; sort(g,g+n); reverse(g,g+n); //优化搜索顺序 dfs1(0,0); //搜前一半[0,n/2) sort(w,w+cnt); cnt=unique(w,w+cnt)-w; dfs2(n/2,0); //搜后一半[n/2,n) cout<<ans; }
//双向DFS+二分: N=2^23=8*10^6, N*logN=2^23*23=2*10^8 #include <iostream> #include <algorithm> using namespace std; int n,m; int g[46]; //存储所有物品的重量 int w[1<<23]; //存储能凑出来的重量 int ans,cnt; //w的个数为cnt //搜索第u个数,当前和为s void dfs1(int u,int s){ if(u==n/2){w[cnt++]=s; return;} //边界 dfs1(u+1,s); //不选g[u] if(g[u]<=m-s) dfs1(u+1,s+g[u]);//选g[u] } void dfs2(int u,int s){ if(u==n){ //找完了n个点,二分一下 int l=0,r=cnt; while(l+1<r){ int mid=l+r>>1; w[mid]<=m-s?l=mid:r=mid; } if(w[l]<=m-s) ans=max(ans,s+w[l]); return; } dfs2(u+1,s); //不选g[u] if(g[u]<=m-s) dfs2(u+1,s+g[u]);//选g[u] } int main(){ cin>>m>>n; //m重量上限, n个礼物 for(int i=0; i<n; i++) cin>>g[i]; sort(g,g+n); reverse(g,g+n);//优化搜索顺序 dfs1(0,0); //搜前一半[0,n/2) sort(w,w+cnt); cnt=unique(w,w+cnt)-w; dfs2(n/2,0); //搜后一半[n/2,n) cout<<ans; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!