Topic Links:
http://www.lightoj.com/volume_showproblem.php?problem=1235
Title Description:
Give n coins, each coin use up to two times, ask can form K value?
Problem Solving Ideas:
Because K chicken big, although n is very small, but 2^n is very big, cannot use the knapsack to do O (NK) complexity. If the violent enumeration complexity immediately soared to O (2^ (n+1)).
So the introduction of a new algorithm, binary lookup: The value to be enumerated, the first part of the value of all cases enumerated, and then the value of the latter part of all the situation enumerated and sorted, combined with two points to find. This reduces the complexity to O (2^ (N/2) *log2 (n)).
Recently did not do the problem, feel oneself Meng Meng da. Everyone play seven, to me, I always look like a crazy face. Hope one day a DP, to the old can also Meng da (.? ' Ω´?)
Code:
1 #include<cstdio>
2 #include<cstring>
3 #include<iostream>
4 #include<algorithm>
5 #include<cmath>
6 using namespace std;
7
8 #define maxn 20000
9 int cnt1, cnt2, k, n, num;
10 int a1[maxn], a2[maxn], b[20];
11
12 void dfs (int sum, int x)
13 {
14 if (x == num)
15 {
16 num == n/2 ? a1[cnt1++] = sum : a2[cnt2++] = sum;
17 return ;
18 }
19 for (int i=0; i<3; i++)
20 dfs (sum+b[x]*i, x+1);
21 }
22
23 bool sreach (int x)
24 {
25 int low = 0, high = cnt2-1;
26
27 while (low <= high)
28 {
29 int mid = (low + high) / 2;
30 if (a1[x] + a2[mid] == k)
31 return true;
32 else if (a1[x] + a2[mid] > k)
33 high = mid - 1;
34 else
35 low = mid + 1;
36 }
37
38 return false;
39 }
40
41 int main ()
42 {
43 int T, l = 1;
44 scanf ("%d", &T);
45
46 while (T --)
47 {
48 scanf ("%d %d", &n, &k);
49 for (int i=0; i<n; i++)
50 scanf ("%d", &b[i]);
51
52 cnt1 = cnt2 = 0;
53 num = n / 2;
54 dfs (0, 0);
55
56 num = n;
57 dfs (0, n/2);
58 sort (a2, a2 + cnt2);
59
60 int i;
61 for (i=0; i<cnt1; i++)
62 {
63 if (sreach (i))
64 break;
65 }
66 if (i == cnt1) printf("Case %d: No\n", l++);
67 else printf ("Case %d: Yes\n", l++);
68 }
69 return 0;
70 }
Lightoj 1235-coin Change (IV) (binary enumeration)