jiahuimbzuai/CoQuIR huggingface dataset:
//  [javascript]
Array.prototype.insertOrderedDesc = function(item) {
	//if(this.length == 0) { this.push(item); return; }
	var range = Math.floor(this.length / 2);
	var dir = 1;
	var index = 0;
	while(range > 1) {
		index += dir * range;
      	var sub = this[index] - item;
		if(sub > 0) { dir = 1;}
		else if(sub < 0) { dir = -1; } else {
			this.splice(index, 0, item); return;
		}
		range = Math.floor(range / 2)
	}
	for(;0 <= index && index < this.length; index += dir) {
		if(dir * (this[index] - item) < 0) break;
	}	
	this.splice(index + (dir < 0 ? 1 : 0), 0, item);
};

var input = require('fs').readFileSync('/dev/stdin', 'utf8').split("\n").map((s)=>{return s.split(" ");});
var N = input[0][0]-0;
var Days = input[0][1]-0;
input.shift();

var works = new Array(Days);
input.forEach((item) => {
	var DFI = item[0]-0;
	if(works[DFI] == undefined) works[DFI] = [];
	works[DFI].push(item[1]-0);
});

var G = [];
var D = 1;
var Gain = 0;

var insertG = (income) => {
	var index = 0;
	for(; index < G.length; index++) {
		if(G[index] < income) break;
	}
	G.splice(index, 0, income);
};

for(;D <= Days; D++) {
	if(works[D] !== undefined) {
		works[D].forEach((income) => { G.insertOrderedDesc(income); });
	}
	if(G.length > 0) {
		Gain += G[0];
		G.shift();
	}
}
console.log(Gain);
//  [javascript]
"use strict";
    
class PriorityQueue {
  constructor() {
    this.heap = [];
  }
 
  push(item) {
    let heap = this.heap;
    let i = heap.length++;
    let j;
 
    while(i) {
      j = Math.floor((i - 1) / 2);
      if(heap[j] <= item) break;
      heap[i] = heap[j]
      i = j;
    }
 
    heap[i] = item;
  }
 
  pop() {
    let heap = this.heap;
    let top = heap[0];
    let popped = heap.pop();
 
    let i = 0;
    let k = Math.floor(heap.length / 2);
    let j;
 
    while(i < k) {
      j = (i * 2) + 1;
      if(heap[j+1] < heap[j]) ++j;
 
      if(popped <= heap[j]) break;
 
      heap[i] = heap[j];
 
      i = j;
    }
 
    if(heap.length) {
      heap[i] = popped;
    }
 
    return top;
  }
 
  size() {
    return this.heap.length;
  }
 
  top() {
    return this.heap[0];
  }
}

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const M = parseInt(arg[0].split(" ")[1]);
    
    let AB = arg.slice(1, N + 1).map(n=>n.split(" ").map(l=>parseInt(l)));
    AB.push([1e9, 0]);
    AB.sort((a,b)=>a[0]-b[0]);
    
    let answer = 0;
    let j = 0;
    
    let pq = new PriorityQueue();
    
    for(let i=1; i<=M; i++) {
        while(AB[j][0] <= i) {
            pq.push(-AB[j][1]);
            j++;
        }
        
        if(pq.size() > 0) {
            answer += pq.pop();
        }
    }
    
    console.log(0 - answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}
var PriorityQueue=(function(){
  function f(){return new PriorityQueue();}
  function PriorityQueue(){
    this.heap=[];
  }
  PriorityQueue.prototype.push=function(x){
    var h=this.heap,i=h.length++,j;
    while(i){
      j=i-1>>1;
      if(h[j]<=x)break;
      h[i]=h[j],i=j;
    }
    h[i]=x;
  };
  PriorityQueue.prototype.pop=function(){
    var h=this.heap,r=h[0],x=h.pop(),l=h.length;
    if(l===0)return r;
    var i=0,j,k=l-->>1;
    while(i<k){
      j=(i<<1)+1;
      if(j<l&&h[j+1]<h[j])j++;
      if(x<=h[j])break;
      h[i]=h[j],i=j;
    }
    h[i]=x;
    return r;
  };
  return f;
})();

