传送门:【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 ;
}