div3 D

124 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第27天,点击查看活动详情

D. Absolute Sorting

time limit per test

2 seconds

memory limit per test

512 megabytes

input

standard input

output

standard output

You are given an array aa consisting of nn integers. The array is sorted if a1≤a2≤⋯≤ana1≤a2≤⋯≤an.

You want to make the array aa sorted by applying the following operation exactly once:

  • choose an integer xx, then for every i∈[1,n]i∈[1,n], replace aiai by |ai−x||ai−x|.

Find any value of xx that will make the array sorted, or report that there is no such value.

Input

The first line contains one integer tt (1≤t≤2⋅1041≤t≤2⋅104) — the number of test cases.

Each test case consists of two lines. The first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105). The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1081≤ai≤108).

Additional constraint on the input: the sum of nn over all test cases does not exceed 2⋅1052⋅105.

Output

For each test case, print any integer xx (0≤x≤1090≤x≤109) that makes the array sorted. It can be shown that if such an integer xx exists, there is at least one such integer between 00 and 109109.

If there is no such integer, then print −1−1. If there are multiple suitable values of xx, print any of them.

Example

input

Copy

8
5
5 3 3 3 5
4
5 3 4 5
8
1 2 3 4 5 6 7 8
6
10 5 4 3 2 1
3
3 3 1
3
42 43 42
2
100000000 99999999
6
29613295 52036613 75100585 78027446 81409090 73215

output

Copy

4
-1
0
42
2
-1
100000000
40741153

Note

In the first test case, after using x=4x=4, the array becomes [1,1,1,1,1][1,1,1,1,1].

In the third test case, after using x=0x=0, the array becomes [1,2,3,4,5,6,7,8][1,2,3,4,5,6,7,8].

In the fourth test case, after using x=42x=42, the array becomes [32,37,38,39,40,41][32,37,38,39,40,41].

分析

这题其实是一个区间问题,就是要考虑维护一个最大左边界和最小右边界,如果满足就输出yes,否则输出no

代码

#include <iostream>
#include <cmath>
#define PII pair<int,int>
using namespace std;
const int N=2e5+10;
int a[N];
//int ce(int x,int y){
//	if((x+y)%2==0) return (x+y)/2;
//	else return (x+y)/2+1;
//}
//int fl(int x,int y){
//	if((x+y)%2==0) return (x+y)/2;
//	else return (x+y)/2-1;
//}
int main(){
	int t;
	cin>>t;
	while(t--){
		int n;
		cin>>n;
		for(int i=1;i<=n;i++){
			cin>>a[i];
		}
		bool ok=0;
		PII temp={0,1e9};
		for(int i=2;i<=n;i++){
			if(a[i]==a[i-1]) continue;
			if(a[i]<a[i-1]){
				int l=ceil(1.0*(a[i]+a[i-1])/2);
				if(l>temp.second){
					puts("-1");
					ok=1;
					break;
				}
				temp.first=max(l,temp.first);
			}	
			else{
				int r=floor(1.0*(a[i]+a[i-1])/2);
				if(r<temp.first){
					puts("-1");
					ok=1;
					break;
				}
				temp.second=min(r,temp.second);
			}
		}
		if(!ok) cout<<temp.first<<endl;
	} 
}