【HDU】1402 A * B Problem Plus 【FFT】

传送门:【HDU】1402 A * B Problem Plus

题目分析:

这就是大数乘法题,问两个大数相乘的结果,由于 O(n2) 的算法复杂度太大,所以我们用FFT来优化他。关于FFT网上资料很多,我就不多说啦。

这是我做的第一道FFT,FFT是看算法导论学来的,感觉算导讲的很不错,简单易懂~

my code:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std ;

typedef long long LL ;

#define clr( a , x ) memset ( a , x , sizeof a )
#define cpy( a , x ) memcpy ( a , x , sizeof a )

const int MAXN = 200005 ;
const double pi = acos ( -1.0 ) ;

struct Complex {
    double r , i ;
    Complex () {}
    Complex ( double r , double i ) : r ( r ) , i ( i ) {}
    Complex operator + ( const Complex& t ) const {
        return Complex ( r + t.r , i + t.i ) ;
    }
    Complex operator - ( const Complex& t ) const {
        return Complex ( r - t.r , i - t.i ) ;
    }
    Complex operator * ( const Complex& t ) const {
        return Complex ( r * t.r - i * t.i , r * t.i + i * t.r ) ;
    }
} ;

void FFT ( Complex y[] , int n , int rev ) {
    for ( int i = 1 , j , k , t ; i < n ; ++ i ) {
        for ( j = 0 , k = n >> 1 , t = i ; k ; k >>= 1 , t >>= 1 ) j = j << 1 | t & 1 ;
        if ( i < j ) swap ( y[i] , y[j] ) ;
    }
    for ( int s = 2 , ds = 1 ; s <= n ; ds = s , s <<= 1 ) {
        Complex wn = Complex ( cos ( rev * 2 * pi / s ) , sin ( rev * 2 * pi / s ) ) , w = Complex ( 1 , 0 ) , t ;
        for ( int k = 0 ; k < ds ; ++ k , w = w * wn ) {
            for ( int i = k ; i < n ; i += s ) {
                y[i + ds] = y[i] - ( t = w * y[i + ds] ) ;
                y[i] = y[i] + t ;
            }
        }
    }
    if ( rev == -1 ) for ( int i = 0 ; i < n ; ++ i ) y[i].r /= n ;
}

char s1[MAXN] , s2[MAXN] ;
Complex x1[MAXN] , x2[MAXN] ;
int num[MAXN] ;

void solve () {
    int n1 = strlen ( s1 ) ;
    int n2 = strlen ( s2 ) ;
    int n = 1 ;
    while ( n < n1 + n2 ) n <<= 1 ;
    for ( int i = 0 ; i < n1 ; ++ i ) x1[i] = Complex ( s1[n1 - i - 1] - '0' , 0 ) ;
    for ( int i = n1 ; i < n ; ++ i ) x1[i] = Complex ( 0 , 0 ) ;
    for ( int i = 0 ; i < n2 ; ++ i ) x2[i] = Complex ( s2[n2 - i - 1] - '0' , 0 ) ;
    for ( int i = n2 ; i < n ; ++ i ) x2[i] = Complex ( 0 , 0 ) ;
    FFT ( x1 , n , 1 ) ;
    FFT ( x2 , n , 1 ) ;
    for ( int i = 0 ; i < n ; ++ i ) x1[i] = x1[i] * x2[i] ;
    FFT ( x1 , n , -1 ) ;
    int t = 0 ;
    for ( int i = 0 ; i < n ; ++ i , t /= 10 ) {
        t += ( int ) ( x1[i].r + 0.1 ) ;
        num[i] = t % 10 ;
    }
    for ( ; t ; t /= 10 ) num[n ++] = t % 10 ;
    while ( n > 1 && !num[n - 1] ) -- n ;
    for ( int i = n - 1 ; i >= 0 ; -- i ) printf ( "%d" , num[i] ) ;
    printf ( "\n" ) ;
}

int main () {
    while ( ~scanf ( "%s%s" , s1 , s2 ) ) solve () ;
    return 0 ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值