bzoj4827

FFT+数学

先开始觉得枚举c就行了,不过我naive了

事实上c是确定的,通过化简式子可以得出一个二次函数,那么c就可以解出来了。

然后把a翻转,fft一下就行了

难得的良心题

#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
const double pi = acos(-1);
int n, len, ans, suma, sumb, mx = -1e9, m;
struct data {
    double x, y;
    data() {}
    data(double _x, double _y) : x(_x), y(_y) {}
    data friend operator - (const data &a, const data &b) {
        return data(a.x - b.x, a.y - b.y);
    }
    data friend operator + (const data &a, const data &b) {
        return data(a.x + b.x, a.y + b.y);
    }
    data friend operator * (const data &a, const data &b) {
        return data(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
    }
} a[N], b[N];
void fft(data *a, int len, int f) {
    int n = 1 << len;
    for(int i = 0; i < n; ++i) {
        int t = 0;
        for(int j = 0; j < len; ++j) {
            if(i & (1 << j)) {
                t |= 1 << (len - j - 1);
            }
        }
        if(i < t) {
            swap(a[i], a[t]);
        }
    }
    for(int l = 2; l <= n; l <<= 1) {
        int m = l >> 1;
        data w = data(cos(pi / m), f * sin(pi / m));
        for(int i = 0; i < n; i += l) {
            data t = data(1, 0);
            for(int k = 0; k < m; ++k, t = t * w) {
                data x = a[k + i], y = t * a[i + k + m];
                a[k + i] = x + y;
                a[i + m + k] = x - y;
            }
        }
    }
}
int main() {
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= n; ++i) {
        scanf("%lf", &a[i].x);
        suma += a[i].x;
    }
    for(int i = 1; i <= n; ++i) {
        scanf("%lf", &b[i].x);
        b[i + n].x = b[i].x;
        sumb += b[i].x;
    }
    int c = floor((double)(sumb - suma) / n + 0.5);
    for(int i = 1; i <= n; ++i) {
        a[i].x += c;
        ans += a[i].x * a[i].x + b[i].x * b[i].x;
    }
    reverse(b + 1, b + 2 * n + 1);
    for(; 1 << len <= 2 * n; ++len);
    fft(a, len, 1);
    fft(b, len, 1);
    for(int i = 0; i < 1 << len; ++i) {
        a[i] = a[i] * b[i];
    }
    fft(a, len, -1);
    for(int i = n + 1; i <= 2 * n + 1; ++i) {
        a[i].x /= (1 << len);
        mx = max(mx, (int)(a[i].x + 0.1));
    }
    printf("%d\n", ans - 2 * mx);
    return 0;
}
View Code

 

posted @ 2018-02-10 18:37  19992147  阅读(111)  评论(0编辑  收藏  举报