题目链接:见这里
题意:给定一个 A 数组和 B 数组,求给定的这个函数值的最小值。
解题思路:

想起去年打这个网络赛的时候连FFT是什么都不知道,还是集训队一个大佬在做,就是因为精度问题,卡到最后也没有过去,今年有幸和他做队友打最后一个赛季了,加油。我会证明自己的。

代码如下:

#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1);
const int maxn = 300000;
typedef long long LL;
typedef complex <double> Complex;

void rader(Complex *y, int len) {
    for(int i = 1, j = len / 2; i < len - 1; i++) {
        if(i < j) swap(y[i], y[j]);
        int k = len / 2;
        while(j >= k) {j -= k; k /= 2;}
        if(j < k) j += k;
    }
}
void fft(Complex *y, int len, int op) {
    rader(y, len);
    for(int h = 2; h <= len; h <<= 1) {
        double ang = op * 2 * PI / h;
        Complex wn(cos(ang), sin(ang));
        for(int j = 0; j < len; j += h) {
            Complex w(1, 0);
            for(int k = j; k < j + h / 2; k++) {
                Complex u = y[k];
                Complex t = w * y[k + h / 2];
                y[k] = u + t;
                y[k + h / 2] = u - t;
                w = w * wn;
            }
        }
    }
    if(op == -1) for(int i = 0; i < len; i++) y[i] /= len;
}

Complex x1[maxn], x2[maxn];
LL a[maxn], b[maxn]; //原数组
LL num[maxn]; //FFT结果
int n;
LL suma, sumb;

int main()
{
    int T;
    scanf("%d", &T);
    while(T--){
        suma = 0;
        sumb = 0;
        memset(num, 0, sizeof(num));
        memset(x1, 0, sizeof(x1));
        memset(x2, 0, sizeof(x2));
        scanf("%d", &n);
        for(int i = 0; i < n; i++){
            scanf("%lld", &a[i]);
            suma += 1LL*a[i]*a[i];
        }
        for(int i = 0; i < n; i++){
            scanf("%lld", &b[i]);
            sumb += 1LL*b[i]*b[i];
        }
        int len = 1;
        while(len < 2 * n) len <<= 1;
        for(int i = 0; i < n; i++) x1[i] = Complex(a[i], 0);
        for(int i = n; i < len; i++) x1[i] = Complex(0, 0);
        for(int i = 0; i < n; i++) x2[i] = Complex(b[n-i-1], 0);
        for(int i = n; i < len; i++) x2[i] = Complex(0, 0);
        fft(x1, len, 1);
        fft(x2, len, 1);
        for(int i = 0; i < len; i++) x1[i] = x1[i] * x2[i];
        fft(x1, len, -1);
        for(int i = 0; i < len; i++) num[i] = (LL) (x1[i].real() + 0.5);
        //find max
        LL ans = num[n - 1];
        int k = 0;
        for(int i = 0; i < n - 2; i++){
            if(ans < num[i] + num[i+n]){
                ans = num[i] + num[i+n];
                k = n - 1 - i;
            }
        }
        //again cal
        ans = 0;
        for(int i = 0; i < n; i++){
            ans += a[i] * b[(i+k)%n];
        }
        ans = suma + sumb - 2 * ans;
        printf("%lld\n", ans);
    }
    return 0;
}