Kattis - polymul2

Input

Standard input begins with an integer T1T≤1, the number of test cases.

Each test case consists of two polynomials. A polynomial is given by an integer 1n1310711≤n≤131071 indicating the degree of the polynomial, followed by a sequence of integers a0,a1,,ana0,a1,…,an, where aiai is the coefficient of xixi in the polynomial. All coefficients will fit in a signed 32-bit integer.

NB! The input and output files for this problem are quite large, which means that you have to be a bit careful about I/O efficiency.

Output

For each test case, output the product of the two polynomials, in the same format as in the input (including the degree). All coefficients in the result will fit in a signed 32-bit integer.

Sample Input 1Sample Output 1
1
2
1 0 5
1
0 -2
3
0 -2 0 -10
思路:如果是普通的多项式乘法,时间复杂度是O(n*n),所以这里要用到快速傅里叶变换(FFT应用于多项式乘法、高精度乘法、优化卷积式等)。

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define maxn (1<<18)
#define pi 3.141592653589793238462643383
using namespace std;

struct complex
{
	double re,im;
	complex(double r=0.0,double i=0.0) {re=r,im=i;}
	void print() {printf("%.lf ",re);}
} a[maxn*2],b[maxn*2],W[2][maxn*2];

int N,na,nb,rev[maxn*2];

complex operator +(const complex&A,const complex&B) {return complex(A.re+B.re,A.im+B.im);}
complex operator -(const complex&A,const complex&B) {return complex(A.re-B.re,A.im-B.im);}
complex operator *(const complex&A,const complex&B) {return complex(A.re*B.re-A.im*B.im,A.re*B.im+A.im*B.re);}

void FFT(complex*a,int f)
{
	complex x,y;
	for (int i=0; i<N; i++) if (i<rev[i]) swap(a[i],a[rev[i]]);
	for (int i=1; i<N; i<<=1)
		for (int j=0,t=N/(i<<1); j<N; j+=i<<1)
			for (int k=0,l=0; k<i; k++,l+=t) x=W[f][l]*a[j+k+i],y=a[j+k],a[j+k]=y+x,a[j+k+i]=y-x;
	if (f) for (int i=0; i<N; i++) a[i].re/=N;
}

void work()
{
	for (int i=0; i<N; i++)
	{
		int x=i,y=0;
		for (int k=1; k<N; x>>=1,k<<=1) (y<<=1)|=x&1;
		rev[i]=y;
	}
	for (int i=0; i<N; i++) W[0][i]=W[1][i]=complex(cos(2*pi*i/N),sin(2*pi*i/N)),W[1][i].im=-W[0][i].im;
}

void init()
{   memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
	scanf("%d",&na); na++;for (int i=0; i<na; i++) scanf("%lf",&a[i].re);
	scanf("%d",&nb); nb++;for (int i=0; i<nb; i++) scanf("%lf",&b[i].re);
	for (N=1; N<na||N<nb; N<<=1); N<<=1;
}

void doit()
{
	work(),FFT(a,0),FFT(b,0);
	for (int i=0; i<N; i++) a[i]=a[i]*b[i];
	FFT(a,1);
	printf("%d\n",na+nb-2); 
	for (int i=0; i<na+nb-1; i++) a[i].print();
	printf("\n");
}

int main()
{
int t; scanf("%d",&t);   
while(t--)
    {
	init();
	doit();
    }
}

posted @ 2018-03-22 16:19  The-Pines-of-Star  阅读(146)  评论(0编辑  收藏  举报