This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define pb push_back
#define s second
#define f first
#define pb push_back
#define pii pair <int,int>
#define ll long long
#define left h*2,l,(l + r)/2
#define right h*2+1,(l + r)/2 + 1,r
using namespace std;
const int N = 3e5 + 5,mod = 1e9 + 7;
int a[N];
int main() {
  ios_base::sync_with_stdio(0),cin.tie(NULL),cout.tie(NULL);
  int n;
  cin>>n;
  for (int i = 1; i <= n; i++){
    cin >> a[i];
  }
  int q;
  cin>>q;
  while (q--){
    multiset <int> st;
    for (int i = 1; i <= n; i++){
      st.insert(a[i]);
    }
    int s;
    cin>>s;
    int ans = 0;
    while (st.size()){
      multiset <int> :: iterator it = st.lower_bound(s);
      int l = -1,r = -1;
      if (it != st.end()) {
        r = *it;
      }
      if (it != st.begin()){
        --it;
        l = *it;
      }
      if (l == -1 || (l != -1 && r != -1 && (r - s) < (s - l))) {
        st.erase(st.find(r));
        ans += abs(r - s);
        s = r;
      }else if (r == -1 || (l != -1 && r != -1 && (s - l) <= (r - s))){
        st.erase(st.find(l));
        ans += abs(s - l);
        s = l;
      }
    }
    cout<<ans<<endl;
  }
}
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |