codeforces 题目 Array Recovery

目录

题目:

题目理解:

思路:

AC代码:


题目:

题目理解:

d数组是a数组经过

d_0 = a_0

d_i = |d_i - a_{i-1}|

操作转变而来的。

题目会给你长度为n的d数组,让你反向求a数组,如果存在多种可能a数组输出-1。

思路:

反向转换回去那其实就是对绝对值进行分析

如果绝对值大于0:a_i = a_{i-1} + d_i

如果绝对值小于0:a_i = a_{i-1} - d_i

题目告诉我们a数组中的元素都是非负的,所以我们只需要求出这两种可能看看谁非负就是谁,若都是非负且不同,则说明存在多种情况,直接输出-1。

思路有了,具体操作请看AC代码

AC代码:

#include<bits/stdc++.h>
 
using namespace std;
 
typedef long long ll;
 
int a[105];
int b[105];
 
int main()
{
	std::ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
 
 
	int t; cin >> t;
 
	while (t--)
	{
		int n;
		cin >> n;
 
		for (int i = 1; i <= n; i++)
			cin >> b[i];
 
		int flag = 1;
 
		a[1] = b[1];
 
		for (int i = 2; i <= n; i++)
		{
			int temp1, temp2;
			temp1 = b[i] + a[i - 1];
			temp2 = a[i - 1] - b[i];
 
			if (temp1 >= 0 && temp2 >= 0 && temp1 != temp2)
			{
				flag = 0;
				break;
			}
			else
				a[i] = (temp1 > temp2 ? temp1 : temp2);
 
		}
 
 
		if (flag)
		{
			for (int i = 1; i <= n; i++)
				cout << a[i] << ' ';
			cout << '\n';
		}
		else
		{
			cout << -1 << '\n';
		}
 
	}
 
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值