题解
要求
min{∑i(xi+c−yi)2}
展开
∑i(xi−yi)2+2(xi−yi)c+c2
,
所以
c=−sumx−sumyn
去掉确定的项
min{∑ix2i+y2i−2xiyi}
。
最后要求
max{∑ixiyi}
,将
x
倍长,然后将
时间复杂度: O(nlogn)
SRC
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std ;
#define N 200000 + 10
typedef long long ll ;
typedef long double LD ;
const LD pi = acos(-1) , eps = 0.5 ;
struct Z {
LD x , y ;
Z ( LD X = 0 , LD Y = 0 ) { x = X , y = Y ; }
} A[N] , B[N] , tmp[N] ;
int a[N] , b[N] ;
int n , m , len ;
ll SumX , SumY ;
ll SumX2 , SumY2 ;
ll ans ;
Z operator + ( Z a , Z b ) { return Z( a.x + b.x , a.y + b.y ) ; }
Z operator - ( Z a , Z b ) { return Z( a.x - b.x , a.y - b.y ) ; }
Z operator * ( Z a , Z b ) { return Z( a.x * b.x - a.y * b.y , a.x * b.y + a.y * b.x ) ; }
int sqr( int x ) { return x * x ; }
void DFT( Z *a , int sig ) {
for (int i = 0 ; i < len ; i ++ ) {
int p = 0 , j = i ;
for (int k = 1 ; k < len ; k <<= 1 , j >>= 1 ) p = (p << 1) + (j & 1) ;
tmp[p] = a[i] ;
}
for (int m = 2 ; m <= len ; m <<= 1 ) {
int half = m / 2 ;
for (int i = 0 ; i < half ; i ++ ) {
Z w = Z( cos( sig * i * pi / half ) , sin( sig * i * pi / half ) ) ;
for (int j = i ; j < len ; j += m ) {
Z u = tmp[j] ;
Z v = tmp[j+half] * w ;
tmp[j] = u + v ;
tmp[j+half] = u - v ;
}
}
}
for (int i = 0 ; i < len ; i ++ ) a[i] = tmp[i] ;
}
int Calc() {
ll ret = 0 ;
for ( len = 1 ; len <= 2 * n ; len += len ) ;
for (int i = 0 ; i < 2 * n ; i ++ ) A[i] = Z( a[i+1] , 0 ) ;
for (int i = 0 ; i < n ; i ++ ) B[i] = Z( b[n-i] , 0 ) ;
DFT( A , 1 ) ;
DFT( B , 1 ) ;
for (int i = 0 ; i < len ; i ++ ) A[i] = A[i] * B[i] ;
DFT( A , -1 ) ;
for (int i = n - 1 ; i < 2 * n ; i ++ ) ret = max( ret , (ll)(A[i].x + eps) / len ) ;
return ret ;
}
int main() {
freopen( "gift.in" , "r" , stdin ) ;
freopen( "gift.out" , "w" , stdout ) ;
scanf( "%d%d" , &n , &m ) ;
for (int i = 1 ; i <= n ; i ++ ) {
scanf( "%d" , &a[i] ) ;
SumX += a[i] ;
SumX2 += sqr(a[i]) ;
}
for (int i = 1 ; i <= n ; i ++ ) {
scanf( "%d" , &b[i] ) ;
SumY += b[i] ;
SumY2 += sqr(b[i]) ;
}
if ( SumX > SumY ) swap( a , b ) , swap( SumX , SumY ) , swap( SumX2 , SumY2 ) ;
for (int i = 1 ; i <= n ; i ++ ) a[n+i] = a[i] ;
ll del = round((double)(SumY - SumX) / n) ;
ans = SumX2 + SumY2 + 2ll * del * (SumX - SumY) + n * sqr(del) ;
ans -= 2ll * Calc() ;
printf( "%d\n" , ans ) ;
return 0 ;
}
以上.