bzoj 2179 FFT快速傅立叶

题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2179

注意进位的时候最好先把所有的都变成 int 再普通进位。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define db double
using namespace std;
const int N=6e4+5,M=N<<2; const db pi=acos(-1);
int n,len,r[M];
struct cpl{db x,y;int c;}a[M],b[M],I;
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};}
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?-sin(pi/m):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()
{
  scanf("%d",&n); n--; I.x=1;
  for(int i=n,d;i>=0;i--)
    {
      scanf("%1d",&d); a[i].x=d;
    }
  for(int i=n,d;i>=0;i--)
    {
      scanf("%1d",&d); b[i].x=d;
    }
  len=1;
  for(;len<=(n<<1);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); int t=n<<1;
  for(int i=0;i<=t;i++)
    a[i].c=int(a[i].x/len+0.5);
  for(int i=0;i<t;i++)//<
    {
      a[i+1].c+=a[i].c/10; a[i].c%=10;
    }
  while(!a[t].c&&t>=0)t--;
  if(t<0)putchar('0');
  for(int i=t;i>=0;i--)
    printf("%d",a[i].c);
  puts("");
  return 0;
}

 

posted on 2018-11-26 15:12  Narh  阅读(101)  评论(0编辑  收藏  举报

导航