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;
}

 

posted @ 2018-11-27 09:34  Zinn  阅读(125)  评论(0编辑  收藏  举报