问题(暂无链接)
输入的第一行, 是要包含的砝码数: n;
输入第二行, 是所有砝码的重量数据: 数组Wn;
求砝码的组合能用来测量哪些重量的物品, 输出能测的不同重量的合计数目.
其中
对50%测试,砝码数n<15,
对全部测试,砝码数n<100,
砝码重量和不超过100000
样例
样例输入
3
1 4 6
输出
10
试图解答
他妈的,我在考场上没来得及写出正确代码来! 天杀的第三题货物堆放!
考完看群里老哥吹水,才想起来这可以算变体的01背包问题
考后写出来的能实现样例的代码如下
(PS: 能暴力的绝不节约时间和空间(小孩子别学))
(PS的PS: 居然取绝对值函数在stdlib库里面,而不是math库里, 好申必)
#include<iostream>
#include<cstdlib>
using namespace std;
#define max_weight 100001
int* weight;
int* state;
int* is;
int n = 0;
int num = 0;
void r(int a) {
int temp = 0;
// 每一个砝码的三种状态(同侧,两侧,不计入),对应到重量计算就是加减和乘以0,统一到一行代码里实现
temp = 0;
state[a] = 0;
for (int i = 0; i < n; i++)
{
temp += weight[i] * state[i];
}
temp = abs(temp);// 取绝对值
if (temp && is[temp] == 0)
{
is[temp] = 1;
num++;
}
if (a < n - 1) {
r(a + 1);
}
temp = 0;
state[a] = -1;
for (int i = 0; i < n; i++)
{
temp += weight[i] * state[i];
}
temp = abs(temp);
if (temp && is[temp] == 0)
{
is[temp] = 1;
num++;
}
if (a < n - 1) {
r(a + 1);
}
temp = 0;
state[a] = 1;
for (int i = 0; i < n; i++)
{
temp += weight[i] * state[i];
}
temp = abs(temp);
if (temp && is[temp] == 0)
{
is[temp] = 1;
num++;
}
if (a < n - 1) {
r(a + 1);
}
}
int main() {
cin >> n;
weight = new int[n];
state = new int[n];
for (int i = 0; i < n; i++)
{
cin >> weight[i];
state[i] = 0;
}
is = new int[max_weight];
for (int i = 0; i < max_weight; i++)
{
is[i] = 0;
}
r(0);
cout << num;
return 0;
}