6039. Subset Sum
Constraints
Time Limit: 1 secs, Memory Limit: 256 MB
Description
Maia would like to buy exactly 3.141592 litres of milk. But guess what? Her local grocery store does not stock a bag that size! So Maia decides to buy multiple bags. Even so, it might not be possible to buy a total of exactly 3.141592 litres. In that case, she is willing to buy a little bit more if necessary, but she wants to minimize the extra amount. In addition, Maia wants the bags to all be of distinct sizes, because it would be too boring to buy two bags of the same size. Maia painstakingly figures out which bags of milk to buy. But the next day, she wants 2.718281 litres of milk, and she has to figure it all out again. Clearly she needs to write a program to help her.
Input
The first line of input contains two integers 0 <= n <= 1000000000 and 0 < m <= 20, the number of microlitres of milk that Maia wants, and the number of sizes of milk that the store sells. The following m lines each contain an integer 0 <= a <= 1000000000, the size of a bag of milk that the store sells (in microlitres).
Output
Output a single integer, the minimum total number of microlitres of milk that Maia needs to buy in order to have at least n microlitres. If it is not possible to buy at leastn microlitres, output the word IMPOSSIBLE.
Sample Input
5859870 3 3141592 2718281 1000000
Sample Output
5859873
Problem Source
Waterloo Local Contest 2012.9
// Problem#: 6039
// Submission#: 3376220
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <iomanip>
#include <algorithm>
#include <queue>
#include <functional>
#include <map>
#include <string.h>
#include <math.h>
using namespace std;
long long M[25];
long long N, m;
long long ans = 1000000005;
void dfs(int pos, long long sum) {
if (pos == m) {
if (sum >= N) ans = min(sum, ans);
return;
}
if (sum >= ans) return;
dfs(pos + 1, sum);
dfs(pos + 1, sum + M[pos]);
}
int main() {
std::ios::sync_with_stdio(false);
cin >> N >> m;
for (int i = 0; i < m; i++) cin >> M[i];
dfs(0, 0);
cout << ans << endl;
return 0;
}