console.log(main());
function main(){
  var n = o.a();
  var m = o.a();
  var a = o.m(n);
  a.push([1e9,0]);
  a.sort((a,b)=>a[0]-b[0]);
  var ans = 0, j = 0;
  var pq = PriorityQueue();
  for(var i = 1; i <= m; i++){
    while(a[j][0] <= i){
      pq.push(-a[j++][1]);
    }
    if(pq.heap.length)ans -= pq.pop();
  }
  return ans;
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var pq []int

func push(x int) {
	p := sort.Search(len(pq), func(i int) bool { return pq[i] <= x })
	if p == len(pq) {
		pq = append(pq, x)
		return
	}
	pq = append(pq[:p+1], pq[p:]...)
	pq[p] = x
}

func pop() int {
	if len(pq) == 0 {
		return 0
	}

	ans := pq[0]
	pq = pq[1:]
	return ans
}

func main() {
	var n, m int
	fmt.Scan(&n, &m)

	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	ts := make(map[int][]int)
	for i := 0; i < n; i++ {
		sc.Scan()
		a, _ := strconv.Atoi(sc.Text())
		sc.Scan()
		b, _ := strconv.Atoi(sc.Text())
		ts[a] = append(ts[a], b)
	}

	pq = make([]int, 0, n)
	ans := 0
	for i := m - 1; i >= 0; i-- {
		if _, ok := ts[m-i]; ok {
			for _, v := range ts[m-i] {
				push(v)
			}
		}
		ans += pop()
	}
	fmt.Println(ans)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var pq []int

func push(x int) {
	p := sort.Search(len(pq), func(i int) bool { return pq[i] <= x })
	if p == len(pq) {
		pq = append(pq, x)
		return
	}
	pq = append(pq[:p+1], pq[p:]...)
	pq[p] = x
}

func pop() int {
	if len(pq) == 0 {
		return 0
	}

	ans := pq[0]
	pq = pq[1:]
	return ans
}

func main() {
	var n, m int
	fmt.Scan(&n, &m)

	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	ts := make(map[int][]int)
	for i := 0; i < n; i++ {
		sc.Scan()
		a, _ := strconv.Atoi(sc.Text())
		sc.Scan()
		b, _ := strconv.Atoi(sc.Text())
		ts[a] = append(ts[a], b)
	}

	pq = make([]int, 0, n)
	ans := 0
	for i := 1; i <= m; i++ {
		if _, ok := ts[i]; ok {
			for _, v := range ts[i] {
				push(v)
			}
		}
		ans += pop()
	}
	fmt.Println(ans)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var pq []int

func push(x int) {
	p := sort.Search(len(pq), func(i int) bool { return pq[i] <= x })
	if p == len(pq) {
		pq = append(pq, x)
		return
	}
	pq = append(pq[:p+1], pq[p:]...)
	pq[p] = x
}

func pop() int {
	if len(pq) == 0 {
		return 0
	}

	ans := pq[0]
	pq = pq[1:]
	return ans
}

type task struct{ a, b int }
type tasks []task

func (t tasks) Len() int           { return len(t) }
func (t tasks) Swap(i, j int)      { t[i], t[j] = t[j], t[i] }
func (t tasks) Less(i, j int) bool { return t[i].a < t[j].a }

func main() {
	var n, m int
	fmt.Scan(&n, &m)

	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	ts := tasks(make([]task, n))
	for i := range ts {
		sc.Scan()
		ts[i].a, _ = strconv.Atoi(sc.Text())
		sc.Scan()
		ts[i].b, _ = strconv.Atoi(sc.Text())
	}
	sort.Sort(ts)

	pq = make([]int, 0, n)
	ans := 0
	ti := 0
	for i := 1; i <= m; i++ {
		for ti < len(ts) && ts[ti].a == i {
			push(ts[ti].b)
			ti++
		}
		ans += pop()
	}
	fmt.Println(ans)
}
//  [ruby]
N, M = gets.split.map(&:to_i)
Job = Struct.new(:day, :money) do
  def <=>(other)
    n = other.money <=> money
    n == 0 ? day <=> other.day : n
  end
end
jobs = $<.read.split(?\n).map {|x| Job.new(*x.split.map(&:to_i))}.sort!

days = [*1..M]
sum_money = jobs.reduce(0) do |sum, job|
  next(sum) unless i = days.bsearch_index {|day| day >= job.day}
  days.delete_at(i)
  sum + job.money
end

puts sum_money
//  [ruby]
n, m = gets.strip.split.map(&:to_i)
abs = n.times.map { gets.strip.split.map(&:to_i) }

abs.sort! {|a, b| (b[1] <=> a[1]).nonzero? || b[0] <=> a[0]}
days = (1..m).to_a

ans = 0
abs.each do |day, reward|
    index = days.bsearch_index { |d| d >= day }
    if index
        days.delete_at(index)
        ans += reward
    end
end

puts ans
//  [ruby]
n, m = gets.split.map(&:to_i)

available_day = []
works = []
n.times { works << gets.split.map(&:to_i) }

(1..m).each{|i| available_day << i}

works.sort!{|a, b| (b[1] <=> a[1]).nonzero? || b[0] <=> a[0] }

sum = 0
works.each do |day, salary|
  if index = available_day.bsearch_index{|e| e >= day }
    available_day.delete_at(index)
    sum += salary
  end
end

p sum
//  [rust]
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };

    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, [ $t:tt ]) => {
        {
            let len = read_value!($next, usize);
            (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
        }
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        n: usize,
        m: usize,
        ab: [(usize, usize); n],
    }
    let mut ab = ab;
    ab.sort_by_key(|row| row.0);

    let mut v = Vec::with_capacity(n);
    let mut index = 0;
    let mut total = 0;
    for remains in 1..m + 1 {
        while index < n && ab[index].0 <= remains {
            let b = ab[index].1;
            let j = match v.binary_search(&b) {
                Ok(j) => j,
                Err(j) => j,
            };
            v.insert(j, b);
            index += 1;
        }
        if let Some(b) = v.pop() {
            total += b;
        }
    }
    println!("{}", total);
}
//  [python]
def resolve():
    n = int(input())
    k = int(input())
    x = list(map(int, input().split()))
    ans = sum([min(2 * xi, 2 * (k - xi)) for xi in x])
    print(ans)
        

if __name__ == "__main__":
    resolve()
//  [python]
n = int(input())
k = int(input())
l = list(map(int,input().split()))
s=0
for i in range(n):
    s+=min(l[i] - 0,k - l[i])
s*=2
print(s)
//  [python]
input();k=int(input());print(2*sum(map(lambda x:min(int(x),k-int(x)),input().split())))
//  [python]
import numpy as np
N = int(input())
K = int(input())
x = np.fromiter(map(int, input().split()), dtype=np.int)
A = x
B = np.abs(x - K*np.ones(N))
C = np.minimum(A,B)
print(int(C.sum()*2))
//  [python]
import sys
import numpy as np 

I = np.array(sys.stdin.read().split(), dtype=np.int64)
n, k = I[:2]
x = I[2:]

def main():
    d = np.minimum(x, k - x)
    return np.sum(d) * 2

if __name__ == '__main__':
    ans = main()
    print(ans)
//  [python]
# region header
import sys
import math
from bisect import bisect_left, bisect_right, insort_left, insort_right
from collections import defaultdict, deque, Counter
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from heapq import heappop, heappush
from itertools import accumulate, groupby, product, permutations, combinations, combinations_with_replacement
from math import ceil, floor, factorial, log, sqrt, sin, cos
from operator import itemgetter
from string import ascii_lowercase, ascii_uppercase, digits
sys.setrecursionlimit(10**7)
rs = lambda: sys.stdin.readline().rstrip()
ri = lambda: int(rs())
rf = lambda: float(rs())
rs_ = lambda: [_ for _ in rs().split()]
ri_ = lambda: [int(_) for _ in rs().split()]
rf_ = lambda: [float(_) for _ in rs().split()]
INF = float('inf')
MOD = 10 ** 9 + 7
PI = math.pi
# endregion
N = ri()
K = ri()
x = ri_()
ans = 0
for i in range(N):
    ans += min(x[i], K - x[i]) * 2
print(ans)
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			String str = br.readLine();
			int N = Integer.parseInt(str);
			str = br.readLine();
			int K = Integer.parseInt(str);
			str = br.readLine();
			String[] s = str.split(" ",0);
			int total = 0;
			for(int i = 0; i < s.length;i++) {
				int x = Integer.parseInt(s[i]);
				int dis = Math.min(x, K -x);
				total += dis;
			}

			System.out.println(total*2);
//			long max  = 1000000007;
		}catch (Exception e) {
			System.exit(0);
		}
	}

}
//  [java]
import java.io.*;
import java.util.*;
class Main{
	static final long MOD = 1_000_000_007; // 10^9+7
    static final int MAX = 2_147_483_646; // intMax 
    static final int INF = 1_000_000_000; // 10^9  
    public static void main(String[] args) throws Exception {
		hayami saori = new hayami();
		int n = saori.saori_hayami();
		int k = saori.saori_hayami();
		int[] x = new int[n];
		for(int i = 0;i < n;i++){
			x[i] = saori.saori_hayami();
		}
		int ans = 0;
		int num = 0;
		for(int i = 0;i < x.length;i++){
			num = 0;
			ans += Math.min(x[i], k-x[i])*2;
		}
		System.out.println(ans);
		saori.close();
    }
}

