bzoj 4827 [Hnoi2017]禮物——FFT
阿新 • • 發佈:2018-11-27
題目:https://www.lydsy.com/JudgeOnline/problem.php?id=4827
式子就是 \sum_{i=0}^{n-1}(a[ i ] - b[ i+k ] + c)^2 。把 b 翻成兩倍後卷積即可。關於 c 的部分是一個二次函式,注意 c 只能是整數!
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #define db double using namespacestd; const int N=5e4+5,M=N*6; const db pi=acos(-1); int n,m,sm,len,ca,cb,r[M]; struct cpl{db x,y;}a[M],b[M],I; cpl operator+ (cpl a,cpl b){return (cpl){a.x+b.x,a.y+b.y};} cpl operator- (cpl a,cpl b){return (cpl){a.x-b.x,a.y-b.y};} cpl operator* (cpl a,cpl b){return (cpl){a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x};}int rdn() { int ret=0;bool fx=1;char ch=getchar(); while(ch>'9'||ch<'0'){if(ch=='-')fx=0;ch=getchar();} while(ch>='0'&&ch<='9') ret=(ret<<3)+(ret<<1)+ch-'0',ch=getchar(); return fx?ret:-ret; } void fft(cpl *a,bool fx) { for(int i=0;i<len;i++) if(i<r[i])swap(a[i],a[r[i]]);for(int R=2;R<=len;R<<=1) { int m=R>>1; cpl Wn=(cpl){ cos(pi/m),fx?-sin(pi/m):sin(pi/m) }; for(int i=0;i<len;i+=R) { cpl w=I; for(int j=0;j<m;j++,w=w*Wn) { cpl tmp=w*a[i+m+j]; a[i+m+j]=a[i+j]-tmp; a[i+j]=a[i+j]+tmp; } } } } int main() { n=rdn();m=rdn(); I.x=1; for(int i=n-1;i>=0;i--) { a[i].x=rdn();sm+=a[i].x*a[i].x;ca+=a[i].x; } for(int i=0;i<n;i++) { b[i].x=b[i+n].x=rdn();sm+=b[i].x*b[i].x;cb+=b[i].x; } int c=floor((db)(cb-ca)/n),tmp=n*c*c+2*(ca-cb)*c; c++; tmp=min(tmp,n*c*c+2*(ca-cb)*c); sm+=tmp; len=1; for(;len<=n*3;len<<=1); for(int i=0;i<len;i++)r[i]=(r[i>>1]>>1)+((i&1)?len>>1:0); fft(a,0); fft(b,0); for(int i=0;i<len;i++)a[i]=a[i]*b[i]; fft(a,1); tmp=0; for(int i=(n<<1)-1;i>=n-1;i--) tmp=max(tmp,int(a[i].x/len+0.5)); sm-=tmp<<1; printf("%d\n",sm); return 0; }