题目大意
给定长度为n的数组a。对于整数k,我们称其为piggy,当且仅当通过执行以下操作任意次数(可能为零),可以将a以非递减顺序排序:
您需要确定最大的piggy整数k。如果不存在这样的整数,则输出−1。
思路讲解
不难注意到,我们可以选用最大的数字或者最小的数字去做中转站,

乍一看,好像选择最小的数字,还是选择最大的数字,取决于两个数字 to 和 now?实际上不是的,我们完全可以换着来,比如说:

这样子就实现了 to 用 mn,now 用这个 mx,反之亦然,完全可以只根据一个数去选择。
okay,那就行了。我们发现,这个 to 和 now 一定都是和有序序列中的同位置值不一样的点,因此,我们的答案其实就是:(其中 S 为所有和有序序列中的同位置值不一样的点的下标集合)
ans←i∈Smin(max(mx−ai,ai−mn))
当然,也可以使用代码中的这个贪心实现。
AC代码
AC
https://codeforces.com/contest/2188/submission/360594620
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#include <iostream> #include <numeric> #include <algorithm> #include <complex> #include <map> #include <ranges> #include <cstring> #include <string> #include <deque> #include <queue> #include <vector> #include <set> #include <cmath> #include <bitset> #include <iterator> #include <random> #include <iomanip> #include <cassert> #include <cstdio> #include <chrono>
#define all(vec) vec.begin(),vec.end() #define lson(o) (o<<1) #define rson(o) (o<<1|1) #define SZ(a) ((long long) a.size()) #define debug(var) cerr << #var <<":"<<var<<"\n"; #define cend cerr<<"\n-----------\n" #define fsp(x) fixed<<setprecision(x)
using namespace std;
using ll = long long; using ull = unsigned long long; using DB = double; using LD = long double;
using CD = complex<double>;
static constexpr ll MAXN = (ll)1e6+10, INF = (1ll<<61)-1; static constexpr ll mod = 998244353; static constexpr double eps = 1e-8; const double pi = acos(-1.0);
ll lT;
void Solve() { ll N; cin >> N; vector<ll> A(N); for (int i=0;i<N;++i) { cin>>A[i]; } if (is_sorted(all(A))) { cout<<-1<<"\n"; return; } vector<ll> a_sort(all(A)); sort(all(A)); ll mn=*min_element(all(A)),mx=*max_element(all(A)); auto check=[&](ll k) { for (int i=0;i<N;++i) { if (A[i]==a_sort[i]) { continue; } if (abs(A[i]-mn)<k && abs(mx-A[i])<k) { return false; } } return true; }; ll l=0,r=mx; while (l<r) { ll mid=(l+r+1)>>1; if (check(mid)) { l=mid; }else { r=mid-1; } } cout<<l<<"\n"; }
signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> lT; while(lT--) Solve(); return 0; }
|
心路历程(WA,TLE,MLE……)