首先知道旋转的一般套路就是开两倍。
然后此时发现可以把
∑ni=1(ai−bi)2
∑
i
=
1
n
(
a
i
−
b
i
)
2
化作
∑ni=1a2i+∑ni=1b2i−2∗∑ni=1ai∗bi
∑
i
=
1
n
a
i
2
+
∑
i
=
1
n
b
i
2
−
2
∗
∑
i
=
1
n
a
i
∗
b
i
发现前面两个能直接预处理出来,后面一个要
O(n)
O
(
n
)
处理出来
因为要枚举所有位置,那么就是
O(n2)
O
(
n
2
)
显然不行,考虑优化…
显然能想到
fft
f
f
t
,那么直接把b数组倒过来就是
∑ni=1a2i+∑ni=1b2i−2∗∑ni=1∑nj=1ai−j+1∗bj
∑
i
=
1
n
a
i
2
+
∑
i
=
1
n
b
i
2
−
2
∗
∑
i
=
1
n
∑
j
=
1
n
a
i
−
j
+
1
∗
b
j
发现这是个很显然的卷积直接
fft
f
f
t
即可复杂度
O(nlogn)
O
(
n
log
n
)
但是发现题目还有一个要求,每个环可以增加一个值
C
C
如果暴力找的话复杂度
并不可以,然后我猜最优位置肯定一直在某一个点,然后发现是对的直接交了
(大胆猜想,不用证明
QAQ
Q
A
Q
)
c++代码如下
#include<bits/stdc++.h>
#define PI acos(-1)
#define rep(i,x,y) for(register int i = x; i <= y; ++ i)
#define repd(i,x,y) for(register int i = x; i >= y; -- i)
using namespace std;
typedef long long ll;
template<typename T>inline void read(T&x)
{
char c;int sign = 1;x = 0;
do { c = getchar(); if(c == '-') sign = -1; }while(!isdigit(c));
do { x = x *10 + c - '0'; c = getchar(); }while(isdigit(c));
x *= sign;
}
struct cpx
{
double x,y;
cpx(){}
cpx(double a,double b) { x = a,y = b; }
cpx operator * (cpx a) { return cpx(x * a.x - y * a.y,x * a.y + y * a.x); }
cpx operator *= (cpx a) { *this = *this*a; }
cpx operator + (cpx a) { return cpx(x + a.x, y + a.y); }
cpx operator - (cpx a) { return cpx(x - a.x, y - a.y); }
};
const int N = 3e5+50;
int n,m,P,L,len,e[N],R[N];
cpx a[N],b[N],c[N],d[N];
inline void fft(cpx*a,int f)
{
rep(i,0,n - 1) if(i < R[i]) swap(a[i],a[R[i]]);
for(register int i = 1 ; i < n ; i <<= 1)
{
cpx nw = cpx(cos(PI/i),f*sin(PI/i));
for(register int j = 0 ; j < n ; j += (i << 1))
{
cpx w = cpx(1,0);
for(register int k = 0; k < i ; ++k, w *= nw)
{
cpx x = a[j + k],y = w * a[i + j + k];
a[j + k] = x + y; a[i + j + k] = x - y;
}
}
}
if(f == -1) rep(i,0,n - 1) a[i].x /= n;
}
inline ll solve(bool e,int C)
{
ll ans = 1e18,sum = 0;
rep(i,0,n) a[i].x = b[i].x = a[i].y = b[i].y = 0;
rep(i,0,len) a[i].x = c[i].x + e*C;
rep(i,0,P) b[i].x = d[i].x + (e^1)*C;
rep(i,0,P) sum += a[i].x*a[i].x + b[i].x*b[i].x;
fft(a,1) , fft(b,1);
rep(i,0,n - 1) a[i] *= b[i];
fft(a,-1);
int pos;
rep(i,P,len)
if(ans >= sum - 2*(ll)(a[i].x+0.5))
ans = min(ans,sum - 2*(ll)(a[i].x+0.5)),
pos = i;
return pos;
}
int main()
{
read(n); read(m);--n;
rep(i,0,n) read(e[i]), c[i].x = e[i];
rep(i,0,n) read(e[i]), d[n-i].x = e[i];
P = n; len = n+1+(n<<1);ll ans = 1e18;
rep(i,0,n) c[n+1+i].x = c[i].x;
for(n = 1;n <= len; n <<= 1) ++L;len = P + P + 1;
rep(i,0,n-1) R[i] = (R[i>>1]>>1)|((i&1)<<(L-1));
int pos = solve(0,0);
rep(i,0,m)
{
ll ans2 = 0;
repd(j,pos,pos-P) a[j].x = c[j].x + i;
rep(j,0,P) ans2 += abs(a[pos-j].x - d[j].x) * abs(a[pos-j].x - d[j].x);
ans = min(ans2,ans);
}
rep(i,0,m)
{
ll ans2 = 0;
rep(j,0,P) b[j].x = d[j].x + i;
rep(j,0,P) ans2 += abs(c[pos-j].x - b[j].x) * abs(c[pos-j].x - b[j].x);
ans = min(ans2,ans);
}
cout << ans << endl;
return 0;
}