Problem:
Problem G
Fair Deal of Dice
You are serving as the gamemaster of a two-player game in which several cubic dice are used.
Each face of the dice has a number on it.
Unlike conventional dice, the numbers are not necessarily one through six.
Before starting a game, you select a predefined number of dice from the set of dice at hand and deal them out to the two players.
  Here, the numbers of dice the two players receive are not necessarily the same, but both players receive at least one die.
Both of the players cast all of the dice dealt in some situations of the game.
At that time, the greater the sum of the numbers on the top faces of the dice of a player is, the more advantage the player gains.
For more exciting games, selecting and dealing the dice in a way that achieves the least
unfairness
is the best.
Definition of the unfairness:
Let
x
denote the sum of the numbers on the top of the dice of one player, and
y
denote that of the other player.
    The unfairness is defined as the expected value of (
x
−
y
)
2
.
    Here, each side of a die comes to the top with probability 1/6 independently of the other dice.
Please compute the minimum achievable unfairness with the dice at hand.
Input
The input consists of multiple datasets, each in the following format.
n
m
a
1,1
a
1,2
a
1,3
a
1,4
a
1,5
a
1,6
⋮
a
n
,1
a
n
,2
a
n
,3
a
n
,4
a
n
,5
a
n
,6
n
is the number of dice you have, and
m
is the number of dice you select to deal to players.
n
and
m
are integers that satisfy 2 ≤
m
≤
n
≤ 60.
a
i
,
j
gives the number on the
j
-th face of the
i
-th die.
a
i
,
j
is an integer that satisfies 0 ≤
a
i
,
j
≤ 60.
The end of the input is indicated by a line consisting of two zeros.
    The number of datasets does not exceed 100.
Output
For each dataset, output the minimum achievable value of the unfairness
multiplied by 36
in a line.
    Note that this value can be proved to be an integer.
