• gym101002K. Inversions (FFT)


    题意:给定一个仅含有AB的字母串
       如果i有一个B j有一个A 且j>i 会对F(j-i)产生贡献 求出所有发Fi
    题解:好像是很裸的FFT B的分布可以看作一个多项式 同理A也可以
       然后把B的位置翻转一下 就搞成了卷积的形式

       设f为B的位置函数 如果si = B, fi = 1否则fi = 0. 设g为A的位置函数

    [F(i)= sum_{j = 1}^{n - i + 1} f(j)*g(i+j) ]

    [把f翻转一下 ]

    [F(i)= sum_{j = 1}^{n - i + 1} f(n - j + 1)*g(i+j) = F(n + 1 + i) ]

    #include <bits/stdc++.h>
    using namespace std;
    const double PI = acos(-1.0);
    
    struct Complex {
        double x, y;
        Complex(double _x = 0.0, double _y = 0.0) {
            x = _x;
            y = _y;
        }
        Complex operator + (const Complex &b) const {
            return Complex(x + b.x, y + b.y);
        }
        Complex operator - (const Complex &b) const {
            return Complex(x - b.x, y - b.y);
        }
        Complex operator * (const Complex &b) const {
            return Complex(x * b.x - y * b.y, x * b.y + y * b.x);
        }
    };
    
    void change(Complex y[], int len) {
        int i, j, k;
        for(i = 1, j = len / 2; i < len - 1; i++) {
            if(i < j) swap(y[i], y[j]);
            k = len / 2;
            while(j >= k) {
                j -= k;
                k /= 2;
            }
            if(j < k) j += k;
        }
    }
    
    void fft(Complex y[], int len, int on) {
        change(y, len);
        for(int h = 2; h <= len; h <<= 1) {
            Complex wn(cos(-on * 2 * PI / h), sin(-on * 2 * PI / h));
            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(on == -1)
            for(int i = 0; i < len; i++)
                y[i].x /= len;
    }
    
    char s[1000005];
    Complex x1[4000005], x2[4000005];
    int main() {
        scanf("%s", s + 1);
        int n = strlen(s + 1);
        for(int i = 1; i <= n; i++) {
            if(s[i] == 'A') {
                x1[i] = Complex(1.0, 0);
                x2[n - i + 1] = Complex(0, 0);
            } else if(s[i] == 'B') {
                x1[i] = Complex(0, 0);
                x2[n - i + 1] = Complex(1.0, 0);
            }
        }
        int len = 1;
        while(len <= n + n) len <<= 1;
        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 = n + 2; i <= n + n; i++) printf("%d
    ", (int)(x1[i].x + 0.5));
        return 0;
    }
    
    
  • 相关阅读:
    python模板引擎Cheetah的安装
    cocos2d 动作
    【leetcode】合并两个有序数组
    【leetcode】合并二叉树
    【leetcode】合并两个有序链表
    【leetcode】链表的中间结点
    【leetcode】使用最小花费爬楼梯
    【leetcode】栈的最小值
    【leetcode】最小绝对差
    【leetcode】玩筹码
  • 原文地址:https://www.cnblogs.com/lwqq3/p/11349099.html
Copyright © 2020-2023  润新知