require 'set'

loop do
  n, m, s = gets.split.map(&:to_i)
  break if n == 0

  points = (1..n).map { gets.split.map(&:to_i) }

  if m == 1
    puts 6 * s * s
    next
  end

  g = {}
  (0..n-1).to_a.combination(2) do |i, j|
    x1, y1, z1 = points[i]
    x2, y2, z2 = points[j]
    lx = [x1, x2].min + s - [x1, x2].max
    ly = [y1, y2].min + s - [y1, y2].max
    lz = [z1, z2].min + s - [z1, z2].max
    if lx > 0 && ly > 0 && lz > 0
      decrease = 2 * (lx * ly + ly * lz + lz * lx)
      g[i] ||= {}
      g[i][j] = decrease
      g[j] ||= {}
      g[j][i] = decrease
    end
  end

  connected_group = []
  reached = Set.new
  (0..n-1).each do |i|
    next if reached.include?(i)
    reached << i
    connected_group << [i]
    queue = [i]
    until queue.empty?
      j = queue.shift
      if g[j]
        g[j].each_key do |k|
          next if reached.include?(k)
          reached << k
          connected_group[-1] << k
          queue << k
        end
      end
    end
  end

  connected_group.select! {|group| group.size >= m }
  if connected_group.empty?
    puts -1
    next
  end

  max_dec = 0
  connected_group.each do |group|
    i = group.find {|i| g[i].size == 1 }
    decs = []
    dec = 0
    if i
      j = g[i].keys[0]
      (m - 1).times do
        decs << g[i][j]
        dec += g[i][j]
        i, j = j, g[j].keys.select {|k| k != i }[0]
      end
      max_dec = dec if dec > max_dec
      (group.size - m).times do
        dec -= decs.shift
        decs << g[i][j]
        dec += g[i][j]
        max_dec = dec if dec > max_dec
        i, j = j, g[j].keys.select {|k| k != i }[0]
      end
    else
      i = group[0]
      j = g[i].keys[0]
      (m - 1).times do
        decs << g[i][j]
        dec += g[i][j]
        i, j = j, g[j].keys.select {|k| k != i }[0]
      end
      if group.size == m
        dec += g[i][j]
        max_dec = dec if dec > max_dec
      else
        max_dec = dec if dec > max_dec
        (group.size - 1).times do
          dec -= decs.shift
          decs << g[i][j]
          dec += g[i][j]
          max_dec = dec if dec > max_dec
          i, j = j, g[j].keys.select {|k| k != i }[0]
        end
      end

    end
  end
  p m * 6 * s * s - max_dec
end

