题目网址:https://nanti.jisuanke.com/t/32229
题意:
给定一个含AB的字符串, 问A-B的距离从1-n 每个距离的AB对的个数是多少?
思路:
完全没想到,把他转化成多项式的思路。
这样把A的部分提出来,如果s【i】=='A ' 就是多项式A x^i 的那一项系数为1,
如果s【j】==‘B’ 就是多项式B x ^( n - j ) 的那一项系数为1;
这样A*B以后,系数和就是个数,设幂 t = i + n - j ;所以 i - j = t - n; 要求1<=(i - j )<=n ,那么就是 1+n<= t <=2*n,作为最终答案输出就可以了。
趁机学习了一下fft,但是只是会套班子了而已,前天一直看网上的一个代码,但是没有深入理解fft,所以不懂他那种做法,
但是这种直接套板子求A*B的还是可以搞的出来的。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=2200000;
char s[N];
int pos[N];
struct comp
{
double r,i;
comp(double _r=0,double _i=0)
{
r=_r,i=_i;
}
comp operator+(const comp&x)
{
return comp(r+x.r,i+x.i);
}
comp operator-(const comp&x)
{
return comp(r-x.r,i-x.i);
}
comp operator*(const comp&x)
{
return comp(r*x.r-i*x.i,r*x.i+i*x.r);
}
comp conj()
{
return comp(r,-i);
}
} A[N],B[N];
const double pi=acos(-1.0);
void FFT(comp a[],int n,int t)
{
for(int i=1,j=0; i<n-1; i++){
for(int s=n; j^=s>>=1, ~j&s;);
if(i<j)
swap(a[i],a[j]);
}
for(int d=0; (1<<d)<n; d++)
{
int m=1<<d,m2=m<<1;
double o=pi*2/m2*t;
comp _w(cos(o),sin(o));
for(int i=0; i<n; i+=m2)
{
comp w(1.0);
for(int j=0; j<m; j++)
{
comp&A=a[i+j+m],&B=a[i+j],t=w*A;
A=B-t;
B=B+t;
w=w*_w;
}
}
}
if(t==-1)
for(int i=0; i<n; i++)
a[i].r/=n;
}
int n,i,j,k;
int main()
{
scanf("%s",s+1);
n=strlen(s+1);
for(i=1; i<=n; i++)
if(s[i]=='A')
A[i].r=1;
else
B[n-i].r=1;
k=1048576*2; //最大的n一定是2的幂
FFT(A,k,1); //qiu
FFT(B,k,1);
for(i=0; i<k; i++)
{
B[i]=(A[i]*B[i]); //直接想乘就是i幂对应的系数。
}
FFT(B,k,-1); //fan
for(i=1; i<n; i++)
printf("%d\n",(int)(B[i+n].r+0.5));
}