CF1772D
Absolute Sorting
题面翻译
给定一个长度为 \(n\) 的正整数序列 \(a\),选择一个整数 \(x\),将所有的 \(a_i\) 变为 \(|x-a_i|\),求能满足 \(a_1\le a_2\le...\le a_n\) 和 \(0\le x\le 10^9\) 的一个解 \(x\)。如果存在这样的一个 \(x\) 请直接输出,如果无解请输出 \(-1\).
数据范围:\(1\le a_i\le10^8,2\le n\le2\cdot 10^5,1\le t\le2\cdot 10^4\)。
题目描述
You are given an array $ a $ consisting of $ n $ integers. The array is sorted if $ a_1 \le a_2 \le \dots \le a_n $ .
You want to make the array $ a $ sorted by applying the following operation exactly once:
- choose an integer $ x $ , then for every $ i \in [1, n] $ , replace $ a_i $ by $ |a_i - x| $ .
Find any value of $ x $ that will make the array sorted, or report that there is no such value.
输入格式
The first line contains one integer $ t $ ( $ 1 \le t \le 2 \cdot 10^4 $ ) — the number of test cases.
Each test case consists of two lines. The first line contains one integer $ n $ ( $ 2 \le n \le 2 \cdot 10^5 $ ). The second line contains $ n $ integers $ a_1, a_2, \dots, a_n $ ( $ 1 \le a_i \le 10^8 $ ).
Additional constraint on the input: the sum of $ n $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
输出格式
For each test case, print any integer $ x $ ( $ 0 \le x \le 10^9 $ ) that makes the array sorted. It can be shown that if such an integer $ x $ exists, there is at least one such integer between $ 0 $ and $ 10^9 $ .
If there is no such integer, then print $ -1 $ . If there are multiple suitable values of $ x $ , print any of them.
样例 #1
样例输入 #1
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
样例输出 #1
4
-1
0
42
2
-1
100000000
40741153
提示
In the first test case, after using $ x = 4 $ , the array becomes $ [1, 1, 1, 1, 1] $ .
In the third test case, after using $ x = 0 $ , the array becomes $ [1, 2, 3, 4, 5, 6, 7, 8] $ .
In the fourth test case, after using $ x = 42 $ , the array becomes $ [32, 37, 38, 39, 40, 41] $ .
Solution:
自己的idea是在极大极小之间枚举,但由于数据范围的限制以及不下降的判断不会写导致这题没做出来
其实换个思路想,只用考虑相邻的两个值就行了
对相邻的两个列出等式
发现其实是一个不等式组构成的范围 取公共部分就行了
点击查看代码
#include<bits/stdc++.h>
using namespace std;
int t,n,a[200005];
int main()
{
ios::sync_with_stdio(false);
cin>>t;
while(t--)
{
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
int l=0,r=1e9;
for(int i=1;i<n;i++)
{
if(a[i+1]>a[i])r=min(r,(int)floor(double(a[i]+a[i+1])/2));
if(a[i+1]<a[i])l=max(l,(int)ceil(double(a[i]+a[i+1])/2));
}
if(l>r)cout<<"-1\n";
else cout<<l<<"\n";
}
return 0;
}
要注意细节的实现,比如说ceil 和 floor 后面应该先强制转换成double类型再取int

浙公网安备 33010602011771号