ACdreamOJ 1726 hash, acdreamoj1726hash
Http://acdream.info/problem? Pid = 1, 1726
Problem DescriptionRecently, Losanto find an interesting Math game. the rule is simple: Tell you a number H, and you can choose some numbers from a set {a [1], a [2],..., a [n]}. if the sum of the number you choose is H, then you win. losanto just want to know whether he can win the game. inputThere are several cases.
In each case, there are two numbers in the first line n (the size of the set) and H. the second line has n numbers {a [1], a [2],..., a [n]}. 0 <n <= 40, 0 <= H <10 ^ 9, 0 <= a [I] <10 ^ 9, All the numbers are integers. outputIf Losanto cocould win the game, output "Yes" in a line. else output "No" in a line. sample Input
10 872 3 4 5 7 9 10 11 12 1310 382 3 4 5 7 9 10 11 12 13
Sample Output
NoYes
/** ACdreamOJ 1726 hash question: given the number of n, I would like to ask whether the parts of these numbers can constitute m. The solution is: Since the maximum value of n is only 40, therefore, we divide all the numbers into two equal parts, and use hash to search for them. */# include <stdio. h> # include <string. h >#include <algorithm> # include <iostream> # include <queue> # include <map> using namespace std; typedef long LL; const int MAXN = 1 <20; const int HASH = 1000007; struct hashmap // create a HASH table {LL a [MAXN]; int head [HASH], next [MAXN], size; void init () // initialize {memset (head,-1, sizeof (he Ad); size = 0;} bool find (LL val) // query whether an element is in the HASH table {int tmp = (val % HASH + HASH) % HASH; for (int I = head [tmp]; I! =-1; I = next [I]) if (val = a [I]) return true; return false;} void add (LL val) // add elements to the HASH table {int tmp = (val % HASH + HASH) % HASH; if (find (val) return; a [size] = val; next [size] = head [tmp]; head [tmp] = size ++ ;}} h1; int n, m, num [55]; int main () {while (~ Scanf ("% d", & n, & m) {h1.init (); for (int I = 0; I <n; I ++) {scanf ("% d", & num [I]);} int t = n/2; for (int I = 0; I <(1 <t ); I ++) {LL sum = 0; for (int j = 0; j <t; j ++) {if (I & (1 <j )) {sum + = num [j] ;}} if (sum> m) continue; h1.add (sum) ;}int tt = n-t; int flag = 0; for (int I = 0; I <(1 <tt); I ++) {LL sum = 0; for (int j = 0; j <tt; j ++) {if (I & (1 <j) {sum + = num [t + j] ;}} if (sum> m) continue; if (h1.find (m-sum) {flag = 1; break ;}} if (flag) printf ("Yes \ n "); else printf ("No \ n");} return 0 ;}