OI XXXI - poj

// https://szkopul.edu.pl/problemset/problem/_uloh99GgCTwxZ0LQVb33ys7/site/?key=statement

#include <bits/stdc++.h>

using namespace std;

#define int long long

#define ar std::array
constexpr int sizik = 1000 * 1001;

struct Ans {
    int a1, b1, a2, b2;

    Ans(int _a1 = 0, int _b1 = 0, int _a2 = 0, int _b2 = 0) {
        a1 = _a1;
        b1 = _b1;
        a2 = _a2;
        b2 = _b2;
    }
};

Ans ans[sizik];

int32_t main() {
    std::ios_base::sync_with_stdio(0);
    std::cin.tie(0);

    int n, k;
    std::cin >> n >> k;

    std::multiset<std::pair<int, int>> s;

    for (int i = 0; i < n; i++) {
        int a;
        std::cin >> a;

        s.insert({a, i + 1});
    }

    int curr = 0;

    while (s.size() > 0) {
        auto ptr = s.begin();
        auto [x, j] = *ptr;

        curr++;

        if (curr > n) {
            std::cout << "NIE\n";
            return 0;
        }

        if (x >= k) {
            ans[curr] = {j, k};

            s.erase(ptr);

            x -= k;

            if (x > 0) {
                s.insert({x, j});
            }
        } else {
            int w = k - x;
            if (s.size() < 2) {
                ans[curr] = {j, x};
                s.erase(ptr);

                continue;
            } else {
                auto ptr2 = s.end();
                ptr2--;

                auto [x1, j1] = *ptr2;

                if (x1 <= w) {
                    s.erase(ptr);

                    ptr2 = s.end();
                    ptr2--;

                    s.erase(ptr2);

                    ans[curr] = {j, x, j1, x1};

                } else {
                    s.erase(ptr);

                    ptr2 = s.end();
                    ptr2--;

                    s.erase(ptr2);

                    ans[curr] = {j, x, j1, w};

                    x1 -= w;

                    s.insert({x1, j1});
                }
            }
        }
    }

    std::cout << "TAK\n";

    for (int i = 1; i <= n; i++) {
        auto [a1, b1, a2, b2] = ans[i];

        int m = 0;

        if (a1 != 0) m++;
        if (a2 != 0) m++;

        std::cout << m;

        if (m >= 1) {
            std::cout << " " << a1 << " " << b1;
        }

        if (m >= 2) {
            std::cout << " " << a2 << " " << b2;
        }

        std::cout << '\n';
    }

    return 0;
}