#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; template struct BinaryIndexedTree { private: int N; vector node; public: BinaryIndexedTree() : N(0) {} BinaryIndexedTree(int N) : N(N), node(N) {} void add(int pos,T x) { assert(0 <= pos && pos < N); pos++; while(pos <= N) { node[pos-1] += x; pos += pos & -pos; } } T sum(int l,int r) { assert(0 <= l && l <= N && r <= N); return sum(r) - sum(l); } T sum(int r) { T ret = 0; while(r > 0) { ret += node[r-1]; r -= r & -r; } return ret; } T sum() {return sum(N);} }; void Main() { int N,K; long long L,U; cin >> N >> K >> L >> U; vector A(N); for(int i = 0;i < N;i++) { cin >> A[i]; } sort(A.begin(),A.end()); vector S(N + 1); for(int i = 0;i < N;i++) { S[i + 1] = S[i] + A[i] / K; } long long ans = (long long)1e18; int ri = 0; BinaryIndexedTree rcnt(K),lcnt(K); for(int i = 0;i < N;i++) { rcnt.add(A[i] % K,1); } for(int i = 0;i < N;i++) { while(ri < N && A[ri] <= A[i] + U - L) { rcnt.add(A[ri] % K,-1); ri++; } long long cur = 0; { //left cur += A[i] / K * i - S[i]; cur += lcnt.sum(0,A[i] % K); } { //right cur += S[N] - S[ri]; cur -= (A[i] + U - L) / K * (N - ri); cur += rcnt.sum((A[i] + U - L) % K + 1,K); } lcnt.add(A[i] % K,1); ans = min(ans,cur); } int li = N; for(int i = N;i--;) { while(li > 0 && A[li - 1] >= A[i] - U + L) { li--; lcnt.add(A[li] % K,-1); } long long cur = 0; { //right cur += S[N] - S[i + 1]; cur -= A[i] / K * (N - i - 1); cur += rcnt.sum(A[i] % K + 1,K); } if(li > 0) { //left cur -= S[li]; cur += (A[i] - U + L) / K * li; cur += lcnt.sum(0,(A[i] - U + L) % K); } rcnt.add(A[i] % K,1); ans = min(ans,cur); } cout << ans << "\n"; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt = 1; /* cin >> tt; */ while(tt--) Main(); }