本题直接使用一个快排和深搜dfs可以解决
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int value_M, tolerance, n, need;
//使用结构体进行存储,方便使用快速排序
typedef struct stone {
int value;
int weight;
}Stone;
Stone a[20];
//以宝石weight为首要标准,从大到小排,weight相同情况下value从大到小
int cmp(Stone x, Stone y) {
if (x.weight == y.weight) return x.value > y.value;
return x.weight > y.weight;
}
void dfs(int k, int ×, int &value, int &weight) {
if (times == need) {//所需宝石数量达到目的
if (value > value_M)//value最大值更新
value_M = value;
return;
}
for (int i = k + 1; i < n; i++) {
if (weight + a[i].weight <= tolerance) {//weight要在可接受范围内才可以进行操作
value += a[i].value;
weight += a[i].weight;
times++;
dfs(i, times, value, weight);//当前宝石符合要求,继续寻找下一个
value -= a[i].value;
weight -= a[i].weight;
times--;
}
}
}
int main() {
int t, value, weight, times;
while (cin >> t)
while (t--) {
for (int i = 0; i < 20; i++) {//初始化
a[i].value = 0;
a[i].weight = 0;
}
value = 0;
weight = 0;
times = 0;
value_M = 0;
cin >> n >> need;
for (int i = 0; i < n; i++)
cin >> a[i].value >> a[i].weight;
cin >> tolerance;
sort(a, a + n, cmp);
while (a[0].weight > tolerance) {//以经排好序,把单个weight大于tolerance的宝石丢掉
for (int i = 0; i < n - 1; i++)
a[i] = a[i + 1];
n--;
}
dfs(0, times, value, weight);
cout << value_M << endl;
}
return 0;
}