Description
n items, the value of the first item is ai. Each item has unlimited quantity. Take k items and ask about the possible value and value.
Input
The first line contains two integers n,k, and then input n integers ai to indicate the value of item i (1 < n,k,ai < 1000)
Output
Output All Possible Values of k Items and
Sample Input
3 2
1 2 3
Sample Output
2 3 4 5 6
Solution
Let f(x)=i=1nxai be the generating function of the value of an item. Let g(x)=f k(x) be the generating function of the sum of the values of K items (considering the order). Fast power set FFT is enough. Note that all the non-zero values can be saved to 1 in the convolution process because only a certain value and existence need to be asked.
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=100001;
#define maxfft 1048576+5
const double pi=acos(-1.0);
struct cp
{
double a,b;
cp operator +(const cp &o)const {return (cp){a+o.a,b+o.b};}
cp operator -(const cp &o)const {return (cp){a-o.a,b-o.b};}
cp operator *(const cp &o)const {return (cp){a*o.a-b*o.b,b*o.a+a*o.b};}
cp operator *(const double &o)const {return (cp){a*o,b*o};}
cp operator !() const{return (cp){a,-b};}
}w[maxfft];
int pos[maxfft];
void fft_init(int len)
{
int j=0;
while((1<<j)<len)j++;
j--;
for(int i=0;i<len;i++)
pos[i]=pos[i>>1]>>1|((i&1)<<j);
}
void fft(cp *x,int len,int sta)
{
for(int i=0;i<len;i++)
if(i<pos[i])swap(x[i],x[pos[i]]);
w[0]=(cp){1,0};
for(unsigned i=2;i<=len;i<<=1)
{
cp g=(cp){cos(2*pi/i),sin(2*pi/i)*sta};
for(int j=i>>1;j>=0;j-=2)w[j]=w[j>>1];
for(int j=1;j<i>>1;j+=2)w[j]=w[j-1]*g;
for(int j=0;j<len;j+=i)
{
cp *a=x+j,*b=a+(i>>1);
for(int l=0;l<i>>1;l++)
{
cp o=b[l]*w[l];
b[l]=a[l]-o;
a[l]=a[l]+o;
}
}
}
if(sta==-1)for(int i=0;i<len;i++)x[i].a/=len,x[i].b/=len;
}
cp x[maxfft],y[maxfft],z[maxfft];
void FFT(int *a,int *b,int n,int m,int *c)
{
int len=1;
while(len<(n+m)>>1)len<<=1;
fft_init(len);
for(int i=n/2;i<len;i++)x[i].a=x[i].b=0;
for(int i=m/2;i<len;i++)y[i].a=y[i].b=0;
for(int i=0;i<n;i++)(i&1?x[i>>1].b:x[i>>1].a)=a[i];
for(int i=0;i<m;i++)(i&1?y[i>>1].b:y[i>>1].a)=b[i];
fft(x,len,1),fft(y,len,1);
for(int i=0;i<len/2;i++)
{
int j=len-1&len-i;
z[i]=x[i]*y[i]-(x[i]-!x[j])*(y[i]-!y[j])*(w[i]+(cp){1,0})*0.25;
}
for(int i=len/2;i<len;i++)
{
int j=len-1&len-i;
z[i]=x[i]*y[i]-(x[i]-!x[j])*(y[i]-!y[j])*((cp){1,0}-w[i^len>>1])*0.25;
}
fft(z,len,-1);
for(int i=0;i<n+m;i++)
if(i&1)c[i]=(int)(z[i>>1].b+0.5)?1:0;
else c[i]=(int)(z[i>>1].a+0.5)?1:0;
}
int n,k,f[maxfft],g[maxfft];
void Pow(int *f,int len,int k,int *g)
{
g[0]=1;
while(k)
{
if(k&1)FFT(g,f,len,len,g);
FFT(f,f,len,len,f);
k>>=1;
len<<=1;
}
}
int main()
{
int n,k,a;
scanf("%d%d",&n,&k);
while(n--)
{
scanf("%d",&a);
f[a]=1;
}
Pow(f,1024,k,g);
for(int i=1;i<=1000000;i++)
if(g[i])printf("%d ",i);
printf("\n");
return 0;
}