Sample Input
4 3
1 2 3 4 5 6
10 10 10 20 20 20
10 11 12 13 14 15
60 0 60 0 60 0
2 2
0 0 0 0 0 0
60 60 60 60 60 60
8 6
58 43 60 42 53 37
13 41 55 4 21 50
35 13 54 43 24 5
40 60 57 48 60 32
51 32 58 44 60 52
40 29 25 22 0 44
31 22 26 30 49 23
16 34 4 40 21 6
0 0
Output for the Sample Input
1146
129600
31878

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(v) v.begin(), v.end()
template <class T, class U>
inline bool chmax(T& a, U b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <class T, class U>
inline bool chmin(T& a, U b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
constexpr int INF = 1000000000;
constexpr int64_t llINF = 3000000000000000000;
constexpr double eps = 1e-10;
const double pi = acos(-1);
struct linear_sieve {
    vector<int> least_factor, prime_list;
    linear_sieve(int n) : least_factor(n + 1, 0) {
        for (int i = 2; i <= n; i++) {
            if (least_factor[i] == 0) {
                least_factor[i] = i;
                prime_list.push_back(i);
            }
            for (int p : prime_list) {
                if (ll(i) * p > n || p > least_factor[i]) break;
                least_factor[i * p] = p;
            }
        }
    }
};
ll extgcd(ll a, ll b, ll& x, ll& y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll d = extgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
ll modpow(ll a, ll b, ll m) {
    ll res = 1;
    while (b) {
        if (b & 1) {
            res *= a;
            res %= m;
        }
        a *= a;
        a %= m;
        b >>= 1;
    }
    return res;
}
template <int modulo>
struct modint {
    int x;
    modint() : x(0) {}
    modint(int64_t y) : x(y >= 0 ? y % modulo : (modulo - (-y) % modulo) % modulo) {}
    modint& operator+=(const modint& p) {
        if ((x += p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint& operator-=(const modint& p) {
        if ((x += modulo - p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint& operator*=(const modint& p) {
        x = (int)(1LL * x * p.x % modulo);
        return *this;
    }
    modint& operator/=(const modint& p) {
        *this *= p.inv();
        return *this;
    }
    modint operator-() const { return modint(-x); }
    modint operator+(const modint& p) const { return modint(*this) += p; }
    modint operator-(const modint& p) const { return modint(*this) -= p; }
    modint operator*(const modint& p) const { return modint(*this) *= p; }
    modint operator/(const modint& p) const { return modint(*this) /= p; }
    bool operator==(const modint& p) const { return x == p.x; }
    bool operator!=(const modint& p) const { return x != p.x; }
    modint inv() const {
        int a = x, b = modulo, u = 1, v = 0, t;
        while (b > 0) {
            t = a / b;
            swap(a -= t * b, b);
            swap(u -= t * v, v);
        }
        return modint(u);
    }
    modint pow(int64_t n) const {
        modint ret(1), mul(x);
        while (n > 0) {
            if (n & 1) ret *= mul;
            mul *= mul;
            n >>= 1;
        }
        return ret;
    }
    friend ostream& operator<<(ostream& os, const modint& p) { return os << p.x; }
    friend istream& operator>>(istream& is, modint& a) {
        int64_t t;
        is >> t;
        a = modint<modulo>(t);
        return (is);
    }
    int val() const { return x; }
    static constexpr int mod() { return modulo; }
    static constexpr int half() { return (modulo + 1) >> 1; }
};
template <typename T>
struct Binomial {
    vector<T> inv, fact, factinv;
    Binomial(int n) {
        inv.resize(n + 1);
        fact.resize(n + 1);
        factinv.resize(n + 1);
        inv[0] = fact[0] = factinv[0] = 1;
        for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i;
        factinv[n] = fact[n].inv();
        inv[n] = fact[n - 1] * factinv[n];
        for (int i = n - 1; i >= 1; i--) {
            factinv[i] = factinv[i + 1] * (i + 1);
            inv[i] = fact[i - 1] * factinv[i];
        }
    }
    T C(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r] * factinv[r];
    }
    T P(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r];
    }
    T H(int n, int r) {
        if (n == 0 && r == 0) return 1;
        if (n < 0 || r < 0) return 0;
        return r == 0 ? 1 : C(n + r - 1, r);
    }
};
namespace geometry {

using floating_point_type = long double;

constexpr floating_point_type EPS = 1e-13;
constexpr floating_point_type Pi = 3.141592653589793;

constexpr floating_point_type operator"" _deg(floating_point_type deg) { return static_cast<floating_point_type>(deg * Pi / 180.0); }
constexpr floating_point_type operator"" _deg(unsigned long long deg) { return static_cast<floating_point_type>(deg * Pi / 180.0); }

template <typename T>
constexpr int sgn(T a) noexcept {
    return (a < -EPS ? -1 : (a > EPS ? +1 : 0));
}

template <typename T, typename U>
constexpr bool same(T a, U b) noexcept {
    return sgn(a - b) == 0;
}

template <typename T>
constexpr T square(T x) noexcept {
    return x * x;
}

// ax + by + c = 0, gcd(a,b,c) = 1
// a != 0 : a > 0
// a = 0: b > 0
tuple<long long, long long, long long> general_form(long long x1, long long y1, long long x2, long long y2) {
    long long a = y1 - y2, b = x2 - x1, c = x1 * y2 - x2 * y1;
    if (a < 0) a = -a, b = -b, c = -c;
    if (a == 0 && b < 0) b = -b, c = -c;
    long long g = gcd(gcd(a, b), c);
    return {a / g, b / g, c / g};
}

template <typename T>
struct Vector2D {
    using value_type = T;
    T x, y;

    Vector2D() = default;
    explicit Vector2D(T arg) : x(cos(arg)), y(sin(arg)) {}
    constexpr Vector2D(T x, T y) noexcept : x(x), y(y) {}

    constexpr bool operator<(const Vector2D& v) const noexcept {
        if (!same(x, v.x)) return x < v.x;
        return y < v.y;
    }
    constexpr bool operator>(const Vector2D& v) const noexcept { return v < *this; }
    constexpr bool operator==(const Vector2D& v) const noexcept { return same(x, v.x) && same(y, v.y); }
    constexpr bool operator!=(const Vector2D& v) const noexcept { return !(*this == v); }

    constexpr Vector2D operator+() const noexcept { return *this; }
    constexpr Vector2D operator-() const noexcept { return {-x, -y}; }

    constexpr Vector2D operator+(const Vector2D& v) const noexcept { return {x + v.x, y + v.y}; }
    constexpr Vector2D operator-(const Vector2D& v) const noexcept { return {x - v.x, y - v.y}; }
    constexpr Vector2D operator*(T s) const noexcept { return {x * s, y * s}; }
    constexpr Vector2D operator/(T s) const noexcept { return {x / s, y / s}; }

    constexpr Vector2D& operator+=(const Vector2D& v) noexcept {
        x += v.x;
        y += v.y;
        return *this;
    }
    constexpr Vector2D& operator-=(const Vector2D& v) noexcept {
        x -= v.x;
        y -= v.y;
        return *this;
    }
    constexpr Vector2D& operator*=(T s) noexcept {
        x *= s;
        y *= s;
        return *this;
    }
    constexpr Vector2D& operator/=(T s) noexcept {
        x /= s;
        y /= s;
        return *this;
    }

    constexpr bool isZero() const noexcept { return x == T(0) && y == T(0); }
    bool hasNan() const { return isnan(x) || isnan(y); }

    constexpr T dot(const Vector2D& v) const noexcept { return x * v.x + y * v.y; }
    constexpr T cross(const Vector2D& v) const noexcept { return x * v.y - y * v.x; }

    floating_point_type length() const {
        if (isZero()) return 0.0;

        const T abs_x = std::abs(x);
        const T abs_y = std::abs(y);

        const auto [u, v] = std::minmax(abs_x, abs_y);
        const T t = u / v;

        return v * std::sqrt(std::fma(t, t, 1.0));
    }
    constexpr T lengthSq() const noexcept { return dot(*this); }

    floating_point_type distanceFrom(const Vector2D& v) const { return (v - *this).length(); }
    constexpr T distanceFromSq(const Vector2D& v) const noexcept { return (v - *this).lengthSq(); }

    Vector2D normalized() const { return *this / length(); }
    Vector2D& normalize() { return *this /= length(); }

    Vector2D rotated(floating_point_type angle) const {
        const T s = sin(angle);
        const T c = cos(angle);
        return {x * c - y * s, x * s + y * c};
    }
    Vector2D& rotate(floating_point_type angle) { return *this = rotated(angle); }

    floating_point_type arg() const { return atan2<floating_point_type>(y, x); }
    floating_point_type arg(const Vector2D& v) const {
        if (isZero() || v.isZero()) {
            return numeric_limits<T>::signaling_NaN();
        }

        return atan2<floating_point_type>(cross(v), dot(v));
    }
    floating_point_type arg(const Vector2D& a, const Vector2D& b) const { return (a - *this).arg(b - *this); }

    constexpr Vector2D lerp(const Vector2D& v, T f) const noexcept { return {x + (v.x - x) * f, y + (v.y - y) * f}; }

    constexpr friend Vector2D operator*(T s, const Vector2D& v) noexcept { return {s * v.x, s * v.y}; }
    friend istream& operator>>(istream& is, Vector2D& v) { return is >> v.x >> v.y; }
    friend ostream& operator<<(ostream& os, const Vector2D& v) { return os << "(" << v.x << ", " << v.y << ")"; }
};

template <typename T>
void argument_sort(vector<Vector2D<T>>& vec, const Vector2D<T>& center = Vector2D<T>(0, 0)) {
    auto orthant = [](const Vector2D<T>& v) {
        if (sgn(v.x) < 0 && sgn(v.y) < 0) return 0;
        if (sgn(v.x) >= 0 && sgn(v.y) < 0) return 1;
        if (sgn(v.x) == 0 && sgn(v.y) == 0) return 2;
        if (sgn(v.x) >= 0 && sgn(v.y) >= 0) return 3;
        return 4;
    };

    auto comp = [orthant, center](const Vector2D<T>& a, const Vector2D<T>& b) {
        const int o1 = orthant(a - center), o2 = orthant(b - center);
        if (o1 != o2) return o1 < o2;

        return (a - center).cross(b - center) > 0;
    };

    sort(vec.begin(), vec.end(), comp);
}

template <typename T>
vector<Vector2D<T>> convex_hull(vector<Vector2D<T>> points) {
    int n = points.size(), k = 0;
    vector<Vector2D<T>> res(n * 2);

    sort(points.begin(), points.end());
    points.erase(unique(points.begin(), points.end()), points.end());

    for (int i = 0; i < n; ++i) {
        while (k > 1 && sgn((res[k - 1] - res[k - 2]).cross(points[i] - res[k - 1])) <= 0) k--;
        res[k++] = points[i];
    }

    for (int i = n - 2, t = k; i >= 0; --i) {
        while (k > t && sgn((res[k - 1] - res[k - 2]).cross(points[i] - res[k - 1])) <= 0) k--;
        res[k++] = points[i];
    }

    res.resize(k - 1);
    return res;
}

/*
ABから見てBCは左に曲がるのなら +1
ABから見てBCは右に曲がるのなら -1
BACの順番で一直線上に並ぶなら +2
ABCの順番で一直線上に並ぶなら -2
CがAB上なら 0
*/
template <typename T>
constexpr int ccw(const Vector2D<T>& a, const Vector2D<T>& b, const Vector2D<T>& c) {
    const int res = sgn((b - a).cross(c - a));

    if (res != 0) return res;
    if (sgn((a - b).dot(c - a)) > 0) return +2;
    if (sgn((b - a).dot(c - b)) > 0) return -2;
    return 0;
}

using Vec2 = Vector2D<floating_point_type>;

struct Line {
    using value_type = Vec2::value_type;
    Vec2 begin, end;

    Line() = default;
    constexpr Line(const Vec2& begin, const Vec2& end) : begin(begin), end(end) {}
    constexpr Line(value_type sx, value_type sy, value_type gx, value_type gy) : begin(sx, sy), end(gx, gy) {}

    // ax + by + c = 0
    Line(value_type a, value_type b, value_type c) {
        assert(sgn(a) != 0 || sgn(b) != 0);

        if (sgn(b) == 0) {
            begin = Vec2(-c / a, 0.0);
            end = Vec2(-c / a, 1.0);
        } else {
            begin = Vec2(0, -c / b);
            end = Vec2(1.0, -(a + c) / b);
        }
    }

    constexpr Vec2 vector() const { return end - begin; }

    constexpr Line& reverse() {
        const Vec2 tmp = begin;
        begin = end;
        end = tmp;
        return *this;
    }
    constexpr Line reversed() const { return {end, begin}; }

    constexpr Line& moveBy(const Vec2& v) {
        begin += v;
        end += v;
        return *this;
    }
    constexpr Line movedBy(const Vec2& v) const { return {begin + v, end + v}; }

    constexpr bool isParallel(const Line& line) const { return sgn(vector().cross(line.vector())) == 0; }
    constexpr bool isOrthogonal(const Line& line) const { return sgn(vector().dot(line.vector())) == 0; }

    floating_point_type length() const { return vector().length(); }
    constexpr value_type lengthSq() const { return vector().lengthSq(); }

    floating_point_type distanceFrom(const Vec2& v) const { return fabs(vector().cross(v - begin)) / length(); }
    constexpr value_type distanceFromSq(const Vec2& v) const {
        const value_type d = vector().cross(v - begin);

        return d / lengthSq() * d;
    }

    optional<Vec2> intersectsAt(const Line& line) const {
        if (sgn(vector().cross(line.vector())) == 0) return nullopt;

        return begin + vector() * fabs((line.end - begin).cross(line.vector()) / vector().cross(line.vector()));
    }

    constexpr Vec2 projection(const Vec2& v) const { return begin + vector() * (v - begin).dot(vector()) / lengthSq(); }
    constexpr Vec2 reflection(const Vec2& v) const { return 2 * projection(v) - v; }

    // ax + by + c = 0
    constexpr tuple<value_type, value_type, value_type> generalForm() const {
        const Vec2 vec = vector();
        return {vec.y, -vec.x, end.cross(begin)};
    }

    friend istream& operator>>(istream& is, Line& rhs) { return is >> rhs.begin >> rhs.end; }
};

namespace segment {

using Segment = Line;

constexpr bool intersect(const Segment& a, const Segment& b) {
    return ccw(a.begin, a.end, b.begin) * ccw(a.begin, a.end, b.end) <= 0 && ccw(b.begin, b.end, a.begin) * ccw(b.begin, b.end, a.end) <= 0;
}

floating_point_type distance(const Segment& a, const Vec2& v) {
    if (sgn(a.vector().dot(v - a.begin)) < 0 || sgn((-a.vector()).dot(v - a.end)) < 0) {
        return min(v.distanceFrom(a.begin), v.distanceFrom(a.end));
    }
    return a.distanceFrom(v);
}

constexpr floating_point_type distanceSq(const Segment& a, const Vec2& v) {
    if (sgn(a.vector().dot(v - a.begin)) < 0 || sgn((-a.vector()).dot(v - a.end)) < 0) {
        return min(v.distanceFromSq(a.begin), v.distanceFromSq(a.end));
    }
    return a.distanceFromSq(v);
}

floating_point_type distance(const Segment& a, const Segment& b) {
    if (intersect(a, b)) return 0.0;

    return min({distance(a, b.begin), distance(a, b.end), distance(b, a.begin), distance(b, a.end)});
}
}  // namespace segment

struct Triangle {
    using value_type = Vec2::value_type;
    Vec2 p0, p1, p2;

    Triangle() = default;
    constexpr Triangle(const Vec2& p0, const Vec2& p1, const Vec2& p2) : p0(p0), p1(p1), p2(p2) {}

    constexpr Vec2& p(size_t index) { return (&p0)[index]; }
    constexpr const Vec2& p(size_t index) const { return (&p0)[index]; }

    constexpr Line side(size_t index) const {
        if (index == 0)
            return Line(p1, p2);
        else if (index == 1)
            return Line(p2, p0);
        else if (index == 2)
            return Line(p0, p1);
        else {
            throw std::out_of_range("Triangle::side() index out of range");
        }
    }

    floating_point_type angle(size_t index) const {
        const Vec2 vec[3] = {p(index), p((index + 1) % 3), p((index + 2) % 3)};

        const value_type res = vec[0].arg(vec[1], vec[2]);

        return fabs(res);
    }

    constexpr value_type area() const {
        const value_type res = (p1 - p0).cross(p2 - p0) / 2;
        return (0 < res ? res : -res);
    }

    constexpr Vec2 circumCenter() const {
        const value_type d0 = side(0).lengthSq(), d1 = side(1).lengthSq(), d2 = side(2).lengthSq(), t0 = d0 * (-d0 + d1 + d2),
                         t1 = d1 * (+d0 - d1 + d2), t2 = d2 * (+d0 + d1 - d2), t3 = t0 + t1 + t2;

        return t0 / t3 * p0 + t1 / t3 * p1 + t2 / t3 * p2;
    }

    Vec2 innerCenter() const {
        const value_type dist[3] = {side(0).length(), side(1).length(), side(2).length()};

        return (dist[0] * p0 + dist[1] * p1 + dist[2] * p2) / (dist[0] + dist[1] + dist[2]);
    }

    friend istream& operator>>(istream& is, Triangle& rhs) { return is >> rhs.p0 >> rhs.p1 >> rhs.p2; }
};

struct Circle {
    using value_type = Vec2::value_type;
    Vec2 center;
    value_type r;

    Circle() = default;
    explicit constexpr Circle(value_type r) : center(0.0, 0.0), r(r) {}
    constexpr Circle(value_type x, value_type y, value_type r) : center(x, y), r(r) {}
    constexpr Circle(const Vec2& center, value_type r) : center(center), r(r) {}

    constexpr bool intersects(const Line& line) const { return sgn(line.distanceFromSq(center) - r * r) <= 0; }

    constexpr bool intersects(const Circle& circle) const {
        const value_type d = center.distanceFromSq(circle.center);

        return sgn(square(r - circle.r) - d) <= 0 && sgn(d - square(r + circle.r)) <= 0;
    }

    constexpr bool circumcribes(const Circle& circle) const { return same(center.distanceFromSq(circle.center), square(r + circle.r)); }

    constexpr bool inscribes(const Circle& circle) const { return same(center.distanceFromSq(circle.center), square(r - circle.r)); }

    constexpr bool contains(const Circle& circle) const {
        return 0 < sgn(square(r - circle.r) - center.distanceFromSq(circle.center)) && 0 < sgn(r - circle.r);
    }

    constexpr value_type area() const { return Pi * r * r; }

    value_type commonArea(const Circle& circle) const {
        const value_type d_sq = center.distanceFromSq(circle.center);
        const value_type d = center.distanceFrom(circle.center);

        const value_type r1 = r;
        const value_type r2 = circle.r;

        if (sgn(d_sq - square(r1 + r2)) >= 0) return 0.0;
        if (sgn(d_sq - square(r1 - r2)) <= 0) return min(this->area(), circle.area());

        const value_type arg1 = acos(((r1 - r2) * (r1 + r2) + d_sq) / (2 * r1 * d));
        const value_type arg2 = acos(((r2 - r1) * (r2 + r1) + d_sq) / (2 * r2 * d));

        return r1 * r1 * (arg1 - sin(2 * arg1) / 2) + r2 * r2 * (arg2 - sin(2 * arg2) / 2);
    }

    constexpr Circle& moveBy(const Vec2& v) {
        center += v;
        return *this;
    }
    constexpr Circle movedBy(const Vec2& v) const { return {center + v, r}; }

    optional<vector<Vec2>> intersectsAt(const Line& line) const {
        if (!intersects(line)) return nullopt;

        vector<Vec2> res;

        const Vec2 v = line.projection(center);

        if (same(line.distanceFrom(center), r))
            res.emplace_back(v);
        else {
            value_type d = sqrt(r * r - (v - center).lengthSq());
            const Vec2 e = line.vector().normalized();

            res.emplace_back(v - d * e);
            res.emplace_back(v + d * e);
        }

        return res;
    }

    optional<vector<Vec2>> intersectsAt(const Circle& circle) const {
        if (!intersects(circle)) return nullopt;

        const value_type d = center.distanceFrom(circle.center), arg = (circle.center - center).arg(),
                         theta = acos((d * d + r * r - circle.r * circle.r) / (2 * d * r));

        vector<Vec2> res;
        res.emplace_back(center + r * Vec2(arg + theta));
        res.emplace_back(center + r * Vec2(arg - theta));

        if (res[0] > res[1]) swap(res[0], res[1]);

        return res;
    }

    optional<vector<Vec2>> tangentPointFrom(const Vec2& v) const {
        const value_type d = center.distanceFromSq(v);

        if (sgn(d - r * r) < 0) return nullopt;
        if (same(d, r * r)) return vector<Vec2>{v};

        const auto [x1, y1] = v - center;

        const auto& opt = Circle(r).intersectsAt(Line(x1, y1, -r * r));

        vector<Vec2> res = opt.value();

        for (Vec2& v : res) v += center;

        if (res[0] > res[1]) swap(res[0], res[1]);

        return res;
    }
    optional<vector<Vec2>> commonTangentPointFrom(const Circle& circle) const {
        const value_type r1 = r, r2 = circle.r;

        vector<Vec2> res;

        if (!same(r1, r2)) {
            const Vec2 p((r2 * center - r1 * circle.center) / (r2 - r1));

            const auto& opt = tangentPointFrom(p);

            if (opt.has_value()) {
                for (const Vec2& vec : opt.value()) {
                    res.emplace_back(vec);
                }
            }
        } else {
            const value_type theta = (circle.center - center).arg();

            res.emplace_back(center + r1 * Vec2(theta + 90_deg));
            res.emplace_back(center + r1 * Vec2(theta - 90_deg));
        }

        const Vec2 q((r2 * center + r1 * circle.center) / (r1 + r2));

        const auto& opt = tangentPointFrom(q);

        if (opt.has_value()) {
            for (const Vec2& vec : opt.value()) {
                res.emplace_back(vec);
            }
        }

        if (res.empty()) return nullopt;

        sort(res.begin(), res.end());

        return res;
    }

    friend istream& operator>>(istream& is, Circle& rhs) { return is >> rhs.center >> rhs.r; }
};

struct Polygon {
    using value_type = Vec2::value_type;
    int n;
    vector<Vec2> vertex;

    Polygon() = default;
    Polygon(int _n) : n(_n), vertex(_n) {}
    Polygon(const vector<Vec2>& vec) : n(static_cast<int>(vec.size())), vertex(vec) {}

    Line side(size_t index) const { return Line(vertex[index], vertex[(index + 1) % n]); }

    Polygon& moveBy(const Vec2& v) {
        for (Vec2& vec : vertex) vec += v;
        return *this;
    }
    Polygon movedBy(const Vec2& v) const {
        vector<Vec2> new_vertex;
        for (const Vec2& vec : vertex) new_vertex.emplace_back(vec + v);

        return Polygon(new_vertex);
    }

    bool isConvex() const {
        for (int i = 0; i < n; ++i) {
            if (ccw(vertex[i], vertex[(i + 1) % n], vertex[(i + 2) % n]) == -1) return false;
        }
        return true;
    }

    bool isOnEdge(const Vec2& v) const {
        for (int i = 0; i < n; ++i) {
            if (ccw(vertex[i], vertex[(i + 1) % n], v) == 0) return true;
        }
        return false;
    }

    bool intersects(const Vec2& v) const {
        floating_point_type sum = 0.0;

        for (int i = 0; i < n; ++i) {
            sum += v.arg(vertex[i], vertex[(i + 1) % n]);
        }

        return sgn(sum - 2.0 * Pi) == 0;
    }

    double area() const {
        value_type sum = 0.0;

        for (int i = 0; i < n; ++i) {
            sum += vertex[i].cross(vertex[i == n - 1 ? 0 : i + 1]);
        }

        return 0.5 * fabs(sum);
    }

    value_type commonArea(const Circle& circle) const {
        if (n < 3) return 0.0;

        if (!same(circle.center.x, 0.0) || !same(circle.center.y, 0.0)) {
            return (*this).movedBy(-circle.center).commonArea(Circle(circle.r));
        }

        auto cross_area = [&](auto self, Circle c, Vec2 a, Vec2 b) -> value_type {
            const Vec2 va = c.center - a, vb = c.center - b;

            value_type f = va.cross(vb), res = 0.0;

            if (same(f, 0.0)) return 0.0;
            if (sgn(max(va.length(), vb.length()) - c.r) <= 0) return f;

            const Line line(a, b);

            if (sgn(segment::distance(line, c.center) - c.r) >= 0) {
                return c.r * c.r * va.arg(vb);
            }

            const auto opt = c.intersectsAt(line);
            vector<Vec2> vec1 = opt.value();

            const vector<Vec2> vec2{a, vec1.front(), vec1.back(), b};

            for (int i = 0; i + 1 < vec2.size(); ++i) {
                res += self(self, c, vec2[i], vec2[i + 1]);
            }

            return res;
        };

        value_type sum = 0.0;

        for (int i = 0; i < n; ++i) {
            sum += cross_area(cross_area, circle, vertex[i], vertex[(i + 1) % n]);
        }

        sum *= 0.5;

        return fabs(sum);
    }

    Polygon convexHull() const { return convex_hull(vertex); }

    Polygon convexCut(const Line& line) const {
        assert(isConvex());

        vector<Vec2> res;

        for (int i = 0; i < n; ++i) {
            const Vec2 &now = vertex[i], &nxt = vertex[(i + 1) % n];

            if (ccw(line.begin, line.end, now) != -1) res.emplace_back(now);
            if (ccw(line.begin, line.end, now) * ccw(line.begin, line.end, nxt) < 0) {
                const auto& opt = Line(now, nxt).intersectsAt(line);
                if (opt.has_value()) res.emplace_back(opt.value());
            }
        }

        return Polygon(res);
    }

    value_type diameter() const {
        const auto convex = (isConvex() ? (*this) : convexHull()).vertex;

        const size_t n = convex.size();

        if (n == 2)
            return convex[0].distanceFrom(convex[1]);
        else {
            size_t i = 0, j = 0;

            for (size_t k = 0; k < n; ++k) {
                if (!(convex[i] < convex[k])) i = k;
                if (convex[j] < convex[k]) j = k;
            }

            value_type res = 0.0;

            const size_t si = i, sj = j;

            while (i != sj || j != si) {
                res = max(res, convex[i].distanceFrom(convex[j]));

                if ((convex[(i + 1) % n] - convex[i]).cross(convex[(j + 1) % n] - convex[j]) < 0) {
                    i = (i + 1) % n;
                } else
                    j = (j + 1) % n;
            }

            return res;
        }
    }

    friend istream& operator>>(istream& is, Polygon& rhs) {
        for (Vec2& e : rhs.vertex) is >> e;
        return is;
    }
};

// x座標でsort済み
floating_point_type distance_closest_pair(vector<Vec2>& points, int left, int right) {
    if (right - left <= 1) return 1e20;

    int mid = (left + right) / 2;
    floating_point_type x = points[mid].x;
    floating_point_type d = min(distance_closest_pair(points, left, mid), distance_closest_pair(points, mid, right));

    inplace_merge(points.begin() + left, points.begin() + mid, points.begin() + right,
                  [](const Vec2& a, const Vec2& b) { return sgn(a.y - b.y) < 0; });

    vector<Vec2> a;

    for (int i = left; i < right; ++i) {
        if (sgn(fabs(points[i].x - x) - d) >= 0) continue;

        for (int j = static_cast<int>(a.size()) - 1; j >= 0; --j) {
            if (sgn(fabs((points[i] - a[j]).y) - d) >= 0) break;
            d = min(d, points[i].distanceFrom(a[j]));
        }

        a.emplace_back(points[i]);
    }

    return d;
}

// 垂直または水平線分の交点
// begin < end
vector<Vec2> intersections(const vector<Line>& lines) {
    const int n = static_cast<int>(lines.size());

    vector<pair<floating_point_type, int>> events;

    for (int i = 0; i < n; ++i) {
        const Line& line = lines[i];

        if (same(line.begin.y, line.end.y)) {  // 水平
            events.emplace_back(make_pair(line.begin.x, i));
            events.emplace_back(make_pair(line.end.x, i + 2 * n));
        } else {  // 垂直
            events.emplace_back(make_pair(line.begin.x, i + n));
        }
    }

    sort(events.begin(), events.end());

    set<floating_point_type> y_list;
    vector<Vec2> res;

    for (int i = 0; i < static_cast<int>(events.size()); ++i) {
        const int kind = events[i].second;
        const int id = kind % n;
        const Line& line = lines[id];

        if (kind < n) {  // 左端
            y_list.insert(line.begin.y);
        } else if (kind < 2 * n) {  // 垂直
            for (auto y : y_list) {
                if (line.begin.y - EPS <= y && y <= line.end.y + EPS) {
                    res.emplace_back(Vec2(line.begin.x, y));
                }
            }
        } else {  // 右端
            y_list.erase(line.end.y);
        }
    }

    return res;
}
}  // namespace geometry

using namespace geometry;
using Point = Vector2D<ll>;
void solve(int n, int m) {
    vector<vector<int>> a(n, vector<int>(6));
    rep(i, n) rep(j, 6) cin >> a[i][j];
    const int S = 360 * n;
    vector<vector<ll>> dp(m + 1, vector<ll>(S * 2 + 1, llINF));
    dp[0][S] = 0;
    rep(i, n) {
        int sum = 0, sqsum = 0;
        rep(j, 6) {
            sum += a[i][j];
            sqsum += a[i][j] * a[i][j];
        }
        sqsum *= 6;
        for (int c = m - 1; c >= 0; c--) {
            rep(s, S * 2 + 1) {
                if (dp[c][s] == llINF) continue;
                chmin(dp[c + 1][s + sum], dp[c][s] + sqsum + 2 * (s - S) * sum);
                chmin(dp[c + 1][s - sum], dp[c][s] + sqsum - 2 * (s - S) * sum);
            }
        }
    }
    cout << *min_element(all(dp[m])) << endl;
}
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n, m, k, p, q;
    string s;
    while (cin >> n >> m) {
        if (n == 0 && m == 0) break;
        solve(n, m);
    }
}
accuracy: 1
time_ms: 6530
memory_kb: 24060
final_rank: 13

code_snippet: // AOJ #1670 Fair Deal of Dice
// 2025.5.22

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int INF = 1000000000;

#define gc() getchar_unlocked()
#define pc(c) putchar_unlocked(c)

int Cin() {
	int n = 0; int c = gc();
	do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
	return n;
}

void Cout(ll n) {
	char b[30];
	if (!n) pc('0');
	else {
		if (n < 0) pc('-'), n = -n;
		int i = 0; while (n) b[i++] = n % 10 + '0', n /= 10;
		while (i--) pc(b[i]);
	}
	pc('\n');
}

int main(){
    while (true) {
        int n = Cin(), m = Cin();
        if (n==0) break;
        vector<int> w(n), d(n);
        for (int i = 0; i < n; i++) {
            int s1=0, s2=0;
            for (int j = 0; j < 6; j++) {
                int a = Cin();
                s1 += a;
                s2 += a*a;
            }
            w[i] = s1;
            d[i] = 6*s2 - s1*s1;
        }
        vector<int> L(m+1, INF), R(m+1, -INF);
        vector<vector<int>> st(m+1), md(m+1), ed(m+1);

        L[0] = R[0] = 0;
        st[0] = {0};
        ed[0] = {0};
        md[0] = {INF};

        for (int i = 0; i < n; i++) {
            int wi = w[i], di = d[i];
            for (int k = min(i+1, m); k >= 1; k--) {
                if (L[k-1] > R[k-1]) continue;
                int l0 = L[k-1], r0 = R[k-1];
                int l1 = L[k],   r1 = R[k];

                int nl = min({l1, l0 + wi, l0 - wi});
                int nr = max({r1, r0 + wi, r0 - wi});
                int sz = nr - nl + 1;

                vector<int> nst(sz, INF), nmd(sz, INF), ned(sz, INF);

                if (l1 <= r1) {
                    for (int D = l1; D <= r1; D++) {
                        int idx_old = D - l1;
                        int idx_new = D - nl;
                        nst[idx_new] = min(nst[idx_new], st[k][idx_old]);
                        nmd[idx_new] = min(nmd[idx_new], md[k][idx_old]);
                        ned[idx_new] = min(ned[idx_new], ed[k][idx_old]);
                    }
                }

                for (int D0 = l0; D0 <= r0; D0++) {
                    int io = D0 - l0;
                    int cst = st[k-1][io];
                    int cmd = md[k-1][io];
                    int ced = ed[k-1][io];
                    {
                        int Dn = D0 - wi;
                        int in = Dn - nl;
                        if (cst < INF) nst[in] = min(nst[in], cst + di);
                        if (cmd < INF) nmd[in] = min(nmd[in], cmd + di);
                        if (ced < INF) nmd[in] = min(nmd[in], ced + di);
                    }
                    {
                        int Dn = D0 + wi;
                        int in = Dn - nl;
                        if (cst < INF) {
                            if (k == 1) ned[in] = min(ned[in], cst + di);
                            else       nmd[in] = min(nmd[in], cst + di);
                        }
                        if (cmd < INF) nmd[in] = min(nmd[in], cmd + di);
                        if (ced < INF) ned[in] = min(ned[in], ced + di);
                    }
                }

                L[k] = nl;  R[k] = nr;
                st[k].swap(nst);
                md[k].swap(nmd);
                ed[k].swap(ned);
            }
        }

        ll ans = LLONG_MAX;
        for (int D = L[m]; D <= R[m]; D++) {
            int v = md[m][D - L[m]];
            if (v == INF) continue;
            ans = min(ans, (ll)D*D + v);
        }
        Cout(ans);
    }
    return 0;
}
accuracy: 1
time_ms: 4120
memory_kb: 14880
final_rank: 8

code_snippet: #include <array>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

const int INF = 1012345678;

int solve(int N, int M, const vector<array<int, 6> >& A) {
	// step #1. preparation
	vector<int> S(N), V(N);
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < 6; j++) {
			S[i] += A[i][j];
		}
		for (int j = 0; j < 6; j++) {
			int x = A[i][j] * 6 - S[i];
			V[i] += x * x;
		}
		V[i] /= 6;
	}

	// step #2. dynamic programming
	vector<vector<int> > dp = { vector<int>({0}) };
	for (int i = 0; i < N; i++) {
		vector<vector<int> > ndp(i + 2, vector<int>(dp[0].size() + 2 * S[i], INF));
		for (int j = 0; j <= i; j++) {
			for (int k = 0; k < int(dp[0].size()); k++) {
				if (dp[j][k] != INF) {
					ndp[j][k + S[i]] = min(ndp[j][k + S[i]], dp[j][k]);
					ndp[j + 1][k] = min(ndp[j + 1][k], dp[j][k] + V[i]);
					ndp[j + 1][k + 2 * S[i]] = min(ndp[j + 1][k + 2 * S[i]],  dp[j][k] + V[i]);
				}
			}
		}
		dp = ndp;
	}

	// step #3. compute answer
	const int C = (dp[0].size() - 1) / 2;
	int ans = INF;
	for (int i = 0; i <= 2 * C; i++) {
		if (dp[M][i] != INF) {
			int score = dp[M][i] + (i - C) * (i - C);
			ans = min(ans, score);
		}
	}

	return ans;
}

int main() {
	while (true) {
		int N, M;
		cin >> N >> M;
		if (N == 0 && M == 0) {
			break;
		}
		vector<array<int, 6> > A(N);
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < 6; j++) {
				cin >> A[i][j];
			}
		}
		int ans = solve(N, M, A);
		cout << ans << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 3630
memory_kb: 21068
final_rank: 7

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

#include <unistd.h>

namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf


uint32_t pil = 0, pir = 0, por = 0;

struct Pre {
    char num[10000][4];
    constexpr Pre() : num() {
        for (int i = 0; i < 10000; i++) {
            int n = i;
            for (int j = 3; j >= 0; j--) {
                num[i][j] = n % 10 | '0';
                n /= 10;
            }
        }
    }
} constexpr pre;

inline void load() {
    memmove(ibuf, ibuf + pil, pir - pil);
    pir = pir - pil + fread(ibuf + pir - pil, 1, SZ - pir + pil, stdin);
    pil = 0;
    if (pir < SZ)
        ibuf[pir++] = '\n';
}

inline void flush() {
    fwrite(obuf, 1, por, stdout);
    por = 0;
}

void rd(char &c) {
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
}

void rd(string &x) {
    x.clear();
    char c;
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
    do {
        x += c;
        if (pil == pir)
            load();
        c = ibuf[pil++];
    } while (!isspace(c));
}

template <typename T> void rd_real(T &x) {
    string s;
    rd(s);
    x = stod(s);
}

template <typename T> void rd_integer(T &x) {
    if (pil + 100 > pir)
        load();
    char c;
    do
        c = ibuf[pil++];
    while (c < '-');
    bool minus = 0;
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (c == '-') {
            minus = 1, c = ibuf[pil++];
        }
    }
    x = 0;
    while ('0' <= c) {
        x = x * 10 + (c & 15), c = ibuf[pil++];
    }
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (minus)
            x = -x;
    }
}

void rd(int &x) {
    rd_integer(x);
}
void rd(ll &x) {
    rd_integer(x);
}
void rd(i128 &x) {
    rd_integer(x);
}
void rd(uint &x) {
    rd_integer(x);
}
void rd(ull &x) {
    rd_integer(x);
}
void rd(u128 &x) {
    rd_integer(x);
}
void rd(double &x) {
    rd_real(x);
}
void rd(long double &x) {
    rd_real(x);
}

template <class T, class U> void rd(pair<T, U> &p) {
    return rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T> void rd_tuple(T &t) {
    if constexpr (N < std::tuple_size<T>::value) {
        auto &x = std::get<N>(t);
        rd(x);
        rd_tuple<N + 1>(t);
    }
}
template <class... T> void rd(tuple<T...> &tpl) {
    rd_tuple(tpl);
}

template <size_t N = 0, typename T> void rd(array<T, N> &x) {
    for (auto &d : x)
        rd(d);
}
template <class T> void rd(vector<T> &x) {
    for (auto &d : x)
        rd(d);
}

void read() {}
template <class H, class... T> void read(H &h, T &...t) {
    rd(h), read(t...);
}

void wt(const char c) {
    if (por == SZ)
        flush();
    obuf[por++] = c;
}
void wt(const string s) {
    for (char c : s)
        wt(c);
}
void wt(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++)
        wt(s[i]);
}

template <typename T> void wt_integer(T x) {
    if (por > SZ - 100)
        flush();
    if (x < 0) {
        obuf[por++] = '-', x = -x;
    }
    int outi;
    for (outi = 96; x >= 10000; outi -= 4) {
        memcpy(out + outi, pre.num[x % 10000], 4);
        x /= 10000;
    }
    if (x >= 1000) {
        memcpy(obuf + por, pre.num[x], 4);
        por += 4;
    } else if (x >= 100) {
        memcpy(obuf + por, pre.num[x] + 1, 3);
        por += 3;
    } else if (x >= 10) {
        int q = (x * 103) >> 10;
        obuf[por] = q | '0';
        obuf[por + 1] = (x - q * 10) | '0';
        por += 2;
    } else
        obuf[por++] = x | '0';
    memcpy(obuf + por, out + outi + 4, 96 - outi);
    por += 96 - outi;
}

template <typename T> void wt_real(T x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << double(x);
    string s = oss.str();
    wt(s);
}

void wt(int x) {
    wt_integer(x);
}
void wt(ll x) {
    wt_integer(x);
}
void wt(i128 x) {
    wt_integer(x);
}
void wt(uint x) {
    wt_integer(x);
}
void wt(ull x) {
    wt_integer(x);
}
void wt(u128 x) {
    wt_integer(x);
}
void wt(double x) {
    wt_real(x);
}
void wt(long double 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 __attribute__((destructor)) _d() {
    flush();
}
} // namespace fastio


using fastio::flush;
using fastio::print;
using fastio::read;

inline void first(bool i = true) {
    print(i ? "first" : "second");
}
inline void Alice(bool i = true) {
    print(i ? "Alice" : "Bob");
}
inline void Takahashi(bool i = true) {
    print(i ? "Takahashi" : "Aoki");
}
inline void yes(bool i = true) {
    print(i ? "yes" : "no");
}
inline void Yes(bool i = true) {
    print(i ? "Yes" : "No");
}
inline void No() {
    print("No");
}
inline void YES(bool i = true) {
    print(i ? "YES" : "NO");
}
inline void NO() {
    print("NO");
}
inline void Yay(bool i = true) {
    print(i ? "Yay!" : ":(");
}
inline void Possible(bool i = true) {
    print(i ? "Possible" : "Impossible");
}
inline void POSSIBLE(bool i = true) {
    print(i ? "POSSIBLE" : "IMPOSSIBLE");
}

/**
 * @brief Fast IO
 */

template <unsigned mod = 1000000007> struct fp {
    unsigned v;
    static constexpr int get_mod() {
        return mod;
    }
    constexpr unsigned inv() const {
        assert(v != 0);
        int x = v, y = mod, p = 1, q = 0, t = 0, tmp = 0;
        while (y > 0) {
            t = x / y;
            x -= t * y, p -= t * q;
            tmp = x, x = y, y = tmp;
            tmp = p, p = q, q = tmp;
        }
        if (p < 0)
            p += mod;
        return p;
    }
    constexpr fp(ll x = 0) : v(x >= 0 ? x % mod : (mod - (-x) % mod) % mod) {}
    fp operator-() const {
        return fp() - *this;
    }
    fp pow(ull t) {
        fp res = 1, b = *this;
        while (t) {
            if (t & 1)
                res *= b;
            b *= b;
            t >>= 1;
        }
        return res;
    }
    fp &operator+=(const fp &x) {
        if ((v += x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator-=(const fp &x) {
        if ((v += mod - x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator*=(const fp &x) {
        v = ull(v) * x.v % mod;
        return *this;
    }
    fp &operator/=(const fp &x) {
        v = ull(v) * x.inv() % mod;
        return *this;
    }
    fp operator+(const fp &x) const {
        return fp(*this) += x;
    }
    fp operator-(const fp &x) const {
        return fp(*this) -= x;
    }
    fp operator*(const fp &x) const {
        return fp(*this) *= x;
    }
    fp operator/(const fp &x) const {
        return fp(*this) /= x;
    }
    bool operator==(const fp &x) const {
        return v == x.v;
    }
    bool operator!=(const fp &x) const {
        return v != x.v;
    }
    friend istream &operator>>(istream &is, fp &x) {
        return is >> x.v;
    }
    friend ostream &operator<<(ostream &os, const fp &x) {
        return os << x.v;
    }
};

template <unsigned mod> void rd(fp<mod> &x) {
    fastio::rd(x.v);
}
template <unsigned mod> void wt(fp<mod> x) {
    fastio::wt(x.v);
}

template <typename T> T Inv(ll n) {
    static const int md = T::get_mod();
    static vector<T> buf({0, 1});
    assert(n > 0);
    n %= md;
    while (SZ(buf) <= n) {
        int k = SZ(buf), q = (md + k - 1) / k;
        buf.push_back(buf[k * q - md] * q);
    }
    return buf[n];
}

template <typename T> T Fact(ll n, bool inv = 0) {
    static const int md = T::get_mod();
    static vector<T> buf({1, 1}), ibuf({1, 1});
    assert(n >= 0 and n < md);
    while (SZ(buf) <= n) {
        buf.push_back(buf.back() * SZ(buf));
        ibuf.push_back(ibuf.back() * Inv<T>(SZ(ibuf)));
    }
    return inv ? ibuf[n] : buf[n];
}

template <typename T> T nPr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nCr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(r, inv ^ 1) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nHr(int n, int r, bool inv = 0) {
    return nCr<T>(n + r - 1, r, inv);
}

/**
 * @brief Modint
 */

int main() {
while(1) {
    int N, M;
    cin >> N >> M;
    if (N == 0 && M == 0) return 0;
    vector<pair<int,int>> D(N);
    rep(i,0,N) {
        int A[6], SUM = 0, SUM2 = 0;
        rep(j,0,6) cin >> A[j], SUM += A[j];
        rep(j,0,6) SUM2 += (SUM - A[j] * 6) * (SUM - A[j] * 6);
        D[i] = {SUM, SUM2 / 6};
    }
    int MAXS = 360 * N + 1;
    static ll DP[2][61][21601] = {};
    rep(i,0,2) {
        rep(j,0,N+1) {
            rep(k,0,MAXS) DP[i][j][k] = INF;
        }
    }
    DP[0][0][0] = 0;
    rep(i,0,N) {
        rep(j,0,N+1) {
            rep(k,0,360*(i+1)+1) DP[(i&1)^1][j][k] = INF;
        }
        rep(j,0,N+1) {
            rep(k,0,360*i+1) {
                if (DP[i&1][j][k] == INF) continue;
                chmin(DP[(i&1)^1][j+1][k+D[i].first], DP[i&1][j][k]+D[i].second);
                chmin(DP[(i&1)^1][j+1][abs(k-D[i].first)], DP[i&1][j][k]+D[i].second);
                chmin(DP[(i&1)^1][j][k], DP[i&1][j][k]);
            }
        }
    }
    ll ANS = INF;
    for (ll i = 0; i < MAXS; i++) {
        chmin(ANS, i*i+DP[N&1][M][i]);
    }
    cout << ANS << endl;
}
}
accuracy: 1
time_ms: 4370
memory_kb: 24092
final_rank: 9

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

#include <unistd.h>

namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf


uint32_t pil = 0, pir = 0, por = 0;

struct Pre {
    char num[10000][4];
    constexpr Pre() : num() {
        for (int i = 0; i < 10000; i++) {
            int n = i;
            for (int j = 3; j >= 0; j--) {
                num[i][j] = n % 10 | '0';
                n /= 10;
            }
        }
    }
} constexpr pre;

inline void load() {
    memmove(ibuf, ibuf + pil, pir - pil);
    pir = pir - pil + fread(ibuf + pir - pil, 1, SZ - pir + pil, stdin);
    pil = 0;
    if (pir < SZ)
        ibuf[pir++] = '\n';
}

inline void flush() {
    fwrite(obuf, 1, por, stdout);
    por = 0;
}

void rd(char &c) {
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
}

void rd(string &x) {
    x.clear();
    char c;
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
    do {
        x += c;
        if (pil == pir)
            load();
        c = ibuf[pil++];
    } while (!isspace(c));
}

template <typename T> void rd_real(T &x) {
    string s;
    rd(s);
    x = stod(s);
}

template <typename T> void rd_integer(T &x) {
    if (pil + 100 > pir)
        load();
    char c;
    do
        c = ibuf[pil++];
    while (c < '-');
    bool minus = 0;
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (c == '-') {
            minus = 1, c = ibuf[pil++];
        }
    }
    x = 0;
    while ('0' <= c) {
        x = x * 10 + (c & 15), c = ibuf[pil++];
    }
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (minus)
            x = -x;
    }
}

void rd(int &x) {
    rd_integer(x);
}
void rd(ll &x) {
    rd_integer(x);
}
void rd(i128 &x) {
    rd_integer(x);
}
void rd(uint &x) {
    rd_integer(x);
}
void rd(ull &x) {
    rd_integer(x);
}
void rd(u128 &x) {
    rd_integer(x);
}
void rd(double &x) {
    rd_real(x);
}
void rd(long double &x) {
    rd_real(x);
}

template <class T, class U> void rd(pair<T, U> &p) {
    return rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T> void rd_tuple(T &t) {
    if constexpr (N < std::tuple_size<T>::value) {
        auto &x = std::get<N>(t);
        rd(x);
        rd_tuple<N + 1>(t);
    }
}
template <class... T> void rd(tuple<T...> &tpl) {
    rd_tuple(tpl);
}

template <size_t N = 0, typename T> void rd(array<T, N> &x) {
    for (auto &d : x)
        rd(d);
}
template <class T> void rd(vector<T> &x) {
    for (auto &d : x)
        rd(d);
}

void read() {}
template <class H, class... T> void read(H &h, T &...t) {
    rd(h), read(t...);
}

void wt(const char c) {
    if (por == SZ)
        flush();
    obuf[por++] = c;
}
void wt(const string s) {
    for (char c : s)
        wt(c);
}
void wt(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++)
        wt(s[i]);
}

template <typename T> void wt_integer(T x) {
    if (por > SZ - 100)
        flush();
    if (x < 0) {
        obuf[por++] = '-', x = -x;
    }
    int outi;
    for (outi = 96; x >= 10000; outi -= 4) {
        memcpy(out + outi, pre.num[x % 10000], 4);
        x /= 10000;
    }
    if (x >= 1000) {
        memcpy(obuf + por, pre.num[x], 4);
        por += 4;
    } else if (x >= 100) {
        memcpy(obuf + por, pre.num[x] + 1, 3);
        por += 3;
    } else if (x >= 10) {
        int q = (x * 103) >> 10;
        obuf[por] = q | '0';
        obuf[por + 1] = (x - q * 10) | '0';
        por += 2;
    } else
        obuf[por++] = x | '0';
    memcpy(obuf + por, out + outi + 4, 96 - outi);
    por += 96 - outi;
}

template <typename T> void wt_real(T x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << double(x);
    string s = oss.str();
    wt(s);
}

void wt(int x) {
    wt_integer(x);
}
void wt(ll x) {
    wt_integer(x);
}
void wt(i128 x) {
    wt_integer(x);
}
void wt(uint x) {
    wt_integer(x);
}
void wt(ull x) {
    wt_integer(x);
}
void wt(u128 x) {
    wt_integer(x);
}
void wt(double x) {
    wt_real(x);
}
void wt(long double 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 __attribute__((destructor)) _d() {
    flush();
}
} // namespace fastio


using fastio::flush;
using fastio::print;
using fastio::read;

inline void first(bool i = true) {
    print(i ? "first" : "second");
}
inline void Alice(bool i = true) {
    print(i ? "Alice" : "Bob");
}
inline void Takahashi(bool i = true) {
    print(i ? "Takahashi" : "Aoki");
}
inline void yes(bool i = true) {
    print(i ? "yes" : "no");
}
inline void Yes(bool i = true) {
    print(i ? "Yes" : "No");
}
inline void No() {
    print("No");
}
inline void YES(bool i = true) {
    print(i ? "YES" : "NO");
}
inline void NO() {
    print("NO");
}
inline void Yay(bool i = true) {
    print(i ? "Yay!" : ":(");
}
inline void Possible(bool i = true) {
    print(i ? "Possible" : "Impossible");
}
inline void POSSIBLE(bool i = true) {
    print(i ? "POSSIBLE" : "IMPOSSIBLE");
}

/**
 * @brief Fast IO
 */

template <unsigned mod = 1000000007> struct fp {
    unsigned v;
    static constexpr int get_mod() {
        return mod;
    }
    constexpr unsigned inv() const {
        assert(v != 0);
        int x = v, y = mod, p = 1, q = 0, t = 0, tmp = 0;
        while (y > 0) {
            t = x / y;
            x -= t * y, p -= t * q;
            tmp = x, x = y, y = tmp;
            tmp = p, p = q, q = tmp;
        }
        if (p < 0)
            p += mod;
        return p;
    }
    constexpr fp(ll x = 0) : v(x >= 0 ? x % mod : (mod - (-x) % mod) % mod) {}
    fp operator-() const {
        return fp() - *this;
    }
    fp pow(ull t) {
        fp res = 1, b = *this;
        while (t) {
            if (t & 1)
                res *= b;
            b *= b;
            t >>= 1;
        }
        return res;
    }
    fp &operator+=(const fp &x) {
        if ((v += x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator-=(const fp &x) {
        if ((v += mod - x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator*=(const fp &x) {
        v = ull(v) * x.v % mod;
        return *this;
    }
    fp &operator/=(const fp &x) {
        v = ull(v) * x.inv() % mod;
        return *this;
    }
    fp operator+(const fp &x) const {
        return fp(*this) += x;
    }
    fp operator-(const fp &x) const {
        return fp(*this) -= x;
    }
    fp operator*(const fp &x) const {
        return fp(*this) *= x;
    }
    fp operator/(const fp &x) const {
        return fp(*this) /= x;
    }
    bool operator==(const fp &x) const {
        return v == x.v;
    }
    bool operator!=(const fp &x) const {
        return v != x.v;
    }
    friend istream &operator>>(istream &is, fp &x) {
        return is >> x.v;
    }
    friend ostream &operator<<(ostream &os, const fp &x) {
        return os << x.v;
    }
};

template <unsigned mod> void rd(fp<mod> &x) {
    fastio::rd(x.v);
}
template <unsigned mod> void wt(fp<mod> x) {
    fastio::wt(x.v);
}

template <typename T> T Inv(ll n) {
    static const int md = T::get_mod();
    static vector<T> buf({0, 1});
    assert(n > 0);
    n %= md;
    while (SZ(buf) <= n) {
        int k = SZ(buf), q = (md + k - 1) / k;
        buf.push_back(buf[k * q - md] * q);
    }
    return buf[n];
}

template <typename T> T Fact(ll n, bool inv = 0) {
    static const int md = T::get_mod();
    static vector<T> buf({1, 1}), ibuf({1, 1});
    assert(n >= 0 and n < md);
    while (SZ(buf) <= n) {
        buf.push_back(buf.back() * SZ(buf));
        ibuf.push_back(ibuf.back() * Inv<T>(SZ(ibuf)));
    }
    return inv ? ibuf[n] : buf[n];
}

template <typename T> T nPr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nCr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(r, inv ^ 1) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nHr(int n, int r, bool inv = 0) {
    return nCr<T>(n + r - 1, r, inv);
}

/**
 * @brief Modint
 */

static ll DP[2][61][21601] = {};

int main() {
while(1) {
    int N, M;
    cin >> N >> M;
    if (N == 0 && M == 0) return 0;
    vector<pair<int,int>> D(N);
    rep(i,0,N) {
        int A[6], SUM = 0, SUM2 = 0;
        rep(j,0,6) cin >> A[j], SUM += A[j];
        rep(j,0,6) SUM2 += (SUM - A[j] * 6) * (SUM - A[j] * 6);
        D[i] = {SUM, SUM2 / 6};
    }
    int MAXS = 360 * N + 1;
    rep(i,0,2) {
        rep(j,0,N+1) {
            rep(k,0,MAXS) DP[i][j][k] = INF;
        }
    }
    DP[0][0][0] = 0;
    rep(i,0,N) {
        rep(j,0,i+1) {
            rep(k,0,MAXS) DP[(i&1)^1][j][k] = INF;
        }
        rep(j,0,i+1) {
            rep(k,0,MAXS) {
                if (DP[i&1][j][k] == INF) continue;
                chmin(DP[(i&1)^1][j+1][k+D[i].first], DP[i&1][j][k]+D[i].second);
                chmin(DP[(i&1)^1][j+1][abs(k-D[i].first)], DP[i&1][j][k]+D[i].second);
                chmin(DP[(i&1)^1][j][k], DP[i&1][j][k]);
            }
        }
    }
    ll ANS = INF;
    for (ll i = 0; i < MAXS; i++) {
        chmin(ANS, i*i+DP[N&1][M][i]);
    }
    cout << ANS << endl;
}
}
accuracy: 1
time_ms: 4430
memory_kb: 24004
final_rank: 10

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

#include <unistd.h>

namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf


uint32_t pil = 0, pir = 0, por = 0;

struct Pre {
    char num[10000][4];
    constexpr Pre() : num() {
        for (int i = 0; i < 10000; i++) {
            int n = i;
            for (int j = 3; j >= 0; j--) {
                num[i][j] = n % 10 | '0';
                n /= 10;
            }
        }
    }
} constexpr pre;

inline void load() {
    memmove(ibuf, ibuf + pil, pir - pil);
    pir = pir - pil + fread(ibuf + pir - pil, 1, SZ - pir + pil, stdin);
    pil = 0;
    if (pir < SZ)
        ibuf[pir++] = '\n';
}

inline void flush() {
    fwrite(obuf, 1, por, stdout);
    por = 0;
}

void rd(char &c) {
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
}

void rd(string &x) {
    x.clear();
    char c;
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
    do {
        x += c;
        if (pil == pir)
            load();
        c = ibuf[pil++];
    } while (!isspace(c));
}

template <typename T> void rd_real(T &x) {
    string s;
    rd(s);
    x = stod(s);
}

template <typename T> void rd_integer(T &x) {
    if (pil + 100 > pir)
        load();
    char c;
    do
        c = ibuf[pil++];
    while (c < '-');
    bool minus = 0;
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (c == '-') {
            minus = 1, c = ibuf[pil++];
        }
    }
    x = 0;
    while ('0' <= c) {
        x = x * 10 + (c & 15), c = ibuf[pil++];
    }
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (minus)
            x = -x;
    }
}

void rd(int &x) {
    rd_integer(x);
}
void rd(ll &x) {
    rd_integer(x);
}
void rd(i128 &x) {
    rd_integer(x);
}
void rd(uint &x) {
    rd_integer(x);
}
void rd(ull &x) {
    rd_integer(x);
}
void rd(u128 &x) {
    rd_integer(x);
}
void rd(double &x) {
    rd_real(x);
}
void rd(long double &x) {
    rd_real(x);
}

template <class T, class U> void rd(pair<T, U> &p) {
    return rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T> void rd_tuple(T &t) {
    if constexpr (N < std::tuple_size<T>::value) {
        auto &x = std::get<N>(t);
        rd(x);
        rd_tuple<N + 1>(t);
    }
}
template <class... T> void rd(tuple<T...> &tpl) {
    rd_tuple(tpl);
}

template <size_t N = 0, typename T> void rd(array<T, N> &x) {
    for (auto &d : x)
        rd(d);
}
template <class T> void rd(vector<T> &x) {
    for (auto &d : x)
        rd(d);
}

void read() {}
template <class H, class... T> void read(H &h, T &...t) {
    rd(h), read(t...);
}

void wt(const char c) {
    if (por == SZ)
        flush();
    obuf[por++] = c;
}
void wt(const string s) {
    for (char c : s)
        wt(c);
}
void wt(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++)
        wt(s[i]);
}

template <typename T> void wt_integer(T x) {
    if (por > SZ - 100)
        flush();
    if (x < 0) {
        obuf[por++] = '-', x = -x;
    }
    int outi;
    for (outi = 96; x >= 10000; outi -= 4) {
        memcpy(out + outi, pre.num[x % 10000], 4);
        x /= 10000;
    }
    if (x >= 1000) {
        memcpy(obuf + por, pre.num[x], 4);
        por += 4;
    } else if (x >= 100) {
        memcpy(obuf + por, pre.num[x] + 1, 3);
        por += 3;
    } else if (x >= 10) {
        int q = (x * 103) >> 10;
        obuf[por] = q | '0';
        obuf[por + 1] = (x - q * 10) | '0';
        por += 2;
    } else
        obuf[por++] = x | '0';
    memcpy(obuf + por, out + outi + 4, 96 - outi);
    por += 96 - outi;
}

template <typename T> void wt_real(T x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << double(x);
    string s = oss.str();
    wt(s);
}

void wt(int x) {
    wt_integer(x);
}
void wt(ll x) {
    wt_integer(x);
}
void wt(i128 x) {
    wt_integer(x);
}
void wt(uint x) {
    wt_integer(x);
}
void wt(ull x) {
    wt_integer(x);
}
void wt(u128 x) {
    wt_integer(x);
}
void wt(double x) {
    wt_real(x);
}
void wt(long double 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 __attribute__((destructor)) _d() {
    flush();
}
} // namespace fastio


using fastio::flush;
using fastio::print;
using fastio::read;

inline void first(bool i = true) {
    print(i ? "first" : "second");
}
inline void Alice(bool i = true) {
    print(i ? "Alice" : "Bob");
}
inline void Takahashi(bool i = true) {
    print(i ? "Takahashi" : "Aoki");
}
inline void yes(bool i = true) {
    print(i ? "yes" : "no");
}
inline void Yes(bool i = true) {
    print(i ? "Yes" : "No");
}
inline void No() {
    print("No");
}
inline void YES(bool i = true) {
    print(i ? "YES" : "NO");
}
inline void NO() {
    print("NO");
}
inline void Yay(bool i = true) {
    print(i ? "Yay!" : ":(");
}
inline void Possible(bool i = true) {
    print(i ? "Possible" : "Impossible");
}
inline void POSSIBLE(bool i = true) {
    print(i ? "POSSIBLE" : "IMPOSSIBLE");
}

/**
 * @brief Fast IO
 */

template <unsigned mod = 1000000007> struct fp {
    unsigned v;
    static constexpr int get_mod() {
        return mod;
    }
    constexpr unsigned inv() const {
        assert(v != 0);
        int x = v, y = mod, p = 1, q = 0, t = 0, tmp = 0;
        while (y > 0) {
            t = x / y;
            x -= t * y, p -= t * q;
            tmp = x, x = y, y = tmp;
            tmp = p, p = q, q = tmp;
        }
        if (p < 0)
            p += mod;
        return p;
    }
    constexpr fp(ll x = 0) : v(x >= 0 ? x % mod : (mod - (-x) % mod) % mod) {}
    fp operator-() const {
        return fp() - *this;
    }
    fp pow(ull t) {
        fp res = 1, b = *this;
        while (t) {
            if (t & 1)
                res *= b;
            b *= b;
            t >>= 1;
        }
        return res;
    }
    fp &operator+=(const fp &x) {
        if ((v += x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator-=(const fp &x) {
        if ((v += mod - x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator*=(const fp &x) {
        v = ull(v) * x.v % mod;
        return *this;
    }
    fp &operator/=(const fp &x) {
        v = ull(v) * x.inv() % mod;
        return *this;
    }
    fp operator+(const fp &x) const {
        return fp(*this) += x;
    }
    fp operator-(const fp &x) const {
        return fp(*this) -= x;
    }
    fp operator*(const fp &x) const {
        return fp(*this) *= x;
    }
    fp operator/(const fp &x) const {
        return fp(*this) /= x;
    }
    bool operator==(const fp &x) const {
        return v == x.v;
    }
    bool operator!=(const fp &x) const {
        return v != x.v;
    }
    friend istream &operator>>(istream &is, fp &x) {
        return is >> x.v;
    }
    friend ostream &operator<<(ostream &os, const fp &x) {
        return os << x.v;
    }
};

template <unsigned mod> void rd(fp<mod> &x) {
    fastio::rd(x.v);
}
template <unsigned mod> void wt(fp<mod> x) {
    fastio::wt(x.v);
}

template <typename T> T Inv(ll n) {
    static const int md = T::get_mod();
    static vector<T> buf({0, 1});
    assert(n > 0);
    n %= md;
    while (SZ(buf) <= n) {
        int k = SZ(buf), q = (md + k - 1) / k;
        buf.push_back(buf[k * q - md] * q);
    }
    return buf[n];
}

template <typename T> T Fact(ll n, bool inv = 0) {
    static const int md = T::get_mod();
    static vector<T> buf({1, 1}), ibuf({1, 1});
    assert(n >= 0 and n < md);
    while (SZ(buf) <= n) {
        buf.push_back(buf.back() * SZ(buf));
        ibuf.push_back(ibuf.back() * Inv<T>(SZ(ibuf)));
    }
    return inv ? ibuf[n] : buf[n];
}

template <typename T> T nPr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nCr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(r, inv ^ 1) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nHr(int n, int r, bool inv = 0) {
    return nCr<T>(n + r - 1, r, inv);
}

/**
 * @brief Modint
 */

static ll DP[2][61][21601] = {};

int main() {
while(1) {
    int N, M;
    cin >> N >> M;
    if (N == 0 && M == 0) return 0;
    vector<pair<int,int>> D(N);
    rep(i,0,N) {
        int A[6], SUM = 0, SUM2 = 0;
        rep(j,0,6) cin >> A[j], SUM += A[j];
        rep(j,0,6) SUM2 += (SUM - A[j] * 6) * (SUM - A[j] * 6);
        D[i] = {SUM, SUM2 / 6};
    }
    int MAXS = 360 * N + 1;
    rep(i,0,2) {
        rep(j,0,N+1) {
            rep(k,0,MAXS) DP[i][j][k] = INF;
        }
    }
    DP[0][0][0] = 0;
    rep(i,0,N) {
        rep(j,0,N+1) {
            rep(k,0,MAXS) DP[(i&1)^1][j][k] = INF;
        }
        rep(j,0,i+1) {
            rep(k,0,MAXS) {
                if (DP[i&1][j][k] == INF) continue;
                chmin(DP[(i&1)^1][j+1][k+D[i].first], DP[i&1][j][k]+D[i].second);
                chmin(DP[(i&1)^1][j+1][abs(k-D[i].first)], DP[i&1][j][k]+D[i].second);
                chmin(DP[(i&1)^1][j][k], DP[i&1][j][k]);
            }
        }
    }
    ll ANS = INF;
    for (ll i = 0; i < MAXS; i++) {
        chmin(ANS, i*i+DP[N&1][M][i]);
    }
    cout << ANS << endl;
}
}
accuracy: 1
time_ms: 5800
memory_kb: 24020
final_rank: 11

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<ll> vi;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef vector<vvb> vvvb;
typedef vector<vvvb> vvvvb;
typedef pair<ll,ll> pi;
typedef pair<ll,pi> ppi;
#define FOR(i,l,r) for(ll i=l;i<r;i++)
#define REP(i,n) FOR(i,0,n)
#define RFOR(i,l,r) for(ll i=r-1;i>=l;i--)
#define RREP(i,n) RFOR(i,0,n)
#define sz(A) (ll)(A.size())
#define ALL(A) A.begin(),A.end()
#define LB(A,x) (ll)(lower_bound(ALL(A),x)-A.begin())
#define UB(A,x) (ll)(upper_bound(ALL(A),x)-A.begin())
#define COU(A,x) (UB(A,x)-LB(A,x))
#define F first
#define S second
template<typename T>using min_priority_queue=priority_queue<T,vector<T>,greater<T>>;
template<typename T1,typename T2>ostream&operator<<(ostream&os,pair<T1,T2>&p){os<<p.F<<" "<<p.S;return os;}
template<typename T1,typename T2>istream&operator>>(istream&is,pair<T1,T2>&p){is>>p.F>>p.S;return is;}
template<typename T>ostream&operator<<(ostream&os,vector<T>&v){REP(i,sz(v))os<<v[i]<<(i+1!=sz(v)?" ":"");return os;}
template<typename T>istream&operator>>(istream&is,vector<T>&v){for(T&in:v)is>>in;return is;}
template<class T>bool chmax(T&a,T b){if(a<b){a=b;return 1;}return 0;}
template<class T>bool chmin(T&a,T b){if(b<a){a=b;return 1;}return 0;}
const ll mod=998244353;
int main(){
    while(1){
        int N,M;cin>>N>>M;
        if(!N)return 0;
        vector<int>B(N),C(N);
        REP(i,N){
            vector<int>A(6);cin>>A;
            REP(j,6)B[i]+=A[j];
            REP(j,6)C[i]+=A[j]*A[j];
            C[i]*=6;C[i]-=B[i]*B[i];
        }
        vector<vector<int>>DP(M+1,vector<int>(360*M+1,1e9));
        DP[0][0]=0;
        REP(i,N){
            auto EP=DP;
            REP(j,M)REP(k,360*M+1){
                chmin(EP[j+1][abs(k-B[i])],DP[j][k]+C[i]);
                if(k+B[i]<=360*M)chmin(EP[j+1][k+B[i]],DP[j][k]+C[i]);
            }
            DP=EP;
        }
        ll ans=1e18;
        REP(i,360*M+1)chmin(ans,DP[M][i]+i*i);
        cout<<ans<<endl;
    }
    return 0;
}
accuracy: 1
time_ms: 7560
memory_kb: 13516
final_rank: 15

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

constexpr int MAX_N = 60;
constexpr int MAX_A = 360;
constexpr int OFFSET = MAX_N * MAX_A;
constexpr int inf = (1 << 30) - 1;

template <class T> void chmin(T& x, const T& y) {
    if (x > y) x = y;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int N, M;
    while (true) {
        cin >> N >> M;
        if (N == 0) break;
        int nowM = 0; 
        int nowOff = nowM * MAX_A;
        vector dp(nowM + 1, vector(2 * nowOff + 1, inf));
        dp[0][0 + nowOff] = 0;
        for (int i = 0; i < N; ++i) {
            int A = 0, B = 0;
            for (int j = 0; j < 6; ++j) {
                int x;
                cin >> x;
                A += x;
                B += x * x;
            }
            int nextM = min(nowM + 1, M);
            int nextOff = nextM * MAX_A;
            vector ndp(nextM + 1, vector(2 * nextOff + 1, inf));
            for (int j = 0; j <= nowM; ++j) {
                for (int k = -j * MAX_A; k <= j * MAX_A; ++k) {
                    const int x = dp[j][k + nowOff];
                    if (x == inf) continue;
                    chmin(ndp[j][k + nextOff], x);
                    if (j < nextM) {
                        chmin(ndp[j + 1][k + A + nextOff], x + 2 * A * k + 6 * B);
                        chmin(ndp[j + 1][k - A + nextOff], x - 2 * A * k + 6 * B);
                    }
                }
            }
            nowM = nextM;
            nowOff = nextOff;
            dp = move(ndp);
        }
        const auto& vec = dp[M];
        cout << *min_element(begin(vec), end(vec)) << '\n';
    }
    return 0;
}
accuracy: 1
time_ms: 3220
memory_kb: 25020
final_rank: 6

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using vvvll = vector<vvll>;
#define rep(i,n) for(ll i=0;i<n;i++)
#define all(A) A.begin(),A.end()


void solve(ll N, ll M) {
    ll B=min(M*60*6+1,ll(8000));
    vvll DP(M+1,vll(B*2+1,1e18));
    DP[0][B]=0;
    rep(i,N){
        vvll NDP=DP;
        vll A(6);
        ll S=0,T=0;
        rep(j,6){
            cin>>A[j];
            S+=A[j];
            T+=A[j]*A[j];
        }
        ll av=6*S;
        ll va=6*T-S;
        rep(m,M){
            rep(a,B*2+1){
                if(DP[m][a]>1e17)continue;
                ll sm=a-(B);
                NDP[m+1][a+S]=min(NDP[m+1][a+S],DP[m][a]+2*S*sm+6*T);
                NDP[m+1][a-S]=min(NDP[m+1][a-S],DP[m][a]-2*S*sm+6*T);
            }
        }
        swap(DP,NDP);
    }
    ll an=1e18;
    rep(i,B*2+1){
        an=min(an,DP[M][i]);
    }
    cout<<an<<endl;
}

int main() {
    
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    ll N,M;
    // clock_t Start=clock();
    while (cin >> N >> M, N+M != 0){
        clock_t start=clock();
        solve(N, M);
        clock_t end=clock();
        // cout<<fixed<<setprecision(15)<<double(start-end)/CLOCKS_PER_SEC<<endl;
    }
    // clock_t End=clock();
    // cout<<fixed<<setprecision(15)<<double(End-Start)/CLOCKS_PER_SEC<<endl;
}
accuracy: 1
time_ms: 6540
memory_kb: 18480
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i, m, n) for (ll i = m; i < n; i++)
#define rrep(i, m, n) for (ll i = m - 1; i >= n; i--)
#define pb(n) push_back(n)
#define UE(N) N.erase(unique(N.begin(), N.end()), N.end());
#define Sort(n) sort(n.begin(), n.end())
#define Rev(n) reverse(n.begin(), n.end())
#define HOUT(S) cout << setprecision(50) << S << endl
#define pint pair<ll, ll>
#define tint tuple<ll, ll, ll>
#define mod 1000000007
#define MAX 100010LL
#define endl "\n"
#define ALL(a) a.begin(), a.end()
#define chmax(a, b) a = (((a) < (b)) ? (b) : (a))
#define chmin(a, b) a = (((a) > (b)) ? (b) : (a))

template <typename T> vector<T> make_v(size_t a) { return vector<T>(a); }

template <typename T, typename... Ts> auto make_v(size_t a, Ts... ts) {
    return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));
}

template <typename T, typename U, typename... V>
typename enable_if<is_same<T, U>::value != 0>::type fill_v(U& u, const V... v) {
    u = U(v...);
}

template <typename T, typename U, typename... V>
typename enable_if<is_same<T, U>::value == 0>::type fill_v(U& u, const V... v) {
    for (auto& e : u) fill_v<T>(e, v...);
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    ll N, M;
    cin >> N >> M;
    while(N) {
        vector<ll> Dice(N, 0), DD(N, 0);
        rep(i, 0, N) rep(j, 0, 6) {
            ll x;
            cin >> x;
            Dice[i] += x;
            DD[i] += x * x;
        }
        ll u = 3600;
        auto dp = make_v<ll>(2, M + 1, 2 * u + 1);
        fill_v<ll>(dp, mod);
        dp[0][0][u] = 0;
        ll w = 0;
        rep(i, 0, N) {
            dp[w ^ 1] = dp[w];
            rep(j, 0, min(i + 1, M + 1)) {
                rep(k, 0, 2 * u + 1) {
                    if(dp[w][j][k] == mod) continue;
                    if(j < M) {
                        if(k + Dice[i] < 2 * u + 1) chmin(dp[w ^ 1][j + 1][k + Dice[i]], dp[w][j][k] + 2 * (k - u) * Dice[i] + 6 * DD[i]);
                        if(k - Dice[i] > -1) chmin(dp[w ^ 1][j + 1][k - Dice[i]], dp[w][j][k] - 2 * (k - u) * Dice[i] + 6 * DD[i]);
                    }
                }
            }
            w ^= 1;
        }
        ll ans = mod;
        rep(i, 0, 2 * u + 1) chmin(ans, dp[w][M][i]);
        cout << ans << endl;
        cin >> N >> M;
    }
}
accuracy: 1
time_ms: 1810
memory_kb: 13416
final_rank: 3

code_snippet: /// 生成AI不使用 / Not using generative AI

// #pragma GCC target ("avx")
// #pragma GCC optimize("Ofast")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

#ifdef MARC_LOCAL
#define _GLIBCXX_DEBUG
#endif

#ifdef ATCODER
#include <atcoder/all>
using namespace atcoder;
#endif

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

//#define int long long
using ll = long long; using vll = vector<ll>; using vvll = vector<vll>; using vvvll = vector<vvll>; using vvvvll = vector<vvvll>;
using vi = vector<int>; using vvi = vector<vi>; using vvvi = vector<vvi>; using vvvvi = vector<vvvi>;
using ld = long double; using vld = vector<ld>; using vvld = vector<vld>; using vd = vector<double>;
using vc = vector<char>; using vvc = vector<vc>; using vs = vector<string>;
using vb = vector<bool>; using vvb = vector<vb>; using vvvb = vector<vvb>;
using pii = pair<int, int>; using pcc = pair<char, char>; using pll = pair<ll, ll>; using pli = pair<ll, int>; using pdd = pair<double, double>; using pldld = pair<ld,ld>;
using vpii = vector<pii>; using vvpii = vector<vpii>; using vpll = vector<pll>; using vvpll = vector<vpll>; using vpldld = vector<pldld>;
using ui = unsigned int; using ull = unsigned long long;
using i128 = __int128; using f128 = __float128;
template<class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#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 overload4(a,b,c,d,name,...) name
#define rep1(n) for(ll i = 0; i < (ll)n; i++)
#define rep2(i,n) for(int i = 0; i < (ll)n; 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 += (ll)c)
#define rep(...) overload4(__VA_ARGS__,rep4,rep3,rep2,rep1)(__VA_ARGS__)
#define repback1(n) for (ll i = (ll)n-1; i >= 0; i--)
#define repback2(i,n) for (ll i = (ll)n-1; i >= 0; i--)
#define repback3(i,a,b) for (ll i = (ll)b-1; i >= (ll)a; i--)
#define repback4(i,a,b,c) for (ll i = (ll)b-1; i >= (ll)a; i -= (ll)c)
#define repback(...) overload4(__VA_ARGS__,repback4,repback3,repback2,repback1)(__VA_ARGS__)
#define all(x) (x).begin(), (x).end()
#define include(y, x, H, W) (0 <= (y) && (y) < (H) && 0 <= (x) && (x) < (W))
#define inrange(x, down, up) ((down) <= (x) && (x) <= (up))
#define pb push_back
#define eb emplace_back
#define fir first
#define sec second
#define TIMER_START TIME_START = clock()
#ifdef MARC_LOCAL
// https://trap.jp/post/1224/
#define debug1(x) cout << "debug: " << (#x) << ": " << (x) << endl
#define debug2(x, y) cout << "debug: " << (#x) << ": " << (x) << ", " << (#y) << ": " << (y) << endl
#define debug3(x, y, z) cout << "debug: " << (#x) << ": " << (x) << ", " << (#y) << ": " << (y) << ", " << (#z) << ": " << (z) << endl
#define debug4(x, y, z, w) cout << "debug: " << (#x) << ": " << (x) << ", " << (#y) << ": " << (y) << ", " << (#z) << ": " << (z) << ", " << (#w) << ": " << (w) << endl
#define debug5(x, y, z, w, v) cout << "debug: " << (#x) << ": " << (x) << ", " << (#y) << ": " << (y) << ", " << (#z) << ": " << (z) << ", " << (#w) << ": " << (w) << ", " << (#v) << ": " << (v) << endl
#define debug6(x, y, z, w, v, u) cout << "debug: " << (#x) << ": " << (x) << ", " << (#y) << ": " << (y) << ", " << (#z) << ": " << (z) << ", " << (#w) << ": " << (w) << ", " << (#v) << ": " << (v) << ", " << (#u) << ": " << (u) << endl
#define overload6(a, b, c, d, e, f, g,...) g
#define debug(...) overload6(__VA_ARGS__, debug6, debug5, debug4, debug3, debug2, debug1)(__VA_ARGS__)
#define debuga cerr << "a" << endl
#define debugnl cout << endl
#define Case(i) cout << "Case #" << (i) << ": "
#define TIMECHECK cerr << 1000.0 * static_cast<double>(clock() - TIME_START) / CLOCKS_PER_SEC << "ms" << endl
#define LOCAL 1
#else
#define debug1(x) void(0)
#define debug2(x, y) void(0)
#define debug3(x, y, z) void(0)
#define debug4(x, y, z, w) void(0)
#define debug5(x, y, z, w, v) void(0)
#define debug6(x, y, z, w, v, u) void(0)
#define debug(...) void(0)
#define debuga void(0)
#define debugnl void(0)
#define Case(i) void(0)
#define TIMECHECK void(0)
#define LOCAL 0
#endif

//mt19937_64 rng(0);
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
clock_t TIME_START;
const long double pi = 3.141592653589793238462643383279L;
const long long INFL = 1000000000000000000ll;
const long long INFLMAX = numeric_limits< long long >::max(); // 9223372036854775807
const int INF = 1000000000;
const int INFMAX = numeric_limits< int >::max(); // 2147483647
const long double INFD = numeric_limits<ld>::infinity();
const long double EPS = 1e-10;
const int mod1 = 1000000007;
const int mod2 = 998244353;
const vi dx1 = {1,0,-1,0};
const vi dy1 = {0,1,0,-1};
const vi dx2 = {0, 1, 1, 1, 0, -1, -1, -1};
const vi dy2 = {1, 1, 0, -1, -1, -1, 0, 1};
constexpr char nl = '\n';
constexpr char bl = ' ';

std::ostream &operator<<(std::ostream &dest, __int128_t value) { std::ostream::sentry s(dest); if (s) {__uint128_t tmp = value < 0 ? -value : value; char buffer[128]; char *d = std::end(buffer); do {--d;*d = "0123456789"[tmp % 10];tmp /= 10;} while (tmp != 0);if (value < 0) {--d;*d = '-';}int len = std::end(buffer) - d;if (dest.rdbuf()->sputn(d, len) != len) {dest.setstate(std::ios_base::badbit);}}return dest; }
__int128 parse(string &s) { __int128 ret = 0; for (int i = 0; i < (int)s.length(); i++) if ('0' <= s[i] && s[i] <= '9') ret = 10 * ret + s[i] - '0'; return ret; } // for __int128 (https://kenkoooo.hatenablog.com/entry/2016/11/30/163533)
template<class T> ostream& operator << (ostream& os, vector<T>& vec) { os << "["; for (int i = 0; i<(int)vec.size(); i++) { os << vec[i] << (i + 1 == (int)vec.size() ? "" : ", "); } os << "]"; return os; } /// vector 出力
template<class T, class U> ostream& operator << (ostream& os, pair<T, U>& pair_var) { os << "(" << pair_var.first << ", " << pair_var.second << ")"; return os; } // pair 出力
template<class T, class U> ostream& operator << (ostream& os, map<T, U>& map_var) { os << "{"; for (auto itr = map_var.begin(); itr != map_var.end(); itr++) { os << "(" << itr->first << ", " << itr->second << ")"; itr++; if(itr != map_var.end()) os << ", "; itr--; } os << "}"; return os; } // map出力
template<class T> ostream& operator << (ostream& os, set<T>& set_var) { os << "{"; for (auto itr = set_var.begin(); itr != set_var.end(); itr++) { os << *itr; ++itr; if(itr != set_var.end()) os << ", "; itr--; } os << "}"; return os; } /// set 出力

bool equals(long double a, long double b) { return fabsl(a - b) < EPS; }
template<class T> int sign(T a) { return equals(a, 0) ? 0 : a > 0 ? 1 : -1; }
long double radian_to_degree(long double r) { return (r * 180.0 / pi); }
long double degree_to_radian(long double d) { return (d * pi / 180.0); }

int popcnt(unsigned long long a){ return __builtin_popcountll(a); } // ll は 64bit対応！
int MSB1(unsigned long long x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); } // MSB(1), 0-indexed ( (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2) )
int LSB1(unsigned long long x) { return (x == 0 ? -1 : __builtin_ctzll(x)); } // LSB(1), 0-indexed ( (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2) )
long long maskbit(int n) { return (1LL << n) - 1; }
bool bit_is1(long long x, int i) { return ((x>>i) & 1); }
string charrep(int n, char c) { return std::string(n, c); }
template<class T> T square(T x) { return (x) * (x); }
template<class T>void UNIQUE(T& A) {sort(all(A)); A.erase(unique(all(A)), A.end());}
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; }
template<class T, class U> bool chmin(T& a, const U& b){ return chmin(a, (T)b); }
template<class T, class U> bool chmax(T& a, const U& b){ return chmax(a, (T)b); }
void YESNO(bool b) {if(b){cout<<"YES"<<'\n';} else{cout<<"NO"<<'\n';}} void YES() {YESNO(true);} void NO() {YESNO(false);}
void yesno(bool b) {if(b){cout<<"yes"<<'\n';} else{cout<<"no"<<'\n';}} void yes() {yesno(true);} void no() {yesno(false);}
void YesNo(bool b) {if(b){cout<<"Yes"<<'\n';} else{cout<<"No"<<'\n';}} void Yes() {YesNo(true);} void No() {YesNo(false);}
void POSIMPOS(bool b) {if(b){cout<<"POSSIBLE"<<'\n';} else{cout<<"IMPOSSIBLE"<<'\n';}}
void PosImpos(bool b) {if(b){cout<<"Possible"<<'\n';} else{cout<<"Impossible"<<'\n';}}
void posimpos(bool b) {if(b){cout<<"possible"<<'\n';} else{cout<<"impossible"<<'\n';}}
void FIRSEC(bool b) {if(b){cout<<"FIRST"<<'\n';} else{cout<<"SECOND"<<'\n';}}
void firsec(bool b) {if(b){cout<<"first"<<'\n';} else{cout<<"second"<<'\n';}}
void FirSec(bool b) {if(b){cout<<"First"<<'\n';} else{cout<<"Second"<<'\n';}}
void AliBob(bool b) {if(b){cout<<"Alice"<<'\n';} else{cout<<"Bob"<<'\n';}}
void TakAok(bool b) {if(b){cout<<"Takahashi"<<'\n';} else{cout<<"Aoki"<<'\n';}}
int GetTime() {return 1000.0*static_cast<double>(clock() - TIME_START) / CLOCKS_PER_SEC;}
ll myRand(ll B) {return (unsigned long long)rng() % B;}
template<class T> void print(const T& x, const char endch = '\n') { cout << x << endch; }

template<class T> T ceil_div(T x, T y) { assert(y); return (x > 0 ? (x + y - 1) / y : x / y); }
template<class T> T floor_div(T x, T y) { assert(y); return (x > 0 ? x / y : (x - y + 1) / y); }
template<class T> pair<T, T> divmod(T x, T y) { T q = floor_div(x, y); return {q, x - q * y}; } /// (q, r) s.t. x = q*y + r 
ll GCD(ll a, ll b) { if(a < b) swap(a, b); if(b == 0) return a; if(a%b == 0) return b; else return GCD(b, a%b); }
ll LCM(ll a, ll b) { assert(GCD(a,b) != 0); return a / GCD(a, b) * b; }
ll MOD(ll &x, const ll P) { ll ret = x%P; if(ret < 0) ret += P; return x = ret; } /// x % P を非負整数に直す
ll mpow(ll x, ll n, const ll mod) { x %= mod; ll ret = 1; while(n > 0) { if(n & 1) ret = ret * x % mod; x = x * x % mod; n >>= 1; } return ret; } /// x^n % mod を計算
ll lpow(ll x, ll n) { ll ret = 1; while(n > 0){ if(n & 1) ret = ret * x; x = x * x; n >>= 1; } return ret; } /// x^nを計算
string toBinary(ll n) { if(n == 0) return "0"; assert(n > 0); string ret; while (n != 0){ ret += ( (n & 1) == 1 ? '1' : '0' ); n >>= 1; } reverse(ret.begin(), ret.end()); return ret; } /// 10進数(long long) -> 2進数(string)への変換
ll toDecimal(string S) { ll ret = 0; for(int i = 0; i < (int)S.size(); i++){ ret *= 2LL; if(S[i] == '1') ret += 1; } return ret; } /// 2進数(string)　→　10進数(long long)への変換
int ceil_pow2(ll n) { int x = 0; while ((1ll << x) < n) x++; return x;} /// return minimum non-negative `x` s.t. `n <= 2**x`
int floor_pow2(ll n) { int x = 0; while ((1ll << (x+1)) <= n) x++; return x;} /// return maximum non-negative `x` s.t. `n >= 2**x`


// ############################
// #                          #
// #    C O D E  S T A R T    #
// #                          #
// ############################

/// main()の中に0を受け取る変数（終了判定）を定義しておく
int N,M;

// E[(X+A)^2] = E[X^2] + 2*E[A]*E[X] + E[A^2] を用いて、DPを更新する（期待値の線形性に加えて、各サイコロ独立なので、E[AX] = E[A]E[X]が成立する！）
//  -> あらかじめ全て36倍として取り扱えるように調整する
// E[X^2] = (E[X])^2 + V[X] を用いても良い（これも各サイコロ独立なので、V[X+Y] = V[X]+V[Y]が成立する！）
void solve() {
    vvi A(N, vi(6)); rep(i,N) rep(j,6) cin >> A[i][j];
    vi B(N,0); rep(i,N) rep(j,6) B[i] += A[i][j]; // E[A[i]]
    vi C(N,0); rep(i,N) rep(j,6) C[i] += A[i][j] * A[i][j] * 6; // E[A[i]^2]
    vi ac(N+1,0); rep(i,N) ac[i+1] = ac[i] + B[i];
    
    vvi dp(M+1, vi(1,0)); // dp[i][j] := サイコロをi個採用して、(x-y)がjのときの、E[x-y]の期待値の最小値
    dp[0][0] = 0;
    rep(i,N) {
        int prev = dp[0].size();
        int cur = 2*ac[i+1] + 1;
        int prevofs = ac[i];
        int curofs = ac[i+1];
        vvi nxt(M+1, vi(cur, INF));

        rep(j,min(i,M)+1) {
            rep(k,prev) {
                if(dp[j][k] == INF) continue;
                chmin(nxt[j][k-prevofs+curofs], dp[j][k]); // 採用しない
                if(j < M) {
                    chmin(nxt[j+1][k+B[i]-prevofs+curofs], dp[j][k] + C[i] + 2*B[i]*(k-prevofs)); // xに渡す
                    chmin(nxt[j+1][k-B[i]-prevofs+curofs], dp[j][k] + C[i] - 2*B[i]*(k-prevofs)); // yに渡す
                }
            }
        }
        
        swap(dp, nxt);
    }

    int ans = INF;
    for(auto v:dp[M]) chmin(ans, v);
    
    cout << ans << endl;

}



signed main() {
    cin.tie(0); ios_base::sync_with_stdio(false);
    TIMER_START;
    //cout << fixed << setprecision(15);
    

    //int tt = 1;
    //cin >> tt;
    while(true){
        cin >> N >> M;
        //debug(N,M);
        if(N == 0 && M == 0) break;

        solve();
    }

    TIMECHECK;
    return 0;
}
accuracy: 1
time_ms: 3560
memory_kb: 15648
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(v) v.begin(), v.end()
template <class T, class U>
inline bool chmax(T& a, U b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <class T, class U>
inline bool chmin(T& a, U b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
constexpr int INF = 1000000000;
constexpr int64_t llINF = 3000000000000000000;
constexpr double eps = 1e-10;
const double pi = acos(-1);
struct linear_sieve {
    vector<int> least_factor, prime_list;
    linear_sieve(int n) : least_factor(n + 1, 0) {
        for (int i = 2; i <= n; i++) {
            if (least_factor[i] == 0) {
                least_factor[i] = i;
                prime_list.push_back(i);
            }
            for (int p : prime_list) {
                if (ll(i) * p > n || p > least_factor[i]) break;
                least_factor[i * p] = p;
            }
        }
    }
};
ll extgcd(ll a, ll b, ll& x, ll& y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll d = extgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
ll modpow(ll a, ll b, ll m) {
    ll res = 1;
    while (b) {
        if (b & 1) {
            res *= a;
            res %= m;
        }
        a *= a;
        a %= m;
        b >>= 1;
    }
    return res;
}
template <int modulo>
struct modint {
    int x;
    modint() : x(0) {}
    modint(int64_t y) : x(y >= 0 ? y % modulo : (modulo - (-y) % modulo) % modulo) {}
    modint& operator+=(const modint& p) {
        if ((x += p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint& operator-=(const modint& p) {
        if ((x += modulo - p.x) >= modulo) x -= modulo;
        return *this;
    }
    modint& operator*=(const modint& p) {
        x = (int)(1LL * x * p.x % modulo);
        return *this;
    }
    modint& operator/=(const modint& p) {
        *this *= p.inv();
        return *this;
    }
    modint operator-() const { return modint(-x); }
    modint operator+(const modint& p) const { return modint(*this) += p; }
    modint operator-(const modint& p) const { return modint(*this) -= p; }
    modint operator*(const modint& p) const { return modint(*this) *= p; }
    modint operator/(const modint& p) const { return modint(*this) /= p; }
    bool operator==(const modint& p) const { return x == p.x; }
    bool operator!=(const modint& p) const { return x != p.x; }
    modint inv() const {
        int a = x, b = modulo, u = 1, v = 0, t;
        while (b > 0) {
            t = a / b;
            swap(a -= t * b, b);
            swap(u -= t * v, v);
        }
        return modint(u);
    }
    modint pow(int64_t n) const {
        modint ret(1), mul(x);
        while (n > 0) {
            if (n & 1) ret *= mul;
            mul *= mul;
            n >>= 1;
        }
        return ret;
    }
    friend ostream& operator<<(ostream& os, const modint& p) { return os << p.x; }
    friend istream& operator>>(istream& is, modint& a) {
        int64_t t;
        is >> t;
        a = modint<modulo>(t);
        return (is);
    }
    int val() const { return x; }
    static constexpr int mod() { return modulo; }
    static constexpr int half() { return (modulo + 1) >> 1; }
};
template <typename T>
struct Binomial {
    vector<T> inv, fact, factinv;
    Binomial(int n) {
        inv.resize(n + 1);
        fact.resize(n + 1);
        factinv.resize(n + 1);
        inv[0] = fact[0] = factinv[0] = 1;
        for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i;
        factinv[n] = fact[n].inv();
        inv[n] = fact[n - 1] * factinv[n];
        for (int i = n - 1; i >= 1; i--) {
            factinv[i] = factinv[i + 1] * (i + 1);
            inv[i] = fact[i - 1] * factinv[i];
        }
    }
    T C(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r] * factinv[r];
    }
    T P(int n, int r) {
        if (n < 0 || n < r || r < 0) return 0;
        return fact[n] * factinv[n - r];
    }
    T H(int n, int r) {
        if (n == 0 && r == 0) return 1;
        if (n < 0 || r < 0) return 0;
        return r == 0 ? 1 : C(n + r - 1, r);
    }
};
namespace geometry {

using floating_point_type = long double;

constexpr floating_point_type EPS = 1e-13;
constexpr floating_point_type Pi = 3.141592653589793;

constexpr floating_point_type operator"" _deg(floating_point_type deg) { return static_cast<floating_point_type>(deg * Pi / 180.0); }
constexpr floating_point_type operator"" _deg(unsigned long long deg) { return static_cast<floating_point_type>(deg * Pi / 180.0); }

template <typename T>
constexpr int sgn(T a) noexcept {
    return (a < -EPS ? -1 : (a > EPS ? +1 : 0));
}

template <typename T, typename U>
constexpr bool same(T a, U b) noexcept {
    return sgn(a - b) == 0;
}

template <typename T>
constexpr T square(T x) noexcept {
    return x * x;
}

// ax + by + c = 0, gcd(a,b,c) = 1
// a != 0 : a > 0
// a = 0: b > 0
tuple<long long, long long, long long> general_form(long long x1, long long y1, long long x2, long long y2) {
    long long a = y1 - y2, b = x2 - x1, c = x1 * y2 - x2 * y1;
    if (a < 0) a = -a, b = -b, c = -c;
    if (a == 0 && b < 0) b = -b, c = -c;
    long long g = gcd(gcd(a, b), c);
    return {a / g, b / g, c / g};
}

template <typename T>
struct Vector2D {
    using value_type = T;
    T x, y;

    Vector2D() = default;
    explicit Vector2D(T arg) : x(cos(arg)), y(sin(arg)) {}
    constexpr Vector2D(T x, T y) noexcept : x(x), y(y) {}

    constexpr bool operator<(const Vector2D& v) const noexcept {
        if (!same(x, v.x)) return x < v.x;
        return y < v.y;
    }
    constexpr bool operator>(const Vector2D& v) const noexcept { return v < *this; }
    constexpr bool operator==(const Vector2D& v) const noexcept { return same(x, v.x) && same(y, v.y); }
    constexpr bool operator!=(const Vector2D& v) const noexcept { return !(*this == v); }

    constexpr Vector2D operator+() const noexcept { return *this; }
    constexpr Vector2D operator-() const noexcept { return {-x, -y}; }

    constexpr Vector2D operator+(const Vector2D& v) const noexcept { return {x + v.x, y + v.y}; }
    constexpr Vector2D operator-(const Vector2D& v) const noexcept { return {x - v.x, y - v.y}; }
    constexpr Vector2D operator*(T s) const noexcept { return {x * s, y * s}; }
    constexpr Vector2D operator/(T s) const noexcept { return {x / s, y / s}; }

    constexpr Vector2D& operator+=(const Vector2D& v) noexcept {
        x += v.x;
        y += v.y;
        return *this;
    }
    constexpr Vector2D& operator-=(const Vector2D& v) noexcept {
        x -= v.x;
        y -= v.y;
        return *this;
    }
    constexpr Vector2D& operator*=(T s) noexcept {
        x *= s;
        y *= s;
        return *this;
    }
    constexpr Vector2D& operator/=(T s) noexcept {
        x /= s;
        y /= s;
        return *this;
    }

    constexpr bool isZero() const noexcept { return x == T(0) && y == T(0); }
    bool hasNan() const { return isnan(x) || isnan(y); }

    constexpr T dot(const Vector2D& v) const noexcept { return x * v.x + y * v.y; }
    constexpr T cross(const Vector2D& v) const noexcept { return x * v.y - y * v.x; }

    floating_point_type length() const {
        if (isZero()) return 0.0;

        const T abs_x = std::abs(x);
        const T abs_y = std::abs(y);

        const auto [u, v] = std::minmax(abs_x, abs_y);
        const T t = u / v;

        return v * std::sqrt(std::fma(t, t, 1.0));
    }
    constexpr T lengthSq() const noexcept { return dot(*this); }

    floating_point_type distanceFrom(const Vector2D& v) const { return (v - *this).length(); }
    constexpr T distanceFromSq(const Vector2D& v) const noexcept { return (v - *this).lengthSq(); }

    Vector2D normalized() const { return *this / length(); }
    Vector2D& normalize() { return *this /= length(); }

    Vector2D rotated(floating_point_type angle) const {
        const T s = sin(angle);
        const T c = cos(angle);
        return {x * c - y * s, x * s + y * c};
    }
    Vector2D& rotate(floating_point_type angle) { return *this = rotated(angle); }

    floating_point_type arg() const { return atan2<floating_point_type>(y, x); }
    floating_point_type arg(const Vector2D& v) const {
        if (isZero() || v.isZero()) {
            return numeric_limits<T>::signaling_NaN();
        }

        return atan2<floating_point_type>(cross(v), dot(v));
    }
    floating_point_type arg(const Vector2D& a, const Vector2D& b) const { return (a - *this).arg(b - *this); }

    constexpr Vector2D lerp(const Vector2D& v, T f) const noexcept { return {x + (v.x - x) * f, y + (v.y - y) * f}; }

    constexpr friend Vector2D operator*(T s, const Vector2D& v) noexcept { return {s * v.x, s * v.y}; }
    friend istream& operator>>(istream& is, Vector2D& v) { return is >> v.x >> v.y; }
    friend ostream& operator<<(ostream& os, const Vector2D& v) { return os << "(" << v.x << ", " << v.y << ")"; }
};

template <typename T>
void argument_sort(vector<Vector2D<T>>& vec, const Vector2D<T>& center = Vector2D<T>(0, 0)) {
    auto orthant = [](const Vector2D<T>& v) {
        if (sgn(v.x) < 0 && sgn(v.y) < 0) return 0;
        if (sgn(v.x) >= 0 && sgn(v.y) < 0) return 1;
        if (sgn(v.x) == 0 && sgn(v.y) == 0) return 2;
        if (sgn(v.x) >= 0 && sgn(v.y) >= 0) return 3;
        return 4;
    };

    auto comp = [orthant, center](const Vector2D<T>& a, const Vector2D<T>& b) {
        const int o1 = orthant(a - center), o2 = orthant(b - center);
        if (o1 != o2) return o1 < o2;

        return (a - center).cross(b - center) > 0;
    };

    sort(vec.begin(), vec.end(), comp);
}

template <typename T>
vector<Vector2D<T>> convex_hull(vector<Vector2D<T>> points) {
    int n = points.size(), k = 0;
    vector<Vector2D<T>> res(n * 2);

    sort(points.begin(), points.end());
    points.erase(unique(points.begin(), points.end()), points.end());

    for (int i = 0; i < n; ++i) {
        while (k > 1 && sgn((res[k - 1] - res[k - 2]).cross(points[i] - res[k - 1])) <= 0) k--;
        res[k++] = points[i];
    }

    for (int i = n - 2, t = k; i >= 0; --i) {
        while (k > t && sgn((res[k - 1] - res[k - 2]).cross(points[i] - res[k - 1])) <= 0) k--;
        res[k++] = points[i];
    }

    res.resize(k - 1);
    return res;
}

/*
ABから見てBCは左に曲がるのなら +1
ABから見てBCは右に曲がるのなら -1
BACの順番で一直線上に並ぶなら +2
ABCの順番で一直線上に並ぶなら -2
CがAB上なら 0
*/
template <typename T>
constexpr int ccw(const Vector2D<T>& a, const Vector2D<T>& b, const Vector2D<T>& c) {
    const int res = sgn((b - a).cross(c - a));

    if (res != 0) return res;
    if (sgn((a - b).dot(c - a)) > 0) return +2;
    if (sgn((b - a).dot(c - b)) > 0) return -2;
    return 0;
}

using Vec2 = Vector2D<floating_point_type>;

struct Line {
    using value_type = Vec2::value_type;
    Vec2 begin, end;

    Line() = default;
    constexpr Line(const Vec2& begin, const Vec2& end) : begin(begin), end(end) {}
    constexpr Line(value_type sx, value_type sy, value_type gx, value_type gy) : begin(sx, sy), end(gx, gy) {}

    // ax + by + c = 0
    Line(value_type a, value_type b, value_type c) {
        assert(sgn(a) != 0 || sgn(b) != 0);

        if (sgn(b) == 0) {
            begin = Vec2(-c / a, 0.0);
            end = Vec2(-c / a, 1.0);
        } else {
            begin = Vec2(0, -c / b);
            end = Vec2(1.0, -(a + c) / b);
        }
    }

    constexpr Vec2 vector() const { return end - begin; }

    constexpr Line& reverse() {
        const Vec2 tmp = begin;
        begin = end;
        end = tmp;
        return *this;
    }
    constexpr Line reversed() const { return {end, begin}; }

    constexpr Line& moveBy(const Vec2& v) {
        begin += v;
        end += v;
        return *this;
    }
    constexpr Line movedBy(const Vec2& v) const { return {begin + v, end + v}; }

    constexpr bool isParallel(const Line& line) const { return sgn(vector().cross(line.vector())) == 0; }
    constexpr bool isOrthogonal(const Line& line) const { return sgn(vector().dot(line.vector())) == 0; }

    floating_point_type length() const { return vector().length(); }
    constexpr value_type lengthSq() const { return vector().lengthSq(); }

    floating_point_type distanceFrom(const Vec2& v) const { return fabs(vector().cross(v - begin)) / length(); }
    constexpr value_type distanceFromSq(const Vec2& v) const {
        const value_type d = vector().cross(v - begin);

        return d / lengthSq() * d;
    }

    optional<Vec2> intersectsAt(const Line& line) const {
        if (sgn(vector().cross(line.vector())) == 0) return nullopt;

        return begin + vector() * fabs((line.end - begin).cross(line.vector()) / vector().cross(line.vector()));
    }

    constexpr Vec2 projection(const Vec2& v) const { return begin + vector() * (v - begin).dot(vector()) / lengthSq(); }
    constexpr Vec2 reflection(const Vec2& v) const { return 2 * projection(v) - v; }

    // ax + by + c = 0
    constexpr tuple<value_type, value_type, value_type> generalForm() const {
        const Vec2 vec = vector();
        return {vec.y, -vec.x, end.cross(begin)};
    }

    friend istream& operator>>(istream& is, Line& rhs) { return is >> rhs.begin >> rhs.end; }
};

namespace segment {

using Segment = Line;

constexpr bool intersect(const Segment& a, const Segment& b) {
    return ccw(a.begin, a.end, b.begin) * ccw(a.begin, a.end, b.end) <= 0 && ccw(b.begin, b.end, a.begin) * ccw(b.begin, b.end, a.end) <= 0;
}

floating_point_type distance(const Segment& a, const Vec2& v) {
    if (sgn(a.vector().dot(v - a.begin)) < 0 || sgn((-a.vector()).dot(v - a.end)) < 0) {
        return min(v.distanceFrom(a.begin), v.distanceFrom(a.end));
    }
    return a.distanceFrom(v);
}

constexpr floating_point_type distanceSq(const Segment& a, const Vec2& v) {
    if (sgn(a.vector().dot(v - a.begin)) < 0 || sgn((-a.vector()).dot(v - a.end)) < 0) {
        return min(v.distanceFromSq(a.begin), v.distanceFromSq(a.end));
    }
    return a.distanceFromSq(v);
}

floating_point_type distance(const Segment& a, const Segment& b) {
    if (intersect(a, b)) return 0.0;

    return min({distance(a, b.begin), distance(a, b.end), distance(b, a.begin), distance(b, a.end)});
}
}  // namespace segment

struct Triangle {
    using value_type = Vec2::value_type;
    Vec2 p0, p1, p2;

    Triangle() = default;
    constexpr Triangle(const Vec2& p0, const Vec2& p1, const Vec2& p2) : p0(p0), p1(p1), p2(p2) {}

    constexpr Vec2& p(size_t index) { return (&p0)[index]; }
    constexpr const Vec2& p(size_t index) const { return (&p0)[index]; }

    constexpr Line side(size_t index) const {
        if (index == 0)
            return Line(p1, p2);
        else if (index == 1)
            return Line(p2, p0);
        else if (index == 2)
            return Line(p0, p1);
        else {
            throw std::out_of_range("Triangle::side() index out of range");
        }
    }

    floating_point_type angle(size_t index) const {
        const Vec2 vec[3] = {p(index), p((index + 1) % 3), p((index + 2) % 3)};

        const value_type res = vec[0].arg(vec[1], vec[2]);

        return fabs(res);
    }

    constexpr value_type area() const {
        const value_type res = (p1 - p0).cross(p2 - p0) / 2;
        return (0 < res ? res : -res);
    }

    constexpr Vec2 circumCenter() const {
        const value_type d0 = side(0).lengthSq(), d1 = side(1).lengthSq(), d2 = side(2).lengthSq(), t0 = d0 * (-d0 + d1 + d2),
                         t1 = d1 * (+d0 - d1 + d2), t2 = d2 * (+d0 + d1 - d2), t3 = t0 + t1 + t2;

        return t0 / t3 * p0 + t1 / t3 * p1 + t2 / t3 * p2;
    }

    Vec2 innerCenter() const {
        const value_type dist[3] = {side(0).length(), side(1).length(), side(2).length()};

        return (dist[0] * p0 + dist[1] * p1 + dist[2] * p2) / (dist[0] + dist[1] + dist[2]);
    }

    friend istream& operator>>(istream& is, Triangle& rhs) { return is >> rhs.p0 >> rhs.p1 >> rhs.p2; }
};

struct Circle {
    using value_type = Vec2::value_type;
    Vec2 center;
    value_type r;

    Circle() = default;
    explicit constexpr Circle(value_type r) : center(0.0, 0.0), r(r) {}
    constexpr Circle(value_type x, value_type y, value_type r) : center(x, y), r(r) {}
    constexpr Circle(const Vec2& center, value_type r) : center(center), r(r) {}

    constexpr bool intersects(const Line& line) const { return sgn(line.distanceFromSq(center) - r * r) <= 0; }

    constexpr bool intersects(const Circle& circle) const {
        const value_type d = center.distanceFromSq(circle.center);

        return sgn(square(r - circle.r) - d) <= 0 && sgn(d - square(r + circle.r)) <= 0;
    }

    constexpr bool circumcribes(const Circle& circle) const { return same(center.distanceFromSq(circle.center), square(r + circle.r)); }

    constexpr bool inscribes(const Circle& circle) const { return same(center.distanceFromSq(circle.center), square(r - circle.r)); }

    constexpr bool contains(const Circle& circle) const {
        return 0 < sgn(square(r - circle.r) - center.distanceFromSq(circle.center)) && 0 < sgn(r - circle.r);
    }

    constexpr value_type area() const { return Pi * r * r; }

    value_type commonArea(const Circle& circle) const {
        const value_type d_sq = center.distanceFromSq(circle.center);
        const value_type d = center.distanceFrom(circle.center);

        const value_type r1 = r;
        const value_type r2 = circle.r;

        if (sgn(d_sq - square(r1 + r2)) >= 0) return 0.0;
        if (sgn(d_sq - square(r1 - r2)) <= 0) return min(this->area(), circle.area());

        const value_type arg1 = acos(((r1 - r2) * (r1 + r2) + d_sq) / (2 * r1 * d));
        const value_type arg2 = acos(((r2 - r1) * (r2 + r1) + d_sq) / (2 * r2 * d));

        return r1 * r1 * (arg1 - sin(2 * arg1) / 2) + r2 * r2 * (arg2 - sin(2 * arg2) / 2);
    }

    constexpr Circle& moveBy(const Vec2& v) {
        center += v;
        return *this;
    }
    constexpr Circle movedBy(const Vec2& v) const { return {center + v, r}; }

    optional<vector<Vec2>> intersectsAt(const Line& line) const {
        if (!intersects(line)) return nullopt;

        vector<Vec2> res;

        const Vec2 v = line.projection(center);

        if (same(line.distanceFrom(center), r))
            res.emplace_back(v);
        else {
            value_type d = sqrt(r * r - (v - center).lengthSq());
            const Vec2 e = line.vector().normalized();

            res.emplace_back(v - d * e);
            res.emplace_back(v + d * e);
        }

        return res;
    }

    optional<vector<Vec2>> intersectsAt(const Circle& circle) const {
        if (!intersects(circle)) return nullopt;

        const value_type d = center.distanceFrom(circle.center), arg = (circle.center - center).arg(),
                         theta = acos((d * d + r * r - circle.r * circle.r) / (2 * d * r));

        vector<Vec2> res;
        res.emplace_back(center + r * Vec2(arg + theta));
        res.emplace_back(center + r * Vec2(arg - theta));

        if (res[0] > res[1]) swap(res[0], res[1]);

        return res;
    }

    optional<vector<Vec2>> tangentPointFrom(const Vec2& v) const {
        const value_type d = center.distanceFromSq(v);

        if (sgn(d - r * r) < 0) return nullopt;
        if (same(d, r * r)) return vector<Vec2>{v};

        const auto [x1, y1] = v - center;

        const auto& opt = Circle(r).intersectsAt(Line(x1, y1, -r * r));

        vector<Vec2> res = opt.value();

        for (Vec2& v : res) v += center;

        if (res[0] > res[1]) swap(res[0], res[1]);

        return res;
    }
    optional<vector<Vec2>> commonTangentPointFrom(const Circle& circle) const {
        const value_type r1 = r, r2 = circle.r;

        vector<Vec2> res;

        if (!same(r1, r2)) {
            const Vec2 p((r2 * center - r1 * circle.center) / (r2 - r1));

            const auto& opt = tangentPointFrom(p);

            if (opt.has_value()) {
                for (const Vec2& vec : opt.value()) {
                    res.emplace_back(vec);
                }
            }
        } else {
            const value_type theta = (circle.center - center).arg();

            res.emplace_back(center + r1 * Vec2(theta + 90_deg));
            res.emplace_back(center + r1 * Vec2(theta - 90_deg));
        }

        const Vec2 q((r2 * center + r1 * circle.center) / (r1 + r2));

        const auto& opt = tangentPointFrom(q);

        if (opt.has_value()) {
            for (const Vec2& vec : opt.value()) {
                res.emplace_back(vec);
            }
        }

        if (res.empty()) return nullopt;

        sort(res.begin(), res.end());

        return res;
    }

    friend istream& operator>>(istream& is, Circle& rhs) { return is >> rhs.center >> rhs.r; }
};

struct Polygon {
    using value_type = Vec2::value_type;
    int n;
    vector<Vec2> vertex;

    Polygon() = default;
    Polygon(int _n) : n(_n), vertex(_n) {}
    Polygon(const vector<Vec2>& vec) : n(static_cast<int>(vec.size())), vertex(vec) {}

    Line side(size_t index) const { return Line(vertex[index], vertex[(index + 1) % n]); }

    Polygon& moveBy(const Vec2& v) {
        for (Vec2& vec : vertex) vec += v;
        return *this;
    }
    Polygon movedBy(const Vec2& v) const {
        vector<Vec2> new_vertex;
        for (const Vec2& vec : vertex) new_vertex.emplace_back(vec + v);

        return Polygon(new_vertex);
    }

    bool isConvex() const {
        for (int i = 0; i < n; ++i) {
            if (ccw(vertex[i], vertex[(i + 1) % n], vertex[(i + 2) % n]) == -1) return false;
        }
        return true;
    }

    bool isOnEdge(const Vec2& v) const {
        for (int i = 0; i < n; ++i) {
            if (ccw(vertex[i], vertex[(i + 1) % n], v) == 0) return true;
        }
        return false;
    }

    bool intersects(const Vec2& v) const {
        floating_point_type sum = 0.0;

        for (int i = 0; i < n; ++i) {
            sum += v.arg(vertex[i], vertex[(i + 1) % n]);
        }

        return sgn(sum - 2.0 * Pi) == 0;
    }

    double area() const {
        value_type sum = 0.0;

        for (int i = 0; i < n; ++i) {
            sum += vertex[i].cross(vertex[i == n - 1 ? 0 : i + 1]);
        }

        return 0.5 * fabs(sum);
    }

    value_type commonArea(const Circle& circle) const {
        if (n < 3) return 0.0;

        if (!same(circle.center.x, 0.0) || !same(circle.center.y, 0.0)) {
            return (*this).movedBy(-circle.center).commonArea(Circle(circle.r));
        }

        auto cross_area = [&](auto self, Circle c, Vec2 a, Vec2 b) -> value_type {
            const Vec2 va = c.center - a, vb = c.center - b;

            value_type f = va.cross(vb), res = 0.0;

            if (same(f, 0.0)) return 0.0;
            if (sgn(max(va.length(), vb.length()) - c.r) <= 0) return f;

            const Line line(a, b);

            if (sgn(segment::distance(line, c.center) - c.r) >= 0) {
                return c.r * c.r * va.arg(vb);
            }

            const auto opt = c.intersectsAt(line);
            vector<Vec2> vec1 = opt.value();

            const vector<Vec2> vec2{a, vec1.front(), vec1.back(), b};

            for (int i = 0; i + 1 < vec2.size(); ++i) {
                res += self(self, c, vec2[i], vec2[i + 1]);
            }

            return res;
        };

        value_type sum = 0.0;

        for (int i = 0; i < n; ++i) {
            sum += cross_area(cross_area, circle, vertex[i], vertex[(i + 1) % n]);
        }

        sum *= 0.5;

        return fabs(sum);
    }

    Polygon convexHull() const { return convex_hull(vertex); }

    Polygon convexCut(const Line& line) const {
        assert(isConvex());

        vector<Vec2> res;

        for (int i = 0; i < n; ++i) {
            const Vec2 &now = vertex[i], &nxt = vertex[(i + 1) % n];

            if (ccw(line.begin, line.end, now) != -1) res.emplace_back(now);
            if (ccw(line.begin, line.end, now) * ccw(line.begin, line.end, nxt) < 0) {
                const auto& opt = Line(now, nxt).intersectsAt(line);
                if (opt.has_value()) res.emplace_back(opt.value());
            }
        }

        return Polygon(res);
    }

    value_type diameter() const {
        const auto convex = (isConvex() ? (*this) : convexHull()).vertex;

        const size_t n = convex.size();

        if (n == 2)
            return convex[0].distanceFrom(convex[1]);
        else {
            size_t i = 0, j = 0;

            for (size_t k = 0; k < n; ++k) {
                if (!(convex[i] < convex[k])) i = k;
                if (convex[j] < convex[k]) j = k;
            }

            value_type res = 0.0;

            const size_t si = i, sj = j;

            while (i != sj || j != si) {
                res = max(res, convex[i].distanceFrom(convex[j]));

                if ((convex[(i + 1) % n] - convex[i]).cross(convex[(j + 1) % n] - convex[j]) < 0) {
                    i = (i + 1) % n;
                } else
                    j = (j + 1) % n;
            }

            return res;
        }
    }

    friend istream& operator>>(istream& is, Polygon& rhs) {
        for (Vec2& e : rhs.vertex) is >> e;
        return is;
    }
};

// x座標でsort済み
floating_point_type distance_closest_pair(vector<Vec2>& points, int left, int right) {
    if (right - left <= 1) return 1e20;

    int mid = (left + right) / 2;
    floating_point_type x = points[mid].x;
    floating_point_type d = min(distance_closest_pair(points, left, mid), distance_closest_pair(points, mid, right));

    inplace_merge(points.begin() + left, points.begin() + mid, points.begin() + right,
                  [](const Vec2& a, const Vec2& b) { return sgn(a.y - b.y) < 0; });

    vector<Vec2> a;

    for (int i = left; i < right; ++i) {
        if (sgn(fabs(points[i].x - x) - d) >= 0) continue;

        for (int j = static_cast<int>(a.size()) - 1; j >= 0; --j) {
            if (sgn(fabs((points[i] - a[j]).y) - d) >= 0) break;
            d = min(d, points[i].distanceFrom(a[j]));
        }

        a.emplace_back(points[i]);
    }

    return d;
}

// 垂直または水平線分の交点
// begin < end
vector<Vec2> intersections(const vector<Line>& lines) {
    const int n = static_cast<int>(lines.size());

    vector<pair<floating_point_type, int>> events;

    for (int i = 0; i < n; ++i) {
        const Line& line = lines[i];

        if (same(line.begin.y, line.end.y)) {  // 水平
            events.emplace_back(make_pair(line.begin.x, i));
            events.emplace_back(make_pair(line.end.x, i + 2 * n));
        } else {  // 垂直
            events.emplace_back(make_pair(line.begin.x, i + n));
        }
    }

    sort(events.begin(), events.end());

    set<floating_point_type> y_list;
    vector<Vec2> res;

    for (int i = 0; i < static_cast<int>(events.size()); ++i) {
        const int kind = events[i].second;
        const int id = kind % n;
        const Line& line = lines[id];

        if (kind < n) {  // 左端
            y_list.insert(line.begin.y);
        } else if (kind < 2 * n) {  // 垂直
            for (auto y : y_list) {
                if (line.begin.y - EPS <= y && y <= line.end.y + EPS) {
                    res.emplace_back(Vec2(line.begin.x, y));
                }
            }
        } else {  // 右端
            y_list.erase(line.end.y);
        }
    }

    return res;
}
}  // namespace geometry

using namespace geometry;
using Point = Vector2D<ll>;
void solve(int n, int m) {
    vector<vector<int>> a(n, vector<int>(6));
    rep(i, n) rep(j, 6) cin >> a[i][j];
    const int S = 360 * n;
    vector<vector<ll>> dp(m + 1, vector<ll>(S * 2 + 1, llINF));
    dp[0][S] = 0;
    rep(i, n) {
        int sum = 0, sqsum = 0;
        rep(j, 6) {
            sum += a[i][j];
            sqsum += a[i][j] * a[i][j];
        }
        sqsum *= 6;
        for (int c = m - 1; c >= 0; c--) {
            rep(s, S * 2 + 1) {
                if (dp[c][s] == llINF) continue;
                chmin(dp[c + 1][s + sum], dp[c][s] + sqsum + 2 * (s - S) * sum);
                chmin(dp[c + 1][s - sum], dp[c][s] + sqsum - 2 * (s - S) * sum);
            }
        }
    }
    cout << *min_element(all(dp[m])) << endl;
}
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n, m, k, p, q;
    string s;
    while (cin >> n >> m) {
        if (n == 0 && m == 0) break;
        solve(n, m);
    }
}
accuracy: 1
time_ms: 6550
memory_kb: 23848
final_rank: 14

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define db double
#define pii pair<int,int>
#define pli pair<ll,int>
#define pil pair<int,ll>
#define pll pair<ll,ll>
#define ti3 tuple<int,int,int>
#define int128 __int128_t
#define pii128 pair<int128,int128>
const int inf = 1 << 30;
const ll linf = (ll)4e18 + 10;
const db EPS = 1e-10;
const db pi = acos(-1);
template<class T> bool chmin(T& x, T y){
    if(x > y) {
        x = y;
        return true;
    } else return false;
}
template<class T> bool chmax(T& x, T y){
    if(x < y) {
        x = y;
        return true;
    } else return false;
}

// overload macro
#define CAT( A, B ) A ## B
#define SELECT( NAME, NUM ) CAT( NAME, NUM )

#define GET_COUNT( _1, _2, _3, _4, _5, _6 /* ad nauseam */, COUNT, ... ) COUNT
#define VA_SIZE( ... ) GET_COUNT( __VA_ARGS__, 6, 5, 4, 3, 2, 1 )

#define VA_SELECT( NAME, ... ) SELECT( NAME, VA_SIZE(__VA_ARGS__) )(__VA_ARGS__)

// rep(overload)
#define rep( ... ) VA_SELECT(rep, __VA_ARGS__)
#define rep2(i, n) for (int i = 0; i < int(n); i++)
#define rep3(i, a, b) for (int i = a; i < int(b); i++)
#define rep4(i, a, b, c) for (int i = a; i < int(b); i += c)

// repll(overload)
#define repll( ... ) VA_SELECT(repll, __VA_ARGS__)
#define repll2(i, n) for (ll i = 0; i < (ll)(n); i++)
#define repll3(i, a, b) for (ll i = a; i < (ll)(b); i++)
#define repll4(i, a, b, c) for (ll i = a; i < (ll)(b); i += c)

// rrep(overload)
#define rrep( ... ) VA_SELECT(rrep, __VA_ARGS__)
#define rrep2(i, n) for (int i = n - 1; i >= 0; i--)
#define rrep3(i, a, b) for (int i = (b) - 1; i >= a; i--)
#define rrep4(i, a, b, c) for (int i = (b) - 1; i >= a; i -= c)

// rrepll(overload)
#define rrepll( ... ) VA_SELECT(rrepll, __VA_ARGS__)
#define rrepll2(i, n) for (ll i = (ll)(n) - 1; i >= 0ll; i--)
#define rrepll3(i, a, b) for (ll i = (b) - 1; i >= (ll)(a); i--)
#define rrepll4(i, a, b, c) for (ll i = (b) - 1; i >= (ll)(a); i -= c)

// for_earh
#define fore(e, v) for (auto&& e : v)

// vector
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()

int dp[61][30 * 60 * 60 * 6 + 1], a[61][6], b[61];
bool solve() {
    int n, m;
    cin >> n >> m;
    if (n == 0 && m == 0) return false;
    int sum = 0;
    rep (i, n + 1) rep (j, n * 30 * 60 * 6 * 1) dp[i][j] = inf;
    dp[0][0] = 0;
    rep (i, n) {
        b[i] = 0;
        int val = 0;
        rep (j, 6) {
            cin >> a[i][j];
            val += a[i][j] * a[i][j] * 6;
            b[i] += a[i][j];
        }
        val -= b[i] * b[i];
        rrep (j, i + 1) rep(k, sum + 1) {
            chmin(dp[j + 1][k + b[i]], dp[j][k] + val);
            chmin(dp[j + 1][abs(k - b[i])], dp[j][k] + val);
        }
        sum += b[i];
        chmin(sum, n * 30 * 60 * 6);
    }
    int ans = inf;
    rep (i, sum + 1) {
        chmin(ans, i * i + dp[m][i]);
    }
    cout << ans << '\n';
    return true;
}

int main() {
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(20);
    bool f = true;
    while (f) f = solve();
    return 0;
}
accuracy: 1
time_ms: 2640
memory_kb: 157868
final_rank: 16

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

#pragma GCC target("avx2")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")

using ll = long long;

template<class T>
bool chmin(T &a, const T &b) {if (a > b) {a = b; return 1;} return 0;}

bool is_end = false;

const int nmax = 62;
const int BASE = 60 * 60;
const int amax = BASE * 2 + 1;

const int INF = 1e9;

void solve()
{
    int N, M; cin >> N >> M;
    if (N == 0 && M == 0)
    {
        is_end = true;
        return;
    }
    
    vector<int> linear(N, 0), square(N, 0);
    for (uint i = 0; i < N; ++i)
    {
        for (uint j = 0; j < 6; ++j)
        {
            int a; cin >> a;
            linear[i] += a;
            square[i] += a * a;
        }
    }
    
    vector<vector<int>> dp(nmax, vector<int>(amax, INF));
    vector<vector<int>> ndp = dp;
    
    dp[0][BASE + 0] = 0;
    for (uint i = 0; i < N; ++i)
    {
        for (uint st = 0; st <= M; ++st)
        {
            for (int sum = -BASE; sum < BASE; ++sum)
            {
                if (dp[st][BASE + sum] == INF) continue;
                int origin = dp[st][BASE + sum];
                
                chmin(ndp[st][BASE + sum], origin);
                // to A
                chmin(ndp[st + 1][BASE + sum + linear[i]], origin + 2 * linear[i] * sum + 6 * square[i]);
                // to B
                chmin(ndp[st + 1][BASE + sum - linear[i]], origin - 2 * linear[i] * sum + 6 * square[i]);
            }
            
        }
        swap(dp, ndp);
    }
    
    
    int res = INF;
    for (int a = -BASE; a < BASE; ++a)
    {
        chmin(res, dp[M][BASE + a]);
    }
    cout << res << endl;
    
    return;
}

int main()
{
    while (!is_end)
    {
        solve();
    }
    
    return 0;
}
accuracy: 1
time_ms: 3100
memory_kb: 6308
final_rank: 4

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

int solve(int n, int m) {
    vector<pair<int,int>> A(n);
    for(int i : rep(n)) {
        vector<int> d = in(6);
        int s1 = 0, s2 = 0;
        for(int k : rep(6)) {
            s1 += d[k];
            s2 += d[k] * d[k];
        }
        A[i] = {s1, s2 * 6 - s1 * s1};
    }
    const int e_max = 60 * 60;
    const i64 INF = 1e18;
    vector dp(m + 1, vector(e_max + 1, INF));
    dp[0][0] = 0;
    for(auto [mean, var] : A) {
        vector nt = dp;
        for(int c = 0; c < m; c++) {
            for(int e = 0; e <= e_max; e++) {
                if(    e + mean  <= e_max) chmin(nt[c + 1][    e + mean ], dp[c][e] + var);
                if(abs(e - mean) <= e_max) chmin(nt[c + 1][abs(e - mean)], dp[c][e] + var);
            }
        }
        dp = move(nt);
    }

    i64 ans = INF;
    for(int e = 0; e <= e_max; e++) chmin(ans, e * e + dp[m][e]);
    return ans;
}

int main() {
    while(true) {
        int n = in(), m = in();
        if(make_pair(n, m) == make_pair(0, 0)) return 0;
        print(solve(n, m));
    }
}
accuracy: 1
time_ms: 1890
memory_kb: 6664
final_rank: 2

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

int main(){
  while(1)[]{
    unsigned long N, M;
    cin >> N >> M;
    if(!(N + M))exit(0);
    vector<array<unsigned long, 6>> die(N);
    vector<pair<unsigned long, unsigned long>> mean_variance;
    mean_variance.reserve(N);
    for(auto&& [a, b, c, d, e, f] : die){
      cin >> a >> b >> c >> d >> e >> f;
      const auto S{a + b + c + d + e + f};
      mean_variance.emplace_back(S, (a * a + b * b + c * c + d * d + e * e + f * f) * 6 - S * S);
    }
    vector<vector<unsigned long>> dp(M + 1);
    for(unsigned long i{}; i <= M; ++i)
      dp[i] = vector<unsigned long>(i * 360 + 1, numeric_limits<unsigned long>::max() / 2);
    dp[0][0] = 0;
    unsigned long j{};
    for(const auto& [m, v] : mean_variance){
      ++j;
      for(unsigned long i{min(M, j)}; i--;){
        for(unsigned long j{}; j <= i * 360; ++j){
          dp[i + 1][j + m] = min(dp[i + 1][j + m], dp[i][j] + v);
          dp[i + 1][max(j, m) - min(j, m)] = min(dp[i + 1][max(j, m) - min(j, m)], dp[i][j] + v);
        }
      }
    }
    unsigned long ans{numeric_limits<unsigned long>::max()};
    for(unsigned long i{}, i_upto{size(dp.back())}; i < i_upto; ++i){
      ans = min(dp.back()[i] + i * i, ans);
    }
    cout << ans << endl;
    return ;
  }();
}
accuracy: 1
time_ms: 960
memory_kb: 8388
final_rank: 1