2019-07-22

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



我的思路:

此题的要求是找到一个尽可能大的数B(所有产品的新价格),使得a_{i}
-B|≤k;即B是由每一个a_{i}加上或者减去一个不大于k的值得到的,而且要保证不管每个a_{i}如何变化最后的新价格都要保持一致。则可知B≤(min+k),对于a_{i}中最大的价格max,只需要保证(max-k)≤(min+k)就可以保证每一个a_{i}都可以变化出B。


#include <iostream>

using namespace std;

int main()

{

    int q;    //q代表有几组数据

    cin >> q;

    for(int i=0; i<q; i++)

    {//不同组的数据都需要重置n,k和用来存储价格的数组a

        int n, k;

        int min=1e8+1, max=-1;

        int a[105];

        cin >> n >> k;

         for(int i=0; i<n; i++)

        {

                cin >> a[i];

        }

        for(int i=0; i<n; i++)

        {

                if(a[i]>max)

                max = a[i];

                if(a[i]<min)

                min = a[i];

            }

            if((min+k)>=(max-k))

            {

                    cout << min+k << endl;

            }

            else

                    cout << -1 << endl;

    }  

}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容