[Pinely Round 4 (Div. 1 + Div. 2)](https://codeforces.com/contest/1991)

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值