output
standard output
You are given a sequence a1,a2,…,an consisting of nn integers.
You can choose any non-negative integer D(i.e. D≥0 ), and for each aiai 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 aiai unchanged.
It is possible that after an operation the value aiai becomes negative.
Your goal is to choose such minimum non-negative integer DD and perform changes in such a way, that all aiai are equal (i.e. a1=a2=⋯=an ).
Print the required DD or, if it is impossible to choose such value DD , print -1.
For example, for array [2,8][2,8] the value D=3D=3 is minimum possible because you can obtain the array [5,5] if you will add DD to 22 and subtract DD from 88 . And for array [1,4,7,7] the value D=3D=3 is also minimum possible. You can add it to 11 and subtract it from 77 and obtain the array [4,4,4,4]
Input
The first line of the input contains one integer nn (1≤n≤1001≤n≤100 ) — the number of elements in aa .
The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100 ) — the sequence aa .
Output
Print one integer — the minimum non-negative integer value DD such that if you add this value to some aiai , subtract this value from some aiai and leave some aiai without changes, all obtained values become equal.
If it is impossible to choose such value DD , print -1.
Examples
Input
6
1 4 4 7 4 1
Output
3
Input
5
2 2 5 2 5
Output
3
Input
4
1 3 3 7
Output
-1
Input
2
2 8
Output
3
题意:首先给我们一个n,下面有n个数,对于每一个数,我i们可有有一个神奇的D,然后可以使这个数等于 +D -D 不变,然后我们要输出这个D,是不是很像那个搜素的问题啦,但是不是滴,想一下。
解法:我们可以先去个重,把数组里边重复的元素先删掉,然后我们再对数组进行个排序,不由的我们就想到了(去重+排序 = set) ,我是用的set做的,也可以用那个去重函数+sort做,然后我们就看这里边还有几个元素,如果大于三个(因为我们去过重了)肯定是不可能存在的,可以想一下,如果等于三个,我们就判断顺序相减是否相等,相等我们输出连续两个的差,如果是两个的话我们判断是否是奇数,如果是直接输出,是偶数的话输出除以2,如果去完重只剩下一个元素,那肯定不存在这样的D
#include<bits/stdc++.h>
using namespace std;
set<int> st;
int main()
{
int n , s[105] , p[105] , nu;
while(~scanf("%d",&n)){
st.clear();
nu = 0 ;
for(int i = 0 ; i < n ; i ++){
scanf("%d",&s[i]);
st.insert(s[i]);
}
set<int>::iterator it;
for(it = st.begin() ; it != st.end() ; it ++){
p[nu++] = * it;
}
if(nu > 3)
cout<<"-1"<<endl;
else if(nu == 3){
if(p[1] - p[0] == p[2] - p[1])
cout<<p[1] - p[0];
else
cout<<"-1"<<endl;
}
else if(nu == 2){
if((p[1]-p[0]) % 2 != 0)
cout << p[1] - p[0] << endl;
else
cout<<(p[1] - p[0]) / 2 <<endl;
}
else if(nu == 1){
cout<<"0"<<endl;
}
}
return 0 ;
}