class hayami implements Closeable {
	private final InputStream in = System.in;
	private final byte[] hayami = new byte[1024];
	private int Hayami = 0;
	private int saori = 0;
	private boolean HayamiSaori() {
		if (Hayami < saori) {
			return true;
		}else{
			Hayami = 0;
			try {
				saori = in.read(hayami);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (saori <= 0) {
				return false;
			}
		}
		return true;
	}
	private int SaoriHayami() { 
		if (HayamiSaori()) {
            return hayami[Hayami++];
         }else{
             return -1;
         }
	}
	private static boolean hayami_saori(int hayami) { 
		return 33 <= hayami && hayami <= 126;
	}
	public boolean hayamisaori() { 
		while(HayamiSaori() && !hayami_saori(hayami[Hayami])) Hayami++; return HayamiSaori();
	}
	public String nextHayami() {
		if (!hayamisaori()) throw new NoSuchElementException();
		StringBuilder hayamin = new StringBuilder();
		int saori = SaoriHayami();
		while(hayami_saori(saori)) {
			hayamin.appendCodePoint(saori);
			saori = SaoriHayami();
		}
		return hayamin.toString();
	}
	public long saorihayami() {//nextLong
		if (!hayamisaori()) throw new NoSuchElementException();
		long hayami = 0;
		boolean misao = false;
		int saori = SaoriHayami();
		if (saori == '-') {
			misao = true;
			saori = SaoriHayami();
		}
		if (saori < '0' || '9' < saori) {
			throw new NumberFormatException();
		}
		while(true){
			if ('0' <= saori && saori <= '9') {
				hayami *= 10;
				hayami += saori - '0';
			}else if(saori == -1 || !hayami_saori(saori)){
				return misao ? -hayami : hayami;
			}else{
				throw new NumberFormatException();
			}
			saori = SaoriHayami();
		}
	}
	public int saori_hayami() {//nextInt
		long hayami = saorihayami();
		if (hayami < Integer.MIN_VALUE || hayami > Integer.MAX_VALUE) throw new NumberFormatException();
		return (int) hayami;
	}
	public double Hayamin() { //nextDouble
		return Double.parseDouble(nextHayami());
	}
	public void close() {
		try {
			in.close();
		} catch (IOException e) {
		}
    }
    
}
//  [java]
import java.io.*;

public class Main {

	final static long MOD = 1000000007;
	public static String[] Ws = null;
	public static int wsIndx = 0;
	public static BufferedReader in = null;
	public static void main(String[] args) throws Exception {

		int N = nextInt();
		int K = nextInt();
		int[] x = nextInts();

		long ans = 0;
		for(int i=0;i<N;i++){
			ans+=Math.min(Math.abs(x[i]-K), x[i])*2;
		}

		System.out.println(ans);

	}

	public static void check() throws Exception{
		if(in == null){
			in = new BufferedReader(new InputStreamReader(System.in));
		}
		if(Ws==null || Ws.length<=wsIndx){
			Ws = in.readLine().split(" ");
			wsIndx=0;
		}
	}
	public static int nextInt()throws Exception{
		check();
		return Integer.parseInt(Ws[wsIndx++]);
	}

	public static long nextLong()throws Exception{
		check();
		return Long.parseLong(Ws[wsIndx++]);
	}

	public static String nextString()throws Exception{
		check();
		return Ws[wsIndx++];
	}

