bzoj2962

线段树+卷积

这个东西直接算不太好,但是合并两段结果却很方便,假设c[i]表示选i个数乘积的和,那么$a[i]=\sum_{j=0}^{i}{b[j]*c[i-j]}$

线段树维护即可

#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:42  19992147  阅读(82)  评论(0编辑  收藏  举报