#include <algorithm> #include <functional> #include <cstdio> using namespace std; const int MX = 24; int n, m; unsigned int a[MX]; unsigned int b[105]; bool dp[2][1<<24]; unsigned int sum[1<<24]; unsigned int total; int best[1<<24]; int mask; int curr, prevr; unsigned int limit; bool go(int T, int i) { if (i == n) return dp[prevr][mask^T]; if (mask & (1<<i)) { if (sum[T|(1<<i)] <= limit) { if (dp[prevr][mask^T^(1<<i)]) { return true; } return go(T|(1<<i), i+1) | go(T, i+1); } } return go(T, i+1); } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n; ++i) scanf("%u", &a[i]); for (int i = 0; i < m; ++i) scanf("%u", &b[i]); sort(b, b+m, greater<int>()); m = min(n, m); for (int S = 0; S < (1<<n); ++S) { for (int i = 0; i < n; ++i) { if (S & (1<<i)) { sum[S] += a[i]; } } } total = sum[(1<<n) - 1]; dp[0][0] = true; for (int i = 0; i < m; ++i) { int prev = i&1, cur = 1 - prev; dp[cur][0] = true; for (int S = 1; S < (1<<n); ++S) { if (dp[prev][S]) dp[cur][S] = true; else { curr = cur; prevr = prev; mask = S; limit = min(b[i], total / (i+1)); dp[cur][S] = go(0, 0); } } if (dp[cur][(1<<n) - 1]) { printf("%d\n", i+1); return 0; } } printf("NIE\n"); return 0; }
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 77 78 79 80 | #include <algorithm> #include <functional> #include <cstdio> using namespace std; const int MX = 24; int n, m; unsigned int a[MX]; unsigned int b[105]; bool dp[2][1<<24]; unsigned int sum[1<<24]; unsigned int total; int best[1<<24]; int mask; int curr, prevr; unsigned int limit; bool go(int T, int i) { if (i == n) return dp[prevr][mask^T]; if (mask & (1<<i)) { if (sum[T|(1<<i)] <= limit) { if (dp[prevr][mask^T^(1<<i)]) { return true; } return go(T|(1<<i), i+1) | go(T, i+1); } } return go(T, i+1); } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n; ++i) scanf("%u", &a[i]); for (int i = 0; i < m; ++i) scanf("%u", &b[i]); sort(b, b+m, greater<int>()); m = min(n, m); for (int S = 0; S < (1<<n); ++S) { for (int i = 0; i < n; ++i) { if (S & (1<<i)) { sum[S] += a[i]; } } } total = sum[(1<<n) - 1]; dp[0][0] = true; for (int i = 0; i < m; ++i) { int prev = i&1, cur = 1 - prev; dp[cur][0] = true; for (int S = 1; S < (1<<n); ++S) { if (dp[prev][S]) dp[cur][S] = true; else { curr = cur; prevr = prev; mask = S; limit = min(b[i], total / (i+1)); dp[cur][S] = go(0, 0); } } if (dp[cur][(1<<n) - 1]) { printf("%d\n", i+1); return 0; } } printf("NIE\n"); return 0; } |