Luogu P3723 [AH2017/HNOI2017]礼物
拆一下式子:
\(\begin{aligned}原式&=\sum\limits_{i=1}^n(x_i-y_i+c)\\ &=\sum\limits_{i=1}^nx_i^2+y_i^2+2x_ic-2y_ic+2c^2-2x_iy_i\\&=nc^2+\sum\limits_{i=1}^nx_i^2+y_i^2+2c(x_i-y_i)-2x_iy_i\end{aligned}\)
那么我们只要令最后一项最大即可。
我们把 \(x\) 数组复制一倍拼到后面,把 \(y\) 数组反转,卷积即可得到 \(x_iy_i\) 的最值。
#include<iostream>
#include<cstdio>
#include<cmath>
#define ll long long
#define R register int
using namespace std;
namespace Luitaryi {
inline int g() { R x=0,f=1;
register char s; while(!isdigit(s=getchar())) f=s=='-'?-1:f;
do x=x*10+(s^48); while(isdigit(s=getchar())); return x*f;
} const int N=270010;
const double PI=acos(-1.0);
int n,m,K,len,mx,p[N];
ll ans=1e9,sa,sb,sa2,sb2;
struct ci {
double x,y;
inline ci operator + (const ci& that) const
{return (ci){x+that.x,y+that.y};}
inline ci operator - (const ci& that) const
{return (ci){x-that.x,y-that.y};}
inline ci operator * (const ci& that) const
{return (ci){x*that.x-y*that.y,x*that.y+y*that.x};}
}a[N],b[N];
inline void fft(ci* a,int op) {
for(R i=0;i<K;++i) if(i<p[i]) swap(a[i],a[p[i]]);
for(R l=1;l<K;l<<=1) {
register ci w1=(ci){cos(PI/l),op*sin(PI/l)},wn,x,y;
for(R len=l<<1,i=0;i<K;i+=len) {
wn=(ci){1,0};
for(R j=0;j<l;++j,wn=wn*w1)
x=a[i+j],y=a[i+j+l]*wn,a[i+j]=x+y,a[i+j+l]=x-y;
}
}
}
inline void main() {
n=g(),m=g();
for(R i=1;i<=n;++i) a[i].x=a[i+n].x=g(),sa2+=a[i].x*a[i].x,sa+=a[i].x;
for(R i=n;i;--i) b[i].x=g(),sb2+=b[i].x*b[i].x,sb+=b[i].x;
K=1,len=0; while(K<=3*n) K<<=1,++len;
for(R i=0;i<K;++i) p[i]=(p[i>>1]>>1)|((i&1)<<(len-1));
fft(a,1),fft(b,1);
for(R i=0;i<K;++i) a[i]=a[i]*b[i];
fft(a,-1);
for(R i=n+1,lim=2*n;i<=lim;++i) a[i].x=(ll)(a[i].x/K+0.5);
for(R i=n+1,lim=2*n;i<=lim;++i) {
for(R j=-m;j<=m;++j)
ans=min(ans,sa2+sb2+2ll*(sa-sb)*j+j*j*n-2*(ll)a[i].x);
} printf("%lld\n",ans);
}
} signed main() {Luitaryi::main(); return 0;}
2020.01.16