fork(1) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define fastIO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  4. #define F first
  5. #define S second
  6. #define pb push_back
  7. #define mp make_pair
  8. #define rep(i,a,b) for(int i=a;i<b;i++)
  9. typedef long long ll;
  10. typedef vector<ll> vi;
  11. typedef pair<ll,ll> pi;
  12. const int mod = 1e9 + 7;
  13. const long long INF = 1e18L + 5;
  14. const int mxn = 2e5 + 1;
  15. int cnt = 1;
  16. void solve()
  17. {
  18. ll n,x,y;
  19. cin>>n;
  20. vi v(n);
  21. rep(i,0,n)
  22. cin>>v[i];
  23. sort(v.begin(),v.end());
  24. vi pre = v;
  25. rep(i,1,n)
  26. pre[i]+=pre[i-1];
  27. ll q;
  28. cin>>q;
  29. while(q--)
  30. {
  31. cin>>x>>y;
  32. ll ans = INF;
  33. ll pos = std::lower_bound(v.begin(),v.end(),x) - v.begin();
  34. ll need = 0;
  35. if(pos==n)
  36. {
  37. ans = x - v[pos-1] + max(ll(0) , y - pre[n-1] + v[pos-1]);
  38. }
  39. else if(pos!=0)
  40. {
  41. ans = min(max(ll(0) , x - v[pos]) + max(ll(0) , y - pre[n-1] + v[pos]) , max(ll(0) , x - v[pos-1]) + max(ll(0) , y - pre[n-1] + v[pos-1]));
  42. }
  43. else
  44. {
  45. ans = max(ll(0) , x - v[pos]) + max(ll(0) , y - pre[n-1] + v[pos]);
  46. }
  47. cout<<ans<<"\n";
  48. }
  49.  
  50.  
  51. }
  52. int main()
  53. {
  54. fastIO;
  55. int t = 1;
  56. //cin>>t;
  57. while(t--)
  58. {
  59. solve();
  60. cnt++;
  61. }
  62. return 0;
  63. }
  64.  
Runtime error #stdin #stdout #stderr 0s 5536KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc