Problem:
ピザ
問題
JOI ピザでは,市の中心部を通る全長
d
メートルの環状線の沿線上でピザの宅配販
売を行っている.
JOI ピザは,環状線上に
n
個の店舗
S
1
, ... ,
S
n
を持つ.本店は
S
1
である.
S
1
から
S
i
まで,時計回りに環状線を移動したときの道のりを
d
i
メートルとおく.
d
2
, ... ,
d
n
は 1 以上
d
- 1 以下の整数である.
d
2
, ... ,
d
n
は全て異なる. ピザの注文を受けると, ピザが冷めないように, 宅配先までの移動距離がもっとも短い店舗でピザを焼き宅配する.
宅配先の位置は 0 以上
d
- 1 以下の整数
k
で表される.これは, 本店
S
1
から宅配先までに時計回りで環状線を移動したときの道のりが
k
メートルであることを意味する. ピザの宅配は環状線に沿って行われ, それ以外の道を通ることは許されない. ただし, 環状線上は時計回りに移動しても反時計回りに移動してもよい.
例えば,店舗の位置と宅配先の位置が下図のようになっている場合 (この例は「入出力の例」の例 1 と対応している),
宅配先 1 にもっとも近い店舗は
S
2
なので, 店舗
S
2
から宅配する.このとき, 店舗からの移動距離は 1 である.また, 宅配先 2 にもっとも近い店舗は
S
1
(本店) なので, 店舗
S
1
(本店) から宅配する.このとき,店舗からの移動距離は 2 である.
環状線の全長
d
, JOI ピザの店舗の個数
n
, 注文の個数
m
, 本店以外の位置を表す
n
- 1 個の整数
d
2
, ... ,
d
n
, 宅配先の場所を表す整数
k
1
, ... ,
k
m
が与えられたとき, 各注文に対する宅配時の移動距離 (すなわち,最寄店舗から宅配先までの道のり) の全注文にわたる総和を求めるプログラムを作成せよ.
入力
入力は複数のデータセットからなる．各データセットは以下の形式で与えられる．
1 行目には環状線の全長を表す正整数
d
(2 ≤
d
≤ 1000000000 = 10
9
), 2 行目には店舗の個数を表す正整数
n
(2 ≤
n
≤ 100000), 3 行目には注文の個数を表す正整数
m
(1 ≤
m
≤ 10000) が書かれている. 4 行目以降の
n
- 1 行には本店以外の店舗の位置を表す整数
d
2
,
d
3
, ... ,
d
n
(1 ≤
d
i
≤
d
- 1) がこの順に書かれており,
n
+ 3 行目以降の
m
行には宅配先の場所を表す整数
k
1
,
k
2
, ... ,
k
m
(0 ≤
k
i
≤
d
- 1) がこの順に書かれている.
採点用データのうち,配点の 40% 分については, n ≤ 10000 を満たす. また,配点の 40% 分については, 求める移動距離の総和と
d
の値はともに 1000000 以下である. さらに,全ての採点用データにおいて, 求める移動距離の総和は 1000000000 = 10
9
以下である.
d
が 0 のとき入力の終了を示す. データセットの数は 10 を超えない．
出力
データセットごとに,宅配時の移動距離の総和を表す 1 つの整数を1 行に出力する.
入出力例
入力例
8
3
2
3
1
4
6
20
4
4
12
8
16
7
7
11
8
0
出力例
3
3
上記問題文と自動審判に使われるデータは、
情報オリンピック日本委員会
が作成し公開している問題文と採点用テストデータです。

Submitted solutions:

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include<utility>
#include<set>
#include<deque>
#include <unordered_map>
#include<string>
#include<map>
#include<cmath>
#include <unordered_set>

using namespace std;

int main() {
	while (true) {
		int d, n, m;
		cin >> d;
		if (d == 0)break;
		cin >> n >> m;
		vector<int>T(n);
		T[0] = 0;
		for (int i = 1; i < n; i++) {
			cin >> T[i];
		}

		T.push_back(d);


		int sa = 0;
		sort(T.begin(), T.end());
		for (int i = 0; i < m; i++) {
			int p;
			cin >> p;
			auto it = upper_bound(T.begin(), T.end(), p);
			int ind = it - T.begin();

			int ans = 0;
			ans = min(abs(p - T[ind]), abs(p - T[ind - 1]));

			sa += ans;
		}
		cout << sa << endl;
	}
}
accuracy: 1
time_ms: 30
memory_kb: 3660
final_rank: 8

code_snippet: #include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>
using namespace std;
int pos[110000];
int erfen(int n, int x)
{
    int l = 1, r = n, ans = 1;
    while(l<=r)
    {
        int mid = (l+r)/2;
        if(pos[mid]<=x)
        {
            ans = mid;
            l = mid+1;
        }
        else
            r = mid-1;
    }
    return ans;
}
int main()
{
    int d, n, m;
    while(scanf("%d", &d), d)
    {
        scanf("%d %d", &n, &m);
        for(int i=1; i<n; i++)
            scanf("%d", &pos[i]);

        sort(pos+1, pos+n);

        long long ans = 0;
        for(int i=1; i<=m; i++)
        {
            int x;
            scanf("%d", &x);
            if(x<=pos[1])
                ans += min(pos[1]-x, x);
            else
            {
                int Index = erfen(n-1, x);
                if(Index == n-1)
                    ans += min(x-pos[n-1], d-x);
                else
                    ans += min(x-pos[Index], pos[Index+1]-x);
            }

        }

        printf("%lld\n", ans);
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3188
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    while(true){
        ll d;
        if(!(cin >> d)) return 0;  // 入力終了
        if(d == 0) break;

        int n; 
        cin >> n;
        int m; 
        cin >> m;

        vector<ll> stores;
        stores.reserve(n);
        // 本店 S1 を 0 としておく
        stores.push_back(0);
        // S2～Sn の位置
        for(int i = 2; i <= n; i++){
            ll di;
            cin >> di;
            stores.push_back(di);
        }
        sort(stores.begin(), stores.end());

        ll total = 0;
        int N = stores.size();  // = n

        while(m--){
            ll k;
            cin >> k;
            // 二分探索で k 以上の最初の要素の index を求める
            int idx = int(lower_bound(stores.begin(), stores.end(), k) - stores.begin());
            // ラップアラウンドを含む２つの候補
            int i1 = idx % N;                // idx==N のときは 0
            int i2 = (idx + N - 1) % N;      // idx==0 のときは N-1

            ll best = d;
            // 候補1
            {
                ll dist = llabs(k - stores[i1]);
                best = min(best, min(dist, d - dist));
            }
            // 候補2
            {
                ll dist = llabs(k - stores[i2]);
                best = min(best, min(dist, d - dist));
            }

            total += best;
        }

        cout << total << "\n";
    }

    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4224
final_rank: 18

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <functional>


using namespace std;
typedef long long int ll;
typedef vector<ll> vll;

bool solve() {
  ll d, n, m;
  cin >> d;
  if (d == 0) {
    return false;
  }
  cin >> n;
  cin >> m;
  vll huts;
  huts.push_back(0);    // 本店
  for (ll i = 0; i < n-1; i++) {
    ll di;
    cin >> di;
    huts.push_back(di);
  }
  huts.push_back(d);    // 本店
   sort(huts.begin(), huts.end());

  ll res = 0;
  for (ll i = 0; i < m; i++) {
    ll k;
    cin >> k;

    auto hut1_d = lower_bound(huts.begin(), huts.end(), k);
    auto hut2_d = lower_bound(huts.rbegin(), huts.rend(), k, greater<ll>{});

    res += min(*hut1_d - k, k - *hut2_d);
  }

  cout << res << endl;
  return true;
}

int main() {
  while (solve());
}
accuracy: 1
time_ms: 30
memory_kb: 3992
final_rank: 15

code_snippet: #include <stdio.h>
#include <vector>
#include<algorithm>
using namespace std;

int main()
{
  int d, n, m, sum;

  while(1){
    sum = 0;
    int store[100000];
    scanf("%d\n", &d); //最大経路
    if(d==0) break;
    scanf("%d\n", &n); //店舗数
    scanf("%d\n", &m); // 宅配先

    // printf("%d, %d, %d\n", d,n,m);
    
    int tmp;  
    // 本店はデータにないので先に入れる
    store[0] = 0;
    for(int i=0;i<n - 1;i++){  
      scanf("%d\n", &tmp);  
      store[i] = tmp;  
    }

    // 環状は面倒なので一本道化する
    store[n] = d;
    n = n + 1;
    

    
    // for(int i=0; i < n; i++){  
    //   printf("%d\n",store[i]);  
    // }
    // printf("\n");

    // 店舗の位置を並べ替え
    sort(store,store+n);
    // for(int i=0; i < n; i++){  
    //   printf("%d\n",store[i]);  
    // }

    for(;m--;){  
      scanf("%d\n", &tmp);  
      // printf("%d ",tmp);
      for(int i=0; i < n; i++){  
        if(store[i] >= tmp){
            if(store[i] == tmp){
                // 店舗と宅配先が同じ座標なのでコスト0
                // printf("0\n");
            }
            if(store[i] - tmp < tmp - store[i-1])
            {
                // iの方が近い
                // printf("%d\n",store[i] - tmp);
                sum+=store[i] - tmp;
            }else{
                // i-1の方が近い
                // printf("%d\n",tmp-store[i-1]);
                sum+=tmp-store[i-1];
            }
            break;
        }
      }
    }  
    printf("%d\n",sum);
  }

}
accuracy: 1
time_ms: 220
memory_kb: 3192
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;++i)
#define ALL(a)  (a).begin(),(a).end()
const int inf = INT_MAX;
using ll = long long;
const ll INF = 1e18;
using P = pair<int,int>;
struct Edge{
    int to;
    ll cost;
    Edge(int to,ll cost):to(to),cost(cost){}
};
using kEdge = pair<int,pair<int,int>>;
using Graph = vector<vector<int>>;
using WeightedGraph = vector<vector<Edge>>;


struct UnionFind{
   vector<int> par,rank,siz;
   UnionFind(int n) : par(n,-1),rank(n,0),siz(n,1){ }

   int root(int x){
       if(par[x]==-1)return x;
       else return par[x]=root(par[x]);
   }

   bool issame(int x,int y){
       return root(x)==root(y);
   }

   bool unite(int x,int y){
       int rx=root(x),ry=root(y);
       if(rx==ry)return false;
       if(rank[rx]<rank[ry])swap(rx,ry);
       par[ry]=rx;
       if(rank[rx]==rank[ry])rank[rx]++;
       siz[rx]+=siz[ry];
       return true;
   }

   int size(int x){
       return siz[root(x)];
   }
};

class SegmentTree{
   public:
   vector<int>dat;
   int siz=1;

   void init(int N){
       siz=1;
       while(siz<N)siz*=2;
       dat=vector<int>(2*siz,0);
   }

   void update(int pos,int x){
       pos=pos+siz-1;
       dat[pos]=x;
       while(pos>=2){
           pos/=2;
           dat[pos]=max(dat[pos*2],dat[pos*2+1]);
       }
   }

   int query(int l,int r,int a,int b,int u){
       if(r<=a || b<=l)return -100000000;
       if(l<=a && b<=r)return dat[u];
       int m=(a+b)/2;
       int AnsL=query(l,r,a,m,u*2);
       int AnsR=query(l,r,m,b,u*2+1);
       return max(AnsL,AnsR);
   }
};

template<typename T> bool chmin(T& a, T b){if(a > b){a = b; return true;} return false;}
template<typename T> bool chmax(T& a, T b){if(a < b){a = b; return true;} return false;}

vector<int>dxs={1,0,-1,0};
vector<int>dys={0,1,0,-1};

//fixed << setprecision(10)
//A[i].erase(unique(ALL(A[i])),A[i].end());

int main(){
    int d,n,m;
    while(cin >> d >> n >> m){
        vector<int>dist(n),k(m);
        dist[0]=0;
        for(int i=1;i<n;i++)cin >> dist[i];
        rep(i,m)cin >> k[i];
        dist.push_back(d);
        ll ans=0;
        sort(ALL(dist));
        rep(i,m){
            int v=lower_bound(ALL(dist),k[i])-dist.begin();
            if(v!=0)ans+=min(dist[v]-k[i],k[i]-dist[v-1]);
            else ans+=dist[v]-k[i];
        }
        cout << ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3696
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;++i)
#define ALL(a)  (a).begin(),(a).end()
const int inf = INT_MAX;
using ll = long long;
const ll INF = 1e18;
using P = pair<int,int>;
struct Edge{
    int to;
    ll cost;
    Edge(int to,ll cost):to(to),cost(cost){}
};
using kEdge = pair<int,pair<int,int>>;
using Graph = vector<vector<int>>;
using WeightedGraph = vector<vector<Edge>>;


struct UnionFind{
   vector<int> par,rank,siz;
   UnionFind(int n) : par(n,-1),rank(n,0),siz(n,1){ }

   int root(int x){
       if(par[x]==-1)return x;
       else return par[x]=root(par[x]);
   }

   bool issame(int x,int y){
       return root(x)==root(y);
   }

   bool unite(int x,int y){
       int rx=root(x),ry=root(y);
       if(rx==ry)return false;
       if(rank[rx]<rank[ry])swap(rx,ry);
       par[ry]=rx;
       if(rank[rx]==rank[ry])rank[rx]++;
       siz[rx]+=siz[ry];
       return true;
   }

   int size(int x){
       return siz[root(x)];
   }
};

class SegmentTree{
   public:
   vector<int>dat;
   int siz=1;

   void init(int N){
       siz=1;
       while(siz<N)siz*=2;
       dat=vector<int>(2*siz,0);
   }

   void update(int pos,int x){
       pos=pos+siz-1;
       dat[pos]=x;
       while(pos>=2){
           pos/=2;
           dat[pos]=max(dat[pos*2],dat[pos*2+1]);
       }
   }

   int query(int l,int r,int a,int b,int u){
       if(r<=a || b<=l)return -100000000;
       if(l<=a && b<=r)return dat[u];
       int m=(a+b)/2;
       int AnsL=query(l,r,a,m,u*2);
       int AnsR=query(l,r,m,b,u*2+1);
       return max(AnsL,AnsR);
   }
};

template<typename T> bool chmin(T& a, T b){if(a > b){a = b; return true;} return false;}
template<typename T> bool chmax(T& a, T b){if(a < b){a = b; return true;} return false;}

vector<int>dxs={1,0,-1,0};
vector<int>dys={0,1,0,-1};

//fixed << setprecision(10)
//A[i].erase(unique(ALL(A[i])),A[i].end());

int main(){
    int d,n,m;
    while(cin >> d && cin >> n && cin >> m){
        vector<int>dist(n),k(m);
        dist[0]=0;
        for(int i=1;i<n;i++)cin >> dist[i];
        rep(i,m)cin >> k[i];
        dist.push_back(d);
        ll ans=0;
        sort(ALL(dist));
        rep(i,m){
            int v=lower_bound(ALL(dist),k[i])-dist.begin();
            if(v!=0)ans+=min(dist[v]-k[i],k[i]-dist[v-1]);
            else ans+=dist[v]-k[i];
        }
        cout << ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3728
final_rank: 12

code_snippet: #line 1 "/opt/library/template.hpp"
#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using i64 = long long;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
using u128 = unsigned __int128;
using f128 = __float128;

template <class T>
constexpr T infty = 0;
template <>
constexpr int infty<int> = 1'000'001'000;
template <>
constexpr ll infty<ll> = ll(infty<int>) * infty<int> * 2;
template <>
constexpr u32 infty<u32> = infty<int>;
template <>
constexpr u64 infty<u64> = infty<ll>;
template <>
constexpr i128 infty<i128> = i128(infty<ll>) * infty<ll>;
template <>
constexpr double infty<double> = infty<ll>;
template <>
constexpr long double infty<long double> = infty<ll>;
#define inf infty<ll>

using pi = pair<ll, ll>;
using vi = vector<ll>;
using vvi = vector<vector<ll>>;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;

#define vv(type, name, h, ...) \
  vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...)   \
  vector<vector<vector<type>>> name( \
      h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)       \
  vector<vector<vector<vector<type>>>> name( \
      a, vector<vector<vector<type>>>(       \
             b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))

#define rep1(a) for (ll _ = 0; _ < (ll)(a); ++_)
#define rep2(i, a) for (ll i = 0; i < (ll)(a); ++i)
#define rep3(i, a, b) for (ll i = a; i < (ll)(b); ++i)
#define rep4(i, a, b, c) for (ll i = a; i < (ll)(b); i += (c))
#define rrep1(a) for (ll i = (a)-1; i >= (ll)(0); --i)
#define rrep2(i, a) for (ll i = (a)-1; i >= (ll)(0); --i)
#define rrep3(i, a, b) for (ll i = (b)-1; i >= (ll)(a); --i)
#define rrep4(i, a, b, c) for (ll i = (b)-1; i >= (ll)(a); i -= (c))
#define overload4(a, b, c, d, e, ...) e
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define rrep(...) overload4(__VA_ARGS__, rrep4, rrep3, rrep2, rrep1)(__VA_ARGS__)

#define all(x) (x).begin(),(x).end()
#define len(x) (ll)(x.size())
#define elif else if
#define bit(x, i) (((x)>>(i))&1)

#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second

#define stoi stoll
#define abs llabs

#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) \
  sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()

ll popcnt(ll x) { return __builtin_popcountll(x); }
ll popcnt(u64 x) { return __builtin_popcountll(x); }
ll popcnt_mod_2(ll x) { return __builtin_parityll(x); }
ll popcnt_mod_2(u64 x) { return __builtin_parityll(x); }
ll topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
ll topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
ll lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
ll lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>
T floor(T a, T b) {
  return a / b - (a % b && (a ^ b) < 0);
}
template <typename T>
T ceil(T x, T y) {
  return floor(x + y - 1, y);
}
template <typename T>
T bmod(T x, T y) {
  return x - y * floor(x, y);
}
template <typename T>
pair<T, T> divmod(T x, T y) {
  T q = floor(x, y);
  return {q, x - q * y};
}

template<typename T> T SUM(const vector<T> &A) {
  T s = 0; for (auto &&a: A) s += a;
  return s;
}

template <typename T>
T POP(queue<T> &que) {
  T a = que.front();
  que.pop();
  return a;
}
template <typename T>
T POP(deque<T> &que) {
  T a = que.front();
  que.pop_front();
  return a;
}
template <typename T>
T POP(pq<T> &que) {
  T a = que.top();
  que.pop();
  return a;
}
template <typename T>
T POP(pqg<T> &que) {
  T a = que.top();
  que.pop();
  return a;
}
template <typename T>
T POP(vc<T> &que) {
  T a = que.back();
  que.pop_back();
  return a;
}

template <typename F>
ll binary_search(F check, ll ok, ll ng, bool check_ok = true) {
  if (check_ok) assert(check(ok));
  while (abs(ok - ng) > 1) {
    auto x = (ng + ok) / 2;
    (check(x) ? ok : ng) = x;
  }
  return ok;
}
template <typename F>
f128 binary_search_real(F check, f128 ok, f128 ng, ll iter = 100) {
  rep(iter) {
    f128 x = (ok + ng) / 2;
    (check(x) ? ok : ng) = x;
  }
  return (ok + ng) / 2;
}

// ? は -1
vc<int> s_to_vi(const string &S, char first_char) {
  vc<int> A(S.size());
  rep(i, S.size()) { A[i] = (S[i] != '?' ? S[i] - first_char : -1); }
  return A;
}

template <typename T, typename U>
vc<T> cumsum(vc<U> &A, ll off = 1) {
  ll N = A.size();
  vc<T> B(N + 1);
  rep(i, N) { B[i + 1] = B[i] + A[i]; }
  if (off == 0) B.erase(B.begin());
  return B;
}

// stable sort
template <typename T>
vi argsort(const vector<T> &A) {
  vi ids(len(A));
  iota(all(ids), 0);
  sort(all(ids),
       [&](ll i, ll j) { return (A[i] == A[j] ? i < j : A[i] < A[j]); });
  return ids;
}

// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vi &I) {
  vc<T> B(len(I));
  rep(i, len(I)) B[i] = A[I[i]];
  return B;
}

template<typename T> inline bool chmax(T &a, T b) {return ((a<b)?(a=b,true):(false));}
template<typename T> inline bool chmin(T &a, T b) {return ((a>b)?(a=b,true):(false));}

inline void wt(const char c) { cout << c; }
inline void wt(const string s) { cout << s; }
inline void wt(const char *s) { cout << s; }

template <typename T>
void wt_integer(T x) {
  if (x < 0) { cout << (i64)(x); }
  else { cout << (u64)(x); }
}
template <typename T>
void wt_real(T x) {
  cout << fixed << setprecision(15) << (long double)(x);
}

inline void wt(int x) { wt_integer(x); }
inline void wt(ll x) { wt_integer(x); }
inline void wt(i128 x) { wt_integer(x); }
inline void wt(u32 x) { wt_integer(x); }
inline void wt(u64 x) { wt_integer(x); }
inline void wt(u128 x) { wt_integer(x); }
inline void wt(double x) { wt_real(x); }
inline void wt(long double x) { wt_real(x); }
inline void wt(f128 x) { wt_real(x); }

template <class T, class U>
void wt(const pair<T, U> val) {
  wt(val.first); wt(' '); wt(val.second);
}
template <size_t N = 0, typename T>
void wt_tuple(const T t) {
  if constexpr (N < std::tuple_size<T>::value) {
    if constexpr (N > 0) { wt(' '); }
    const auto x = std::get<N>(t);
    wt(x);
    wt_tuple<N + 1>(t);
  }
}
template <class... T>
void wt(tuple<T...> tpl) {
  wt_tuple(tpl);
}
template <class T, size_t S>
void wt(const array<T, S> val) {
  auto n = val.size();
  for (size_t i = 0; i < n; i++) {
    if (i) wt(' ');
    wt(val[i]);
  }
}
template <class T>
void wt(const vector<T> val) {
  auto n = val.size();
  for (size_t i = 0; i < n; i++) {
    if (i) wt(' ');
    wt(val[i]);
  }
}

void print() { wt('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
  wt(head);
  if (sizeof...(Tail)) wt(' ');
  print(forward<Tail>(tail)...);
}

void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
void onez(bool t = 1) { print(t ? 1 : 0); }
#define endl '\n'
#define dump(x) {cerr << #x " = " << x << '\n';}
#line 2 "main.cpp"

int solve();
int main() {
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  while (!solve()) {}
  return 0;
}

int solve() {
  ll D, N, M, k;
  cin >> D;
  if (D == 0) return 1;
  cin >> N >> M;
  vi d(N+1);
  rep(i, 1, N) cin >> d[i];
  d[0] = 0;
  d[N] = D;
  sort(all(d));
  ll ans = 0;
  rep(M) {
    cin >> k;
    ll lb = LB(d, k);
    ll dist = d[lb] - k;
    if (lb >= 1) chmin(dist, k-d[lb-1]);
    ans += dist;
  }
  print(ans);
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3896
final_rank: 14

code_snippet: #ifdef LOCAL
#include "algo/debug.h"
#else
#define _debug(...) 42
#endif

#include <bits/stdc++.h>

void solve(unsigned int len) {
	std::size_t n, m;
	std::cin >> n >> m;

	std::vector<unsigned int> d(n + 1, 0);
	for (std::size_t i = 1; i < n; ++i) std::cin >> d[i];
	d[n] = len;
	std::sort(d.begin(), d.end());

	auto get_nearest_shops_dist = [&d, n](unsigned int k) {
		unsigned int left = 0, right = n;
		while (right - left > 1) {
			unsigned int middle = (left + right) / 2;
			if (d[middle] <= k) left = middle;
			else right = middle;
		}
		return std::min(k - d[left], d[right] - k);
	};

	unsigned long long result = 0;

	while (m--) {
		unsigned int k;
		std::cin >> k;

		result += get_nearest_shops_dist(k);
	}

	std::cout << result << '\n';
}

int main() {
	std::cin.tie(nullptr);
	std::ios::sync_with_stdio(false);

	while (true) {
		unsigned int len;
		std::cin >> len;

		if (len == 0) break;

		solve(len);
	}
}
accuracy: 1
time_ms: 10
memory_kb: 3500
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
int d, n, m;
int main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    while(cin >> d && d){
        cin >> n >> m;
        vector<int> vet;
        vet.push_back(0);
        for(int i = 0; i < n-1; ++ i){
            int x;
            cin >> x;
            vet.push_back(x);
        }
        vet.push_back(d);
        sort(vet.begin(), vet.end());
        long long res = 0;
        for(int i = 0; i < m; ++ i){
            int x;
            cin >> x;
            vector<int>::iterator p = upper_bound(vet.begin(),  vet.end(), x);
            res += min(*p - x, x - *(p-1));
        }
        cout << res << "\n";
    }
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3496
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
int main(){
    while(true){
long long d,n,m;cin >>d;
if(d == 0)return 0;
cin >>n>>m;
vector<unsigned long long>v;
v.push_back(0);
for(long long i = 1;i < n;i++){
    long long u;cin >>u;
    v.push_back(u);
}
v.push_back(d);
long long ans = 0;
sort(v.begin(),v.end());
for(long long i = 0;i < m;i++){
    long long u;cin >>u;
    long long y = lower_bound(v.begin(),v.end(),u)-v.begin();
    ans += min(v[y]-u,u-v[y-1]);
}
cout <<ans<<"\n";
    }
}
accuracy: 1
time_ms: 30
memory_kb: 4012
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
int main(){
    while(true){
long long d,n,m;cin >>d;
if(d == 0)return 0;
cin >>n>>m;
vector<unsigned int>v;
v.push_back(0);
for(long long i = 1;i < n;i++){
    long long u;cin >>u;
    v.push_back(u);
}
v.push_back(d);
long long ans = 0;
sort(v.begin(),v.end());
for(long long i = 0;i < m;i++){
    long long u;cin >>u;
    long long y = lower_bound(v.begin(),v.end(),u)-v.begin();
    ans += min(v[y]-u,u-v[y-1]);
}
cout <<ans<<"\n";
    }
}
accuracy: 1
time_ms: 30
memory_kb: 3620
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
int main(){
    while(true){
long long d,n,m;cin >>d;
if(d == 0)return 0;
cin >>n>>m;
vector<int>v;
v.push_back(0);
for(long long i = 1;i < n;i++){
    long long u;cin >>u;
    v.push_back(u);
}
v.push_back(d);
long long ans = 0;
sort(v.begin(),v.end());
for(long long i = 0;i < m;i++){
    long long u;cin >>u;
    long long y = lower_bound(v.begin(),v.end(),u)-v.begin();
    ans += min(v[y]-u,u-v[y-1]);
}
cout <<ans<<"\n";
    }
}
accuracy: 1
time_ms: 30
memory_kb: 3756
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vl = vector<ll>;
using vvl = vector<vl>;
using pl = pair<ll,ll>;
using vp = vector<pl>;
#define rep(i,n) for(ll i=0;i<(ll)(n);++i)
#define reps(i,s,n) for(ll i=(s);i<(ll)(n);++i)
#define rep1(i,n) for(ll i=1;i<=(ll)(n);++i)
template<typename T>inline bool chmax(T &a,T b){return a<b?a=b,true:false;}
template<typename T>inline bool chmin(T &a,T b){return a>b?a=b,true:false;}
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define be(v) (v).begin(),(v).end()
const long long INF = 1e18;
#ifdef DEBUG
#include <debug.hpp>
#endif

bool solve(){
	#ifdef DEBUG
	cout << "--- Input ---" << endl;
	#endif
	//cin.unsetf(ios::skipws);
	ll D,N,M;cin>>D>>N>>M;
	if(D==0)return false;
	vl E(N),W(N),C(M);
	E.at(0)=0;W.at(0)=0;
	reps(n,1,N){
		cin>>E.at(n);
		W.at(n)=D-E.at(n);
	}
	rep(m,M)cin>>C.at(m);
	sort(be(E));
	sort(be(W));
	sort(be(C));
	#ifdef DEBUG
	show(D,N,M,E,W,C);
	cout << "--- Logic ---" << endl;
	#endif
	auto cal=[&](vl v,ll c){
		ll ret;
		auto i=lower_bound(be(v),c)-v.begin();
		if(i==N) ret=D-c;
		else ret=v.at(i)-c;
		return ret;
	};
	ll ans=0;
	rep(m,M){
		ll a1=cal(E,C.at(m));
		ll a2=cal(W,D-C.at(m));
		ans+=min(a1,a2);
	#ifdef DEBUG
		show("m=",m,"a1=",a1,"a2=",a2,"ans=",ans,'\n');
	#endif
	}
	#ifdef DEBUG
	cout << "--- Answer ---" << endl;
	#endif
	cout<<ans<<endl;
	return true;
}
int main(){
	#ifdef DEBUG
	cout << "--- Main ---" << endl;
	#endif
	//solve();
	while(solve());
	return 0;
}
//cout << fixed << setprecision(9);
accuracy: 1
time_ms: 480
memory_kb: 5408
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;




int main(){
    while(1){
    int D,N,M;
    cin>>D;
    if(D==0)return 0;
    cin>>N>>M;

    vector<int> S(N+1,0);
    for(int i=1;i<N;i++)cin>>S[i];
    S[N]=D;
    int an=0;
    sort(S.begin(),S.end());
    for(int i=0;i<M;i++){
        int a;
        cin>>a;
        int res=D;
        auto p=upper_bound(S.begin(),S.end(),a);
        res=min(res,*p-a);
        p--;
        res=min(res,a-*p);
        an+=res;
    }
    cout<<an<<endl;
    }
}
accuracy: 1
time_ms: 30
memory_kb: 3532
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long;
using ull = unsigned long long;
using ld = long double;
template<class t> using vc = vector<t>;
template<class t> using vvc = vc<vc<t>>;
using pi = pair<int,int>;
using vi = vc<int>;
using vvi = vvc<int>;

#define rep(i,a,b) for (int i = (a); i < (b); i++)
#define irep(i,a,b) for (int i = (a); i > (b); i--)
#define all(a) a.begin(),a.end()
#define print(n) cout << n << '\n'
#define pritn(n) print(n)
#define printv(n,a) {copy(all(n),ostream_iterator<a>(cout," ")); cout<<"\n";}
#define rup(a,b) (a+b-1)/b
#define input(A,N) rep(i,0,N) cin>>A[i]
#define chmax(a,b) a = max(a,b)
#define chmin(a,b) a = min(a,b)


int main(){
    cout << fixed << setprecision(15);
    
    while(1){
    ll d,n,m;
    cin>>d;
    if(d==0) break;
    cin>>n>>m;
    vc<ll> ds(n+1);
    ds[0] = 0;
    rep(i,1,n){
        ll a;cin>>a;
        ds[i] = a;
    }
    ds[n] = d;
    sort(all(ds));
    ll sum = 0;
    rep(i,0,m){
        ll k;cin>>k;
        if(k==0){
            continue;
        }
        auto itr = upper_bound(all(ds),k);
        sum += min(abs(k-*itr),abs(k-*(itr-1)));
        // cout << k << " "<<*itr<<" "<<*(itr-1)<<endl;
    }
    print(sum);

    }

    
    //system("pause");
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3720
final_rank: 11

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <set>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)

template<class T>
using vi = vector<T>;

template<class T>
using vii = vector<vi<T>>;

template<class T>
using viii = vector<vii<T>>;

using pii = pair<int, int>;

int main()
{
    int d, n, m;
    while (cin >> d, d) {
        cin >> n >> m;
        vi<int> dist(n);
        rep(i, n - 1) cin >> dist[i];
        dist.push_back(d);
        sort(dist.begin(), dist.end());
        int k = 0;
        int ans = 0;
        rep(i, m) {
            cin >> k;
            auto pos = upper_bound(dist.begin(), dist.end(), k) - dist.begin();
            ans += min(dist[pos] - k, k - dist[pos - 1]);
        }
        cout << ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3524
final_rank: 4

code_snippet: #include "bits/stdc++.h"

#define REP(i,num) for(ll i=0;i<(num);++i)
#define FOR(i,c,num) for(ll (i)=(c);(i)<(num);++(i))
#define LOOP(i) while(i--)
#define ALL(c) c.begin(),c.end()
#define PRINTALL(c) for(auto pitr=c.begin();pitr!=c.end();++pitr){cout<<*pitr;if(next(pitr,1)!=c.end())cout<<' ';}cout<<endl;
#define PAIRCOMP(c,comp) [](const pair<ll,ll>& lhs,const pair<ll,ll>& rhs){return lhs.c comp rhs.c;}

using namespace std;
using ll = long long;
using ull = unsigned long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;

constexpr ll atcoder_mod = 1e9+7;

template<typename T=ll>
T in(){ T x; cin >> x; return (x); }
template<typename T=ll,typename C=vector<T>>
C vecin(int N){ C x(N);REP(i,N){ x[i]=in<T>(); }return x; }
template<typename T=ll,size_t N>
array<T,N> arrin(){array<T,N> x;REP(i,N){ x[i]=in<T>(); }return x;}

void vout(){ cout << endl; }
template<typename Head,typename... Tail>
void vout(Head&& h,Tail&&... t){ cout << ' ' << h;vout(forward<Tail>(t)...); }
void out(){ cout << endl; }
template<typename Head,typename... Tail>
void out(Head&& h,Tail&&... t){ cout << h;vout(forward<Tail>(t)...); }

template<typename T>
bool chmax(T& a,T b){ if(a<b){ a=b;return true; }return false; }
template<typename T>
bool chmin(T& a,T b){ if(a>b){ a=b;return true; }return false; }

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout<<fixed<<setprecision(10);

	while(true){
		ll D=in();
		if(!D) break;

		ll N=in(),M=in();
		vll S(N);
		S[0]=0;
		FOR(i,1,N){
			S[i]=in();
		}
		sort(ALL(S));

		ll L=0;
		LOOP(M){
			ll Q=in();
			auto res = upper_bound(ALL(S),Q);
			if(res==S.begin()){
				L += 0;
			}
			else if(res==S.end()){
				L += min(Q-S.back(),D-Q);
			}
			else{
				L += min(*res-Q,Q-*(res-1));
			}
		}
		out(L);
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3756
final_rank: 9

code_snippet: //Source.cpp
//いつもの
#ifdef LOCAL
#define _USE_MATH_DEFINES
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<list>
#include<array>
#include<algorithm>
#include<numeric>
#include<cmath>
#include<climits>
#include<iomanip>
#include<cctype>
#include<sstream>
#include<regex>
#include<bitset>
#include<random>
#include<complex>
#include<cassert>
#else
#include<bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#ifdef ONLINE_JUDGE
#include<atcoder/all>
using namespace atcoder;
#else
#define gcd __gcd
#define lcm __detail::__lcm
#endif
#endif
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#ifdef LOCAL
//*
#include<atcoder/all>
using namespace atcoder;
//*/
unsigned popcount(unsigned x){
	return __popcnt(x);
}
unsigned popcountll(ull x){
	return __popcnt64(x);
}
unsigned parity(unsigned x){
	return popcount(x)%2;
}
unsigned parityll(ull x){
	return popcountll(x)%2;
}
unsigned clz(unsigned x){
	if(x==0)
		throw;
	unsigned cnt=__lzcnt(x);
	return cnt;
}
unsigned clzll(ull x){
	if(x==0)
		throw;
	unsigned cnt=__lzcnt64(x);
	return cnt;
}
unsigned ctz(unsigned x){
	if(x==0)
		throw;
	x&=~x+1;
	unsigned cnt=0;
	if(x&0xffff0000)
		cnt|=16;
	if(x&0xff00ff00)
		cnt|=8;
	if(x&0xf0f0f0f0)
		cnt|=4;
	if(x&0xcccccccc)
		cnt|=2;
	if(x&0xaaaaaaaa)
		cnt|=1;
	return cnt;
}
unsigned ctzll(ull x){
	if(x==0)
		throw;
	x&=~x+1;
	unsigned cnt=0;
	if(x&0xffffffff00000000)
		cnt|=32;
	if(x&0xffff0000ffff0000)
		cnt|=16;
	if(x&0xff00ff00ff00ff00)
		cnt|=8;
	if(x&0xf0f0f0f0f0f0f0f0)
		cnt|=4;
	if(x&0xcccccccccccccccc)
		cnt|=2;
	if(x&0xaaaaaaaaaaaaaaaa)
		cnt|=1;
	return cnt;
}
unsigned ffs(unsigned x){
	if(x==0)
		return 0;
	return ctz(x)+1;
}
unsigned ffsll(ull x){
	if(x==0)
		return 0;
	return ctzll(x)+1;
}
#define __builtin_popcount popcount
#define __builtin_popcountll popcountll
#define __builtin_parity parity
#define __builtin_parityll parityll
#define __builtin_clz clz
#define __builtin_clzll clzll
#define __builtin_ctz ctz
#define __builtin_ctzll ctzll
#define __builtin_ffs ffs
#define __builtin_ffsll ffsll
#endif
constexpr int mod=1e9+7;
constexpr int Mod=998244353;
constexpr int inf=mod;
constexpr ll linf=(ll)mod*mod;
struct fastio{
	fastio(){
		cin.tie(0);
		ios::sync_with_stdio(0);
		cout<<fixed<<setprecision(20);
	};
}fio;
template<class T>
bool chmax(T&a,const T&b){
	if(a<b){
		a=b;
		return 1;
	}
	return 0;
}
template<class T>
bool chmin(T&a,const T&b){
	if(a>b){
		a=b;
		return 1;
	}
	return 0;
}
int main(){
	int d[100001],n,m,k;
	while(cin>>d[0]>>n>>m){
		for(int i=1;i<n;i++)
			cin>>d[i];
		d[n]=0;
		sort(d,d+n+1);
		ll ans=0;
		for(int i=0;i<m;i++){
			cin>>k;
			auto it1=*prev(upper_bound(d,d+n+1,k)),it2=*lower_bound(d,d+n+1,k);
			ans+=min(it2-k,k-it1);
		}
		cout<<ans<<endl;
	}
}
accuracy: 1
time_ms: 10
memory_kb: 3748
final_rank: 7

code_snippet: //#include <atcoder/all>
#include <bits/stdc++.h>
using namespace std;
using lint = long long;
constexpr lint mod = 1e9 + 7;
#define all(x) begin(x), end(x)
#define bitcount(n) __builtin_popcountll((lint)(n))
#define fcout cout << fixed << setprecision(15)
#define highest(x) (63 - __builtin_clzll(x))
#define rep(i, n) for(int i = 0; i < int(n); i++)
#define rep2(i, l, r) for(int i = int(l); i < int(r); i++)
#define repr(i, n) for(int i = int(n) - 1; i >= 0; i--)
#define repr2(i, l, r) for(int i = int(r) - 1; i >= int(l); i--)
constexpr int inf9 = 1e9; constexpr lint inf18 = 1e18;
inline void Yes(bool condition){ if(condition) cout << "Yes" << endl; else cout << "No" << endl; }
template<class itr> void array_output(itr start, itr goal){ for(auto i = start; i != goal; i++) cout << (i == start ? "" : " ") << (*i); cout << endl; }
template<class itr> void cins(itr first, itr last){ for(auto i = first; i != last; i++){ cin >> (*i); } }
template<class T> T gcd(T a, T b){ if(b) return gcd(b, a % b); else return a; }
template<class T> T lcm(T a, T b){ return a / gcd(a, b) * b; }
template<class T> bool chmax(T &a, const T &b){ if(a < b){ a = b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b){ if(b < a){ a = b; return 1; } return 0; }
inline int has(lint i, int j){ return (i >> j) & 1; }
int dy[4] = {1, 0, -1, 0}; int dx[4] = {0, 1, 0, -1};
bool is_inside(lint y, lint x, lint H, lint W){ return (0 <= y && y < H && 0 <= x && x < W); }

struct io_init {
    io_init() {
        cin.tie(nullptr); cout.tie(nullptr);
        std::ios::sync_with_stdio(false);
    }
} io_init;

void solve(){
    lint d;
    int n, q;
    cin >> d;
    if(d == 0) exit(0);
    cin >> n >> q;
    
    vector<lint> shop(n, 0);
    rep2(i, 1, n){
        lint di;
        cin >> di;
        shop[i] = di;
    }
    sort(all(shop));
    shop.push_back(d);
    
    lint ans = 0;
    rep(_, q){
        lint x;
        cin >> x;
        
        int r_pos = int(lower_bound(all(shop), x) - shop.begin());
        lint dist = abs(x - shop[r_pos]);
        
        if(r_pos > 0){
            chmin(dist, abs(x - shop[r_pos - 1]));
        }
        
        ans += dist;
//        cout << dist << endl;
    }
    
    cout << ans << endl;
}

int main(){
    while(true) solve();
}
accuracy: 1
time_ms: 10
memory_kb: 4560
final_rank: 19