题目链接:https://cn.vjudge.net/contest/280041#problem/B
题目大意:给你n个数,然后让你找满足a[i] + a[j] = a[k] 的情况总数。
具体思路:首先把每一种情况的个数算出来(两个数相加的结果),然后再就是去重的过程。
(因为题目中会有负数,我们可以全部转换成非负数去进行计算)
1,自己和自己相加。
2,1+0=1,0+1=1这个时候,1是使用了两次,所以需要去掉这种情况,就是去掉(0的总数)*2.
3,0+0=0,0+0=0,这个时候我们可以按照第一种的思路来(这个时候i!=j,因为自己加自己情况已经去掉了),把其中一个0看成(非0的数),然后再按照公式进行计算,不过计算的时候是(0的总数-1)*2.
AC代码:
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<stdio.h>
using namespace std;
# define ll long long
const double PI = acos(-1.0);
const int maxn = 2e5+;
struct complex
{
double r,i;
complex(double _r = ,double _i = )
{
r = _r;
i = _i;
}
complex operator +(const complex &b)
{
return complex(r+b.r,i+b.i);
}
complex operator -(const complex &b)
{
return complex(r-b.r,i-b.i);
}
complex operator *(const complex &b)
{
return complex(r*b.r-i*b.i,r*b.i+i*b.r);
}
};
void change(complex y[],int len)
{
int i,j,k;
for(i = , j = len/; i < len-; i++)
{
if(i < j)
swap(y[i],y[j]);
k = len/;
while( j >= k)
{
j -= k;
k /= ;
}
if(j < k)
j += k;
}
}
void fft(complex y[],int len,int on)
{
change(y,len);
for(int h = ; h <= len; h <<= )
{
complex wn(cos(-on**PI/h),sin(-on**PI/h));
for(int j = ; j < len; j += h)
{
complex w(,);
for(int k = j; k < j+h/; k++)
{
complex u = y[k];
complex t = w*y[k+h/];
y[k] = u+t;
y[k+h/] = u-t;
w = w*wn;
}
}
}
if(on == -)
for(int i = ; i < len; i++)
y[i].r /= len;
}
const int T=5e4;
complex x1[maxn<<];
ll num[maxn<<],a[maxn<<],b[maxn<<];
int main()
{
int n;
scanf("%d",&n);
int ans=;
int len=;
while(len<maxn)
len<<=;
for(int i=; i<n; i++)
{
scanf("%lld",&a[i]);
if(a[i]==)
ans++;
b[a[i]+T]++;
}
for(int i=; i<len; i++)
{
x1[i]=complex(b[i],);
}
fft(x1,len,);
for(int i=; i<len; i++)
{
x1[i]=x1[i]*x1[i];
}
fft(x1,len,-);
for(int i=; i<len; i++)
{
num[i]=(ll)(x1[i].r+0.5);
}
for(int i=; i<n; i++)
{
num[(a[i]+T)*]--;
}//重复的去掉
ll sum=;
// cout<<num[T+T]<<endl;
for(int i=; i<n; i++)
{
sum+=num[a[i]+*T];//比如说 1 2 3 ,我们现在要计算能组成3的个数,也就是3加上 2 个T,因为他的两个因子分别有一个T
sum-=(ans-(a[i]==))*;// 0+4 =4 ,4+0=4,这个时候4是用了两遍的,所以减去的就应该是ans*2。
// 对于0+0等于0,这种情况,如果说当前只有两个0的话,num[0]是等于2的(去重之后),这个时候我们就把其中一个0看成非0的,然后再按照上面的步骤进行计算。
}
printf("%lld\n",sum);
return ;
}