标签:超时 for target clu space 礼物 stdin sort boa
20 5
7
5
4
18
1
19
对于20%的数据 N<=26
对于40%的数据 W<=2^26
对于100%的数据 N<=45 W<=2^31-1
最多45件礼物,如果直接暴力枚举就会超时。将礼物分成两半,分别枚举出两半中的各种组合,然后利用二分进行匹配,寻找最优解。
#include "bits/stdc++.h" using namespace std; const int maxn = 1e7 + 11; typedef long long ll; ll s[100]; ll sum[maxn]; ll ans = 0; int tot = 0; ll w, n; void dfs1(int now, ll val) { if (now > n) { sum[++tot] = val; return; } if (val + s[now] <= w) dfs1(now + 1, val + s[now]); dfs1(now + 1, val); } int mid; void dfs2(int now, ll val) { if (now >= mid) { ll l = lower_bound(sum + 1, sum + tot + 1, w - val) - sum; ans = max(ans, val + sum[l-1]); return; } if (val + s[now] <= w) dfs2(now + 1, val + s[now]); dfs2(now + 1, val); } int main() { //freopen("input.txt", "r", stdin); cin >> w >> n; for (int i = 1; i <= n; i++) { cin >> s[i]; } sort(s + 1, s + 1 + n); mid = (n + 1) >> 1; dfs1(mid, 0); sort(sum + 1, sum + tot + 1); dfs2(1, 0); cout << ans << endl; return 0; }
标签:超时 for target clu space 礼物 stdin sort boa
原文地址:https://www.cnblogs.com/albert-biu/p/10111177.html