1. 程式人生 > >bzoj 4827 [Hnoi2017] 禮物 —— FFT

bzoj 4827 [Hnoi2017] 禮物 —— FFT

題目:https://www.lydsy.com/JudgeOnline/problem.php?id=4827

首先,旋轉對應,可以把 b 序列擴充套件成2倍,則 a 序列對應到的還是一段區間;

再把 a 序列翻轉,就成了卷積的形式;

如果 b 從 k 位置斷開,則值為 ∑(0<=i<=n) (a[n-i] - b[k+i] + c)2

拆開求即可,注意 c 的取值是個二次函式,最低點左右兩個整數值都要試一下;

如果一開始把 n-- 了,別忘了計算時帶入 n+1 !

程式碼如下:

#include<iostream>
#include<cstdio>
#include
<cstring> #include<algorithm> #include<cmath> using namespace std; typedef double db; int const xn=(1<<18); db const Pi=acos(-1.0); int n,m,lim,rev[xn],af,bf,as,bs; struct com{db x,y;}a[xn],b[xn]; com operator + (com a,com b){return (com){a.x+b.x,a.y+b.y};} com operator - (com a,com b){return
(com){a.x-b.x,a.y-b.y};} com operator * (com a,com b){return (com){a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x};} int rd() { int ret=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=0; ch=getchar();} while(ch>='0'&&ch<='9')ret=(ret<<3)+(ret<<1)+ch-'0',ch=getchar();
return f?ret:-ret; } void fft(com *a,int tp) { for(int i=0;i<lim;i++) if(i<rev[i])swap(a[i],a[rev[i]]); for(int mid=1;mid<lim;mid<<=1) { com wn=(com){cos(Pi/mid),tp*sin(Pi/mid)}; for(int j=0,len=(mid<<1);j<lim;j+=len) { com w=(com){1,0}; for(int k=0;k<mid;k++,w=w*wn) { com x=a[j+k],y=w*a[j+mid+k]; a[j+k]=x+y; a[j+mid+k]=x-y; } } } } int main() { n=rd(); m=rd(); n--; for(int i=0,x;i<=n;i++)x=rd(),as+=x,af+=x*x,a[n-i].x=x;// for(int i=0,x;i<=n;i++)x=rd(),bs+=x,bf+=x*x,b[i].x=b[i+n+1].x=x; lim=1; int l=0; while(lim<=n+2*n+1)lim<<=1,l++; for(int i=0;i<lim;i++) rev[i]=((rev[i>>1]>>1)|((i&1)<<(l-1))); fft(a,1); fft(b,1); for(int i=0;i<lim;i++)a[i]=a[i]*b[i]; fft(a,-1); for(int i=0;i<=lim;i++)a[i].x=(int)(a[i].x/lim+0.5); int ans=1e9,c,t; c=floor(1.0*(bs-as)/(n+1)); t=(n+1)*c*c+2*(as-bs)*c;//n--! c++; t=min(t,(n+1)*c*c+2*(as-bs)*c); t=af+bf+t; for(int k=0;k<=n;k++)ans=min(ans,t-2*(int)a[n+k].x); printf("%d\n",ans); return 0; }