Advertisement
Dmaxiya

买瓜 参考代码

Apr 4th, 2025
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long LL;
  5. const int maxn = 100;
  6. int n, ans;
  7. LL m;
  8. LL num[maxn];
  9. unordered_map<LL, int> cnt;
  10. unordered_map<LL, int>::iterator it;
  11.  
  12. void dfs1(int depth, LL sum, int k) {
  13.     if (sum > m) {
  14.         return ;
  15.     }
  16.     if (depth == n / 2 + 1) {
  17.         it = cnt.find(sum);
  18.         if (it == cnt.end()) {
  19.             cnt[sum] = k;
  20.         } else {
  21.             it->second = min(it->second, k);
  22.         }
  23.         return ;
  24.     }
  25.     dfs1(depth + 1, sum, k);
  26.     dfs1(depth + 1, sum + num[depth], k);
  27.     dfs1(depth + 1, sum + num[depth] / 2, k + 1);
  28. }
  29.  
  30. void dfs2(int depth, LL sum, int k) {
  31.     if (sum > m) {
  32.         return ;
  33.     }
  34.     if (depth == n + 1) {
  35.         it = cnt.find(m - sum);
  36.         if (it != cnt.end()) {
  37.             ans = min(ans, it->second + k);
  38.         }
  39.         return ;
  40.     }
  41.     dfs2(depth + 1, sum, k);
  42.     dfs2(depth + 1, sum + num[depth], k);
  43.     dfs2(depth + 1, sum + num[depth] / 2, k + 1);
  44. }
  45.  
  46. int main() {
  47. #ifdef ExRoc
  48.     freopen("test.txt", "r", stdin);
  49. #endif // ExRoc
  50.     ios::sync_with_stdio(false);
  51.  
  52.     cin >> n >> m;
  53.     m <<= 1;
  54.     for (int i = 1; i <= n; ++i) {
  55.         cin >> num[i];
  56.         num[i] <<= 1;
  57.     }
  58.     sort(num + 1, num + 1 + n);
  59.     ans = INT_MAX;
  60.     dfs1(1, 0, 0);
  61.     dfs2(n / 2 + 1, 0, 0);
  62.     cout << (ans == INT_MAX ? -1 : ans) << endl;
  63.  
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement