Total Submission(s): 2235 Accepted Submission(s): 868
For each case, the first line contains two integers N (N <= 20), the total number of stones, and K (K <= N), the exact number of stones to make a necklace.
Then N lines follow, each containing two integers: a (a<=1000), representing the value of each precious stone, and b (b<=1000), its weight.
The last line of each case contains an integer W, the maximum weight my mother will accept, W <= 1000.
1 2 1 1 1 1 1 3
1
#include <iostream> #include <limits> using namespace std; int c, n, k, max_w; int max_val, sum_val, sum_w; struct node { int val; int w; int visit; }a[22]; void DFS(int start,int count) //start循环开始点,count记录已用石头数 { int i; if(sum_w > max_w) //剪枝 return ; if(count > k) return; if(k == count && sum_w <= max_w) { if(max_val < sum_val) max_val = sum_val; return ; } for(i = start; i < n; i++) // if(a[i].visit == 0) { sum_val += a[i].val; sum_w += a[i].w; a[i].visit = 1; DFS(i + 1, count + 1); sum_val -= a[i].val; sum_w -= a[i].w; a[i].visit = 0; } } int main() { int i; cin >> c; while(c--) { cin >> n >> k; for(i = 0; i < n; i++) { cin >> a[i].val; cin >> a[i].w; a[i].visit = 0; } cin >> max_w; sum_w = sum_val = max_val = 0; DFS(0, 0); cout << max_val << endl; } return 0; }