zoukankan      html  css  js  c++  java
  • 洛谷 3803 【模板】多项式乘法(FFT)

    题目:https://www.luogu.org/problemnew/show/P3803

    第一道FFT!

    https://www.cnblogs.com/zwfymqz/p/8244902.html

    http://www.cnblogs.com/RabbitHu/p/FFT.html

    就是把系数转化为2*n个点值,点值相乘一下,再转化回2*n个系数的过程。

    转化为点值的过程就是倍增一样,第一步是w_{1,0},也就是说x都是1,所以一开始2*n个位置上的点值都是原来的系数;然后变成两个一组取w_{2,0},w_{2,1}的点值,最后变成2*n个分别取w_{2*n,0},w_{2*n,1},......,w_{2*n,2*n-1}的点值。过程就是DFT,证明可见上面博客。

    从点值转化回系数的方法和DFT差不多,似乎只要把 x 都变成倒数、做一边刚才的就行。变成倒数的方法就是那个Wn方向变成负的,这样 x^k 就是倒着转的,上面那个角标就一直是和原来相反的了。

    最后算答案的时候似乎直接把虚数的部分舍弃了。

    对于iDFT的证明还有点不明白。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<cmath>
    #define db double
    using namespace std;
    const int N=1e6+5;const db pi=acos(-1.0);
    int n,m,len,r[N<<2];//<<2! for (n+m)<<1
    struct cpl{
      db x,y;
    }I,a[N<<2],b[N<<2];
    cpl operator+ (cpl a,cpl b){return (cpl){a.x+b.x,a.y+b.y};}
    cpl operator- (cpl a,cpl b){return (cpl){a.x-b.x,a.y-b.y};}
    cpl operator* (cpl a,cpl b){return (cpl){a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x};}
    int rdn()
    {
      int ret=0;bool fx=1;char ch=getchar();
      while(ch>'9'||ch<'0'){if(ch=='-')fx=0;ch=getchar();}
      while(ch>='0'&&ch<='9') ret=(ret<<3)+(ret<<1)+ch-'0',ch=getchar();
      return fx?ret:-ret;
    }
    void fft(cpl *a,bool fx)
    {
      for(int i=0;i<len;i++)
        if(i<r[i])swap(a[i],a[r[i]]);
      for(int R=2;R<=len;R<<=1)//<=
        {
          int m=R>>1;
          cpl Wn=(cpl){ cos(pi/m),(fx?-1:1)*sin(pi/m) };
          for(int i=0;i<len;i+=R)
        {
          cpl w=I;
          for(int j=0;j<m;j++,w=w*Wn)
            {
              cpl tmp=w*a[i+m+j];
              a[i+m+j]=a[i+j]-tmp;
              a[i+j]=a[i+j]+tmp;
            }
        }
        }
    }
    int main()
    {
      n=rdn(); m=rdn(); I.x=1; I.y=0;
      for(int i=0;i<=n;i++)a[i].x=rdn();
      for(int i=0;i<=m;i++)b[i].x=rdn();
      len=1;
      while(len<=n+m)len<<=1;//<=
      for(int i=0;i<len;i++)
        r[i]=(r[i>>1]>>1)+((i&1)?len>>1:0);
      fft(a,0);  fft(b,0);
      for(int i=0;i<len;i++)
        a[i]=a[i]*b[i];
      fft(a,1);
      for(int i=0;i<=n+m;i++)
        printf("%d ",int(a[i].x/len+0.5));puts("");
      return 0;
    }
  • 相关阅读:
    Python中的分支条件结构
    Python中常用的数据类型转换
    Python中的运算符
    Python中的输入和输出
    信息收集之zoomeye
    信息收集之censys
    linux权限管理
    linux软件安装管理
    Linux网络管理
    磁盘管理与用户管理
  • 原文地址:https://www.cnblogs.com/Narh/p/10019574.html
Copyright © 2011-2022 走看看