POJ 1742 Coins(多重背包 + 单调队列优化)
题意:
有 n 种硬币,每种硬币有 c 个,问这 n 种硬币能组成 1-m 的多少个价值。
思路:
1. 背包可行性问题,把价值看成是重量,求最后的解决方案
2. 用普通的方法会超时,倍增优化也只是擦边线,最后看到了单调队列优化
3. 由于 w == v 时,单调队列的特殊性,可以简化思路:sum 为队列里面状态的和,当 !dp[v] && sum 为真时,说明当剩余类为 rem 时,状态 dp[v] 可以恰好装满
4. 采用了2点剪枝:ci == 1 和 ci * ai >= m,分别采用 01 背包 和 完全背包 策略
参考文章:
http://wenku.baidu.com/view/8ab3daef5ef7ba0d4a733b25.html
http://www.cppblog.com/flyinghearts/archive/2010/09/01/125555.html
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 110;
const int MAXD = 100010;
int A[MAXN], C[MAXN];
bool dp[MAXD], deq[MAXD];
int main()
{
int n, m;
while (scanf("%d %d", &n, &m) && n && m >= 0)
{
for (int i = 0; i < n; ++i)
scanf("%d", &A[i]);
for (int i = 0; i < n; ++i)
scanf("%d", &C[i]);
for (int v = 0; v <= m; ++v)
dp[v] = false;
int ret = 0;
dp[0] = true;
for (int i = 0; i < n; ++i)
{
if (C[i] == 1)
{
for (int v = m; v >= A[i]; --v)
if (!dp[v] && dp[v - A[i]])
dp[v] = true, ++ret;
continue;
}
if (A[i] * C[i] >= m)
{
for (int v = A[i]; v <= m; ++v)
if (dp[v - A[i]] && !dp[v])
dp[v] = true, ++ret;
continue;
}
for (int rem = 0; rem < A[i]; ++rem)
{
int s = 0, e = -1, sum = 0;
for (int v = rem; v <= m; v += A[i])
{
if (s + C[i] == e)
sum -= deq[s++];
deq[++e] = dp[v];
sum += dp[v];
if (!dp[v] && sum)
dp[v] = true, ++ret;
}
}
}
printf("%d\n", ret);
}
return 0;
}
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------