题目:1598C - Delete Two Elements
题意:给你a[n]个数组,他们的平均数为k,若 删除2个数后的数组平均数仍然为k,请求出可行数据有多少队。
题解:得出平均数后 直接使用双指针,特判一下当a[i]==a[j]的情况。
#include<iostream>
#include<bits/stdc++.h>
#define csh(a) memset(a,0,sizeof(a));
typedef long long ll;
using namespace std;
const int N = 2e5 + 5;
int a[N];
ll sovle()
{
int n;
cin >> n;
double sum = 0;
for (int i = 0; i < n; i++)
{
cin >> a[i];
sum += a[i];
}
sum /= n;
sort(a, a + n);
ll cnt = 0;
ll i = 0, j = n-1;
while (i<j)
{
double val = ( double)(a[i] + a[j]) / 2;
if (val < sum) i++;
else if (val>sum) j--;
else {
ll ai = i, aj = j;
ll cnti = 0, cntj = 0;
if (a[i] != a[j])
{
while (a[ai] == a[i]){
ai++;
cnti++;
}
while (a[aj] == a[j]) {
aj--;
cntj++;
}
cnt += cnti * cntj;
i = ai;
j = aj;
}
else {
ll y = j - i + 1;
cnt += y * (y - 1) / 2;
break;
}
}
}
return cnt;
}
int main()
{
int t;
cin >> t;
while (t--){
cout << sovle() << endl;
}
}