题目大意
现有n个砝码,重量分别为a1,a2,a3,……,an,在去掉m个砝码后,问最多能称量出多少不同的重量(不包括0)。n≤20,m≤4,m<n,ai≤100。
题解
错误做法
首先枚举子集预处理出不去掉砝码所能得到的重量,随后枚举组合得到去掉的砝码集合A,随后在去掉的砝码里枚举子集得到损失的重量数。
但是请先试一试样例!这么做是不对的!因为损失的重量还与A内和A外的砝码有关!
完了完了,赶紧打个暴力,直接枚举A以外的砝码的子集来得到能凑成的重量吧。。。
正确做法
枚举子集得到重量?优化子集问题为何不想到01背包!
另外有剪枝:优化搜索顺序,将砝码按重量排序,随后如果枚举组合时后一个元素与前一个元素相同,则跳过。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int MAX_N = 25, MAX_W = 2010, INF = 0x3f3f3f3f;
int N, M, TotW, Ans;
int W[MAX_N];
bool F[MAX_W];
void DP()
{
memset(F, false, sizeof(F));
F[0] = true;
for (int i = 1; i <= N; i++)
for (int j = TotW; j >= W[i]; j--)
F[j] |= F[j - W[i]];
int ans = 0;
for (int i = 1; i <= TotW; i++)
ans += F[i];
Ans = max(Ans, ans);
}
void DoSth(vector<int>& chosen)
{
static int tempW[MAX_N];
for (int i = 0; i < chosen.size(); i++)
{
tempW[chosen[i]] = W[chosen[i]];
W[chosen[i]] = 0;
}
DP();
for (int i = 0; i < chosen.size(); i++)
W[chosen[i]] = tempW[chosen[i]];
}
void Dfs(vector<int>& chosen, int n, int m, int begin)
{
if (m == 0)
{
DoSth(chosen);
return;
}
if (n - begin + 1 < m)
return;
for (int i = begin; i <= n; i++)
{
if (i == begin || W[i] != W[i - 1])
{
chosen.push_back(i);
Dfs(chosen, n, m - 1, i + 1);
chosen.pop_back();
}
}
}
int main()
{
scanf("%d%d", &N, &M);
for (int i = 1; i <= N; i++)
scanf("%d", &W[i]);
sort(W + 1, W + N + 1);
for (int i = 1; i <= N; i++)
TotW += W[i];
static vector<int> chosen;
Dfs(chosen, N, M, 1);
printf("%d\n", Ans);
return 0;
}