C. Absolute Zero
题目要求
一个长度为n的数组a,你可以进行不操作40次的操作,判断其能否变为数组元素全为0
每次操作,可以选择一个数x,将数组的每个元素都替换为|a_i - x|。
思路
其实就是让逐渐的减少数的范围,使得他们最后等于0
可以发现如果要想让数组元素的范围变小,其实就是依次的取x为最大值和最小值的和的二分之一。这样就会使得数组a的元素都控制在<=x的范围内。
那么我们只需要判断最后是否会在不超过40次的操作下,使得数组元素最后变为0。
代码
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl "\n"
#define debug(x) cout << #x << " " << x << endl
#define LL long long
void solve()
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
vector<int> ans; // 存每次操作的x
for (int i = 1; i <= 40; i++)
{
int zero_num = 0; // 每次都统计数组中0的个数
LL mx = *max_element(a.begin(), a.end());
LL mn = *min_element(a.begin(), a.end());
int x = mx + mn >> 1;
ans.push_back(x);
for (int j = 0; j < n; j++) {
a[j] = abs(a[j] - x);
if (a[j] == 0) {
zero_num++;
}
}
// 如果数组中的元素全变为了0
if (zero_num == n) {
cout << ans.size() << endl;
for (int j = 0; j < ans.size(); j++) {
cout << ans[j] << " ";
}
cout << endl;
return;
}
}
cout << -1 << endl;
}
signed main()
{
int T;
cin >> T;
while (T--)
{
solve();
}
return 0;
}