#include <bits/stdc++.h>
#define ff(i,a,b) for(int (i) = (a); (i) <= (b); ++(i))
//#include "boxes.h"
#define maxn 10000005
using namespace std;
typedef long long ll;
int n,k;
int niz[maxn];
int d;
set<int>s;
ll dist(int l, int r){
if(l > r)swap(l, r);
ll res = min(r - l, l + d - r);
return res;
}
long long delivery(int N, int K, int L, int p[]) {
n = N, k = K, d = L;
ff(i,1,n)niz[i] = p[i - 1];
ff(i,1,n){
s.insert(niz[i]);
}
int poz = 0;
int cap = k;
ll res = 0;
while(1){
if(s.empty())break;
//cout << poz << " ";
//for(auto c:s)cout << c << " ";
//cout << "\n\n";
if(cap == 0){
res += dist(poz, 0);
poz = 0;
cap = k;
continue;
}
int levi = *s.begin();
int desni = *s.rbegin();
int dist1 = dist(levi, poz);
int dist2 = dist(desni, poz);
int najbliza;
if(dist1 < dist2)najbliza = levi;
else najbliza = desni;
//cout << dist(najbliza, 0) << endl;
if(poz == 0){
res += dist(najbliza, poz);
poz = najbliza;
cap--;
s.erase(najbliza);
continue;
}
if(abs(najbliza - poz) + dist(najbliza, 0) <= dist(najbliza,0) + dist(poz,0)){
res += abs(najbliza - poz);
poz = najbliza;
cap--;
s.erase(najbliza);
}
else{
res += dist(poz, 0);
poz = 0;
}
}
res += dist(poz, 0);
return res;
}
int aa[105];
int N,K,L;
int main(){
cin >> N >> K >> L;
ff(i,0,N - 1)cin >> aa[i];
cout << delivery(N,K,L,aa);
return 0;
}
/*
3 2 8
1 2 5
*/
Compilation message
boxes.cpp: In function 'long long int delivery(int, int, int, int*)':
boxes.cpp:39:25: warning: conversion to 'int' from 'll {aka long long int}' may alter its value [-Wconversion]
int dist1 = dist(levi, poz);
~~~~^~~~~~~~~~~
boxes.cpp:40:25: warning: conversion to 'int' from 'll {aka long long int}' may alter its value [-Wconversion]
int dist2 = dist(desni, poz);
~~~~^~~~~~~~~~~~
/tmp/ccU5tkc8.o: In function `main':
grader.c:(.text.startup+0x0): multiple definition of `main'
/tmp/ccais3bu.o:boxes.cpp:(.text.startup+0x0): first defined here
collect2: error: ld returned 1 exit status