大数相乘(hdu 1402)

------------------题目链接---------------------

题目没啥说的,两个数相乘,fft,一发模板就AC,kuangbin模板大法好,不懂原理的小白也能体验AC。

个人学的比较菜,不懂原理,把学习资料整合一下。存一下模板。


大佬的讲解 另一个讲解

#include <cstdio>
#include <cstring>
#include <cctype>
#include <cmath>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <complex>
using namespace std;
typedef long long LL;
const int INF=2e9+1e8;

const int MOD=1e9+7;
const double eps=0.0000000001;
void fre()
{
    freopen("test.in","r",stdin);
    freopen("test.out","w",stdout);
}
#define MSET(a,b) memset(a,b,sizeof(a))


const double PI=acos(-1.0);
typedef complex<double> Complex;
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].real(y[i].real()/len);
    }
}
/******************************************************/

const int MAXN = 200010;
Complex x1[MAXN], x2[MAXN];
char str1[MAXN / 2], str2[MAXN / 2];
int sum[MAXN];
int main()
{
    while (scanf("%s%s", str1, str2) == 2)
    {
        int len1 = strlen(str1);
        int len2 = strlen(str2);
        int len = 1;
        while (len < len1 * 2 || len < len2 * 2) //2^n<
            len <<= 1;
        for (int i = 0; i < len1; i++)
            x1[i] = Complex(str1[len1 - 1 - i] - '0', 0);
        for (int i = len1; i < len; i++)
            x1[i] = Complex(0, 0);
        for (int i = 0; i < len2; i++)
            x2[i] = Complex(str2[len2 - 1 - i] - '0', 0);
        for (int i = len2; i < len; i++)
            x2[i] = Complex(0, 0);
        //求DFT
        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 = 0; i < len; i++)
            sum[i] = (int)(x1[i].real() + 0.5);
        for (int i = 0; i < len; i++)
        {
            sum[i + 1] += sum[i] / 10;
            sum[i] %= 10;
        }
        len = len1 + len2 - 1;
        while (sum[len] <= 0 && len > 0)
            len--;
        for (int i = len; i >= 0; i--)
            printf("%c", sum[i] + '0');
        printf("\n");
    }
    return 0;
}

posted @ 2017-08-04 16:52  Code-dream  阅读(356)  评论(0编辑  收藏  举报