萌新才入门c++,求大佬改改,悬棺
查看原帖
萌新才入门c++,求大佬改改,悬棺
665688
ybchenyuyang楼主2023/9/5 23:15

萌新初学FFT,想来简单的试一下,代码也没有完全搞懂,照着其他博客的思路打了一遍,结果40pts,有RE,WA

#include<bits/stdc++.h>
using namespace std;
typedef struct node{
    double a,b;
    node(double x=0,double y=0){
        a=x,b=y;
    }
    node operator+(const node&t)const{
        return node(a+t.a,b+t.b);
    }
    node operator-(const node&t)const{
        return node(a-t.a,b-t.b);
    }
    node operator*(const node&t)const{
        return node(a*t.a-b*t.b,a*t.b+b*t.a);
    }
}aplusb;
const double pi=2*acos(-1);
char f[20],g[20],c[20];
int n,m,r[20];
aplusb a[20],w[20];
int log_2(int x){
    int ans=0;
    if(x&0xffff0000){
    	ans+=16,x>>=16;
	}
    if(x&0xff00){
    	ans+=8,x>>=8;
	}
    if(x&0xf0){
    	ans+=4,x>>=4;
	}
    if(x&0xc){
    	ans+=2,x>>=2;
	}
    if(x&2){
    	++ans;
	}
    return ans;
}
void init(){
    m+=n;
    int Log_2=log_2(m);
    n=1<<Log_2+1;
    for(int i=0;i<n;++i){
    	r[i]=r[i>>1]>>1|(i&1)<<Log_2;
	} 
    aplusb t(cos(pi/n),sin(pi/n));
    w[0].a=1;
    for(int i=1;i<n;++i){
    	w[i]=w[i-1]*t;
	}
}
void swap(aplusb& a,aplusb& b){
    static aplusb t;
    t=a,a=b,b=t;
}
void fft(bool type){
    for(int i=0;i<n;++i){
    	if(i<r[i]){
			swap(a[i],a[r[i]]);
		}
	}
    static aplusb x,y;
    for(int len=2;len<=n;len<<=1){
    	for(int l=0;l<n;l+=len){
    		for (int i=0,j=len>>1;j<len;++i,++j){
                x=a[l+i],y=w[n/len*i];
                if(type){
                	y=y*a[l+j];
				}else{
                	y=aplusb(y.a,-y.b)*a[l+j];
				}
                a[l+i]=x+y,a[l+j]=x-y;
            }
		}
	}
}
int main(){
    cin>>f>>g;
    n=strlen(f)-1;
	m=strlen(g)-1;
    for(int i=n;~i;--i){
    	a[i].a=(double)(f[n-i]^48);
	}
    for(int i=m;~i;--i){
    	a[i].b=(double)(g[m-i]^48);
	} 
    init();
    fft(1);
    for(int i=0;i<n;++i){
    	a[i]=a[i]*a[i];
	}
    fft(0);
    int t=0;
    for(int i=0;i<=m;++i){
        t+=(int)(a[i].b/n/2.0+0.5);
        c[i]=t%10^48;
		t/=10;
    }
    int ans=0;
    if(t!=0){
    	ans=ans*10+t;
	}
    for(int i=m;i>=0;--i){
    	ans=ans*10+(c[i]-'0');
	}
    n=strlen(f)-1;
	m=strlen(g)-1;
    int a=0,b=0;
    for(int i=0;i<=n;++i){
    	a=a*10+(f[i]-'0');
	}
    for(int i=0;i<=m;++i){
    	b=b*10+(g[i]-'0');
	}
	cout<<ans-a*b+a+b;
    return 0;
}
2023/9/5 23:15
加载中...