【题目链接】点击打开链接
【题意】给定N, K, N种物品每种的价值为Ai,必须装满K个物品的背包,求所有能装的价值,从小到大输出。
【解题方法】其实就是长度为1000的价值向量的k次幂, 存在该价值就为1,否则为0。然后用FFT求K维卷积,用bool数组可以降低精度误差,同时长度不要直接设为1e6。
【复杂度分析】 O(W*logW*logK)
【AC代码】
//
//Created by BLUEBUFF 2016/1/10
//Copyright (c) 2016 BLUEBUFF.All Rights Reserved
//
#pragma comment(linker,"/STACK:102400000,102400000")
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdio>
#include <time.h>
#include <cstdlib>
#include <cstring>
#include <complex>
#include <sstream> //isstringstream
#include <iostream>
#include <algorithm>
using namespace std;
//using namespace __gnu_pbds;
typedef long long LL;
typedef pair<int, LL> pp;
#define REP1(i, a, b) for(int i = a; i < b; i++)
#define REP2(i, a, b) for(int i = a; i <= b; i++)
#define REP3(i, a, b) for(int i = a; i >= b; i--)
#define CLR(a, b) memset(a, b, sizeof(a))
#define MP(x, y) make_pair(x,y)
template <class T1, class T2>inline void getmax(T1 &a, T2 b) { if (b>a)a = b; }
template <class T1, class T2>inline void getmin(T1 &a, T2 b) { if (b<a)a = b; }
const int maxn = (1<<21) + 10;
const int maxm = 100010;
const int maxs = 10;
const int maxp = 1e3 + 10;
const int INF = 1e9;
const int UNF = -1e9;
const int mod = 1e9 + 7;
const double PI = acos(-1);
//head
typedef complex <double> Complex;
void rader(Complex *y, int len) {
for(int i = 1, j = len / 2; i < len - 1; i++) {
if(i < j) swap(y[i], y[j]);
int k = len / 2;
while(j >= k) {j -= k; k /= 2;}
if(j < k) j += k;
}
}
void fft(Complex *y, int len, int op) {
rader(y, len);
for(int h = 2; h <= len; h <<= 1) {
double ang = op * 2 * PI / h;
Complex wn(cos(ang), sin(ang));
for(int j = 0; j < len; j += h) {
Complex w(1, 0);
for(int k = j; k < j + h / 2; k++) {
Complex u = y[k];
Complex t = w * y[k + h / 2];
y[k] = u + t;
y[k + h / 2] = u - t;
w = w * wn;
}
}
}
if(op == -1) for(int i = 0; i < len; i++) y[i] /= len;
}
int n, m, k;
Complex x1[maxn], x2[maxn];
bool p[maxn], q[maxn];
void multiply(bool *p, int &n, bool *q, int m){
int len = 1;
while(len <= n + m) len <<= 1;
for(int i = 0; i < len; i++) x1[i] = Complex(i <= n ? p[i] : 0, 0);
for(int i = 0; i < len; i++) x2[i] = Complex(i <= m ? q[i] : 0, 0);
fft(x1, len, 1);
fft(x2, len, 1);
for(int i = 0; i < len; i++) x1[i] = x1[i] * x2[i];
fft(x1, len, -1);
for(int i = 0; i <= n + m; i++) p[i] = x1[i].real() > 0.5;
n += m;
}
int main()
{
scanf("%d%d", &n, &k);
for(int i = 1; i <= n; i++){
int x;
scanf("%d", &x);
q[x] = 1;
}
m = 1000;
n = 0;
p[0] = 1;
while(k)
{
if(k & 1) multiply(p, n, q, m);
if(k > 1) multiply(q, m, q, m);
k >>= 1;
}
for(int i = 1; i <= n; i++) if(p[i]) printf("%d ", i); printf("\n");
return 0;
}