这道题我超时了!请求大佬优化

P2677 [USACO07DEC] Bookshelf 2 B

题目???
by LquidKeseLameGG @ 2022-04-30 14:39:39


@[KeseLameGG](/user/722682) P2677
by YIDINGZ @ 2022-04-30 15:03:55


你可以试着换成C语言的输入输出
by 左昊天 @ 2022-04-30 15:04:46


```cpp #include <iostream> #include <cstring> #include <string> #include <cstdio> #include <algorithm> //#define ing long long using namespace std; const int maxn=1e6+5; int n,k,a[maxn],dp[20000005]; int main() { cin>>n>>k; int sum=0; for(int i=1; i<=n; i++) { cin>>a[i]; sum+=a[i]; } for(int i=1; i<=n; i++) for(int j=sum; j>=a[i]; j--) dp[j]=max(dp[j],dp[j-a[i]]+a[i]); for(int i=k;i<=sum;i++){ if(dp[i]==i){//如果当前的体积可以放满,说明对应的背包方案存在 cout<<i-k<<endl; //cout<<i<<" "<<dp[i]<<endl; break; } } } ```
by LquidKeseLameGG @ 2022-04-30 19:46:34


无超时
by LquidKeseLameGG @ 2022-04-30 19:48:04


@[YIDINGZ](/user/592111) 为啥要for循环? 先选和后选无实质上的区别 ```cpp #include<iostream> using namespace std; int n,h[30],b; int ans=0x7fffffff; void dfs(int x,int now){ if(x>n){ if(now>=b)ans=min(ans,now); return; } dfs(x+1,now+h[x]); dfs(x+1,now); return; } int main(){ cin>>n>>b; for(int i=1;i<=n;i++){ cin>>h[i]; } dfs(1,0); cout<<ans-b; } ``` 这是我的搜索,希望能对你有所帮助。
by WannaYellow @ 2022-05-18 17:25:22


|