CF552-Div3-B. Make Them Equal

You are given a sequence a1,a2,…,an consisting of n integers.

You can choose any non-negative integer D (i.e. D≥0), and for each ai you can:

add D (only once), i. e. perform ai:=ai+D, or
subtract D (only once), i. e. perform ai:=ai−D, or
leave the value of ai unchanged.
It is possible that after an operation the value ai becomes negative.

Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all ai are equal (i.e. a1=a2=⋯=an).

Print the required D or, if it is impossible to choose such value D, print -1.

For example, for array [2,8] the value D=3 is minimum possible because you can obtain the array [5,5] if you will add D to 2 and subtract D from 8. And for array [1,4,7,7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4,4,4,4].

**题意:给你n个数,你可以对任意一个ai(可能重复)进行三种操作(有三种操作,只能选一种且只能进行一次):1.给ai加上D. 2. 给ai减去D 3.不对ai做任何操作.(D>=0) **

让你求出最小的D,在对每个元素进行操作以后,使每个元素都相等.
如果不存在,输出 -1 .

题解:首先对于相同的元素,对他们的操作都是一样的,所以我们只要统计不同数就行,不同数的个数记为N.

先对不同数进行sort排序,

分成四种情况: 1. N>3 肯定不存在,输出 -1 2. N=3,这三个不同的数必须满足等差数列,即 (x1+x3)=x2*2,才有D,输出x2-x1,否则输出 -1 3.N=2 两种情况 1)如果 x2-x1 的结果是偶数,那么输出 (x2-x1)/2,否则输出 x2-x1 4.N=1 无需任何操作,输出 0

#include <bits/stdc++.h>
using namespace std;
const int N=105;
int a[N];
int b[N];
int main(){
	int n;cin>>n;
	for(int i=1;i<=n;i++){
		int tmp;cin>>tmp;
		a[tmp]++;
	}
	
	int cnt=0;
	for(int i=1;i<=100;i++) if(a[i]>0) b[++cnt]=i;
	
	sort(b+1,b+1+cnt);
	if(cnt>3) puts("-1");
	else if(cnt==3){
		if(b[1]+b[3]==b[2]*2){
			cout<<b[2]-b[1]<<endl;
		}
		else puts("-1");
	}
	else if(cnt==2){
		if((b[2]-b[1])%2==0){
			cout<<(b[2]-b[1])/2<<endl;
		}
		else cout<<b[2]-b[1]<<endl;
	}
	else cout<<"0"<<endl;
	return 0;
}
posted @ 2019-04-18 00:50  _yjun  阅读(454)  评论(0编辑  收藏  举报