lower_bound 和 upper_bound
注意点:1.越界的时候n+1的判断。
2.lower_bound和upper_bound 的插入位置在哪里。
https://codeforces.com/contest/1574/problem/C
这题主要是个贪心,如果有大于x的就选大于x的最小 (pos=lower_bound(a+1,a+1+n,x)-a)
然后和用最接近x的取min就可以了 (pos-1)要判断一下pos>1
lower_bound是返回大于等于x的第一个下标,如果都小于,就会返回n+1的下标
upper_bound是返回第一个大于x的下标如果都比x小,返回n+1,如果都比x大,返回下标1.
#include<bits/stdc++.h> #define pb push_back using namespace std; typedef long long ll; typedef pair<ll,ll>pii; const int mod=998244353; const int N=2e5+5; ll x,y; ll a[N]; ll sum; void solve(){ ll n; cin>>n; sum=0; for(int i=1;i<=n;i++)cin>>a[i]; sum=accumulate(a+1,a+1+n,0); sort(a+1,a+1+n); ll m; cin>>m; while(m--){ cin>>x>>y; ll ans=2e18; ll pos=lower_bound(a+1,a+1+n,x)-a; if(pos<=n)ans=min(ans,max(0ll,y-(sum-a[pos]))); if(pos>1)ans=min(ans,x-a[pos-1]+max(0ll,+y-(sum-a[pos-1]))); cout<<ans<<endl; } } int main(){ ios::sync_with_stdio(false); cin.tie(0); // int t; // cin>>t; // while(t--){ solve(); // } return 0; }