Equaliaze Prices

There are n products in the shop. The price of the i-th product is ai. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.In fact, the owner of the shop can change the price of some product ii in such a way that the difference between the old price of this product ai and the new price bi is at most k. In other words, the condition |ai−bi|≤k should be satisfied (|x| is the absolute value of x).He can change the price for each product not more than once. Note that he can leave the old prices for some products. The new price bi of each product i should be positive (i.e. bi>0 should be satisfied for all ii from 11 to n.Your task is to find out the maximum possible equal price B of all products with the restriction that for all products the condition |ai−B|≤k should be satisfied (where ai is the old price of the product and B is the same new price of all products) or report that it is impossible to find such price B.Note that the chosen price B should be integer.You should answer q independent queries.

Input:

The first line of the input contains one integer q (1≤q≤100) — the number of queries. Each query is presented by two lines.The first line of the query contains two integers n and k (1≤n≤100,1≤k≤1e8) — the number of products and the value k. The second line of the query contains n integers a1, a2,…,an (1≤ai≤1e8), where ai is the price of the i-th product.

Output:

Print q integers, where the i-th integer is the answer B on the i-th query.If it is impossible to equalize prices of all given products with restriction that for all products the condition |ai−B|≤k should be satisfied (where ai is the old price of the product and B is the new equal price of all products), print -1. Otherwise print the maximum possible equal price of all products.
Example Input:
4
5 1
1 1 2 3 1
4 2
6 4 8 5
2 2
1 6
3 5
5 2 5
Output:
2
6
-1
7
题目大意:改变给出的多组商品价格的数据,使得每组数据中的每个价格可以是相等(通过加或者减给定的值k),即保证该价格为最高的;
思路:只要满足数据中的最大价格max-k的绝对值小于d等于最小值min+k。即*|max-k|<=min+k*;
注意事项:1.求得的值是最大值,所以如果存在,最大即为min+k,2.利用排序的函数可减短运行时间:#include<bits/stdc++.h> sort(a,a+len)(len为数组的长度)
代码
#include
#include<bits/stdc++.h>
using namespace std;
int a[100000];
int main()
{
int m,k1,k2;
cin>>m;
for(int i=0;i<m;i++)
{
int y=0;
cin>>k1>>k2;
//读取一组数据
for(int j=0;j<k1;j++)
{
cin>>a[j];
}
sort(a,a+k1);//数组排序找出最值
//关系式
if((a[0]+k2)>=(a[k1-1]-k2))
{
cout << a[0]+k2 << endl;
}
else
cout << “-1”<< endl;
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值