C. Delete Two Elements
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Monocarp has got an array aa consisting of nn integers. Let's denote kk as the mathematic mean of these elements (note that it's possible that kk is not an integer).
The mathematic mean of an array of nn elements is the sum of elements divided by the number of these elements (i. e. sum divided by nn).
Monocarp wants to delete exactly two elements from aa so that the mathematic mean of the remaining (n−2)(n−2) elements is still equal to kk.
Your task is to calculate the number of pairs of positions [i,j][i,j] (i<ji<j) such that if the elements on these positions are deleted, the mathematic mean of (n−2)(n−2) remaining elements is equal to kk (that is, it is equal to the mathematic mean of nn elements of the original array aa).
Input
The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of testcases.
The first line of each testcase contains one integer nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of elements in the array.
The second line contains a sequence of integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109), where aiai is the ii-th element of the array.
The sum of nn over all testcases doesn't exceed 2⋅1052⋅105.
Output
Print one integer — the number of pairs of positions [i,j][i,j] (i<ji<j) such that if the elements on these positions are deleted, the mathematic mean of (n−2)(n−2) remaining elements is equal to kk (that is, it is equal to the mathematic mean of nn elements of the original array aa).
Example
input
Copy
4 4 8 8 8 8 3 50 20 10 5 1 4 7 3 5 7 1 2 3 4 5 6 7
output
Copy
6 0 2 3
Note
In the first example, any pair of elements can be removed since all of them are equal.
In the second example, there is no way to delete two elements so the mathematic mean doesn't change.
In the third example, it is possible to delete the elements on positions 11 and 33, or the elements on positions 44 and 55.
-------------------------------------------------------------------------------
本题考察map应用,题目要求删掉两个数之后,平均值k不变,也就是说删掉的这两个数平均值也要是k,sum+(n-2)*k=n*k sum=2*k =总和*2 /n ,另外,由于数组元素全是整数,sum也必定是整数,总和*2/N也必须是整数才行,可以先判断是否为整数,不是就输出0,否则继续判断
map遍历的内部,如果某个数就是平均值,那么选法是个数*(个数-1)/2 ,如果不是,选法是
个数*(sum-a[i])的个数/2 ,为了方便计算,/2操作最后统一进行。
# include<iostream>
# include<math.h>
# include<stack>
# include<vector>
# include<algorithm>
# include<cstring>
# include<map>
using namespace std;
typedef long long int ll;
ll a[200000+10];
map<ll,ll>m;
int main ()
{
int t;
cin>>t;
while(t--)
{
int n;
scanf("%d",&n);
ll sum=0;
for(int i=1; i<=n; i++)
{
scanf("%lld",&a[i]);
sum+=a[i];
m[a[i]]++;
}
ll cnt=0;
ll ans=sum*2/n;
if(sum*2%n)
{
cout<<0<<'\n';
m.clear();
continue;
}
for(auto it:m)
{
if(it.first==ans-it.first)
cnt+=it.second*(it.second-1);
else
cnt+=it.second*m[ans-it.first];
}
cout<<cnt/2<<'\n';
m.clear();
}
return 0;
}