-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem0171.h
76 lines (67 loc) · 2.2 KB
/
Problem0171.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//
// Created by Fengwei Zhang on 2021/7/26.
//
#ifndef ACWINGSOLUTION_PROBLEM0171_H
#define ACWINGSOLUTION_PROBLEM0171_H
#include <algorithm>
#include <iostream>
using namespace std;
class Problem0171 {
// https://www.acwing.com/solution/content/38250/
public:
const int N = 46;
int g[N];
int firstHalfWeights[1 << (N / 2)];
int wEnd = 0;
int findUpperValue(const int *arr, int start, int end, const int target) {
while (start < end) {
auto mid = start + (end - start + 1) / 2;
if (arr[mid] <= target) {
start = mid;
} else {
end = mid - 1;
}
}
return arr[start];
}
void dfs1(const int currentIdx, const int currentSum, const int n, const int maxSum) {
if (currentIdx == n) {
firstHalfWeights[wEnd++] = currentSum;
return;
}
dfs1(currentIdx + 1, currentSum, n, maxSum);
if ((long long) currentSum + g[currentIdx] > maxSum) {
return;
}
dfs1(currentIdx + 1, currentSum + g[currentIdx], n, maxSum);
}
void dfs2(const int currentIdx, const int currentSum, const int n, const int maxSum, int &answer) {
if (currentIdx == n) {
int maxOfFirstHalf = findUpperValue(firstHalfWeights, 0, wEnd - 1, maxSum - currentSum);
answer = max(answer, maxOfFirstHalf + currentSum);
return;
}
dfs2(currentIdx + 1, currentSum, n, maxSum, answer);
if ((long long) currentSum + g[currentIdx] > maxSum) {
return;
}
dfs2(currentIdx + 1, currentSum + g[currentIdx], n, maxSum, answer);
}
int main() {
int maxSum, n;
scanf("%d%d", &maxSum, &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &g[i]);
}
sort(g, g + n);
reverse(g, g + n);
dfs1(0, 0, n / 2, maxSum);
sort(firstHalfWeights, firstHalfWeights + wEnd);
wEnd = (int) (unique(firstHalfWeights, firstHalfWeights + wEnd) - firstHalfWeights);
int answer = -1;
dfs2(n / 2, 0, n, maxSum, answer);
printf("%d\n", answer);
return 0;
}
};
#endif //ACWINGSOLUTION_PROBLEM0171_H