#include<bits/stdc++.h> using namespace std; #define int long long const int N=1e5+10; int Max,Min,n,t; int a[N],b[N]; bool check(int x){ int lim=Max-x; int L=-1,R; for (int i=1; i<=n; ++i){ b[i]=a[i]; if (a[i]<lim){ if (L==-1) L=i; R=i; } } if (L==-1) L=R=t; for (int i=L; i<=R; ++i) b[i]*=2; int Min1=b[1],Max1=b[1]; for (int i=2; i<=n; ++i) Min1=min(Min1,b[i]),Max1=max(Max1,b[i]); if (Max1-Min1<=x) return 1; return 0; } void solve(){ cin>>n; for (int i=1; i<=n; ++i) cin>>a[i]; if (n==1){ cout<<0; return; } Min=Max=a[1]; for (int i=2; i<=n; ++i) Min=min(Min,a[i]),Max=max(Max,a[i]); for (int i=1; i<=n; ++i) if (a[i]==Min) t=i; int l=0,r=2*(Max-Min),Ans=2*(Max-Min); while (l<=r){ int mid=l+r>>1; if (check(mid)) Ans=mid,r=mid-1; else l=mid+1; } cout<<Ans; } signed main(){ ios_base::sync_with_stdio(false); cin.tie(0),cout.tie(0); int _=1; //cin>>_; while (_--) solve(); return 0; } //正解 #include <bits/stdc++.h> void solve() { int n; std::cin >> n; std::vector<int> a(n); for (int i = 0; i < n; i++) { std::cin >> a[i]; } std::vector<int> id(n); std::iota(id.begin(), id.end(), 0); auto cmp = [&a] (int x, int y) -> bool { return a[x] < a[y]; }; std::sort(id.begin(), id.end(), cmp); int l = id[0]; int r = l; a[l] *= 2; std::multiset<int> S(a.begin(), a.end()); int ans = INT_MAX; for (int i : id) { while (i < l) { int p = --l; S.erase(S.find(a[p])); a[p] *= 2; S.insert(a[p]); } while (r < i) { int p = ++r; S.erase(S.find(a[p])); a[p] *= 2; S.insert(a[p]); } ans = std::min(ans, *S.rbegin() - *S.begin()); } std::cout << ans << '\n'; } int main() { int T = 1; // std::cin >> T; while (T--) { solve(); } return 0; }
标签:std,begin,21,int,mid,学习,2025,while,id From: https://www.cnblogs.com/litianyu1969/p/18684573