	public static int[] nextInts()throws Exception{
		check();
		int[] tmp = new int[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Integer.parseInt(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static long[] nextLongs()throws Exception{
		check();
		long[] tmp = new long[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Long.parseLong(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static String[] nextStrings()throws Exception{
		check();
		wsIndx=Ws.length;
		return Ws;
	}


}
//  [java]
import java.util.*;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int result = IntStream.range(0,n).map(i->{
            int a = sc.nextInt();
            if( k-a < a ){
                a = k-a;
            }
            return  a*2;
        }).sum();

        System.out.print(result);
    }
}
//  [java]

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
	Main m = new Main();
	m.answer();
    }

    private Scanner scan = new Scanner(System.in);
    private final int N;
    private final int K;
    private final int[] x;

    public Main() {
	N = Integer.parseInt(scan.next());
	K = Integer.parseInt(scan.next());
	x = new int[N];

	for (int i = 0; i < N; i++) {
	    x[i] = Integer.parseInt(scan.next());
	}

	scan.close();
    }

    public final void answer() {
	int ans = Arrays.stream(x).map(x -> 2 * Integer.min(x, K-x)).sum();
	System.out.println(ans);
    }
}
//  [java]
import java.util.Scanner;
public class Main {
	public static void main(String[] args){
		Scanner in = new java.util.Scanner(System.in);
		int N = in.nextInt();
		int K = in.nextInt();
		int sum = 0;
		for(int i=0; i<N; i++) {
			int x = in.nextInt();
			int d = Math.abs(x-K);
			if(Math.abs(x) < d) {
				sum += 2*x;
			}else {
				sum += 2*d;
			}
		}
		System.out.println(sum);
		
		
		in.close();
	}
}
//  [cpp]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main()
{
	int n,k,sum,t;
	while(scanf("%d", &n)!=EOF&n>0)
	{
		scanf("%d", &k);
		sum=0;
		while(n--)
		{
			scanf("%d", &t);
			if(k-t<t)
				sum+=2*(k-t);
			else
				sum+=2*t;
		}
		printf("%d\n",sum);
	}
	
	
	return 0;
}
//  [cpp]
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=110;
int n,k,a;
int main(){
	int i,j,ans=0;
	scanf("%d%d",&n,&k);
	for(i=0;i<n;i++){
		scanf("%d",&a);
		j=min(a,k-a);
		ans+=2*j;	
	}
	printf("%d\n",ans);
	return 0;
}
//  [cpp]
#include<cstdio>
int n,k,a;
inline int min(int x,int y){return x<y?x:y;}
int main()
{
	scanf("%d%d",&n,&k);
	int ans=0;
	for(int i=0;i<n;i++)
	{
		scanf("%d",&a);
		ans+=min(a,k-a);
	}
	printf("%d\n",ans<<1);
}
//  [cpp]
//# define FLAG
///delet....................................
# include   <bits/stdc++.h>
using namespace std;
# define    pb                      push_back
# define    mp                      make_pair
# define    IOS                     ios::sync_with_stdio(false)
# define    mem(a,b)                memset(a,b,sizeof(a))
# define    FO(i,n,a)               for(int i=n; i>=a; --i)
# define    FOR(i,a,n)              for(int i=a; i<=n; ++i)
# define    pi                      acos(-1.0)
# define    MAX(a,b)                (a)>(b)?(a):(b)
# define    MIN(a,b)                (a)<(b)?(a):(b)
# define    LINF                    0xfcfcfcfcfcfcfcf
# define    INF                     0x3f3f3f3f
# define    MOD                     1000000007
# define    eps                     0.00000001
# define    hr                      putchar('\n')
# define    bug                     puts("H");
# pragma    comment(linker,"/STACK:1024000000,1024000000")
typedef     vector<int>             VI;
typedef     long long               LL;
typedef     unsigned long long      ULL;
inline char gtc() {
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
# define    Template                LL
inline Template read() {
    int flag=1;
    char ch=gtc();
    if(ch==EOF)return EOF;
    Template sum=0;
    while(!((ch>='0'&&ch<='9')||ch=='-'))ch=gtc();
    if(ch=='-')flag=-1,ch=gtc();
    while(ch>='0'&&ch<='9')sum=sum*10+ch-'0',ch=gtc();
    return sum*flag;
}
inline void out(Template x) {
    if(x<0)putchar('-'),x=-x;
    if(x>9)out(x/10);
    putchar(x%10+'0');
}
///coding...................................

int main() {
    IOS;
#ifdef FLAG
    freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
#endif
    int a,b,n,num=0;
    cin>>a>>b;
    FOR(i,1,a) {
        cin>>n;
        num+=min(n,b-n)*2;
    }
    cout<<num<<endl;
    return 0;
}










///delete FLAG..............................
//  [cpp]
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <math.h>
#include <cmath>
#include <limits.h>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <functional>
#include <stdio.h>
using namespace std;

long long MOD = 1000000007;

int main() {
    
    int N,K;
    cin >> N >> K;
    int ans = 0;
    for ( int i = 0; i < N; i++ ) {
        int a;
        cin >> a;
        
        ans += min( a*2, (K-a)*2 );
    }
    
    cout << ans << endl;
    
    
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef long l;
typedef unsigned long ul;
typedef pair<ll,ll> pll;
typedef pair<l,l> pl;
typedef pair<int,int> pi;
typedef vector<ll> vll;
typedef vector<l> vl;
typedef vector<int> vi;

#define pb push_back
#define mp make_pair
#define eb emplace_back

#define fi first
#define se second

int main(){
	ll N, K;
	cin >> N >> K;
	ll dis = 0;
	for (ll i = 0; i < N; ++i){
		ll temp;
		cin >> temp;
		dis += 2*min(abs(K-temp),temp);
	}
	cout << dis << endl;
	return 0;
}
//  [c]
#include <stdio.h>
int main(void)
{
    int n,k,y;
    int ans=0;
    scanf("%d\n%d",&n,&k);
    int x[n];
    for(int p=0;p<n;p++)
    {
        scanf("%d",&x[p]);
        y=k-x[p];
        if(y>x[p])
          ans+=x[p]*2;
        else
          ans+=y*2;
    }
    printf("%d",ans);
}
//  [c]
#include <stdio.h>
#define REP(a) for(i = 0; i < a; i++)
int main(void) {
    int n,k,i,sum = 0;
    scanf("%d",&n);
    scanf("%d",&k);
    int x[n];
    REP(n) {
        scanf("%d",&x[i]);
        if (x[i] < k - x[i]) {
            sum += x[i];
        } else {
            sum += k - x[i];
        }
    }
    printf("%d\n",sum * 2);
    return 0;
}
//  [c]
#include <stdio.h>

int main()
{ 
	int N;
	int K;
	int wa;
	int i;
	
	scanf("%d",&N);
	scanf("%d",&K);
	
	int x[N];
	
	for (i = 0; i < N; i++){
		scanf("%d",&x[i]);
	}
	
	for (i = 0; i < N; i++){
		if ( (K - x[i]) > x[i] )
				wa += x[i];
		else
				wa += K - x[i];
	}
	
	printf("%d", wa*2);
		
	return 0;
	
}
//  [c]
#include <stdio.h>

int main(void)
{
	int N, K, x[100], Amin = 0, Bmin = 0;
	
	scanf("%d", &N);
	scanf("%d", &K);
	
	for(int i = 0; i < N; i++) scanf("%d", &x[i]);
	
	for(int i = 0; i < N; i++){
		if(x[i] < (K - x[i])){
			Amin += 2*x[i];
		} else {
			Bmin += 2*(K - x[i]);
		}
	}
	
	printf("%d\n", Amin + Bmin);
	
	return 0;
}
//  [c]
#include<stdio.h>

int main(void){
  int n,k;
  int x=0;
  int sum = 0;

  
  scanf("%d", &n);
  scanf("%d", &k);
  for(int i=0;i<n;i++){
  	scanf("%d", &x);
    if(x<(k-x)){
    sum += (2*x);
    }
    else
    sum += (2*(k-x));
   
  }
 /*
  for(int i=0;i<n;i++){
    //handan(x,k);
    if(x<(k/2)){
    sum += (2*x);
    }
    else
    sum += (2*(k-x));
  
    //sum += handan(x,k);
  }
  */
  
  printf("%d", sum);
  return 0;
}
//  [c]
#include <stdio.h>

int min(int a, int b){
    if(a<b)return a;
    else return b;
}
int main(void){
    int n, k;
    scanf("%d", &n);
    scanf("%d", &k);
    
    int ans=0;
    for(int i=0; i<n; i++){
        int x;
        scanf("%d", &x);
        
        int a=x*2;
        int b=(k-x)*2;
        ans+=min(a, b);
    }
    printf("%d\n", ans);
    return 0;
}
//  [javascript]
function Main(input) {
    inputs = input.split(/\n/)
    const N = i(inputs[0])
    const K = i(inputs[1])
    const X = inputs[2].split(' ')
    const ans = X.reduce(function(sum, x, y){
        if(Math.abs(K - i(x)) < x){
            return sum + Math.abs(K - i(x)) * 2
        } else {
            return i(sum) + i(x) * 2
        }
    }, 0)
    console.log(ans)
}
function i(x){ return parseInt(x, 10)}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
  input = input.split("\n");
  var sum = 0;
  var arr = input[2].split(" ").map(Number);
  arr.forEach(function(val){
      sum += Math.min(val,input[1]-val);
      })
      console.log(sum*2);
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
//  [javascript]
'use strict'

function main(s) {

  s = s.split('\n');

  const k = Number(s[1]);
  const xs = s[2].split(' ').map(n => Number(n));

  let sum = 0;

  for (const x of xs) {
    sum += Math.min(2 * x, 2 * (k - x));
  }

  console.log(sum);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
'use strict'

function Main(input) {
  const inputs = input.split('\n');
  const n = inputs[0];
  const k = inputs[1];
  const balls = inputs[2].split(' ').map(n => parseInt(n, 10)).sort((a, b) => a-b);
  
  let sum = 0;
  balls.map(b => {
    const dist = Math.min(b, k - b);
    sum += dist * 2;
  });
  
  console.log(sum);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict"
// inputに入力データ全体が入る
function Main(input) {
    // 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split("\n");
    var tmp = input[1].split(" ");
    //文字列から10進数に変換するときはparseIntを使います
    var a = parseInt(input[0], 10);
    var b = parseInt(tmp[0], 10);
    var c = parseInt(tmp[1], 10);
    var s = input[2];
    for (var i = 0; i < input.length; i++){
        input[i] = input[i].match(/[0-9]*/g);
        input[i] = input[i].filter(v => v);
    }
    //中身
    var leng = 0;
    var n = input[0];
    var k = input[1]/2;

    for(var count = 0; count < n; count++){
        if(input[2][count] < k){
            leng += Number(input[2][count])*2;
        } else {
            leng += Number(input[1]-input[2][count])*2;
        }
    }
    console.log(leng);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
'use strict'

const main = (input) => {
    input = input.split('\n')
    const N = parseInt(input[0])
    const K = parseInt(input[1])
    const x = input[2].split(' ').map(v => parseInt(v))
    let sum = 0
    x.forEach(v => {
        let b = Math.abs(K - v)
        if(v < b){
            sum += v * 2
        }else{
            sum += b * 2
        }
    })
    console.log(sum)
}

main(require('fs').readFileSync('/dev/stdin', 'utf-8'))
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	var wtr = bufio.NewWriter(os.Stdout)
	var scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanLines)
	var N, K int
	if scanner.Scan() {
		str := scanner.Text()
		//cols := strings.Split(str, " ")
		N, _ = strconv.Atoi(str)
	}
	if scanner.Scan() {
		str := scanner.Text()
		K, _ = strconv.Atoi(str)
	}
	x := make([]int, N)
	if scanner.Scan() {
		str := scanner.Text()
		cols := strings.Split(str, " ")
		for i := 0; i < N; i++ {
			p, _ := strconv.Atoi(cols[i])
			x[i] = p
		}

	}
	var sum int
	for i := 0; i < N; i++ {
		sum += min(x[i], K-x[i])
	}

	fmt.Fprintln(wtr, sum*2)
	_ = wtr.Flush()
}

func max(a int, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func min(a int, b int) int {
	if a < b {
		return a
	} else {
		return b
	}
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

//Util
func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func maxInt(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func minInt(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

func absInt(a int) int {
	if a >= 0 {
		return a
	} else {
		return -a
	}
}

func absFloat64(a float64) float64 {
	if a >= 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a > b {
		return b
	} else {
		return a
	}
}

func str2Int(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func isPrime(x int) bool {
	if x == 1 {
		return false
	}
	if x == 2 {
		return true
	}
	if x%2 == 0 {
		return false
	}

	b := true
	rootx := int(math.Sqrt(float64(x)))
	i := 3
	for i <= rootx {
		if x%i == 0 {
			b = false
			break
		}
		i += 2
	}
	return b
}

//Main
const (
	initialBufSize = 10000
	maxBufSize     = 1000000
	mod            = 1e9 + 7
)

var (
	sc *bufio.Scanner = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, initialBufSize)
		sc.Buffer(buf, maxBufSize)
		return sc
	}()
)

var N, K int

func main() {
	sc.Split(bufio.ScanWords)
	N, K = nextInt(), nextInt()

	ans := 0
	var tmp int
	for i := 0; i < N; i++ {
		tmp = nextInt()
		ans += 2 * minInt(K-tmp, tmp)
	}

	fmt.Println(ans)
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n, k int
	fmt.Scan(&n, &k)

	list := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&list[i])
	}

	total := 0
	for i := 0; i < n; i++ {
		if list[i] > k-list[i] {
			total += 2 * (k - list[i])
		} else {
			total += 2 * (list[i])
		}

	}
	fmt.Println(total)
}
//  [go]
package main

import (
	"fmt"
	"math"
)

func main() {
	// Code for B - Collecting Balls (Easy Version)
	var N, K int
	fmt.Scanf("%d\n%d", &N, &K)

	var x int
	var sum int = 0
	for i := 0; i < N; i++ {
		fmt.Scanf("%d", &x)
		sum += 2 * int(math.Min(float64(x), float64(K-x)))
	}

	fmt.Println(sum)
}
//  [go]
package main

import (
	"fmt"
	"math"
)

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	x := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&x[i])
	}

	var ans int

	for i := 0; i < n; i++ {
		ans += int(math.Min(float64(2*(x[i])), float64(2*math.Abs(float64(x[i]-k)))))
	}
	fmt.Println(int(ans))
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	n := nextInt()
	k := nextInt()
	xlist := make([]int, n)

	for i := 0; i < n; i++ {
		xlist[i] = nextInt()
	}

	run := 0
	for i := 0; i < n; i++ {
		x := xlist[i]

		// 近い線判定
		run += 2 * min(x, k-x)
	}

	fmt.Println(run)

}
func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}

// ---- readfunc
func scanInit() {
	const cap = 64 * 1024
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [ruby]
n = gets.to_i
k = gets.to_i
x = gets.split(" ").map(&:to_i)
count = 0
n.times do |i|
    small = (x[i] - 0).abs
    big = (k - x[i]).abs
     saitan = [small,big].min
     count = count + saitan * 2
end
puts count
//  [ruby]
n = gets.to_i
k = gets.to_i
X = gets.split(' ').map(&:to_i)
ans = 0
X.each { |x| ans += [(0-x).abs, (k-x).abs].min * 2 }
p ans
//  [ruby]
N = gets.to_i
K = gets.to_i
res = 0
gets.split.map(&:to_i).each do |x|
    left = x
    right = (K-x).abs
    y = [left,right].min
    res += y*2
end
puts res
//  [ruby]
eval"N,K,*X="+`dd`.split*?,;p eval X.map{|x|[x,(K-x).abs].min*2}*?+
//  [ruby]
n = gets.to_i
k = gets.to_i
xs = gets.chomp.split(" ").map(&:to_i)

total = 0
xs.each do |x|
    k - x > x - 0 ? total += (x - 0) * 2 : total += (k - x) * 2
end

puts total
//  [ruby]
n = gets.to_i
k = gets.to_i
X = gets.chomp.split(' ').map(&:to_i)
ans = 0

X.each do |x|
  d = (x-k).abs
  if x < d
    ans += x*2
  else
    ans += d*2
  end
end
puts ans
//  [rust]
use std::io;
use std::cmp::min;

fn procon_read<T: std::str::FromStr>() ->  Vec<T> {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v: Vec<T> = Vec::new();
	for i in iter {
		v.push(i.parse().ok().unwrap());
	}
	v
}

fn main() {
	let v:Vec<i32> = procon_read();
	let n = v[0];
	let v:Vec<i32> = procon_read();
	let k = v[0];
	let x:Vec<i32> = procon_read();
	let mut sum = 0;
	for i in x {
		sum += min(i*2, 2*(k - i));
	}
	println!("{}", sum);
}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
fn adjacent4(x: usize, y: usize, sx: usize, sy: usize) -> Vec<(usize, usize)> {
    [(-1, 0), (1, 0), (0, -1), (0, 1)]
        .into_iter()
        .filter_map(|&(dx, dy)| {
            let nx = x as isize + dx;
            let ny = y as isize + dy;
            if nx >= 0 && nx < sx as isize && ny >= 0 && ny < sy as isize {
                Some((nx as usize, ny as usize))
            } else {
                None
            }
        })
        .collect()
}

#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
fn main() {
    input! {
        n: usize,
        k: isize,
        x: [isize; n]
    }

    let mut ans = 0;
    for i in 0..n {
        ans += std::cmp::min(x[i], (k - x[i]).abs());
    }
    println!("{}", ans * 2);
}
//  [rust]
use std::cmp;

fn solve(xs: &Vec<i32>, k: i32) -> i32 {
    xs.iter().map(|x| 2 * cmp::min(*x, k - *x)).sum()
}

#[test]
fn test_solve() {
    assert_eq!(solve(&vec![2], 10), 4);
    assert_eq!(solve(&vec![3, 6], 9), 12);
    assert_eq!(solve(&vec![11, 12, 9, 17, 12], 20), 74);
}

pub mod contest_input {
    use std::io;
    use std::str::FromStr;
    use std::fmt::Debug;

    pub fn read_line<F>() -> F
    where F: FromStr, <F as FromStr>::Err: Debug {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input.trim().parse().unwrap()
    }

    pub fn read_words<F>() -> Vec<F>
    where F: FromStr, <F as FromStr>::Err: Debug {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input
            .split_whitespace()
            .map(|i| i.parse().unwrap())
            .collect()
    }

    pub fn read_matrix<F>(num_lines: usize) -> Vec<Vec<F>>
    where F: FromStr, <F as FromStr>::Err: Debug {
        (0..num_lines).map(|_| read_words()).collect()
    }
}

fn main() {
    contest_input::read_line::<usize>(); // N
    let k: i32 = contest_input::read_line();
    let xs: Vec<i32> = contest_input::read_words();
    println!("{}", solve(&xs, k));
}
//  [rust]
#![allow(unused_imports)]

use std::cmp;
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::fmt::{Debug, Display};
use std::io::{self, Read};
use std::str::{self, FromStr};


fn solve(k: usize, xs: Vec<usize>) -> usize {
    xs.into_iter()
        .map(|x| 2 * if x <= k / 2 { x } else { k - x })
        .sum::<usize>()
}


fn main() {
    let stdin = io::stdin();
    let mut sc = Scanner::new(stdin.lock().bytes());
    let (n, k) = (sc.next(), sc.next());
    println!("{}", solve(k, sc.vec(n)));
}


struct Scanner<R: Read> {
    buf: Vec<u8>,
    bytes: io::Bytes<R>,
}

#[allow(dead_code)]
impl<R: Read> Scanner<R> {
    fn new(bytes: io::Bytes<R>) -> Self {
        Scanner {
            buf: Vec::with_capacity(256),
            bytes: bytes,
        }
    }

    fn next<T: FromStr>(&mut self) -> T
    where
        <T as FromStr>::Err: Debug,
    {
        self.buf.clear();
        for c in self.bytes
            .by_ref()
            .map(|c| c.unwrap())
            .skip_while(|&c| c == ' ' as u8 || c == '\n' as u8)
            .take_while(|&c| !(c == ' ' as u8 || c == '\n' as u8))
        {
            self.buf.push(c);
        }
        str::from_utf8(&self.buf).unwrap().parse().unwrap()
    }

    fn vec<T: FromStr>(&mut self, n: usize) -> Vec<T>
    where
        <T as FromStr>::Err: Debug,
    {
        (0..n).map(|_| self.next()).collect()
    }

    fn pairs<A: FromStr, B: FromStr>(&mut self, n: usize) -> Vec<(A, B)>
    where
        <A as FromStr>::Err: Debug,
        <B as FromStr>::Err: Debug,
    {
        (0..n).map(|_| (self.next(), self.next())).collect()
    }

    fn trios<A: FromStr, B: FromStr, C: FromStr>(&mut self, n: usize) -> Vec<(A, B, C)>
    where
        <A as FromStr>::Err: Debug,
        <B as FromStr>::Err: Debug,
        <C as FromStr>::Err: Debug,
    {
        (0..n)
            .map(|_| (self.next(), self.next(), self.next()))
            .collect()
    }

    fn mat<T: FromStr>(&mut self, m: usize, n: usize) -> Vec<Vec<T>>
    where
        <T as FromStr>::Err: Debug,
    {
        (0..n).map(|_| self.vec(m)).collect()
    }
}


#[allow(dead_code)]
fn print_yesno(x: bool, yes: &'static str, no: &'static str) {
    println!("{}", if x { yes } else { no });
}


#[allow(dead_code)]
fn print_foreach<T: Display, I: IntoIterator<Item = T>>(xs: I) {
    for x in xs.into_iter() {
        println!("{}", x);
    }
}


#[allow(dead_code)]
fn print_or<T: Display>(x: Option<T>, or: &'static str) {
    if let Some(x) = x {
        println!("{}", x);
    } else {
        println!("{}", or);
    }
}
//  [rust]
use std::io::*;
use std::str::*;
use std::f64::consts::*;
use std::f64;

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input!{
        n: usize,
        k: i32,
        v: [i32; n],
    }
    let mut sum = 0;
    for i in 0..n {
        if (k - v[i] < v[i]) {
            sum += (k - v[i]) * 2;
        } else {
            sum += v[i] * 2;
        }
    }
    println!("{}", sum);
}
//  [rust]
#[allow(unused_imports)]
use std::{cmp::Reverse, collections::*};

#[allow(unused_imports)]
use proconio::{
    fastout, input,
    marker::{Chars, Usize1},
};

#[allow(unused_imports)]
use itertools::Itertools;

#[allow(unused_imports)]
use num::Integer;

#[fastout]
pub fn main() {
    input! {
        n: usize,
        k: i32,
        x: [i32; n],
    }

    println!("{}", x.iter().map(|x| x.min(&(k - x)) * 2).sum::<i32>());
}
//  [swift]
let _=readLine(),K=Int(readLine()!)!,x=readLine()!.characters.split(" ").map{Int(String($0))!};print(x.reduce(0){$0+($1>K/2 ?abs(K-$1):$1)}*2)
//  [swift]
import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
func exponentiate(_ lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
//extension Array where Element == String {
//    func joined(separator separator: String) -> String {
//        return self.joinWithSeparator(separator)
//    }
//}
extension Array where Element: Comparable {
    func max() -> Element {
        return self.maxElement()!
    }
    func min() -> Element {
        return self.minElement()!
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
func exponentiate(lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/



/*************** メインプログラム ***************/

let N = readInt()!
let K = readInt()!
let x = readIntSplit(by: " ")
print(x.reduce(0){$0+($1>K/2 ?abs(K-$1):$1)}*2)
//  [swift]
import Foundation
func readInts() -> [Int] { readLine()!.split(separator: " ").map { Int($0)! } }

let n = Int(readLine()!)!
let k = Int(readLine()!)!
let xi = readInts()
let ans = xi.map { min($0, k - $0) * 2 }.reduce(0) { $0 + $1 }
print(ans)
//  [typescript]
declare function require(x: string): any;

var input = require("fs").readFileSync("/dev/stdin", "utf8");
input = input.split("\n");

const n = +input[0];
const k = +input[1];
const x = input[2].split(" ").map((x:string)=>+x);


let result = 0;
for(const a of x){
	result += Math.min(a, Math.abs(a-k))*2;
}

console.log(result);
//  [typescript]
const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);let input_i=-1;const tn=():number=>{input_i++;return Number(input[input_i])};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{input_i++;return String(input[input_i])};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const asc=(ar:number[])=>{const t=[...ar];return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{const t=[...ar];return t.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1]}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const deduplicate=(a:any[]):any[]=>{return Array.from(new Set(a))}
const main=()=>{
  let [n,k]=tnn(2),balls=tnn(n),ans=0
  for(let i=0;i<n;i++){
    ans+=min(balls[i],abs(balls[i]-k))*2
  }
  to(ans)
}
main()
//  [typescript]
"use strict";
const Main = (input) =>{
   let xs = input.trim().split('\n');
   let N = Number(xs[0]);
   let K = Number(xs[1]);
   let x = xs[2].split(' ').map(v=>parseInt(v,10));
   
   let ans = 0;
   let sum = 0;
  
   for(let i=0; i<N; i++){
     let x1 = x[i];
     let x2 = K-x[i];
     
     if(x1>x2){
        sum = x2*2;
        ans +=sum; 
     }else{
        sum = x1*2;
        ans +=sum;
     }
   }
   console.log(ans);
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const K = Number(input[1][0]);
  const X = input[2].map(Number);

  let answer = 0;

  X.forEach((x) => {
    answer += Math.min(x, K - x) * 2;
  });

  return answer;
};

console.log(main(read()));
//  [python]
import numpy as np

# x: T-x * 0.006
# 平均気温がA度に最も近い点を選ぶ
n = int(input())
t, a = map(int, input().split())
h = np.array(list(map(int, input().split())))
h2 = abs((t-h*0.006) - a)
res = np.where(h2==min(h2))[0][0] + 1

print(res)
//  [python]
import numpy as np

N = int(input())
T, A = map(int, input().split())
N = np.array([int(n) for n in input().split()])

N = np.abs(T - N * 0.006 - A)
print(np.argmin(N) + 1)
//  [python]
import numpy as np

n = int(input())
t, a = map(int, input().split())
h = list(map(int, input().split()))
h = np.array(h)

dift = abs((t - h * 0.006) - a)

ans = np.argmin(dift) + 1

print(ans)
//  [java]
import java.util.*;
import java.util.stream.*;
import java.util.function.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        double t = sc.nextInt();
        double a = sc.nextInt();
        double[] h = IntStream.range(0, n).mapToDouble(i -> sc.nextInt()).toArray();
        
        int result = 0;
        double min = Double.MAX_VALUE;
        for(int i = 0; i < h.length; i++) {
            double diff = Math.abs(a - (t - (h[i] * 0.006)));
            if(diff < min) {
                min = diff;
                result = i;
            }
        }
        
        System.out.println(result + 1);
    }
}
//  [java]
import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        Double T = sc.nextDouble();
        Double A = sc.nextDouble();

        List<Point> Ps = new ArrayList<>();
        
        for (int i=0; i<N; i++) {
            Ps.add(new Point(i + 1, Math.abs(A - (T - sc.nextDouble()*0.006))));
        }

        Ps.sort((Point a, Point b) -> a.temp <= b.temp ? -1 : 1);

        System.out.println(Ps.get(0).index);

    }
}

class Point {

    public int index;

    public Double temp;

    public Point(int index, Double temp) {
        this.index = index;
        this.temp = temp;
    }

}