B. Equalize Prices(思维水题)Codeforces Round #570 (Div. 3)

原题链接: https://codeforces.com/contest/1183/problem/B

在这里插入图片描述
测试样例

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

题意: 给你一系列商品的价格数组 a a a,现在需要你设置一个均价 B B B,使得 ∣ a [ i ] − B ∣ ≤ k |a[i]-B|\leq k a[i]Bk。你需要找到符合条件的最大的 B B B,若没有,则打印 − 1 -1 1

解题思路: 一道简单的思维题,影响决策的在于最大值和最小值。若其之差大于 2 × k 2\times k 2×k,那么自然是不行的。其他情况自然可行。那么影响 B B B的值又在于哪个呢?当然是最小值。我们直接让最小值加上一个 k k k即是最大的 B B B了,因为这个值能让最小限制的刚好通过,属于一个临界条件,即最大值。

AC代码

/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h>	//POJ不支持

#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair

using namespace std;

const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e5;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll>  pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//

int t;
int n,k;
int a[maxn];//寻找最大值最小值处理即可。
int main(){
	//freopen("in.txt", "r", stdin);//提交的时候要注释掉
	IOS;
	while(cin>>t){
		while(t--){
			cin>>n>>k;
			int maxx=0,minn=inf;
			rep(i,1,n){
				cin>>a[i];
				maxx=max(maxx,a[i]);
				minn=min(minn,a[i]);
			}
			if(maxx-minn>2*k){
				cout<<-1<<endl;
			}
			else{
				cout<<minn+k<<endl;
			}
		}
	}
	return 0;
}

posted @   unique_pursuit  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示