赞
踩
//DFS + 剪枝优化 #include<bits/stdc++.h> #define endl "\n" #define deb(x) cout << #x << " = " << x << '\n'; #define INF 0x3f3f3f3f using namespace std; const int N = 100; double a[N]; double s[N]; int n, m; int ans = INF;//当前合法方案的最小值。 void dfs(int u, double w, int cnt) { if(w == m){ ans = min(ans, cnt); return; } //如果n个瓜都遍历完了,那就返回。 if(u >= n)return; //如果当前方案并不优于已有的合法答案,那就返回。 if(cnt >= ans)return; //如果总重量已经超了,那么当前方案不合法。 if(w > m)return; //如果后面的瓜的所有重量加起来,都小于m,那么当前方案不合法。 if(w + s[u] < m)return; //选,但是不切 dfs(u + 1, w + a[u], cnt); //选,但是切 dfs(u + 1, w + a[u] / 2.0, cnt + 1); //不选 dfs(u + 1, w, cnt); } void solve() { cin >> n >> m; for(int i = 0; i < n; i ++){ cin >> a[i]; } sort(a, a + n, [&](int x, int y){return x > y;}); for(int i = n - 1; i >= 0; i --){ s[i] = s[i + 1] + a[i]; } dfs(0, 0.0, 0); if(ans == INF)ans = -1; cout << ans << endl; } signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; // cin >> t; while(t--) solve(); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。