{"model_name":"mercury-2","codes":{"1":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    if(!(cin >> n)) return 0;\n    vector<int> x(n), y(n);\n    vector<long long> r(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> x[i] >> y[i] >> r[i];\n    }\n    // output a unit cell for each company\n    for (int i = 0; i < n; ++i) {\n        int a = x[i];\n        int b = y[i];\n        int c = x[i] + 1;\n        int d = y[i] + 1;\n        cout << a << ' ' << b << ' ' << c << ' ' << d << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int si, sj;\n    if (!(cin >> si >> sj)) return 0;\n    const int N = 50;\n    vector<vector<int>> tile(N, vector<int>(N));\n    int maxTile = -1;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> tile[i][j];\n            maxTile = max(maxTile, tile[i][j]);\n        }\n    }\n    vector<vector<int>> val(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> val[i][j];\n\n    const int M = maxTile + 1;\n    const char dirChar[4] = {'U', 'D', 'L', 'R'};\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n\n    string bestPath;\n    long long bestScore = -1;\n\n    // number of random greedy runs \u2013 can be tuned\n    const int RUNS = 3000;\n\n    for (int run = 0; run < RUNS; ++run) {\n        vector<char> visited(M, 0);\n        int ci = si, cj = sj;\n        visited[tile[ci][cj]] = 1;\n        long long curScore = val[ci][cj];\n        string curPath;\n\n        while (true) {\n            int bestScoreNeighbour = -1;\n            vector<int> bestDirs; // indices of directions achieving the best score\n            // first pass: find maximal p among admissible neighbours\n            for (int d = 0; d < 4; ++d) {\n                int ni = ci + dx[d];\n                int nj = cj + dy[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int t = tile[ni][nj];\n                if (visited[t]) continue;\n                int sc = val[ni][nj];\n                if (sc > bestScoreNeighbour) {\n                    bestScoreNeighbour = sc;\n                    bestDirs.clear();\n                    bestDirs.push_back(d);\n                } else if (sc == bestScoreNeighbour) {\n                    bestDirs.push_back(d);\n                }\n            }\n            if (bestScoreNeighbour == -1) break; // no move possible\n\n            // random tie breaking\n            int chosenIdx = std::uniform_int_distribution<int>(0, (int)bestDirs.size() - 1)(rng);\n            int d = bestDirs[chosenIdx];\n            int ni = ci + dx[d];\n            int nj = cj + dy[d];\n            // perform the move\n            curPath.push_back(dirChar[d]);\n            ci = ni; cj = nj;\n            visited[tile[ci][cj]] = 1;\n            curScore += val[ci][cj];\n        }\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestPath = curPath;\n        }\n    }\n\n    cout << bestPath << \"\\n\";\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;                     // grid size\nconstexpr int V = N * N;                 // number of vertices\nconstexpr double INF = 1e100;\nconstexpr double INIT_WEIGHT = 5000.0;    // initial estimate for every edge\nconstexpr double LR = 0.01;              // learning rate\n\ninline int node_id(int i, int j) { return i * N + j; }\ninline pair<int,int> id_to_coord(int id) { return {id / N, id % N}; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    /*  edge weights:\n       horizontal:  i = 0..29, j = 0..28   \u2192 index = i*(N-1)+j   (size N*(N-1))\n       vertical:    i = 0..28, j = 0..29   \u2192 index = i*N + j     (size (N-1)*N)\n    */\n    const int Hcnt = N * (N - 1);\n    const int Vcnt = (N - 1) * N;\n    vector<double> h(Hcnt, INIT_WEIGHT);\n    vector<double> v(Vcnt, INIT_WEIGHT);\n\n    for (int query = 0; query < 1000; ++query) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) return 0;   // EOF safety\n        int s = node_id(si, sj);\n        int t = node_id(ti, tj);\n\n        /* ---------- Dijkstra with current estimates ---------- */\n        vector<double> dist(V, INF);\n        vector<int> parent(V, -1);\n        vector<char> move(V, 0);\n        dist[s] = 0.0;\n        using P = pair<double,int>;\n        priority_queue<P, vector<P>, greater<P>> pq;\n        pq.emplace(0.0, s);\n\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u]) continue;\n            if (u == t) break;\n            auto [i, j] = id_to_coord(u);\n\n            // up\n            if (i > 0) {\n                int nb = node_id(i-1, j);\n                double w = v[(i-1)*N + j];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'U';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // down\n            if (i < N-1) {\n                int nb = node_id(i+1, j);\n                double w = v[i*N + j];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'D';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // left\n            if (j > 0) {\n                int nb = node_id(i, j-1);\n                double w = h[i*(N-1) + (j-1)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'L';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // right\n            if (j < N-1) {\n                int nb = node_id(i, j+1);\n                double w = h[i*(N-1) + j];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'R';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n        }\n\n        /* ---------- reconstruct the path ---------- */\n        vector<char> rev_path;\n        // each entry: (isHorizontal, index)\n        vector<pair<bool,int>> rev_edges;\n        int cur = t;\n        while (cur != s) {\n            int p = parent[cur];\n            char d = move[cur];\n            rev_path.push_back(d);\n            auto [ci, cj] = id_to_coord(cur);\n            auto [pi, pj] = id_to_coord(p);\n            if (ci == pi + 1 && cj == pj) {               // moved down\n                rev_edges.emplace_back(false, pi * N + pj); // vertical edge (top node)\n            } else if (ci == pi - 1 && cj == pj) {        // moved up\n                rev_edges.emplace_back(false, ci * N + cj);\n            } else if (cj == pj + 1 && ci == pi) {        // moved right\n                rev_edges.emplace_back(true, pi * (N-1) + pj);\n            } else if (cj == pj - 1 && ci == pi) {        // moved left\n                rev_edges.emplace_back(true, ci * (N-1) + cj);\n            }\n            cur = p;\n        }\n        reverse(rev_path.begin(), rev_path.end());\n        reverse(rev_edges.begin(), rev_edges.end());\n\n        string out_path;\n        out_path.reserve(rev_path.size());\n        for (char c : rev_path) out_path.push_back(c);\n\n        /* ---------- output and flush ---------- */\n        cout << out_path << '\\n' << flush;\n\n        /* ---------- read noisy length ---------- */\n        long long L;\n        if (!(cin >> L)) return 0;   // safety\n\n        /* ---------- update edge estimates ---------- */\n        double est = 0.0;\n        for (auto &e : rev_edges) {\n            if (e.first)  // horizontal\n                est += h[e.second];\n            else\n                est += v[e.second];\n        }\n        double err = est - static_cast<double>(L);\n        int plen = static_cast<int>(rev_edges.size());\n        if (plen > 0) {\n            double delta = LR * err / plen;\n            for (auto &e : rev_edges) {\n                if (e.first) {\n                    h[e.second] -= delta;\n                    if (h[e.second] < 1.0) h[e.second] = 1.0;\n                } else {\n                    v[e.second] -= delta;\n                    if (v[e.second] < 1.0) v[e.second] = 1.0;\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int MAX_N = 20;\nconstexpr int MAX_LEN = 12;\nconstexpr uint8_t EMPTY = 8;          // value for '.' (unused after fill)\n\nstruct Placement {\n    uint8_t len;                      // length of the string (\u226412)\n    uint16_t cells[MAX_LEN];          // linear cell indices (0 \u2026 399)\n    uint8_t  need[MAX_LEN];           // required character (0 \u2026 7)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<string> S(M);\n    for (int i = 0; i < M; ++i) cin >> S[i];\n\n    // ---------- pre\u2011compute all placements ----------\n    vector<vector<Placement>> placements(M);\n    placements.reserve(M);\n    for (int i = 0; i < M; ++i) {\n        const string &st = S[i];\n        int L = (int)st.size();\n        placements[i].reserve(2 * N * N);\n        // horizontal\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                Placement p;\n                p.len = (uint8_t)L;\n                for (int k = 0; k < L; ++k) {\n                    int col = (c + k) % N;\n                    p.cells[k] = (uint16_t)(r * N + col);\n                    p.need[k] = (uint8_t)(st[k] - 'A');   // 0 \u2026 7\n                }\n                placements[i].push_back(p);\n            }\n        }\n        // vertical\n        for (int c = 0; c < N; ++c) {\n            for (int r = 0; r < N; ++r) {\n                Placement p;\n                p.len = (uint8_t)L;\n                for (int k = 0; k < L; ++k) {\n                    int row = (r + k) % N;\n                    p.cells[k] = (uint16_t)(row * N + c);\n                    p.need[k] = (uint8_t)(st[k] - 'A');\n                }\n                placements[i].push_back(p);\n            }\n        }\n    }\n\n    // ---------- heuristic ----------\n    std::mt19937 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> distChar(0, 7);\n\n    const int ITER = 30;                     // enough for the time limit\n    int bestScore = -1;\n    vector<uint8_t> bestMat(N * N, EMPTY);\n\n    vector<int> length(M);\n    for (int i = 0; i < M; ++i) length[i] = (int)S[i].size();\n\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n\n    for (int it = 0; it < ITER; ++it) {\n        // ----- start with an empty matrix -----\n        vector<uint8_t> mat(N * N, EMPTY);\n\n        // ----- order of processing -----\n        if (it % 2 == 0) {\n            shuffle(order.begin(), order.end(), rng);\n        } else {\n            // length descending, ties keep original order\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     if (length[a] != length[b]) return length[a] > length[b];\n                     return a < b;\n                 });\n        }\n\n        // ----- greedy placement -----\n        for (int idx : order) {\n            const auto &pls = placements[idx];\n            int bestPl = -1;\n            int bestOverlap = -1;\n            for (int pi = 0; pi < (int)pls.size(); ++pi) {\n                const Placement &p = pls[pi];\n                bool conflict = false;\n                int overlap = 0;\n                for (int k = 0; k < p.len; ++k) {\n                    uint8_t cur = mat[p.cells[k]];\n                    uint8_t need = p.need[k];\n                    if (cur != EMPTY && cur != need) {\n                        conflict = true;\n                        break;\n                    }\n                    if (cur == need) ++overlap;\n                }\n                if (!conflict) {\n                    if (overlap > bestOverlap) {\n                        bestOverlap = overlap;\n                        bestPl = pi;\n                        if (overlap == p.len) break;   // perfect match\n                    }\n                }\n            }\n            if (bestPl != -1) {\n                const Placement &p = pls[bestPl];\n                for (int k = 0; k < p.len; ++k) {\n                    uint16_t cell = p.cells[k];\n                    if (mat[cell] == EMPTY) mat[cell] = p.need[k];\n                }\n            }\n        }\n\n        // ----- fill remaining empty cells with random letters -----\n        for (int i = 0; i < N * N; ++i) {\n            if (mat[i] == EMPTY) mat[i] = (uint8_t)distChar(rng);\n        }\n\n        // ----- count satisfied strings -----\n        int satisfied = 0;\n        for (int i = 0; i < M; ++i) {\n            const auto &pls = placements[i];\n            bool okString = false;\n            for (const Placement &p : pls) {\n                bool ok = true;\n                for (int k = 0; k < p.len; ++k) {\n                    if (mat[p.cells[k]] != p.need[k]) {\n                        ok = false;\n                        break;\n                    }\n                }\n                if (ok) {\n                    okString = true;\n                    break;\n                }\n            }\n            if (okString) ++satisfied;\n        }\n\n        if (satisfied > bestScore) {\n            bestScore = satisfied;\n            bestMat = mat;\n        }\n    }\n\n    // ----- output the best matrix -----\n    for (int r = 0; r < N; ++r) {\n        string line;\n        line.reserve(N);\n        for (int c = 0; c < N; ++c) {\n            uint8_t v = bestMat[r * N + c];\n            line.push_back(char('A' + v));   // v is 0 \u2026 7\n        }\n        cout << line << '\\n';\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, si, sj;\nvector<string> grid;\nvector<vector<char>> visited;\nstring answer;\n\n// direction vectors and corresponding characters\nconst int dx[4] = {-1, 1, 0, 0};\nconst int dy[4] = {0, 0, -1, 1};\nconst char dirChar[4] = {'U', 'D', 'L', 'R'};\nconst char revChar[4] = {'D', 'U', 'R', 'L'};\n\nvoid dfs(int i, int j) {\n    visited[i][j] = 1;\n    for (int d = 0; d < 4; ++d) {\n        int ni = i + dx[d];\n        int nj = j + dy[d];\n        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n        if (grid[ni][nj] == '#') continue;\n        if (visited[ni][nj]) continue;\n        // move to child\n        answer.push_back(dirChar[d]);\n        dfs(ni, nj);\n        // backtrack\n        answer.push_back(revChar[d]);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    if (!(cin >> N >> si >> sj)) return 0;\n    grid.resize(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n\n    visited.assign(N, vector<char>(N, 0));\n    answer.clear();\n\n    dfs(si, sj);               // produces a closed walk\n\n    cout << answer << \"\\n\";\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    if (!(cin >> N >> M >> K >> R)) return 0;\n\n    // read required skill vectors (not used by the greedy algorithm)\n    vector<vector<int>> d(N, vector<int>(K));\n    for (int i = 0; i < N; ++i)\n        for (int k = 0; k < K; ++k)\n            cin >> d[i][k];\n\n    // read dependencies\n    vector<vector<int>> adj(N);\n    vector<int> indeg(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        adj[u].push_back(v);\n        ++indeg[v];\n    }\n\n    // state of members and tasks\n    vector<int> member_task(M, -1);          // which task a member is working on (0\u2011based), -1 = idle\n    vector<char> task_started(N, 0);        // 0 = not started, 1 = in progress\n    vector<char> task_completed(N, 0);      // 0 = not finished, 1 = finished\n\n    // ready queue (tasks whose indegree is zero and not started yet)\n    deque<int> ready;\n    for (int i = 0; i < N; ++i)\n        if (indeg[i] == 0) ready.push_back(i);\n\n    int completed_cnt = 0;\n    while (true) {\n        // ---------- start of a new day ----------\n        vector<pair<int,int>> assign;   // (member, task) both 1\u2011based for output\n        for (int j = 0; j < M && !ready.empty(); ++j) {\n            if (member_task[j] == -1) {\n                int task = ready.front();\n                ready.pop_front();\n                member_task[j] = task;\n                task_started[task] = 1;\n                assign.emplace_back(j + 1, task + 1);\n            }\n        }\n\n        // output assignments\n        cout << assign.size();\n        for (auto &p : assign) cout << ' ' << p.first << ' ' << p.second;\n        cout << \"\\n\" << flush;\n\n        // ---------- read judge response ----------\n        int n;\n        if (!(cin >> n)) return 0;          // EOF (should not happen)\n        if (n == -1) break;                 // all tasks done or day limit reached\n\n        vector<int> finished_members(n);\n        for (int i = 0; i < n; ++i) cin >> finished_members[i];\n\n        // process completions\n        for (int f : finished_members) {\n            int member = f - 1;\n            int task = member_task[member];\n            if (task == -1) continue;       // safety, should not happen\n            member_task[member] = -1;\n            task_started[task] = 0;\n            task_completed[task] = 1;\n            ++completed_cnt;\n\n            // update indegrees of successors\n            for (int v : adj[task]) {\n                --indeg[v];\n                if (indeg[v] == 0 && !task_started[v] && !task_completed[v]) {\n                    ready.push_back(v);\n                }\n            }\n        }\n\n        // If all tasks are finished we will receive -1 on the next line,\n        // but we keep the loop until that happens.\n    }\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Order {\n    int a, b, c, d;   // pickup (a,b) and delivery (c,d)\n    int idx;          // 1\u2011based index in the original list\n    int internalDist; // Manhattan distance between pickup and delivery\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 1000;\n    vector<Order> all(N);\n    for (int i = 0; i < N; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        all[i] = {a, b, c, d, i + 1, abs(a - c) + abs(b - d)};\n    }\n\n    // 1) select 50 orders with smallest internal distance\n    sort(all.begin(), all.end(),\n         [](const Order& x, const Order& y) { return x.internalDist < y.internalDist; });\n    const int M = 50;\n    vector<Order> sel(all.begin(), all.begin() + M);\n\n    // 2) greedy nearest\u2011neighbor ordering of the selected orders\n    vector<int> orderIdx;               // indices in the order they are processed\n    vector<pair<int, int>> route;       // sequence of visited points\n    int curX = 400, curY = 400;\n    route.emplace_back(curX, curY);    // start at the office\n\n    vector<bool> used(M, false);\n    for (int step = 0; step < M; ++step) {\n        int best = -1;\n        int bestDist = INT_MAX;\n        for (int i = 0; i < M; ++i) if (!used[i]) {\n            int d = abs(curX - sel[i].a) + abs(curY - sel[i].b);\n            if (d < bestDist) {\n                bestDist = d;\n                best = i;\n            }\n        }\n        // go to pickup\n        curX = sel[best].a;\n        curY = sel[best].b;\n        route.emplace_back(curX, curY);\n        // go to delivery\n        curX = sel[best].c;\n        curY = sel[best].d;\n        route.emplace_back(curX, curY);\n\n        used[best] = true;\n        orderIdx.push_back(sel[best].idx);\n    }\n\n    // return to office\n    route.emplace_back(400, 400);\n\n    // ----- output -----\n    cout << M;\n    for (int id : orderIdx) cout << ' ' << id;\n    cout << '\\n';\n\n    int n = (int)route.size();          // number of points in the route\n    cout << n;\n    for (auto [x, y] : route) cout << ' ' << x << ' ' << y;\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        sz.assign(n, 1);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\n/*** Edge description ***/\nstruct Edge {\n    int u, v;\n    int d;          // rounded Euclidean distance\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        long long dx = (long long)x[u] - x[v];\n        long long dy = (long long)y[u] - y[v];\n        double dist = sqrt((double)dx * dx + (double)dy * dy);\n        int d = (int)lround(dist);          // round to nearest integer\n        edges[i] = {u, v, d};\n    }\n\n    DSU dsu(N);\n    int accepted = 0;\n\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;                // true length of edge i\n\n        bool take = false;\n        if (dsu.find(edges[i].u) != dsu.find(edges[i].v)) {\n            // the edge connects two different components -> accept\n            take = true;\n            dsu.unite(edges[i].u, edges[i].v);\n            ++accepted;\n        }\n        cout << (take ? 1 : 0) << '\\n' << flush;\n        // optional early stop: after we already have N-1 edges we could\n        // skip further processing, but we must still read the remaining\n        // lengths to keep the I/O protocol correct.\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if (!(cin >> N)) return 0;          // no input\n    struct Pet { int x, y, type; };\n    vector<Pet> pets(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n    }\n    int M;\n    cin >> M;\n    vector<pair<int,int>> humans(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].first >> humans[i].second;\n    }\n\n    const string do_nothing(M, '.');   // M characters '.'\n\n    for (int turn = 0; turn < 300; ++turn) {\n        // output actions for this turn\n        cout << do_nothing << '\\n' << flush;\n\n        // read the N pet move strings and discard them\n        for (int i = 0; i < N; ++i) {\n            string mv;\n            cin >> mv;   // each mv can be \".\" or a short sequence like \"URDL\"\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct PrevInfo {\n    int pi = -1, pj = -1;   // predecessor cell\n    char dir = 0;           // direction used to go from predecessor to this cell\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj, ti, tj;\n    double p;\n    if (!(cin >> si >> sj >> ti >> tj >> p)) return 0;\n\n    // read horizontal walls: 20 rows, each 19 characters\n    vector<string> h(20);\n    for (int i = 0; i < 20; ++i) {\n        cin >> h[i];\n    }\n    // read vertical walls: 19 rows, each 20 characters\n    vector<string> v(19);\n    for (int i = 0; i < 19; ++i) {\n        cin >> v[i];\n    }\n\n    const int N = 20;\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char dch[4] = {'U', 'D', 'L', 'R'};\n\n    // BFS\n    queue<pair<int,int>> q;\n    bool visited[N][N] = {};\n    PrevInfo prevInfo[N][N];\n    q.emplace(si, sj);\n    visited[si][sj] = true;\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        if (i == ti && j == tj) break; // reached target\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool blocked = false;\n            if (dir == 0) { // U\n                blocked = (v[i-1][j] == '1');\n            } else if (dir == 1) { // D\n                blocked = (v[i][j] == '1');\n            } else if (dir == 2) { // L\n                blocked = (h[i][j-1] == '1');\n            } else { // R\n                blocked = (h[i][j] == '1');\n            }\n            if (blocked) continue;\n            if (!visited[ni][nj]) {\n                visited[ni][nj] = true;\n                prevInfo[ni][nj] = {i, j, dch[dir]};\n                q.emplace(ni, nj);\n            }\n        }\n    }\n\n    // reconstruct path\n    string ans;\n    int ci = ti, cj = tj;\n    while (!(ci == si && cj == sj)) {\n        const PrevInfo &pr = prevInfo[ci][cj];\n        if (pr.pi == -1) { // should not happen, but safety\n            break;\n        }\n        ans.push_back(pr.dir);\n        ci = pr.pi;\n        cj = pr.pj;\n    }\n    reverse(ans.begin(), ans.end());\n\n    // enforce length limit\n    if ((int)ans.size() > 200) ans.resize(200);\n\n    cout << ans << \"\\n\";\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;\nconstexpr int DIR = 4;\nconstexpr int TOTAL = N * N * DIR;               // 30*30*4 = 3600\nconstexpr int di[DIR] = {0, -1, 0, 1};            // left, up, right, down\nconstexpr int dj[DIR] = {-1, 0, 1, 0};\n\nint tile[N][N];                                   // original tile types\nint to_rot[8][4][4];                              // to after rotation\n\ninline int idx(int i, int j, int d) { return ((i * N + j) * DIR + d); }\n\n/* -------------------------------------------------------------\n   compute the score (L1 * L2) for a given rotation matrix\n   ------------------------------------------------------------- */\nint computeScore(const array<array<int, N>, N>& rot) {\n    static int nxt[TOTAL];\n    static int prv[TOTAL];\n    // initialise\n    for (int v = 0; v < TOTAL; ++v) {\n        nxt[v] = -1;\n        prv[v] = -1;\n    }\n    // build directed edges\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int t = tile[i][j];\n            for (int d = 0; d < DIR; ++d) {\n                int r = rot[i][j];\n                int d2 = to_rot[t][r][d];\n                if (d2 == -1) continue;\n                int ni = i + di[d2];\n                int nj = j + dj[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) & 3;\n                int u = idx(i, j, d);\n                int v = idx(ni, nj, nd);\n                nxt[u] = v;\n                prv[v] = u;\n            }\n        }\n    }\n\n    static bool visited[TOTAL];\n    for (int v = 0; v < TOTAL; ++v) visited[v] = false;\n\n    vector<int> lengths;\n    for (int v = 0; v < TOTAL; ++v) {\n        if (visited[v]) continue;\n        if (nxt[v] == -1 && prv[v] == -1) continue;   // isolated\n        // collect the whole component (undirected)\n        vector<int> comp;\n        stack<int> st;\n        st.push(v);\n        while (!st.empty()) {\n            int u = st.top(); st.pop();\n            if (visited[u]) continue;\n            visited[u] = true;\n            comp.push_back(u);\n            if (nxt[u] != -1 && !visited[nxt[u]]) st.push(nxt[u]);\n            if (prv[u] != -1 && !visited[prv[u]]) st.push(prv[u]);\n        }\n        // count directed edges inside the component\n        int edges = 0;\n        for (int node : comp) if (nxt[node] != -1) ++edges;\n        if (edges == (int)comp.size()) {   // every vertex has out\u2011degree 1 \u2192 a cycle\n            lengths.push_back((int)comp.size());\n        }\n    }\n\n    if (lengths.size() < 2) return 0;\n    sort(lengths.begin(), lengths.end(), greater<int>());\n    long long L1 = lengths[0];\n    long long L2 = lengths[1];\n    return (int)(L1 * L2);\n}\n\n/* ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read the board\n    for (int i = 0; i < N; ++i) {\n        string line; cin >> line;\n        for (int j = 0; j < N; ++j) tile[i][j] = line[j] - '0';\n    }\n\n    // base table \"to\"\n    const int base[8][4] = {\n        { 1, 0,-1,-1},\n        { 3,-1,-1, 0},\n        {-1,-1, 3, 2},\n        {-1, 2, 1,-1},\n        { 1, 0, 3, 2},\n        { 3, 2, 1, 0},\n        { 2,-1, 0,-1},\n        {-1, 3,-1, 1}\n    };\n    // pre\u2011compute to_rot\n    for (int t = 0; t < 8; ++t)\n        for (int r = 0; r < 4; ++r)\n            for (int d = 0; d < 4; ++d) {\n                int local = (d - r + 4) & 3;\n                int out = base[t][local];\n                if (out == -1) to_rot[t][r][d] = -1;\n                else to_rot[t][r][d] = (out + r) & 3;\n            }\n\n    // random generator\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dirDist(0, 3);\n    uniform_int_distribution<int> cellDist(0, N - 1);\n\n    // best solution found\n    array<array<int, N>, N> bestRot{};\n    int bestScore = -1;\n\n    // time limit (1.9 seconds)\n    const double TIME_LIMIT = 1.9;\n    auto startTime = chrono::steady_clock::now();\n\n    // ---------- random restarts + simple hill climbing ----------\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        // random initial board\n        array<array<int, N>, N> curRot{};\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                curRot[i][j] = dirDist(rng);\n\n        int curScore = computeScore(curRot);\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestRot = curRot;\n        }\n\n        // a few hundred local moves\n        const int LOCAL_STEPS = 300;\n        for (int step = 0; step < LOCAL_STEPS; ++step) {\n            now = chrono::steady_clock::now();\n            elapsed = chrono::duration<double>(now - startTime).count();\n            if (elapsed > TIME_LIMIT) break;\n\n            int i = cellDist(rng);\n            int j = cellDist(rng);\n            int oldR = curRot[i][j];\n            int newR = dirDist(rng);\n            if (newR == oldR) continue;\n            curRot[i][j] = newR;\n            int newScore = computeScore(curRot);\n            if (newScore >= curScore) {\n                curScore = newScore;\n                if (newScore > bestScore) {\n                    bestScore = newScore;\n                    bestRot = curRot;\n                }\n            } else {\n                curRot[i][j] = oldR;   // revert\n            }\n        }\n    }\n\n    // ---------- output ----------\n    string out;\n    out.reserve(N * N);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            out.push_back(char('0' + bestRot[i][j]));\n    cout << out << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    long long T;\n    if (!(cin >> N >> T)) return 0;          // no input\n    string line;\n    for (int i = 0; i < N; ++i) {\n        cin >> line;                         // read each row (hex strings)\n    }\n    // Output an empty move sequence \u2013 a single newline.\n    cout << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, K;\n    if (!(cin >> N >> K)) return 0;\n    vector<int> a(11);\n    for (int d = 1; d <= 10; ++d) cin >> a[d];\n    // read strawberry coordinates, we do not need them for the simple heuristic\n    for (int i = 0; i < N; ++i) {\n        long long x, y;\n        cin >> x >> y;\n    }\n\n    const long long R = 10000;      // cake radius\n    const long long M = 20000;      // far outside the cake, still within limits\n    const int V = min(10, K / 2);   // number of vertical lines\n    const int H = min(10, K / 2);   // number of horizontal lines\n    const int totalCuts = V + H;\n    long long step = (2 * R) / (V + 1);   // integer step, V>=1\n\n    cout << totalCuts << \"\\n\";\n\n    // vertical lines: x = -R + i*step\n    for (int i = 1; i <= V; ++i) {\n        long long x = -R + i * step;\n        cout << x << \" \" << -M << \" \" << x << \" \" << M << \"\\n\";\n    }\n\n    // horizontal lines: y = -R + j*step\n    for (int j = 1; j <= H; ++j) {\n        long long y = -R + j * step;\n        cout << -M << \" \" << y << \" \" << M << \" \" << y << \"\\n\";\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    // read and discard the initial dot coordinates\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    // No operations are performed.\n    cout << 0 << \"\\n\";\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* -------------------------------------------------------------\n   tilt the board in the given direction\n   F : up (front)   \u2192 rows move towards index 0\n   B : down (back)  \u2192 rows move towards index 9\n   L : left         \u2192 columns move towards index 0\n   R : right        \u2192 columns move towards index 9\n   ------------------------------------------------------------- */\nvoid tilt(int g[10][10], char dir) {\n    if (dir == 'L') {\n        for (int i = 0; i < 10; ++i) {\n            int write = 0;\n            for (int j = 0; j < 10; ++j) {\n                if (g[i][j] != 0) {\n                    int v = g[i][j];\n                    if (write != j) {\n                        g[i][write] = v;\n                        g[i][j] = 0;\n                    }\n                    ++write;\n                }\n            }\n        }\n    } else if (dir == 'R') {\n        for (int i = 0; i < 10; ++i) {\n            int write = 9;\n            for (int j = 9; j >= 0; --j) {\n                if (g[i][j] != 0) {\n                    int v = g[i][j];\n                    if (write != j) {\n                        g[i][write] = v;\n                        g[i][j] = 0;\n                    }\n                    --write;\n                }\n            }\n        }\n    } else if (dir == 'F') {\n        for (int j = 0; j < 10; ++j) {\n            int write = 0;\n            for (int i = 0; i < 10; ++i) {\n                if (g[i][j] != 0) {\n                    int v = g[i][j];\n                    if (write != i) {\n                        g[write][j] = v;\n                        g[i][j] = 0;\n                    }\n                    ++write;\n                }\n            }\n        }\n    } else { // dir == 'B'\n        for (int j = 0; j < 10; ++j) {\n            int write = 9;\n            for (int i = 9; i >= 0; --i) {\n                if (g[i][j] != 0) {\n                    int v = g[i][j];\n                    if (write != i) {\n                        g[write][j] = v;\n                        g[i][j] = 0;\n                    }\n                    --write;\n                }\n            }\n        }\n    }\n}\n\n/* -------------------------------------------------------------\n   compute \u03a3 (size of a connected component)\u00b2\n   ------------------------------------------------------------- */\nlong long computeScore(const int g[10][10]) {\n    bool vis[10][10] = {};\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    long long sum = 0;\n\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (g[i][j] != 0 && !vis[i][j]) {\n                int flavour = g[i][j];\n                int cnt = 0;\n                queue<pair<int,int>> q;\n                q.emplace(i, j);\n                vis[i][j] = true;\n                while (!q.empty()) {\n                    auto [x, y] = q.front(); q.pop();\n                    ++cnt;\n                    for (int k = 0; k < 4; ++k) {\n                        int nx = x + dx[k];\n                        int ny = y + dy[k];\n                        if (0 <= nx && nx < 10 && 0 <= ny && ny < 10 &&\n                            !vis[nx][ny] && g[nx][ny] == flavour) {\n                            vis[nx][ny] = true;\n                            q.emplace(nx, ny);\n                        }\n                    }\n                }\n                sum += 1LL * cnt * cnt;\n            }\n        }\n    }\n    return sum;\n}\n\n/* ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<int> f(100);\n    for (int i = 0; i < 100; ++i) {\n        if (!(cin >> f[i])) return 0;   // no input \u2192 nothing to do\n    }\n\n    int grid[10][10];\n    memset(grid, 0, sizeof(grid));\n\n    const char dirs[4] = {'F', 'B', 'L', 'R'};\n\n    for (int t = 0; t < 100; ++t) {\n        int p;               // index of the empty cell (1\u2011based)\n        cin >> p;\n\n        /* ---- place the new candy -------------------------------- */\n        int cnt = 0;\n        bool placed = false;\n        for (int i = 0; i < 10 && !placed; ++i) {\n            for (int j = 0; j < 10 && !placed; ++j) {\n                if (grid[i][j] == 0) {\n                    ++cnt;\n                    if (cnt == p) {\n                        grid[i][j] = f[t];\n                        placed = true;\n                    }\n                }\n            }\n        }\n\n        /* ---- after the last candy no tilt is required ------------- */\n        if (t == 99) break;\n\n        /* ---- greedy choice among the four tilts ------------------- */\n        long long bestScore = -1;\n        char bestDir = 'F';\n        for (char d : dirs) {\n            int tmp[10][10];\n            memcpy(tmp, grid, sizeof(grid));\n            tilt(tmp, d);\n            long long sc = computeScore(tmp);\n            if (sc > bestScore) {\n                bestScore = sc;\n                bestDir = d;\n            }\n        }\n\n        cout << bestDir << '\\n';\n        cout.flush();\n\n        /* ---- apply the chosen tilt to the real board ------------- */\n        tilt(grid, bestDir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;          // no input\n    \n    // choose the smallest possible N (\u22654 and \u2265M)\n    int N = max(4, M);\n    if (N > 100) N = 100;                      // just in case, but M\u2264100\n    \n    long long L = 1LL * N * (N - 1) / 2;       // length of adjacency string\n    \n    // pre\u2011compute sorted degree vectors of all Gk (star graphs)\n    vector<vector<int>> candDegSorted(M, vector<int>(N));\n    for (int k = 0; k < M; ++k) {\n        vector<int> deg(N, 0);\n        deg[0] = k;                 // centre degree\n        for (int i = 1; i <= k; ++i) deg[i] = 1;   // leaves\n        // remaining vertices already 0\n        sort(deg.begin(), deg.end());\n        candDegSorted[k] = move(deg);\n    }\n    \n    // output N\n    cout << N << \"\\n\";\n    // output the M graphs\n    string base(L, '0');\n    for (int k = 0; k < M; ++k) {\n        string s = base;\n        // edges (0, j) for j = 1..k correspond to positions 0..k-1\n        for (int j = 1; j <= k; ++j) {\n            // position of edge (0,j) in lexicographic order:\n            // for i = 0, the first (N-1) entries are (0,1),(0,2),..., (0,N-1)\n            // so position = j-1\n            s[j - 1] = '1';\n        }\n        cout << s << \"\\n\";\n    }\n    cout.flush();                     // important\n    \n    // answer 100 queries\n    for (int query = 0; query < 100; ++query) {\n        string H;\n        cin >> H;\n        // compute degree vector of H\n        vector<int> deg(N, 0);\n        long long pos = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (H[pos] == '1') {\n                    ++deg[i];\n                    ++deg[j];\n                }\n                ++pos;\n            }\n        }\n        sort(deg.begin(), deg.end());\n        // find the closest candidate\n        int best = 0;\n        long long bestDist = LLONG_MAX;\n        for (int k = 0; k < M; ++k) {\n            long long dist = 0;\n            for (int i = 0; i < N; ++i) {\n                dist += llabs((long long)deg[i] - (long long)candDegSorted[k][i]);\n            }\n            if (dist < bestDist) {\n                bestDist = dist;\n                best = k;\n            }\n        }\n        cout << best << \"\\n\";\n        cout.flush();\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    // read edges, we do not need their data for the schedule\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        (void)u; (void)v; (void)w;\n    }\n\n    // read vertex coordinates, also not needed\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        (void)x; (void)y;\n    }\n\n    // round\u2011robin assignment\n    vector<int> day(M);\n    for (int i = 0; i < M; ++i) {\n        day[i] = (i % D) + 1;          // days are 1\u2011based\n    }\n\n    // output\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << day[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D;\n    if (!(cin >> D)) return 0;\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n\n    const int N = D * D * D;\n    vector<int> b0(N, 0), b1(N, 0);\n    int cur_id = 1;\n\n    // silhouette 0\n    for (int x = 0; x < D; ++x)\n        for (int y = 0; y < D; ++y)\n            for (int z = 0; z < D; ++z) {\n                if (f[0][z][x] == '1' && r[0][z][y] == '1') {\n                    int idx = x * D * D + y * D + z;\n                    b0[idx] = cur_id++;\n                }\n            }\n\n    // silhouette 1\n    for (int x = 0; x < D; ++x)\n        for (int y = 0; y < D; ++y)\n            for (int z = 0; z < D; ++z) {\n                if (f[1][z][x] == '1' && r[1][z][y] == '1') {\n                    int idx = x * D * D + y * D + z;\n                    b1[idx] = cur_id++;\n                }\n            }\n\n    int n = cur_id - 1;\n    cout << n << \"\\n\";\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << b0[i];\n    }\n    cout << \"\\n\";\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << b1[i];\n    }\n    cout << \"\\n\";\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ---------- Disjoint Set Union ----------\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\n// ---------- Main ----------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;\n\n    vector<long long> xs(N), ys(N);\n    for (int i = 0; i < N; ++i) cin >> xs[i] >> ys[i];\n\n    struct Edge {\n        int u, v;\n        long long w;\n        int idx;\n    };\n    vector<Edge> edges(M);\n    for (int j = 0; j < M; ++j) {\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[j] = {u, v, w, j};\n    }\n\n    vector<long long> a(K), b(K);\n    for (int k = 0; k < K; ++k) cin >> a[k] >> b[k];\n\n    // ---------- 1) Minimum Spanning Tree ----------\n    vector<int> B(M, 0);\n    vector<Edge> sorted = edges;\n    sort(sorted.begin(), sorted.end(),\n         [](const Edge& e1, const Edge& e2) { return e1.w < e2.w; });\n    DSU dsu(N);\n    for (const auto& e : sorted) {\n        if (dsu.unite(e.u, e.v)) {\n            B[e.idx] = 1;          // edge is powered\n        }\n    }\n\n    // ---------- 2) Assign residents to nearest station ----------\n    const long long INF64 = (1LL << 60);\n    vector<long long> maxDist2(N, -1);   // -1 means no resident assigned yet\n    for (int k = 0; k < K; ++k) {\n        long long bestDist2 = INF64;\n        int bestIdx = -1;\n        for (int i = 0; i < N; ++i) {\n            long long dx = xs[i] - a[k];\n            long long dy = ys[i] - b[k];\n            long long d2 = dx*dx + dy*dy;\n            if (d2 < bestDist2) {\n                bestDist2 = d2;\n                bestIdx = i;\n            }\n        }\n        // update max distance for that station\n        if (maxDist2[bestIdx] < bestDist2) maxDist2[bestIdx] = bestDist2;\n    }\n\n    // ---------- 3) Compute radii ----------\n    vector<int> P(N, 0);\n    for (int i = 0; i < N; ++i) {\n        if (maxDist2[i] == -1) {\n            P[i] = 0;\n        } else {\n            double d = sqrt((double)maxDist2[i]);\n            int rad = (int)floor(d);\n            // ceil: increase while rad\u00b2 < dist2\n            while ((long long)rad * rad < maxDist2[i]) ++rad;\n            // rad is now the smallest integer with rad\u00b2 \u2265 dist\u00b2\n            if (rad > 5000) rad = 5000;   // safety, should never happen\n            P[i] = rad;\n        }\n    }\n\n    // ---------- 4) Output ----------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << P[i];\n    }\n    cout << '\\n';\n    for (int j = 0; j < M; ++j) {\n        if (j) cout << ' ';\n        cout << B[j];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 30;\n    const int M = N * (N + 1) / 2;          // 465\n\n    // read the pyramid\n    vector<vector<int>> a(N);\n    for (int x = 0; x < N; ++x) {\n        a[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> a[x][y];\n        }\n    }\n\n    struct Op { int x1, y1, x2, y2; };\n    vector<Op> ops;\n    ops.reserve(10000);\n\n    // main loop \u2013 vertical bubble\n    while (true) {\n        bool changed = false;\n        for (int x = 0; x < N - 1; ++x) {\n            for (int y = 0; y <= x; ++y) {\n                // child down\u2011left (x+1 , y)\n                if (a[x][y] > a[x + 1][y]) {\n                    swap(a[x][y], a[x + 1][y]);\n                    ops.push_back({x, y, x + 1, y});\n                    changed = true;\n                    if (ops.size() > 10000) break;\n                }\n                // child down\u2011right (x+1 , y+1)\n                if (a[x][y] > a[x + 1][y + 1]) {\n                    swap(a[x][y], a[x + 1][y + 1]);\n                    ops.push_back({x, y, x + 1, y + 1});\n                    changed = true;\n                    if (ops.size() > 10000) break;\n                }\n            }\n            if (ops.size() > 10000) break;\n        }\n        if (!changed) break;\n        if (ops.size() > 10000) break;   // safety, should never happen\n    }\n\n    // output\n    cout << ops.size() << '\\n';\n    for (auto &op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' '\n             << op.x2 << ' ' << op.y2 << '\\n';\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int D, N;\n    if (!(cin >> D >> N)) return 0;\n    const int entrance_i = 0;\n    const int entrance_j = (D - 1) / 2;\n\n    vector<vector<bool>> obstacle(D, vector<bool>(D, false));\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        obstacle[ri][rj] = true;\n    }\n\n    // -----------------------------------------------------------------\n    // BFS from the entrance, assign an id to every reachable cell\n    // -----------------------------------------------------------------\n    const int INF = -1;\n    vector<vector<int>> id(D, vector<int>(D, INF));\n    vector<int> dist;               // dist[id]\n    vector<int> parent;             // parent[id] (id of parent, -1 for entrance)\n    vector<pair<int,int>> coord;    // coord[id] = (i,j)\n\n    queue<pair<int,int>> q;\n    int curId = 0;\n    id[entrance_i][entrance_j] = curId++;\n    dist.push_back(0);\n    parent.push_back(-1);\n    coord.emplace_back(entrance_i, entrance_j);\n    q.emplace(entrance_i, entrance_j);\n\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        int cur = id[i][j];\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= D || nj < 0 || nj >= D) continue;\n            if (obstacle[ni][nj]) continue;\n            if (id[ni][nj] != INF) continue;\n            id[ni][nj] = curId++;\n            dist.push_back(dist[cur] + 1);\n            parent.push_back(cur);\n            coord.emplace_back(ni, nj);\n            q.emplace(ni, nj);\n        }\n    }\n\n    int totalCells = curId;               // includes entrance\n    int entranceId = 0;\n    int M = totalCells - 1;               // number of containers\n    // sanity check (optional)\n    // assert(M == D*D - 1 - N);\n\n    // -----------------------------------------------------------------\n    // Build list of cells (ids) that can store a container\n    // -----------------------------------------------------------------\n    vector<int> placementIds;\n    placementIds.reserve(M);\n    for (int idv = 1; idv < totalCells; ++idv) placementIds.push_back(idv);\n    sort(placementIds.begin(), placementIds.end(),\n         [&](int a, int b) {\n             if (dist[a] != dist[b]) return dist[a] > dist[b]; // farthest first\n             // tie\u2011break deterministic\n             if (coord[a].first != coord[b].first) return coord[a].first > coord[b].first;\n             return coord[a].second > coord[b].second;\n         });\n\n    // -----------------------------------------------------------------\n    // Read containers and output placement positions\n    // -----------------------------------------------------------------\n    vector<int> containerNumber(totalCells, -1); // containerNumber[id] = t\n    int ptr = 0; // index in placementIds\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;\n        int cid = placementIds[ptr++];\n        containerNumber[cid] = t;\n        cout << coord[cid].first << ' ' << coord[cid].second << \"\\n\";\n        cout.flush(); // required after each placement\n    }\n\n    // -----------------------------------------------------------------\n    // Build children lists of the BFS tree\n    // -----------------------------------------------------------------\n    vector<vector<int>> children(totalCells);\n    for (int v = 1; v < totalCells; ++v) {\n        int p = parent[v];\n        children[p].push_back(v);\n    }\n\n    // -----------------------------------------------------------------\n    // Transport order: Kahn + min\u2011heap on container number\n    // -----------------------------------------------------------------\n    struct HeapNode {\n        int number; // container number\n        int id;\n        bool operator<(HeapNode const& other) const {\n            // priority_queue in C++ is a max\u2011heap, so reverse comparison\n            return number > other.number;\n        }\n    };\n    priority_queue<HeapNode> pq;\n    // initially all children of the entrance are ready\n    for (int v : children[entranceId]) {\n        pq.push({containerNumber[v], v});\n    }\n\n    while (!pq.empty()) {\n        auto cur = pq.top(); pq.pop();\n        int v = cur.id;\n        cout << coord[v].first << ' ' << coord[v].second << \"\\n\";\n        for (int ch : children[v]) {\n            pq.push({containerNumber[ch], ch});\n        }\n    }\n    // No more output needed\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    vector<vector<int>> a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (j) cout << ' ';\n            cout << a[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n    vector<long long> w(N);\n    for (int i = 0; i < N; ++i) cin >> w[i];\n\n    long long total = 0;\n    for (auto x : w) total += x;\n    double target = static_cast<double>(total) / D;\n\n    // random generator\n    std::mt19937_64 rng(\n        chrono::steady_clock::now().time_since_epoch().count());\n\n    vector<int> bestAssign(N);\n    double bestScore = numeric_limits<double>::infinity();\n\n    auto computeScore = [&](const vector<long long> &sum) -> double {\n        double sc = 0.0;\n        for (int d = 0; d < D; ++d) {\n            double diff = static_cast<double>(sum[d]) - target;\n            sc += diff * diff;\n        }\n        return sc;\n    };\n\n    // time limit handling\n    const double TIME_LIMIT = 1.8;                // seconds\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        // ----- 1) random order for greedy -----\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) {\n                 if (w[a] != w[b]) return w[a] > w[b];\n                 return (rng() & 1ULL);\n             });\n\n        // ----- 2) greedy assignment -----\n        vector<int> assign(N, -1);\n        vector<long long> sum(D, 0);\n        for (int idx : order) {\n            int bestSet = 0;\n            long long minSum = sum[0];\n            for (int d = 1; d < D; ++d) {\n                if (sum[d] < minSum) {\n                    minSum = sum[d];\n                    bestSet = d;\n                }\n            }\n            assign[idx] = bestSet;\n            sum[bestSet] += w[idx];\n        }\n\n        // ----- 3) local improvement (hill climbing) -----\n        bool improved = true;\n        while (improved) {\n            improved = false;\n\n            // try moving a single item\n            for (int i = 0; i < N && !improved; ++i) {\n                int a = assign[i];\n                long long wi = w[i];\n                double curDiffA = static_cast<double>(sum[a]) - target;\n                for (int b = 0; b < D; ++b) {\n                    if (b == a) continue;\n                    double curDiffB = static_cast<double>(sum[b]) - target;\n                    double newDiffA = static_cast<double>(sum[a] - wi) - target;\n                    double newDiffB = static_cast<double>(sum[b] + wi) - target;\n                    double delta = (newDiffA * newDiffA + newDiffB * newDiffB) -\n                                   (curDiffA * curDiffA + curDiffB * curDiffB);\n                    if (delta < -1e-9) {\n                        // perform move\n                        sum[a] -= wi;\n                        sum[b] += wi;\n                        assign[i] = b;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n\n            if (improved) continue;\n\n            // try swapping two items\n            for (int i = 0; i < N && !improved; ++i) {\n                int a = assign[i];\n                long long wi = w[i];\n                for (int j = i + 1; j < N; ++j) {\n                    int b = assign[j];\n                    if (a == b) continue;\n                    long long wj = w[j];\n                    double curDiffA = static_cast<double>(sum[a]) - target;\n                    double curDiffB = static_cast<double>(sum[b]) - target;\n                    double newDiffA = static_cast<double>(sum[a] - wi + wj) - target;\n                    double newDiffB = static_cast<double>(sum[b] - wj + wi) - target;\n                    double delta = (newDiffA * newDiffA + newDiffB * newDiffB) -\n                                   (curDiffA * curDiffA + curDiffB * curDiffB);\n                    if (delta < -1e-9) {\n                        // perform swap\n                        sum[a] = sum[a] - wi + wj;\n                        sum[b] = sum[b] - wj + wi;\n                        assign[i] = b;\n                        assign[j] = a;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n        }\n\n        // ----- 4) evaluate -----\n        double curScore = computeScore(sum);\n        if (curScore < bestScore) {\n            bestScore = curScore;\n            bestAssign = assign;\n        }\n\n        // ----- 5) time check -----\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n    }\n\n    // ----- 6) output best assignment -----\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << bestAssign[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    const int per = n / m;                // = 20\n    vector<vector<int>> stack(m);          // bottom -> top\n    vector<int> boxStack(n + 1, -1);       // current stack index of each box\n\n    for (int i = 0; i < m; ++i) {\n        stack[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x; cin >> x;\n            stack[i].push_back(x);\n            boxStack[x] = i;\n        }\n    }\n\n    vector<pair<int,int>> ops;             // (v , i)   i = 0 \u2192 removal\n\n    for (int v = 1; v <= n; ++v) {\n        int s = boxStack[v];               // stack that currently holds v\n        // move all boxes above v\n        while (!stack[s].empty() && stack[s].back() != v) {\n            int w = stack[s].back();       // topmost box\n            // choose destination stack: smallest size, different from s\n            int d = -1, bestSize = INT_MAX;\n            for (int i = 0; i < m; ++i) if (i != s) {\n                int sz = (int)stack[i].size();\n                if (sz < bestSize) {\n                    bestSize = sz;\n                    d = i;\n                }\n            }\n            // perform move\n            ops.emplace_back(w, d + 1);    // +1 because stacks are 1\u2011indexed in output\n            stack[s].pop_back();\n            stack[d].push_back(w);\n            boxStack[w] = d;\n        }\n        // now v is on top\n        ops.emplace_back(v, 0);             // removal\n        // erase v\n        stack[s].pop_back();\n        boxStack[v] = -1;\n    }\n\n    // output\n    for (auto [v, i] : ops) {\n        cout << v << ' ' << i << '\\n';\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> h;               // (N-1) \u00d7 N  : vertical walls\nvector<string> v;               // N \u00d7 (N-1)  : horizontal walls\nvector<vector<char>> visited;   // visited cells\nstring answer;                  // resulting move sequence\n\n// directions: 0=R, 1=D, 2=L, 3=U\nconst int dr[4] = {0, 1, 0, -1};\nconst int dc[4] = {1, 0, -1, 0};\nconst char dirChar[4] = {'R', 'D', 'L', 'U'};\n\n// true iff we can move from (r,c) to the neighbour in direction dir\nbool canMove(int r, int c, int dir) {\n    int nr = r + dr[dir];\n    int nc = c + dc[dir];\n    if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n    if (dir == 0) {               // right\n        return v[r][c] == '0';\n    } else if (dir == 2) {        // left\n        return v[r][c - 1] == '0';\n    } else if (dir == 1) {        // down\n        return h[r][c] == '0';\n    } else {                      // up\n        return h[r - 1][c] == '0';\n    }\n}\n\n// depth\u2011first traversal\nvoid dfs(int r, int c) {\n    visited[r][c] = 1;\n    for (int dir = 0; dir < 4; ++dir) {\n        if (!canMove(r, c, dir)) continue;\n        int nr = r + dr[dir];\n        int nc = c + dc[dir];\n        if (!visited[nr][nc]) {\n            answer.push_back(dirChar[dir]);          // go to neighbour\n            dfs(nr, nc);\n            answer.push_back(dirChar[(dir + 2) % 4]); // come back\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N)) return 0;\n\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n\n    v.resize(N);\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    // read and ignore the d\u2011values\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            long long x;\n            cin >> x;\n        }\n\n    visited.assign(N, vector<char>(N, 0));\n    dfs(0, 0);\n\n    cout << answer << '\\n';\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n    \n    // positions[letter] = list of (i,j) where board[i][j] == letter\n    vector<pair<int,int>> positions[26];\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = board[i][j];\n            positions[c - 'A'].push_back({i, j});\n        }\n    }\n    \n    vector<string> targets(M);\n    for (int k = 0; k < M; ++k) cin >> targets[k];\n    \n    vector<pair<int,int>> answer;\n    int cur_i = si, cur_j = sj;\n    \n    for (const string& t : targets) {\n        for (char ch : t) {\n            const auto& vec = positions[ch - 'A'];\n            // choose the cell with minimal Manhattan distance to current position\n            int bestDist = INT_MAX;\n            int best_i = -1, best_j = -1;\n            for (auto [i, j] : vec) {\n                int d = abs(i - cur_i) + abs(j - cur_j);\n                if (d < bestDist) {\n                    bestDist = d;\n                    best_i = i;\n                    best_j = j;\n                }\n            }\n            // should always find at least one cell\n            answer.emplace_back(best_i, best_j);\n            cur_i = best_i;\n            cur_j = best_j;\n        }\n    }\n    \n    // output\n    for (auto [i, j] : answer) {\n        cout << i << ' ' << j << '\\n';\n    }\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    double eps;\n    if (!(cin >> N >> M >> eps)) return 0;   // no input\n    \n    // read the M polyomino shapes (not needed for the offline solution)\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int t = 0; t < d; ++t) {\n            int i, j;\n            cin >> i >> j;\n        }\n    }\n    \n    // read the positions of the fields (also not needed)\n    for (int k = 0; k < M; ++k) {\n        int di, dj;\n        cin >> di >> dj;\n    }\n    \n    // read the whole v matrix\n    vector<vector<int>> v(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> v[i][j];\n        }\n    }\n    \n    // read and discard the 2 * N^2 random numbers used for noisy queries\n    int discard_cnt = 2 * N * N;\n    double dummy;\n    for (int i = 0; i < discard_cnt; ++i) {\n        if (!(cin >> dummy)) break; // safety for non\u2011interactive runs\n    }\n    \n    // collect all squares with v > 0\n    vector<pair<int,int>> ans;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (v[i][j] > 0) ans.emplace_back(i, j);\n        }\n    }\n    \n    // output the answer in the required format\n    cout << \"a \" << ans.size();\n    for (auto [i, j] : ans) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << '\\n';\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\n    // read and ignore the desired areas\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            long long a;\n            cin >> a;\n        }\n    }\n    // output the baseline layout: horizontal strips of height 1\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            // rectangle: (k, 0) .. (k+1, W)\n            cout << k << ' ' << 0 << ' ' << k + 1 << ' ' << W << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long MOD = 998244353LL;\n\nstruct Op {\n    int m, p, q;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;          // N = 9, M = 20, K = 81\n    vector<vector<long long>> board(N, vector<long long>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            long long x; cin >> x;\n            board[i][j] = x % MOD;\n        }\n    }\n    // stamps[m][u][v]\n    vector<array<array<long long,3>,3>> stamp(M);\n    for (int m = 0; m < M; ++m) {\n        for (int u = 0; u < 3; ++u) {\n            for (int v = 0; v < 3; ++v) {\n                long long x; cin >> x;\n                stamp[m][u][v] = x % MOD;\n            }\n        }\n    }\n\n    vector<Op> ops;\n    const int maxP = N - 3;   // last top\u2011left row where a stamp fits\n    const int maxQ = N - 3;   // last top\u2011left column\n\n    for (int step = 0; step < K; ++step) {\n        long long bestDelta = LLONG_MIN;\n        Op bestOp{-1,-1,-1};\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= maxP; ++p) {\n                for (int q = 0; q <= maxQ; ++q) {\n                    long long delta = 0;\n                    for (int u = 0; u < 3; ++u) {\n                        for (int v = 0; v < 3; ++v) {\n                            long long old = board[p+u][q+v];\n                            long long add = stamp[m][u][v];\n                            long long nw = old + add;\n                            if (nw >= MOD) nw -= MOD;\n                            delta += (nw - old);\n                        }\n                    }\n                    if (delta > bestDelta) {\n                        bestDelta = delta;\n                        bestOp = {m, p, q};\n                    }\n                }\n            }\n        }\n\n        if (bestDelta <= 0) break;          // no improving operation\n        // apply the chosen operation\n        int m = bestOp.m, p = bestOp.p, q = bestOp.q;\n        for (int u = 0; u < 3; ++u) {\n            for (int v = 0; v < 3; ++v) {\n                board[p+u][q+v] += stamp[m][u][v];\n                if (board[p+u][q+v] >= MOD) board[p+u][q+v] -= MOD;\n            }\n        }\n        ops.push_back(bestOp);\n    }\n\n    cout << ops.size() << \"\\n\";\n    for (auto &op : ops) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << \"\\n\";\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\n// generate a Manhattan walk from (r,c) to (tr,tc)\nstatic string walk(int r, int c, int tr, int tc) {\n    string s;\n    while (r > tr) { s.push_back('U'); --r; }\n    while (r < tr) { s.push_back('D'); ++r; }\n    while (c > tc) { s.push_back('L'); --c; }\n    while (c < tc) { s.push_back('R'); ++c; }\n    return s;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> A(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> A[i][j];\n\n    // actions for each crane\n    vector<string> act(N);\n    // small cranes: bomb at turn 0, later do nothing\n    // we will pad them later to the length of the large crane\n    for (int i = 1; i < N; ++i) act[i] = \"B\";\n\n    // large crane (crane 0)\n    string &big = act[0];\n    int curR = 0, curC = 0;               // start position (0,0)\n\n    for (int i = 0; i < N; ++i) {        // receiving gate i\n        for (int j = 0; j < N; ++j) {    // j\u2011th container of this gate\n            // move to (i,0)\n            big += walk(curR, curC, i, 0);\n            curR = i; curC = 0;\n            // pick up\n            big.push_back('P');\n            int b = A[i][j];\n            int dr = b / N;               // destination row\n            // move to dispatch gate (dr, N-1)\n            big += walk(curR, curC, dr, N - 1);\n            curR = dr; curC = N - 1;\n            // release\n            big.push_back('Q');\n            // move back to the receiving gate (i,0)\n            big += walk(curR, curC, i, 0);\n            curR = i; curC = 0;\n        }\n    }\n\n    // pad small cranes with '.' to the length of the longest string\n    size_t L = big.size();\n    for (int i = 1; i < N; ++i) {\n        if (act[i].size() < L) act[i].append(L - act[i].size(), '.');\n    }\n\n    // output\n    for (int i = 0; i < N; ++i) {\n        cout << act[i] << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> h(N, vector<int>(N));\n    bool allZero = true;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> h[i][j];\n            if (h[i][j] != 0) allZero = false;\n        }\n    }\n    if (allZero) return 0;               // nothing to do\n\n    vector<string> ops;\n    ops.reserve(2000);\n\n    int curX = 0, curY = 0;               // current truck position\n    long long load = 0;                  // amount of soil on the truck\n\n    auto moveTo = [&](int tx, int ty) {\n        while (curX != tx || curY != ty) {\n            if (curX < tx) {\n                ops.emplace_back(\"D\");\n                ++curX;\n            } else if (curX > tx) {\n                ops.emplace_back(\"U\");\n                --curX;\n            } else if (curY < ty) {\n                ops.emplace_back(\"R\");\n                ++curY;\n            } else { // curY > ty\n                ops.emplace_back(\"L\");\n                --curY;\n            }\n        }\n    };\n\n    // snake order: left\u2192right on even rows, right\u2192left on odd rows\n    vector<pair<int,int>> order;\n    order.reserve(N * N);\n    for (int i = 0; i < N; ++i) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; ++j) order.emplace_back(i, j);\n        } else {\n            for (int j = N - 1; j >= 0; --j) order.emplace_back(i, j);\n        }\n    }\n\n    // ---------- Phase 1 : collect all surplus ----------\n    for (auto [x, y] : order) {\n        moveTo(x, y);\n        if (h[x][y] > 0) {\n            int d = h[x][y];\n            ops.emplace_back(\"+\" + to_string(d));\n            load += d;\n            h[x][y] = 0;\n        }\n    }\n\n    // ---------- Phase 2 : distribute to deficits ----------\n    for (auto [x, y] : order) {\n        moveTo(x, y);\n        if (h[x][y] < 0) {\n            int d = -h[x][y];\n            ops.emplace_back(\"-\" + to_string(d));\n            load -= d;\n            h[x][y] = 0;\n        }\n    }\n\n    // output\n    for (const string& s : ops) {\n        cout << s << '\\n';\n    }\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    const int S = 2 * N * (N - 1);          // number of seeds = 60\n    const int cells = N * N;               // 36\n    \n    // read initial seeds\n    vector<vector<int>> X(S, vector<int>(M));\n    for (int i = 0; i < S; ++i)\n        for (int j = 0; j < M; ++j)\n            cin >> X[i][j];\n    \n    vector<int> idx(S);\n    iota(idx.begin(), idx.end(), 0);\n    \n    for (int turn = 0; turn < T; ++turn) {\n        // compute V = sum of components\n        vector<int> V(S);\n        for (int i = 0; i < S; ++i) {\n            long long sum = 0;\n            for (int j = 0; j < M; ++j) sum += X[i][j];\n            V[i] = static_cast<int>(sum);\n        }\n        // sort indices by decreasing V\n        sort(idx.begin(), idx.end(),\n             [&](int a, int b) { return V[a] > V[b]; });\n        \n        // place the best 'cells' seeds on the board (row\u2011major)\n        int pos = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << idx[pos++];\n                if (j + 1 == N) cout << '\\n';\n                else cout << ' ';\n            }\n        }\n        cout.flush();   // important for interactive judges\n        \n        // read the next batch of seeds\n        for (int i = 0; i < S; ++i)\n            for (int j = 0; j < M; ++j)\n                cin >> X[i][j];\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, V;\n    if (!(cin >> N >> M >> V)) return 0;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) cin >> s[i];\n    for (int i = 0; i < N; ++i) cin >> t[i];\n\n    // collect positions\n    vector<Pos> srcOnly, dstOnly;\n    vector<vector<int>> hasTak(N, vector<int>(N, 0));\n    vector<vector<int>> isTarget(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (s[i][j] == '1') hasTak[i][j] = 1;\n            if (t[i][j] == '1') isTarget[i][j] = 1;\n        }\n\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (hasTak[i][j] && !isTarget[i][j])\n                srcOnly.push_back({i, j});\n            if (!hasTak[i][j] && isTarget[i][j])\n                dstOnly.push_back({i, j});\n        }\n\n    // sort for deterministic output\n    auto cmpPos = [](const Pos& a, const Pos& b) {\n        if (a.x != b.x) return a.x < b.x;\n        return a.y < b.y;\n    };\n    sort(srcOnly.begin(), srcOnly.end(), cmpPos);\n    sort(dstOnly.begin(), dstOnly.end(), cmpPos);\n    // they have the same size\n    int K = srcOnly.size();\n\n    // direction vectors for orientation indices 0..3\n    const int dx[4] = {0, 1, 0, -1};\n    const int dy[4] = {1, 0, -1, 0};\n\n    // helper: choose a direction for a target cell so that root stays inside\n    auto choose_dir = [&](int x, int y) -> int {\n        for (int d = 0; d < 4; ++d) {\n            int rx = x - dx[d];\n            int ry = y - dy[d];\n            if (0 <= rx && rx < N && 0 <= ry && ry < N) return d;\n        }\n        // should never happen\n        return 0;\n    };\n\n    // current state\n    int curRootX = 0, curRootY = 0;   // start at (0,0)\n    int curDir = 0;                  // leaf initially points right\n\n    vector<string> ops; // each string length = 4\n\n    auto add_op = [&](char moveC, char rotC, char rootAct, char leafAct) {\n        string s(4, '.');\n        s[0] = moveC;\n        s[1] = rotC;\n        s[2] = rootAct;\n        s[3] = leafAct;\n        ops.push_back(s);\n    };\n\n    auto rotate_to = [&](int targetDir) {\n        int diff = (targetDir - curDir + 4) % 4;\n        if (diff == 0) return;\n        if (diff == 1) {               // one clockwise\n            add_op('.', 'R', '.', '.');\n            curDir = (curDir + 1) % 4;\n        } else if (diff == 2) {        // two clockwise\n            add_op('.', 'R', '.', '.');\n            curDir = (curDir + 1) % 4;\n            add_op('.', 'R', '.', '.');\n            curDir = (curDir + 1) % 4;\n        } else { // diff == 3, one counter\u2011clockwise\n            add_op('.', 'L', '.', '.');\n            curDir = (curDir + 3) % 4;\n        }\n    };\n\n    auto move_root_to = [&](int tx, int ty) {\n        while (curRootX < tx) {\n            add_op('D', '.', '.', '.');\n            ++curRootX;\n        }\n        while (curRootX > tx) {\n            add_op('U', '.', '.', '.');\n            --curRootX;\n        }\n        while (curRootY < ty) {\n            add_op('R', '.', '.', '.');\n            ++curRootY;\n        }\n        while (curRootY > ty) {\n            add_op('L', '.', '.', '.');\n            --curRootY;\n        }\n    };\n\n    for (int i = 0; i < K; ++i) {\n        Pos sPos = srcOnly[i];\n        Pos dPos = dstOnly[i];\n\n        // ----- go to source -----\n        int dirSrc = choose_dir(sPos.x, sPos.y);\n        int rootTargetX = sPos.x - dx[dirSrc];\n        int rootTargetY = sPos.y - dy[dirSrc];\n\n        rotate_to(dirSrc);\n        move_root_to(rootTargetX, rootTargetY);\n        // pick up\n        add_op('.', '.', '.', 'P');\n\n        // ----- go to destination -----\n        int dirDst = choose_dir(dPos.x, dPos.y);\n        int rootTargetX2 = dPos.x - dx[dirDst];\n        int rootTargetY2 = dPos.y - dy[dirDst];\n\n        rotate_to(dirDst);\n        move_root_to(rootTargetX2, rootTargetY2);\n        // release\n        add_op('.', '.', '.', 'P');\n    }\n\n    // ---------- output ----------\n    // tree description\n    cout << 2 << \"\\n\";\n    cout << 0 << \" \" << 1 << \"\\n\";   // parent of vertex 1 and length\n    cout << 0 << \" \" << 0 << \"\\n\";   // root position (0,0)\n\n    // operations\n    for (const string& s : ops) cout << s << \"\\n\";\n\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ull = unsigned long long;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if(!(cin >> N)) return 0;\n    vector<pair<int,int>> mackerel(N);\n    vector<pair<int,int>> sardine(N);\n    for (int i = 0; i < N; ++i) {\n        int x,y; cin >> x >> y;\n        mackerel[i] = {x,y};\n    }\n    unordered_set<ull> sardineSet;\n    sardineSet.reserve(N*2);\n    for (int i = 0; i < N; ++i) {\n        int x,y; cin >> x >> y;\n        sardine[i] = {x,y};\n        ull key = ( (ull)x << 32 ) | (unsigned int) y;\n        sardineSet.insert(key);\n    }\n    \n    // ------------------------------------------------------------\n    // 1) try to isolate a single mackerel with a 1x1 square\n    for (auto [x,y] : mackerel) {\n        if (x >= 100000 || y >= 100000) continue; // would go out of bounds\n        bool ok = true;\n        for (int dx = 0; dx <= 1 && ok; ++dx) {\n            for (int dy = 0; dy <= 1; ++dy) {\n                int nx = x + dx;\n                int ny = y + dy;\n                ull key = ( (ull)nx << 32 ) | (unsigned int) ny;\n                if (sardineSet.find(key) != sardineSet.end()) {\n                    ok = false;\n                    break;\n                }\n            }\n        }\n        if (ok) {\n            // output rectangle [x,x+1] \u00d7 [y,y+1]\n            cout << 4 << \"\\n\";\n            cout << x << \" \" << y << \"\\n\";\n            cout << x+1 << \" \" << y << \"\\n\";\n            cout << x+1 << \" \" << y+1 << \"\\n\";\n            cout << x << \" \" << y+1 << \"\\n\";\n            return 0;\n        }\n    }\n    \n    // ------------------------------------------------------------\n    // 2) grid cell fallback\n    const int G = 2000;                // side length of a cell\n    const int C = 100000 / G;          // 50, divides exactly\n    vector<vector<int>> mCount(C, vector<int>(C, 0));\n    vector<vector<int>> sCount(C, vector<int>(C, 0));\n    \n    auto cellIdx = [&](int coord) -> int {\n        int idx = coord / G;\n        if (idx >= C) idx = C-1;\n        return idx;\n    };\n    \n    for (auto [x,y] : mackerel) {\n        int cx = cellIdx(x);\n        int cy = cellIdx(y);\n        ++mCount[cx][cy];\n    }\n    for (auto [x,y] : sardine) {\n        int cx = cellIdx(x);\n        int cy = cellIdx(y);\n        ++sCount[cx][cy];\n    }\n    \n    int bestCx = -1, bestCy = -1;\n    int bestNet = INT_MIN;\n    for (int cx = 0; cx < C; ++cx) {\n        for (int cy = 0; cy < C; ++cy) {\n            int net = mCount[cx][cy] - sCount[cx][cy];\n            if (net > bestNet) {\n                bestNet = net;\n                bestCx = cx;\n                bestCy = cy;\n            }\n        }\n    }\n    if (bestNet > 0) {\n        int left   = bestCx * G;\n        int right  = (bestCx + 1) * G;\n        int bottom = bestCy * G;\n        int top    = (bestCy + 1) * G;\n        cout << 4 << \"\\n\";\n        cout << left << \" \" << bottom << \"\\n\";\n        cout << right << \" \" << bottom << \"\\n\";\n        cout << right << \" \" << top << \"\\n\";\n        cout << left << \" \" << top << \"\\n\";\n        return 0;\n    }\n    \n    // ------------------------------------------------------------\n    // 3) whole area fallback\n    cout << 4 << \"\\n\";\n    cout << 0 << \" \" << 0 << \"\\n\";\n    cout << 100000 << \" \" << 0 << \"\\n\";\n    cout << 100000 << \" \" << 100000 << \"\\n\";\n    cout << 0 << \" \" << 100000 << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    long long sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    vector<long long> w(N), h(N);\n    for (int i = 0; i < N; ++i) cin >> w[i] >> h[i];\n\n    for (int turn = 0; turn < T; ++turn) {\n        // place all rectangles in a single row\n        cout << N << '\\n';\n        for (int i = 0; i < N; ++i) {\n            int r = (h[i] > w[i]) ? 1 : 0;          // rotate if observed height is larger\n            int b = (i == 0) ? -1 : i - 1;          // reference rectangle\n            cout << i << ' ' << r << ' ' << 'U' << ' ' << b << '\\n';\n        }\n        cout.flush();                               // required for the interactive protocol\n\n        long long Wp, Hp;\n        if (!(cin >> Wp >> Hp)) break;             // read the noisy box size (ignored)\n    }\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, H;\n    if (!(cin >> N >> M >> H)) return 0;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    // coordinates are irrelevant for the algorithm\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    // sort neighbours by beauty ascending (low beauty first)\n    for (int v = 0; v < N; ++v) {\n        sort(adj[v].begin(), adj[v].end(),\n             [&](int a, int b){ return A[a] < A[b]; });\n    }\n    \n    const int UNASSIGNED = -2;\n    vector<int> parent(N, UNASSIGNED);\n    vector<int> depth(N, -1);\n    \n    // vertices ordered by decreasing beauty\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int i, int j){ return A[i] > A[j]; });\n    \n    queue<pair<int,int>> q;\n    for (int v : order) {\n        if (parent[v] != UNASSIGNED) continue; // already placed\n        // start a new tree with v as root\n        parent[v] = -1;\n        depth[v] = 0;\n        q.emplace(v, 0);\n        while (!q.empty()) {\n            auto [u, d] = q.front(); q.pop();\n            if (d == H) continue; // cannot go deeper\n            for (int w : adj[u]) {\n                if (parent[w] == UNASSIGNED) {\n                    parent[w] = u;\n                    depth[w] = d + 1;\n                    q.emplace(w, d + 1);\n                }\n            }\n        }\n    }\n    \n    // output\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << parent[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    struct Op { char d; int p; };\n    vector<Op> ops;\n\n    // collect all initial Oni positions\n    vector<pair<int,int>> oni;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (board[i][j] == 'x')\n                oni.emplace_back(i, j);\n\n    for (auto [i, j] : oni) {\n        // check safety of the four directions\n        bool safeU = true, safeD = true, safeL = true, safeR = true;\n        for (int k = 0; k < i; ++k) if (board[k][j] == 'o') safeU = false;\n        for (int k = i + 1; k < N; ++k) if (board[k][j] == 'o') safeD = false;\n        for (int k = 0; k < j; ++k) if (board[i][k] == 'o') safeL = false;\n        for (int k = j + 1; k < N; ++k) if (board[i][k] == 'o') safeR = false;\n\n        // distances to the edge\n        int distU = i + 1;\n        int distD = N - i;\n        int distL = j + 1;\n        int distR = N - j;\n\n        // choose safe direction with minimal distance\n        char dir = '?';\n        int best = INT_MAX;\n        if (safeU && distU < best) { best = distU; dir = 'U'; }\n        if (safeD && distD < best) { best = distD; dir = 'D'; }\n        if (safeL && distL < best) { best = distL; dir = 'L'; }\n        if (safeR && distR < best) { best = distR; dir = 'R'; }\n\n        // generate the opposite shift sequence\n        if (dir == 'U') {\n            for (int k = 0; k < distU; ++k) ops.push_back({'U', j});\n            for (int k = 0; k < distU; ++k) ops.push_back({'D', j});\n        } else if (dir == 'D') {\n            for (int k = 0; k < distD; ++k) ops.push_back({'D', j});\n            for (int k = 0; k < distD; ++k) ops.push_back({'U', j});\n        } else if (dir == 'L') {\n            for (int k = 0; k < distL; ++k) ops.push_back({'L', i});\n            for (int k = 0; k < distL; ++k) ops.push_back({'R', i});\n        } else if (dir == 'R') {\n            for (int k = 0; k < distR; ++k) ops.push_back({'R', i});\n            for (int k = 0; k < distR; ++k) ops.push_back({'L', i});\n        } else {\n            // This should never happen because the input guarantees a safe direction.\n        }\n\n        // mark the Oni as removed in our copy of the board\n        board[i][j] = '.';\n    }\n\n    // output\n    for (auto [d, p] : ops) {\n        cout << d << ' ' << p << '\\n';\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    long long L;\n    if (!(cin >> N >> L)) return 0;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    /* ---------- weighted distribution (T_i + 1) ---------- */\n    vector<long long> pref(N + 1, 0);\n    for (int i = 0; i < N; ++i) pref[i + 1] = pref[i] + (static_cast<long long>(T[i]) + 1);\n    const long long totalWeight = pref[N];\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    auto sample = [&](void) -> int {\n        long long r = rng() % totalWeight;\n        // first index with pref[idx] > r\n        int idx = static_cast<int>(upper_bound(pref.begin(), pref.end(), r) - pref.begin() - 1);\n        return idx;\n    };\n\n    /* ---------- simulation and error computation ---------- */\n    auto error_of = [&](const vector<int> &a, const vector<int> &b) -> long long {\n        static vector<int> cnt;          // reused to avoid reallocation\n        cnt.assign(N, 0);\n        int cur = 0;\n        for (long long step = 0; step < L; ++step) {\n            int t = cnt[cur];\n            ++cnt[cur];\n            if ((t & 1) == 0) cur = b[cur];   // even \u2192 b\n            else               cur = a[cur];   // odd  \u2192 a\n        }\n        long long err = 0;\n        for (int i = 0; i < N; ++i) err += llabs(static_cast<long long>(cnt[i]) - static_cast<long long>(T[i]));\n        return err;\n    };\n\n    /* ---------- initial deterministic cycle (baseline) ---------- */\n    vector<int> best_a(N), best_b(N);\n    for (int i = 0; i < N; ++i) {\n        best_a[i] = (i + 1) % N;\n        best_b[i] = (i + 1) % N;\n    }\n    long long best_err = error_of(best_a, best_b);\n\n    /* ---------- random search (time limited) ---------- */\n    const double TIME_LIMIT = 1.8;                     // seconds\n    const auto start = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        vector<int> a(N), b(N);\n        bool cycleIsA = (rng() & 1);   // decide which side holds the cycle\n        if (cycleIsA) {\n            for (int i = 0; i < N; ++i) a[i] = (i + 1) % N;\n            for (int i = 0; i < N; ++i) b[i] = sample();\n        } else {\n            for (int i = 0; i < N; ++i) b[i] = (i + 1) % N;\n            for (int i = 0; i < N; ++i) a[i] = sample();\n        }\n\n        long long err = error_of(a, b);\n        if (err < best_err) {\n            best_err = err;\n            best_a = std::move(a);\n            best_b = std::move(b);\n        }\n    }\n\n    /* ---------- output ---------- */\n    for (int i = 0; i < N; ++i) {\n        cout << best_a[i] << ' ' << best_b[i] << '\\n';\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n    // read and ignore the rectangle data\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n    }\n\n    // ----- build groups -------------------------------------------------\n    vector<vector<int>> groups;\n    groups.reserve(M);\n    int cur = 0;\n    for (int i = 0; i < M; ++i) {\n        vector<int> grp;\n        grp.reserve(G[i]);\n        for (int j = 0; j < G[i]; ++j) {\n            grp.push_back(cur++);\n        }\n        groups.push_back(move(grp));\n    }\n\n    // ----- output -------------------------------------------------------\n    cout << \"!\\n\";\n    for (int i = 0; i < M; ++i) {\n        const auto &g = groups[i];\n        // line with the cities of the group\n        for (size_t j = 0; j < g.size(); ++j) {\n            if (j) cout << ' ';\n            cout << g[j];\n        }\n        cout << \"\\n\";\n        // edges of a simple chain\n        for (size_t j = 0; j + 1 < g.size(); ++j) {\n            cout << g[j] << ' ' << g[j + 1] << \"\\n\";\n        }\n    }\n    cout.flush();\n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<pair<int,int>> pos(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> pos[i].first >> pos[i].second;\n    }\n\n    int cur_r = pos[0].first;\n    int cur_c = pos[0].second;\n\n    // we will output actions directly to stdout\n    for (int idx = 1; idx < M; ++idx) {\n        int tr = pos[idx].first;\n        int tc = pos[idx].second;\n\n        // vertical movement\n        while (cur_r < tr) {\n            cout << \"M D\\n\";\n            ++cur_r;\n        }\n        while (cur_r > tr) {\n            cout << \"M U\\n\";\n            --cur_r;\n        }\n        // horizontal movement\n        while (cur_c < tc) {\n            cout << \"M R\\n\";\n            ++cur_c;\n        }\n        while (cur_c > tc) {\n            cout << \"M L\\n\";\n            --cur_c;\n        }\n    }\n    // No need to output anything else.\n    return 0;\n}"},"2":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    long long r;\n    int idx;\n};\n\nint n;\nvector<Point> pt;\nvector<int> ans_a, ans_b, ans_c, ans_d;\n\n/* -------------------------------------------------------------\n   leaf rectangle \u2013 try to choose width/height that best matches\n   the desired area while still containing the point.\n   ------------------------------------------------------------- */\nvoid allocate_leaf(int x0, int x1, int y0, int y1, const Point& p) {\n    int width  = x1 - x0;\n    int height = y1 - y0;\n    long long want = p.r;\n\n    int best_w = width, best_h = height;\n    long long best_diff = LLONG_MAX;\n\n    // try all possible widths (1 \u2026 width)\n    for (int w = 1; w <= width; ++w) {\n        // two candidates for height: floor and ceil of want/w\n        long long h_floor = want / w;\n        long long h_ceil  = (want + w - 1) / w;\n\n        for (long long h_raw : {h_floor, h_ceil}) {\n            if (h_raw < 1) continue;\n            if (h_raw > height) continue;\n            int h = (int)h_raw;\n\n            // check that the rectangle can be placed so that (x,y) is inside\n            int a_low  = max(x0, p.x - w + 1);\n            int a_high = min(p.x, x1 - w);\n            if (a_low > a_high) continue;\n            int b_low  = max(y0, p.y - h + 1);\n            int b_high = min(p.y, y1 - h);\n            if (b_low > b_high) continue;\n\n            long long area = 1LL * w * h;\n            long long diff = llabs(area - want);\n            if (diff < best_diff) {\n                best_diff = diff;\n                best_w = w;\n                best_h = h;\n            }\n        }\n    }\n\n    // place the rectangle as far left / bottom as possible inside the leaf\n    int a_low  = max(x0, p.x - best_w + 1);\n    int a_high = min(p.x, x1 - best_w);\n    int a = a_low;                     // any value in [a_low, a_high] works\n    int b_low  = max(y0, p.y - best_h + 1);\n    int b_high = min(p.y, y1 - best_h);\n    int b = b_low;                     // any value in [b_low, b_high] works\n\n    ans_a[p.idx] = a;\n    ans_b[p.idx] = b;\n    ans_c[p.idx] = a + best_w;\n    ans_d[p.idx] = b + best_h;\n}\n\n/* -------------------------------------------------------------\n   recursive guillotine partition\n   ------------------------------------------------------------- */\nvoid solve_region(int x0, int x1, int y0, int y1,\n                  const vector<int>& ids) {\n    if (ids.empty()) return;\n    if (ids.size() == 1) {\n        allocate_leaf(x0, x1, y0, y1, pt[ids[0]]);\n        return;\n    }\n\n    int width  = x1 - x0;\n    int height = y1 - y0;\n    bool vertical = (width >= height);\n\n    if (vertical) {\n        // ----- vertical cut -------------------------------------------------\n        vector<int> sorted = ids;\n        sort(sorted.begin(), sorted.end(),\n             [&](int a, int b){ return pt[a].x < pt[b].x; });\n\n        // prefix sums of r\n        vector<long long> pref(sorted.size());\n        for (size_t i = 0; i < sorted.size(); ++i) {\n            pref[i] = pt[sorted[i]].r + (i ? pref[i-1] : 0);\n        }\n\n        long long bestDiff = LLONG_MAX;\n        int bestX = -1;                     // cut column (absolute coordinate)\n\n        for (size_t k = 0; k + 1 < sorted.size(); ++k) {\n            long long sumLeft = pref[k];\n            int leftMaxX  = pt[sorted[k]].x;\n            int rightMinX = pt[sorted[k+1]].x;\n\n            // ideal width to host sumLeft area\n            long long needW = (sumLeft + height - 1) / height; // ceil\n            int X = x0 + (int)needW;\n\n            // enforce that the cut lies between the two point columns\n            if (X <= leftMaxX) X = leftMaxX + 1;\n            if (X >  rightMinX) X = rightMinX;\n            if (X <= x0) X = x0 + 1;\n            if (X >= x1) X = x1 - 1;\n\n            long long areaLeft = 1LL * (X - x0) * height;\n            long long diff = llabs(areaLeft - sumLeft);\n            if (diff < bestDiff) {\n                bestDiff = diff;\n                bestX = X;\n            }\n        }\n\n        // fallback: split in the middle if no suitable cut was found\n        if (bestX == -1) {\n            bestX = x0 + width / 2;\n            if (bestX == x0) bestX = x0 + 1;\n            if (bestX == x1) bestX = x1 - 1;\n        }\n\n        // partition ids\n        vector<int> leftIds, rightIds;\n        for (int id : ids) {\n            if (pt[id].x < bestX) leftIds.push_back(id);\n            else                 rightIds.push_back(id);\n        }\n\n        // if a side became empty (possible when many points share the same x)\n        if (leftIds.empty() || rightIds.empty()) {\n            bestX = (x0 + x1) / 2;\n            if (bestX == x0) bestX = x0 + 1;\n            if (bestX == x1) bestX = x1 - 1;\n            leftIds.clear(); rightIds.clear();\n            for (int id : ids) {\n                if (pt[id].x < bestX) leftIds.push_back(id);\n                else                 rightIds.push_back(id);\n            }\n        }\n\n        solve_region(x0, bestX, y0, y1, leftIds);\n        solve_region(bestX, x1, y0, y1, rightIds);\n    } else {\n        // ----- horizontal cut ------------------------------------------------\n        vector<int> sorted = ids;\n        sort(sorted.begin(), sorted.end(),\n             [&](int a, int b){ return pt[a].y < pt[b].y; });\n\n        vector<long long> pref(sorted.size());\n        for (size_t i = 0; i < sorted.size(); ++i) {\n            pref[i] = pt[sorted[i]].r + (i ? pref[i-1] : 0);\n        }\n\n        long long bestDiff = LLONG_MAX;\n        int bestY = -1;                     // cut row (absolute coordinate)\n\n        for (size_t k = 0; k + 1 < sorted.size(); ++k) {\n            long long sumTop = pref[k];\n            int topMaxY    = pt[sorted[k]].y;\n            int bottomMinY = pt[sorted[k+1]].y;\n\n            long long needH = (sumTop + width - 1) / width; // ceil\n            int Y = y0 + (int)needH;\n\n            if (Y <= topMaxY)   Y = topMaxY + 1;\n            if (Y >  bottomMinY) Y = bottomMinY;\n            if (Y <= y0) Y = y0 + 1;\n            if (Y >= y1) Y = y1 - 1;\n\n            long long areaTop = 1LL * (Y - y0) * width;\n            long long diff = llabs(areaTop - sumTop);\n            if (diff < bestDiff) {\n                bestDiff = diff;\n                bestY = Y;\n            }\n        }\n\n        if (bestY == -1) {\n            bestY = y0 + height / 2;\n            if (bestY == y0) bestY = y0 + 1;\n            if (bestY == y1) bestY = y1 - 1;\n        }\n\n        vector<int> topIds, botIds;\n        for (int id : ids) {\n            if (pt[id].y < bestY) topIds.push_back(id);\n            else                  botIds.push_back(id);\n        }\n\n        if (topIds.empty() || botIds.empty()) {\n            bestY = (y0 + y1) / 2;\n            if (bestY == y0) bestY = y0 + 1;\n            if (bestY == y1) bestY = y1 - 1;\n            topIds.clear(); botIds.clear();\n            for (int id : ids) {\n                if (pt[id].y < bestY) topIds.push_back(id);\n                else                  botIds.push_back(id);\n            }\n        }\n\n        solve_region(x0, x1, y0, bestY, topIds);\n        solve_region(x0, x1, bestY, y1, botIds);\n    }\n}\n\n/* ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> n)) return 0;\n    pt.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> pt[i].x >> pt[i].y >> pt[i].r;\n        pt[i].idx = i;\n    }\n\n    ans_a.assign(n, 0);\n    ans_b.assign(n, 0);\n    ans_c.assign(n, 0);\n    ans_d.assign(n, 0);\n\n    vector<int> all_ids(n);\n    iota(all_ids.begin(), all_ids.end(), 0);\n    solve_region(0, 10000, 0, 10000, all_ids);\n\n    for (int i = 0; i < n; ++i) {\n        cout << ans_a[i] << ' ' << ans_b[i] << ' '\n             << ans_c[i] << ' ' << ans_d[i] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 50;\n    int si, sj;\n    if (!(cin >> si >> sj)) return 0;\n\n    // read tile ids\n    vector<vector<int>> tile(N, vector<int>(N));\n    int maxTile = -1;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> tile[i][j];\n            maxTile = max(maxTile, tile[i][j]);\n        }\n    }\n    const int M = maxTile + 1;               // number of tiles\n\n    // read values\n    vector<vector<int>> val(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> val[i][j];\n\n    const char dirChar[4] = {'U', 'D', 'L', 'R'};\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    // random generator\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n\n    // visited array using run id trick (no need to clear each run)\n    vector<int> visited(M, 0);\n    int runId = 1;\n\n    string bestPath;\n    long long bestScore = -1;\n\n    // time limit (\u22481.9 seconds)\n    const long long TIME_LIMIT_MS = 1900;\n    auto startTime = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        long long elapsed = chrono::duration_cast<chrono::milliseconds>(now - startTime).count();\n        if (elapsed > TIME_LIMIT_MS) break;\n\n        // choose heuristic for this run (0 = value\u2011greedy, 1 = degree\u2011aware)\n        int heuristic = (rng() & 1);   // cheap random 0/1\n\n        int curRun = runId++;          // unique id for this run\n        // mark start tile as visited\n        visited[tile[si][sj]] = curRun;\n\n        int ci = si, cj = sj;\n        long long curScore = val[ci][cj];\n        string curPath;\n\n        while (true) {\n            // collect admissible directions\n            int cand[4];\n            int candCnt = 0;\n            for (int d = 0; d < 4; ++d) {\n                int nx = ci + dx[d];\n                int ny = cj + dy[d];\n                if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                if (visited[tile[nx][ny]] == curRun) continue;\n                cand[candCnt++] = d;\n            }\n            if (candCnt == 0) break;   // dead end\n\n            int chosenDir = -1;\n\n            if (heuristic == 0) {\n                // value\u2011greedy\n                int bestVal = -1;\n                vector<int> best;\n                for (int i = 0; i < candCnt; ++i) {\n                    int d = cand[i];\n                    int nx = ci + dx[d];\n                    int ny = cj + dy[d];\n                    int v = val[nx][ny];\n                    if (v > bestVal) {\n                        bestVal = v;\n                        best.clear();\n                        best.push_back(d);\n                    } else if (v == bestVal) {\n                        best.push_back(d);\n                    }\n                }\n                chosenDir = best[rng() % best.size()];\n            } else {\n                // degree\u2011aware (prefer larger degree, then larger value)\n                int bestDeg = -1;\n                int bestVal = -1;\n                vector<int> best;\n                for (int i = 0; i < candCnt; ++i) {\n                    int d = cand[i];\n                    int nx = ci + dx[d];\n                    int ny = cj + dy[d];\n                    int neighTile = tile[nx][ny];\n                    // compute degree as if we had already visited neighTile\n                    int deg = 0;\n                    for (int nd = 0; nd < 4; ++nd) {\n                        int nnx = nx + dx[nd];\n                        int nny = ny + dy[nd];\n                        if (nnx < 0 || nnx >= N || nny < 0 || nny >= N) continue;\n                        int t = tile[nnx][nny];\n                        if (t == neighTile) continue;          // same tile \u2192 already visited\n                        if (visited[t] != curRun) deg++;\n                    }\n                    int v = val[nx][ny];\n                    if (deg > bestDeg || (deg == bestDeg && v > bestVal)) {\n                        bestDeg = deg;\n                        bestVal = v;\n                        best.clear();\n                        best.push_back(d);\n                    } else if (deg == bestDeg && v == bestVal) {\n                        best.push_back(d);\n                    }\n                }\n                chosenDir = best[rng() % best.size()];\n            }\n\n            // perform the move\n            ci += dx[chosenDir];\n            cj += dy[chosenDir];\n            curPath.push_back(dirChar[chosenDir]);\n            visited[tile[ci][cj]] = curRun;\n            curScore += val[ci][cj];\n        }\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestPath = curPath;\n        }\n    }\n\n    cout << bestPath << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;                     // grid size\nconstexpr int V = N * N;                 // number of vertices\nconstexpr double INF = 1e100;\nconstexpr double INIT_WEIGHT = 5000.0;    // initial estimate for every edge\nconstexpr double LR = 0.01;              // learning rate\n\ninline int node_id(int i, int j) { return i * N + j; }\ninline pair<int,int> id_to_coord(int id) { return {id / N, id % N}; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    /*  edge weights:\n       horizontal:  i = 0..29, j = 0..28   \u2192 index = i*(N-1)+j   (size N*(N-1))\n       vertical:    i = 0..28, j = 0..29   \u2192 index = i*N + j     (size (N-1)*N)\n    */\n    const int Hcnt = N * (N - 1);\n    const int Vcnt = (N - 1) * N;\n    vector<double> h(Hcnt, INIT_WEIGHT);\n    vector<double> v(Vcnt, INIT_WEIGHT);\n\n    for (int query = 0; query < 1000; ++query) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) return 0;   // EOF safety\n        int s = node_id(si, sj);\n        int t = node_id(ti, tj);\n\n        /* ---------- Dijkstra with current estimates ---------- */\n        vector<double> dist(V, INF);\n        vector<int> parent(V, -1);\n        vector<char> move(V, 0);\n        dist[s] = 0.0;\n        using P = pair<double,int>;\n        priority_queue<P, vector<P>, greater<P>> pq;\n        pq.emplace(0.0, s);\n\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u]) continue;\n            if (u == t) break;\n            auto [i, j] = id_to_coord(u);\n\n            // up\n            if (i > 0) {\n                int nb = node_id(i-1, j);\n                double w = v[(i-1)*N + j];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'U';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // down\n            if (i < N-1) {\n                int nb = node_id(i+1, j);\n                double w = v[i*N + j];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'D';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // left\n            if (j > 0) {\n                int nb = node_id(i, j-1);\n                double w = h[i*(N-1) + (j-1)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'L';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // right\n            if (j < N-1) {\n                int nb = node_id(i, j+1);\n                double w = h[i*(N-1) + j];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'R';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n        }\n\n        /* ---------- reconstruct the path ---------- */\n        vector<char> rev_path;\n        // each entry: (isHorizontal, index)\n        vector<pair<bool,int>> rev_edges;\n        int cur = t;\n        while (cur != s) {\n            int p = parent[cur];\n            char d = move[cur];\n            rev_path.push_back(d);\n            auto [ci, cj] = id_to_coord(cur);\n            auto [pi, pj] = id_to_coord(p);\n            if (ci == pi + 1 && cj == pj) {               // moved down\n                rev_edges.emplace_back(false, pi * N + pj); // vertical edge (top node)\n            } else if (ci == pi - 1 && cj == pj) {        // moved up\n                rev_edges.emplace_back(false, ci * N + cj);\n            } else if (cj == pj + 1 && ci == pi) {        // moved right\n                rev_edges.emplace_back(true, pi * (N-1) + pj);\n            } else if (cj == pj - 1 && ci == pi) {        // moved left\n                rev_edges.emplace_back(true, ci * (N-1) + cj);\n            }\n            cur = p;\n        }\n        reverse(rev_path.begin(), rev_path.end());\n        reverse(rev_edges.begin(), rev_edges.end());\n\n        string out_path;\n        out_path.reserve(rev_path.size());\n        for (char c : rev_path) out_path.push_back(c);\n\n        /* ---------- output and flush ---------- */\n        cout << out_path << '\\n' << flush;\n\n        /* ---------- read noisy length ---------- */\n        long long L;\n        if (!(cin >> L)) return 0;   // safety\n\n        /* ---------- update edge estimates ---------- */\n        double est = 0.0;\n        for (auto &e : rev_edges) {\n            if (e.first)  // horizontal\n                est += h[e.second];\n            else\n                est += v[e.second];\n        }\n        double err = est - static_cast<double>(L);\n        int plen = static_cast<int>(rev_edges.size());\n        if (plen > 0) {\n            double delta = LR * err / plen;\n            for (auto &e : rev_edges) {\n                if (e.first) {\n                    h[e.second] -= delta;\n                    if (h[e.second] < 1.0) h[e.second] = 1.0;\n                } else {\n                    v[e.second] -= delta;\n                    if (v[e.second] < 1.0) v[e.second] = 1.0;\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int MAX_N = 20;\nconstexpr int MAX_LEN = 12;\nconstexpr uint8_t EMPTY = 8;          // value for '.' (unused after fill)\n\nstruct Placement {\n    uint8_t len;                      // length of the string (\u226412)\n    uint16_t cells[MAX_LEN];          // linear cell indices (0 \u2026 399)\n    uint8_t  need[MAX_LEN];           // required character (0 \u2026 7)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<string> S(M);\n    for (int i = 0; i < M; ++i) cin >> S[i];\n\n    // ---------- pre\u2011compute all placements ----------\n    vector<vector<Placement>> placements(M);\n    placements.reserve(M);\n    for (int i = 0; i < M; ++i) {\n        const string &st = S[i];\n        int L = (int)st.size();\n        placements[i].reserve(2 * N * N);\n        // horizontal\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                Placement p;\n                p.len = (uint8_t)L;\n                for (int k = 0; k < L; ++k) {\n                    int col = (c + k) % N;\n                    p.cells[k] = (uint16_t)(r * N + col);\n                    p.need[k] = (uint8_t)(st[k] - 'A');   // 0 \u2026 7\n                }\n                placements[i].push_back(p);\n            }\n        }\n        // vertical\n        for (int c = 0; c < N; ++c) {\n            for (int r = 0; r < N; ++r) {\n                Placement p;\n                p.len = (uint8_t)L;\n                for (int k = 0; k < L; ++k) {\n                    int row = (r + k) % N;\n                    p.cells[k] = (uint16_t)(row * N + c);\n                    p.need[k] = (uint8_t)(st[k] - 'A');\n                }\n                placements[i].push_back(p);\n            }\n        }\n    }\n\n    // ---------- heuristic ----------\n    std::mt19937 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> distChar(0, 7);\n\n    const int ITER = 30;                     // enough for the time limit\n    int bestScore = -1;\n    vector<uint8_t> bestMat(N * N, EMPTY);\n\n    vector<int> length(M);\n    for (int i = 0; i < M; ++i) length[i] = (int)S[i].size();\n\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n\n    for (int it = 0; it < ITER; ++it) {\n        // ----- start with an empty matrix -----\n        vector<uint8_t> mat(N * N, EMPTY);\n\n        // ----- order of processing -----\n        if (it % 2 == 0) {\n            shuffle(order.begin(), order.end(), rng);\n        } else {\n            // length descending, ties keep original order\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     if (length[a] != length[b]) return length[a] > length[b];\n                     return a < b;\n                 });\n        }\n\n        // ----- greedy placement -----\n        for (int idx : order) {\n            const auto &pls = placements[idx];\n            int bestPl = -1;\n            int bestOverlap = -1;\n            for (int pi = 0; pi < (int)pls.size(); ++pi) {\n                const Placement &p = pls[pi];\n                bool conflict = false;\n                int overlap = 0;\n                for (int k = 0; k < p.len; ++k) {\n                    uint8_t cur = mat[p.cells[k]];\n                    uint8_t need = p.need[k];\n                    if (cur != EMPTY && cur != need) {\n                        conflict = true;\n                        break;\n                    }\n                    if (cur == need) ++overlap;\n                }\n                if (!conflict) {\n                    if (overlap > bestOverlap) {\n                        bestOverlap = overlap;\n                        bestPl = pi;\n                        if (overlap == p.len) break;   // perfect match\n                    }\n                }\n            }\n            if (bestPl != -1) {\n                const Placement &p = pls[bestPl];\n                for (int k = 0; k < p.len; ++k) {\n                    uint16_t cell = p.cells[k];\n                    if (mat[cell] == EMPTY) mat[cell] = p.need[k];\n                }\n            }\n        }\n\n        // ----- fill remaining empty cells with random letters -----\n        for (int i = 0; i < N * N; ++i) {\n            if (mat[i] == EMPTY) mat[i] = (uint8_t)distChar(rng);\n        }\n\n        // ----- count satisfied strings -----\n        int satisfied = 0;\n        for (int i = 0; i < M; ++i) {\n            const auto &pls = placements[i];\n            bool okString = false;\n            for (const Placement &p : pls) {\n                bool ok = true;\n                for (int k = 0; k < p.len; ++k) {\n                    if (mat[p.cells[k]] != p.need[k]) {\n                        ok = false;\n                        break;\n                    }\n                }\n                if (ok) {\n                    okString = true;\n                    break;\n                }\n            }\n            if (okString) ++satisfied;\n        }\n\n        if (satisfied > bestScore) {\n            bestScore = satisfied;\n            bestMat = mat;\n        }\n    }\n\n    // ----- output the best matrix -----\n    for (int r = 0; r < N; ++r) {\n        string line;\n        line.reserve(N);\n        for (int c = 0; c < N; ++c) {\n            uint8_t v = bestMat[r * N + c];\n            line.push_back(char('A' + v));   // v is 0 \u2026 7\n        }\n        cout << line << '\\n';\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll INF = (1LL << 60);\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, si, sj;\n    if (!(cin >> N >> si >> sj)) return 0;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n\n    // assign an id to every road cell\n    vector<vector<int>> id(N, vector<int>(N, -1));\n    vector<pair<int,int>> pos;          // id -> (i,j)\n    vector<int> cost;                   // id -> travel cost (5\u20119)\n    int r = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                id[i][j] = r++;\n                pos.emplace_back(i, j);\n                cost.push_back(grid[i][j] - '0');\n            }\n        }\n    }\n    if (r == 0) return 0; // should never happen (start is a road)\n\n    int startId = id[si][sj];\n\n    // adjacency list (directed: moving to neighbour costs neighbour's cost)\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    const char dirChar[4] = {'U','D','L','R'};\n    const char revChar[4] = {'D','U','R','L'};\n    vector<vector<pair<int,int>>> adj(r);\n    for (int v = 0; v < r; ++v) {\n        int i = pos[v].first;\n        int j = pos[v].second;\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d];\n            int nj = j + dy[d];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (grid[ni][nj] == '#') continue;\n            int to = id[ni][nj];\n            adj[v].push_back({to, cost[to]}); // weight = cost of destination\n        }\n    }\n\n    vector<char> visited(r, 0);\n    visited[startId] = 1;\n    int visitedCnt = 1;\n    int cur = startId;\n    string answer;\n\n    // helper: run Dijkstra from src, stop when the first unvisited vertex is popped\n    auto dijkstra_to_nearest = [&](int src, vector<int> &parent, int &target) {\n        vector<ll> dist(r, INF);\n        parent.assign(r, -1);\n        using P = pair<ll,int>;\n        priority_queue<P, vector<P>, greater<P>> pq;\n        dist[src] = 0;\n        pq.emplace(0, src);\n        target = -1;\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d != dist[u]) continue;\n            if (!visited[u] && u != src) { // nearest unvisited reached\n                target = u;\n                break;\n            }\n            for (auto [v, w] : adj[u]) {\n                ll nd = d + w;\n                if (nd < dist[v]) {\n                    dist[v] = nd;\n                    parent[v] = u;\n                    pq.emplace(nd, v);\n                }\n            }\n        }\n    };\n\n    // helper: run full Dijkstra from src to a given destination (used for the final return)\n    auto dijkstra_full = [&](int src, int dst, vector<int> &parent) {\n        vector<ll> dist(r, INF);\n        parent.assign(r, -1);\n        using P = pair<ll,int>;\n        priority_queue<P, vector<P>, greater<P>> pq;\n        dist[src] = 0;\n        pq.emplace(0, src);\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d != dist[u]) continue;\n            if (u == dst) break;\n            for (auto [v, w] : adj[u]) {\n                ll nd = d + w;\n                if (nd < dist[v]) {\n                    dist[v] = nd;\n                    parent[v] = u;\n                    pq.emplace(nd, v);\n                }\n            }\n        }\n    };\n\n    // main loop: always go to the nearest still\u2011unvisited cell\n    while (visitedCnt < r) {\n        vector<int> parent;\n        int target = -1;\n        dijkstra_to_nearest(cur, parent, target);\n        if (target == -1) break; // should not happen (graph is connected)\n\n        // reconstruct path cur \u2192 target\n        vector<int> path;\n        int x = target;\n        while (x != cur) {\n            path.push_back(x);\n            x = parent[x];\n        }\n        path.push_back(cur);\n        reverse(path.begin(), path.end());\n\n        // output moves and mark visited cells\n        for (size_t i = 1; i < path.size(); ++i) {\n            int a = path[i-1];\n            int b = path[i];\n            int di = pos[b].first - pos[a].first;\n            int dj = pos[b].second - pos[a].second;\n            char c;\n            if (di == -1) c = 'U';\n            else if (di == 1) c = 'D';\n            else if (dj == -1) c = 'L';\n            else if (dj == 1) c = 'R';\n            else continue; // should never happen\n            answer.push_back(c);\n            if (!visited[b]) {\n                visited[b] = 1;\n                ++visitedCnt;\n            }\n        }\n        cur = target;\n    }\n\n    // finally return to the start cell\n    if (cur != startId) {\n        vector<int> parent;\n        dijkstra_full(cur, startId, parent);\n        // reconstruct path cur \u2192 startId\n        vector<int> path;\n        int x = startId;\n        while (x != cur) {\n            path.push_back(x);\n            x = parent[x];\n        }\n        path.push_back(cur);\n        reverse(path.begin(), path.end());\n        for (size_t i = 1; i < path.size(); ++i) {\n            int a = path[i-1];\n            int b = path[i];\n            int di = pos[b].first - pos[a].first;\n            int dj = pos[b].second - pos[a].second;\n            char c;\n            if (di == -1) c = 'U';\n            else if (di == 1) c = 'D';\n            else if (dj == -1) c = 'L';\n            else if (dj == 1) c = 'R';\n            else continue;\n            answer.push_back(c);\n        }\n    }\n\n    cout << answer << '\\n';\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- data structures ---------- */\n\nstruct ReadyTask {\n    int id;          // task index (0\u2011based)\n    int dp;          // longest path length starting from the task\n    long long sum;   // \u03a3 d_i,k\n    // priority: larger dp first, then larger sum\n    bool operator<(const ReadyTask& other) const {\n        if (dp != other.dp) return dp < other.dp;\n        return sum < other.sum;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    if (!(cin >> N >> M >> K >> R)) return 0;\n\n    /* ----- read required skill vectors ----- */\n    vector<vector<int>> d(N, vector<int>(K));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < K; ++j)\n            cin >> d[i][j];\n\n    /* ----- compute sum of required skills for each task ----- */\n    vector<long long> sum_d(N, 0);\n    for (int i = 0; i < N; ++i) {\n        long long s = 0;\n        for (int j = 0; j < K; ++j) s += d[i][j];\n        sum_d[i] = s;\n    }\n\n    /* ----- read dependencies ----- */\n    vector<vector<int>> adj(N);\n    vector<int> indeg(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        adj[u].push_back(v);\n        ++indeg[v];\n    }\n\n    /* ----- longest path length (critical\u2011path priority) ----- */\n    vector<int> dp(N, 1);\n    for (int i = N - 1; i >= 0; --i) {\n        for (int v : adj[i]) {\n            dp[i] = max(dp[i], dp[v] + 1);\n        }\n    }\n\n    /* ----- initial ready queue ----- */\n    priority_queue<ReadyTask> readyPQ;\n    for (int i = 0; i < N; ++i) {\n        if (indeg[i] == 0) {\n            readyPQ.push({i, dp[i], sum_d[i]});\n        }\n    }\n\n    /* ----- state of members and tasks ----- */\n    vector<int> member_task(M, -1);          // task currently executed, -1 = idle\n    vector<int> task_start_day(N, -1);       // day when the task started\n    vector<char> task_started(N, 0);\n    vector<char> task_completed(N, 0);\n\n    /* ----- statistics for skill estimation ----- */\n    vector<long long> sum_d_done(M, 0);\n    vector<long long> sum_t_done(M, 0);\n    vector<int> cnt_done(M, 0);\n    vector<double> skill_est(M, 0.0);        // estimate of \u03a3 s_j\n\n    int day = 0;\n    while (true) {\n        ++day;\n\n        /* ----- collect idle members ----- */\n        vector<int> idle;\n        for (int j = 0; j < M; ++j)\n            if (member_task[j] == -1) idle.push_back(j);\n\n        /* ----- order idle members by estimated skill (strongest first) ----- */\n        sort(idle.begin(), idle.end(),\n             [&](int a, int b) { return skill_est[a] > skill_est[b]; });\n\n        /* ----- assign tasks ----- */\n        vector<pair<int,int>> assign;   // (member, task) in 1\u2011based form\n        for (int idx = 0; idx < (int)idle.size() && !readyPQ.empty(); ++idx) {\n            int member = idle[idx];\n            ReadyTask rt = readyPQ.top(); readyPQ.pop();\n            int task = rt.id;\n\n            assign.emplace_back(member + 1, task + 1);\n            member_task[member] = task;\n            task_started[task] = 1;\n            task_start_day[task] = day;\n        }\n\n        /* ----- output ----- */\n        cout << assign.size();\n        for (auto &p : assign) cout << ' ' << p.first << ' ' << p.second;\n        cout << \"\\n\" << flush;\n\n        /* ----- read judge response ----- */\n        int n;\n        if (!(cin >> n)) return 0;          // EOF (should not happen)\n        if (n == -1) break;                 // all tasks done or day limit\n        vector<int> finished;\n        finished.reserve(n);\n        for (int i = 0; i < n; ++i) {\n            int f; cin >> f;\n            finished.push_back(f);\n        }\n\n        /* ----- process completions ----- */\n        for (int f : finished) {\n            int member = f - 1;\n            int task = member_task[member];\n            if (task == -1) continue;       // safety, should not happen\n\n            // real duration of the task\n            int duration = day - task_start_day[task] + 1;\n\n            // update skill estimate of the member\n            ++cnt_done[member];\n            sum_d_done[member] += sum_d[task];\n            sum_t_done[member] += duration;\n            double raw = (double)sum_d_done[member] - (double)sum_t_done[member];\n            if (raw < 0) raw = 0;\n            skill_est[member] = raw / cnt_done[member];\n\n            // free the member\n            member_task[member] = -1;\n\n            // mark task as completed\n            task_started[task] = 0;\n            task_completed[task] = 1;\n\n            // make successors ready\n            for (int v : adj[task]) {\n                --indeg[v];\n                if (indeg[v] == 0) {\n                    readyPQ.push({v, dp[v], sum_d[v]});\n                }\n            }\n        }\n    }\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Order {\n    int a, b, c, d;   // pickup (a,b), delivery (c,d)\n    int idx;          // 1\u2011based index in the original list\n    long long cost;  // heuristic cost for selection\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 1000;\n    const int M = 50;\n    const int OFF_X = 400, OFF_Y = 400;\n\n    vector<Order> orders(N);\n    for (int i = 0; i < N; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        long long cost = 0;\n        cost += manhattan(OFF_X, OFF_Y, a, b); // office -> pickup\n        cost += manhattan(a, b, c, d);         // pickup -> delivery\n        cost += manhattan(c, d, OFF_X, OFF_Y); // delivery -> office\n        orders[i] = {a, b, c, d, i + 1, cost};\n    }\n\n    // -----------------------------------------------------------------\n    // 1) select 50 orders with smallest heuristic cost\n    sort(orders.begin(), orders.end(),\n         [](const Order& x, const Order& y) { return x.cost < y.cost; });\n    vector<Order> sel(orders.begin(), orders.begin() + M);\n\n    // -----------------------------------------------------------------\n    // 2) greedy feasible\u2011node walk\n    // status: 0 = not started, 1 = pickup done, 2 = delivered\n    vector<int> status(M, 0);\n    vector<int> chosenIdx;          // order indices in the order we first visit pickup\n    vector<pair<int,int>> route;    // visited points\n\n    int curX = OFF_X, curY = OFF_Y;\n    route.emplace_back(curX, curY);   // start at office\n\n    int remaining = M;   // number of orders not yet delivered\n    while (remaining > 0) {\n        int bestDist = INT_MAX;\n        int bestIdx = -1;\n        bool bestIsPickup = true;   // true -> pickup, false -> delivery\n\n        for (int i = 0; i < M; ++i) {\n            if (status[i] == 0) { // pickup not visited yet\n                int d = manhattan(curX, curY, sel[i].a, sel[i].b);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx = i;\n                    bestIsPickup = true;\n                }\n            } else if (status[i] == 1) { // pickup done, delivery pending\n                int d = manhattan(curX, curY, sel[i].c, sel[i].d);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx = i;\n                    bestIsPickup = false;\n                }\n            }\n        }\n\n        // we must have found a candidate\n        if (bestIsPickup) {\n            // go to pickup\n            curX = sel[bestIdx].a;\n            curY = sel[bestIdx].b;\n            route.emplace_back(curX, curY);\n            status[bestIdx] = 1;\n            chosenIdx.push_back(sel[bestIdx].idx);\n        } else {\n            // go to delivery\n            curX = sel[bestIdx].c;\n            curY = sel[bestIdx].d;\n            route.emplace_back(curX, curY);\n            status[bestIdx] = 2;\n            --remaining;\n        }\n    }\n\n    // return to office\n    route.emplace_back(OFF_X, OFF_Y);\n\n    // -----------------------------------------------------------------\n    // 3) output\n    cout << M;\n    for (int id : chosenIdx) cout << ' ' << id;\n    cout << '\\n';\n\n    cout << route.size();\n    for (auto [x, y] : route) cout << ' ' << x << ' ' << y;\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        sz.assign(n, 1);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\n/*** Edge description ***/\nstruct Edge {\n    int u, v;\n    int d;          // rounded Euclidean distance\n    int idx;        // original index in input order\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        long long dx = (long long)x[u] - x[v];\n        long long dy = (long long)y[u] - y[v];\n        double dist = sqrt((double)dx * dx + (double)dy * dy);\n        int d = (int)lround(dist);          // round to nearest integer\n        edges[i] = {u, v, d, i};\n    }\n\n    /* ---------- build geometric MST (weight = d_i) ---------- */\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a, int b) {\n             if (edges[a].d != edges[b].d) return edges[a].d < edges[b].d;\n             return a < b;\n         });\n\n    DSU dsu_mst(N);\n    vector<char> inMST(M, 0);\n    int taken = 0;\n    for (int id : order) {\n        const Edge &e = edges[id];\n        if (dsu_mst.unite(e.u, e.v)) {\n            inMST[id] = 1;\n            ++taken;\n            if (taken == N - 1) break;\n        }\n    }\n\n    /* ---------- online phase ---------- */\n    DSU dsu(N);\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;                     // true length of edge i\n        bool accept = false;\n        if (inMST[i] && dsu.find(edges[i].u) != dsu.find(edges[i].v)) {\n            accept = true;\n            dsu.unite(edges[i].u, edges[i].v);\n        }\n        cout << (accept ? 1 : 0) << '\\n' << flush;\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pet {\n    int x, y, type;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    if (!(cin >> N)) return 0;          // no input\n    vector<Pet> pets(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n    }\n    int M;\n    cin >> M;\n    vector<pair<int,int>> humans(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].first >> humans[i].second;\n    }\n\n    // board: 1..30 are usable cells, outside is impassable\n    const int H = 30;\n    bool wall[31][31] = {};   // false = passable, true = impassable\n\n    // direction data\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    const char wallChar[4] = {'u','d','l','r'};\n    const char moveChar[4] = {'U','D','L','R'};\n\n    // auxiliary arrays for fast occupancy queries\n    bool petOcc[31][31];\n    bool humanOcc[31][31];\n\n    auto inside = [&](int x, int y)->bool{\n        return 1 <= x && x <= H && 1 <= y && y <= H;\n    };\n\n    for (int turn = 0; turn < 300; ++turn) {\n        // build occupancy maps for this turn (before any actions)\n        memset(petOcc, 0, sizeof(petOcc));\n        for (const auto &p : pets) petOcc[p.x][p.y] = true;\n\n        memset(humanOcc, 0, sizeof(humanOcc));\n        for (const auto &h : humans) humanOcc[h.first][h.second] = true;\n\n        // decide actions\n        string actions(M, '.');\n        set<pair<int,int>> wallTargets;   // squares that will become walls this turn\n\n        for (int i = 0; i < M; ++i) {\n            int hx = humans[i].first;\n            int hy = humans[i].second;\n\n            bool done = false;\n\n            // 1) try to build a wall\n            for (int d = 0; d < 4; ++d) {\n                int tx = hx + dx[d];\n                int ty = hy + dy[d];\n                if (!inside(tx,ty)) continue;               // outer border already impassable\n                if (wall[tx][ty]) continue;                  // already a wall\n                if (humanOcc[tx][ty]) continue;              // occupied by a human\n                if (petOcc[tx][ty]) continue;                // occupied by a pet\n\n                // check adjacency of target square to any pet\n                bool adjPet = false;\n                for (int nd = 0; nd < 4; ++nd) {\n                    int nx = tx + dx[nd];\n                    int ny = ty + dy[nd];\n                    if (!inside(nx,ny)) continue;\n                    if (petOcc[nx][ny]) { adjPet = true; break; }\n                }\n                if (adjPet) continue;\n\n                // safe to build wall here\n                actions[i] = wallChar[d];\n                wallTargets.emplace(tx,ty);\n                done = true;\n                break;\n            }\n            if (done) continue;\n\n            // 2) try to move away from pets (if any pet is adjacent or on the same cell)\n            bool petNearby = false;\n            // check same cell\n            if (petOcc[hx][hy]) petNearby = true;\n            // check orthogonal neighbours\n            for (int d = 0; d < 4 && !petNearby; ++d) {\n                int nx = hx + dx[d];\n                int ny = hy + dy[d];\n                if (!inside(nx,ny)) continue;\n                if (petOcc[nx][ny]) petNearby = true;\n            }\n\n            if (petNearby) {\n                for (int d = 0; d < 4; ++d) {\n                    int nx = hx + dx[d];\n                    int ny = hy + dy[d];\n                    if (!inside(nx,ny)) continue;\n                    if (wall[nx][ny]) continue;               // cannot move into a wall\n                    if (petOcc[nx][ny]) continue;             // avoid stepping onto a pet\n                    if (wallTargets.count({nx,ny})) continue; // another human builds a wall here\n\n                    // after moving, must have no adjacent pet\n                    bool adjPet = false;\n                    for (int nd = 0; nd < 4; ++nd) {\n                        int ax = nx + dx[nd];\n                        int ay = ny + dy[nd];\n                        if (!inside(ax,ay)) continue;\n                        if (petOcc[ax][ay]) { adjPet = true; break; }\n                    }\n                    if (adjPet) continue;\n\n                    // safe move\n                    actions[i] = moveChar[d];\n                    done = true;\n                    break;\n                }\n            }\n            // if not done, stay still ('.')\n        }\n\n        // output actions and flush\n        cout << actions << '\\n' << flush;\n\n        // read pet move strings\n        vector<string> petMoves(N);\n        for (int i = 0; i < N; ++i) {\n            cin >> petMoves[i];\n        }\n\n        // ----- apply human actions (walls first, then moves) -----\n        // walls\n        for (int i = 0; i < M; ++i) {\n            char c = actions[i];\n            if (c >= 'a' && c <= 'z') {            // wall building\n                int d = (c=='u'?0:(c=='d'?1:(c=='l'?2:3)));\n                int tx = humans[i].first + dx[d];\n                int ty = humans[i].second + dy[d];\n                if (inside(tx,ty)) wall[tx][ty] = true;\n            }\n        }\n        // moves\n        for (int i = 0; i < M; ++i) {\n            char c = actions[i];\n            if (c >= 'A' && c <= 'Z') {            // movement\n                int d = (c=='U'?0:(c=='D'?1:(c=='L'?2:3)));\n                int nx = humans[i].first + dx[d];\n                int ny = humans[i].second + dy[d];\n                if (inside(nx,ny) && !wall[nx][ny]) {\n                    humans[i].first = nx;\n                    humans[i].second = ny;\n                }\n            }\n        }\n\n        // ----- apply pet moves -----\n        for (int i = 0; i < N; ++i) {\n            const string &s = petMoves[i];\n            for (char c : s) {\n                if (c == '.') continue;\n                if (c == 'U') pets[i].x--;\n                else if (c == 'D') pets[i].x++;\n                else if (c == 'L') pets[i].y--;\n                else if (c == 'R') pets[i].y++;\n                // the judge guarantees the move is legal (inside board and not a wall)\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct PrevInfo {\n    int pi = -1, pj = -1;   // predecessor cell\n    char dir = 0;           // direction used to come from predecessor to this cell\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj, ti, tj;\n    double p;               // not needed for the construction\n    if (!(cin >> si >> sj >> ti >> tj >> p)) return 0;\n\n    // horizontal walls: 20 rows, each 19 chars\n    vector<string> h(20);\n    for (int i = 0; i < 20; ++i) cin >> h[i];\n    // vertical walls: 19 rows, each 20 chars\n    vector<string> v(19);\n    for (int i = 0; i < 19; ++i) cin >> v[i];\n\n    const int N = 20;\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char dch[4] = {'U', 'D', 'L', 'R'};\n\n    // BFS\n    queue<pair<int,int>> q;\n    bool visited[N][N] = {};\n    PrevInfo prevInfo[N][N];\n    q.emplace(si, sj);\n    visited[si][sj] = true;\n\n    auto can_move = [&](int i, int j, int dir)->bool{\n        if (dir == 0) { // U\n            if (i == 0) return false;\n            return v[i-1][j] == '0';\n        } else if (dir == 1) { // D\n            if (i == N-1) return false;\n            return v[i][j] == '0';\n        } else if (dir == 2) { // L\n            if (j == 0) return false;\n            return h[i][j-1] == '0';\n        } else { // R\n            if (j == N-1) return false;\n            return h[i][j] == '0';\n        }\n    };\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        if (i == ti && j == tj) break; // target reached\n        for (int d = 0; d < 4; ++d) {\n            if (!can_move(i, j, d)) continue;\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            if (!visited[ni][nj]) {\n                visited[ni][nj] = true;\n                prevInfo[ni][nj] = {i, j, dch[d]};\n                q.emplace(ni, nj);\n            }\n        }\n    }\n\n    // reconstruct one shortest path\n    string base;\n    int ci = ti, cj = tj;\n    while (!(ci == si && cj == sj)) {\n        const PrevInfo &pr = prevInfo[ci][cj];\n        if (pr.pi == -1) break; // should not happen (graph is connected)\n        base.push_back(pr.dir);\n        ci = pr.pi;\n        cj = pr.pj;\n    }\n    reverse(base.begin(), base.end());\n\n    // repeat the path to fill up to 200 characters\n    const int MAXLEN = 200;\n    string answer;\n    while ((int)answer.size() + (int)base.size() <= MAXLEN) {\n        answer += base;\n    }\n    if ((int)answer.size() < MAXLEN) {\n        int need = MAXLEN - (int)answer.size();\n        answer += base.substr(0, need);\n    }\n\n    // safety: if for some reason base is empty (should never happen) output a single stay move.\n    if (answer.empty()) answer = \"U\";\n\n    cout << answer << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;\nconstexpr int DIR = 4;\nconstexpr int TOTAL = N * N * DIR;          // 30*30*4 = 3600\nconstexpr int di[DIR] = {0, -1, 0, 1};       // left, up, right, down\nconstexpr int dj[DIR] = {-1, 0, 1, 0};\n\nint tile[N][N];                              // original tile types\n\n// base connection table from the statement\nconst int base_to[8][4] = {\n    { 1, 0,-1,-1},\n    { 3,-1,-1, 0},\n    {-1,-1, 3, 2},\n    {-1, 2, 1,-1},\n    { 1, 0, 3, 2},\n    { 3, 2, 1, 0},\n    { 2,-1, 0,-1},\n    {-1, 3,-1, 1}\n};\n\nint to_rot[8][4][4];                         // after rotation\n\ninline int idx(int i, int j, int d) { return ((i * N + j) * DIR + d); }\n\n// ------------------------------------------------------------\n// fast Xorshift64 PRNG\nstruct XorShift {\n    uint64_t x;\n    XorShift() { x = chrono::steady_clock::now().time_since_epoch().count(); }\n    uint32_t next() {\n        x ^= x << 13;\n        x ^= x >> 7;\n        x ^= x << 17;\n        return static_cast<uint32_t>(x);\n    }\n    uint32_t next(uint32_t n) { return next() % n; }\n    double nextDouble() { return (next() >> 11) * (1.0 / 9007199254740992.0); }\n};\n// ------------------------------------------------------------\n\n// ------------------------------------------------------------\n// compute the score (L1 * L2) for a given rotation vector (size 900)\nint computeScore(const vector<int>& rot) {\n    static int nxt[TOTAL];\n    fill(nxt, nxt + TOTAL, -1);\n\n    // build outgoing edges\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int t = tile[i][j];\n            int r = rot[i * N + j];\n            for (int d = 0; d < DIR; ++d) {\n                int d2 = to_rot[t][r][d];\n                if (d2 == -1) continue;\n                int ni = i + di[d2];\n                int nj = j + dj[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) & 3;\n                nxt[idx(i, j, d)] = idx(ni, nj, nd);\n            }\n        }\n    }\n\n    static uint8_t state[TOTAL];   // 0 = unvisited, 1 = in current walk, 2 = finished\n    static int pos[TOTAL];\n    fill(state, state + TOTAL, 0);\n    fill(pos, pos + TOTAL, -1);\n\n    int best1 = 0, best2 = 0;\n    vector<int> path;\n    path.reserve(TOTAL);\n\n    for (int v = 0; v < TOTAL; ++v) {\n        if (state[v]) continue;\n        int cur = v;\n        while (true) {\n            if (cur == -1) break;\n            if (state[cur] == 0) {\n                state[cur] = 1;\n                pos[cur] = static_cast<int>(path.size());\n                path.push_back(cur);\n                cur = nxt[cur];\n            } else if (state[cur] == 1) {\n                int len = static_cast<int>(path.size()) - pos[cur];\n                if (len > best1) { best2 = best1; best1 = len; }\n                else if (len > best2) { best2 = len; }\n                break;\n            } else { // state[cur] == 2\n                break;\n            }\n        }\n        for (int node : path) {\n            state[node] = 2;\n            pos[node] = -1;\n        }\n        path.clear();\n    }\n    if (best2 == 0) return 0;\n    return best1 * best2;\n}\n// ------------------------------------------------------------\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read input\n    for (int i = 0; i < N; ++i) {\n        string line; cin >> line;\n        for (int j = 0; j < N; ++j) tile[i][j] = line[j] - '0';\n    }\n\n    // pre\u2011compute to_rot\n    for (int t = 0; t < 8; ++t) {\n        for (int r = 0; r < 4; ++r) {\n            for (int d = 0; d < 4; ++d) {\n                int local = (d - r + 4) & 3;\n                int out = base_to[t][local];\n                if (out == -1) to_rot[t][r][d] = -1;\n                else to_rot[t][r][d] = (out + r) & 3;\n            }\n        }\n    }\n\n    XorShift rng;\n    vector<int> cur(900), best(900);\n    for (int i = 0; i < 900; ++i) cur[i] = rng.next(4);\n    int curScore = computeScore(cur);\n    best = cur;\n    int bestScore = curScore;\n\n    const double TIME_LIMIT = 1.9;          // seconds\n    const double T0 = 50000.0;              // initial temperature\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        int idx = rng.next(900);\n        int oldR = cur[idx];\n        int newR = rng.next(4);\n        if (newR == oldR) continue;\n        cur[idx] = newR;\n        int newScore = computeScore(cur);\n        int delta = newScore - curScore;\n\n        bool accept = false;\n        if (delta >= 0) accept = true;\n        else {\n            double T = T0 * (1.0 - elapsed / TIME_LIMIT);\n            if (T < 1e-9) T = 1e-9;\n            double prob = exp(delta / T);\n            if (rng.nextDouble() < prob) accept = true;\n        }\n\n        if (accept) {\n            curScore = newScore;\n            if (newScore > bestScore) {\n                bestScore = newScore;\n                best = cur;\n            }\n        } else {\n            cur[idx] = oldR; // revert\n        }\n    }\n\n    // output best solution\n    string out;\n    out.reserve(900);\n    for (int i = 0; i < 900; ++i) out.push_back(char('0' + best[i]));\n    cout << out << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint hexCharToInt(char c) {\n    if ('0' <= c && c <= '9') return c - '0';\n    return 10 + (c - 'a');\n}\n\n/* Compute the size of the largest tree component.\n   A component is a tree iff #edges == #vertices - 1.\n   Edges are counted only once (right and down directions). */\nint largestTreeSize(const vector<vector<int>>& board) {\n    int N = board.size();\n    vector<vector<char>> vis(N, vector<char>(N, 0));\n    int best = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0 || vis[i][j]) continue;\n            int verts = 0, edges = 0;\n            queue<pair<int,int>> q;\n            q.emplace(i, j);\n            vis[i][j] = 1;\n            while (!q.empty()) {\n                auto [x, y] = q.front(); q.pop();\n                ++verts;\n                int mask = board[x][y];\n                // right\n                if ((mask & 4) && y + 1 < N && board[x][y+1] != 0 && (board[x][y+1] & 1)) {\n                    ++edges;\n                    if (!vis[x][y+1]) { vis[x][y+1] = 1; q.emplace(x, y+1); }\n                }\n                // down\n                if ((mask & 8) && x + 1 < N && board[x+1][y] != 0 && (board[x+1][y] & 2)) {\n                    ++edges;\n                    if (!vis[x+1][y]) { vis[x+1][y] = 1; q.emplace(x+1, y); }\n                }\n                // left (only for connectivity)\n                if ((mask & 1) && y - 1 >= 0 && board[x][y-1] != 0 && (board[x][y-1] & 4)) {\n                    if (!vis[x][y-1]) { vis[x][y-1] = 1; q.emplace(x, y-1); }\n                }\n                // up\n                if ((mask & 2) && x - 1 >= 0 && board[x-1][y] != 0 && (board[x-1][y] & 8)) {\n                    if (!vis[x-1][y]) { vis[x-1][y] = 1; q.emplace(x-1, y); }\n                }\n            }\n            if (edges == verts - 1) best = max(best, verts);\n        }\n    }\n    return best;\n}\n\n/* Apply a move (direction idx) to board and update empty position. */\nvoid applyMove(vector<vector<int>>& board, int& ex, int& ey, int idx,\n               const int dx[4], const int dy[4]) {\n    int nx = ex + dx[idx];\n    int ny = ey + dy[idx];\n    swap(board[ex][ey], board[nx][ny]); // board[ex][ey] becomes the tile, empty moves to (nx,ny)\n    ex = nx; ey = ny;\n}\n\n/* Undo a move \u2013 just apply the opposite direction. */\nvoid undoMove(vector<vector<int>>& board, int& ex, int& ey, int idx,\n              const int dx[4], const int dy[4]) {\n    // opposite direction index: 0<->1, 2<->3\n    int opp = idx ^ 1; // 0<->1, 2<->3\n    applyMove(board, ex, ey, opp, dx, dy);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    long long T;\n    if (!(cin >> N >> T)) return 0;\n    vector<vector<int>> board(N, vector<int>(N));\n    int ex = -1, ey = -1; // empty cell\n    for (int i = 0; i < N; ++i) {\n        string s; cin >> s;\n        for (int j = 0; j < N; ++j) {\n            board[i][j] = hexCharToInt(s[j]);\n            if (board[i][j] == 0) { ex = i; ey = j; }\n        }\n    }\n\n    const char dirChar[4] = {'U','D','L','R'};\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    int totalTiles = N * N - 1;\n    int curS = largestTreeSize(board);\n    int bestS = curS;\n    string bestMoves;          // sequence that achieved bestS\n    string curMoves;           // moves taken so far\n\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n\n    for (long long step = 0; step < T; ++step) {\n        // enumerate possible moves\n        vector<int> cand;\n        for (int d = 0; d < 4; ++d) {\n            int nx = ex + dx[d];\n            int ny = ey + dy[d];\n            if (0 <= nx && nx < N && 0 <= ny && ny < N) cand.push_back(d);\n        }\n        if (cand.empty()) break; // should never happen\n\n        int bestIdx = -1;\n        int bestNextS = -1;\n        // try each candidate move\n        for (int d : cand) {\n            // simulate\n            applyMove(board, ex, ey, d, dx, dy);\n            int ns = largestTreeSize(board);\n            // revert\n            undoMove(board, ex, ey, d, dx, dy);\n            if (ns > bestNextS) {\n                bestNextS = ns;\n                bestIdx = d;\n            }\n        }\n\n        if (bestIdx == -1) break; // no move (should not happen)\n\n        // if the best move does not decrease S, accept it\n        if (bestNextS >= curS) {\n            applyMove(board, ex, ey, bestIdx, dx, dy);\n            curS = bestNextS;\n            curMoves.push_back(dirChar[bestIdx]);\n\n            if (curS > bestS) {\n                bestS = curS;\n                bestMoves = curMoves;\n                if (bestS == totalTiles) break; // full tree reached\n            }\n        } else {\n            // no non\u2011decreasing move exists \u2192 stop\n            break;\n        }\n    }\n\n    // output the best sequence found (may be empty)\n    cout << bestMoves << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, K;\n    if (!(cin >> N >> K)) return 0;\n    vector<int> a(11);\n    for (int d = 1; d <= 10; ++d) cin >> a[d];\n    vector<pair<ll,ll>> strawberries(N);\n    for (int i = 0; i < N; ++i) {\n        ll x, y;\n        cin >> x >> y;\n        strawberries[i] = {x, y};\n    }\n\n    const ll R = 10000;          // cake radius\n    const ll M = 20000;          // far outside the cake, still within limits\n    const int MAX_ATTEMPTS = 800;   // enough for a good solution\n\n    std::mt19937_64 rng(\n        std::chrono::steady_clock::now().time_since_epoch().count());\n\n    int bestScore = -1;\n    int bestV = 0, bestH = 0;\n    int bestOffsetX = 0, bestOffsetY = 0;\n    int bestStepV = 0, bestStepH = 0;\n\n    // Helper lambda: evaluate a concrete grid\n    auto evaluate = [&](int V, int H, int offsetX, int offsetY) {\n        if (V < 0 || H < 0 || V + H > K) return -1;\n        int stepV = (V == 0) ? 0 : (int)((2 * R) / (V + 1));\n        int stepH = (H == 0) ? 0 : (int)((2 * R) / (H + 1));\n        vector<int> xs, ys;\n        xs.reserve(V);\n        ys.reserve(H);\n        for (int i = 1; i <= V; ++i) {\n            ll x = -R + offsetX + (ll)i * stepV;\n            xs.push_back((int)x);\n        }\n        for (int j = 1; j <= H; ++j) {\n            ll y = -R + offsetY + (ll)j * stepH;\n            ys.push_back((int)y);\n        }\n\n        // counts[i][j] : i = #vertical lines left of point, j = #horizontal lines below point\n        vector<vector<int>> cnt(V + 1, vector<int>(H + 1, 0));\n\n        for (auto [x, y] : strawberries) {\n            bool onLine = false;\n            int ix = 0, iy = 0;\n            if (V > 0) {\n                ix = lower_bound(xs.begin(), xs.end(), (int)x) - xs.begin();\n                if (ix < V && xs[ix] == (int)x) { onLine = true; }\n            }\n            if (H > 0) {\n                iy = lower_bound(ys.begin(), ys.end(), (int)y) - ys.begin();\n                if (iy < H && ys[iy] == (int)y) { onLine = true; }\n            }\n            if (onLine) continue;               // strawberry cut away\n            cnt[ix][iy]++;                       // belongs to cell (ix,iy)\n        }\n\n        int b[11] = {0};\n        for (int i = 0; i <= V; ++i) {\n            for (int j = 0; j <= H; ++j) {\n                int c = cnt[i][j];\n                if (1 <= c && c <= 10) b[c]++;\n            }\n        }\n        int score = 0;\n        for (int d = 1; d <= 10; ++d) score += min(a[d], b[d]);\n        return score;\n    };\n\n    // Random search over many grid parameters\n    for (int it = 0; it < MAX_ATTEMPTS; ++it) {\n        // choose V randomly, H = K - V (any distribution works)\n        uniform_int_distribution<int> distV(0, K);\n        int V = distV(rng);\n        int H = K - V;\n\n        int stepV = (V == 0) ? 0 : (int)((2 * R) / (V + 1));\n        int stepH = (H == 0) ? 0 : (int)((2 * R) / (H + 1));\n\n        int offsetX = 0, offsetY = 0;\n        if (V > 0) {\n            uniform_int_distribution<int> distOffX(0, stepV - 1);\n            offsetX = distOffX(rng);\n        }\n        if (H > 0) {\n            uniform_int_distribution<int> distOffY(0, stepH - 1);\n            offsetY = distOffY(rng);\n        }\n\n        int sc = evaluate(V, H, offsetX, offsetY);\n        if (sc > bestScore) {\n            bestScore = sc;\n            bestV = V; bestH = H;\n            bestOffsetX = offsetX; bestOffsetY = offsetY;\n            bestStepV = stepV; bestStepH = stepH;\n        }\n    }\n\n    // In the unlikely case that no grid was accepted (should never happen),\n    // fall back to a tiny deterministic grid.\n    if (bestScore < 0) {\n        bestV = bestH = 10;\n        bestStepV = bestStepH = (int)((2 * R) / (bestV + 1));\n        bestOffsetX = bestOffsetY = 0;\n    }\n\n    // Build the final list of lines\n    vector<array<ll,4>> answer;   // (px,py,qx,qy)\n\n    // vertical lines\n    for (int i = 1; i <= bestV; ++i) {\n        ll X = -R + bestOffsetX + (ll)i * bestStepV;\n        answer.push_back({X, -M, X, M});\n    }\n    // horizontal lines\n    for (int j = 1; j <= bestH; ++j) {\n        ll Y = -R + bestOffsetY + (ll)j * bestStepH;\n        answer.push_back({-M, Y, M, Y});\n    }\n\n    cout << answer.size() << \"\\n\";\n    for (auto &ln : answer) {\n        cout << ln[0] << ' ' << ln[1] << ' ' << ln[2] << ' ' << ln[3] << \"\\n\";\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int x1, y1, x2, y2, x3, y3, x4, y4;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<vector<char>> dot(N, vector<char>(N, 0));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        dot[x][y] = 1;\n    }\n\n    // usedEdge[x][y][dir] : 0=right,1=up,2=left,3=down\n    vector<vector<array<char,4>>> used(N, vector<array<char,4>>(N));\n    for (int x = 0; x < N; ++x)\n        for (int y = 0; y < N; ++y)\n            used[x][y].fill(0);\n\n    // cells sorted by weight descending\n    struct Cell {int x, y; long long w;};\n    vector<Cell> cells;\n    cells.reserve(N * N);\n    long long c = (N - 1) / 2;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y < N; ++y) {\n            long long w = (x - c) * (x - c) + (y - c) * (y - c) + 1;\n            cells.push_back({x, y, w});\n        }\n    }\n    sort(cells.begin(), cells.end(),\n         [](const Cell& a, const Cell& b){ return a.w > b.w; });\n\n    vector<Op> ops;\n\n    auto markEdge = [&](int x, int y, int dir) {\n        used[x][y][dir] = 1;\n        int nx = x + (dir == 0) - (dir == 2);\n        int ny = y + (dir == 1) - (dir == 3);\n        int opp = (dir + 2) & 3;\n        used[nx][ny][opp] = 1;\n    };\n\n    bool anyAdded = true;\n    while (anyAdded) {\n        anyAdded = false;\n        for (const auto& cell : cells) {\n            int x = cell.x, y = cell.y;\n            if (dot[x][y]) continue;          // already occupied\n\n            // ---- orientation 0 : missing bottom\u2011left ----\n            if (x + 1 < N && y + 1 < N) {\n                if (dot[x+1][y] && dot[x+1][y+1] && dot[x][y+1]) {\n                    if (!used[x][y][0] && !used[x+1][y][1] &&\n                        !used[x+1][y+1][2] && !used[x][y+1][3]) {\n                        ops.push_back({x, y, x+1, y, x+1, y+1, x, y+1});\n                        dot[x][y] = 1;\n                        markEdge(x, y, 0);\n                        markEdge(x+1, y, 1);\n                        markEdge(x+1, y+1, 2);\n                        markEdge(x, y+1, 3);\n                        anyAdded = true;\n                        continue;\n                    }\n                }\n            }\n\n            // ---- orientation 1 : missing bottom\u2011right ----\n            if (x - 1 >= 0 && y + 1 < N) {\n                if (dot[x-1][y] && dot[x-1][y+1] && dot[x][y+1]) {\n                    if (!used[x][y][2] && !used[x-1][y][1] &&\n                        !used[x-1][y+1][0] && !used[x][y+1][3]) {\n                        ops.push_back({x, y, x-1, y, x-1, y+1, x, y+1});\n                        dot[x][y] = 1;\n                        markEdge(x, y, 2);\n                        markEdge(x-1, y, 1);\n                        markEdge(x-1, y+1, 0);\n                        markEdge(x, y+1, 3);\n                        anyAdded = true;\n                        continue;\n                    }\n                }\n            }\n\n            // ---- orientation 2 : missing top\u2011left ----\n            if (y - 1 >= 0 && x + 1 < N) {\n                if (dot[x][y-1] && dot[x+1][y-1] && dot[x+1][y]) {\n                    if (!used[x][y][3] && !used[x][y-1][0] &&\n                        !used[x+1][y-1][1] && !used[x+1][y][2]) {\n                        ops.push_back({x, y, x, y-1, x+1, y-1, x+1, y});\n                        dot[x][y] = 1;\n                        markEdge(x, y, 3);\n                        markEdge(x, y-1, 0);\n                        markEdge(x+1, y-1, 1);\n                        markEdge(x+1, y, 2);\n                        anyAdded = true;\n                        continue;\n                    }\n                }\n            }\n\n            // ---- orientation 3 : missing top\u2011right ----\n            if (x - 1 >= 0 && y - 1 >= 0) {\n                if (dot[x-1][y] && dot[x-1][y-1] && dot[x][y-1]) {\n                    if (!used[x][y][2] && !used[x-1][y][3] &&\n                        !used[x-1][y-1][0] && !used[x][y-1][1]) {\n                        ops.push_back({x, y, x-1, y, x-1, y-1, x, y-1});\n                        dot[x][y] = 1;\n                        markEdge(x, y, 2);\n                        markEdge(x-1, y, 3);\n                        markEdge(x-1, y-1, 0);\n                        markEdge(x, y-1, 1);\n                        anyAdded = true;\n                        continue;\n                    }\n                }\n            }\n        }\n    }\n\n    cout << ops.size() << \"\\n\";\n    for (auto &op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' '\n             << op.x2 << ' ' << op.y2 << ' '\n             << op.x3 << ' ' << op.y3 << ' '\n             << op.x4 << ' ' << op.y4 << \"\\n\";\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Board {\n    int a[10][10];\n};\n\ninline void tilt(Board &b, char dir) {\n    if (dir == 'L') {\n        for (int i = 0; i < 10; ++i) {\n            int write = 0;\n            for (int j = 0; j < 10; ++j) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != j) {\n                        b.a[i][write] = v;\n                        b.a[i][j] = 0;\n                    }\n                    ++write;\n                }\n            }\n        }\n    } else if (dir == 'R') {\n        for (int i = 0; i < 10; ++i) {\n            int write = 9;\n            for (int j = 9; j >= 0; --j) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != j) {\n                        b.a[i][write] = v;\n                        b.a[i][j] = 0;\n                    }\n                    --write;\n                }\n            }\n        }\n    } else if (dir == 'F') {          // forward = up\n        for (int j = 0; j < 10; ++j) {\n            int write = 0;\n            for (int i = 0; i < 10; ++i) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != i) {\n                        b.a[write][j] = v;\n                        b.a[i][j] = 0;\n                    }\n                    ++write;\n                }\n            }\n        }\n    } else {                         // dir == 'B'  backward = down\n        for (int j = 0; j < 10; ++j) {\n            int write = 9;\n            for (int i = 9; i >= 0; --i) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != i) {\n                        b.a[write][j] = v;\n                        b.a[i][j] = 0;\n                    }\n                    --write;\n                }\n            }\n        }\n    }\n}\n\n// \u03a3 size\u00b2 of all connected components (four\u2011directional, same flavour)\nlong long score(const Board &b) {\n    bool vis[10][10] = {};\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    long long sum = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (b.a[i][j] != 0 && !vis[i][j]) {\n                int flavour = b.a[i][j];\n                int cnt = 0;\n                queue<pair<int,int>> q;\n                q.emplace(i, j);\n                vis[i][j] = true;\n                while (!q.empty()) {\n                    auto [x, y] = q.front(); q.pop();\n                    ++cnt;\n                    for (int k = 0; k < 4; ++k) {\n                        int nx = x + dx[k];\n                        int ny = y + dy[k];\n                        if (0 <= nx && nx < 10 && 0 <= ny && ny < 10 &&\n                            !vis[nx][ny] && b.a[nx][ny] == flavour) {\n                            vis[nx][ny] = true;\n                            q.emplace(nx, ny);\n                        }\n                    }\n                }\n                sum += 1LL * cnt * cnt;\n            }\n        }\n    }\n    return sum;\n}\n\n// place a candy of flavour f into the p\u2011th empty cell (1\u2011based)\ninline void place(Board &b, int f, int p) {\n    int cnt = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (b.a[i][j] == 0) {\n                ++cnt;\n                if (cnt == p) {\n                    b.a[i][j] = f;\n                    return;\n                }\n            }\n        }\n    }\n}\n\n// greedy tilt \u2013 direction that gives the largest immediate score\nchar bestTilt(const Board &b) {\n    const char dirs[4] = {'F','B','L','R'};\n    long long best = -1;\n    char bestDir = 'F';\n    for (char d : dirs) {\n        Board tmp = b;\n        tilt(tmp, d);\n        long long sc = score(tmp);\n        if (sc > best) {\n            best = sc;\n            bestDir = d;\n        }\n    }\n    return bestDir;\n}\n\n// collect coordinates of empty cells (row\u2011major order)\ninline void emptyCells(const Board &b, vector<pair<int,int>> &out) {\n    out.clear();\n    out.reserve(100);\n    for (int i = 0; i < 10; ++i)\n        for (int j = 0; j < 10; ++j)\n            if (b.a[i][j] == 0) out.emplace_back(i, j);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<int> f(100);\n    for (int i = 0; i < 100; ++i) cin >> f[i];\n\n    Board board{};\n    memset(board.a, 0, sizeof(board.a));\n\n    const char dirs[4] = {'F','B','L','R'};\n    const int SIM = 3;          // Monte\u2011Carlo repetitions\n    const int K   = 5;          // look\u2011ahead steps\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    vector<pair<int,int>> empties;\n    empties.reserve(100);\n\n    for (int t = 0; t < 100; ++t) {\n        int p; cin >> p;\n        place(board, f[t], p);\n        if (t == 99) break;                 // no tilt after the last candy\n\n        double bestAvg = -1e100;\n        char bestDir = 'F';\n\n        for (char d : dirs) {\n            Board tmp = board;\n            tilt(tmp, d);\n            long long immScore = score(tmp);\n            double total = static_cast<double>(immScore);\n\n            // Monte\u2011Carlo simulations\n            for (int sim = 0; sim < SIM; ++sim) {\n                Board simBoard = tmp;\n                int remaining = 100 - (t + 1);\n                int steps = min(K, remaining);\n                for (int step = t + 1; step < t + 1 + steps; ++step) {\n                    // random placement of f[step]\n                    emptyCells(simBoard, empties);\n                    if (empties.empty()) break;\n                    int idx = rng() % static_cast<int>(empties.size());\n                    auto [ri, rj] = empties[idx];\n                    simBoard.a[ri][rj] = f[step];\n\n                    // greedy tilt for the simulated step\n                    char d2 = bestTilt(simBoard);\n                    tilt(simBoard, d2);\n                }\n                total += static_cast<double>(score(simBoard));\n            }\n            double avg = total / (SIM + 1);\n            if (avg > bestAvg) {\n                bestAvg = avg;\n                bestDir = d;\n            }\n        }\n\n        cout << bestDir << '\\n' << std::flush;\n        tilt(board, bestDir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;          // no input\n    \n    // choose the smallest possible N (\u22654 and \u2265M)\n    int N = max(4, M);\n    if (N > 100) N = 100;                      // just in case, but M\u2264100\n    \n    long long L = 1LL * N * (N - 1) / 2;       // length of adjacency string\n    \n    // pre\u2011compute sorted degree vectors of all Gk (star graphs)\n    vector<vector<int>> candDegSorted(M, vector<int>(N));\n    for (int k = 0; k < M; ++k) {\n        vector<int> deg(N, 0);\n        deg[0] = k;                 // centre degree\n        for (int i = 1; i <= k; ++i) deg[i] = 1;   // leaves\n        // remaining vertices already 0\n        sort(deg.begin(), deg.end());\n        candDegSorted[k] = move(deg);\n    }\n    \n    // output N\n    cout << N << \"\\n\";\n    // output the M graphs\n    string base(L, '0');\n    for (int k = 0; k < M; ++k) {\n        string s = base;\n        // edges (0, j) for j = 1..k correspond to positions 0..k-1\n        for (int j = 1; j <= k; ++j) {\n            // position of edge (0,j) in lexicographic order:\n            // for i = 0, the first (N-1) entries are (0,1),(0,2),..., (0,N-1)\n            // so position = j-1\n            s[j - 1] = '1';\n        }\n        cout << s << \"\\n\";\n    }\n    cout.flush();                     // important\n    \n    // answer 100 queries\n    for (int query = 0; query < 100; ++query) {\n        string H;\n        cin >> H;\n        // compute degree vector of H\n        vector<int> deg(N, 0);\n        long long pos = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (H[pos] == '1') {\n                    ++deg[i];\n                    ++deg[j];\n                }\n                ++pos;\n            }\n        }\n        sort(deg.begin(), deg.end());\n        // find the closest candidate\n        int best = 0;\n        long long bestDist = LLONG_MAX;\n        for (int k = 0; k < M; ++k) {\n            long long dist = 0;\n            for (int i = 0; i < N; ++i) {\n                dist += llabs((long long)deg[i] - (long long)candDegSorted[k][i]);\n            }\n            if (dist < bestDist) {\n                bestDist = dist;\n                best = k;\n            }\n        }\n        cout << best << \"\\n\";\n        cout.flush();\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll INF = (1LL << 60);\n\nstruct Edge {\n    int u, v;\n    int w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[i] = {u, v, w};\n    }\n    // coordinates are irrelevant for the schedule\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // adjacency list (undirected)\n    vector<vector<tuple<int,int,int>>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u = edges[i].u, v = edges[i].v, w = edges[i].w;\n        adj[u].push_back({v, w, i});\n        adj[v].push_back({u, w, i});\n    }\n\n    // ---------- Brandes algorithm for weighted graphs ----------\n    vector<double> edge_bc(M, 0.0);          // betweenness (still doubled for undirected)\n    vector<ll> dist(N);\n    vector<double> sigma(N);\n    vector<double> delta(N);\n    vector<vector<int>> pred(N);\n    vector<vector<int>> pred_e(N);\n    vector<int> order; order.reserve(N);\n\n    for (int s = 0; s < N; ++s) {\n        // initialise\n        fill(dist.begin(), dist.end(), INF);\n        fill(sigma.begin(), sigma.end(), 0.0);\n        for (int i = 0; i < N; ++i) {\n            pred[i].clear();\n            pred_e[i].clear();\n        }\n        order.clear();\n\n        dist[s] = 0;\n        sigma[s] = 1.0;\n        using PQItem = pair<ll,int>;\n        priority_queue<PQItem, vector<PQItem>, greater<PQItem>> pq;\n        pq.emplace(0LL, s);\n\n        // Dijkstra + predecessor collection\n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d != dist[v]) continue;\n            order.push_back(v);\n            for (auto [to, wgt, eid] : adj[v]) {\n                ll nd = d + wgt;\n                if (nd < dist[to]) {\n                    dist[to] = nd;\n                    sigma[to] = sigma[v];\n                    pred[to].clear();\n                    pred_e[to].clear();\n                    pred[to].push_back(v);\n                    pred_e[to].push_back(eid);\n                    pq.emplace(nd, to);\n                } else if (nd == dist[to]) {\n                    sigma[to] += sigma[v];\n                    pred[to].push_back(v);\n                    pred_e[to].push_back(eid);\n                }\n            }\n        }\n\n        // Dependency accumulation (back\u2011propagation)\n        fill(delta.begin(), delta.end(), 0.0);\n        for (int idx = (int)order.size() - 1; idx >= 0; --idx) {\n            int w = order[idx];\n            for (size_t i = 0; i < pred[w].size(); ++i) {\n                int v = pred[w][i];\n                int eid = pred_e[w][i];\n                double coeff = (sigma[v] / sigma[w]) * (1.0 + delta[w]);\n                delta[v] += coeff;\n                edge_bc[eid] += coeff;          // each direction contributes once\n            }\n        }\n    }\n    // ---------------------------------------------------------\n\n    // Sort edges by decreasing betweenness (most critical first)\n    vector<int> idx(M);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(),\n         [&](int a, int b) { return edge_bc[a] > edge_bc[b]; });\n\n    // Assign days round\u2011robin on the sorted order\n    vector<int> day(M);\n    for (int i = 0; i < M; ++i) {\n        int e = idx[i];\n        day[e] = (i % D) + 1;          // days are 1\u2011based\n    }\n\n    // Output\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << day[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D;\n    if (!(cin >> D)) return 0;\n    const int N = D * D * D;\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n\n    // helper to convert (x,y,z) -> index\n    auto idx = [&](int x, int y, int z) { return x * D * D + y * D + z; };\n\n    vector<char> need0(N, 0), need1(N, 0), shared(N, 0);\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                int id = idx(x, y, z);\n                bool a0 = (f[0][z][x] == '1') && (r[0][z][y] == '1');\n                bool a1 = (f[1][z][x] == '1') && (r[1][z][y] == '1');\n                need0[id] = a0;\n                need1[id] = a1;\n                shared[id] = a0 && a1;\n            }\n        }\n    }\n\n    // output arrays\n    vector<int> b0(N, 0), b1(N, 0);\n    int cur_id = 1;\n\n    // neighbour offsets (6\u2011connected)\n    const int dx[6] = {1,-1,0,0,0,0};\n    const int dy[6] = {0,0,1,-1,0,0};\n    const int dz[6] = {0,0,0,0,1,-1};\n\n    // ---------- process shared cells ----------\n    vector<char> visited(N, 0);\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                int start = idx(x, y, z);\n                if (!shared[start] || visited[start]) continue;\n                // BFS for this component\n                queue<int> q;\n                vector<int> comp;\n                q.push(start);\n                visited[start] = 1;\n                while (!q.empty()) {\n                    int v = q.front(); q.pop();\n                    comp.push_back(v);\n                    int cx = v / (D * D);\n                    int cy = (v / D) % D;\n                    int cz = v % D;\n                    for (int dir = 0; dir < 6; ++dir) {\n                        int nx = cx + dx[dir];\n                        int ny = cy + dy[dir];\n                        int nz = cz + dz[dir];\n                        if (nx < 0 || nx >= D || ny < 0 || ny >= D || nz < 0 || nz >= D) continue;\n                        int nid = idx(nx, ny, nz);\n                        if (shared[nid] && !visited[nid]) {\n                            visited[nid] = 1;\n                            q.push(nid);\n                        }\n                    }\n                }\n                // assign a new block id to this component (used in both objects)\n                for (int v : comp) {\n                    b0[v] = cur_id;\n                    b1[v] = cur_id;\n                }\n                ++cur_id;\n            }\n        }\n    }\n\n    // ---------- process cells exclusive to silhouette 0 ----------\n    fill(visited.begin(), visited.end(), 0);\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                int start = idx(x, y, z);\n                if (!(need0[start] && !need1[start]) || visited[start]) continue;\n                queue<int> q;\n                vector<int> comp;\n                q.push(start);\n                visited[start] = 1;\n                while (!q.empty()) {\n                    int v = q.front(); q.pop();\n                    comp.push_back(v);\n                    int cx = v / (D * D);\n                    int cy = (v / D) % D;\n                    int cz = v % D;\n                    for (int dir = 0; dir < 6; ++dir) {\n                        int nx = cx + dx[dir];\n                        int ny = cy + dy[dir];\n                        int nz = cz + dz[dir];\n                        if (nx < 0 || nx >= D || ny < 0 || ny >= D || nz < 0 || nz >= D) continue;\n                        int nid = idx(nx, ny, nz);\n                        if (need0[nid] && !need1[nid] && !visited[nid]) {\n                            visited[nid] = 1;\n                            q.push(nid);\n                        }\n                    }\n                }\n                for (int v : comp) b0[v] = cur_id;\n                ++cur_id;\n            }\n        }\n    }\n\n    // ---------- process cells exclusive to silhouette 1 ----------\n    fill(visited.begin(), visited.end(), 0);\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                int start = idx(x, y, z);\n                if (!(need1[start] && !need0[start]) || visited[start]) continue;\n                queue<int> q;\n                vector<int> comp;\n                q.push(start);\n                visited[start] = 1;\n                while (!q.empty()) {\n                    int v = q.front(); q.pop();\n                    comp.push_back(v);\n                    int cx = v / (D * D);\n                    int cy = (v / D) % D;\n                    int cz = v % D;\n                    for (int dir = 0; dir < 6; ++dir) {\n                        int nx = cx + dx[dir];\n                        int ny = cy + dy[dir];\n                        int nz = cz + dz[dir];\n                        if (nx < 0 || nx >= D || ny < 0 || ny >= D || nz < 0 || nz >= D) continue;\n                        int nid = idx(nx, ny, nz);\n                        if (need1[nid] && !need0[nid] && !visited[nid]) {\n                            visited[nid] = 1;\n                            q.push(nid);\n                        }\n                    }\n                }\n                for (int v : comp) b1[v] = cur_id;\n                ++cur_id;\n            }\n        }\n    }\n\n    int n = cur_id - 1;\n    cout << n << \"\\n\";\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << b0[i];\n    }\n    cout << \"\\n\";\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << b1[i];\n    }\n    cout << \"\\n\";\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ---------- Disjoint Set Union ----------\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;\n\n    vector<long long> xs(N), ys(N);\n    for (int i = 0; i < N; ++i) cin >> xs[i] >> ys[i];\n\n    struct Edge {\n        int u, v;\n        long long w;\n        int idx;\n    };\n    vector<Edge> edges(M);\n    for (int j = 0; j < M; ++j) {\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[j] = {u, v, w, j};\n    }\n\n    vector<long long> a(K), b(K);\n    for (int k = 0; k < K; ++k) cin >> a[k] >> b[k];\n\n    // ---------- 1) Minimum Spanning Tree ----------\n    vector<int> B(M, 0);                     // edge on/off\n    vector<Edge> sorted = edges;\n    sort(sorted.begin(), sorted.end(),\n         [](const Edge& e1, const Edge& e2) { return e1.w < e2.w; });\n    DSU dsu(N);\n    for (const auto& e : sorted) {\n        if (dsu.unite(e.u, e.v)) {\n            B[e.idx] = 1;                    // edge belongs to the MST\n        }\n    }\n\n    // Build adjacency list of the MST (only edges with B==1)\n    vector<vector<pair<int,int>>> adj(N);\n    for (int j = 0; j < M; ++j) if (B[j]) {\n        int u = edges[j].u, v = edges[j].v;\n        adj[u].push_back({v, j});\n        adj[v].push_back({u, j});\n    }\n\n    // ---------- 2) Assign residents to the nearest station ----------\n    const long long INF64 = (1LL << 60);\n    vector<long long> maxDist2(N, -1);        // -1 means no resident assigned\n    for (int k = 0; k < K; ++k) {\n        long long bestDist2 = INF64;\n        int bestIdx = -1;\n        for (int i = 0; i < N; ++i) {\n            long long dx = xs[i] - a[k];\n            long long dy = ys[i] - b[k];\n            long long d2 = dx*dx + dy*dy;\n            if (d2 < bestDist2) {\n                bestDist2 = d2;\n                bestIdx = i;\n            }\n        }\n        if (maxDist2[bestIdx] < bestDist2) maxDist2[bestIdx] = bestDist2;\n    }\n\n    // ---------- 3) Compute broadcast radii ----------\n    vector<int> P(N, 0);\n    for (int i = 0; i < N; ++i) {\n        if (maxDist2[i] == -1) {\n            P[i] = 0;\n        } else {\n            double d = sqrt((double)maxDist2[i]);\n            int rad = (int)floor(d);\n            while ((long long)rad * rad < maxDist2[i]) ++rad; // ceil\n            if (rad > 5000) rad = 5000; // safety, should never happen\n            P[i] = rad;\n        }\n    }\n\n    // ---------- 4) Prune the MST to the minimal subtree covering all active stations ----------\n    // Determine which stations are \"active\" (need a non\u2011zero radius)\n    vector<char> active(N, 0);\n    for (int i = 0; i < N; ++i) if (maxDist2[i] != -1) active[i] = 1;\n\n    // Root the tree at vertex 0 (station 1)\n    vector<int> parent(N, -1);\n    vector<int> parentEdge(N, -1);\n    vector<int> order;\n    order.reserve(N);\n    stack<int> st;\n    st.push(0);\n    parent[0] = 0;\n    while (!st.empty()) {\n        int v = st.top(); st.pop();\n        order.push_back(v);\n        for (auto [to, idx] : adj[v]) {\n            if (to == parent[v]) continue;\n            parent[to] = v;\n            parentEdge[to] = idx;\n            st.push(to);\n        }\n    }\n\n    // Mark edges that are needed (those on a path from an active node to the root)\n    vector<char> neededEdge(M, 0);\n    for (int i = 0; i < N; ++i) if (active[i]) {\n        int cur = i;\n        while (cur != 0) {\n            int eIdx = parentEdge[cur];\n            neededEdge[eIdx] = 1;\n            cur = parent[cur];\n        }\n    }\n\n    // Final edge on/off vector\n    for (int j = 0; j < M; ++j) B[j] = neededEdge[j] ? 1 : 0;\n\n    // ---------- 5) Output ----------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << P[i];\n    }\n    cout << '\\n';\n    for (int j = 0; j < M; ++j) {\n        if (j) cout << ' ';\n        cout << B[j];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 30;\n    const int M = N * (N + 1) / 2;          // 465\n\n    // read the pyramid\n    vector<vector<int>> a(N);\n    for (int x = 0; x < N; ++x) {\n        a[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> a[x][y];\n        }\n    }\n\n    struct Op { int x1, y1, x2, y2; };\n    vector<Op> ops;\n    ops.reserve(10000);\n\n    // main loop \u2013 vertical bubble\n    while (true) {\n        bool changed = false;\n        for (int x = 0; x < N - 1; ++x) {\n            for (int y = 0; y <= x; ++y) {\n                // child down\u2011left (x+1 , y)\n                if (a[x][y] > a[x + 1][y]) {\n                    swap(a[x][y], a[x + 1][y]);\n                    ops.push_back({x, y, x + 1, y});\n                    changed = true;\n                    if (ops.size() > 10000) break;\n                }\n                // child down\u2011right (x+1 , y+1)\n                if (a[x][y] > a[x + 1][y + 1]) {\n                    swap(a[x][y], a[x + 1][y + 1]);\n                    ops.push_back({x, y, x + 1, y + 1});\n                    changed = true;\n                    if (ops.size() > 10000) break;\n                }\n            }\n            if (ops.size() > 10000) break;\n        }\n        if (!changed) break;\n        if (ops.size() > 10000) break;   // safety, should never happen\n    }\n\n    // output\n    cout << ops.size() << '\\n';\n    for (auto &op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' '\n             << op.x2 << ' ' << op.y2 << '\\n';\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int D, N;\n    if (!(cin >> D >> N)) return 0;\n    const int entrance_i = 0;\n    const int entrance_j = (D - 1) / 2;\n\n    vector<vector<bool>> obstacle(D, vector<bool>(D, false));\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        obstacle[ri][rj] = true;\n    }\n\n    // -----------------------------------------------------------------\n    // BFS from the entrance, assign an id to every reachable cell\n    // -----------------------------------------------------------------\n    const int INF = -1;\n    vector<vector<int>> id(D, vector<int>(D, INF));\n    vector<int> dist;               // dist[id]\n    vector<int> parent;             // parent[id] (id of parent, -1 for entrance)\n    vector<pair<int,int>> coord;    // coord[id] = (i,j)\n\n    queue<pair<int,int>> q;\n    int curId = 0;\n    id[entrance_i][entrance_j] = curId++;\n    dist.push_back(0);\n    parent.push_back(-1);\n    coord.emplace_back(entrance_i, entrance_j);\n    q.emplace(entrance_i, entrance_j);\n\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        int cur = id[i][j];\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= D || nj < 0 || nj >= D) continue;\n            if (obstacle[ni][nj]) continue;\n            if (id[ni][nj] != INF) continue;\n            id[ni][nj] = curId++;\n            dist.push_back(dist[cur] + 1);\n            parent.push_back(cur);\n            coord.emplace_back(ni, nj);\n            q.emplace(ni, nj);\n        }\n    }\n\n    int totalCells = curId;               // includes entrance\n    int entranceId = 0;\n    int M = totalCells - 1;               // number of containers\n    // sanity check (optional)\n    // assert(M == D*D - 1 - N);\n\n    // -----------------------------------------------------------------\n    // Build list of cells (ids) that can store a container\n    // -----------------------------------------------------------------\n    vector<int> placementIds;\n    placementIds.reserve(M);\n    for (int idv = 1; idv < totalCells; ++idv) placementIds.push_back(idv);\n    sort(placementIds.begin(), placementIds.end(),\n         [&](int a, int b) {\n             if (dist[a] != dist[b]) return dist[a] > dist[b]; // farthest first\n             // tie\u2011break deterministic\n             if (coord[a].first != coord[b].first) return coord[a].first > coord[b].first;\n             return coord[a].second > coord[b].second;\n         });\n\n    // -----------------------------------------------------------------\n    // Read containers and output placement positions\n    // -----------------------------------------------------------------\n    vector<int> containerNumber(totalCells, -1); // containerNumber[id] = t\n    int ptr = 0; // index in placementIds\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;\n        int cid = placementIds[ptr++];\n        containerNumber[cid] = t;\n        cout << coord[cid].first << ' ' << coord[cid].second << \"\\n\";\n        cout.flush(); // required after each placement\n    }\n\n    // -----------------------------------------------------------------\n    // Build children lists of the BFS tree\n    // -----------------------------------------------------------------\n    vector<vector<int>> children(totalCells);\n    for (int v = 1; v < totalCells; ++v) {\n        int p = parent[v];\n        children[p].push_back(v);\n    }\n\n    // -----------------------------------------------------------------\n    // Transport order: Kahn + min\u2011heap on container number\n    // -----------------------------------------------------------------\n    struct HeapNode {\n        int number; // container number\n        int id;\n        bool operator<(HeapNode const& other) const {\n            // priority_queue in C++ is a max\u2011heap, so reverse comparison\n            return number > other.number;\n        }\n    };\n    priority_queue<HeapNode> pq;\n    // initially all children of the entrance are ready\n    for (int v : children[entranceId]) {\n        pq.push({containerNumber[v], v});\n    }\n\n    while (!pq.empty()) {\n        auto cur = pq.top(); pq.pop();\n        int v = cur.id;\n        cout << coord[v].first << ' ' << coord[v].second << \"\\n\";\n        for (int ch : children[v]) {\n            pq.push({containerNumber[ch], ch});\n        }\n    }\n    // No more output needed\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    vector<vector<int>> a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (j) cout << ' ';\n            cout << a[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n    vector<long long> w(N);\n    for (int i = 0; i < N; ++i) cin >> w[i];\n\n    long long total = 0;\n    for (auto x : w) total += x;\n    double target = static_cast<double>(total) / D;\n\n    // random generator\n    std::mt19937_64 rng(\n        chrono::steady_clock::now().time_since_epoch().count());\n\n    vector<int> bestAssign(N);\n    double bestScore = numeric_limits<double>::infinity();\n\n    auto computeScore = [&](const vector<long long> &sum) -> double {\n        double sc = 0.0;\n        for (int d = 0; d < D; ++d) {\n            double diff = static_cast<double>(sum[d]) - target;\n            sc += diff * diff;\n        }\n        return sc;\n    };\n\n    // time limit handling\n    const double TIME_LIMIT = 1.8;                // seconds\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        // ----- 1) random order for greedy -----\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) {\n                 if (w[a] != w[b]) return w[a] > w[b];\n                 return (rng() & 1ULL);\n             });\n\n        // ----- 2) greedy assignment -----\n        vector<int> assign(N, -1);\n        vector<long long> sum(D, 0);\n        for (int idx : order) {\n            int bestSet = 0;\n            long long minSum = sum[0];\n            for (int d = 1; d < D; ++d) {\n                if (sum[d] < minSum) {\n                    minSum = sum[d];\n                    bestSet = d;\n                }\n            }\n            assign[idx] = bestSet;\n            sum[bestSet] += w[idx];\n        }\n\n        // ----- 3) local improvement (hill climbing) -----\n        bool improved = true;\n        while (improved) {\n            improved = false;\n\n            // try moving a single item\n            for (int i = 0; i < N && !improved; ++i) {\n                int a = assign[i];\n                long long wi = w[i];\n                double curDiffA = static_cast<double>(sum[a]) - target;\n                for (int b = 0; b < D; ++b) {\n                    if (b == a) continue;\n                    double curDiffB = static_cast<double>(sum[b]) - target;\n                    double newDiffA = static_cast<double>(sum[a] - wi) - target;\n                    double newDiffB = static_cast<double>(sum[b] + wi) - target;\n                    double delta = (newDiffA * newDiffA + newDiffB * newDiffB) -\n                                   (curDiffA * curDiffA + curDiffB * curDiffB);\n                    if (delta < -1e-9) {\n                        // perform move\n                        sum[a] -= wi;\n                        sum[b] += wi;\n                        assign[i] = b;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n\n            if (improved) continue;\n\n            // try swapping two items\n            for (int i = 0; i < N && !improved; ++i) {\n                int a = assign[i];\n                long long wi = w[i];\n                for (int j = i + 1; j < N; ++j) {\n                    int b = assign[j];\n                    if (a == b) continue;\n                    long long wj = w[j];\n                    double curDiffA = static_cast<double>(sum[a]) - target;\n                    double curDiffB = static_cast<double>(sum[b]) - target;\n                    double newDiffA = static_cast<double>(sum[a] - wi + wj) - target;\n                    double newDiffB = static_cast<double>(sum[b] - wj + wi) - target;\n                    double delta = (newDiffA * newDiffA + newDiffB * newDiffB) -\n                                   (curDiffA * curDiffA + curDiffB * curDiffB);\n                    if (delta < -1e-9) {\n                        // perform swap\n                        sum[a] = sum[a] - wi + wj;\n                        sum[b] = sum[b] - wj + wi;\n                        assign[i] = b;\n                        assign[j] = a;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n        }\n\n        // ----- 4) evaluate -----\n        double curScore = computeScore(sum);\n        if (curScore < bestScore) {\n            bestScore = curScore;\n            bestAssign = assign;\n        }\n\n        // ----- 5) time check -----\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n    }\n\n    // ----- 6) output best assignment -----\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << bestAssign[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    const int per = n / m;                 // = 20 for the given data\n    vector<vector<int>> st(m);             // bottom \u2192 top\n    vector<int> pos(n + 1, -1);            // current stack of each box\n\n    for (int i = 0; i < m; ++i) {\n        st[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x; cin >> x;\n            st[i].push_back(x);\n            pos[x] = i;\n        }\n    }\n\n    vector<pair<int,int>> ops;             // (v , i)   i = 0 \u2192 removal\n\n    // helper: choose a destination for the top box w of stack src\n    auto choose_dest = [&](int w, int src) -> int {\n        // 1) empty stack\n        for (int i = 0; i < m; ++i) if (i != src && st[i].empty())\n            return i;\n        // 2) stack whose top is larger than w (pick the smallest such top)\n        int best = -1, bestTop = INT_MAX;\n        for (int i = 0; i < m; ++i) if (i != src && !st[i].empty() && st[i].back() > w) {\n            if (st[i].back() < bestTop) {\n                bestTop = st[i].back();\n                best = i;\n            }\n        }\n        if (best != -1) return best;\n        // 3) fallback \u2013 any other stack, choose the one with smallest size\n        int minSize = INT_MAX;\n        for (int i = 0; i < m; ++i) if (i != src) {\n            if ((int)st[i].size() < minSize) {\n                minSize = (int)st[i].size();\n                best = i;\n            }\n        }\n        return best;   // always exists because m \u2265 2\n    };\n\n    for (int v = 1; v <= n; ++v) {\n        int s = pos[v];                     // stack that currently holds v\n        // bring v to the top\n        while (!st[s].empty() && st[s].back() != v) {\n            int w = st[s].back();           // top box, w > v\n            int d = choose_dest(w, s);\n            // perform the move\n            st[s].pop_back();\n            st[d].push_back(w);\n            pos[w] = d;\n            ops.emplace_back(w, d + 1);     // +1 because stacks are 1\u2011indexed in output\n        }\n        // now v is on the top \u2192 remove it\n        ops.emplace_back(v, 0);\n        st[s].pop_back();\n        pos[v] = -1;\n    }\n\n    // safety check (the problem guarantees 5000 is enough)\n    assert(ops.size() <= 5000);\n\n    for (auto [v, i] : ops) {\n        cout << v << ' ' << i << '\\n';\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> h;               // (N-1) \u00d7 N  : vertical walls\nvector<string> v;               // N \u00d7 (N-1)  : horizontal walls\nvector<vector<char>> visited;   // visited cells\nstring answer;                  // resulting move sequence\n\n// directions: 0=R, 1=D, 2=L, 3=U\nconst int dr[4] = {0, 1, 0, -1};\nconst int dc[4] = {1, 0, -1, 0};\nconst char dirChar[4] = {'R', 'D', 'L', 'U'};\n\n// true iff we can move from (r,c) to the neighbour in direction dir\nbool canMove(int r, int c, int dir) {\n    int nr = r + dr[dir];\n    int nc = c + dc[dir];\n    if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n    if (dir == 0) {               // right\n        return v[r][c] == '0';\n    } else if (dir == 2) {        // left\n        return v[r][c - 1] == '0';\n    } else if (dir == 1) {        // down\n        return h[r][c] == '0';\n    } else {                      // up\n        return h[r - 1][c] == '0';\n    }\n}\n\n// depth\u2011first traversal\nvoid dfs(int r, int c) {\n    visited[r][c] = 1;\n    for (int dir = 0; dir < 4; ++dir) {\n        if (!canMove(r, c, dir)) continue;\n        int nr = r + dr[dir];\n        int nc = c + dc[dir];\n        if (!visited[nr][nc]) {\n            answer.push_back(dirChar[dir]);          // go to neighbour\n            dfs(nr, nc);\n            answer.push_back(dirChar[(dir + 2) % 4]); // come back\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N)) return 0;\n\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n\n    v.resize(N);\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    // read and ignore the d\u2011values\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            long long x;\n            cin >> x;\n        }\n\n    visited.assign(N, vector<char>(N, 0));\n    dfs(0, 0);\n\n    cout << answer << '\\n';\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int i, j;\n};\n\nint manhattan(const Pos& a, const Pos& b) {\n    return abs(a.i - b.i) + abs(a.j - b.j);\n}\n\n// compute the longest overlap of suffix of a and prefix of b\nint overlap(const string& a, const string& b) {\n    int maxk = min((int)a.size(), (int)b.size());\n    for (int k = maxk; k > 0; --k) {\n        bool ok = true;\n        for (int t = 0; t < k; ++t) {\n            if (a[a.size() - k + t] != b[t]) {\n                ok = false; break;\n            }\n        }\n        if (ok) return k;\n    }\n    return 0;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n    \n    // positions for each letter\n    vector<Pos> pos[26];\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = board[i][j];\n            pos[c - 'A'].push_back({i, j});\n        }\n    }\n    \n    vector<string> cur(M);\n    for (int k = 0; k < M; ++k) cin >> cur[k];\n    \n    // ---------- 1. greedy shortest common superstring ----------\n    while (cur.size() > 1) {\n        int bestOv = -1;\n        int bestI = -1, bestJ = -1;\n        string bestMerged;\n        int sz = cur.size();\n        for (int i = 0; i < sz; ++i) {\n            for (int j = 0; j < sz; ++j) if (i != j) {\n                int ov = overlap(cur[i], cur[j]);\n                if (ov > bestOv) {\n                    bestOv = ov;\n                    bestI = i;\n                    bestJ = j;\n                    bestMerged = cur[i] + cur[j].substr(ov);\n                }\n            }\n        }\n        // merge bestI and bestJ\n        if (bestI > bestJ) swap(bestI, bestJ); // erase larger index first\n        cur.erase(cur.begin() + bestJ);\n        cur.erase(cur.begin() + bestI);\n        cur.push_back(bestMerged);\n    }\n    string S = cur[0];                 // final output string\n    int L = (int)S.size();\n    \n    // ---------- 2. DP for optimal movement ----------\n    // layerPos[p] = list of cells that can type S[p]\n    vector<vector<Pos>> layerPos(L);\n    for (int p = 0; p < L; ++p) {\n        layerPos[p] = pos[S[p] - 'A'];\n    }\n    \n    const int INF = 1e9;\n    vector<vector<int>> dp(L);\n    vector<vector<int>> parent(L);\n    \n    // first layer\n    dp[0].resize(layerPos[0].size());\n    parent[0].resize(layerPos[0].size(), -1);\n    for (size_t i = 0; i < layerPos[0].size(); ++i) {\n        dp[0][i] = manhattan({si, sj}, layerPos[0][i]) + 1;\n    }\n    \n    // subsequent layers\n    for (int p = 1; p < L; ++p) {\n        const auto& prevCells = layerPos[p-1];\n        const auto& curCells  = layerPos[p];\n        dp[p].assign(curCells.size(), INF);\n        parent[p].assign(curCells.size(), -1);\n        for (size_t ci = 0; ci < curCells.size(); ++ci) {\n            int best = INF;\n            int bestPrev = -1;\n            for (size_t pj = 0; pj < prevCells.size(); ++pj) {\n                int cand = dp[p-1][pj] + manhattan(prevCells[pj], curCells[ci]) + 1;\n                if (cand < best) {\n                    best = cand;\n                    bestPrev = (int)pj;\n                }\n            }\n            dp[p][ci] = best;\n            parent[p][ci] = bestPrev;\n        }\n    }\n    \n    // find minimal cost at the last layer\n    int lastIdx = -1;\n    int bestCost = INF;\n    for (size_t i = 0; i < dp[L-1].size(); ++i) {\n        if (dp[L-1][i] < bestCost) {\n            bestCost = dp[L-1][i];\n            lastIdx = (int)i;\n        }\n    }\n    \n    // reconstruct the sequence of cells\n    vector<Pos> answer(L);\n    int curIdx = lastIdx;\n    for (int p = L-1; p >= 0; --p) {\n        answer[p] = layerPos[p][curIdx];\n        curIdx = parent[p][curIdx];\n    }\n    \n    // ---------- output ----------\n    for (const Pos& p : answer) {\n        cout << p.i << ' ' << p.j << '\\n';\n    }\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    double eps;\n    if (!(cin >> N >> M >> eps)) return 0;   // no input\n\n    // read and discard the description of the M polyomino shapes\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int t = 0; t < d; ++t) {\n            int i, j;\n            cin >> i >> j;   // coordinates inside the shape, not needed later\n        }\n    }\n\n    vector<pair<int,int>> answer;   // cells with v(i,j) > 0\n\n    // query every cell individually\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << \"q 1 \" << i << ' ' << j << '\\n';\n            cout.flush();                     // important for interactive judge\n            int v;\n            cin >> v;                         // judge returns the exact value\n            if (v > 0) answer.emplace_back(i, j);\n        }\n    }\n\n    // output the final answer\n    cout << \"a \" << answer.size();\n    for (auto [i, j] : answer) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << '\\n';\n    cout.flush();\n\n    // read the final verdict (1 = correct, 0 = wrong) \u2013 not required to act on it\n    int verdict;\n    if (cin >> verdict) {\n        // nothing to do; the program will exit immediately afterwards\n    }\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\n    // read and ignore the desired areas\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            long long a;\n            cin >> a;\n        }\n    }\n    // output the baseline layout: horizontal strips of height 1\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            // rectangle: (k, 0) .. (k+1, W)\n            cout << k << ' ' << 0 << ' ' << k + 1 << ' ' << W << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr long long MOD = 998244353LL;\n\nstruct Op {\n    int m, p, q;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;          // N = 9, M = 20, K = 81\n    const int maxP = N - 3;   // 6\n    const int maxQ = N - 3;   // 6\n\n    // initial board (flattened)\n    vector<long long> initBoard(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            long long x; cin >> x;\n            initBoard[i * N + j] = x % MOD;\n        }\n    }\n\n    // stamps\n    vector<array<array<long long, 3>, 3>> stamp(M);\n    for (int m = 0; m < M; ++m) {\n        for (int u = 0; u < 3; ++u) {\n            for (int v = 0; v < 3; ++v) {\n                long long x; cin >> x;\n                stamp[m][u][v] = x % MOD;\n            }\n        }\n    }\n\n    // ---------- helper lambdas ----------\n    auto applyOp = [&](vector<long long> &board, const Op &op) {\n        for (int u = 0; u < 3; ++u) {\n            int baseRow = (op.p + u) * N;\n            for (int v = 0; v < 3; ++v) {\n                int idx = baseRow + (op.q + v);\n                board[idx] += stamp[op.m][u][v];\n                if (board[idx] >= MOD) board[idx] -= MOD;\n            }\n        }\n    };\n\n    auto simulate = [&](const vector<Op> &ops, vector<long long> &board) {\n        board = initBoard;\n        for (const Op &op : ops) applyOp(board, op);\n    };\n\n    auto totalScore = [&](const vector<long long> &board) -> long long {\n        long long sum = 0;\n        for (long long v : board) sum += v;\n        return sum;\n    };\n\n    // returns best operation and its delta on the given board\n    auto bestOperation = [&](const vector<long long> &board) -> pair<Op, long long> {\n        long long bestDelta = LLONG_MIN;\n        Op bestOp{-1, -1, -1};\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= maxP; ++p) {\n                for (int q = 0; q <= maxQ; ++q) {\n                    long long delta = 0;\n                    for (int u = 0; u < 3; ++u) {\n                        int baseRow = (p + u) * N;\n                        for (int v = 0; v < 3; ++v) {\n                            int idx = baseRow + (q + v);\n                            long long old = board[idx];\n                            long long add = stamp[m][u][v];\n                            long long nw = old + add;\n                            if (nw >= MOD) nw -= MOD;\n                            delta += (nw - old);\n                        }\n                    }\n                    if (delta > bestDelta) {\n                        bestDelta = delta;\n                        bestOp = {m, p, q};\n                    }\n                }\n            }\n        }\n        return {bestOp, bestDelta};\n    };\n\n    // ---------- initial greedy ----------\n    vector<Op> bestOps;\n    vector<long long> board = initBoard;\n    while ((int)bestOps.size() < K) {\n        auto [op, delta] = bestOperation(board);\n        if (delta <= 0) break;\n        applyOp(board, op);\n        bestOps.push_back(op);\n    }\n    long long bestScore = totalScore(board);\n\n    // ---------- hill climbing ----------\n    std::mt19937_64 rng(\n        (uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n\n    const double TIME_LIMIT = 1.9; // seconds\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        // copy current best solution\n        vector<Op> curOps = bestOps;\n\n        // random modification\n        int modType = rng() % 3; // 0 = replace, 1 = insert, 2 = delete\n        if (modType == 0 && !curOps.empty()) {\n            int idx = rng() % curOps.size();\n            Op rnd{int(rng() % M), int(rng() % (maxP + 1)), int(rng() % (maxQ + 1))};\n            curOps[idx] = rnd;\n        } else if (modType == 1 && (int)curOps.size() < K) {\n            int idx = rng() % (curOps.size() + 1);\n            Op rnd{int(rng() % M), int(rng() % (maxP + 1)), int(rng() % (maxQ + 1))};\n            curOps.insert(curOps.begin() + idx, rnd);\n        } else if (modType == 2 && !curOps.empty()) {\n            int idx = rng() % curOps.size();\n            curOps.erase(curOps.begin() + idx);\n        }\n        // rebuild board from the (possibly) modified prefix\n        vector<long long> curBoard;\n        simulate(curOps, curBoard);\n\n        // greedy completion again\n        while ((int)curOps.size() < K) {\n            auto [op, delta] = bestOperation(curBoard);\n            if (delta <= 0) break;\n            applyOp(curBoard, op);\n            curOps.push_back(op);\n        }\n\n        long long curScore = totalScore(curBoard);\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestOps.swap(curOps);\n        }\n    }\n\n    // ---------- output ----------\n    cout << bestOps.size() << \"\\n\";\n    for (const Op &op : bestOps) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << \"\\n\";\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\n// generate a Manhattan walk from (r,c) to (tr,tc)\nstatic string walk(int r, int c, int tr, int tc) {\n    string s;\n    while (r > tr) { s.push_back('U'); --r; }\n    while (r < tr) { s.push_back('D'); ++r; }\n    while (c > tc) { s.push_back('L'); --c; }\n    while (c < tc) { s.push_back('R'); ++c; }\n    return s;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> A(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> A[i][j];\n\n    // actions for each crane\n    vector<string> act(N);\n    // small cranes: bomb at turn 0, later do nothing\n    // we will pad them later to the length of the large crane\n    for (int i = 1; i < N; ++i) act[i] = \"B\";\n\n    // large crane (crane 0)\n    string &big = act[0];\n    int curR = 0, curC = 0;               // start position (0,0)\n\n    for (int i = 0; i < N; ++i) {        // receiving gate i\n        for (int j = 0; j < N; ++j) {    // j\u2011th container of this gate\n            // move to (i,0)\n            big += walk(curR, curC, i, 0);\n            curR = i; curC = 0;\n            // pick up\n            big.push_back('P');\n            int b = A[i][j];\n            int dr = b / N;               // destination row\n            // move to dispatch gate (dr, N-1)\n            big += walk(curR, curC, dr, N - 1);\n            curR = dr; curC = N - 1;\n            // release\n            big.push_back('Q');\n            // move back to the receiving gate (i,0)\n            big += walk(curR, curC, i, 0);\n            curR = i; curC = 0;\n        }\n    }\n\n    // pad small cranes with '.' to the length of the longest string\n    size_t L = big.size();\n    for (int i = 1; i < N; ++i) {\n        if (act[i].size() < L) act[i].append(L - act[i].size(), '.');\n    }\n\n    // output\n    for (int i = 0; i < N; ++i) {\n        cout << act[i] << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Node {\n    int x, y;\n    int amt;          // remaining amount to send / receive\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> h[i][j];\n\n    vector<Node> sources, sinks;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (h[i][j] > 0) sources.push_back({i, j, h[i][j]});\n            else if (h[i][j] < 0) sinks.push_back({i, j, -h[i][j]});\n        }\n\n    // nothing to do?\n    if (sources.empty() && sinks.empty()) return 0;\n\n    // current truck position\n    int curX = 0, curY = 0;\n    vector<string> ops;\n    ops.reserve(20000);\n\n    auto dist = [&](int x1, int y1, int x2, int y2) {\n        return abs(x1 - x2) + abs(y1 - y2);\n    };\n\n    // move from (curX,curY) to (tx,ty) using Manhattan steps\n    auto moveTo = [&](int tx, int ty) {\n        while (curX != tx) {\n            if (curX < tx) {\n                ops.emplace_back(\"D\");\n                ++curX;\n            } else {\n                ops.emplace_back(\"U\");\n                --curX;\n            }\n        }\n        while (curY != ty) {\n            if (curY < ty) {\n                ops.emplace_back(\"R\");\n                ++curY;\n            } else {\n                ops.emplace_back(\"L\");\n                --curY;\n            }\n        }\n    };\n\n    // Greedy transport\n    while (true) {\n        // find a source with remaining amount\n        int sIdx = -1;\n        int bestDist = INT_MAX;\n        for (int i = 0; i < (int)sources.size(); ++i) {\n            if (sources[i].amt == 0) continue;\n            int d = dist(curX, curY, sources[i].x, sources[i].y);\n            if (d < bestDist) {\n                bestDist = d;\n                sIdx = i;\n            }\n        }\n        if (sIdx == -1) break;               // all supplies exhausted\n\n        // find the nearest sink for this source\n        int tIdx = -1;\n        bestDist = INT_MAX;\n        for (int i = 0; i < (int)sinks.size(); ++i) {\n            if (sinks[i].amt == 0) continue;\n            int d = dist(sources[sIdx].x, sources[sIdx].y,\n                         sinks[i].x, sinks[i].y);\n            if (d < bestDist) {\n                bestDist = d;\n                tIdx = i;\n            }\n        }\n        // there must be a sink because total sum is zero\n        int amount = min(sources[sIdx].amt, sinks[tIdx].amt);\n\n        // 1) move empty to source\n        moveTo(sources[sIdx].x, sources[sIdx].y);\n        // 2) load\n        ops.emplace_back(\"+\" + to_string(amount));\n        // 3) move loaded to sink\n        moveTo(sinks[tIdx].x, sinks[tIdx].y);\n        // 4) unload\n        ops.emplace_back(\"-\" + to_string(amount));\n\n        // update amounts\n        sources[sIdx].amt -= amount;\n        sinks[tIdx].amt   -= amount;\n        // truck is empty again, current position is the sink\n    }\n\n    // output\n    for (const string& s : ops) {\n        cout << s << '\\n';\n    }\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct PairScore {\n    int i, j;\n    long long score;\n    bool operator<(PairScore const& other) const {\n        return score > other.score; // descending\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    const int S = 2 * N * (N - 1);          // 60 for N = 6\n    const int cells = N * N;               // 36\n\n    // read initial seeds\n    vector<vector<int>> X(S, vector<int>(M));\n    for (int i = 0; i < S; ++i)\n        for (int j = 0; j < M; ++j)\n            cin >> X[i][j];\n\n    // global maxima per component (used as weights)\n    vector<long long> weight(M, 0);\n    for (int l = 0; l < M; ++l) {\n        long long mx = 0;\n        for (int i = 0; i < S; ++i) mx = max(mx, (long long)X[i][l]);\n        weight[l] = mx;\n    }\n\n    // pre\u2011compute the list of edges (cell indices)\n    vector<pair<int,int>> edges;\n    edges.reserve(2 * N * (N - 1));\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            int id = r * N + c;\n            if (c + 1 < N) edges.emplace_back(id, id + 1);          // right neighbor\n            if (r + 1 < N) edges.emplace_back(id, id + N);          // down neighbor\n        }\n    }\n    // edges size = 60 for N = 6\n\n    for (int turn = 0; turn < T; ++turn) {\n        // 1. weighted sum for each seed\n        vector<long long> W(S, 0);\n        for (int i = 0; i < S; ++i) {\n            long long sum = 0;\n            for (int l = 0; l < M; ++l) sum += weight[l] * (long long)X[i][l];\n            W[i] = sum;\n        }\n\n        // 2. compute pair scores\n        vector<PairScore> pairs;\n        pairs.reserve(S * (S - 1) / 2);\n        for (int i = 0; i < S; ++i) {\n            for (int j = i + 1; j < S; ++j) {\n                long long sc = 0;\n                for (int l = 0; l < M; ++l) {\n                    int mx = max(X[i][l], X[j][l]);\n                    sc += weight[l] * (long long)mx;\n                }\n                pairs.push_back({i, j, sc});\n            }\n        }\n        sort(pairs.begin(), pairs.end());\n\n        // 3. board initialisation\n        vector<int> board(cells, -1);\n        vector<char> usedSeed(S, 0);\n        size_t edgePtr = 0;\n\n        // 4. place best pairs on free edges\n        for (const auto& p : pairs) {\n            if (usedSeed[p.i] || usedSeed[p.j]) continue;\n            while (edgePtr < edges.size() &&\n                   (board[edges[edgePtr].first] != -1 ||\n                    board[edges[edgePtr].second] != -1)) {\n                ++edgePtr;\n            }\n            if (edgePtr == edges.size()) break;\n            board[edges[edgePtr].first]  = p.i;\n            board[edges[edgePtr].second] = p.j;\n            usedSeed[p.i] = usedSeed[p.j] = 1;\n            ++edgePtr;\n        }\n\n        // 5. fill remaining cells with best unused seeds\n        vector<int> remaining;\n        remaining.reserve(S);\n        for (int i = 0; i < S; ++i) if (!usedSeed[i]) remaining.push_back(i);\n        sort(remaining.begin(), remaining.end(),\n             [&](int a, int b) { return W[a] > W[b]; });\n\n        size_t rpos = 0;\n        for (int cell = 0; cell < cells; ++cell) {\n            if (board[cell] == -1) {\n                board[cell] = remaining[rpos++];\n            }\n        }\n\n        // 6. output board (row\u2011major)\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (c) cout << ' ';\n                cout << board[r * N + c];\n            }\n            cout << '\\n';\n        }\n        cout.flush();\n\n        // 7. read next batch of seeds\n        for (int i = 0; i < S; ++i)\n            for (int l = 0; l < M; ++l)\n                cin >> X[i][l];\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, V;\n    if (!(cin >> N >> M >> V)) return 0;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) cin >> s[i];\n    for (int i = 0; i < N; ++i) cin >> t[i];\n\n    // collect source cells (initial takoyaki not on target) and target cells (empty)\n    vector<Pos> src, dst;\n    vector<vector<int>> hasTak(N, vector<int>(N, 0));\n    vector<vector<int>> isTarget(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (s[i][j] == '1') hasTak[i][j] = 1;\n            if (t[i][j] == '1') isTarget[i][j] = 1;\n        }\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (hasTak[i][j] && !isTarget[i][j])\n                src.push_back({i, j});\n            if (!hasTak[i][j] && isTarget[i][j])\n                dst.push_back({i, j});\n        }\n\n    const int Vprime = 2;               // root + one leaf\n    // output arm description\n    cout << Vprime << \"\\n\";\n    cout << 0 << \" \" << 1 << \"\\n\";       // parent of vertex 1, length 1\n    cout << 0 << \" \" << 0 << \"\\n\";       // initial root position\n\n    // direction vectors\n    const int dx[4] = {0, 1, 0, -1};\n    const int dy[4] = {1, 0, -1, 0};\n\n    // helper to compute rotation cost\n    auto rotCost = [&](int cur, int target) -> int {\n        int diff = (target - cur + 4) % 4;\n        if (diff == 0) return 0;\n        if (diff == 2) return 2;\n        return 1;\n    };\n\n    // storage for operations\n    vector<string> ops;\n\n    // helper to push a turn\n    auto pushTurn = [&](char mv, char rot, char leafAct) {\n        string s(4, '.');\n        s[0] = mv;\n        s[1] = rot;\n        s[3] = leafAct;\n        ops.push_back(s);\n    };\n\n    // current state\n    int curX = 0, curY = 0;   // root position\n    int curDir = 0;           // leaf points right (dx=0, dy=+1)\n\n    // rotate leaf to target direction (may need 1 or 2 turns)\n    auto rotateTo = [&](int targetDir) {\n        int diff = (targetDir - curDir + 4) % 4;\n        if (diff == 0) return;\n        if (diff == 1) {\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n        } else if (diff == 3) {\n            pushTurn('.', 'L', '.');\n            curDir = (curDir + 3) % 4;\n        } else { // diff == 2\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n        }\n    };\n\n    // move root to (tx,ty) by Manhattan steps\n    auto moveRootTo = [&](int tx, int ty) {\n        while (curX < tx) {\n            pushTurn('D', '.', '.');\n            ++curX;\n        }\n        while (curX > tx) {\n            pushTurn('U', '.', '.');\n            --curX;\n        }\n        while (curY < ty) {\n            pushTurn('R', '.', '.');\n            ++curY;\n        }\n        while (curY > ty) {\n            pushTurn('L', '.', '.');\n            --curY;\n        }\n    };\n\n    // alive flags\n    vector<char> srcAlive(src.size(), 1);\n    vector<char> dstAlive(dst.size(), 1);\n    int remaining = (int)src.size();\n\n    while (remaining > 0) {\n        // ----- choose nearest source -----\n        int bestDist = INT_MAX;\n        int bestIdx = -1, bestDir = -1, bestRx = -1, bestRy = -1;\n        for (int i = 0; i < (int)src.size(); ++i) if (srcAlive[i]) {\n            const Pos &p = src[i];\n            for (int d = 0; d < 4; ++d) {\n                int rx = p.x - dx[d];\n                int ry = p.y - dy[d];\n                if (0 <= rx && rx < N && 0 <= ry && ry < N) {\n                    int dist = abs(curX - rx) + abs(curY - ry);\n                    if (dist < bestDist) {\n                        bestDist = dist;\n                        bestIdx = i;\n                        bestDir = d;\n                        bestRx = rx;\n                        bestRy = ry;\n                    }\n                }\n            }\n        }\n        // move to source\n        rotateTo(bestDir);\n        moveRootTo(bestRx, bestRy);\n        pushTurn('.', '.', 'P');          // pick up\n        srcAlive[bestIdx] = 0;\n        --remaining;\n\n        // ----- choose nearest target -----\n        int bestDist2 = INT_MAX;\n        int bestIdxT = -1, bestDir2 = -1, bestRx2 = -1, bestRy2 = -1;\n        for (int i = 0; i < (int)dst.size(); ++i) if (dstAlive[i]) {\n            const Pos &p = dst[i];\n            for (int d = 0; d < 4; ++d) {\n                int rx = p.x - dx[d];\n                int ry = p.y - dy[d];\n                if (0 <= rx && rx < N && 0 <= ry && ry < N) {\n                    int rotC = rotCost(curDir, d);\n                    int dist = abs(curX - rx) + abs(curY - ry) + rotC;\n                    if (dist < bestDist2) {\n                        bestDist2 = dist;\n                        bestIdxT = i;\n                        bestDir2 = d;\n                        bestRx2 = rx;\n                        bestRy2 = ry;\n                    }\n                }\n            }\n        }\n        // move to target\n        rotateTo(bestDir2);\n        moveRootTo(bestRx2, bestRy2);\n        pushTurn('.', '.', 'P');          // release\n        dstAlive[bestIdxT] = 0;\n    }\n\n    // output operations\n    for (const string &s : ops) cout << s << \"\\n\";\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ull = unsigned long long;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if(!(cin >> N)) return 0;\n    vector<pair<int,int>> mackerel(N);\n    vector<pair<int,int>> sardine(N);\n    for (int i = 0; i < N; ++i) {\n        int x,y; cin >> x >> y;\n        mackerel[i] = {x,y};\n    }\n    unordered_set<ull> sardineSet;\n    sardineSet.reserve(N*2);\n    for (int i = 0; i < N; ++i) {\n        int x,y; cin >> x >> y;\n        sardine[i] = {x,y};\n        ull key = ( (ull)x << 32 ) | (unsigned int) y;\n        sardineSet.insert(key);\n    }\n    \n    // ------------------------------------------------------------\n    // 1) try to isolate a single mackerel with a 1x1 square\n    for (auto [x,y] : mackerel) {\n        if (x >= 100000 || y >= 100000) continue; // would go out of bounds\n        bool ok = true;\n        for (int dx = 0; dx <= 1 && ok; ++dx) {\n            for (int dy = 0; dy <= 1; ++dy) {\n                int nx = x + dx;\n                int ny = y + dy;\n                ull key = ( (ull)nx << 32 ) | (unsigned int) ny;\n                if (sardineSet.find(key) != sardineSet.end()) {\n                    ok = false;\n                    break;\n                }\n            }\n        }\n        if (ok) {\n            // output rectangle [x,x+1] \u00d7 [y,y+1]\n            cout << 4 << \"\\n\";\n            cout << x << \" \" << y << \"\\n\";\n            cout << x+1 << \" \" << y << \"\\n\";\n            cout << x+1 << \" \" << y+1 << \"\\n\";\n            cout << x << \" \" << y+1 << \"\\n\";\n            return 0;\n        }\n    }\n    \n    // ------------------------------------------------------------\n    // 2) grid cell fallback\n    const int G = 2000;                // side length of a cell\n    const int C = 100000 / G;          // 50, divides exactly\n    vector<vector<int>> mCount(C, vector<int>(C, 0));\n    vector<vector<int>> sCount(C, vector<int>(C, 0));\n    \n    auto cellIdx = [&](int coord) -> int {\n        int idx = coord / G;\n        if (idx >= C) idx = C-1;\n        return idx;\n    };\n    \n    for (auto [x,y] : mackerel) {\n        int cx = cellIdx(x);\n        int cy = cellIdx(y);\n        ++mCount[cx][cy];\n    }\n    for (auto [x,y] : sardine) {\n        int cx = cellIdx(x);\n        int cy = cellIdx(y);\n        ++sCount[cx][cy];\n    }\n    \n    int bestCx = -1, bestCy = -1;\n    int bestNet = INT_MIN;\n    for (int cx = 0; cx < C; ++cx) {\n        for (int cy = 0; cy < C; ++cy) {\n            int net = mCount[cx][cy] - sCount[cx][cy];\n            if (net > bestNet) {\n                bestNet = net;\n                bestCx = cx;\n                bestCy = cy;\n            }\n        }\n    }\n    if (bestNet > 0) {\n        int left   = bestCx * G;\n        int right  = (bestCx + 1) * G;\n        int bottom = bestCy * G;\n        int top    = (bestCy + 1) * G;\n        cout << 4 << \"\\n\";\n        cout << left << \" \" << bottom << \"\\n\";\n        cout << right << \" \" << bottom << \"\\n\";\n        cout << right << \" \" << top << \"\\n\";\n        cout << left << \" \" << top << \"\\n\";\n        return 0;\n    }\n    \n    // ------------------------------------------------------------\n    // 3) whole area fallback\n    cout << 4 << \"\\n\";\n    cout << 0 << \" \" << 0 << \"\\n\";\n    cout << 100000 << \" \" << 0 << \"\\n\";\n    cout << 100000 << \" \" << 100000 << \"\\n\";\n    cout << 0 << \" \" << 100000 << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    long long sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    vector<long long> w(N), h(N);\n    for (int i = 0; i < N; ++i) cin >> w[i] >> h[i];\n\n    for (int turn = 0; turn < T; ++turn) {\n        // place all rectangles in a single row\n        cout << N << '\\n';\n        for (int i = 0; i < N; ++i) {\n            int r = (h[i] > w[i]) ? 1 : 0;          // rotate if observed height is larger\n            int b = (i == 0) ? -1 : i - 1;          // reference rectangle\n            cout << i << ' ' << r << ' ' << 'U' << ' ' << b << '\\n';\n        }\n        cout.flush();                               // required for the interactive protocol\n\n        long long Wp, Hp;\n        if (!(cin >> Wp >> Hp)) break;             // read the noisy box size (ignored)\n    }\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, H;\n    if (!(cin >> N >> M >> H)) return 0;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    // coordinates are irrelevant for the algorithm\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    // sort neighbours by beauty ascending (low beauty first)\n    for (int v = 0; v < N; ++v) {\n        sort(adj[v].begin(), adj[v].end(),\n             [&](int a, int b){ return A[a] < A[b]; });\n    }\n    \n    const int UNASSIGNED = -2;\n    vector<int> parent(N, UNASSIGNED);\n    vector<int> depth(N, -1);\n    \n    // vertices ordered by decreasing beauty\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int i, int j){ return A[i] > A[j]; });\n    \n    queue<pair<int,int>> q;\n    for (int v : order) {\n        if (parent[v] != UNASSIGNED) continue; // already placed\n        // start a new tree with v as root\n        parent[v] = -1;\n        depth[v] = 0;\n        q.emplace(v, 0);\n        while (!q.empty()) {\n            auto [u, d] = q.front(); q.pop();\n            if (d == H) continue; // cannot go deeper\n            for (int w : adj[u]) {\n                if (parent[w] == UNASSIGNED) {\n                    parent[w] = u;\n                    depth[w] = d + 1;\n                    q.emplace(w, d + 1);\n                }\n            }\n        }\n    }\n    \n    // output\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << parent[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    // groups: for each row/column we store the distances of the assigned Oni\n    vector<vector<int>> rowLeft(N), rowRight(N), colUp(N), colDown(N);\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] != 'x') continue;          // not an Oni\n            // safety checks\n            bool safeU = true, safeD = true, safeL = true, safeR = true;\n            for (int k = 0; k < i; ++k) if (board[k][j] == 'o') safeU = false;\n            for (int k = i + 1; k < N; ++k) if (board[k][j] == 'o') safeD = false;\n            for (int k = 0; k < j; ++k) if (board[i][k] == 'o') safeL = false;\n            for (int k = j + 1; k < N; ++k) if (board[i][k] == 'o') safeR = false;\n\n            int dU = i + 1;\n            int dD = N - i;\n            int dL = j + 1;\n            int dR = N - j;\n\n            // choose the safe direction with minimal distance\n            char chosen = '?';\n            int bestDist = INT_MAX;\n            if (safeU && dU < bestDist) { bestDist = dU; chosen = 'U'; }\n            if (safeD && dD < bestDist) { bestDist = dD; chosen = 'D'; }\n            if (safeL && dL < bestDist) { bestDist = dL; chosen = 'L'; }\n            if (safeR && dR < bestDist) { bestDist = dR; chosen = 'R'; }\n\n            // assign to the corresponding group\n            if (chosen == 'U') colUp[j].push_back(bestDist);\n            else if (chosen == 'D') colDown[j].push_back(bestDist);\n            else if (chosen == 'L') rowLeft[i].push_back(bestDist);\n            else if (chosen == 'R') rowRight[i].push_back(bestDist);\n            // the problem guarantees at least one safe direction\n        }\n    }\n\n    vector<pair<char,int>> ops;\n\n    // process column groups first (any order is fine)\n    for (int j = 0; j < N; ++j) {\n        if (!colUp[j].empty()) {\n            int mx = *max_element(colUp[j].begin(), colUp[j].end());\n            for (int k = 0; k < mx; ++k) ops.emplace_back('U', j);\n            for (int k = 0; k < mx; ++k) ops.emplace_back('D', j);\n        }\n        if (!colDown[j].empty()) {\n            int mx = *max_element(colDown[j].begin(), colDown[j].end());\n            for (int k = 0; k < mx; ++k) ops.emplace_back('D', j);\n            for (int k = 0; k < mx; ++k) ops.emplace_back('U', j);\n        }\n    }\n    // then row groups\n    for (int i = 0; i < N; ++i) {\n        if (!rowLeft[i].empty()) {\n            int mx = *max_element(rowLeft[i].begin(), rowLeft[i].end());\n            for (int k = 0; k < mx; ++k) ops.emplace_back('L', i);\n            for (int k = 0; k < mx; ++k) ops.emplace_back('R', i);\n        }\n        if (!rowRight[i].empty()) {\n            int mx = *max_element(rowRight[i].begin(), rowRight[i].end());\n            for (int k = 0; k < mx; ++k) ops.emplace_back('R', i);\n            for (int k = 0; k < mx; ++k) ops.emplace_back('L', i);\n        }\n    }\n\n    // output\n    for (auto [d, p] : ops) {\n        cout << d << ' ' << p << '\\n';\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\n// ------------------------------------------------------------\n// simulate the process and return the error \u03a3|cnt[i] - T[i]|\nstatic ll simulate_error(const vector<int> &a,\n                         const vector<int> &b,\n                         const vector<int> &T,\n                         long long L,\n                         ll early_stop = LLONG_MAX)   // abort if error already > early_stop\n{\n    const int N = (int)a.size();\n    static int cnt[200];               // N \u2264 100, static to avoid reallocation\n    for (int i = 0; i < N; ++i) cnt[i] = 0;\n\n    int cur = 0;\n    for (long long step = 0; step < L; ++step) {\n        int t = cnt[cur];\n        ++cnt[cur];\n        cur = (t & 1) ? a[cur] : b[cur];\n    }\n\n    ll err = 0;\n    for (int i = 0; i < N; ++i) {\n        err += llabs(static_cast<ll>(cnt[i]) - static_cast<ll>(T[i]));\n        if (err > early_stop) return err;   // early abort, not essential\n    }\n    return err;\n}\n\n// ------------------------------------------------------------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    long long L;\n    if (!(cin >> N >> L)) return 0;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    const double target_factor = (2.0 * N) / static_cast<double>(L); // 2N / L\n\n    // ---------- compute desired extra indegree ----------\n    vector<double> w(N);\n    for (int i = 0; i < N; ++i) w[i] = T[i] * target_factor; // expected indegree\n\n    vector<int> extra(N, 0);\n    vector<double> rem(N, 0.0);\n    int sum_extra = 0;\n    for (int i = 0; i < N; ++i) {\n        double val = w[i] - 1.0;               // we already have 1 from the cycle\n        if (val <= 0.0) {\n            extra[i] = 0;\n            rem[i] = val;                      // negative, will never be chosen\n        } else {\n            extra[i] = static_cast<int>(floor(val));\n            rem[i] = val - extra[i];\n            sum_extra += extra[i];\n        }\n    }\n\n    int need = N - sum_extra;                  // how many extra edges are still missing\n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    if (need > 0) {\n        sort(idx.begin(), idx.end(),\n             [&](int a, int b) { return rem[a] > rem[b]; });\n        for (int k = 0; k < need; ++k) ++extra[idx[k]];\n    } else if (need < 0) {\n        sort(idx.begin(), idx.end(),\n             [&](int a, int b) { return rem[a] < rem[b]; });\n        for (int k = 0; k < -need; ++k) {\n            int i = idx[k];\n            if (extra[i] > 0) --extra[i];\n        }\n    }\n    // now \u03a3 extra[i] == N\n\n    // ---------- build the graph ----------\n    // a[i] : a random Hamiltonian cycle (permutation)\n    vector<int> a(N), b(N);\n    vector<int> perm(N);\n    iota(perm.begin(), perm.end(), 0);\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    shuffle(perm.begin(), perm.end(), rng);\n    for (int i = 0; i < N; ++i) a[i] = perm[i];\n\n    // b[i] : distribute the remaining N edges according to extra[\u00b7]\n    vector<int> pool;\n    pool.reserve(N);\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < extra[i]; ++k) pool.push_back(i);\n    }\n    // pool size must be exactly N\n    if ((int)pool.size() != N) {\n        // fallback \u2013 fill missing entries with random nodes\n        while ((int)pool.size() < N) pool.push_back(rng() % N);\n        while ((int)pool.size() > N) pool.pop_back();\n    }\n    shuffle(pool.begin(), pool.end(), rng);\n    for (int i = 0; i < N; ++i) b[i] = pool[i];\n\n    // ---------- initial error ----------\n    ll best_err = simulate_error(a, b, T, L);\n    vector<int> best_a = a, best_b = b;\n\n    // ---------- hill climbing on b[\u00b7] ----------\n    const double TIME_LIMIT = 1.8; // seconds\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        int i1 = rng() % N;\n        int i2 = rng() % N;\n        if (i1 == i2) continue;\n        swap(b[i1], b[i2]);\n\n        ll cur_err = simulate_error(a, b, T, L, best_err);\n        if (cur_err < best_err) {\n            best_err = cur_err;\n            best_a = a;\n            best_b = b;\n        } else {\n            // revert\n            swap(b[i1], b[i2]);\n        }\n    }\n\n    // ---------- output ----------\n    for (int i = 0; i < N; ++i) {\n        cout << best_a[i] << ' ' << best_b[i] << '\\n';\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    // read rectangle data, keep only the centre coordinates\n    vector<int> lx(N), rx(N), ly(N), ry(N);\n    vector<long long> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n        cx[i] = (static_cast<long long>(lx[i]) + rx[i]) / 2;\n        cy[i] = (static_cast<long long>(ly[i]) + ry[i]) / 2;\n    }\n\n    // sort indices by centre (lexicographic)\n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(),\n        [&](int a, int b) {\n            if (cx[a] != cx[b]) return cx[a] < cx[b];\n            return cy[a] < cy[b];\n        });\n\n    // split into groups according to G\n    vector<vector<int>> groups;\n    groups.reserve(M);\n    int pos = 0;\n    for (int i = 0; i < M; ++i) {\n        vector<int> g;\n        g.reserve(G[i]);\n        for (int j = 0; j < G[i]; ++j) {\n            g.push_back(idx[pos++]);\n        }\n        groups.push_back(move(g));\n    }\n\n    // store edges for each group\n    vector<vector<pair<int,int>>> groupEdges(M);\n\n    // ----- perform queries for small groups -----\n    for (int gi = 0; gi < M; ++gi) {\n        const auto &g = groups[gi];\n        int sz = static_cast<int>(g.size());\n        if (sz <= 1) continue;                // nothing to do\n        if (sz <= L) {\n            // query the whole group\n            cout << \"? \" << sz;\n            for (int v : g) cout << ' ' << v;\n            cout << \"\\n\" << flush;\n\n            // read sz-1 edges\n            vector<pair<int,int>> edges;\n            edges.reserve(sz - 1);\n            for (int i = 0; i < sz - 1; ++i) {\n                int a, b;\n                cin >> a >> b;\n                edges.emplace_back(a, b);\n            }\n            groupEdges[gi] = move(edges);\n        } else {\n            // chain (fallback)\n            vector<pair<int,int>> edges;\n            edges.reserve(sz - 1);\n            for (int i = 0; i + 1 < sz; ++i) {\n                edges.emplace_back(g[i], g[i+1]);\n            }\n            groupEdges[gi] = move(edges);\n        }\n    }\n\n    // ----- output final answer -----\n    cout << \"!\\n\";\n    for (int gi = 0; gi < M; ++gi) {\n        const auto &g = groups[gi];\n        // line with cities of the group\n        for (size_t i = 0; i < g.size(); ++i) {\n            if (i) cout << ' ';\n            cout << g[i];\n        }\n        cout << \"\\n\";\n        // edges\n        for (auto [a,b] : groupEdges[gi]) {\n            cout << a << ' ' << b << \"\\n\";\n        }\n    }\n    cout.flush();\n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<pair<int,int>> pos(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> pos[i].first >> pos[i].second;\n    }\n\n    int cur_r = pos[0].first;\n    int cur_c = pos[0].second;\n\n    // we will output actions directly to stdout\n    for (int idx = 1; idx < M; ++idx) {\n        int tr = pos[idx].first;\n        int tc = pos[idx].second;\n\n        // vertical movement\n        while (cur_r < tr) {\n            cout << \"M D\\n\";\n            ++cur_r;\n        }\n        while (cur_r > tr) {\n            cout << \"M U\\n\";\n            --cur_r;\n        }\n        // horizontal movement\n        while (cur_c < tc) {\n            cout << \"M R\\n\";\n            ++cur_c;\n        }\n        while (cur_c > tc) {\n            cout << \"M L\\n\";\n            --cur_c;\n        }\n    }\n    // No need to output anything else.\n    return 0;\n}"},"4":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    long long r;\n    int idx;\n};\n\nint n;\nvector<Point> pt;\nvector<int> ans_a, ans_b, ans_c, ans_d;\n\n/* -------------------------------------------------------------\n   leaf rectangle \u2013 try to choose width/height that best matches\n   the desired area while still containing the point.\n   ------------------------------------------------------------- */\nvoid allocate_leaf(int x0, int x1, int y0, int y1, const Point& p) {\n    int width  = x1 - x0;\n    int height = y1 - y0;\n    long long want = p.r;\n\n    int best_w = width, best_h = height;\n    long long best_diff = LLONG_MAX;\n\n    // try all possible widths (1 \u2026 width)\n    for (int w = 1; w <= width; ++w) {\n        // two candidates for height: floor and ceil of want/w\n        long long h_floor = want / w;\n        long long h_ceil  = (want + w - 1) / w;\n\n        for (long long h_raw : {h_floor, h_ceil}) {\n            if (h_raw < 1) continue;\n            if (h_raw > height) continue;\n            int h = (int)h_raw;\n\n            // check that the rectangle can be placed so that (x,y) is inside\n            int a_low  = max(x0, p.x - w + 1);\n            int a_high = min(p.x, x1 - w);\n            if (a_low > a_high) continue;\n            int b_low  = max(y0, p.y - h + 1);\n            int b_high = min(p.y, y1 - h);\n            if (b_low > b_high) continue;\n\n            long long area = 1LL * w * h;\n            long long diff = llabs(area - want);\n            if (diff < best_diff) {\n                best_diff = diff;\n                best_w = w;\n                best_h = h;\n            }\n        }\n    }\n\n    // place the rectangle as far left / bottom as possible inside the leaf\n    int a_low  = max(x0, p.x - best_w + 1);\n    int a_high = min(p.x, x1 - best_w);\n    int a = a_low;                     // any value in [a_low, a_high] works\n    int b_low  = max(y0, p.y - best_h + 1);\n    int b_high = min(p.y, y1 - best_h);\n    int b = b_low;                     // any value in [b_low, b_high] works\n\n    ans_a[p.idx] = a;\n    ans_b[p.idx] = b;\n    ans_c[p.idx] = a + best_w;\n    ans_d[p.idx] = b + best_h;\n}\n\n/* -------------------------------------------------------------\n   recursive guillotine partition\n   ------------------------------------------------------------- */\nvoid solve_region(int x0, int x1, int y0, int y1,\n                  const vector<int>& ids) {\n    if (ids.empty()) return;\n    if (ids.size() == 1) {\n        allocate_leaf(x0, x1, y0, y1, pt[ids[0]]);\n        return;\n    }\n\n    int width  = x1 - x0;\n    int height = y1 - y0;\n    bool vertical = (width >= height);\n\n    if (vertical) {\n        // ----- vertical cut -------------------------------------------------\n        vector<int> sorted = ids;\n        sort(sorted.begin(), sorted.end(),\n             [&](int a, int b){ return pt[a].x < pt[b].x; });\n\n        // prefix sums of r\n        vector<long long> pref(sorted.size());\n        for (size_t i = 0; i < sorted.size(); ++i) {\n            pref[i] = pt[sorted[i]].r + (i ? pref[i-1] : 0);\n        }\n\n        long long bestDiff = LLONG_MAX;\n        int bestX = -1;                     // cut column (absolute coordinate)\n\n        for (size_t k = 0; k + 1 < sorted.size(); ++k) {\n            long long sumLeft = pref[k];\n            int leftMaxX  = pt[sorted[k]].x;\n            int rightMinX = pt[sorted[k+1]].x;\n\n            // ideal width to host sumLeft area\n            long long needW = (sumLeft + height - 1) / height; // ceil\n            int X = x0 + (int)needW;\n\n            // enforce that the cut lies between the two point columns\n            if (X <= leftMaxX) X = leftMaxX + 1;\n            if (X >  rightMinX) X = rightMinX;\n            if (X <= x0) X = x0 + 1;\n            if (X >= x1) X = x1 - 1;\n\n            long long areaLeft = 1LL * (X - x0) * height;\n            long long diff = llabs(areaLeft - sumLeft);\n            if (diff < bestDiff) {\n                bestDiff = diff;\n                bestX = X;\n            }\n        }\n\n        // fallback: split in the middle if no suitable cut was found\n        if (bestX == -1) {\n            bestX = x0 + width / 2;\n            if (bestX == x0) bestX = x0 + 1;\n            if (bestX == x1) bestX = x1 - 1;\n        }\n\n        // partition ids\n        vector<int> leftIds, rightIds;\n        for (int id : ids) {\n            if (pt[id].x < bestX) leftIds.push_back(id);\n            else                 rightIds.push_back(id);\n        }\n\n        // if a side became empty (possible when many points share the same x)\n        if (leftIds.empty() || rightIds.empty()) {\n            bestX = (x0 + x1) / 2;\n            if (bestX == x0) bestX = x0 + 1;\n            if (bestX == x1) bestX = x1 - 1;\n            leftIds.clear(); rightIds.clear();\n            for (int id : ids) {\n                if (pt[id].x < bestX) leftIds.push_back(id);\n                else                 rightIds.push_back(id);\n            }\n        }\n\n        solve_region(x0, bestX, y0, y1, leftIds);\n        solve_region(bestX, x1, y0, y1, rightIds);\n    } else {\n        // ----- horizontal cut ------------------------------------------------\n        vector<int> sorted = ids;\n        sort(sorted.begin(), sorted.end(),\n             [&](int a, int b){ return pt[a].y < pt[b].y; });\n\n        vector<long long> pref(sorted.size());\n        for (size_t i = 0; i < sorted.size(); ++i) {\n            pref[i] = pt[sorted[i]].r + (i ? pref[i-1] : 0);\n        }\n\n        long long bestDiff = LLONG_MAX;\n        int bestY = -1;                     // cut row (absolute coordinate)\n\n        for (size_t k = 0; k + 1 < sorted.size(); ++k) {\n            long long sumTop = pref[k];\n            int topMaxY    = pt[sorted[k]].y;\n            int bottomMinY = pt[sorted[k+1]].y;\n\n            long long needH = (sumTop + width - 1) / width; // ceil\n            int Y = y0 + (int)needH;\n\n            if (Y <= topMaxY)   Y = topMaxY + 1;\n            if (Y >  bottomMinY) Y = bottomMinY;\n            if (Y <= y0) Y = y0 + 1;\n            if (Y >= y1) Y = y1 - 1;\n\n            long long areaTop = 1LL * (Y - y0) * width;\n            long long diff = llabs(areaTop - sumTop);\n            if (diff < bestDiff) {\n                bestDiff = diff;\n                bestY = Y;\n            }\n        }\n\n        if (bestY == -1) {\n            bestY = y0 + height / 2;\n            if (bestY == y0) bestY = y0 + 1;\n            if (bestY == y1) bestY = y1 - 1;\n        }\n\n        vector<int> topIds, botIds;\n        for (int id : ids) {\n            if (pt[id].y < bestY) topIds.push_back(id);\n            else                  botIds.push_back(id);\n        }\n\n        if (topIds.empty() || botIds.empty()) {\n            bestY = (y0 + y1) / 2;\n            if (bestY == y0) bestY = y0 + 1;\n            if (bestY == y1) bestY = y1 - 1;\n            topIds.clear(); botIds.clear();\n            for (int id : ids) {\n                if (pt[id].y < bestY) topIds.push_back(id);\n                else                  botIds.push_back(id);\n            }\n        }\n\n        solve_region(x0, x1, y0, bestY, topIds);\n        solve_region(x0, x1, bestY, y1, botIds);\n    }\n}\n\n/* ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> n)) return 0;\n    pt.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> pt[i].x >> pt[i].y >> pt[i].r;\n        pt[i].idx = i;\n    }\n\n    ans_a.assign(n, 0);\n    ans_b.assign(n, 0);\n    ans_c.assign(n, 0);\n    ans_d.assign(n, 0);\n\n    vector<int> all_ids(n);\n    iota(all_ids.begin(), all_ids.end(), 0);\n    solve_region(0, 10000, 0, 10000, all_ids);\n\n    for (int i = 0; i < n; ++i) {\n        cout << ans_a[i] << ' ' << ans_b[i] << ' '\n             << ans_c[i] << ' ' << ans_d[i] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 50;\nconstexpr int DIRS = 4;\nconstexpr char DIR_CHAR[DIRS] = {'U', 'D', 'L', 'R'};\nconstexpr int DX[DIRS] = {-1, 1, 0, 0};\nconstexpr int DY[DIRS] = {0, 0, -1, 1};\n\nusing Clock = chrono::steady_clock;\nusing ms    = chrono::milliseconds;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    if (!(cin >> si >> sj)) return 0;\n\n    vector<vector<int>> tile(N, vector<int>(N));\n    int maxTile = -1;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> tile[i][j];\n            maxTile = max(maxTile, tile[i][j]);\n        }\n    }\n    const int M = maxTile + 1;                 // number of tiles\n\n    vector<vector<int>> val(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> val[i][j];\n\n    // random generator\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n\n    // visited array \u2013 we use a run id to avoid clearing\n    vector<int> visited(M, 0);\n    int curRunId = 1;                         // will be increased each run\n\n    string bestPath;\n    long long bestScore = -1;\n\n    const int TIME_LIMIT_MS = 1900;           // leave a margin\n    auto startTime = Clock::now();\n\n    // helper: degree of a cell (number of still unvisited neighbour tiles)\n    auto degree = [&](int x, int y, const vector<int>& vis) -> int {\n        int deg = 0;\n        int curTile = tile[x][y];\n        for (int d = 0; d < DIRS; ++d) {\n            int nx = x + DX[d];\n            int ny = y + DY[d];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            int t = tile[nx][ny];\n            if (t == curTile) continue;               // same tile (already visited)\n            if (vis[t] != curRunId) ++deg;\n        }\n        return deg;\n    };\n\n    // helper: short random playout (depth = DEPTH) from (x,y) with a copy of visited\n    auto simulate = [&](int x, int y, const vector<int>& vis, int DEPTH) -> int {\n        vector<int> copyVis = vis;                     // copy of visited flags\n        int sum = 0;\n        int cx = x, cy = y;\n        for (int step = 0; step < DEPTH; ++step) {\n            vector<int> cand;\n            for (int d = 0; d < DIRS; ++d) {\n                int nx = cx + DX[d];\n                int ny = cy + DY[d];\n                if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                int t = tile[nx][ny];\n                if (copyVis[t] == curRunId) continue;\n                cand.push_back(d);\n            }\n            if (cand.empty()) break;\n            int d = cand[rng() % cand.size()];\n            cx += DX[d];\n            cy += DY[d];\n            int t = tile[cx][cy];\n            copyVis[t] = curRunId;\n            sum += val[cx][cy];\n        }\n        return sum;\n    };\n\n    // main loop \u2013 run many random walks until time runs out\n    while (true) {\n        auto now = Clock::now();\n        if (chrono::duration_cast<ms>(now - startTime).count() > TIME_LIMIT_MS) break;\n\n        // pick a heuristic mode (0\u20264)\n        int mode = uniform_int_distribution<int>(0, 4)(rng);\n        // for mode 3 (weighted) we also pick random weights\n        double w_val = uniform_real_distribution<double>(0.0, 1.0)(rng);\n        double w_deg = uniform_real_distribution<double>(0.0, 1.0)(rng);\n\n        // initialise visited flags for this run\n        ++curRunId;                                 // new id\n        visited[tile[si][sj]] = curRunId;            // start tile already used\n\n        int ci = si, cj = sj;\n        long long curScore = val[ci][cj];\n        string curPath;\n\n        while (true) {\n            // collect admissible neighbours\n            vector<int> candDir;\n            vector<double> candScore;\n            for (int d = 0; d < DIRS; ++d) {\n                int nx = ci + DX[d];\n                int ny = cj + DY[d];\n                if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                int t = tile[nx][ny];\n                if (visited[t] == curRunId) continue;   // already used tile\n\n                double sc = 0.0;\n                if (mode == 0) {                         // max immediate value\n                    sc = val[nx][ny];\n                } else if (mode == 1) {                  // max degree\n                    sc = degree(nx, ny, visited);\n                } else if (mode == 2) {                  // min degree (Warnsdorff)\n                    sc = -degree(nx, ny, visited);\n                } else if (mode == 3) {                  // weighted combination\n                    int deg = degree(nx, ny, visited);\n                    sc = w_val * val[nx][ny] + w_deg * deg;\n                } else {                                 // mode == 4, look\u2011ahead\n                    const int DEPTH = 6;\n                    // mark the neighbour tile as visited for the simulation\n                    vector<int> tempVis = visited;\n                    tempVis[t] = curRunId;\n                    int sim = simulate(nx, ny, tempVis, DEPTH);\n                    sc = val[nx][ny] + sim;\n                }\n\n                candDir.push_back(d);\n                candScore.push_back(sc);\n            }\n\n            if (candDir.empty()) break;                 // dead end\n\n            // choose the best (ties random)\n            double best = candScore[0];\n            vector<int> bestIdx = {0};\n            for (size_t i = 1; i < candScore.size(); ++i) {\n                if (candScore[i] > best) {\n                    best = candScore[i];\n                    bestIdx.clear();\n                    bestIdx.push_back(i);\n                } else if (candScore[i] == best) {\n                    bestIdx.push_back(i);\n                }\n            }\n            int chosen = bestIdx[rng() % bestIdx.size()];\n            int d = candDir[chosen];\n\n            // perform the move\n            ci += DX[d];\n            cj += DY[d];\n            curPath.push_back(DIR_CHAR[d]);\n            visited[tile[ci][cj]] = curRunId;\n            curScore += val[ci][cj];\n        }\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestPath = curPath;\n        }\n    }\n\n    cout << bestPath << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;                     // grid size\nconstexpr int V = N * N;                 // number of vertices\nconstexpr double INF = 1e100;\nconstexpr double INIT_WEIGHT = 5000.0;    // initial estimate for every edge\nconstexpr double LR = 0.01;              // learning rate\n\ninline int node_id(int i, int j) { return i * N + j; }\ninline pair<int,int> id_to_coord(int id) { return {id / N, id % N}; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    /*  edge weights:\n       horizontal:  i = 0..29, j = 0..28   \u2192 index = i*(N-1)+j   (size N*(N-1))\n       vertical:    i = 0..28, j = 0..29   \u2192 index = i*N + j     (size (N-1)*N)\n    */\n    const int Hcnt = N * (N - 1);\n    const int Vcnt = (N - 1) * N;\n    vector<double> h(Hcnt, INIT_WEIGHT);\n    vector<double> v(Vcnt, INIT_WEIGHT);\n\n    for (int query = 0; query < 1000; ++query) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) return 0;   // EOF safety\n        int s = node_id(si, sj);\n        int t = node_id(ti, tj);\n\n        /* ---------- Dijkstra with current estimates ---------- */\n        vector<double> dist(V, INF);\n        vector<int> parent(V, -1);\n        vector<char> move(V, 0);\n        dist[s] = 0.0;\n        using P = pair<double,int>;\n        priority_queue<P, vector<P>, greater<P>> pq;\n        pq.emplace(0.0, s);\n\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u]) continue;\n            if (u == t) break;\n            auto [i, j] = id_to_coord(u);\n\n            // up\n            if (i > 0) {\n                int nb = node_id(i-1, j);\n                double w = v[(i-1)*N + j];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'U';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // down\n            if (i < N-1) {\n                int nb = node_id(i+1, j);\n                double w = v[i*N + j];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'D';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // left\n            if (j > 0) {\n                int nb = node_id(i, j-1);\n                double w = h[i*(N-1) + (j-1)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'L';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // right\n            if (j < N-1) {\n                int nb = node_id(i, j+1);\n                double w = h[i*(N-1) + j];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move[nb] = 'R';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n        }\n\n        /* ---------- reconstruct the path ---------- */\n        vector<char> rev_path;\n        // each entry: (isHorizontal, index)\n        vector<pair<bool,int>> rev_edges;\n        int cur = t;\n        while (cur != s) {\n            int p = parent[cur];\n            char d = move[cur];\n            rev_path.push_back(d);\n            auto [ci, cj] = id_to_coord(cur);\n            auto [pi, pj] = id_to_coord(p);\n            if (ci == pi + 1 && cj == pj) {               // moved down\n                rev_edges.emplace_back(false, pi * N + pj); // vertical edge (top node)\n            } else if (ci == pi - 1 && cj == pj) {        // moved up\n                rev_edges.emplace_back(false, ci * N + cj);\n            } else if (cj == pj + 1 && ci == pi) {        // moved right\n                rev_edges.emplace_back(true, pi * (N-1) + pj);\n            } else if (cj == pj - 1 && ci == pi) {        // moved left\n                rev_edges.emplace_back(true, ci * (N-1) + cj);\n            }\n            cur = p;\n        }\n        reverse(rev_path.begin(), rev_path.end());\n        reverse(rev_edges.begin(), rev_edges.end());\n\n        string out_path;\n        out_path.reserve(rev_path.size());\n        for (char c : rev_path) out_path.push_back(c);\n\n        /* ---------- output and flush ---------- */\n        cout << out_path << '\\n' << flush;\n\n        /* ---------- read noisy length ---------- */\n        long long L;\n        if (!(cin >> L)) return 0;   // safety\n\n        /* ---------- update edge estimates ---------- */\n        double est = 0.0;\n        for (auto &e : rev_edges) {\n            if (e.first)  // horizontal\n                est += h[e.second];\n            else\n                est += v[e.second];\n        }\n        double err = est - static_cast<double>(L);\n        int plen = static_cast<int>(rev_edges.size());\n        if (plen > 0) {\n            double delta = LR * err / plen;\n            for (auto &e : rev_edges) {\n                if (e.first) {\n                    h[e.second] -= delta;\n                    if (h[e.second] < 1.0) h[e.second] = 1.0;\n                } else {\n                    v[e.second] -= delta;\n                    if (v[e.second] < 1.0) v[e.second] = 1.0;\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int MAX_N = 20;\nconstexpr int MAX_LEN = 12;\nconstexpr uint8_t EMPTY = 8;          // value for '.' (unused after fill)\n\nstruct Placement {\n    uint8_t len;                      // length of the string (\u226412)\n    uint16_t cells[MAX_LEN];          // linear cell indices (0 \u2026 399)\n    uint8_t  need[MAX_LEN];           // required character (0 \u2026 7)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<string> S(M);\n    for (int i = 0; i < M; ++i) cin >> S[i];\n\n    /* ---------- pre\u2011compute all placements ---------- */\n    vector<vector<Placement>> placements(M);\n    placements.reserve(M);\n    for (int i = 0; i < M; ++i) {\n        const string &st = S[i];\n        int L = (int)st.size();\n        placements[i].reserve(2 * N * N);\n        // horizontal\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                Placement p;\n                p.len = (uint8_t)L;\n                for (int k = 0; k < L; ++k) {\n                    int col = (c + k) % N;\n                    p.cells[k] = (uint16_t)(r * N + col);\n                    p.need[k] = (uint8_t)(st[k] - 'A');   // 0 \u2026 7\n                }\n                placements[i].push_back(p);\n            }\n        }\n        // vertical\n        for (int c = 0; c < N; ++c) {\n            for (int r = 0; r < N; ++r) {\n                Placement p;\n                p.len = (uint8_t)L;\n                for (int k = 0; k < L; ++k) {\n                    int row = (r + k) % N;\n                    p.cells[k] = (uint16_t)(row * N + c);\n                    p.need[k] = (uint8_t)(st[k] - 'A');\n                }\n                placements[i].push_back(p);\n            }\n        }\n    }\n\n    /* ---------- helper: count satisfied strings ---------- */\n    auto countSatisfied = [&](const vector<uint8_t> &mat) -> int {\n        int cnt = 0;\n        for (int i = 0; i < M; ++i) {\n            const auto &pls = placements[i];\n            bool ok = false;\n            for (const Placement &p : pls) {\n                bool good = true;\n                for (int k = 0; k < p.len; ++k) {\n                    if (mat[p.cells[k]] != p.need[k]) {\n                        good = false;\n                        break;\n                    }\n                }\n                if (good) { ok = true; break; }\n            }\n            if (ok) ++cnt;\n        }\n        return cnt;\n    };\n\n    /* ---------- main heuristic ---------- */\n    std::mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> distChar(0, 7);\n\n    const double TIME_LIMIT = 2.9;          // seconds per test case\n    auto startTime = chrono::steady_clock::now();\n\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    vector<int> length(M);\n    for (int i = 0; i < M; ++i) length[i] = (int)S[i].size();\n\n    int bestScore = -1;\n    vector<uint8_t> bestMat(N * N, EMPTY);\n\n    const int MIN_ITER = 30;                // guarantee enough exploration\n    int iter = 0;\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT && iter >= MIN_ITER) break;\n\n        // ----- order for this iteration -----\n        if (iter % 2 == 0) {\n            shuffle(order.begin(), order.end(), rng);\n        } else {\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     if (length[a] != length[b]) return length[a] > length[b];\n                     return a < b;\n                 });\n        }\n\n        // ----- greedy construction -----\n        vector<uint8_t> mat(N * N, EMPTY);\n        for (int idx : order) {\n            const auto &pls = placements[idx];\n            int bestPl = -1;\n            int bestOverlap = -1;\n            for (int pi = 0; pi < (int)pls.size(); ++pi) {\n                const Placement &p = pls[pi];\n                bool conflict = false;\n                int overlap = 0;\n                for (int k = 0; k < p.len; ++k) {\n                    uint8_t cur = mat[p.cells[k]];\n                    uint8_t need = p.need[k];\n                    if (cur != EMPTY && cur != need) {\n                        conflict = true;\n                        break;\n                    }\n                    if (cur == need) ++overlap;\n                }\n                if (conflict) continue;\n                if (overlap > bestOverlap) {\n                    bestOverlap = overlap;\n                    bestPl = pi;\n                    if (overlap == p.len) break;   // perfect match\n                }\n            }\n            if (bestPl != -1) {\n                const Placement &p = pls[bestPl];\n                for (int k = 0; k < p.len; ++k) {\n                    uint16_t cell = p.cells[k];\n                    if (mat[cell] == EMPTY) mat[cell] = p.need[k];\n                }\n            }\n        }\n\n        // ----- fill remaining empty cells with random letters -----\n        for (int i = 0; i < N * N; ++i) {\n            if (mat[i] == EMPTY) mat[i] = (uint8_t)distChar(rng);\n        }\n\n        // ----- evaluate -----\n        int satisfied = countSatisfied(mat);\n        if (satisfied > bestScore) {\n            bestScore = satisfied;\n            bestMat = mat;\n        }\n        ++iter;\n    }\n\n    /* ---------- output the best matrix ---------- */\n    for (int r = 0; r < N; ++r) {\n        string line;\n        line.reserve(N);\n        for (int c = 0; c < N; ++c) {\n            uint8_t v = bestMat[r * N + c];\n            line.push_back(char('A' + v));   // v is 0 \u2026 7\n        }\n        cout << line << '\\n';\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll INF = (1LL << 60);\n\n/*** 1.  Input & basic structures ***/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, si, sj;\n    if (!(cin >> N >> si >> sj)) return 0;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n\n    // assign an id to every road cell\n    vector<vector<int>> id(N, vector<int>(N, -1));\n    vector<int> row, col, cost;          // by id\n    int r = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                id[i][j] = r++;\n                row.push_back(i);\n                col.push_back(j);\n                cost.push_back(grid[i][j] - '0');\n            }\n        }\n    }\n    int startId = id[si][sj];\n\n    // adjacency list (directed: moving to neighbour costs neighbour's cost)\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    vector<vector<pair<int,int>>> adj(r);\n    for (int v = 0; v < r; ++v) {\n        int i = row[v], j = col[v];\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d], nj = j + dy[d];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (grid[ni][nj] == '#') continue;\n            int to = id[ni][nj];\n            adj[v].push_back({to, cost[to]});\n        }\n    }\n\n    /*** 2.  Build the set of representatives (one per maximal segment) ***/\n    vector<char> isRep(r, 0);\n    vector<int> reps;               // ids of representatives\n\n    // horizontal segments\n    for (int i = 0; i < N; ++i) {\n        int j = 0;\n        while (j < N) {\n            if (grid[i][j] == '#') { ++j; continue; }\n            int start = j;\n            while (j < N && grid[i][j] != '#') ++j;\n            // segment [start, j-1]\n            int repId = id[i][start];          // leftmost cell\n            if (!isRep[repId]) {\n                isRep[repId] = 1;\n                reps.push_back(repId);\n            }\n        }\n    }\n    // vertical segments\n    for (int j = 0; j < N; ++j) {\n        int i = 0;\n        while (i < N) {\n            if (grid[i][j] == '#') { ++i; continue; }\n            int start = i;\n            while (i < N && grid[i][j] != '#') ++i;\n            // segment [start, i-1]\n            int repId = id[start][j];          // topmost cell\n            if (!isRep[repId]) {\n                isRep[repId] = 1;\n                reps.push_back(repId);\n            }\n        }\n    }\n    // ensure start cell is a representative\n    if (!isRep[startId]) {\n        isRep[startId] = 1;\n        reps.push_back(startId);\n    }\n\n    int m = (int)reps.size();               // number of representatives\n    // map from road id to index in reps vector\n    unordered_map<int,int> repIdxOfId;\n    repIdxOfId.reserve(m*2);\n    for (int i = 0; i < m; ++i) repIdxOfId[reps[i]] = i;\n\n    /*** 3.  All\u2011pairs shortest paths from each representative ***/\n    vector<vector<ll>> dist(m, vector<ll>(r, INF));\n    vector<vector<int>> parent(m, vector<int>(r, -1));\n\n    using P = pair<ll,int>;\n    for (int k = 0; k < m; ++k) {\n        int src = reps[k];\n        priority_queue<P, vector<P>, greater<P>> pq;\n        dist[k][src] = 0;\n        pq.emplace(0LL, src);\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d != dist[k][u]) continue;\n            for (auto [v, w] : adj[u]) {\n                ll nd = d + w;\n                if (nd < dist[k][v]) {\n                    dist[k][v] = nd;\n                    parent[k][v] = u;\n                    pq.emplace(nd, v);\n                }\n            }\n        }\n    }\n\n    // distance matrix between representatives (directed)\n    vector<vector<ll>> repDist(m, vector<ll>(m, INF));\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < m; ++j) {\n            repDist[i][j] = dist[i][reps[j]];\n        }\n    }\n\n    /*** 4.  Initial tour \u2013 nearest neighbour ***/\n    int startIdx = repIdxOfId[startId];\n    vector<char> visitedRep(m, 0);\n    vector<int> order;          // indices into reps, first element = startIdx\n    order.reserve(m);\n    order.push_back(startIdx);\n    visitedRep[startIdx] = 1;\n    int cur = startIdx;\n    for (int cnt = 1; cnt < m; ++cnt) {\n        ll best = INF;\n        int bestIdx = -1;\n        for (int j = 0; j < m; ++j) if (!visitedRep[j]) {\n            if (repDist[cur][j] < best) {\n                best = repDist[cur][j];\n                bestIdx = j;\n            }\n        }\n        // graph is connected, bestIdx must exist\n        visitedRep[bestIdx] = 1;\n        order.push_back(bestIdx);\n        cur = bestIdx;\n    }\n\n    /*** 5.  2\u2011opt improvement (few passes) ***/\n    auto tourLength = [&](const vector<int>& o) -> ll {\n        ll sum = 0;\n        for (size_t i = 0; i < o.size(); ++i) {\n            int a = o[i];\n            int b = (i + 1 == o.size()) ? o[0] : o[i+1];\n            sum += repDist[a][b];\n        }\n        return sum;\n    };\n    const int OPT_PASSES = 5;\n    for (int pass = 0; pass < OPT_PASSES; ++pass) {\n        bool improved = false;\n        for (int i = 1; i < m - 1; ++i) {\n            for (int j = i + 1; j < m; ++j) {\n                int a = order[i-1];\n                int b = order[i];\n                int c = order[j];\n                int d = (j + 1 == m) ? order[0] : order[j+1];\n                ll curLen = repDist[a][b] + repDist[c][d];\n                ll newLen = repDist[a][c] + repDist[b][d];\n                if (newLen < curLen) {\n                    reverse(order.begin() + i, order.begin() + j + 1);\n                    improved = true;\n                }\n            }\n        }\n        if (!improved) break;\n    }\n\n    /*** 6.  Reconstruct the final movement string ***/\n    string answer;\n    auto appendPath = [&](int srcId, int dstId, int srcRepIdx) {\n        // reconstruct srcId -> dstId using parent[srcRepIdx][*]\n        vector<int> path;\n        int v = dstId;\n        while (v != srcId) {\n            path.push_back(v);\n            v = parent[srcRepIdx][v];\n        }\n        path.push_back(srcId);\n        reverse(path.begin(), path.end());\n        for (size_t k = 1; k < path.size(); ++k) {\n            int a = path[k-1];\n            int b = path[k];\n            int dr = row[b] - row[a];\n            int dc = col[b] - col[a];\n            char ch;\n            if (dr == -1) ch = 'U';\n            else if (dr == 1) ch = 'D';\n            else if (dc == -1) ch = 'L';\n            else /* dc == 1 */ ch = 'R';\n            answer.push_back(ch);\n        }\n    };\n\n    int curId = startId;\n    int curRepIdx = startIdx;\n    for (size_t idx = 1; idx < order.size(); ++idx) {\n        int nxtRepIdx = order[idx];\n        int nxtId = reps[nxtRepIdx];\n        appendPath(curId, nxtId, curRepIdx);\n        curId = nxtId;\n        curRepIdx = nxtRepIdx;\n    }\n    // finally return to start\n    if (curId != startId) {\n        appendPath(curId, startId, curRepIdx);\n    }\n\n    cout << answer << '\\n';\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- data structures ---------- */\n\nstruct ReadyTask {\n    int id;          // task index (0\u2011based)\n    int dp;          // longest path length starting from the task\n    long long sum;   // \u03a3 d_i,k\n    // priority: larger dp first, then larger sum\n    bool operator<(const ReadyTask& other) const {\n        if (dp != other.dp) return dp < other.dp;\n        return sum < other.sum;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    if (!(cin >> N >> M >> K >> R)) return 0;\n\n    /* ----- read required skill vectors ----- */\n    vector<vector<int>> d(N, vector<int>(K));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < K; ++j)\n            cin >> d[i][j];\n\n    /* ----- compute sum of required skills for each task ----- */\n    vector<long long> sum_d(N, 0);\n    for (int i = 0; i < N; ++i) {\n        long long s = 0;\n        for (int j = 0; j < K; ++j) s += d[i][j];\n        sum_d[i] = s;\n    }\n\n    /* ----- read dependencies ----- */\n    vector<vector<int>> adj(N);\n    vector<int> indeg(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        adj[u].push_back(v);\n        ++indeg[v];\n    }\n\n    /* ----- longest path length (critical\u2011path priority) ----- */\n    vector<int> dp(N, 1);\n    for (int i = N - 1; i >= 0; --i) {\n        for (int v : adj[i]) {\n            dp[i] = max(dp[i], dp[v] + 1);\n        }\n    }\n\n    /* ----- initial ready queue ----- */\n    priority_queue<ReadyTask> readyPQ;\n    for (int i = 0; i < N; ++i) {\n        if (indeg[i] == 0) {\n            readyPQ.push({i, dp[i], sum_d[i]});\n        }\n    }\n\n    /* ----- state of members and tasks ----- */\n    vector<int> member_task(M, -1);          // task currently executed, -1 = idle\n    vector<int> task_start_day(N, -1);       // day when the task started\n    vector<char> task_started(N, 0);\n    vector<char> task_completed(N, 0);\n\n    /* ----- statistics for skill estimation ----- */\n    vector<long long> sum_d_done(M, 0);\n    vector<long long> sum_t_done(M, 0);\n    vector<int> cnt_done(M, 0);\n    vector<double> skill_est(M, 0.0);        // estimate of \u03a3 s_j\n\n    int day = 0;\n    while (true) {\n        ++day;\n\n        /* ----- collect idle members ----- */\n        vector<int> idle;\n        for (int j = 0; j < M; ++j)\n            if (member_task[j] == -1) idle.push_back(j);\n\n        /* ----- order idle members by estimated skill (strongest first) ----- */\n        sort(idle.begin(), idle.end(),\n             [&](int a, int b) { return skill_est[a] > skill_est[b]; });\n\n        /* ----- assign tasks ----- */\n        vector<pair<int,int>> assign;   // (member, task) in 1\u2011based form\n        for (int idx = 0; idx < (int)idle.size() && !readyPQ.empty(); ++idx) {\n            int member = idle[idx];\n            ReadyTask rt = readyPQ.top(); readyPQ.pop();\n            int task = rt.id;\n\n            assign.emplace_back(member + 1, task + 1);\n            member_task[member] = task;\n            task_started[task] = 1;\n            task_start_day[task] = day;\n        }\n\n        /* ----- output ----- */\n        cout << assign.size();\n        for (auto &p : assign) cout << ' ' << p.first << ' ' << p.second;\n        cout << \"\\n\" << flush;\n\n        /* ----- read judge response ----- */\n        int n;\n        if (!(cin >> n)) return 0;          // EOF (should not happen)\n        if (n == -1) break;                 // all tasks done or day limit\n        vector<int> finished;\n        finished.reserve(n);\n        for (int i = 0; i < n; ++i) {\n            int f; cin >> f;\n            finished.push_back(f);\n        }\n\n        /* ----- process completions ----- */\n        for (int f : finished) {\n            int member = f - 1;\n            int task = member_task[member];\n            if (task == -1) continue;       // safety, should not happen\n\n            // real duration of the task\n            int duration = day - task_start_day[task] + 1;\n\n            // update skill estimate of the member\n            ++cnt_done[member];\n            sum_d_done[member] += sum_d[task];\n            sum_t_done[member] += duration;\n            double raw = (double)sum_d_done[member] - (double)sum_t_done[member];\n            if (raw < 0) raw = 0;\n            skill_est[member] = raw / cnt_done[member];\n\n            // free the member\n            member_task[member] = -1;\n\n            // mark task as completed\n            task_started[task] = 0;\n            task_completed[task] = 1;\n\n            // make successors ready\n            for (int v : adj[task]) {\n                --indeg[v];\n                if (indeg[v] == 0) {\n                    readyPQ.push({v, dp[v], sum_d[v]});\n                }\n            }\n        }\n    }\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Order {\n    int a, b, c, d;   // pickup (a,b), delivery (c,d)\n    int idx;          // 1\u2011based index in the original list\n    long long cost;  // heuristic cost for selection\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 1000;\n    const int M = 50;\n    const int OFF_X = 400, OFF_Y = 400;\n\n    vector<Order> orders(N);\n    for (int i = 0; i < N; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        long long cost = 0;\n        cost += manhattan(OFF_X, OFF_Y, a, b); // office -> pickup\n        cost += manhattan(a, b, c, d);         // pickup -> delivery\n        cost += manhattan(c, d, OFF_X, OFF_Y); // delivery -> office\n        orders[i] = {a, b, c, d, i + 1, cost};\n    }\n\n    // -----------------------------------------------------------------\n    // 1) select 50 orders with smallest heuristic cost\n    sort(orders.begin(), orders.end(),\n         [](const Order& x, const Order& y) { return x.cost < y.cost; });\n    vector<Order> sel(orders.begin(), orders.begin() + M);\n\n    // -----------------------------------------------------------------\n    // 2) greedy feasible\u2011node walk\n    // status: 0 = not started, 1 = pickup done, 2 = delivered\n    vector<int> status(M, 0);\n    vector<int> chosenIdx;          // order indices in the order we first visit pickup\n    vector<pair<int,int>> route;    // visited points\n\n    int curX = OFF_X, curY = OFF_Y;\n    route.emplace_back(curX, curY);   // start at office\n\n    int remaining = M;   // number of orders not yet delivered\n    while (remaining > 0) {\n        int bestDist = INT_MAX;\n        int bestIdx = -1;\n        bool bestIsPickup = true;   // true -> pickup, false -> delivery\n\n        for (int i = 0; i < M; ++i) {\n            if (status[i] == 0) { // pickup not visited yet\n                int d = manhattan(curX, curY, sel[i].a, sel[i].b);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx = i;\n                    bestIsPickup = true;\n                }\n            } else if (status[i] == 1) { // pickup done, delivery pending\n                int d = manhattan(curX, curY, sel[i].c, sel[i].d);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx = i;\n                    bestIsPickup = false;\n                }\n            }\n        }\n\n        // we must have found a candidate\n        if (bestIsPickup) {\n            // go to pickup\n            curX = sel[bestIdx].a;\n            curY = sel[bestIdx].b;\n            route.emplace_back(curX, curY);\n            status[bestIdx] = 1;\n            chosenIdx.push_back(sel[bestIdx].idx);\n        } else {\n            // go to delivery\n            curX = sel[bestIdx].c;\n            curY = sel[bestIdx].d;\n            route.emplace_back(curX, curY);\n            status[bestIdx] = 2;\n            --remaining;\n        }\n    }\n\n    // return to office\n    route.emplace_back(OFF_X, OFF_Y);\n\n    // -----------------------------------------------------------------\n    // 3) output\n    cout << M;\n    for (int id : chosenIdx) cout << ' ' << id;\n    cout << '\\n';\n\n    cout << route.size();\n    for (auto [x, y] : route) cout << ' ' << x << ' ' << y;\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        sz.assign(n, 1);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\n/*** Edge description ***/\nstruct Edge {\n    int u, v;\n    int d;          // rounded Euclidean distance\n    int idx;        // original index in input order\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        long long dx = (long long)x[u] - x[v];\n        long long dy = (long long)y[u] - y[v];\n        double dist = sqrt((double)dx * dx + (double)dy * dy);\n        int d = (int)lround(dist);          // round to nearest integer\n        edges[i] = {u, v, d, i};\n    }\n\n    /* ---------- build geometric MST (weight = d_i) ---------- */\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a, int b) {\n             if (edges[a].d != edges[b].d) return edges[a].d < edges[b].d;\n             return a < b;\n         });\n\n    DSU dsu_mst(N);\n    vector<char> inMST(M, 0);\n    int taken = 0;\n    for (int id : order) {\n        const Edge &e = edges[id];\n        if (dsu_mst.unite(e.u, e.v)) {\n            inMST[id] = 1;\n            ++taken;\n            if (taken == N - 1) break;\n        }\n    }\n\n    /* ---------- online phase ---------- */\n    DSU dsu(N);\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;                     // true length of edge i\n        bool accept = false;\n        if (inMST[i] && dsu.find(edges[i].u) != dsu.find(edges[i].v)) {\n            accept = true;\n            dsu.unite(edges[i].u, edges[i].v);\n        }\n        cout << (accept ? 1 : 0) << '\\n' << flush;\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pet   { int x, y, type; };\nstruct Human { int x, y; };\nstruct WallTask {\n    int px, py;      // required human position\n    char dir;        // lower\u2011case direction to build the wall\n    int tx, ty;      // square that becomes a wall\n};\n\nstatic const int H = 30;\ninline bool inside(int x, int y) { return 1 <= x && x <= H && 1 <= y && y <= H; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;  if (!(cin >> N)) return 0;\n    vector<Pet> pets(N);\n    for (auto &p : pets) cin >> p.x >> p.y >> p.type;\n\n    int M;  cin >> M;\n    vector<Human> humans(M);\n    for (auto &h : humans) cin >> h.x >> h.y;\n\n    // ----- board data -----\n    bool wall[31][31] = {};          // impassable squares\n    bool petOcc[31][31];\n    bool humanOcc[31][31];\n    bool wallTarget[31][31];         // squares that will become walls this turn\n\n    // ----- candidate 3\u00d73 blocks (top\u2011left corners) -----\n    vector<pair<int,int>> cand = {\n        {1,1},{1,7},{1,13},{1,19},{1,25},\n        {7,1},{7,7},{7,13},{7,19},{7,25}\n    };\n    vector<bool> blockUsed(cand.size(), false);\n\n    // ----- human state -----\n    struct HState {\n        int state = 2;               // 0=move to centre, 1=build walls, 2=idle\n        int targetX = -1, targetY = -1;\n        vector<WallTask> tasks;\n        size_t taskIdx = 0;\n    };\n    vector<HState> hst(M);\n\n    // initial pet occupancy (used only for block selection)\n    memset(petOcc, 0, sizeof(petOcc));\n    for (const auto &p : pets) petOcc[p.x][p.y] = true;\n\n    // assign a block to each human if possible\n    for (int i = 0; i < M; ++i) {\n        bool assigned = false;\n        for (size_t b = 0; b < cand.size(); ++b) if (!blockUsed[b]) {\n            int rx = cand[b].first;\n            int ry = cand[b].second;\n            bool ok = true;\n            for (int x = rx; x < rx + 3 && ok; ++x)\n                for (int y = ry; y < ry + 3; ++y)\n                    if (petOcc[x][y]) { ok = false; break; }\n            if (!ok) continue;\n            blockUsed[b] = true;\n            assigned = true;\n            // centre of the block\n            hst[i].targetX = rx + 1;\n            hst[i].targetY = ry + 1;\n            hst[i].state = 0;   // start moving\n            // generate wall tasks (perimeter)\n            vector<WallTask> tasks;\n            // top side\n            for (int y = ry; y <= ry + 2; ++y) {\n                int tx = rx - 1, ty = y;\n                if (inside(tx, ty))\n                    tasks.push_back({rx, y, 'u', tx, ty});\n            }\n            // bottom side\n            for (int y = ry; y <= ry + 2; ++y) {\n                int tx = rx + 3, ty = y;\n                if (inside(tx, ty))\n                    tasks.push_back({rx + 2, y, 'd', tx, ty});\n            }\n            // left side\n            for (int x = rx; x <= rx + 2; ++x) {\n                int tx = x, ty = ry - 1;\n                if (inside(tx, ty))\n                    tasks.push_back({x, ry, 'l', tx, ty});\n            }\n            // right side\n            for (int x = rx; x <= rx + 2; ++x) {\n                int tx = x, ty = ry + 3;\n                if (inside(tx, ty))\n                    tasks.push_back({x, ry + 2, 'r', tx, ty});\n            }\n            hst[i].tasks = std::move(tasks);\n            break;\n        }\n        if (!assigned) {\n            hst[i].state = 2;   // idle\n        }\n    }\n\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    const char moveChar[4] = {'U','D','L','R'};\n    const char wallChar[4] = {'u','d','l','r'};\n\n    auto canBuild = [&](int tx, int ty) -> bool {\n        if (!inside(tx, ty)) return false;\n        if (wall[tx][ty]) return false;\n        if (humanOcc[tx][ty]) return false;\n        if (petOcc[tx][ty]) return false;\n        for (int d = 0; d < 4; ++d) {\n            int nx = tx + dx[d], ny = ty + dy[d];\n            if (inside(nx, ny) && petOcc[nx][ny]) return false;\n        }\n        return true;\n    };\n\n    // ----- main simulation (300 turns) -----\n    for (int turn = 0; turn < 300; ++turn) {\n        // rebuild occupancy maps for the start of this turn\n        memset(petOcc, 0, sizeof(petOcc));\n        for (const auto &p : pets) petOcc[p.x][p.y] = true;\n        memset(humanOcc, 0, sizeof(humanOcc));\n        for (const auto &h : humans) humanOcc[h.x][h.y] = true;\n        memset(wallTarget, 0, sizeof(wallTarget));\n\n        string actions(M, '?');   // '?' will be replaced later\n\n        // ---------- first pass : decide walls ----------\n        for (int i = 0; i < M; ++i) {\n            HState &st = hst[i];\n            Human &h = humans[i];\n            if (st.state == 1 && st.taskIdx < st.tasks.size()) {\n                const WallTask &wt = st.tasks[st.taskIdx];\n                if (h.x == wt.px && h.y == wt.py && canBuild(wt.tx, wt.ty)) {\n                    actions[i] = wt.dir;               // build wall\n                    wallTarget[wt.tx][wt.ty] = true;\n                    ++st.taskIdx;\n                    if (st.taskIdx >= st.tasks.size()) st.state = 2;\n                    continue;\n                }\n            }\n            // not a wall this turn\n            actions[i] = '?';\n        }\n\n        // ---------- second pass : decide movements ----------\n        for (int i = 0; i < M; ++i) {\n            if (actions[i] != '?') continue;   // already a wall action\n            HState &st = hst[i];\n            Human &h = humans[i];\n            char chosen = '.';\n\n            // helper lambda to test a neighbour\n            auto tryDir = [&](int d) -> bool {\n                int nx = h.x + dx[d], ny = h.y + dy[d];\n                if (!inside(nx, ny)) return false;\n                if (wall[nx][ny]) return false;\n                if (wallTarget[nx][ny]) return false;\n                // moving onto a pet is allowed\n                chosen = moveChar[d];\n                return true;\n            };\n\n            if (st.state == 0) {                     // move to centre\n                if (h.x == st.targetX && h.y == st.targetY) {\n                    st.state = 1;                    // start building\n                } else {\n                    // move one step that reduces Manhattan distance\n                    int bestDist = INT_MAX, bestDir = -1;\n                    for (int d = 0; d < 4; ++d) {\n                        int nx = h.x + dx[d], ny = h.y + dy[d];\n                        if (!inside(nx, ny) || wall[nx][ny] || wallTarget[nx][ny]) continue;\n                        int dist = abs(nx - st.targetX) + abs(ny - st.targetY);\n                        if (dist < bestDist) {\n                            bestDist = dist;\n                            bestDir = d;\n                        }\n                    }\n                    if (bestDir != -1) chosen = moveChar[bestDir];\n                }\n            } else if (st.state == 1) {              // building walls\n                if (st.taskIdx < st.tasks.size()) {\n                    const WallTask &wt = st.tasks[st.taskIdx];\n                    if (h.x != wt.px || h.y != wt.py) {\n                        // move towards the required position\n                        int bestDist = INT_MAX, bestDir = -1;\n                        for (int d = 0; d < 4; ++d) {\n                            int nx = h.x + dx[d], ny = h.y + dy[d];\n                            if (!inside(nx, ny) || wall[nx][ny] || wallTarget[nx][ny]) continue;\n                            int dist = abs(nx - wt.px) + abs(ny - wt.py);\n                            if (dist < bestDist) {\n                                bestDist = dist;\n                                bestDir = d;\n                            }\n                        }\n                        if (bestDir != -1) chosen = moveChar[bestDir];\n                    } else {\n                        // at required position but cannot build now \u2192 move away from pets\n                        bool petAdj = false;\n                        for (int d = 0; d < 4; ++d) {\n                            int nx = h.x + dx[d], ny = h.y + dy[d];\n                            if (inside(nx, ny) && petOcc[nx][ny]) { petAdj = true; break; }\n                        }\n                        if (petAdj) {\n                            // try any safe neighbour\n                            for (int d = 0; d < 4; ++d) {\n                                if (tryDir(d)) break;\n                            }\n                        } else {\n                            chosen = '.';\n                        }\n                    }\n                } else {\n                    // all tasks finished, become idle\n                    st.state = 2;\n                    chosen = '.';\n                }\n            } else {                                 // state == 2 (idle)\n                chosen = '.';\n            }\n            actions[i] = chosen;\n        }\n\n        // ---------- output ----------\n        cout << actions << '\\n' << flush;\n\n        // ---------- read pet moves ----------\n        vector<string> petMoves(N);\n        for (int i = 0; i < N; ++i) cin >> petMoves[i];\n\n        // ---------- apply walls ----------\n        for (int i = 0; i < M; ++i) {\n            char c = actions[i];\n            if (c >= 'a' && c <= 'z') {\n                int d = (c == 'u' ? 0 : (c == 'd' ? 1 : (c == 'l' ? 2 : 3)));\n                int tx = humans[i].x + dx[d];\n                int ty = humans[i].y + dy[d];\n                if (inside(tx, ty)) wall[tx][ty] = true;\n            }\n        }\n\n        // ---------- apply movements ----------\n        for (int i = 0; i < M; ++i) {\n            char c = actions[i];\n            if (c >= 'A' && c <= 'Z') {\n                int d = (c == 'U' ? 0 : (c == 'D' ? 1 : (c == 'L' ? 2 : 3)));\n                int nx = humans[i].x + dx[d];\n                int ny = humans[i].y + dy[d];\n                if (inside(nx, ny) && !wall[nx][ny]) {\n                    humans[i].x = nx;\n                    humans[i].y = ny;\n                }\n            }\n        }\n\n        // ---------- apply pet moves ----------\n        for (int i = 0; i < N; ++i) {\n            const string &s = petMoves[i];\n            for (char c : s) {\n                if (c == '.') continue;\n                int d = (c == 'U' ? 0 : (c == 'D' ? 1 : (c == 'L' ? 2 : 3)));\n                pets[i].x += dx[d];\n                pets[i].y += dy[d];\n                // the judge guarantees the move is legal\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 20;                 // grid size\nconstexpr int V = N * N;              // number of cells\nconstexpr int MAXLEN = 200;           // maximal output length\n\n// direction handling\nconst int di[4] = {-1, 1, 0, 0};\nconst int dj[4] = {0, 0, -1, 1};\nconst char dch[4] = {'U', 'D', 'L', 'R'};\ninline int dirIdx(char c) {\n    if (c == 'U') return 0;\n    if (c == 'D') return 1;\n    if (c == 'L') return 2;\n    return 3; // 'R'\n}\n\n// ------------------------------------------------------------\n// evaluate expected score of a given string (exact DP)\ndouble evaluate(const string& s,\n                const array<array<int,4>,V>& nxt,\n                int startId, int targetId, double p)\n{\n    const double stayProb = p;\n    const double moveProb = 1.0 - p;\n\n    static double cur[V];\n    static double nxtdp[V];\n    fill(begin(cur), end(cur), 0.0);\n    cur[startId] = 1.0;\n\n    double expected = 0.0;\n\n    for (int step = 0; step < (int)s.size(); ++step) {\n        fill(begin(nxtdp), end(nxtdp), 0.0);\n        int d = dirIdx(s[step]);\n        for (int v = 0; v < V; ++v) {\n            double prob = cur[v];\n            if (prob == 0.0) continue;\n            if (v == targetId) {\n                nxtdp[v] += prob;               // absorbing\n                continue;\n            }\n            int w = nxt[v][d];\n            // move remembered\n            nxtdp[w] += prob * moveProb;\n            // character forgotten\n            nxtdp[v] += prob * stayProb;\n        }\n        double newArrived = nxtdp[targetId] - cur[targetId];\n        expected += (401.0 - (step + 1)) * newArrived;\n        memcpy(cur, nxtdp, sizeof(cur));\n    }\n    return expected;\n}\n\n// ------------------------------------------------------------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj, ti, tj;\n    double p;\n    if (!(cin >> si >> sj >> ti >> tj >> p)) return 0;\n\n    // read walls\n    vector<string> h(N);          // horizontal, length 19\n    for (int i = 0; i < N; ++i) cin >> h[i];\n    vector<string> v(N-1);        // vertical, length 20\n    for (int i = 0; i < N-1; ++i) cin >> v[i];\n\n    // neighbour table: nxt[cell][direction] = destination cell\n    array<array<int,4>,V> nxt;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int id = i * N + j;\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d];\n                int nj = j + dj[d];\n                bool blocked = false;\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) {\n                    blocked = true;\n                } else {\n                    if (d == 0) { // U\n                        blocked = (v[i-1][j] == '1');\n                    } else if (d == 1) { // D\n                        blocked = (v[i][j] == '1');\n                    } else if (d == 2) { // L\n                        blocked = (h[i][j-1] == '1');\n                    } else { // R\n                        blocked = (h[i][j] == '1');\n                    }\n                }\n                if (blocked) nxt[id][d] = id;\n                else nxt[id][d] = ni * N + nj;\n            }\n        }\n    }\n\n    int startId = si * N + sj;\n    int targetId = ti * N + tj;\n\n    // --------------------------------------------------------\n    // 1) BFS from target to obtain a shortest path\n    vector<int> dist(V, -1);\n    vector<int> prevDir(V, -1);   // direction from predecessor to this cell\n    vector<int> prevCell(V, -1);\n    queue<int> q;\n    dist[targetId] = 0;\n    q.push(targetId);\n    while (!q.empty()) {\n        int vtx = q.front(); q.pop();\n        int vi = vtx / N, vj = vtx % N;\n        for (int d = 0; d < 4; ++d) {\n            int u = nxt[vtx][d];\n            if (u == vtx) continue;               // wall\n            if (dist[u] == -1) {\n                dist[u] = dist[vtx] + 1;\n                prevDir[u] = d ^ 1;               // opposite direction\n                prevCell[u] = vtx;\n                q.push(u);\n            }\n        }\n    }\n\n    // reconstruct one shortest path (forward direction)\n    string basePath;\n    int cur = startId;\n    while (cur != targetId && prevDir[cur] != -1) {\n        basePath.push_back(dch[prevDir[cur]]);\n        cur = prevCell[cur];\n    }\n\n    // --------------------------------------------------------\n    // 2) build initial answer: repeat the shortest path as many times as possible\n    string best;\n    if (!basePath.empty()) {\n        while ((int)best.size() + (int)basePath.size() <= MAXLEN) {\n            best += basePath;\n        }\n        int need = MAXLEN - (int)best.size();\n        if (need > 0 && need <= (int)basePath.size())\n            best += basePath.substr(0, need);\n    }\n    if (best.empty()) { // fallback (should never happen)\n        static const char dirs[4] = {'U','D','L','R'};\n        std::mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n        for (int i = 0; i < MAXLEN; ++i) best.push_back(dirs[rng() % 4]);\n    }\n\n    // --------------------------------------------------------\n    // 3) DP evaluation function (already defined above)\n    double bestScore = evaluate(best, nxt, startId, targetId, p);\n\n    // --------------------------------------------------------\n    // 4) random generator\n    std::mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    const char dirs[4] = {'U','D','L','R'};\n    uniform_real_distribution<double> real01(0.0, 1.0);\n    uniform_int_distribution<int> dirDist(0, 3);\n\n    // --------------------------------------------------------\n    // 5) generate a few biased random strings\n    const int BIASED_CANDIDATES = 500;\n    for (int it = 0; it < BIASED_CANDIDATES; ++it) {\n        string cand;\n        cand.reserve(MAXLEN);\n        int curCell = startId;\n        for (int pos = 0; pos < MAXLEN; ++pos) {\n            // collect the four possible directions\n            vector<int> candDir;\n            candDir.reserve(4);\n            for (int d = 0; d < 4; ++d) candDir.push_back(d);\n            // compute Manhattan distance after each move\n            int bestDist = INT_MAX;\n            for (int d : candDir) {\n                int nb = nxt[curCell][d];\n                int r = nb / N, c = nb % N;\n                int dist = abs(r - ti) + abs(c - tj);\n                if (dist < bestDist) bestDist = dist;\n            }\n            vector<int> good;\n            for (int d : candDir) {\n                int nb = nxt[curCell][d];\n                int r = nb / N, c = nb % N;\n                int dist = abs(r - ti) + abs(c - tj);\n                if (dist == bestDist) good.push_back(d);\n            }\n            int chosen;\n            if (real01(rng) < 0.8 && !good.empty())\n                chosen = good[dirDist(rng) % good.size()];\n            else\n                chosen = candDir[dirDist(rng) % candDir.size()];\n            cand.push_back(dirs[chosen]);\n            curCell = nxt[curCell][chosen];\n        }\n        double sc = evaluate(cand, nxt, startId, targetId, p);\n        if (sc > bestScore) {\n            bestScore = sc;\n            best = cand;\n        }\n    }\n\n    // --------------------------------------------------------\n    // 6) hill\u2011climbing (local search)\n    const double TIME_LIMIT = 1.80; // seconds\n    auto startTime = chrono::steady_clock::now();\n\n    while (true) {\n        double elapsed = chrono::duration<double>(chrono::steady_clock::now() - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        // mutate a copy of the current best string\n        string cand = best;\n        // pick a random position and replace it\n        int pos = uniform_int_distribution<int>(0, (int)cand.size() - 1)(rng);\n        cand[pos] = dirs[dirDist(rng)];\n        double sc = evaluate(cand, nxt, startId, targetId, p);\n        if (sc >= bestScore) {\n            bestScore = sc;\n            best = cand;\n        }\n    }\n\n    // --------------------------------------------------------\n    cout << best << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;\nconstexpr int DIR = 4;\nconstexpr int TOTAL = N * N * DIR;          // 30*30*4 = 3600\nconstexpr int di[DIR] = {0, -1, 0, 1};       // left, up, right, down\nconstexpr int dj[DIR] = {-1, 0, 1, 0};\n\nint tile[N][N];                              // original tile types\n\n// base connection table from the statement\nconst int base_to[8][4] = {\n    { 1, 0,-1,-1},\n    { 3,-1,-1, 0},\n    {-1,-1, 3, 2},\n    {-1, 2, 1,-1},\n    { 1, 0, 3, 2},\n    { 3, 2, 1, 0},\n    { 2,-1, 0,-1},\n    {-1, 3,-1, 1}\n};\n\nint to_rot[8][4][4];                         // after rotation\n\ninline int idx(int i, int j, int d) { return ((i * N + j) * DIR + d); }\n\n// ------------------------------------------------------------\n// fast Xorshift64 PRNG\nstruct XorShift {\n    uint64_t x;\n    XorShift() { x = chrono::steady_clock::now().time_since_epoch().count(); }\n    uint32_t next() {\n        x ^= x << 13;\n        x ^= x >> 7;\n        x ^= x << 17;\n        return static_cast<uint32_t>(x);\n    }\n    uint32_t next(uint32_t n) { return next() % n; }\n    double nextDouble() { return (next() >> 11) * (1.0 / 9007199254740992.0); }\n};\n// ------------------------------------------------------------\n\n// ------------------------------------------------------------\n// compute the score (L1 * L2) for a given rotation vector (size 900)\nint computeScore(const vector<int>& rot) {\n    static int nxt[TOTAL];\n    fill(nxt, nxt + TOTAL, -1);\n\n    // build outgoing edges\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int t = tile[i][j];\n            int r = rot[i * N + j];\n            for (int d = 0; d < DIR; ++d) {\n                int d2 = to_rot[t][r][d];\n                if (d2 == -1) continue;\n                int ni = i + di[d2];\n                int nj = j + dj[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) & 3;\n                nxt[idx(i, j, d)] = idx(ni, nj, nd);\n            }\n        }\n    }\n\n    static uint8_t state[TOTAL];   // 0 = unvisited, 1 = in current walk, 2 = finished\n    static int pos[TOTAL];\n    fill(state, state + TOTAL, 0);\n    fill(pos, pos + TOTAL, -1);\n\n    int best1 = 0, best2 = 0;\n    vector<int> path;\n    path.reserve(TOTAL);\n\n    for (int v = 0; v < TOTAL; ++v) {\n        if (state[v]) continue;\n        int cur = v;\n        while (true) {\n            if (cur == -1) break;\n            if (state[cur] == 0) {\n                state[cur] = 1;\n                pos[cur] = static_cast<int>(path.size());\n                path.push_back(cur);\n                cur = nxt[cur];\n            } else if (state[cur] == 1) {\n                int len = static_cast<int>(path.size()) - pos[cur];\n                if (len > best1) { best2 = best1; best1 = len; }\n                else if (len > best2) { best2 = len; }\n                break;\n            } else { // state[cur] == 2\n                break;\n            }\n        }\n        for (int node : path) {\n            state[node] = 2;\n            pos[node] = -1;\n        }\n        path.clear();\n    }\n    if (best2 == 0) return 0;\n    return best1 * best2;\n}\n// ------------------------------------------------------------\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read input\n    for (int i = 0; i < N; ++i) {\n        string line; cin >> line;\n        for (int j = 0; j < N; ++j) tile[i][j] = line[j] - '0';\n    }\n\n    // pre\u2011compute to_rot\n    for (int t = 0; t < 8; ++t) {\n        for (int r = 0; r < 4; ++r) {\n            for (int d = 0; d < 4; ++d) {\n                int local = (d - r + 4) & 3;\n                int out = base_to[t][local];\n                if (out == -1) to_rot[t][r][d] = -1;\n                else to_rot[t][r][d] = (out + r) & 3;\n            }\n        }\n    }\n\n    XorShift rng;\n    vector<int> cur(900), best(900);\n    for (int i = 0; i < 900; ++i) cur[i] = rng.next(4);\n    int curScore = computeScore(cur);\n    best = cur;\n    int bestScore = curScore;\n\n    const double TIME_LIMIT = 1.9;          // seconds\n    const double T0 = 50000.0;              // initial temperature\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        int idx = rng.next(900);\n        int oldR = cur[idx];\n        int newR = rng.next(4);\n        if (newR == oldR) continue;\n        cur[idx] = newR;\n        int newScore = computeScore(cur);\n        int delta = newScore - curScore;\n\n        bool accept = false;\n        if (delta >= 0) accept = true;\n        else {\n            double T = T0 * (1.0 - elapsed / TIME_LIMIT);\n            if (T < 1e-9) T = 1e-9;\n            double prob = exp(delta / T);\n            if (rng.nextDouble() < prob) accept = true;\n        }\n\n        if (accept) {\n            curScore = newScore;\n            if (newScore > bestScore) {\n                bestScore = newScore;\n                best = cur;\n            }\n        } else {\n            cur[idx] = oldR; // revert\n        }\n    }\n\n    // output best solution\n    string out;\n    out.reserve(900);\n    for (int i = 0; i < 900; ++i) out.push_back(char('0' + best[i]));\n    cout << out << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ------------------------------------------------------------\n// conversion from hexadecimal character to integer mask (0\u201115)\ninline int hexCharToInt(char c) {\n    if ('0' <= c && c <= '9') return c - '0';\n    return 10 + (c - 'a');\n}\n\n// ------------------------------------------------------------\nconstexpr int DR[4] = {-1, 1, 0, 0};          // U D L R\nconstexpr int DC[4] = {0, 0, -1, 1};\nconstexpr char DIR_CHAR[4] = {'U', 'D', 'L', 'R'};\nconstexpr int DIR_MASK[4] = {2, 8, 1, 4};     // up, down, left, right\nconstexpr int OPP[4] = {1, 0, 3, 2};         // opposite direction index\n\n// ------------------------------------------------------------\n// compute the size of the largest tree component\nint largestTreeSize(const vector<uint8_t> &board, int N) {\n    const int SZ = N * N;\n    static bool visited[100];\n    for (int i = 0; i < SZ; ++i) visited[i] = false;\n    int best = 0;\n\n    static int q[100];\n    for (int start = 0; start < SZ; ++start) {\n        if (board[start] == 0 || visited[start]) continue;\n        int head = 0, tail = 0;\n        q[tail++] = start;\n        visited[start] = true;\n        int verts = 0, edges = 0;\n        while (head < tail) {\n            int pos = q[head++];\n            ++verts;\n            int r = pos / N, c = pos % N;\n            int mask = board[pos];\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + DR[d];\n                int nc = c + DC[d];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                int npos = nr * N + nc;\n                if (board[npos] == 0) continue;\n                if ((mask & DIR_MASK[d]) && (board[npos] & DIR_MASK[OPP[d]])) {\n                    // count each undirected edge only once (down or right)\n                    if (d == 1 || d == 3) ++edges;\n                    if (!visited[npos]) {\n                        visited[npos] = true;\n                        q[tail++] = npos;\n                    }\n                }\n            }\n        }\n        if (edges == verts - 1) best = max(best, verts);\n    }\n    return best;\n}\n\n// ------------------------------------------------------------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    long long T;\n    if (!(cin >> N >> T)) return 0;\n    const int SZ = N * N;\n    vector<uint8_t> origBoard(SZ);\n    int emptyPos = -1;\n\n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) {\n            int v = hexCharToInt(row[j]);\n            origBoard[i * N + j] = static_cast<uint8_t>(v);\n            if (v == 0) emptyPos = i * N + j;\n        }\n    }\n\n    const int totalTiles = SZ - 1;\n    string bestSeq;\n    int bestScore = 0;\n\n    // --------------------------------------------------------\n    // 1) Greedy baseline (never accept a decreasing move)\n    {\n        vector<uint8_t> board = origBoard;\n        int empty = emptyPos;\n        string seq;\n        int curScore = largestTreeSize(board, N);\n        int bestLocalScore = curScore;\n        string bestLocalSeq = \"\";\n\n        for (long long step = 0; step < T; ++step) {\n            // legal moves\n            vector<int> cand;\n            int er = empty / N, ec = empty % N;\n            for (int d = 0; d < 4; ++d) {\n                int nr = er + DR[d], nc = ec + DC[d];\n                if (0 <= nr && nr < N && 0 <= nc && nc < N) cand.push_back(d);\n            }\n            if (cand.empty()) break;\n\n            int bestMoveScore = -1;\n            vector<int> bestMoves;\n            for (int d : cand) {\n                int nr = er + DR[d], nc = ec + DC[d];\n                int npos = nr * N + nc;\n                swap(board[empty], board[npos]);\n                int ns = largestTreeSize(board, N);\n                swap(board[empty], board[npos]); // revert\n                if (ns > bestMoveScore) {\n                    bestMoveScore = ns;\n                    bestMoves.clear();\n                    bestMoves.push_back(d);\n                } else if (ns == bestMoveScore) {\n                    bestMoves.push_back(d);\n                }\n            }\n\n            if (bestMoveScore < curScore) break; // no non\u2011decreasing move\n\n            static std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n            int chosen = bestMoves[uniform_int_distribution<int>(0, (int)bestMoves.size() - 1)(rng)];\n            int nr = er + DR[chosen], nc = ec + DC[chosen];\n            int npos = nr * N + nc;\n            swap(board[empty], board[npos]);\n            empty = npos;\n            seq.push_back(DIR_CHAR[chosen]);\n            curScore = bestMoveScore;\n\n            if (curScore > bestLocalScore ||\n                (curScore == bestLocalScore && seq.size() < bestLocalSeq.size())) {\n                bestLocalScore = curScore;\n                bestLocalSeq = seq;\n                if (bestLocalScore == totalTiles) break;\n            }\n        }\n        bestSeq = bestLocalSeq;\n        bestScore = bestLocalScore;\n        if (bestScore == totalTiles) {\n            cout << bestSeq << \"\\n\";\n            return 0;\n        }\n    }\n\n    // --------------------------------------------------------\n    // 2) Simulated annealing (randomised hill\u2011climbing)\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_real_distribution<double> probDist(0.0, 1.0);\n    auto startTime = chrono::steady_clock::now();\n    const double TIME_LIMIT = 2.8; // seconds, leave margin for I/O\n\n    while (true) {\n        // time check\n        double elapsed = chrono::duration<double>(chrono::steady_clock::now() - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        vector<uint8_t> board = origBoard;\n        int empty = emptyPos;\n        string curSeq;\n        int curScore = largestTreeSize(board, N);\n        double temperature = 1.0;\n\n        for (long long step = 0; step < T; ++step) {\n            // legal moves\n            vector<int> cand;\n            int er = empty / N, ec = empty % N;\n            for (int d = 0; d < 4; ++d) {\n                int nr = er + DR[d], nc = ec + DC[d];\n                if (0 <= nr && nr < N && 0 <= nc && nc < N) cand.push_back(d);\n            }\n            if (cand.empty()) break;\n\n            int d = cand[uniform_int_distribution<int>(0, (int)cand.size() - 1)(rng)];\n            int nr = er + DR[d], nc = ec + DC[d];\n            int npos = nr * N + nc;\n            swap(board[empty], board[npos]);\n            int newScore = largestTreeSize(board, N);\n            int delta = newScore - curScore;\n\n            bool accept = false;\n            if (delta >= 0) {\n                accept = true;\n            } else {\n                double prob = exp(delta / temperature);\n                if (probDist(rng) < prob) accept = true;\n            }\n\n            if (accept) {\n                empty = npos;\n                curScore = newScore;\n                curSeq.push_back(DIR_CHAR[d]);\n\n                if (curScore > bestScore ||\n                    (curScore == bestScore && curSeq.size() < bestSeq.size())) {\n                    bestScore = curScore;\n                    bestSeq = curSeq;\n                    if (bestScore == totalTiles) break;\n                }\n            } else {\n                // revert the swap\n                swap(board[empty], board[npos]);\n            }\n\n            temperature *= 0.9995; // slow cooling\n        }\n\n        if (bestScore == totalTiles) break;\n    }\n\n    cout << bestSeq << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, K;\n    if (!(cin >> N >> K)) return 0;\n    vector<int> a(11);\n    for (int d = 1; d <= 10; ++d) cin >> a[d];\n    vector<pair<ll,ll>> strawberries(N);\n    for (int i = 0; i < N; ++i) {\n        ll x, y;\n        cin >> x >> y;\n        strawberries[i] = {x, y};\n    }\n\n    const ll R = 10000;          // cake radius\n    const ll M = 20000;          // far outside the cake, still within limits\n    const int MAX_ATTEMPTS = 800;   // enough for a good solution\n\n    std::mt19937_64 rng(\n        std::chrono::steady_clock::now().time_since_epoch().count());\n\n    int bestScore = -1;\n    int bestV = 0, bestH = 0;\n    int bestOffsetX = 0, bestOffsetY = 0;\n    int bestStepV = 0, bestStepH = 0;\n\n    // Helper lambda: evaluate a concrete grid\n    auto evaluate = [&](int V, int H, int offsetX, int offsetY) {\n        if (V < 0 || H < 0 || V + H > K) return -1;\n        int stepV = (V == 0) ? 0 : (int)((2 * R) / (V + 1));\n        int stepH = (H == 0) ? 0 : (int)((2 * R) / (H + 1));\n        vector<int> xs, ys;\n        xs.reserve(V);\n        ys.reserve(H);\n        for (int i = 1; i <= V; ++i) {\n            ll x = -R + offsetX + (ll)i * stepV;\n            xs.push_back((int)x);\n        }\n        for (int j = 1; j <= H; ++j) {\n            ll y = -R + offsetY + (ll)j * stepH;\n            ys.push_back((int)y);\n        }\n\n        // counts[i][j] : i = #vertical lines left of point, j = #horizontal lines below point\n        vector<vector<int>> cnt(V + 1, vector<int>(H + 1, 0));\n\n        for (auto [x, y] : strawberries) {\n            bool onLine = false;\n            int ix = 0, iy = 0;\n            if (V > 0) {\n                ix = lower_bound(xs.begin(), xs.end(), (int)x) - xs.begin();\n                if (ix < V && xs[ix] == (int)x) { onLine = true; }\n            }\n            if (H > 0) {\n                iy = lower_bound(ys.begin(), ys.end(), (int)y) - ys.begin();\n                if (iy < H && ys[iy] == (int)y) { onLine = true; }\n            }\n            if (onLine) continue;               // strawberry cut away\n            cnt[ix][iy]++;                       // belongs to cell (ix,iy)\n        }\n\n        int b[11] = {0};\n        for (int i = 0; i <= V; ++i) {\n            for (int j = 0; j <= H; ++j) {\n                int c = cnt[i][j];\n                if (1 <= c && c <= 10) b[c]++;\n            }\n        }\n        int score = 0;\n        for (int d = 1; d <= 10; ++d) score += min(a[d], b[d]);\n        return score;\n    };\n\n    // Random search over many grid parameters\n    for (int it = 0; it < MAX_ATTEMPTS; ++it) {\n        // choose V randomly, H = K - V (any distribution works)\n        uniform_int_distribution<int> distV(0, K);\n        int V = distV(rng);\n        int H = K - V;\n\n        int stepV = (V == 0) ? 0 : (int)((2 * R) / (V + 1));\n        int stepH = (H == 0) ? 0 : (int)((2 * R) / (H + 1));\n\n        int offsetX = 0, offsetY = 0;\n        if (V > 0) {\n            uniform_int_distribution<int> distOffX(0, stepV - 1);\n            offsetX = distOffX(rng);\n        }\n        if (H > 0) {\n            uniform_int_distribution<int> distOffY(0, stepH - 1);\n            offsetY = distOffY(rng);\n        }\n\n        int sc = evaluate(V, H, offsetX, offsetY);\n        if (sc > bestScore) {\n            bestScore = sc;\n            bestV = V; bestH = H;\n            bestOffsetX = offsetX; bestOffsetY = offsetY;\n            bestStepV = stepV; bestStepH = stepH;\n        }\n    }\n\n    // In the unlikely case that no grid was accepted (should never happen),\n    // fall back to a tiny deterministic grid.\n    if (bestScore < 0) {\n        bestV = bestH = 10;\n        bestStepV = bestStepH = (int)((2 * R) / (bestV + 1));\n        bestOffsetX = bestOffsetY = 0;\n    }\n\n    // Build the final list of lines\n    vector<array<ll,4>> answer;   // (px,py,qx,qy)\n\n    // vertical lines\n    for (int i = 1; i <= bestV; ++i) {\n        ll X = -R + bestOffsetX + (ll)i * bestStepV;\n        answer.push_back({X, -M, X, M});\n    }\n    // horizontal lines\n    for (int j = 1; j <= bestH; ++j) {\n        ll Y = -R + bestOffsetY + (ll)j * bestStepH;\n        answer.push_back({-M, Y, M, Y});\n    }\n\n    cout << answer.size() << \"\\n\";\n    for (auto &ln : answer) {\n        cout << ln[0] << ' ' << ln[1] << ' ' << ln[2] << ' ' << ln[3] << \"\\n\";\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int x1, y1, x2, y2, x3, y3, x4, y4;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<vector<char>> dot(N, vector<char>(N, 0));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        dot[x][y] = 1;\n    }\n\n    // usedEdge[x][y][dir] : 0=right,1=up,2=left,3=down\n    vector<vector<array<char,4>>> used(N, vector<array<char,4>>(N));\n    for (int x = 0; x < N; ++x)\n        for (int y = 0; y < N; ++y)\n            used[x][y].fill(0);\n\n    // cells sorted by weight descending\n    struct Cell {int x, y; long long w;};\n    vector<Cell> cells;\n    cells.reserve(N * N);\n    long long c = (N - 1) / 2;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y < N; ++y) {\n            long long w = (x - c) * (x - c) + (y - c) * (y - c) + 1;\n            cells.push_back({x, y, w});\n        }\n    }\n    sort(cells.begin(), cells.end(),\n         [](const Cell& a, const Cell& b){ return a.w > b.w; });\n\n    vector<Op> ops;\n\n    auto markEdge = [&](int x, int y, int dir) {\n        used[x][y][dir] = 1;\n        int nx = x + (dir == 0) - (dir == 2);\n        int ny = y + (dir == 1) - (dir == 3);\n        int opp = (dir + 2) & 3;\n        used[nx][ny][opp] = 1;\n    };\n\n    bool anyAdded = true;\n    while (anyAdded) {\n        anyAdded = false;\n        for (const auto& cell : cells) {\n            int x = cell.x, y = cell.y;\n            if (dot[x][y]) continue;          // already occupied\n\n            // ---- orientation 0 : missing bottom\u2011left ----\n            if (x + 1 < N && y + 1 < N) {\n                if (dot[x+1][y] && dot[x+1][y+1] && dot[x][y+1]) {\n                    if (!used[x][y][0] && !used[x+1][y][1] &&\n                        !used[x+1][y+1][2] && !used[x][y+1][3]) {\n                        ops.push_back({x, y, x+1, y, x+1, y+1, x, y+1});\n                        dot[x][y] = 1;\n                        markEdge(x, y, 0);\n                        markEdge(x+1, y, 1);\n                        markEdge(x+1, y+1, 2);\n                        markEdge(x, y+1, 3);\n                        anyAdded = true;\n                        continue;\n                    }\n                }\n            }\n\n            // ---- orientation 1 : missing bottom\u2011right ----\n            if (x - 1 >= 0 && y + 1 < N) {\n                if (dot[x-1][y] && dot[x-1][y+1] && dot[x][y+1]) {\n                    if (!used[x][y][2] && !used[x-1][y][1] &&\n                        !used[x-1][y+1][0] && !used[x][y+1][3]) {\n                        ops.push_back({x, y, x-1, y, x-1, y+1, x, y+1});\n                        dot[x][y] = 1;\n                        markEdge(x, y, 2);\n                        markEdge(x-1, y, 1);\n                        markEdge(x-1, y+1, 0);\n                        markEdge(x, y+1, 3);\n                        anyAdded = true;\n                        continue;\n                    }\n                }\n            }\n\n            // ---- orientation 2 : missing top\u2011left ----\n            if (y - 1 >= 0 && x + 1 < N) {\n                if (dot[x][y-1] && dot[x+1][y-1] && dot[x+1][y]) {\n                    if (!used[x][y][3] && !used[x][y-1][0] &&\n                        !used[x+1][y-1][1] && !used[x+1][y][2]) {\n                        ops.push_back({x, y, x, y-1, x+1, y-1, x+1, y});\n                        dot[x][y] = 1;\n                        markEdge(x, y, 3);\n                        markEdge(x, y-1, 0);\n                        markEdge(x+1, y-1, 1);\n                        markEdge(x+1, y, 2);\n                        anyAdded = true;\n                        continue;\n                    }\n                }\n            }\n\n            // ---- orientation 3 : missing top\u2011right ----\n            if (x - 1 >= 0 && y - 1 >= 0) {\n                if (dot[x-1][y] && dot[x-1][y-1] && dot[x][y-1]) {\n                    if (!used[x][y][2] && !used[x-1][y][3] &&\n                        !used[x-1][y-1][0] && !used[x][y-1][1]) {\n                        ops.push_back({x, y, x-1, y, x-1, y-1, x, y-1});\n                        dot[x][y] = 1;\n                        markEdge(x, y, 2);\n                        markEdge(x-1, y, 3);\n                        markEdge(x-1, y-1, 0);\n                        markEdge(x, y-1, 1);\n                        anyAdded = true;\n                        continue;\n                    }\n                }\n            }\n        }\n    }\n\n    cout << ops.size() << \"\\n\";\n    for (auto &op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' '\n             << op.x2 << ' ' << op.y2 << ' '\n             << op.x3 << ' ' << op.y3 << ' '\n             << op.x4 << ' ' << op.y4 << \"\\n\";\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* -------------------------------------------------------------\n   Board representation\n   ------------------------------------------------------------- */\nstruct Board {\n    int a[10][10];\n};\n\ninline void tilt(Board &b, char dir) {\n    if (dir == 'L') {\n        for (int i = 0; i < 10; ++i) {\n            int write = 0;\n            for (int j = 0; j < 10; ++j) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != j) {\n                        b.a[i][write] = v;\n                        b.a[i][j] = 0;\n                    }\n                    ++write;\n                }\n            }\n        }\n    } else if (dir == 'R') {\n        for (int i = 0; i < 10; ++i) {\n            int write = 9;\n            for (int j = 9; j >= 0; --j) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != j) {\n                        b.a[i][write] = v;\n                        b.a[i][j] = 0;\n                    }\n                    --write;\n                }\n            }\n        }\n    } else if (dir == 'F') {          // forward = up\n        for (int j = 0; j < 10; ++j) {\n            int write = 0;\n            for (int i = 0; i < 10; ++i) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != i) {\n                        b.a[write][j] = v;\n                        b.a[i][j] = 0;\n                    }\n                    ++write;\n                }\n            }\n        }\n    } else {                         // dir == 'B'  backward = down\n        for (int j = 0; j < 10; ++j) {\n            int write = 9;\n            for (int i = 9; i >= 0; --i) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != i) {\n                        b.a[write][j] = v;\n                        b.a[i][j] = 0;\n                    }\n                    --write;\n                }\n            }\n        }\n    }\n}\n\n/* -------------------------------------------------------------\n   \u03a3 size\u00b2 of all connected components (four\u2011directional)\n   ------------------------------------------------------------- */\nlong long score(const Board &b) {\n    bool vis[10][10] = {};\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    long long sum = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (b.a[i][j] != 0 && !vis[i][j]) {\n                int flavour = b.a[i][j];\n                int cnt = 0;\n                queue<pair<int,int>> q;\n                q.emplace(i, j);\n                vis[i][j] = true;\n                while (!q.empty()) {\n                    auto [x, y] = q.front(); q.pop();\n                    ++cnt;\n                    for (int k = 0; k < 4; ++k) {\n                        int nx = x + dx[k];\n                        int ny = y + dy[k];\n                        if (0 <= nx && nx < 10 && 0 <= ny && ny < 10 &&\n                            !vis[nx][ny] && b.a[nx][ny] == flavour) {\n                            vis[nx][ny] = true;\n                            q.emplace(nx, ny);\n                        }\n                    }\n                }\n                sum += 1LL * cnt * cnt;\n            }\n        }\n    }\n    return sum;\n}\n\n/* -------------------------------------------------------------\n   place a candy of flavour f into the p\u2011th empty cell (1\u2011based)\n   ------------------------------------------------------------- */\ninline void place(Board &b, int f, int p) {\n    int cnt = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (b.a[i][j] == 0) {\n                ++cnt;\n                if (cnt == p) {\n                    b.a[i][j] = f;\n                    return;\n                }\n            }\n        }\n    }\n}\n\n/* -------------------------------------------------------------\n   collect coordinates of empty cells (row\u2011major order)\n   ------------------------------------------------------------- */\ninline void emptyCells(const Board &b, pair<int,int> *out, int &outCnt) {\n    outCnt = 0;\n    for (int i = 0; i < 10; ++i)\n        for (int j = 0; j < 10; ++j)\n            if (b.a[i][j] == 0)\n                out[outCnt++] = {i, j};\n}\n\n/* -------------------------------------------------------------\n   greedy tilt \u2013 direction that maximises the immediate score\n   ------------------------------------------------------------- */\nchar greedyTilt(const Board &b) {\n    const char dirs[4] = {'F','B','L','R'};\n    long long best = -1;\n    char bestDir = 'F';\n    for (char d : dirs) {\n        Board tmp = b;\n        tilt(tmp, d);\n        long long sc = score(tmp);\n        if (sc > best) {\n            best = sc;\n            bestDir = d;\n        }\n    }\n    return bestDir;\n}\n\n/* -------------------------------------------------------------\n   main\n   ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int TOTAL = 100;\n    vector<int> flavor(TOTAL);\n    for (int i = 0; i < TOTAL; ++i) cin >> flavor[i];\n\n    Board board{};\n    memset(board.a, 0, sizeof(board.a));\n\n    const char DIRS[4] = {'F','B','L','R'};\n    const int K   = 15;          // look\u2011ahead depth\n    const int SIM = 8;           // Monte\u2011Carlo repetitions\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    pair<int,int> empties[100];\n    int emptyCnt;\n\n    for (int t = 0; t < TOTAL; ++t) {\n        int p; cin >> p;\n        place(board, flavor[t], p);\n\n        if (t == TOTAL-1) break;               // last candy \u2013 no tilt needed\n\n        double bestAvg = -1e100;\n        char bestDir = 'F';\n\n        for (char d : DIRS) {\n            Board tmp = board;\n            tilt(tmp, d);\n            long long imm = score(tmp);\n            double total = static_cast<double>(imm);\n\n            for (int sim = 0; sim < SIM; ++sim) {\n                Board simBoard = tmp;\n                int remaining = TOTAL - (t + 1);\n                int steps = min(K, remaining);\n                for (int step = 0; step < steps; ++step) {\n                    // random placement of the known future flavour\n                    emptyCells(simBoard, empties, emptyCnt);\n                    int idx = rng() % emptyCnt;\n                    auto [ri, rj] = empties[idx];\n                    simBoard.a[ri][rj] = flavor[t + 1 + step];\n\n                    // greedy tilt for the simulated step\n                    char d2 = greedyTilt(simBoard);\n                    tilt(simBoard, d2);\n                }\n                total += static_cast<double>(score(simBoard));\n            }\n            double avg = total / (SIM + 1);\n            if (avg > bestAvg) {\n                bestAvg = avg;\n                bestDir = d;\n            }\n        }\n\n        cout << bestDir << '\\n';\n        cout.flush();\n\n        tilt(board, bestDir);          // apply the chosen tilt to the real board\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;          // bring Eigen symbols into scope\n\nstruct GraphInfo {\n    string adjStr;               // original binary string\n    vector<double> eig;          // sorted eigenvalues\n    vector<int> deg;             // sorted degree vector\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;          // no input\n\n    const int N = 10;                          // small, fixed, 4 \u2264 N \u2264 100\n    const int L = N * (N - 1) / 2;\n\n    vector<GraphInfo> graphs;\n    graphs.reserve(M);\n    unordered_set<string> eigSet;              // to avoid identical signatures\n\n    mt19937_64 rng(123456789ULL);              // deterministic seed\n\n    for (int k = 0; k < M; ++k) {\n        while (true) {\n            // ----- generate random graph -----\n            vector<vector<char>> adj(N, vector<char>(N, 0));\n            string s;\n            s.reserve(L);\n            for (int i = 0; i < N; ++i) {\n                for (int j = i + 1; j < N; ++j) {\n                    bool edge = (rng() & 1ULL);\n                    adj[i][j] = adj[j][i] = edge;\n                    s.push_back(edge ? '1' : '0');\n                }\n            }\n\n            // ----- degree vector -----\n            vector<int> deg(N);\n            for (int i = 0; i < N; ++i) {\n                int cnt = 0;\n                for (int j = 0; j < N; ++j) cnt += adj[i][j];\n                deg[i] = cnt;\n            }\n            sort(deg.begin(), deg.end());\n\n            // ----- eigenvalues -----\n            MatrixXd mat(N, N);\n            for (int i = 0; i < N; ++i)\n                for (int j = 0; j < N; ++j)\n                    mat(i, j) = static_cast<double>(adj[i][j]);\n\n            SelfAdjointEigenSolver<MatrixXd> es(mat);\n            VectorXd ev = es.eigenvalues();\n            vector<double> eig(N);\n            for (int i = 0; i < N; ++i) eig[i] = ev(i);\n            sort(eig.begin(), eig.end());\n\n            // ----- fingerprint for uniqueness -----\n            string fingerprint;\n            fingerprint.reserve(N * 12);\n            for (double v : eig) {\n                long long r = llround(v * 1e6);\n                fingerprint += to_string(r);\n                fingerprint.push_back(',');\n            }\n            if (eigSet.find(fingerprint) != eigSet.end()) continue; // duplicate\n\n            eigSet.insert(fingerprint);\n            GraphInfo gi;\n            gi.adjStr = std::move(s);\n            gi.deg = std::move(deg);\n            gi.eig = std::move(eig);\n            graphs.push_back(std::move(gi));\n            break;\n        }\n    }\n\n    // ----- output the graphs -----\n    cout << N << \"\\n\";\n    for (int k = 0; k < M; ++k) {\n        cout << graphs[k].adjStr << \"\\n\";\n    }\n    cout.flush();\n\n    // ----- answer the 100 queries -----\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n        // rebuild adjacency matrix of H\n        vector<vector<char>> adj(N, vector<char>(N, 0));\n        int pos = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                bool edge = (H[pos++] == '1');\n                adj[i][j] = adj[j][i] = edge;\n            }\n        }\n\n        // degree vector of H\n        vector<int> deg(N);\n        for (int i = 0; i < N; ++i) {\n            int cnt = 0;\n            for (int j = 0; j < N; ++j) cnt += adj[i][j];\n            deg[i] = cnt;\n        }\n        sort(deg.begin(), deg.end());\n\n        // eigenvalues of H\n        MatrixXd mat(N, N);\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                mat(i, j) = static_cast<double>(adj[i][j]);\n\n        SelfAdjointEigenSolver<MatrixXd> es(mat);\n        VectorXd ev = es.eigenvalues();\n        vector<double> eig(N);\n        for (int i = 0; i < N; ++i) eig[i] = ev(i);\n        sort(eig.begin(), eig.end());\n\n        // find the closest stored graph\n        int bestIdx = 0;\n        double bestDist = numeric_limits<double>::infinity();\n        for (int k = 0; k < M; ++k) {\n            double dist = 0.0;\n            // eigenvalue part (squared Euclidean distance)\n            for (int i = 0; i < N; ++i) {\n                double d = eig[i] - graphs[k].eig[i];\n                dist += d * d;\n            }\n            // degree part (weighted L1)\n            for (int i = 0; i < N; ++i) {\n                dist += 0.5 * fabs(static_cast<double>(deg[i] - graphs[k].deg[i]));\n            }\n            if (dist < bestDist) {\n                bestDist = dist;\n                bestIdx = k;\n            }\n        }\n        cout << bestIdx << \"\\n\" << flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll INF = (1LL << 60);\n\nstruct Edge {\n    int u, v;\n    int w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[i] = {u, v, w};\n    }\n    // coordinates are irrelevant for the schedule\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        (void)x; (void)y;\n    }\n\n    // ---------- adjacency list ----------\n    vector<vector<tuple<int,int,int>>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u = edges[i].u, v = edges[i].v, w = edges[i].w;\n        adj[u].push_back({v, w, i});\n        adj[v].push_back({u, w, i});\n    }\n\n    // ---------- Brandes (weighted) ----------\n    vector<double> edge_bc(M, 0.0);\n    vector<ll> dist(N);\n    vector<double> sigma(N);\n    vector<double> delta(N);\n    vector<vector<int>> pred(N);\n    vector<vector<int>> pred_e(N);\n    vector<int> order;\n    order.reserve(N);\n\n    for (int s = 0; s < N; ++s) {\n        // initialise\n        fill(dist.begin(), dist.end(), INF);\n        fill(sigma.begin(), sigma.end(), 0.0);\n        for (int i = 0; i < N; ++i) {\n            pred[i].clear();\n            pred_e[i].clear();\n        }\n        order.clear();\n\n        dist[s] = 0;\n        sigma[s] = 1.0;\n        using PQItem = pair<ll,int>;\n        priority_queue<PQItem, vector<PQItem>, greater<PQItem>> pq;\n        pq.emplace(0LL, s);\n\n        // Dijkstra + predecessor collection\n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d != dist[v]) continue;\n            order.push_back(v);\n            for (auto [to, wgt, eid] : adj[v]) {\n                ll nd = d + wgt;\n                if (nd < dist[to]) {\n                    dist[to] = nd;\n                    sigma[to] = sigma[v];\n                    pred[to].clear();\n                    pred_e[to].clear();\n                    pred[to].push_back(v);\n                    pred_e[to].push_back(eid);\n                    pq.emplace(nd, to);\n                } else if (nd == dist[to]) {\n                    sigma[to] += sigma[v];\n                    pred[to].push_back(v);\n                    pred_e[to].push_back(eid);\n                }\n            }\n        }\n\n        // back\u2011propagation of dependencies\n        fill(delta.begin(), delta.end(), 0.0);\n        for (int idx = (int)order.size() - 1; idx >= 0; --idx) {\n            int w = order[idx];\n            for (size_t i = 0; i < pred[w].size(); ++i) {\n                int v = pred[w][i];\n                int eid = pred_e[w][i];\n                double coeff = (sigma[v] / sigma[w]) * (1.0 + delta[w]);\n                delta[v] += coeff;\n                edge_bc[eid] += coeff;          // each direction contributes once\n            }\n        }\n    }\n    // -------------------------------------\n\n    // average betweenness (used for penalty scaling)\n    double total_bc = 0.0;\n    for (double x : edge_bc) total_bc += x;\n    double avg_bc = total_bc / M;\n    const double PENALTY_FACTOR = avg_bc * 0.5;   // tunable\n\n    // sort edges by decreasing betweenness\n    vector<int> idx(M);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(),\n         [&](int a, int b) { return edge_bc[a] > edge_bc[b]; });\n\n    // assignment structures\n    vector<int> day_of_edge(M, -1);\n    vector<double> day_sum(D, 0.0);\n    vector<int> day_cnt(D, 0);\n    vector<vector<int>> inc_cnt(D, vector<int>(N, 0));\n\n    // greedy load\u2011balancing with a small adjacency penalty\n    for (int id : idx) {\n        const Edge &e = edges[id];\n        int best_day = -1;\n        double best_score = numeric_limits<double>::infinity();\n\n        for (int d = 0; d < D; ++d) {\n            if (day_cnt[d] >= K) continue;          // day already full\n            double penalty = PENALTY_FACTOR *\n                             (inc_cnt[d][e.u] + inc_cnt[d][e.v]);\n            double score = day_sum[d] + penalty;\n            if (score < best_score) {\n                best_score = score;\n                best_day = d;\n            }\n        }\n        // best_day must exist because total capacity D*K >= M\n        day_of_edge[id] = best_day + 1;               // 1\u2011based output\n        day_sum[best_day] += edge_bc[id];\n        ++day_cnt[best_day];\n        ++inc_cnt[best_day][e.u];\n        ++inc_cnt[best_day][e.v];\n    }\n\n    // output\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << day_of_edge[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Block {\n    vector<int> cells;   // indices of unit cubes\n    int len;             // number of cells (for vertical lines)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D;\n    if (!(cin >> D)) return 0;\n    const int N = D * D * D;\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n\n    auto idx = [&](int x, int y, int z) { return x * D * D + y * D + z; };\n\n    // need0 / need1 / shared\n    vector<char> need0(N, 0), need1(N, 0), shared(N, 0);\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                int id = idx(x, y, z);\n                need0[id] = (f[0][z][x] == '1') && (r[0][z][y] == '1');\n                need1[id] = (f[1][z][x] == '1') && (r[1][z][y] == '1');\n                shared[id] = need0[id] && need1[id];\n            }\n        }\n    }\n\n    // output arrays\n    vector<int> b0(N, 0), b1(N, 0);\n    int cur_id = 1;\n\n    // -------------------------------------------------------------\n    // 1) shared components (3\u2011D connectivity)\n    const int dx[6] = {1,-1,0,0,0,0};\n    const int dy[6] = {0,0,1,-1,0,0};\n    const int dz[6] = {0,0,0,0,1,-1};\n\n    vector<char> visited(N, 0);\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                int start = idx(x, y, z);\n                if (!shared[start] || visited[start]) continue;\n                // BFS for this component\n                queue<int> q;\n                vector<int> comp;\n                q.push(start);\n                visited[start] = 1;\n                while (!q.empty()) {\n                    int v = q.front(); q.pop();\n                    comp.push_back(v);\n                    int cx = v / (D * D);\n                    int cy = (v / D) % D;\n                    int cz = v % D;\n                    for (int dir = 0; dir < 6; ++dir) {\n                        int nx = cx + dx[dir];\n                        int ny = cy + dy[dir];\n                        int nz = cz + dz[dir];\n                        if (nx < 0 || nx >= D || ny < 0 || ny >= D || nz < 0 || nz >= D) continue;\n                        int nid = idx(nx, ny, nz);\n                        if (shared[nid] && !visited[nid]) {\n                            visited[nid] = 1;\n                            q.push(nid);\n                        }\n                    }\n                }\n                // assign a new block id to this component (used in both objects)\n                for (int cell : comp) {\n                    b0[cell] = cur_id;\n                    b1[cell] = cur_id;\n                }\n                ++cur_id;\n            }\n        }\n    }\n\n    // -------------------------------------------------------------\n    // 2) exclusive cells (need && !shared)\n    vector<char> excl0(N, 0), excl1(N, 0);\n    for (int i = 0; i < N; ++i) {\n        excl0[i] = need0[i] && !shared[i];\n        excl1[i] = need1[i] && !shared[i];\n    }\n\n    // 3) vertical lines for each object\n    vector<Block> lines0, lines1;\n\n    auto extract_lines = [&](const vector<char>& excl, vector<Block>& out) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                int z = 0;\n                while (z < D) {\n                    int id = idx(x, y, z);\n                    if (!excl[id]) { ++z; continue; }\n                    int start = z;\n                    while (z + 1 < D && excl[idx(x, y, z + 1)]) ++z;\n                    int end = z;\n                    Block blk;\n                    blk.len = end - start + 1;\n                    blk.cells.reserve(blk.len);\n                    for (int zz = start; zz <= end; ++zz)\n                        blk.cells.push_back(idx(x, y, zz));\n                    out.push_back(std::move(blk));\n                    ++z;\n                }\n            }\n        }\n    };\n\n    extract_lines(excl0, lines0);\n    extract_lines(excl1, lines1);\n\n    // 4) match vertical lines of equal length\n    unordered_map<int, vector<int>> map0, map1;   // length -> list of indices\n    for (int i = 0; i < (int)lines0.size(); ++i) map0[lines0[i].len].push_back(i);\n    for (int i = 0; i < (int)lines1.size(); ++i) map1[lines1[i].len].push_back(i);\n\n    vector<char> used0(lines0.size(), 0), used1(lines1.size(), 0);\n\n    for (auto &kv : map0) {\n        int len = kv.first;\n        auto it = map1.find(len);\n        if (it == map1.end()) continue;\n        vector<int> &v0 = kv.second;\n        vector<int> &v1 = it->second;\n        size_t i = 0, j = 0;\n        while (i < v0.size() && j < v1.size()) {\n            int id0 = v0[i];\n            int id1 = v1[j];\n            // shared block\n            for (int cell : lines0[id0].cells) b0[cell] = cur_id;\n            for (int cell : lines1[id1].cells) b1[cell] = cur_id;\n            used0[id0] = 1;\n            used1[id1] = 1;\n            ++cur_id;\n            ++i; ++j;\n        }\n    }\n\n    // 5) remaining exclusive lines become exclusive blocks\n    for (int i = 0; i < (int)lines0.size(); ++i) {\n        if (used0[i]) continue;\n        for (int cell : lines0[i].cells) b0[cell] = cur_id;\n        ++cur_id;\n    }\n    for (int i = 0; i < (int)lines1.size(); ++i) {\n        if (used1[i]) continue;\n        for (int cell : lines1[i].cells) b1[cell] = cur_id;\n        ++cur_id;\n    }\n\n    int n = cur_id - 1;\n    cout << n << \"\\n\";\n    // output b0\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                if (x || y || z) cout << ' ';\n                cout << b0[idx(x, y, z)];\n            }\n        }\n    }\n    cout << \"\\n\";\n    // output b1\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                if (x || y || z) cout << ' ';\n                cout << b1[idx(x, y, z)];\n            }\n        }\n    }\n    cout << \"\\n\";\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ---------- Disjoint Set Union ----------\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\n// integer ceil(sqrt(x)) for x >= 0\nint ceil_sqrt(long long x) {\n    if (x <= 0) return 0;\n    long long s = sqrt((long double)x);\n    while (s * s < x) ++s;\n    while ((s - 1) * (s - 1) >= x) --s;\n    return (int)s;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;\n\n    vector<long long> xs(N), ys(N);\n    for (int i = 0; i < N; ++i) cin >> xs[i] >> ys[i];\n\n    struct Edge {\n        int u, v;\n        long long w;\n        int idx;\n    };\n    vector<Edge> edges(M);\n    for (int j = 0; j < M; ++j) {\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[j] = {u, v, w, j};\n    }\n\n    vector<long long> a(K), b(K);\n    for (int k = 0; k < K; ++k) cin >> a[k] >> b[k];\n\n    // ---------- pre\u2011compute all squared distances ----------\n    const long long INF64 = (1LL << 60);\n    vector<vector<long long>> dist2(K, vector<long long>(N));\n    for (int k = 0; k < K; ++k) {\n        for (int i = 0; i < N; ++i) {\n            long long dx = xs[i] - a[k];\n            long long dy = ys[i] - b[k];\n            dist2[k][i] = dx * dx + dy * dy;\n        }\n    }\n\n    // ---------- 1) Minimum Spanning Tree ----------\n    vector<int> B(M, 0);                     // edge ON/OFF\n    vector<Edge> sorted = edges;\n    sort(sorted.begin(), sorted.end(),\n         [](const Edge& e1, const Edge& e2) { return e1.w < e2.w; });\n    DSU dsu(N);\n    for (const auto& e : sorted) {\n        if (dsu.unite(e.u, e.v)) {\n            B[e.idx] = 1;                    // edge belongs to the MST\n        }\n    }\n\n    const int ROOT = 0;                      // station 1 (0\u2011based)\n\n    // ---------- helper containers ----------\n    vector<vector<int>> residents(N);\n    vector<long long> maxDist2(N, -1);\n    vector<int> P(N, 0);\n    vector<char> active(N, 0);\n\n    // ---------- main iterative improvement ----------\n    while (true) {\n        // ----- rebuild adjacency of the current tree -----\n        vector<vector<pair<int,int>>> treeAdj(N);\n        for (int j = 0; j < M; ++j) if (B[j]) {\n            int u = edges[j].u, v = edges[j].v;\n            treeAdj[u].push_back({v, j});\n            treeAdj[v].push_back({u, j});\n        }\n\n        // ----- degree and parent information -----\n        vector<int> degree(N, 0);\n        for (int i = 0; i < N; ++i) degree[i] = (int)treeAdj[i].size();\n\n        // vertices that are still part of the tree (root is always kept)\n        vector<char> inTree(N, 0);\n        for (int i = 0; i < N; ++i)\n            if (i == ROOT || degree[i] > 0) inTree[i] = 1;\n\n        // ----- assignment of residents to the nearest in\u2011tree station -----\n        for (int i = 0; i < N; ++i) {\n            residents[i].clear();\n            maxDist2[i] = -1;\n        }\n        for (int k = 0; k < K; ++k) {\n            long long best = INF64;\n            int bestStation = -1;\n            for (int i = 0; i < N; ++i) if (inTree[i]) {\n                long long d2 = dist2[k][i];\n                if (d2 < best) {\n                    best = d2;\n                    bestStation = i;\n                }\n            }\n            residents[bestStation].push_back(k);\n            if (maxDist2[bestStation] < best) maxDist2[bestStation] = best;\n        }\n\n        // ----- compute radii -----\n        for (int i = 0; i < N; ++i) {\n            if (maxDist2[i] == -1) {\n                P[i] = 0;\n                active[i] = 0;\n            } else {\n                P[i] = ceil_sqrt(maxDist2[i]);\n                active[i] = 1;\n            }\n        }\n\n        // ----- BFS to obtain parent and parentEdge -----\n        vector<int> parent(N, -1), parentEdge(N, -1);\n        queue<int> q;\n        q.push(ROOT);\n        parent[ROOT] = ROOT;\n        while (!q.empty()) {\n            int v = q.front(); q.pop();\n            for (auto [to, idx] : treeAdj[v]) {\n                if (parent[to] != -1) continue;\n                parent[to] = v;\n                parentEdge[to] = idx;\n                q.push(to);\n            }\n        }\n\n        // ----- try to delete one leaf -----\n        bool removed = false;\n        for (int i = 0; i < N; ++i) {\n            if (i == ROOT) continue;\n            if (degree[i] != 1) continue;          // not a leaf\n            int p = parent[i];\n            if (p == -1) continue;                 // unreachable (should not happen)\n\n            // new maximal distance for the parent after receiving i's residents\n            long long newMax = maxDist2[p];\n            if (newMax == -1) newMax = 0;\n            for (int r : residents[i]) {\n                long long d2 = dist2[r][p];\n                if (d2 > newMax) newMax = d2;\n            }\n            int newP = ceil_sqrt(newMax);\n\n            long long cost_before = (active[i] ? (long long)P[i] * P[i] : 0LL)\n                                   + (long long)P[p] * P[p]\n                                   + edges[parentEdge[i]].w;\n            long long cost_after  = (long long)newP * newP;\n\n            if (cost_after < cost_before) {\n                // perform removal\n                B[parentEdge[i]] = 0;\n                // move residents to the parent\n                for (int r : residents[i]) residents[p].push_back(r);\n                residents[i].clear();\n                removed = true;\n                break;          // restart the whole outer loop\n            }\n        }\n\n        if (!removed) break;   // no improvement possible\n    }\n\n    // ---------- final recomputation (to obtain the final radii) ----------\n    // rebuild adjacency one last time\n    vector<vector<pair<int,int>>> finalAdj(N);\n    for (int j = 0; j < M; ++j) if (B[j]) {\n        int u = edges[j].u, v = edges[j].v;\n        finalAdj[u].push_back({v, j});\n        finalAdj[v].push_back({u, j});\n    }\n    vector<char> finalInTree(N, 0);\n    for (int i = 0; i < N; ++i) {\n        if (i == ROOT || !finalAdj[i].empty()) finalInTree[i] = 1;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        residents[i].clear();\n        maxDist2[i] = -1;\n    }\n    for (int k = 0; k < K; ++k) {\n        long long best = INF64;\n        int bestStation = -1;\n        for (int i = 0; i < N; ++i) if (finalInTree[i]) {\n            long long d2 = dist2[k][i];\n            if (d2 < best) {\n                best = d2;\n                bestStation = i;\n            }\n        }\n        residents[bestStation].push_back(k);\n        if (maxDist2[bestStation] < best) maxDist2[bestStation] = best;\n    }\n    for (int i = 0; i < N; ++i) {\n        if (maxDist2[i] == -1) P[i] = 0;\n        else P[i] = ceil_sqrt(maxDist2[i]);\n    }\n\n    // ---------- output ----------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << P[i];\n    }\n    cout << '\\n';\n    for (int j = 0; j < M; ++j) {\n        if (j) cout << ' ';\n        cout << B[j];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 30;                     // fixed by the statement\n    int a[N][N];                          // a[x][y] , 0 <= y <= x\n\n    // read the triangular input\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            cin >> a[x][y];\n        }\n    }\n\n    vector<Op> ops;\n    ops.reserve(10000);\n\n    // bottom\u2011up heapify (min\u2011heap) using only the two down\u2011edges\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            int cx = x, cy = y;\n            while (cx < N - 1) {                     // while a child exists\n                int bestX = cx, bestY = cy;\n                // down\u2011left child (cx+1 , cy)\n                if (a[bestX][bestY] > a[cx + 1][cy]) {\n                    bestX = cx + 1;\n                    bestY = cy;\n                }\n                // down\u2011right child (cx+1 , cy+1)\n                if (a[bestX][bestY] > a[cx + 1][cy + 1]) {\n                    bestX = cx + 1;\n                    bestY = cy + 1;\n                }\n                if (bestX == cx && bestY == cy) break;   // heap property satisfied\n                swap(a[cx][cy], a[bestX][bestY]);\n                ops.push_back({cx, cy, bestX, bestY});\n                cx = bestX;\n                cy = bestY;\n                // safety: the problem guarantees K <= 10000, but we keep the bound\n                if (ops.size() > 10000) break;\n            }\n            if (ops.size() > 10000) break;\n        }\n        if (ops.size() > 10000) break;\n    }\n\n    // output\n    cout << ops.size() << '\\n';\n    for (const auto &op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' '\n             << op.x2 << ' ' << op.y2 << '\\n';\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- helper for transport phase ---------- */\nstruct HeapNode {\n    int number;   // container number\n    int id;       // vertex id\n    bool operator<(HeapNode const& other) const {\n        // priority_queue is a max\u2011heap \u2192 reverse for a min\u2011heap\n        return number > other.number;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    /* ----- input (D is always 9, but read it normally) ----- */\n    int D, N;\n    if (!(cin >> D >> N)) return 0;\n    const int entrance_i = 0;\n    const int entrance_j = (D - 1) / 2;          // (0,4)\n\n    vector<vector<bool>> obstacle(D, vector<bool>(D, false));\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        obstacle[ri][rj] = true;\n    }\n\n    /* ----- BFS \u2013 build the tree ----- */\n    vector<vector<int>> id(D, vector<int>(D, -1));\n    vector<pair<int,int>> coord;   // id \u2192 (i,j)\n    vector<int> depth;             // BFS distance\n    vector<int> parent;            // parent id, -1 for entrance\n\n    queue<pair<int,int>> q;\n    int curId = 0;\n    id[entrance_i][entrance_j] = curId++;\n    coord.emplace_back(entrance_i, entrance_j);\n    depth.push_back(0);\n    parent.push_back(-1);\n    q.emplace(entrance_i, entrance_j);\n\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        int cur = id[i][j];\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= D || nj < 0 || nj >= D) continue;\n            if (obstacle[ni][nj]) continue;\n            if (id[ni][nj] != -1) continue;\n            id[ni][nj] = curId++;\n            coord.emplace_back(ni, nj);\n            depth.push_back(depth[cur] + 1);\n            parent.push_back(cur);\n            q.emplace(ni, nj);\n        }\n    }\n\n    const int totalCells = curId;          // includes entrance\n    const int entranceId = 0;\n    const int M = totalCells - 1;          // number of containers\n    const int maxNumber = totalCells - 2;  // largest possible container number\n\n    /* ----- children list and remaining\u2011children counter ----- */\n    vector<vector<int>> children(totalCells);\n    vector<int> remainingChildren(totalCells, 0);\n    for (int v = 1; v < totalCells; ++v) {\n        int p = parent[v];\n        children[p].push_back(v);\n        ++remainingChildren[p];\n    }\n\n    /* ----- depth distribution for a better target depth ----- */\n    vector<int> allDepths;\n    allDepths.reserve(M);\n    for (int v = 1; v < totalCells; ++v) allDepths.push_back(depth[v]);\n    sort(allDepths.begin(), allDepths.end());   // increasing\n\n    /* ----- leaf set (depth , id) ----- */\n    using LeafKey = pair<int,int>;\n    set<LeafKey> leafSet;\n    for (int v = 1; v < totalCells; ++v) {\n        if (children[v].empty()) leafSet.emplace(depth[v], v);\n    }\n\n    /* ----- placement phase ----- */\n    vector<int> containerNumber(totalCells, -1);   // number assigned to each cell\n    for (int step = 0; step < M; ++step) {\n        int t;               // number of the arriving container\n        cin >> t;\n\n        // target depth according to the empirical distribution\n        int targetIdx = static_cast<int>((static_cast<long long>(t) * (M - 1)) / maxNumber);\n        int targetDepth = allDepths[targetIdx];\n\n        // find leaf with depth closest to targetDepth\n        auto it = leafSet.lower_bound({targetDepth, -1});\n        LeafKey chosen;\n        if (it == leafSet.end()) {\n            chosen = *prev(leafSet.end());            // deepest leaf\n        } else if (it == leafSet.begin()) {\n            chosen = *it;                              // shallowest leaf\n        } else {\n            auto itHigh = it;\n            auto itLow  = prev(it);\n            int diffLow  = abs(itLow->first  - targetDepth);\n            int diffHigh = abs(itHigh->first - targetDepth);\n            chosen = (diffLow <= diffHigh) ? *itLow : *itHigh;\n        }\n\n        int v = chosen.second;\n        leafSet.erase({chosen.first, v});\n\n        containerNumber[v] = t;\n        cout << coord[v].first << ' ' << coord[v].second << \"\\n\";\n        cout.flush();   // required after each placement\n\n        // update parent: maybe it becomes a leaf now\n        int p = parent[v];\n        if (p != -1 && p != entranceId) {\n            if (--remainingChildren[p] == 0) {\n                leafSet.emplace(depth[p], p);\n            }\n        }\n    }\n\n    /* ----- transport phase ----- */\n    priority_queue<HeapNode> pq;\n    for (int c : children[entranceId]) {\n        pq.push({containerNumber[c], c});\n    }\n\n    while (!pq.empty()) {\n        auto cur = pq.top(); pq.pop();\n        int v = cur.id;\n        cout << coord[v].first << ' ' << coord[v].second << \"\\n\";\n        for (int c : children[v]) {\n            pq.push({containerNumber[c], c});\n        }\n    }\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    vector<vector<int>> a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (j) cout << ' ';\n            cout << a[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n    vector<long long> w(N);\n    for (int i = 0; i < N; ++i) cin >> w[i];\n\n    long long total = 0;\n    for (auto x : w) total += x;\n    double target = static_cast<double>(total) / D;\n\n    // random generator\n    std::mt19937_64 rng(\n        chrono::steady_clock::now().time_since_epoch().count());\n\n    vector<int> bestAssign(N);\n    double bestScore = numeric_limits<double>::infinity();\n\n    auto computeScore = [&](const vector<long long> &sum) -> double {\n        double sc = 0.0;\n        for (int d = 0; d < D; ++d) {\n            double diff = static_cast<double>(sum[d]) - target;\n            sc += diff * diff;\n        }\n        return sc;\n    };\n\n    // time limit handling\n    const double TIME_LIMIT = 1.8;                // seconds\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        // ----- 1) random order for greedy -----\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) {\n                 if (w[a] != w[b]) return w[a] > w[b];\n                 return (rng() & 1ULL);\n             });\n\n        // ----- 2) greedy assignment -----\n        vector<int> assign(N, -1);\n        vector<long long> sum(D, 0);\n        for (int idx : order) {\n            int bestSet = 0;\n            long long minSum = sum[0];\n            for (int d = 1; d < D; ++d) {\n                if (sum[d] < minSum) {\n                    minSum = sum[d];\n                    bestSet = d;\n                }\n            }\n            assign[idx] = bestSet;\n            sum[bestSet] += w[idx];\n        }\n\n        // ----- 3) local improvement (hill climbing) -----\n        bool improved = true;\n        while (improved) {\n            improved = false;\n\n            // try moving a single item\n            for (int i = 0; i < N && !improved; ++i) {\n                int a = assign[i];\n                long long wi = w[i];\n                double curDiffA = static_cast<double>(sum[a]) - target;\n                for (int b = 0; b < D; ++b) {\n                    if (b == a) continue;\n                    double curDiffB = static_cast<double>(sum[b]) - target;\n                    double newDiffA = static_cast<double>(sum[a] - wi) - target;\n                    double newDiffB = static_cast<double>(sum[b] + wi) - target;\n                    double delta = (newDiffA * newDiffA + newDiffB * newDiffB) -\n                                   (curDiffA * curDiffA + curDiffB * curDiffB);\n                    if (delta < -1e-9) {\n                        // perform move\n                        sum[a] -= wi;\n                        sum[b] += wi;\n                        assign[i] = b;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n\n            if (improved) continue;\n\n            // try swapping two items\n            for (int i = 0; i < N && !improved; ++i) {\n                int a = assign[i];\n                long long wi = w[i];\n                for (int j = i + 1; j < N; ++j) {\n                    int b = assign[j];\n                    if (a == b) continue;\n                    long long wj = w[j];\n                    double curDiffA = static_cast<double>(sum[a]) - target;\n                    double curDiffB = static_cast<double>(sum[b]) - target;\n                    double newDiffA = static_cast<double>(sum[a] - wi + wj) - target;\n                    double newDiffB = static_cast<double>(sum[b] - wj + wi) - target;\n                    double delta = (newDiffA * newDiffA + newDiffB * newDiffB) -\n                                   (curDiffA * curDiffA + curDiffB * curDiffB);\n                    if (delta < -1e-9) {\n                        // perform swap\n                        sum[a] = sum[a] - wi + wj;\n                        sum[b] = sum[b] - wj + wi;\n                        assign[i] = b;\n                        assign[j] = a;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n        }\n\n        // ----- 4) evaluate -----\n        double curScore = computeScore(sum);\n        if (curScore < bestScore) {\n            bestScore = curScore;\n            bestAssign = assign;\n        }\n\n        // ----- 5) time check -----\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n    }\n\n    // ----- 6) output best assignment -----\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << bestAssign[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    const int per = n / m;                 // = 20 for the given data\n    vector<vector<int>> st(m);             // bottom \u2192 top\n    vector<int> pos(n + 1, -1);            // current stack of each box\n\n    for (int i = 0; i < m; ++i) {\n        st[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x; cin >> x;\n            st[i].push_back(x);\n            pos[x] = i;\n        }\n    }\n\n    vector<pair<int,int>> ops;             // (v , i)   i = 0 \u2192 removal\n\n    // helper: choose a destination for the top box w of stack src\n    auto choose_dest = [&](int w, int src) -> int {\n        // 1) empty stack\n        for (int i = 0; i < m; ++i) if (i != src && st[i].empty())\n            return i;\n        // 2) stack whose top is larger than w (pick the smallest such top)\n        int best = -1, bestTop = INT_MAX;\n        for (int i = 0; i < m; ++i) if (i != src && !st[i].empty() && st[i].back() > w) {\n            if (st[i].back() < bestTop) {\n                bestTop = st[i].back();\n                best = i;\n            }\n        }\n        if (best != -1) return best;\n        // 3) fallback \u2013 any other stack, choose the one with smallest size\n        int minSize = INT_MAX;\n        for (int i = 0; i < m; ++i) if (i != src) {\n            if ((int)st[i].size() < minSize) {\n                minSize = (int)st[i].size();\n                best = i;\n            }\n        }\n        return best;   // always exists because m \u2265 2\n    };\n\n    for (int v = 1; v <= n; ++v) {\n        int s = pos[v];                     // stack that currently holds v\n        // bring v to the top\n        while (!st[s].empty() && st[s].back() != v) {\n            int w = st[s].back();           // top box, w > v\n            int d = choose_dest(w, s);\n            // perform the move\n            st[s].pop_back();\n            st[d].push_back(w);\n            pos[w] = d;\n            ops.emplace_back(w, d + 1);     // +1 because stacks are 1\u2011indexed in output\n        }\n        // now v is on the top \u2192 remove it\n        ops.emplace_back(v, 0);\n        st[s].pop_back();\n        pos[v] = -1;\n    }\n\n    // safety check (the problem guarantees 5000 is enough)\n    assert(ops.size() <= 5000);\n\n    for (auto [v, i] : ops) {\n        cout << v << ' ' << i << '\\n';\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> h;               // (N-1) \u00d7 N  : vertical walls\nvector<string> v;               // N \u00d7 (N-1)  : horizontal walls\nvector<vector<char>> visited;   // visited cells\nstring answer;                  // resulting move sequence\n\n// directions: 0=R, 1=D, 2=L, 3=U\nconst int dr[4] = {0, 1, 0, -1};\nconst int dc[4] = {1, 0, -1, 0};\nconst char dirChar[4] = {'R', 'D', 'L', 'U'};\n\n// true iff we can move from (r,c) to the neighbour in direction dir\nbool canMove(int r, int c, int dir) {\n    int nr = r + dr[dir];\n    int nc = c + dc[dir];\n    if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n    if (dir == 0) {               // right\n        return v[r][c] == '0';\n    } else if (dir == 2) {        // left\n        return v[r][c - 1] == '0';\n    } else if (dir == 1) {        // down\n        return h[r][c] == '0';\n    } else {                      // up\n        return h[r - 1][c] == '0';\n    }\n}\n\n// depth\u2011first traversal\nvoid dfs(int r, int c) {\n    visited[r][c] = 1;\n    for (int dir = 0; dir < 4; ++dir) {\n        if (!canMove(r, c, dir)) continue;\n        int nr = r + dr[dir];\n        int nc = c + dc[dir];\n        if (!visited[nr][nc]) {\n            answer.push_back(dirChar[dir]);          // go to neighbour\n            dfs(nr, nc);\n            answer.push_back(dirChar[(dir + 2) % 4]); // come back\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N)) return 0;\n\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n\n    v.resize(N);\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    // read and ignore the d\u2011values\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            long long x;\n            cin >> x;\n        }\n\n    visited.assign(N, vector<char>(N, 0));\n    dfs(0, 0);\n\n    cout << answer << '\\n';\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int i, j;\n};\n\nint manhattan(const Pos& a, const Pos& b) {\n    return abs(a.i - b.i) + abs(a.j - b.j);\n}\n\n// compute the longest overlap of suffix of a and prefix of b\nint overlap(const string& a, const string& b) {\n    int maxk = min((int)a.size(), (int)b.size());\n    for (int k = maxk; k > 0; --k) {\n        bool ok = true;\n        for (int t = 0; t < k; ++t) {\n            if (a[a.size() - k + t] != b[t]) {\n                ok = false; break;\n            }\n        }\n        if (ok) return k;\n    }\n    return 0;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n    \n    // positions for each letter\n    vector<Pos> pos[26];\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = board[i][j];\n            pos[c - 'A'].push_back({i, j});\n        }\n    }\n    \n    vector<string> cur(M);\n    for (int k = 0; k < M; ++k) cin >> cur[k];\n    \n    // ---------- 1. greedy shortest common superstring ----------\n    while (cur.size() > 1) {\n        int bestOv = -1;\n        int bestI = -1, bestJ = -1;\n        string bestMerged;\n        int sz = cur.size();\n        for (int i = 0; i < sz; ++i) {\n            for (int j = 0; j < sz; ++j) if (i != j) {\n                int ov = overlap(cur[i], cur[j]);\n                if (ov > bestOv) {\n                    bestOv = ov;\n                    bestI = i;\n                    bestJ = j;\n                    bestMerged = cur[i] + cur[j].substr(ov);\n                }\n            }\n        }\n        // merge bestI and bestJ\n        if (bestI > bestJ) swap(bestI, bestJ); // erase larger index first\n        cur.erase(cur.begin() + bestJ);\n        cur.erase(cur.begin() + bestI);\n        cur.push_back(bestMerged);\n    }\n    string S = cur[0];                 // final output string\n    int L = (int)S.size();\n    \n    // ---------- 2. DP for optimal movement ----------\n    // layerPos[p] = list of cells that can type S[p]\n    vector<vector<Pos>> layerPos(L);\n    for (int p = 0; p < L; ++p) {\n        layerPos[p] = pos[S[p] - 'A'];\n    }\n    \n    const int INF = 1e9;\n    vector<vector<int>> dp(L);\n    vector<vector<int>> parent(L);\n    \n    // first layer\n    dp[0].resize(layerPos[0].size());\n    parent[0].resize(layerPos[0].size(), -1);\n    for (size_t i = 0; i < layerPos[0].size(); ++i) {\n        dp[0][i] = manhattan({si, sj}, layerPos[0][i]) + 1;\n    }\n    \n    // subsequent layers\n    for (int p = 1; p < L; ++p) {\n        const auto& prevCells = layerPos[p-1];\n        const auto& curCells  = layerPos[p];\n        dp[p].assign(curCells.size(), INF);\n        parent[p].assign(curCells.size(), -1);\n        for (size_t ci = 0; ci < curCells.size(); ++ci) {\n            int best = INF;\n            int bestPrev = -1;\n            for (size_t pj = 0; pj < prevCells.size(); ++pj) {\n                int cand = dp[p-1][pj] + manhattan(prevCells[pj], curCells[ci]) + 1;\n                if (cand < best) {\n                    best = cand;\n                    bestPrev = (int)pj;\n                }\n            }\n            dp[p][ci] = best;\n            parent[p][ci] = bestPrev;\n        }\n    }\n    \n    // find minimal cost at the last layer\n    int lastIdx = -1;\n    int bestCost = INF;\n    for (size_t i = 0; i < dp[L-1].size(); ++i) {\n        if (dp[L-1][i] < bestCost) {\n            bestCost = dp[L-1][i];\n            lastIdx = (int)i;\n        }\n    }\n    \n    // reconstruct the sequence of cells\n    vector<Pos> answer(L);\n    int curIdx = lastIdx;\n    for (int p = L-1; p >= 0; --p) {\n        answer[p] = layerPos[p][curIdx];\n        curIdx = parent[p][curIdx];\n    }\n    \n    // ---------- output ----------\n    for (const Pos& p : answer) {\n        cout << p.i << ' ' << p.j << '\\n';\n    }\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    double eps;\n    if (!(cin >> N >> M >> eps)) return 0;   // no input\n\n    // ------------------------------------------------------------\n    // 1. read the M polyomino shapes\n    struct Shape {\n        vector<pair<int,int>> cells;   // coordinates relative to (0,0)\n        int max_i = 0, max_j = 0;      // size of the bounding box\n    };\n    vector<Shape> shapes(M);\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        shapes[k].cells.resize(d);\n        for (int t = 0; t < d; ++t) {\n            int i, j;\n            cin >> i >> j;\n            shapes[k].cells[t] = {i, j};\n            shapes[k].max_i = max(shapes[k].max_i, i);\n            shapes[k].max_j = max(shapes[k].max_j, j);\n        }\n    }\n\n    // ------------------------------------------------------------\n    // 2. compute which squares can possibly be covered\n    vector<vector<char>> possible(N, vector<char>(N, 0));\n    for (const auto& sh : shapes) {\n        int height = sh.max_i + 1;\n        int width  = sh.max_j + 1;\n        for (int di = 0; di <= N - height; ++di) {\n            for (int dj = 0; dj <= N - width; ++dj) {\n                for (auto [ci, cj] : sh.cells) {\n                    possible[di + ci][dj + cj] = 1;\n                }\n            }\n        }\n    }\n\n    // ------------------------------------------------------------\n    // 3. drill all cells that may contain oil\n    vector<pair<int,int>> answer;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!possible[i][j]) continue;          // guaranteed empty\n            cout << \"q 1 \" << i << ' ' << j << '\\n';\n            cout.flush();\n            int v;\n            cin >> v;                               // exact value\n            if (v > 0) answer.emplace_back(i, j);\n        }\n    }\n\n    // ------------------------------------------------------------\n    // 4. output the final answer\n    cout << \"a \" << answer.size();\n    for (auto [i, j] : answer) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << '\\n';\n    cout.flush();\n\n    // read the final verdict (1 = correct, 0 = wrong) \u2013 not used further\n    int verdict;\n    if (cin >> verdict) {\n        // nothing to do\n    }\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int W = 1000;                 // hall size (fixed by the statement)\n\nstruct PlacedRect {\n    int i0, j0, i1, j1;                // top\u2011left \u2192 bottom\u2011right (grid points)\n};\n\nstruct Rect {\n    int x0, y0, x1, y1;                // top\u2011left \u2192 bottom\u2011right\n    int width()  const { return x1 - x0; }\n    int height() const { return y1 - y0; }\n    int area()   const { return width() * height(); }\n};\n\n/* split a free rectangle by a placed rectangle (MaxRects style) */\nstatic void splitFreeRect(const Rect& freeR, const Rect& placed, vector<Rect>& out) {\n    // no intersection \u2192 keep the original free rectangle\n    if (placed.x1 <= freeR.x0 || placed.x0 >= freeR.x1 ||\n        placed.y1 <= freeR.y0 || placed.y0 >= freeR.y1) {\n        out.push_back(freeR);\n        return;\n    }\n    // left part\n    if (placed.x0 > freeR.x0)\n        out.push_back({freeR.x0, freeR.y0, placed.x0, freeR.y1});\n    // right part\n    if (placed.x1 < freeR.x1)\n        out.push_back({placed.x1, freeR.y0, freeR.x1, freeR.y1});\n    // top part\n    if (placed.y0 > freeR.y0)\n        out.push_back({max(freeR.x0, placed.x0), freeR.y0,\n                       min(freeR.x1, placed.x1), placed.y0});\n    // bottom part\n    if (placed.y1 < freeR.y1)\n        out.push_back({max(freeR.x0, placed.x0), placed.y1,\n                       min(freeR.x1, placed.x1), freeR.y1});\n}\n\n/* remove any rectangle that is completely contained in another one */\nstatic void prune(vector<Rect>& rects) {\n    int n = (int)rects.size();\n    vector<char> removed(n, 0);\n    for (int i = 0; i < n; ++i) if (!removed[i]) {\n        for (int j = 0; j < n; ++j) if (i != j && !removed[j]) {\n            const Rect& a = rects[i];\n            const Rect& b = rects[j];\n            bool a_contains_b = a.x0 <= b.x0 && a.y0 <= b.y0 &&\n                                a.x1 >= b.x1 && a.y1 >= b.y1;\n            bool b_contains_a = b.x0 <= a.x0 && b.y0 <= a.y0 &&\n                                b.x1 >= a.x1 && b.y1 >= a.y1;\n            if (a_contains_b) removed[j] = 1;\n            else if (b_contains_a) { removed[i] = 1; break; }\n        }\n    }\n    vector<Rect> nxt;\n    for (int i = 0; i < n; ++i) if (!removed[i]) nxt.push_back(rects[i]);\n    rects.swap(nxt);\n}\n\n/* try to place a rectangle of area >= need inside a given free rectangle.\n   Returns true if possible and writes the chosen (h,w) into outH/outW. */\nstatic bool bestFitInFree(const Rect& freeR, long long need,\n                         int& outH, int& outW, long long& outWaste) {\n    bool found = false;\n    long long bestWaste = LLONG_MAX;\n    int bestH = -1, bestW = -1;\n\n    // candidate heights to try \u2013 a few sensible values\n    vector<int> candH;\n    // minimal height that makes width fit\n    int h_min = (int) ((need + freeR.width() - 1) / freeR.width()); // ceil(need / freeW)\n    if (h_min < 1) h_min = 1;\n    if (h_min <= freeR.height()) candH.push_back(h_min);\n    // height close to sqrt(need)\n    int h_sqrt = (int)ceil(sqrt((double)need));\n    if (h_sqrt < 1) h_sqrt = 1;\n    if (h_sqrt <= freeR.height()) candH.push_back(h_sqrt);\n    // maximal height\n    candH.push_back(freeR.height());\n\n    // also try a few heights around the above values\n    for (int delta = -2; delta <= 2; ++delta) {\n        int h = h_sqrt + delta;\n        if (h >= 1 && h <= freeR.height()) candH.push_back(h);\n    }\n\n    // deduplicate\n    sort(candH.begin(), candH.end());\n    candH.erase(unique(candH.begin(), candH.end()), candH.end());\n\n    for (int h : candH) {\n        int w = (int)((need + h - 1) / h);          // ceil(need / h)\n        if (w > freeR.width()) continue;\n        long long area = 1LL * h * w;\n        long long waste = freeR.area() - area;\n        if (waste < bestWaste) {\n            bestWaste = waste;\n            bestH = h;\n            bestW = w;\n            found = true;\n        }\n    }\n\n    if (found) {\n        outH = bestH;\n        outW = bestW;\n        outWaste = bestWaste;\n    }\n    return found;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int W_input, D, N;\n    if (!(cin >> W_input >> D >> N)) return 0;   // W_input is always 1000\n    // we ignore W_input because W is a compile\u2011time constant\n\n    vector<vector<long long>> a(D, vector<long long>(N));\n    for (int d = 0; d < D; ++d)\n        for (int k = 0; k < N; ++k)\n            cin >> a[d][k];\n\n    vector<vector<PlacedRect>> answer(D, vector<PlacedRect>(N));\n\n    for (int d = 0; d < D; ++d) {\n        // ----- items sorted by decreasing required area -----\n        struct Item { int idx; long long area; };\n        vector<Item> items;\n        items.reserve(N);\n        for (int k = 0; k < N; ++k) items.push_back({k, a[d][k]});\n        sort(items.begin(), items.end(),\n             [](const Item& A, const Item& B){ return A.area > B.area; });\n\n        // ----- MaxRects packing -----\n        vector<Rect> freeRects;\n        freeRects.push_back({0, 0, W, W});          // whole hall is free at the start\n        bool fail = false;\n        vector<PlacedRect> placed(N);\n\n        for (const auto& it : items) {\n            long long need = it.area;\n            long long bestWaste = LLONG_MAX;\n            int bestIdx = -1;\n            int bestH = -1, bestW = -1;\n\n            // try every free rectangle\n            for (size_t f = 0; f < freeRects.size(); ++f) {\n                int h, w;\n                long long waste;\n                if (!bestFitInFree(freeRects[f], need, h, w, waste)) continue;\n                if (waste < bestWaste) {\n                    bestWaste = waste;\n                    bestIdx = (int)f;\n                    bestH = h;\n                    bestW = w;\n                }\n            }\n\n            if (bestIdx == -1) {          // cannot place this reservation\n                fail = true;\n                break;\n            }\n\n            // place rectangle at the top\u2011left corner of the chosen free rectangle\n            const Rect& fr = freeRects[bestIdx];\n            Rect placedR = {fr.x0, fr.y0, fr.x0 + bestW, fr.y0 + bestH};\n            placed[it.idx] = {placedR.x0, placedR.y0, placedR.x1, placedR.y1};\n\n            // ----- update free rectangles (MaxRects) -----\n            vector<Rect> newFree;\n            for (size_t i = 0; i < freeRects.size(); ++i) {\n                if ((int)i == bestIdx) continue;   // the rectangle we split will be processed below\n                splitFreeRect(freeRects[i], placedR, newFree);\n            }\n            // split the rectangle we used for placement as well\n            splitFreeRect(fr, placedR, newFree);\n\n            // prune contained rectangles\n            prune(newFree);\n            freeRects.swap(newFree);\n        }\n\n        if (fail) {\n            // fallback to the trivial horizontal\u2011strip layout (guarantees legality)\n            for (int k = 0; k < N; ++k)\n                answer[d][k] = {k, 0, k + 1, W};\n        } else {\n            answer[d] = placed;\n        }\n    }\n\n    // ----- output -----\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            const auto& r = answer[d][k];\n            cout << r.i0 << ' ' << r.j0 << ' '\n                 << r.i1 << ' ' << r.j1 << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr long long MOD = 998244353LL;\n\n/* -------------------------------------------------------------\n   information for a single possible stamp placement\n   ------------------------------------------------------------- */\nstruct OpInfo {\n    int m, p, q;               // stamp id and top\u2011left board position\n    int idx[9];                // flat board indices (0 \u2026 N*N-1)\n    long long add[9];          // stamp values (already % MOD)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;          // N = 9, M = 20, K = 81\n    const int maxP = N - 3;   // last top\u2011left row where a stamp fits\n    const int maxQ = N - 3;   // last top\u2011left column\n\n    // ---------- read initial board ----------\n    vector<long long> initBoard(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            long long x; cin >> x;\n            initBoard[i * N + j] = x % MOD;\n        }\n    }\n\n    // ---------- read stamps ----------\n    vector<array<long long, 9>> stampVals(M);\n    for (int m = 0; m < M; ++m) {\n        for (int u = 0; u < 3; ++u) {\n            for (int v = 0; v < 3; ++v) {\n                long long x; cin >> x;\n                stampVals[m][u * 3 + v] = x % MOD;\n            }\n        }\n    }\n\n    // ---------- pre\u2011compute all possible operations ----------\n    vector<OpInfo> ops;\n    for (int m = 0; m < M; ++m) {\n        for (int p = 0; p <= maxP; ++p) {\n            for (int q = 0; q <= maxQ; ++q) {\n                OpInfo info;\n                info.m = m; info.p = p; info.q = q;\n                int t = 0;\n                for (int u = 0; u < 3; ++u) {\n                    for (int v = 0; v < 3; ++v) {\n                        info.idx[t] = (p + u) * N + (q + v);\n                        info.add[t] = stampVals[m][u * 3 + v];\n                        ++t;\n                    }\n                }\n                ops.push_back(info);\n            }\n        }\n    }\n    const int totalOps = (int)ops.size();   // = 980\n\n    // ------------------------------------------------------------\n    // helper functions\n    // ------------------------------------------------------------\n    auto computeDelta = [&](const vector<long long> &board,\n                            const OpInfo &op) -> long long {\n        long long delta = 0;\n        for (int t = 0; t < 9; ++t) {\n            long long old = board[op.idx[t]];\n            long long newv = old + op.add[t];\n            if (newv >= MOD) newv -= MOD;\n            delta += (newv - old);\n        }\n        return delta;\n    };\n\n    // apply (+1) or remove (-1) a stamp, return the change of the total sum\n    auto applyOp = [&](vector<long long> &board,\n                       const OpInfo &op,\n                       int sign) -> long long {\n        long long delta = 0;\n        if (sign == +1) {\n            for (int t = 0; t < 9; ++t) {\n                int idx = op.idx[t];\n                long long old = board[idx];\n                long long newv = old + op.add[t];\n                if (newv >= MOD) newv -= MOD;\n                board[idx] = newv;\n                delta += (newv - old);\n            }\n        } else { // sign == -1\n            for (int t = 0; t < 9; ++t) {\n                int idx = op.idx[t];\n                long long old = board[idx];\n                long long newv = old - op.add[t];\n                if (newv < 0) newv += MOD;\n                board[idx] = newv;\n                delta += (newv - old);\n            }\n        }\n        return delta;\n    };\n\n    // greedy fill from a given board, returns list of operation ids\n    auto greedyFill = [&](vector<long long> &board) -> vector<int> {\n        vector<int> chosen;\n        while ((int)chosen.size() < K) {\n            long long bestDelta = LLONG_MIN;\n            int bestId = -1;\n            for (int id = 0; id < totalOps; ++id) {\n                long long d = computeDelta(board, ops[id]);\n                if (d > bestDelta) {\n                    bestDelta = d;\n                    bestId = id;\n                }\n            }\n            if (bestDelta <= 0) break;\n            applyOp(board, ops[bestId], +1);\n            chosen.push_back(bestId);\n        }\n        return chosen;\n    };\n\n    // ------------------------------------------------------------\n    // initial greedy solution\n    // ------------------------------------------------------------\n    vector<long long> board = initBoard;\n    vector<int> bestOps = greedyFill(board);\n    long long bestScore = 0;\n    for (long long v : board) bestScore += v;\n\n    // ------------------------------------------------------------\n    // hill\u2011climbing loop (time\u2011bounded)\n    // ------------------------------------------------------------\n    std::mt19937_64 rng(\n        (uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_real_distribution<double> distReal(0.0, 1.0);\n    const double TIME_LIMIT = 1.9;          // seconds\n    auto startTime = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        // start from the current best solution\n        vector<int> curOps = bestOps;\n        vector<long long> curBoard = initBoard;\n        for (int id : curOps) applyOp(curBoard, ops[id], +1);\n\n        int sz = (int)curOps.size();\n        int moveType = rng() % 3;   // 0 = insert, 1 = delete, 2 = replace\n\n        // ----- INSERT -------------------------------------------------\n        if (moveType == 0 && sz < K) {\n            int pos = rng() % (sz + 1);                 // insertion position\n            int newId = rng() % totalOps;\n            curOps.insert(curOps.begin() + pos, newId);\n            applyOp(curBoard, ops[newId], +1);\n        }\n        // ----- DELETE -------------------------------------------------\n        else if (moveType == 1 && sz > 0) {\n            int pos = rng() % sz;\n            int delId = curOps[pos];\n            applyOp(curBoard, ops[delId], -1);\n            curOps.erase(curOps.begin() + pos);\n        }\n        // ----- REPLACE ------------------------------------------------\n        else if (moveType == 2 && sz > 0) {\n            int pos = rng() % sz;\n            int oldId = curOps[pos];\n            int newId = rng() % totalOps;\n            applyOp(curBoard, ops[oldId], -1);\n            applyOp(curBoard, ops[newId], +1);\n            curOps[pos] = newId;\n        }\n        // if the chosen move was illegal (e.g. insert when size==K) we simply\n        // skip it \u2013 the loop will try another random move next time.\n\n        // ----- greedy completion after the modification -------------\n        while ((int)curOps.size() < K) {\n            long long bestDelta = LLONG_MIN;\n            int bestId = -1;\n            for (int id = 0; id < totalOps; ++id) {\n                long long d = computeDelta(curBoard, ops[id]);\n                if (d > bestDelta) {\n                    bestDelta = d;\n                    bestId = id;\n                }\n            }\n            if (bestDelta <= 0) break;\n            applyOp(curBoard, ops[bestId], +1);\n            curOps.push_back(bestId);\n        }\n\n        // ----- evaluate ------------------------------------------------\n        long long curScore = 0;\n        for (long long v : curBoard) curScore += v;\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestOps.swap(curOps);\n        }\n    }\n\n    // ------------------------------------------------------------\n    // final greedy completion (in case the best solution is not full)\n    // ------------------------------------------------------------\n    board = initBoard;\n    for (int id : bestOps) applyOp(board, ops[id], +1);\n    while ((int)bestOps.size() < K) {\n        long long bestDelta = LLONG_MIN;\n        int bestId = -1;\n        for (int id = 0; id < totalOps; ++id) {\n            long long d = computeDelta(board, ops[id]);\n            if (d > bestDelta) {\n                bestDelta = d;\n                bestId = id;\n            }\n        }\n        if (bestDelta <= 0) break;\n        applyOp(board, ops[bestId], +1);\n        bestOps.push_back(bestId);\n    }\n\n    // ------------------------------------------------------------\n    // output\n    // ------------------------------------------------------------\n    cout << bestOps.size() << \"\\n\";\n    for (int id : bestOps) {\n        const OpInfo &o = ops[id];\n        cout << o.m << ' ' << o.p << ' ' << o.q << \"\\n\";\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\n// generate a Manhattan walk from (r,c) to (tr,tc)\nstatic string walk(int r, int c, int tr, int tc) {\n    string s;\n    while (r > tr) { s.push_back('U'); --r; }\n    while (r < tr) { s.push_back('D'); ++r; }\n    while (c > tc) { s.push_back('L'); --c; }\n    while (c < tc) { s.push_back('R'); ++c; }\n    return s;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> A(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> A[i][j];\n\n    // actions for each crane\n    vector<string> act(N);\n    // small cranes: bomb at turn 0, later do nothing\n    // we will pad them later to the length of the large crane\n    for (int i = 1; i < N; ++i) act[i] = \"B\";\n\n    // large crane (crane 0)\n    string &big = act[0];\n    int curR = 0, curC = 0;               // start position (0,0)\n\n    for (int i = 0; i < N; ++i) {        // receiving gate i\n        for (int j = 0; j < N; ++j) {    // j\u2011th container of this gate\n            // move to (i,0)\n            big += walk(curR, curC, i, 0);\n            curR = i; curC = 0;\n            // pick up\n            big.push_back('P');\n            int b = A[i][j];\n            int dr = b / N;               // destination row\n            // move to dispatch gate (dr, N-1)\n            big += walk(curR, curC, dr, N - 1);\n            curR = dr; curC = N - 1;\n            // release\n            big.push_back('Q');\n            // move back to the receiving gate (i,0)\n            big += walk(curR, curC, i, 0);\n            curR = i; curC = 0;\n        }\n    }\n\n    // pad small cranes with '.' to the length of the longest string\n    size_t L = big.size();\n    for (int i = 1; i < N; ++i) {\n        if (act[i].size() < L) act[i].append(L - act[i].size(), '.');\n    }\n\n    // output\n    for (int i = 0; i < N; ++i) {\n        cout << act[i] << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Node {\n    int x, y;\n    int amt;          // remaining amount to send / receive\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> h[i][j];\n\n    vector<Node> sources, sinks;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (h[i][j] > 0) sources.push_back({i, j, h[i][j]});\n            else if (h[i][j] < 0) sinks.push_back({i, j, -h[i][j]});\n        }\n\n    if (sources.empty() && sinks.empty()) return 0;   // already flat\n\n    // current truck position\n    int curX = 0, curY = 0;\n    vector<string> ops;\n    ops.reserve(40000);\n\n    auto dist = [&](int x1, int y1, int x2, int y2) {\n        return abs(x1 - x2) + abs(y1 - y2);\n    };\n\n    // move from (curX,curY) to (tx,ty) using Manhattan steps\n    auto moveTo = [&](int tx, int ty) {\n        while (curX != tx) {\n            if (curX < tx) {\n                ops.emplace_back(\"D\");\n                ++curX;\n            } else {\n                ops.emplace_back(\"U\");\n                --curX;\n            }\n        }\n        while (curY != ty) {\n            if (curY < ty) {\n                ops.emplace_back(\"R\");\n                ++curY;\n            } else {\n                ops.emplace_back(\"L\");\n                --curY;\n            }\n        }\n    };\n\n    // Main loop: process all sources\n    while (true) {\n        // find the nearest source that still has soil\n        int srcIdx = -1;\n        int best = INT_MAX;\n        for (int i = 0; i < (int)sources.size(); ++i) {\n            if (sources[i].amt == 0) continue;\n            int d = dist(curX, curY, sources[i].x, sources[i].y);\n            if (d < best) {\n                best = d;\n                srcIdx = i;\n            }\n        }\n        if (srcIdx == -1) break;   // all supplies exhausted\n\n        // go to that source (empty)\n        moveTo(sources[srcIdx].x, sources[srcIdx].y);\n\n        // load everything from the source\n        int loadAmt = sources[srcIdx].amt;\n        ops.emplace_back(\"+\" + to_string(loadAmt));\n        sources[srcIdx].amt = 0;\n        int curLoad = loadAmt;   // amount currently on the truck\n\n        // deliver while we still carry soil\n        while (curLoad > 0) {\n            // nearest sink with remaining demand\n            int sinkIdx = -1;\n            best = INT_MAX;\n            for (int i = 0; i < (int)sinks.size(); ++i) {\n                if (sinks[i].amt == 0) continue;\n                int d = dist(curX, curY, sinks[i].x, sinks[i].y);\n                if (d < best) {\n                    best = d;\n                    sinkIdx = i;\n                }\n            }\n            // there must be a sink because total supply = total demand\n            moveTo(sinks[sinkIdx].x, sinks[sinkIdx].y);\n            int unloadAmt = min(curLoad, sinks[sinkIdx].amt);\n            ops.emplace_back(\"-\" + to_string(unloadAmt));\n            curLoad -= unloadAmt;\n            sinks[sinkIdx].amt -= unloadAmt;\n        }\n        // now the truck is empty again, position = last visited sink\n    }\n\n    // output the operation list\n    for (const string& s : ops) {\n        cout << s << '\\n';\n    }\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct PairScore {\n    int i, j;\n    long long score;\n    bool operator<(PairScore const& other) const {\n        return score > other.score; // descending\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    const int S = 2 * N * (N - 1);          // 60 for N = 6\n    const int cells = N * N;               // 36\n\n    // read initial seeds\n    vector<vector<int>> X(S, vector<int>(M));\n    for (int i = 0; i < S; ++i)\n        for (int j = 0; j < M; ++j)\n            cin >> X[i][j];\n\n    // global maxima per component (used as weights)\n    vector<long long> weight(M, 0);\n    for (int l = 0; l < M; ++l) {\n        long long mx = 0;\n        for (int i = 0; i < S; ++i) mx = max(mx, (long long)X[i][l]);\n        weight[l] = mx;\n    }\n\n    // pre\u2011compute the list of edges (cell indices)\n    vector<pair<int,int>> edges;\n    edges.reserve(2 * N * (N - 1));\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            int id = r * N + c;\n            if (c + 1 < N) edges.emplace_back(id, id + 1);          // right neighbor\n            if (r + 1 < N) edges.emplace_back(id, id + N);          // down neighbor\n        }\n    }\n    // edges size = 60 for N = 6\n\n    for (int turn = 0; turn < T; ++turn) {\n        // 1. weighted sum for each seed\n        vector<long long> W(S, 0);\n        for (int i = 0; i < S; ++i) {\n            long long sum = 0;\n            for (int l = 0; l < M; ++l) sum += weight[l] * (long long)X[i][l];\n            W[i] = sum;\n        }\n\n        // 2. compute pair scores\n        vector<PairScore> pairs;\n        pairs.reserve(S * (S - 1) / 2);\n        for (int i = 0; i < S; ++i) {\n            for (int j = i + 1; j < S; ++j) {\n                long long sc = 0;\n                for (int l = 0; l < M; ++l) {\n                    int mx = max(X[i][l], X[j][l]);\n                    sc += weight[l] * (long long)mx;\n                }\n                pairs.push_back({i, j, sc});\n            }\n        }\n        sort(pairs.begin(), pairs.end());\n\n        // 3. board initialisation\n        vector<int> board(cells, -1);\n        vector<char> usedSeed(S, 0);\n        size_t edgePtr = 0;\n\n        // 4. place best pairs on free edges\n        for (const auto& p : pairs) {\n            if (usedSeed[p.i] || usedSeed[p.j]) continue;\n            while (edgePtr < edges.size() &&\n                   (board[edges[edgePtr].first] != -1 ||\n                    board[edges[edgePtr].second] != -1)) {\n                ++edgePtr;\n            }\n            if (edgePtr == edges.size()) break;\n            board[edges[edgePtr].first]  = p.i;\n            board[edges[edgePtr].second] = p.j;\n            usedSeed[p.i] = usedSeed[p.j] = 1;\n            ++edgePtr;\n        }\n\n        // 5. fill remaining cells with best unused seeds\n        vector<int> remaining;\n        remaining.reserve(S);\n        for (int i = 0; i < S; ++i) if (!usedSeed[i]) remaining.push_back(i);\n        sort(remaining.begin(), remaining.end(),\n             [&](int a, int b) { return W[a] > W[b]; });\n\n        size_t rpos = 0;\n        for (int cell = 0; cell < cells; ++cell) {\n            if (board[cell] == -1) {\n                board[cell] = remaining[rpos++];\n            }\n        }\n\n        // 6. output board (row\u2011major)\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (c) cout << ' ';\n                cout << board[r * N + c];\n            }\n            cout << '\\n';\n        }\n        cout.flush();\n\n        // 7. read next batch of seeds\n        for (int i = 0; i < S; ++i)\n            for (int l = 0; l < M; ++l)\n                cin >> X[i][l];\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, V;\n    if (!(cin >> N >> M >> V)) return 0;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) cin >> s[i];\n    for (int i = 0; i < N; ++i) cin >> t[i];\n\n    // collect source cells (initial takoyaki not on target) and target cells (empty)\n    vector<Pos> src, dst;\n    vector<vector<int>> hasTak(N, vector<int>(N, 0));\n    vector<vector<int>> isTarget(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (s[i][j] == '1') hasTak[i][j] = 1;\n            if (t[i][j] == '1') isTarget[i][j] = 1;\n        }\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (hasTak[i][j] && !isTarget[i][j])\n                src.push_back({i, j});\n            if (!hasTak[i][j] && isTarget[i][j])\n                dst.push_back({i, j});\n        }\n\n    const int Vprime = 2;               // root + one leaf\n    // output arm description\n    cout << Vprime << \"\\n\";\n    cout << 0 << \" \" << 1 << \"\\n\";       // parent of vertex 1, length 1\n    cout << 0 << \" \" << 0 << \"\\n\";       // initial root position\n\n    // direction vectors\n    const int dx[4] = {0, 1, 0, -1};\n    const int dy[4] = {1, 0, -1, 0};\n\n    // helper to compute rotation cost\n    auto rotCost = [&](int cur, int target) -> int {\n        int diff = (target - cur + 4) % 4;\n        if (diff == 0) return 0;\n        if (diff == 2) return 2;\n        return 1;\n    };\n\n    // storage for operations\n    vector<string> ops;\n\n    // helper to push a turn\n    auto pushTurn = [&](char mv, char rot, char leafAct) {\n        string s(4, '.');\n        s[0] = mv;\n        s[1] = rot;\n        s[3] = leafAct;\n        ops.push_back(s);\n    };\n\n    // current state\n    int curX = 0, curY = 0;   // root position\n    int curDir = 0;           // leaf points right (dx=0, dy=+1)\n\n    // rotate leaf to target direction (may need 1 or 2 turns)\n    auto rotateTo = [&](int targetDir) {\n        int diff = (targetDir - curDir + 4) % 4;\n        if (diff == 0) return;\n        if (diff == 1) {\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n        } else if (diff == 3) {\n            pushTurn('.', 'L', '.');\n            curDir = (curDir + 3) % 4;\n        } else { // diff == 2\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n        }\n    };\n\n    // move root to (tx,ty) by Manhattan steps\n    auto moveRootTo = [&](int tx, int ty) {\n        while (curX < tx) {\n            pushTurn('D', '.', '.');\n            ++curX;\n        }\n        while (curX > tx) {\n            pushTurn('U', '.', '.');\n            --curX;\n        }\n        while (curY < ty) {\n            pushTurn('R', '.', '.');\n            ++curY;\n        }\n        while (curY > ty) {\n            pushTurn('L', '.', '.');\n            --curY;\n        }\n    };\n\n    // alive flags\n    vector<char> srcAlive(src.size(), 1);\n    vector<char> dstAlive(dst.size(), 1);\n    int remaining = (int)src.size();\n\n    while (remaining > 0) {\n        // ----- choose nearest source -----\n        int bestDist = INT_MAX;\n        int bestIdx = -1, bestDir = -1, bestRx = -1, bestRy = -1;\n        for (int i = 0; i < (int)src.size(); ++i) if (srcAlive[i]) {\n            const Pos &p = src[i];\n            for (int d = 0; d < 4; ++d) {\n                int rx = p.x - dx[d];\n                int ry = p.y - dy[d];\n                if (0 <= rx && rx < N && 0 <= ry && ry < N) {\n                    int dist = abs(curX - rx) + abs(curY - ry);\n                    if (dist < bestDist) {\n                        bestDist = dist;\n                        bestIdx = i;\n                        bestDir = d;\n                        bestRx = rx;\n                        bestRy = ry;\n                    }\n                }\n            }\n        }\n        // move to source\n        rotateTo(bestDir);\n        moveRootTo(bestRx, bestRy);\n        pushTurn('.', '.', 'P');          // pick up\n        srcAlive[bestIdx] = 0;\n        --remaining;\n\n        // ----- choose nearest target -----\n        int bestDist2 = INT_MAX;\n        int bestIdxT = -1, bestDir2 = -1, bestRx2 = -1, bestRy2 = -1;\n        for (int i = 0; i < (int)dst.size(); ++i) if (dstAlive[i]) {\n            const Pos &p = dst[i];\n            for (int d = 0; d < 4; ++d) {\n                int rx = p.x - dx[d];\n                int ry = p.y - dy[d];\n                if (0 <= rx && rx < N && 0 <= ry && ry < N) {\n                    int rotC = rotCost(curDir, d);\n                    int dist = abs(curX - rx) + abs(curY - ry) + rotC;\n                    if (dist < bestDist2) {\n                        bestDist2 = dist;\n                        bestIdxT = i;\n                        bestDir2 = d;\n                        bestRx2 = rx;\n                        bestRy2 = ry;\n                    }\n                }\n            }\n        }\n        // move to target\n        rotateTo(bestDir2);\n        moveRootTo(bestRx2, bestRy2);\n        pushTurn('.', '.', 'P');          // release\n        dstAlive[bestIdxT] = 0;\n    }\n\n    // output operations\n    for (const string &s : ops) cout << s << \"\\n\";\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ull = unsigned long long;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if(!(cin >> N)) return 0;\n    vector<pair<int,int>> mackerel(N);\n    vector<pair<int,int>> sardine(N);\n    for (int i = 0; i < N; ++i) {\n        int x,y; cin >> x >> y;\n        mackerel[i] = {x,y};\n    }\n    unordered_set<ull> sardineSet;\n    sardineSet.reserve(N*2);\n    for (int i = 0; i < N; ++i) {\n        int x,y; cin >> x >> y;\n        sardine[i] = {x,y};\n        ull key = ( (ull)x << 32 ) | (unsigned int) y;\n        sardineSet.insert(key);\n    }\n    \n    // ------------------------------------------------------------\n    // 1) try to isolate a single mackerel with a 1x1 square\n    for (auto [x,y] : mackerel) {\n        if (x >= 100000 || y >= 100000) continue; // would go out of bounds\n        bool ok = true;\n        for (int dx = 0; dx <= 1 && ok; ++dx) {\n            for (int dy = 0; dy <= 1; ++dy) {\n                int nx = x + dx;\n                int ny = y + dy;\n                ull key = ( (ull)nx << 32 ) | (unsigned int) ny;\n                if (sardineSet.find(key) != sardineSet.end()) {\n                    ok = false;\n                    break;\n                }\n            }\n        }\n        if (ok) {\n            // output rectangle [x,x+1] \u00d7 [y,y+1]\n            cout << 4 << \"\\n\";\n            cout << x << \" \" << y << \"\\n\";\n            cout << x+1 << \" \" << y << \"\\n\";\n            cout << x+1 << \" \" << y+1 << \"\\n\";\n            cout << x << \" \" << y+1 << \"\\n\";\n            return 0;\n        }\n    }\n    \n    // ------------------------------------------------------------\n    // 2) grid cell fallback\n    const int G = 2000;                // side length of a cell\n    const int C = 100000 / G;          // 50, divides exactly\n    vector<vector<int>> mCount(C, vector<int>(C, 0));\n    vector<vector<int>> sCount(C, vector<int>(C, 0));\n    \n    auto cellIdx = [&](int coord) -> int {\n        int idx = coord / G;\n        if (idx >= C) idx = C-1;\n        return idx;\n    };\n    \n    for (auto [x,y] : mackerel) {\n        int cx = cellIdx(x);\n        int cy = cellIdx(y);\n        ++mCount[cx][cy];\n    }\n    for (auto [x,y] : sardine) {\n        int cx = cellIdx(x);\n        int cy = cellIdx(y);\n        ++sCount[cx][cy];\n    }\n    \n    int bestCx = -1, bestCy = -1;\n    int bestNet = INT_MIN;\n    for (int cx = 0; cx < C; ++cx) {\n        for (int cy = 0; cy < C; ++cy) {\n            int net = mCount[cx][cy] - sCount[cx][cy];\n            if (net > bestNet) {\n                bestNet = net;\n                bestCx = cx;\n                bestCy = cy;\n            }\n        }\n    }\n    if (bestNet > 0) {\n        int left   = bestCx * G;\n        int right  = (bestCx + 1) * G;\n        int bottom = bestCy * G;\n        int top    = (bestCy + 1) * G;\n        cout << 4 << \"\\n\";\n        cout << left << \" \" << bottom << \"\\n\";\n        cout << right << \" \" << bottom << \"\\n\";\n        cout << right << \" \" << top << \"\\n\";\n        cout << left << \" \" << top << \"\\n\";\n        return 0;\n    }\n    \n    // ------------------------------------------------------------\n    // 3) whole area fallback\n    cout << 4 << \"\\n\";\n    cout << 0 << \" \" << 0 << \"\\n\";\n    cout << 100000 << \" \" << 0 << \"\\n\";\n    cout << 100000 << \" \" << 100000 << \"\\n\";\n    cout << 0 << \" \" << 100000 << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int p;          // rectangle index\n    int r;          // rotation 0/1\n    char d;         // direction 'U' or 'L'\n    int b;          // reference rectangle (-1 or previous index)\n};\n\nstruct Placed {\n    long long x, y; // lower\u2011left corner\n    long long w, h; // size used for placement (estimated)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    long long sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n    vector<long long> wObs(N), hObs(N);\n    for (int i = 0; i < N; ++i) cin >> wObs[i] >> hObs[i];\n\n    const long long MARGIN = 5LL * sigma;          // safety margin\n    vector<long long> wEst(N), hEst(N);\n    for (int i = 0; i < N; ++i) {\n        wEst[i] = wObs[i] + MARGIN;\n        hEst[i] = hObs[i] + MARGIN;\n    }\n\n    // ---------- helper: greedy placement for a given rotation vector ----------\n    auto greedy_place = [&](const vector<int> &rot) -> vector<Op> {\n        vector<Op> ops;\n        vector<Placed> placed;\n        ops.reserve(N);\n        placed.reserve(N);\n\n        long long curMaxX = 0, curMaxY = 0;\n\n        for (int i = 0; i < N; ++i) {\n            long long wi = (rot[i] == 0 ? wEst[i] : hEst[i]);\n            long long hi = (rot[i] == 0 ? hEst[i] : wEst[i]);\n\n            long long bestScore = (1LL << 62);\n            long long bestX = 0, bestY = 0;\n            int bestB = -1;\n            char bestD = 'U';\n\n            // try all possible reference rectangles and both directions\n            for (int b = -1; b <= i - 1; ++b) {\n                // direction U\n                {\n                    long long x = (b == -1) ? 0LL : placed[b].x + placed[b].w;\n                    long long y = 0;\n                    for (const auto &p : placed) {\n                        // overlap in x ?\n                        if (!(x + wi <= p.x || x >= p.x + p.w)) {\n                            y = max(y, p.y + p.h);\n                        }\n                    }\n                    long long newMaxX = max(curMaxX, x + wi);\n                    long long newMaxY = max(curMaxY, y + hi);\n                    long long score = newMaxX + newMaxY;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestX = x; bestY = y;\n                        bestB = b; bestD = 'U';\n                    }\n                }\n                // direction L\n                {\n                    long long y = (b == -1) ? 0LL : placed[b].y + placed[b].h;\n                    long long x = 0;\n                    for (const auto &p : placed) {\n                        // overlap in y ?\n                        if (!(y + hi <= p.y || y >= p.y + p.h)) {\n                            x = max(x, p.x + p.w);\n                        }\n                    }\n                    long long newMaxX = max(curMaxX, x + wi);\n                    long long newMaxY = max(curMaxY, y + hi);\n                    long long score = newMaxX + newMaxY;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestX = x; bestY = y;\n                        bestB = b; bestD = 'L';\n                    }\n                }\n            }\n\n            // commit the best placement\n            ops.push_back({i, rot[i], bestD, bestB});\n            placed.push_back({bestX, bestY, wi, hi});\n            curMaxX = max(curMaxX, bestX + wi);\n            curMaxY = max(curMaxY, bestY + hi);\n        }\n\n        // ----- optional dropping of a suffix (choose best prefix) -----\n        // prefix maxX / maxY\n        vector<long long> prefMaxX(N), prefMaxY(N);\n        long long curX = 0, curY = 0;\n        for (int i = 0; i < N; ++i) {\n            curX = max(curX, placed[i].x + placed[i].w);\n            curY = max(curY, placed[i].y + placed[i].h);\n            prefMaxX[i] = curX;\n            prefMaxY[i] = curY;\n        }\n        // suffix penalty (estimated)\n        vector<long long> suffix(N + 1, 0);\n        for (int i = N - 1; i >= 0; --i) {\n            suffix[i] = suffix[i + 1] + wEst[i] + hEst[i];\n        }\n        // choose k (number of placed rectangles) minimizing estimated score\n        int bestK = N;\n        long long bestEstScore = prefMaxX[N - 1] + prefMaxY[N - 1] + suffix[N];\n        for (int k = 0; k <= N; ++k) {\n            long long curScore = (k == 0 ? 0 : prefMaxX[k - 1])\n                               + (k == 0 ? 0 : prefMaxY[k - 1])\n                               + suffix[k];\n            if (curScore < bestEstScore) {\n                bestEstScore = curScore;\n                bestK = k;\n            }\n        }\n        // keep only the first bestK operations\n        ops.resize(bestK);\n        return ops;\n    };\n\n    // ---------- generate a few different candidates ----------\n    const int M = min(T, 20);                 // number of different placements\n    vector<vector<Op>> candidates;\n    candidates.reserve(M);\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    for (int c = 0; c < M; ++c) {\n        vector<int> rot(N);\n        for (int i = 0; i < N; ++i) {\n            // random rotation, 50% chance\n            rot[i] = (rng() & 1);\n        }\n        candidates.push_back(greedy_place(rot));\n    }\n\n    // ---------- interactive loop ----------\n    for (int turn = 0; turn < T; ++turn) {\n        const vector<Op> &ops = candidates[turn % M];\n        int n = (int)ops.size();\n        cout << n << '\\n';\n        for (const auto &op : ops) {\n            cout << op.p << ' ' << op.r << ' ' << op.d << ' ' << op.b << '\\n';\n        }\n        cout.flush();\n\n        long long Wp, Hp;\n        if (!(cin >> Wp >> Hp)) return 0;   // read the noisy result (ignored)\n    }\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    if (!(cin >> N >> M >> H)) return 0;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n\n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    // coordinates are irrelevant for the algorithm\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // sort neighbours by increasing beauty \u2013 low\u2011beauty neighbours are visited first\n    for (int v = 0; v < N; ++v) {\n        sort(adj[v].begin(), adj[v].end(),\n             [&](int a, int b){ return A[a] < A[b]; });\n    }\n\n    const int UNSET = -2;\n    vector<int> parent(N, UNSET);\n    vector<int> depth (N, -1);\n\n    // vertices processed from low beauty to high beauty\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int i, int j){ return A[i] < A[j]; });\n\n    for (int v : order) {\n        if (parent[v] != UNSET) continue;          // already placed\n\n        // start a new tree with v as root\n        parent[v] = -1;\n        depth [v] = 0;\n        queue<pair<int,int>> q;\n        q.emplace(v, 0);\n\n        while (!q.empty()) {\n            auto [u, d] = q.front(); q.pop();\n            if (d == H) continue;                  // cannot go deeper\n            for (int w : adj[u]) {\n                if (parent[w] == UNSET) {\n                    parent[w] = u;\n                    depth [w] = d + 1;\n                    q.emplace(w, d + 1);\n                }\n            }\n        }\n    }\n\n    // output the parent array\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << parent[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DirInfo {\n    char dir;                     // 'L','R','U','D'\n    int idx;                      // row or column index\n    multiset<int> dists;          // distances of assigned Oni\n    int maxDist = 0;              // 0 if empty\n};\n\nstruct OniInfo {\n    vector<int> dirIds;           // safe direction ids\n    vector<int> dists;            // distance for each dirId (same order)\n    int curDir = -1;              // currently assigned direction id\n    int curDist = -1;             // distance for curDir\n};\n\nchar opposite(char d) {\n    if (d == 'L') return 'R';\n    if (d == 'R') return 'L';\n    if (d == 'U') return 'D';\n    return 'U';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    const int MAXN = 20;\n    // create direction ids\n    int dirCnt = 0;\n    int rowL[MAXN], rowR[MAXN], colU[MAXN], colD[MAXN];\n    for (int i = 0; i < N; ++i) {\n        rowL[i] = dirCnt++;\n        rowR[i] = dirCnt++;\n    }\n    for (int j = 0; j < N; ++j) {\n        colU[j] = dirCnt++;\n        colD[j] = dirCnt++;\n    }\n    vector<DirInfo> dirs(dirCnt);\n    for (int i = 0; i < N; ++i) {\n        dirs[rowL[i]] = {'L', i, {}, 0};\n        dirs[rowR[i]] = {'R', i, {}, 0};\n    }\n    for (int j = 0; j < N; ++j) {\n        dirs[colU[j]] = {'U', j, {}, 0};\n        dirs[colD[j]] = {'D', j, {}, 0};\n    }\n\n    // collect Oni\n    vector<OniInfo> ons;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] != 'x') continue;\n            OniInfo o;\n            // safety tests\n            bool safeU = true, safeD = true, safeL = true, safeR = true;\n            for (int k = 0; k < i; ++k) if (board[k][j] == 'o') safeU = false;\n            for (int k = i + 1; k < N; ++k) if (board[k][j] == 'o') safeD = false;\n            for (int k = 0; k < j; ++k) if (board[i][k] == 'o') safeL = false;\n            for (int k = j + 1; k < N; ++k) if (board[i][k] == 'o') safeR = false;\n\n            int dU = i + 1;\n            int dD = N - i;\n            int dL = j + 1;\n            int dR = N - j;\n\n            if (safeU) {\n                o.dirIds.push_back(colU[j]);\n                o.dists.push_back(dU);\n            }\n            if (safeD) {\n                o.dirIds.push_back(colD[j]);\n                o.dists.push_back(dD);\n            }\n            if (safeL) {\n                o.dirIds.push_back(rowL[i]);\n                o.dists.push_back(dL);\n            }\n            if (safeR) {\n                o.dirIds.push_back(rowR[i]);\n                o.dists.push_back(dR);\n            }\n            ons.push_back(std::move(o));\n        }\n    }\n    int M = (int)ons.size();               // = 2*N = 40\n\n    // ---------- initial assignment (cheapest safe direction) ----------\n    for (int id = 0; id < M; ++id) {\n        int bestIdx = -1, bestDist = INT_MAX;\n        for (int k = 0; k < (int)ons[id].dirIds.size(); ++k) {\n            if (ons[id].dists[k] < bestDist) {\n                bestDist = ons[id].dists[k];\n                bestIdx = k;\n            }\n        }\n        int dir = ons[id].dirIds[bestIdx];\n        int dist = ons[id].dists[bestIdx];\n        ons[id].curDir = dir;\n        ons[id].curDist = dist;\n        dirs[dir].dists.insert(dist);\n        dirs[dir].maxDist = max(dirs[dir].maxDist, dist);\n    }\n\n    // total cost = sum 2*maxDist\n    int totalCost = 0;\n    for (auto &d : dirs) if (!d.dists.empty()) totalCost += 2 * d.maxDist;\n\n    // ---------- local improvement ----------\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        int bestDelta = 0;          // negative value = improvement\n        int bestOni = -1, bestFrom = -1, bestTo = -1;\n        int bestCurDist = -1, bestToDist = -1;\n\n        for (int oid = 0; oid < M; ++oid) {\n            int from = ons[oid].curDir;\n            int curDist = ons[oid].curDist;\n            const DirInfo &dFrom = dirs[from];\n            int oldMaxFrom = dFrom.maxDist;\n\n            for (int k = 0; k < (int)ons[oid].dirIds.size(); ++k) {\n                int to = ons[oid].dirIds[k];\n                if (to == from) continue;\n                int toDist = ons[oid].dists[k];\n                const DirInfo &dTo = dirs[to];\n                int oldMaxTo = dTo.maxDist;\n\n                // new max for 'from' after removing curDist\n                int newMaxFrom;\n                if (curDist < oldMaxFrom) {\n                    newMaxFrom = oldMaxFrom;\n                } else { // curDist == oldMaxFrom\n                    int cnt = dFrom.dists.count(oldMaxFrom);\n                    if (cnt >= 2) {\n                        newMaxFrom = oldMaxFrom;\n                    } else {\n                        if (dFrom.dists.size() == 1) newMaxFrom = 0;\n                        else {\n                            auto it = dFrom.dists.rbegin();\n                            ++it; // second largest\n                            newMaxFrom = *it;\n                        }\n                    }\n                }\n\n                // new max for 'to' after inserting toDist\n                int newMaxTo = max(oldMaxTo, toDist);\n\n                int newCost = totalCost - 2 * oldMaxFrom - 2 * oldMaxTo\n                              + 2 * newMaxFrom + 2 * newMaxTo;\n                int delta = newCost - totalCost; // negative = improvement\n                if (delta < bestDelta) {\n                    bestDelta = delta;\n                    bestOni = oid;\n                    bestFrom = from;\n                    bestTo = to;\n                    bestCurDist = curDist;\n                    bestToDist = toDist;\n                }\n            }\n        }\n\n        if (bestDelta < 0) {\n            // apply the best move\n            // erase from old direction\n            auto &setFrom = dirs[bestFrom].dists;\n            auto it = setFrom.find(bestCurDist);\n            setFrom.erase(it);\n            dirs[bestFrom].maxDist = setFrom.empty() ? 0 : *setFrom.rbegin();\n\n            // insert into new direction\n            auto &setTo = dirs[bestTo].dists;\n            setTo.insert(bestToDist);\n            dirs[bestTo].maxDist = *setTo.rbegin();\n\n            // update Oni info\n            ons[bestOni].curDir = bestTo;\n            ons[bestOni].curDist = bestToDist;\n\n            totalCost += bestDelta;\n            improved = true;\n        }\n    }\n\n    // ---------- output ----------\n    vector<pair<char,int>> out;\n    for (int d = 0; d < dirCnt; ++d) {\n        int D = dirs[d].maxDist;\n        if (D == 0) continue;\n        char dir = dirs[d].dir;\n        int idx = dirs[d].idx;\n        for (int k = 0; k < D; ++k) out.emplace_back(dir, idx);\n        for (int k = 0; k < D; ++k) out.emplace_back(opposite(dir), idx);\n    }\n\n    for (auto [c, p] : out) {\n        cout << c << ' ' << p << '\\n';\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\n/* ------------------------------------------------------------\n   Global data\n   ------------------------------------------------------------ */\nint N;\nlong long L;\nvector<int> T;\n\n/* ------------------------------------------------------------\n   Fast simulation \u2013 returns error, aborts early if it already exceeds limit\n   ------------------------------------------------------------ */\nll simulate_error(const vector<int> &a, const vector<int> &b, ll limit = LLONG_MAX) {\n    static int cnt[200];               // N \u2264 100\n    for (int i = 0; i < N; ++i) cnt[i] = 0;\n\n    int cur = 0;\n    for (long long step = 0; step < L; ++step) {\n        int t = cnt[cur];\n        ++cnt[cur];\n        cur = (t & 1) ? a[cur] : b[cur];\n    }\n\n    ll err = 0;\n    for (int i = 0; i < N; ++i) {\n        err += llabs((ll)cnt[i] - (ll)T[i]);\n        if (err > limit) return err;   // early exit \u2013 we only need to know that it is not better\n    }\n    return err;\n}\n\n/* ------------------------------------------------------------\n   Build a candidate (a,b) from the target frequencies\n   ------------------------------------------------------------ */\nvoid build_candidate(vector<int> &a, vector<int> &b, mt19937_64 &rng) {\n    // ----- a : random permutation (the base cycle) -----\n    a.resize(N);\n    iota(a.begin(), a.end(), 0);\n    shuffle(a.begin(), a.end(), rng);\n\n    // ----- target indegree w[i] = T[i] * (2N / L) -----\n    const double factor = (2.0 * N) / (double)L;   // = 0.0004 for the given limits\n    vector<double> w(N);\n    for (int i = 0; i < N; ++i) w[i] = T[i] * factor;\n\n    // ----- extra indegree that must be supplied by b -----\n    vector<int> extra(N, 0);\n    vector<double> rem(N, -1e9);   // fractional part, -inf for nodes that need none\n    int sum_extra = 0;\n    for (int i = 0; i < N; ++i) {\n        double val = w[i] - 1.0;                // one indegree already from a\n        if (val <= 0.0) {\n            extra[i] = 0;\n        } else {\n            int base = (int)floor(val);\n            extra[i] = base;\n            rem[i] = val - base;                // fractional part\n            sum_extra += base;\n        }\n    }\n    int need = N - sum_extra;                   // still missing indegree slots\n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(),\n         [&](int i, int j){ return rem[i] > rem[j]; });\n    for (int k = 0; k < need; ++k) ++extra[idx[k]];\n\n    // ----- build the list of successors for b -----\n    vector<int> pool;\n    pool.reserve(N);\n    for (int i = 0; i < N; ++i)\n        for (int k = 0; k < extra[i]; ++k) pool.push_back(i);\n    // safety \u2013 should be exactly N\n    while ((int)pool.size() < N) pool.push_back(rng() % N);\n    while ((int)pool.size() > N) pool.pop_back();\n\n    shuffle(pool.begin(), pool.end(), rng);\n    b.resize(N);\n    for (int i = 0; i < N; ++i) b[i] = pool[i];\n}\n\n/* ------------------------------------------------------------\n   Main\n   ------------------------------------------------------------ */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N >> L)) return 0;\n    T.resize(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    // ----- initial candidate (the best among a few random ones) -----\n    vector<int> best_a, best_b;\n    ll best_err = LLONG_MAX;\n\n    for (int trial = 0; trial < 12; ++trial) {\n        vector<int> a, b;\n        build_candidate(a, b, rng);\n        ll err = simulate_error(a, b, best_err);\n        if (err < best_err) {\n            best_err = err;\n            best_a = a;\n            best_b = b;\n        }\n    }\n\n    // ----- hill climbing -------------------------------------------------\n    vector<int> cur_a = best_a, cur_b = best_b;\n    ll cur_err = best_err;\n\n    const double TIME_LIMIT = 1.85;          // seconds\n    auto start = chrono::steady_clock::now();\n\n    int iterations_without_improve = 0;\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        // choose a random move\n        int move_type = rng() % 100;          // 0\u201159 : swap b, 60\u201179 : swap a, 80\u201199 : flip a/b\n        bool accepted = false;\n        ll new_err = LLONG_MAX;\n\n        if (move_type < 60) {                // swap two b\u2011edges\n            int i = rng() % N;\n            int j = rng() % N;\n            if (i == j) continue;\n            swap(cur_b[i], cur_b[j]);\n            new_err = simulate_error(cur_a, cur_b, best_err);\n            if (new_err <= cur_err) {\n                accepted = true;\n                cur_err = new_err;\n                if (new_err < best_err) {\n                    best_err = new_err;\n                    best_a = cur_a;\n                    best_b = cur_b;\n                }\n            } else {\n                swap(cur_b[i], cur_b[j]);    // revert\n            }\n        } else if (move_type < 80) {         // swap two a\u2011edges (keeps permutation)\n            int i = rng() % N;\n            int j = rng() % N;\n            if (i == j) continue;\n            swap(cur_a[i], cur_a[j]);\n            new_err = simulate_error(cur_a, cur_b, best_err);\n            if (new_err <= cur_err) {\n                accepted = true;\n                cur_err = new_err;\n                if (new_err < best_err) {\n                    best_err = new_err;\n                    best_a = cur_a;\n                    best_b = cur_b;\n                }\n            } else {\n                swap(cur_a[i], cur_a[j]);    // revert\n            }\n        } else {                             // flip a[i] and b[i] for a single node\n            int i = rng() % N;\n            swap(cur_a[i], cur_b[i]);\n            new_err = simulate_error(cur_a, cur_b, best_err);\n            if (new_err <= cur_err) {\n                accepted = true;\n                cur_err = new_err;\n                if (new_err < best_err) {\n                    best_err = new_err;\n                    best_a = cur_a;\n                    best_b = cur_b;\n                }\n            } else {\n                swap(cur_a[i], cur_b[i]);    // revert\n            }\n        }\n\n        if (!accepted) {\n            ++iterations_without_improve;\n            // occasional random restart to escape a deep local optimum\n            if (iterations_without_improve >= 500) {\n                vector<int> a, b;\n                build_candidate(a, b, rng);\n                ll err = simulate_error(a, b, best_err);\n                if (err < cur_err) {\n                    cur_a = a; cur_b = b; cur_err = err;\n                }\n                iterations_without_improve = 0;\n            }\n        } else {\n            iterations_without_improve = 0;\n        }\n    }\n\n    // ----- output ---------------------------------------------------------\n    for (int i = 0; i < N; ++i) {\n        cout << best_a[i] << ' ' << best_b[i] << '\\n';\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a);\n        b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\n/*** Hilbert order (recursive) ***/\nuint64_t hilbertOrder(int x, int y, int pow = 21, int rot = 0) {\n    if (pow == 0) return 0;\n    int h = 1 << (pow - 1);\n    int seg = ((x < h) ? 0 : 1) * 2 + ((y < h) ? 0 : 1);\n    seg = (seg + rot) & 3;\n    static const int rotateDelta[4] = {3, 0, 0, 1};\n    int nx = x & (h - 1);\n    int ny = y & (h - 1);\n    int nrot = (rot + rotateDelta[seg]) & 3;\n    uint64_t subSquareSize = uint64_t(1) << (2 * pow - 2);\n    uint64_t ans = seg * subSquareSize;\n    uint64_t add = hilbertOrder(nx, ny, pow - 1, nrot);\n    ans += (seg == 1 || seg == 2) ? add : (subSquareSize - add - 1);\n    return ans;\n}\n\n/*** Edge used for Kruskal ***/\nstruct Edge {\n    int u, v;\n    long long d2;          // squared distance of the centres\n    bool operator<(Edge const& other) const { return d2 < other.d2; }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n    vector<int> G(M);\n    for (int &x : G) cin >> x;\n\n    /* read rectangle data, keep centre coordinates */\n    vector<long long> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cx[i] = (static_cast<long long>(lx) + rx) / 2;\n        cy[i] = (static_cast<long long>(ly) + ry) / 2;\n    }\n\n    /* Hilbert order for better spatial locality */\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    vector<uint64_t> hilbert(N);\n    for (int i = 0; i < N; ++i) {\n        hilbert[i] = hilbertOrder(static_cast<int>(cx[i]),\n                                  static_cast<int>(cy[i]));\n    }\n    sort(order.begin(), order.end(),\n         [&](int a, int b) {\n             if (hilbert[a] != hilbert[b]) return hilbert[a] < hilbert[b];\n             if (cx[a] != cx[b]) return cx[a] < cx[b];\n             return cy[a] < cy[b];\n         });\n\n    /* split into groups according to G */\n    vector<vector<int>> groups;\n    groups.reserve(M);\n    int pos = 0;\n    for (int sz : G) {\n        vector<int> g;\n        g.reserve(sz);\n        for (int i = 0; i < sz; ++i) g.push_back(order[pos++]);\n        groups.emplace_back(move(g));\n    }\n\n    vector<vector<pair<int,int>>> groupEdges(M);   // edges for each group\n\n    /* process each group */\n    for (int gi = 0; gi < M; ++gi) {\n        const vector<int> &g = groups[gi];\n        int k = static_cast<int>(g.size());\n        if (k <= 1) continue;          // nothing to output\n\n        if (k <= L) {\n            /* query the judge for the exact MST */\n            cout << \"? \" << k;\n            for (int v : g) cout << ' ' << v;\n            cout << \"\\n\" << flush;\n\n            vector<pair<int,int>> edges;\n            edges.reserve(k - 1);\n            for (int i = 0; i < k - 1; ++i) {\n                int a, b;\n                cin >> a >> b;\n                edges.emplace_back(a, b);\n            }\n            groupEdges[gi] = move(edges);\n        } else {\n            /* build an approximate MST using centre distances */\n            vector<Edge> cand;\n            cand.reserve(k * (k - 1) / 2);\n            for (int i = 0; i < k; ++i) {\n                for (int j = i + 1; j < k; ++j) {\n                    long long dx = cx[g[i]] - cx[g[j]];\n                    long long dy = cy[g[i]] - cy[g[j]];\n                    long long d2 = dx * dx + dy * dy;\n                    cand.push_back({g[i], g[j], d2});\n                }\n            }\n            sort(cand.begin(), cand.end());\n\n            DSU dsu(N);                 // fresh DSU for this group\n            vector<pair<int,int>> edges;\n            edges.reserve(k - 1);\n            for (const auto &e : cand) {\n                if (dsu.unite(e.u, e.v)) {\n                    edges.emplace_back(e.u, e.v);\n                    if ((int)edges.size() == k - 1) break;\n                }\n            }\n            groupEdges[gi] = move(edges);\n        }\n    }\n\n    /* ----- final answer ----- */\n    cout << \"!\\n\";\n    for (int gi = 0; gi < M; ++gi) {\n        const auto &g = groups[gi];\n        for (size_t i = 0; i < g.size(); ++i) {\n            if (i) cout << ' ';\n            cout << g[i];\n        }\n        cout << \"\\n\";\n        for (auto [a, b] : groupEdges[gi]) {\n            cout << a << ' ' << b << \"\\n\";\n        }\n    }\n    cout.flush();\n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct PrevInfo {\n    int prev;      // previous cell id, -1 for start\n    char act;      // 'M' or 'S'\n    char dir;      // 'U','D','L','R'\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    if (!(cin >> N >> M)) return 0;          // read board size and number of points\n\n    vector<pair<int,int>> pos(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> pos[i].first >> pos[i].second;\n    }\n\n    // direction data\n    const char dch[4] = {'U','D','L','R'};\n    const int dr[4] = {-1, 1, 0, 0};\n    const int dc[4] = {0, 0, -1, 1};\n\n    int cur_r = pos[0].first;\n    int cur_c = pos[0].second;\n\n    const int V = N * N;                     // number of cells\n\n    // helper to convert (r,c) to a single id\n    auto id = [&](int r, int c) { return r * N + c; };\n\n    for (int idx = 1; idx < M; ++idx) {\n        int tr = pos[idx].first;\n        int tc = pos[idx].second;\n\n        // ---------- BFS from current position ----------\n        vector<int> dist(V, -1);\n        vector<PrevInfo> prev(V, {-1, 0, 0});\n        queue<int> q;\n\n        int start = id(cur_r, cur_c);\n        dist[start] = 0;\n        q.push(start);\n\n        while (!q.empty()) {\n            int cur = q.front(); q.pop();\n            int r = cur / N;\n            int c = cur % N;\n            int dcur = dist[cur];\n\n            // 4 moves\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + dr[d];\n                int nc = c + dc[d];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                int nid = id(nr, nc);\n                if (dist[nid] == -1) {\n                    dist[nid] = dcur + 1;\n                    prev[nid] = {cur, 'M', dch[d]};\n                    q.push(nid);\n                }\n            }\n\n            // 4 slides \u2013 slide straight to the border in each direction\n            for (int d = 0; d < 4; ++d) {\n                int nr = r, nc = c;\n                if (d == 0) nr = 0;          // up\n                else if (d == 1) nr = N - 1; // down\n                else if (d == 2) nc = 0;     // left\n                else if (d == 3) nc = N - 1; // right\n                if (nr == r && nc == c) continue; // already at border\n                int nid = id(nr, nc);\n                if (dist[nid] == -1) {\n                    dist[nid] = dcur + 1;\n                    prev[nid] = {cur, 'S', dch[d]};\n                    q.push(nid);\n                }\n            }\n        }\n\n        // ---------- reconstruct shortest path ----------\n        int target_id = id(tr, tc);\n        vector<pair<char,char>> actions;   // (action, direction) in reverse order\n        int cur = target_id;\n        while (cur != start) {\n            const PrevInfo &p = prev[cur];\n            actions.emplace_back(p.act, p.dir);\n            cur = p.prev;\n        }\n        reverse(actions.begin(), actions.end());\n\n        // ---------- output ----------\n        for (auto [a, d] : actions) {\n            cout << a << ' ' << d << '\\n';\n        }\n\n        // update current position\n        cur_r = tr;\n        cur_c = tc;\n    }\n\n    return 0;\n}"},"8":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    long long r;\n    int idx;\n};\n\nint n;\nvector<Point> pt;\nvector<int> ans_a, ans_b, ans_c, ans_d;\n\n/* -------------------------------------------------------------\n   leaf rectangle \u2013 try to choose width/height that best matches\n   the desired area while still containing the point.\n   ------------------------------------------------------------- */\nvoid allocate_leaf(int x0, int x1, int y0, int y1, const Point& p) {\n    int width  = x1 - x0;\n    int height = y1 - y0;\n    long long want = p.r;\n\n    int best_w = width, best_h = height;\n    long long best_diff = LLONG_MAX;\n\n    // try all possible widths (1 \u2026 width)\n    for (int w = 1; w <= width; ++w) {\n        // two candidates for height: floor and ceil of want/w\n        long long h_floor = want / w;\n        long long h_ceil  = (want + w - 1) / w;\n\n        for (long long h_raw : {h_floor, h_ceil}) {\n            if (h_raw < 1) continue;\n            if (h_raw > height) continue;\n            int h = (int)h_raw;\n\n            // check that the rectangle can be placed so that (x,y) is inside\n            int a_low  = max(x0, p.x - w + 1);\n            int a_high = min(p.x, x1 - w);\n            if (a_low > a_high) continue;\n            int b_low  = max(y0, p.y - h + 1);\n            int b_high = min(p.y, y1 - h);\n            if (b_low > b_high) continue;\n\n            long long area = 1LL * w * h;\n            long long diff = llabs(area - want);\n            if (diff < best_diff) {\n                best_diff = diff;\n                best_w = w;\n                best_h = h;\n            }\n        }\n    }\n\n    // place the rectangle as far left / bottom as possible inside the leaf\n    int a_low  = max(x0, p.x - best_w + 1);\n    int a_high = min(p.x, x1 - best_w);\n    int a = a_low;                     // any value in [a_low, a_high] works\n    int b_low  = max(y0, p.y - best_h + 1);\n    int b_high = min(p.y, y1 - best_h);\n    int b = b_low;                     // any value in [b_low, b_high] works\n\n    ans_a[p.idx] = a;\n    ans_b[p.idx] = b;\n    ans_c[p.idx] = a + best_w;\n    ans_d[p.idx] = b + best_h;\n}\n\n/* -------------------------------------------------------------\n   recursive guillotine partition\n   ------------------------------------------------------------- */\nvoid solve_region(int x0, int x1, int y0, int y1,\n                  const vector<int>& ids) {\n    if (ids.empty()) return;\n    if (ids.size() == 1) {\n        allocate_leaf(x0, x1, y0, y1, pt[ids[0]]);\n        return;\n    }\n\n    int width  = x1 - x0;\n    int height = y1 - y0;\n    bool vertical = (width >= height);\n\n    if (vertical) {\n        // ----- vertical cut -------------------------------------------------\n        vector<int> sorted = ids;\n        sort(sorted.begin(), sorted.end(),\n             [&](int a, int b){ return pt[a].x < pt[b].x; });\n\n        // prefix sums of r\n        vector<long long> pref(sorted.size());\n        for (size_t i = 0; i < sorted.size(); ++i) {\n            pref[i] = pt[sorted[i]].r + (i ? pref[i-1] : 0);\n        }\n\n        long long bestDiff = LLONG_MAX;\n        int bestX = -1;                     // cut column (absolute coordinate)\n\n        for (size_t k = 0; k + 1 < sorted.size(); ++k) {\n            long long sumLeft = pref[k];\n            int leftMaxX  = pt[sorted[k]].x;\n            int rightMinX = pt[sorted[k+1]].x;\n\n            // ideal width to host sumLeft area\n            long long needW = (sumLeft + height - 1) / height; // ceil\n            int X = x0 + (int)needW;\n\n            // enforce that the cut lies between the two point columns\n            if (X <= leftMaxX) X = leftMaxX + 1;\n            if (X >  rightMinX) X = rightMinX;\n            if (X <= x0) X = x0 + 1;\n            if (X >= x1) X = x1 - 1;\n\n            long long areaLeft = 1LL * (X - x0) * height;\n            long long diff = llabs(areaLeft - sumLeft);\n            if (diff < bestDiff) {\n                bestDiff = diff;\n                bestX = X;\n            }\n        }\n\n        // fallback: split in the middle if no suitable cut was found\n        if (bestX == -1) {\n            bestX = x0 + width / 2;\n            if (bestX == x0) bestX = x0 + 1;\n            if (bestX == x1) bestX = x1 - 1;\n        }\n\n        // partition ids\n        vector<int> leftIds, rightIds;\n        for (int id : ids) {\n            if (pt[id].x < bestX) leftIds.push_back(id);\n            else                 rightIds.push_back(id);\n        }\n\n        // if a side became empty (possible when many points share the same x)\n        if (leftIds.empty() || rightIds.empty()) {\n            bestX = (x0 + x1) / 2;\n            if (bestX == x0) bestX = x0 + 1;\n            if (bestX == x1) bestX = x1 - 1;\n            leftIds.clear(); rightIds.clear();\n            for (int id : ids) {\n                if (pt[id].x < bestX) leftIds.push_back(id);\n                else                 rightIds.push_back(id);\n            }\n        }\n\n        solve_region(x0, bestX, y0, y1, leftIds);\n        solve_region(bestX, x1, y0, y1, rightIds);\n    } else {\n        // ----- horizontal cut ------------------------------------------------\n        vector<int> sorted = ids;\n        sort(sorted.begin(), sorted.end(),\n             [&](int a, int b){ return pt[a].y < pt[b].y; });\n\n        vector<long long> pref(sorted.size());\n        for (size_t i = 0; i < sorted.size(); ++i) {\n            pref[i] = pt[sorted[i]].r + (i ? pref[i-1] : 0);\n        }\n\n        long long bestDiff = LLONG_MAX;\n        int bestY = -1;                     // cut row (absolute coordinate)\n\n        for (size_t k = 0; k + 1 < sorted.size(); ++k) {\n            long long sumTop = pref[k];\n            int topMaxY    = pt[sorted[k]].y;\n            int bottomMinY = pt[sorted[k+1]].y;\n\n            long long needH = (sumTop + width - 1) / width; // ceil\n            int Y = y0 + (int)needH;\n\n            if (Y <= topMaxY)   Y = topMaxY + 1;\n            if (Y >  bottomMinY) Y = bottomMinY;\n            if (Y <= y0) Y = y0 + 1;\n            if (Y >= y1) Y = y1 - 1;\n\n            long long areaTop = 1LL * (Y - y0) * width;\n            long long diff = llabs(areaTop - sumTop);\n            if (diff < bestDiff) {\n                bestDiff = diff;\n                bestY = Y;\n            }\n        }\n\n        if (bestY == -1) {\n            bestY = y0 + height / 2;\n            if (bestY == y0) bestY = y0 + 1;\n            if (bestY == y1) bestY = y1 - 1;\n        }\n\n        vector<int> topIds, botIds;\n        for (int id : ids) {\n            if (pt[id].y < bestY) topIds.push_back(id);\n            else                  botIds.push_back(id);\n        }\n\n        if (topIds.empty() || botIds.empty()) {\n            bestY = (y0 + y1) / 2;\n            if (bestY == y0) bestY = y0 + 1;\n            if (bestY == y1) bestY = y1 - 1;\n            topIds.clear(); botIds.clear();\n            for (int id : ids) {\n                if (pt[id].y < bestY) topIds.push_back(id);\n                else                  botIds.push_back(id);\n            }\n        }\n\n        solve_region(x0, x1, y0, bestY, topIds);\n        solve_region(x0, x1, bestY, y1, botIds);\n    }\n}\n\n/* ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> n)) return 0;\n    pt.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> pt[i].x >> pt[i].y >> pt[i].r;\n        pt[i].idx = i;\n    }\n\n    ans_a.assign(n, 0);\n    ans_b.assign(n, 0);\n    ans_c.assign(n, 0);\n    ans_d.assign(n, 0);\n\n    vector<int> all_ids(n);\n    iota(all_ids.begin(), all_ids.end(), 0);\n    solve_region(0, 10000, 0, 10000, all_ids);\n\n    for (int i = 0; i < n; ++i) {\n        cout << ans_a[i] << ' ' << ans_b[i] << ' '\n             << ans_c[i] << ' ' << ans_d[i] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 50;\nconstexpr int DIRS = 4;\nconstexpr char DIR_CHAR[DIRS] = {'U', 'D', 'L', 'R'};\nconstexpr int DX[DIRS] = {-1, 1, 0, 0};\nconstexpr int DY[DIRS] = {0, 0, -1, 1};\n\nusing Clock = chrono::steady_clock;\nusing ms    = chrono::milliseconds;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    if (!(cin >> si >> sj)) return 0;\n\n    vector<vector<int>> tile(N, vector<int>(N));\n    int maxTile = -1;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> tile[i][j];\n            maxTile = max(maxTile, tile[i][j]);\n        }\n    }\n    const int M = maxTile + 1;                 // number of tiles\n\n    vector<vector<int>> val(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> val[i][j];\n\n    // random generator\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n\n    // visited array \u2013 we use a run id to avoid clearing\n    vector<int> visited(M, 0);\n    int curRunId = 1;                         // will be increased each run\n\n    string bestPath;\n    long long bestScore = -1;\n\n    const int TIME_LIMIT_MS = 1900;           // leave a margin\n    auto startTime = Clock::now();\n\n    // helper: degree of a cell (number of still unvisited neighbour tiles)\n    auto degree = [&](int x, int y, const vector<int>& vis) -> int {\n        int deg = 0;\n        int curTile = tile[x][y];\n        for (int d = 0; d < DIRS; ++d) {\n            int nx = x + DX[d];\n            int ny = y + DY[d];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            int t = tile[nx][ny];\n            if (t == curTile) continue;               // same tile (already visited)\n            if (vis[t] != curRunId) ++deg;\n        }\n        return deg;\n    };\n\n    // helper: short random playout (depth = DEPTH) from (x,y) with a copy of visited\n    auto simulate = [&](int x, int y, const vector<int>& vis, int DEPTH) -> int {\n        vector<int> copyVis = vis;                     // copy of visited flags\n        int sum = 0;\n        int cx = x, cy = y;\n        for (int step = 0; step < DEPTH; ++step) {\n            vector<int> cand;\n            for (int d = 0; d < DIRS; ++d) {\n                int nx = cx + DX[d];\n                int ny = cy + DY[d];\n                if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                int t = tile[nx][ny];\n                if (copyVis[t] == curRunId) continue;\n                cand.push_back(d);\n            }\n            if (cand.empty()) break;\n            int d = cand[rng() % cand.size()];\n            cx += DX[d];\n            cy += DY[d];\n            int t = tile[cx][cy];\n            copyVis[t] = curRunId;\n            sum += val[cx][cy];\n        }\n        return sum;\n    };\n\n    // main loop \u2013 run many random walks until time runs out\n    while (true) {\n        auto now = Clock::now();\n        if (chrono::duration_cast<ms>(now - startTime).count() > TIME_LIMIT_MS) break;\n\n        // pick a heuristic mode (0\u20264)\n        int mode = uniform_int_distribution<int>(0, 4)(rng);\n        // for mode 3 (weighted) we also pick random weights\n        double w_val = uniform_real_distribution<double>(0.0, 1.0)(rng);\n        double w_deg = uniform_real_distribution<double>(0.0, 1.0)(rng);\n\n        // initialise visited flags for this run\n        ++curRunId;                                 // new id\n        visited[tile[si][sj]] = curRunId;            // start tile already used\n\n        int ci = si, cj = sj;\n        long long curScore = val[ci][cj];\n        string curPath;\n\n        while (true) {\n            // collect admissible neighbours\n            vector<int> candDir;\n            vector<double> candScore;\n            for (int d = 0; d < DIRS; ++d) {\n                int nx = ci + DX[d];\n                int ny = cj + DY[d];\n                if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                int t = tile[nx][ny];\n                if (visited[t] == curRunId) continue;   // already used tile\n\n                double sc = 0.0;\n                if (mode == 0) {                         // max immediate value\n                    sc = val[nx][ny];\n                } else if (mode == 1) {                  // max degree\n                    sc = degree(nx, ny, visited);\n                } else if (mode == 2) {                  // min degree (Warnsdorff)\n                    sc = -degree(nx, ny, visited);\n                } else if (mode == 3) {                  // weighted combination\n                    int deg = degree(nx, ny, visited);\n                    sc = w_val * val[nx][ny] + w_deg * deg;\n                } else {                                 // mode == 4, look\u2011ahead\n                    const int DEPTH = 6;\n                    // mark the neighbour tile as visited for the simulation\n                    vector<int> tempVis = visited;\n                    tempVis[t] = curRunId;\n                    int sim = simulate(nx, ny, tempVis, DEPTH);\n                    sc = val[nx][ny] + sim;\n                }\n\n                candDir.push_back(d);\n                candScore.push_back(sc);\n            }\n\n            if (candDir.empty()) break;                 // dead end\n\n            // choose the best (ties random)\n            double best = candScore[0];\n            vector<int> bestIdx = {0};\n            for (size_t i = 1; i < candScore.size(); ++i) {\n                if (candScore[i] > best) {\n                    best = candScore[i];\n                    bestIdx.clear();\n                    bestIdx.push_back(i);\n                } else if (candScore[i] == best) {\n                    bestIdx.push_back(i);\n                }\n            }\n            int chosen = bestIdx[rng() % bestIdx.size()];\n            int d = candDir[chosen];\n\n            // perform the move\n            ci += DX[d];\n            cj += DY[d];\n            curPath.push_back(DIR_CHAR[d]);\n            visited[tile[ci][cj]] = curRunId;\n            curScore += val[ci][cj];\n        }\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestPath = curPath;\n        }\n    }\n\n    cout << bestPath << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;                     // grid dimension\nconstexpr int V = N * N;                 // number of vertices\nconstexpr double INF = 1e100;\nconstexpr double MIN_W = 500.0;\nconstexpr double MAX_W = 10000.0;\n\n/* edge indexing helpers */\ninline int horiz_id(int i, int j) { return i * (N - 1) + j; }   // 0 \u2264 i < N, 0 \u2264 j < N\u20111\ninline int vert_id (int i, int j) { return i * N + j; }       // 0 \u2264 i < N\u20111, 0 \u2264 j < N\ninline int node_id (int i, int j) { return i * N + j; }\ninline pair<int,int> id_to_coord(int id) { return {id / N, id % N}; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int Hcnt = N * (N - 1);          // horizontal edges\n    const int Vcnt = (N - 1) * N;          // vertical edges\n\n    /* ----- model parameters ----- */\n    vector<double> base_h(N, 5000.0);      // row bases\n    vector<double> base_v(N, 5000.0);      // column bases\n    vector<double> res_h(Hcnt, 0.0);       // horizontal residuals\n    vector<double> res_v(Vcnt, 0.0);       // vertical   residuals\n\n    vector<int> cntBaseRow(N, 0);         // how many horizontal steps have been used per row\n    vector<int> cntBaseCol(N, 0);         // how many vertical   steps have been used per column\n    vector<int> cntResH(Hcnt, 0);          // per\u2011edge residual update count\n    vector<int> cntResV(Vcnt, 0);\n\n    const double base_lr = 0.5;           // learning rate for bases\n    const double edge_lr = 0.05;          // learning rate for residuals\n\n    for (int q = 0; q < 1000; ++q) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) return 0;   // safety\n        int s = node_id(si, sj);\n        int t = node_id(ti, tj);\n\n        /* ---------- Dijkstra on current weights ---------- */\n        vector<double> dist(V, INF);\n        vector<int>    parent(V, -1);\n        vector<char>   move_dir(V, 0);\n        dist[s] = 0.0;\n        using PQItem = pair<double,int>;\n        priority_queue<PQItem, vector<PQItem>, greater<PQItem>> pq;\n        pq.emplace(0.0, s);\n\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u]) continue;\n            if (u == t) break;\n            auto [i, j] = id_to_coord(u);\n\n            // up\n            if (i > 0) {\n                int nb = node_id(i-1, j);\n                double w = base_v[j] + res_v[vert_id(i-1, j)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move_dir[nb] = 'U';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // down\n            if (i + 1 < N) {\n                int nb = node_id(i+1, j);\n                double w = base_v[j] + res_v[vert_id(i, j)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move_dir[nb] = 'D';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // left\n            if (j > 0) {\n                int nb = node_id(i, j-1);\n                double w = base_h[i] + res_h[horiz_id(i, j-1)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move_dir[nb] = 'L';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // right\n            if (j + 1 < N) {\n                int nb = node_id(i, j+1);\n                double w = base_h[i] + res_h[horiz_id(i, j)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move_dir[nb] = 'R';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n        }\n\n        /* ---------- reconstruct path (reverse order) ---------- */\n        vector<char> rev_path;\n        vector<pair<bool,int>> rev_edges; // (isHorizontal, edgeId)\n        int cur = t;\n        while (cur != s) {\n            int p = parent[cur];\n            char d = move_dir[cur];\n            rev_path.push_back(d);\n            auto [ci, cj] = id_to_coord(cur);\n            auto [pi, pj] = id_to_coord(p);\n            if (ci == pi + 1 && cj == pj) {               // moved down\n                rev_edges.emplace_back(false, vert_id(pi, pj));\n            } else if (ci == pi - 1 && cj == pj) {        // moved up\n                rev_edges.emplace_back(false, vert_id(ci, cj));\n            } else if (cj == pj + 1 && ci == pi) {        // moved right\n                rev_edges.emplace_back(true, horiz_id(pi, pj));\n            } else if (cj == pj - 1 && ci == pi) {        // moved left\n                rev_edges.emplace_back(true, horiz_id(ci, cj));\n            }\n            cur = p;\n        }\n        reverse(rev_path.begin(), rev_path.end());\n        reverse(rev_edges.begin(), rev_edges.end());\n\n        string out_path;\n        out_path.reserve(rev_path.size());\n        for (char c : rev_path) out_path.push_back(c);\n\n        /* ---------- output and flush ---------- */\n        cout << out_path << '\\n' << flush;\n\n        long long L;\n        if (!(cin >> L)) return 0;   // safety\n\n        /* ---------- collect statistics ---------- */\n        int steps = static_cast<int>(rev_path.size());\n        if (steps == 0) continue;   // should never happen (Manhattan distance \u226510)\n\n        array<int, N> cntRow{}; cntRow.fill(0);\n        array<int, N> cntCol{}; cntCol.fill(0);\n        vector<int> horizEdges;\n        vector<int> vertEdges;\n\n        for (auto &e : rev_edges) {\n            if (e.first) { // horizontal\n                int id = e.second;\n                horizEdges.push_back(id);\n                int row = id / (N - 1);\n                ++cntRow[row];\n            } else {       // vertical\n                int id = e.second;\n                vertEdges.push_back(id);\n                int col = id % N;\n                ++cntCol[col];\n            }\n        }\n\n        /* ---------- current estimate of the path length ---------- */\n        double est = 0.0;\n        for (int id : horizEdges) {\n            int row = id / (N - 1);\n            est += base_h[row] + res_h[id];\n        }\n        for (int id : vertEdges) {\n            int col = id % N;\n            est += base_v[col] + res_v[id];\n        }\n        double err = est - static_cast<double>(L);\n        double grad = err / steps;   // same for every edge of the path\n\n        /* ---------- update bases (row / column) ---------- */\n        for (int i = 0; i < N; ++i) if (cntRow[i] > 0) {\n            double lr = base_lr / sqrt(static_cast<double>(cntBaseRow[i] + 1));\n            base_h[i] -= lr * err * cntRow[i] / steps;\n            if (base_h[i] < MIN_W) base_h[i] = MIN_W;\n            if (base_h[i] > MAX_W) base_h[i] = MAX_W;\n            cntBaseRow[i] += cntRow[i];\n        }\n        for (int j = 0; j < N; ++j) if (cntCol[j] > 0) {\n            double lr = base_lr / sqrt(static_cast<double>(cntBaseCol[j] + 1));\n            base_v[j] -= lr * err * cntCol[j] / steps;\n            if (base_v[j] < MIN_W) base_v[j] = MIN_W;\n            if (base_v[j] > MAX_W) base_v[j] = MAX_W;\n            cntBaseCol[j] += cntCol[j];\n        }\n\n        /* ---------- update residuals (per\u2011edge) ---------- */\n        for (int id : horizEdges) {\n            int row = id / (N - 1);\n            double lr = edge_lr / sqrt(static_cast<double>(cntResH[id] + 1));\n            res_h[id] -= lr * grad;\n            ++cntResH[id];\n            double w = base_h[row] + res_h[id];\n            if (w < MIN_W) res_h[id] = MIN_W - base_h[row];\n            if (w > MAX_W) res_h[id] = MAX_W - base_h[row];\n        }\n        for (int id : vertEdges) {\n            int col = id % N;\n            double lr = edge_lr / sqrt(static_cast<double>(cntResV[id] + 1));\n            res_v[id] -= lr * grad;\n            ++cntResV[id];\n            double w = base_v[col] + res_v[id];\n            if (w < MIN_W) res_v[id] = MIN_W - base_v[col];\n            if (w > MAX_W) res_v[id] = MAX_W - base_v[col];\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int MAX_N = 20;\nconstexpr int MAX_LEN = 12;\nconstexpr uint8_t EMPTY = 8;          // value for '.' (unused after fill)\n\n/* ---------- data structures ---------- */\n\nstruct Placement {\n    uint8_t len;                      // length of the string (\u226412)\n    uint16_t cells[MAX_LEN];          // linear cell indices (0 \u2026 399)\n    uint8_t  need[MAX_LEN];           // required character (0 \u2026 7)\n    int stringId;                     // which string it belongs to\n};\n\nstruct CellPlacementInfo {\n    int pid;          // global placement id\n    uint8_t need;     // needed character for this cell\n};\n\n/* ---------- main ---------- */\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<string> S(M);\n    for (int i = 0; i < M; ++i) cin >> S[i];\n\n    /* ----- generate all placements ----- */\n    vector<Placement> allPl;               // flat list of all placements\n    allPl.reserve(M * 800);\n    vector<vector<int>> plOfString(M);     // placement ids per string\n    vector<vector<CellPlacementInfo>> cellInfo(N * N);\n    for (int sid = 0; sid < M; ++sid) {\n        const string &st = S[sid];\n        int L = (int)st.size();\n        // horizontal\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                Placement p;\n                p.len = (uint8_t)L;\n                p.stringId = sid;\n                for (int k = 0; k < L; ++k) {\n                    int col = (c + k) % N;\n                    p.cells[k] = (uint16_t)(r * N + col);\n                    p.need[k] = (uint8_t)(st[k] - 'A');\n                }\n                int pid = (int)allPl.size();\n                allPl.push_back(p);\n                plOfString[sid].push_back(pid);\n                for (int k = 0; k < L; ++k) {\n                    cellInfo[p.cells[k]].push_back({pid, p.need[k]});\n                }\n            }\n        }\n        // vertical\n        for (int c = 0; c < N; ++c) {\n            for (int r = 0; r < N; ++r) {\n                Placement p;\n                p.len = (uint8_t)L;\n                p.stringId = sid;\n                for (int k = 0; k < L; ++k) {\n                    int row = (r + k) % N;\n                    p.cells[k] = (uint16_t)(row * N + c);\n                    p.need[k] = (uint8_t)(st[k] - 'A');\n                }\n                int pid = (int)allPl.size();\n                allPl.push_back(p);\n                plOfString[sid].push_back(pid);\n                for (int k = 0; k < L; ++k) {\n                    cellInfo[p.cells[k]].push_back({pid, p.need[k]});\n                }\n            }\n        }\n    }\n    const int PL_TOTAL = (int)allPl.size();\n\n    /* ----- random utilities ----- */\n    std::mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> distChar(0, 7);\n    std::uniform_int_distribution<int> distString(0, M - 1);\n\n    const double TIME_LIMIT = 2.9;          // seconds per test case\n    auto startTime = chrono::steady_clock::now();\n\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    vector<int> length(M);\n    for (int i = 0; i < M; ++i) length[i] = (int)S[i].size();\n\n    int bestScore = -1;\n    vector<uint8_t> bestMat(N * N, EMPTY);\n\n    const int MIN_ITER = 30;                // guarantee enough greedy runs\n    int iter = 0;\n\n    /* ----- greedy phase (multiple random orders) ----- */\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT - 0.5 && iter >= MIN_ITER) break; // reserve time for local search\n\n        // choose order\n        if (iter % 2 == 0) {\n            shuffle(order.begin(), order.end(), rng);\n        } else {\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     if (length[a] != length[b]) return length[a] > length[b];\n                     return a < b;\n                 });\n        }\n\n        // greedy placement\n        vector<uint8_t> mat(N * N, EMPTY);\n        for (int sid : order) {\n            const auto &plist = plOfString[sid];\n            int bestPid = -1;\n            int bestOverlap = -1;\n            for (int pid : plist) {\n                const Placement &p = allPl[pid];\n                bool conflict = false;\n                int overlap = 0;\n                for (int k = 0; k < p.len; ++k) {\n                    uint8_t cur = mat[p.cells[k]];\n                    uint8_t need = p.need[k];\n                    if (cur != EMPTY && cur != need) {\n                        conflict = true;\n                        break;\n                    }\n                    if (cur == need) ++overlap;\n                }\n                if (conflict) continue;\n                if (overlap > bestOverlap) {\n                    bestOverlap = overlap;\n                    bestPid = pid;\n                    if (overlap == p.len) break; // perfect match\n                }\n            }\n            if (bestPid != -1) {\n                const Placement &p = allPl[bestPid];\n                for (int k = 0; k < p.len; ++k) {\n                    uint16_t cell = p.cells[k];\n                    if (mat[cell] == EMPTY) mat[cell] = p.need[k];\n                }\n            }\n        }\n\n        // majority\u2011vote fill for remaining empty cells\n        static int freq[400][8];\n        for (int i = 0; i < N * N; ++i)\n            for (int c = 0; c < 8; ++c) freq[i][c] = 0;\n\n        // count compatible placements (still possible)\n        for (int sid = 0; sid < M; ++sid) {\n            const auto &plist = plOfString[sid];\n            for (int pid : plist) {\n                const Placement &p = allPl[pid];\n                bool compatible = true;\n                for (int k = 0; k < p.len; ++k) {\n                    uint8_t cur = mat[p.cells[k]];\n                    if (cur != EMPTY && cur != p.need[k]) {\n                        compatible = false;\n                        break;\n                    }\n                }\n                if (!compatible) continue;\n                for (int k = 0; k < p.len; ++k) {\n                    uint16_t cell = p.cells[k];\n                    if (mat[cell] == EMPTY) ++freq[cell][p.need[k]];\n                }\n            }\n        }\n        for (int i = 0; i < N * N; ++i) {\n            if (mat[i] != EMPTY) continue;\n            int bestChar = 0, bestCnt = -1;\n            for (int c = 0; c < 8; ++c) {\n                if (freq[i][c] > bestCnt) {\n                    bestCnt = freq[i][c];\n                    bestChar = c;\n                }\n            }\n            if (bestCnt <= 0) bestChar = distChar(rng);\n            mat[i] = (uint8_t)bestChar;\n        }\n\n        // count satisfied strings\n        int satisfied = 0;\n        for (int sid = 0; sid < M; ++sid) {\n            const auto &plist = plOfString[sid];\n            bool ok = false;\n            for (int pid : plist) {\n                const Placement &p = allPl[pid];\n                bool good = true;\n                for (int k = 0; k < p.len; ++k) {\n                    if (mat[p.cells[k]] != p.need[k]) {\n                        good = false;\n                        break;\n                    }\n                }\n                if (good) { ok = true; break; }\n            }\n            if (ok) ++satisfied;\n        }\n        if (satisfied > bestScore) {\n            bestScore = satisfied;\n            bestMat = mat;\n        }\n        ++iter;\n    }\n\n    /* ----- prepare data for local search on the best matrix ----- */\n    // mismatch per placement\n    vector<uint8_t> mismatch(PL_TOTAL, 0);\n    vector<int> satCnt(M, 0);\n    for (int pid = 0; pid < PL_TOTAL; ++pid) {\n        const Placement &p = allPl[pid];\n        uint8_t cnt = 0;\n        for (int k = 0; k < p.len; ++k) {\n            if (bestMat[p.cells[k]] != p.need[k]) ++cnt;\n        }\n        mismatch[pid] = cnt;\n        if (cnt == 0) ++satCnt[p.stringId];\n    }\n    int totalSat = 0;\n    for (int i = 0; i < M; ++i) if (satCnt[i] > 0) ++totalSat;\n\n    /* ----- local search (hill climbing) ----- */\n    vector<uint8_t> curMat = bestMat;\n    vector<uint8_t> curMismatch = mismatch;\n    vector<int> curSatCnt = satCnt;\n    int curTotalSat = totalSat;\n\n    const int MAX_LOCAL_ITER = 800;          // safe upper bound\n    int localIter = 0;\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n        if (localIter >= MAX_LOCAL_ITER) break;\n\n        int cell = rng() % (N * N);\n        uint8_t oldChar = curMat[cell];\n        int delta[8] = {0};\n\n        for (const auto &ci : cellInfo[cell]) {\n            int pid = ci.pid;\n            uint8_t need = ci.need;\n            int sid = allPl[pid].stringId;\n            uint8_t mc = curMismatch[pid];\n            bool beforeMatch = (oldChar == need);\n            for (int c = 0; c < 8; ++c) {\n                bool afterMatch = (c == need);\n                if (beforeMatch == afterMatch) continue;\n                if (beforeMatch && !afterMatch) { // breaking a match\n                    if (mc == 0 && curSatCnt[sid] == 1) delta[c] -= 1;\n                } else { // fixing a mismatch\n                    if (mc == 1 && curSatCnt[sid] == 0) delta[c] += 1;\n                }\n            }\n        }\n\n        // choose best character\n        int bestChar = oldChar;\n        int bestDelta = 0;\n        for (int c = 0; c < 8; ++c) {\n            if (delta[c] > bestDelta) {\n                bestDelta = delta[c];\n                bestChar = c;\n            }\n        }\n\n        if (bestDelta > 0) {\n            // apply the change\n            curMat[cell] = (uint8_t)bestChar;\n            for (const auto &ci : cellInfo[cell]) {\n                int pid = ci.pid;\n                uint8_t need = ci.need;\n                int sid = allPl[pid].stringId;\n                uint8_t &mc = curMismatch[pid];\n                bool beforeMatch = (oldChar == need);\n                bool afterMatch = (bestChar == need);\n                if (beforeMatch == afterMatch) continue;\n                if (beforeMatch && !afterMatch) { // breaking a match\n                    if (mc == 0) {\n                        // placement becomes unsatisfied\n                        if (curSatCnt[sid] == 1) --curTotalSat;\n                        --curSatCnt[sid];\n                    }\n                    ++mc;\n                } else { // fixing a mismatch\n                    if (mc == 1) {\n                        // placement becomes satisfied\n                        if (curSatCnt[sid] == 0) ++curTotalSat;\n                        ++curSatCnt[sid];\n                    }\n                    --mc;\n                }\n            }\n            if (curTotalSat > bestScore) {\n                bestScore = curTotalSat;\n                bestMat = curMat;\n            }\n        }\n        ++localIter;\n    }\n\n    /* ----- output ----- */\n    for (int r = 0; r < N; ++r) {\n        string line;\n        line.reserve(N);\n        for (int c = 0; c < N; ++c) {\n            uint8_t v = bestMat[r * N + c];\n            line.push_back(char('A' + v));\n        }\n        cout << line << '\\n';\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll INF = (1LL << 60);\n\n/*** 1.  Input & basic structures ***/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, si, sj;\n    if (!(cin >> N >> si >> sj)) return 0;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n\n    // assign an id to every road cell\n    vector<vector<int>> id(N, vector<int>(N, -1));\n    vector<int> row, col, cost;          // by id\n    int r = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                id[i][j] = r++;\n                row.push_back(i);\n                col.push_back(j);\n                cost.push_back(grid[i][j] - '0');\n            }\n        }\n    }\n    int startId = id[si][sj];\n\n    // adjacency list (directed: moving to neighbour costs neighbour's cost)\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    vector<vector<pair<int,int>>> adj(r);\n    for (int v = 0; v < r; ++v) {\n        int i = row[v], j = col[v];\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d], nj = j + dy[d];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (grid[ni][nj] == '#') continue;\n            int to = id[ni][nj];\n            adj[v].push_back({to, cost[to]});\n        }\n    }\n\n    /*** 2.  Build representatives \u2013 one per maximal segment ***/\n    vector<char> isRep(r, 0);\n    vector<int> reps;               // ids of representatives\n\n    // horizontal segments\n    for (int i = 0; i < N; ++i) {\n        int j = 0;\n        while (j < N) {\n            if (grid[i][j] == '#') { ++j; continue; }\n            int start = j;\n            while (j < N && grid[i][j] != '#') ++j;\n            int repId = id[i][start];          // leftmost cell\n            if (!isRep[repId]) {\n                isRep[repId] = 1;\n                reps.push_back(repId);\n            }\n        }\n    }\n    // vertical segments\n    for (int j = 0; j < N; ++j) {\n        int i = 0;\n        while (i < N) {\n            if (grid[i][j] == '#') { ++i; continue; }\n            int start = i;\n            while (i < N && grid[i][j] != '#') ++i;\n            int repId = id[start][j];          // topmost cell\n            if (!isRep[repId]) {\n                isRep[repId] = 1;\n                reps.push_back(repId);\n            }\n        }\n    }\n    // ensure start cell is a representative\n    if (!isRep[startId]) {\n        isRep[startId] = 1;\n        reps.push_back(startId);\n    }\n\n    int m = (int)reps.size();               // number of representatives\n    unordered_map<int,int> repIdxOfId;\n    repIdxOfId.reserve(m*2);\n    for (int i = 0; i < m; ++i) repIdxOfId[reps[i]] = i;\n\n    /*** 3.  All\u2011pairs shortest paths from each representative ***/\n    vector<vector<ll>> dist(m, vector<ll>(r, INF));\n    vector<vector<int>> parent(m, vector<int>(r, -1));\n\n    using P = pair<ll,int>;\n    for (int k = 0; k < m; ++k) {\n        int src = reps[k];\n        priority_queue<P, vector<P>, greater<P>> pq;\n        dist[k][src] = 0;\n        pq.emplace(0LL, src);\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d != dist[k][u]) continue;\n            for (auto [v, w] : adj[u]) {\n                ll nd = d + w;\n                if (nd < dist[k][v]) {\n                    dist[k][v] = nd;\n                    parent[k][v] = u;\n                    pq.emplace(nd, v);\n                }\n            }\n        }\n    }\n\n    // distance matrix between representatives (directed)\n    vector<vector<ll>> repDist(m, vector<ll>(m, INF));\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < m; ++j) {\n            repDist[i][j] = dist[i][reps[j]];\n        }\n    }\n\n    /*** 4.  Helper: tour length ***/\n    auto tourLength = [&](const vector<int>& t)->ll{\n        ll sum = 0;\n        int sz = (int)t.size();\n        for (int i = 0; i < sz; ++i) {\n            int a = t[i];\n            int b = t[(i+1)%sz];\n            sum += repDist[a][b];\n        }\n        return sum;\n    };\n\n    /*** 5.  2\u2011opt improvement ***/\n    auto twoOpt = [&](vector<int>& tour) {\n        bool improved = true;\n        int passes = 0;\n        const int MAX_PASSES = 5;\n        int sz = (int)tour.size();\n        while (improved && passes < MAX_PASSES) {\n            improved = false;\n            ++passes;\n            for (int i = 0; i < sz; ++i) {\n                for (int j = i + 2; j < sz; ++j) {\n                    if (i == 0 && j == sz - 1) continue; // adjacent in cycle\n                    int a = tour[i];\n                    int b = tour[(i+1)%sz];\n                    int c = tour[j];\n                    int d = tour[(j+1)%sz];\n                    ll curLen = repDist[a][b] + repDist[c][d];\n                    ll newLen = repDist[a][c] + repDist[b][d];\n                    if (newLen < curLen) {\n                        // reverse segment (i+1 .. j)\n                        if (i+1 <= j) reverse(tour.begin() + i + 1, tour.begin() + j + 1);\n                        improved = true;\n                    }\n                }\n            }\n        }\n    };\n\n    /*** 6.  Build initial tour (nearest\u2011neighbour) ***/\n    vector<char> visited(m, 0);\n    vector<int> bestTour;\n    bestTour.reserve(m);\n    int startIdx = repIdxOfId[startId];\n    // deterministic nearest\u2011neighbour\n    {\n        vector<char> vis(m, 0);\n        vector<int> tour;\n        tour.reserve(m);\n        int cur = startIdx;\n        tour.push_back(cur);\n        vis[cur] = 1;\n        for (int cnt = 1; cnt < m; ++cnt) {\n            ll best = INF;\n            int bestIdx = -1;\n            for (int i = 0; i < m; ++i) if (!vis[i]) {\n                if (repDist[cur][i] < best) {\n                    best = repDist[cur][i];\n                    bestIdx = i;\n                }\n            }\n            vis[bestIdx] = 1;\n            tour.push_back(bestIdx);\n            cur = bestIdx;\n        }\n        twoOpt(tour);\n        bestTour = tour;\n    }\n\n    /*** 7.  Randomised improvement within time budget ***/\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    vector<int> otherIdx;\n    otherIdx.reserve(m-1);\n    for (int i = 0; i < m; ++i) if (i != startIdx) otherIdx.push_back(i);\n\n    auto startClock = chrono::steady_clock::now();\n    const double TIME_LIMIT = 2.7; // seconds\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startClock).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        shuffle(otherIdx.begin(), otherIdx.end(), rng);\n        vector<int> tour;\n        tour.reserve(m);\n        tour.push_back(startIdx);\n        tour.insert(tour.end(), otherIdx.begin(), otherIdx.end());\n\n        twoOpt(tour);\n        ll len = tourLength(tour);\n        if (len < tourLength(bestTour)) {\n            bestTour = tour;\n        }\n    }\n\n    /*** 8.  Reconstruct the movement string ***/\n    string answer;\n\n    // helper: output shortest path from srcId to dstId using parent of srcRepIdx\n    auto appendPath = [&](int srcId, int dstId, int srcRepIdx) {\n        vector<int> path;\n        int cur = dstId;\n        while (cur != srcId) {\n            path.push_back(cur);\n            cur = parent[srcRepIdx][cur];\n        }\n        path.push_back(srcId);\n        reverse(path.begin(), path.end());\n        for (size_t k = 1; k < path.size(); ++k) {\n            int a = path[k-1];\n            int b = path[k];\n            int dr = row[b] - row[a];\n            int dc = col[b] - col[a];\n            char ch;\n            if (dr == -1) ch = 'U';\n            else if (dr == 1) ch = 'D';\n            else if (dc == -1) ch = 'L';\n            else /* dc == 1 */ ch = 'R';\n            answer.push_back(ch);\n        }\n    };\n\n    int curId = startId;\n    int curRepIdx = startIdx;\n    for (size_t i = 1; i < bestTour.size(); ++i) {\n        int nxtId = reps[bestTour[i]];\n        appendPath(curId, nxtId, curRepIdx);\n        curId = nxtId;\n        curRepIdx = bestTour[i];\n    }\n    // finally return to start\n    if (curId != startId) {\n        appendPath(curId, startId, curRepIdx);\n    }\n\n    cout << answer << '\\n';\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- data structures ---------- */\n\nstruct ReadyTask {\n    int id;          // task index (0\u2011based)\n    int dp;          // longest path length starting from the task\n    long long sum;   // \u03a3 d_i,k\n    // priority: larger dp first, then larger sum\n    bool operator<(const ReadyTask& other) const {\n        if (dp != other.dp) return dp < other.dp;\n        return sum < other.sum;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    if (!(cin >> N >> M >> K >> R)) return 0;\n\n    /* ----- read required skill vectors ----- */\n    vector<vector<int>> d(N, vector<int>(K));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < K; ++j)\n            cin >> d[i][j];\n\n    /* ----- compute sum of required skills for each task ----- */\n    vector<long long> sum_d(N, 0);\n    for (int i = 0; i < N; ++i) {\n        long long s = 0;\n        for (int j = 0; j < K; ++j) s += d[i][j];\n        sum_d[i] = s;\n    }\n\n    /* ----- read dependencies ----- */\n    vector<vector<int>> adj(N);\n    vector<int> indeg(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        adj[u].push_back(v);\n        ++indeg[v];\n    }\n\n    /* ----- longest path length (critical\u2011path priority) ----- */\n    vector<int> dp(N, 1);\n    for (int i = N - 1; i >= 0; --i) {\n        for (int v : adj[i]) {\n            dp[i] = max(dp[i], dp[v] + 1);\n        }\n    }\n\n    /* ----- initial ready queue ----- */\n    priority_queue<ReadyTask> readyPQ;\n    for (int i = 0; i < N; ++i) {\n        if (indeg[i] == 0) {\n            readyPQ.push({i, dp[i], sum_d[i]});\n        }\n    }\n\n    /* ----- state of members and tasks ----- */\n    vector<int> member_task(M, -1);          // task currently executed, -1 = idle\n    vector<int> task_start_day(N, -1);       // day when the task started\n    vector<char> task_started(N, 0);\n    vector<char> task_completed(N, 0);\n\n    /* ----- statistics for skill estimation ----- */\n    vector<long long> sum_d_done(M, 0);\n    vector<long long> sum_t_done(M, 0);\n    vector<int> cnt_done(M, 0);\n    vector<double> skill_est(M, 0.0);        // estimate of \u03a3 s_j\n\n    int day = 0;\n    while (true) {\n        ++day;\n\n        /* ----- collect idle members ----- */\n        vector<int> idle;\n        for (int j = 0; j < M; ++j)\n            if (member_task[j] == -1) idle.push_back(j);\n\n        /* ----- order idle members by estimated skill (strongest first) ----- */\n        sort(idle.begin(), idle.end(),\n             [&](int a, int b) { return skill_est[a] > skill_est[b]; });\n\n        /* ----- assign tasks ----- */\n        vector<pair<int,int>> assign;   // (member, task) in 1\u2011based form\n        for (int idx = 0; idx < (int)idle.size() && !readyPQ.empty(); ++idx) {\n            int member = idle[idx];\n            ReadyTask rt = readyPQ.top(); readyPQ.pop();\n            int task = rt.id;\n\n            assign.emplace_back(member + 1, task + 1);\n            member_task[member] = task;\n            task_started[task] = 1;\n            task_start_day[task] = day;\n        }\n\n        /* ----- output ----- */\n        cout << assign.size();\n        for (auto &p : assign) cout << ' ' << p.first << ' ' << p.second;\n        cout << \"\\n\" << flush;\n\n        /* ----- read judge response ----- */\n        int n;\n        if (!(cin >> n)) return 0;          // EOF (should not happen)\n        if (n == -1) break;                 // all tasks done or day limit\n        vector<int> finished;\n        finished.reserve(n);\n        for (int i = 0; i < n; ++i) {\n            int f; cin >> f;\n            finished.push_back(f);\n        }\n\n        /* ----- process completions ----- */\n        for (int f : finished) {\n            int member = f - 1;\n            int task = member_task[member];\n            if (task == -1) continue;       // safety, should not happen\n\n            // real duration of the task\n            int duration = day - task_start_day[task] + 1;\n\n            // update skill estimate of the member\n            ++cnt_done[member];\n            sum_d_done[member] += sum_d[task];\n            sum_t_done[member] += duration;\n            double raw = (double)sum_d_done[member] - (double)sum_t_done[member];\n            if (raw < 0) raw = 0;\n            skill_est[member] = raw / cnt_done[member];\n\n            // free the member\n            member_task[member] = -1;\n\n            // mark task as completed\n            task_started[task] = 0;\n            task_completed[task] = 1;\n\n            // make successors ready\n            for (int v : adj[task]) {\n                --indeg[v];\n                if (indeg[v] == 0) {\n                    readyPQ.push({v, dp[v], sum_d[v]});\n                }\n            }\n        }\n    }\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Order {\n    int a, b, c, d;   // pickup (a,b), delivery (c,d)\n    int idx;          // 1\u2011based index in the original list\n    long long cost;  // heuristic cost for selection\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 1000;\n    const int M = 50;\n    const int OFF_X = 400, OFF_Y = 400;\n\n    vector<Order> orders(N);\n    for (int i = 0; i < N; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        long long cost = 0;\n        cost += manhattan(OFF_X, OFF_Y, a, b); // office -> pickup\n        cost += manhattan(a, b, c, d);         // pickup -> delivery\n        cost += manhattan(c, d, OFF_X, OFF_Y); // delivery -> office\n        orders[i] = {a, b, c, d, i + 1, cost};\n    }\n\n    // -----------------------------------------------------------------\n    // 1) select 50 orders with smallest heuristic cost\n    sort(orders.begin(), orders.end(),\n         [](const Order& x, const Order& y) { return x.cost < y.cost; });\n    vector<Order> sel(orders.begin(), orders.begin() + M);\n\n    // -----------------------------------------------------------------\n    // 2) greedy feasible\u2011node walk\n    // status: 0 = not started, 1 = pickup done, 2 = delivered\n    vector<int> status(M, 0);\n    vector<int> chosenIdx;          // order indices in the order we first visit pickup\n    vector<pair<int,int>> route;    // visited points\n\n    int curX = OFF_X, curY = OFF_Y;\n    route.emplace_back(curX, curY);   // start at office\n\n    int remaining = M;   // number of orders not yet delivered\n    while (remaining > 0) {\n        int bestDist = INT_MAX;\n        int bestIdx = -1;\n        bool bestIsPickup = true;   // true -> pickup, false -> delivery\n\n        for (int i = 0; i < M; ++i) {\n            if (status[i] == 0) { // pickup not visited yet\n                int d = manhattan(curX, curY, sel[i].a, sel[i].b);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx = i;\n                    bestIsPickup = true;\n                }\n            } else if (status[i] == 1) { // pickup done, delivery pending\n                int d = manhattan(curX, curY, sel[i].c, sel[i].d);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx = i;\n                    bestIsPickup = false;\n                }\n            }\n        }\n\n        // we must have found a candidate\n        if (bestIsPickup) {\n            // go to pickup\n            curX = sel[bestIdx].a;\n            curY = sel[bestIdx].b;\n            route.emplace_back(curX, curY);\n            status[bestIdx] = 1;\n            chosenIdx.push_back(sel[bestIdx].idx);\n        } else {\n            // go to delivery\n            curX = sel[bestIdx].c;\n            curY = sel[bestIdx].d;\n            route.emplace_back(curX, curY);\n            status[bestIdx] = 2;\n            --remaining;\n        }\n    }\n\n    // return to office\n    route.emplace_back(OFF_X, OFF_Y);\n\n    // -----------------------------------------------------------------\n    // 3) output\n    cout << M;\n    for (int id : chosenIdx) cout << ' ' << id;\n    cout << '\\n';\n\n    cout << route.size();\n    for (auto [x, y] : route) cout << ' ' << x << ' ' << y;\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        sz.assign(n, 1);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\n/*** Edge description ***/\nstruct Edge {\n    int u, v;\n    int d;          // rounded Euclidean distance\n    int idx;        // original index in input order\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        long long dx = (long long)x[u] - x[v];\n        long long dy = (long long)y[u] - y[v];\n        double dist = sqrt((double)dx * dx + (double)dy * dy);\n        int d = (int)lround(dist);          // round to nearest integer\n        edges[i] = {u, v, d, i};\n    }\n\n    /* ---------- build geometric MST (weight = d_i) ---------- */\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a, int b) {\n             if (edges[a].d != edges[b].d) return edges[a].d < edges[b].d;\n             return a < b;\n         });\n\n    DSU dsu_mst(N);\n    vector<char> inMST(M, 0);\n    int taken = 0;\n    for (int id : order) {\n        const Edge &e = edges[id];\n        if (dsu_mst.unite(e.u, e.v)) {\n            inMST[id] = 1;\n            ++taken;\n            if (taken == N - 1) break;\n        }\n    }\n\n    /* ---------- online phase ---------- */\n    DSU dsu(N);\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;                     // true length of edge i\n        bool accept = false;\n        if (inMST[i] && dsu.find(edges[i].u) != dsu.find(edges[i].v)) {\n            accept = true;\n            dsu.unite(edges[i].u, edges[i].v);\n        }\n        cout << (accept ? 1 : 0) << '\\n' << flush;\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pet   { int x, y, type; };\nstruct Human { int x, y; };\nstruct WallTask {\n    int px, py;      // human must stand here\n    char dir;        // lower\u2011case direction to build the wall\n    int tx, ty;      // target wall square\n};\n\nstatic const int H = 30;\ninline bool inside(int x, int y) { return 1 <= x && x <= H && 1 <= y && y <= H; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;  if (!(cin >> N)) return 0;\n    vector<Pet> pets(N);\n    for (auto &p : pets) cin >> p.x >> p.y >> p.type;\n\n    int M;  cin >> M;\n    vector<Human> humans(M);\n    for (auto &h : humans) cin >> h.x >> h.y;\n\n    // ----- board data -----\n    bool wall[31][31] = {};          // impassable squares\n    bool petOcc[31][31];\n    bool humanOcc[31][31];\n    bool wallTarget[31][31];         // squares that will become walls this turn\n\n    // ----- block generation (5\u00d75 blocks, spacing 7) -----\n    const int B = 5;                 // block side length (odd)\n    vector<pair<int,int>> blockTopLeft;\n    for (int rx = 1; rx + B - 1 <= H; rx += B + 2)\n        for (int ry = 1; ry + B - 1 <= H; ry += B + 2)\n            blockTopLeft.emplace_back(rx, ry);\n    vector<bool> blockUsed(blockTopLeft.size(), false);\n\n    // ----- human state machine -----\n    struct HState {\n        int state = 2;               // 0=go to centre, 1=build walls, 2=idle\n        int targetX = -1, targetY = -1;\n        vector<WallTask> tasks;\n        size_t taskIdx = 0;\n    };\n    vector<HState> hst(M);\n\n    // initial pet occupancy (only needed for block selection)\n    memset(petOcc, 0, sizeof(petOcc));\n    for (const auto &p : pets) petOcc[p.x][p.y] = true;\n\n    // assign a block to each human if possible\n    for (int i = 0; i < M; ++i) {\n        bool assigned = false;\n        for (size_t b = 0; b < blockTopLeft.size(); ++b) if (!blockUsed[b]) {\n            int rx = blockTopLeft[b].first;\n            int ry = blockTopLeft[b].second;\n            bool ok = true;\n            for (int x = rx; x < rx + B && ok; ++x)\n                for (int y = ry; y < ry + B; ++y)\n                    if (petOcc[x][y]) { ok = false; break; }\n            if (!ok) continue;\n            blockUsed[b] = true;\n            assigned = true;\n            // centre of the block\n            hst[i].targetX = rx + B/2;\n            hst[i].targetY = ry + B/2;\n            hst[i].state = 0;   // start moving\n            // generate wall tasks (perimeter)\n            vector<WallTask> tasks;\n            // top side (build upward)\n            for (int y = ry; y < ry + B; ++y) {\n                int tx = rx - 1, ty = y;\n                if (inside(tx, ty))\n                    tasks.push_back({rx, y, 'u', tx, ty});\n            }\n            // bottom side (build downward)\n            for (int y = ry; y < ry + B; ++y) {\n                int tx = rx + B, ty = y;\n                if (inside(tx, ty))\n                    tasks.push_back({rx + B - 1, y, 'd', tx, ty});\n            }\n            // left side (build leftward)\n            for (int x = rx; x < rx + B; ++x) {\n                int tx = x, ty = ry - 1;\n                if (inside(tx, ty))\n                    tasks.push_back({x, ry, 'l', tx, ty});\n            }\n            // right side (build rightward)\n            for (int x = rx; x < rx + B; ++x) {\n                int tx = x, ty = ry + B;\n                if (inside(tx, ty))\n                    tasks.push_back({x, ry + B - 1, 'r', tx, ty});\n            }\n            hst[i].tasks = std::move(tasks);\n            break;\n        }\n        if (!assigned) hst[i].state = 2;   // idle (no block)\n    }\n\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    const char moveChar[4] = {'U','D','L','R'};\n    const char wallChar[4] = {'u','d','l','r'};\n\n    auto canBuild = [&](int tx, int ty) -> bool {\n        if (!inside(tx, ty)) return false;\n        if (wall[tx][ty]) return false;\n        if (humanOcc[tx][ty]) return false;\n        if (petOcc[tx][ty]) return false;\n        for (int d = 0; d < 4; ++d) {\n            int nx = tx + dx[d], ny = ty + dy[d];\n            if (inside(nx, ny) && petOcc[nx][ny]) return false;\n        }\n        return true;\n    };\n\n    // ----- main simulation (300 turns) -----\n    for (int turn = 0; turn < 300; ++turn) {\n        // rebuild occupancy maps for the start of this turn\n        memset(petOcc, 0, sizeof(petOcc));\n        for (const auto &p : pets) petOcc[p.x][p.y] = true;\n        memset(humanOcc, 0, sizeof(humanOcc));\n        for (const auto &h : humans) humanOcc[h.x][h.y] = true;\n        memset(wallTarget, 0, sizeof(wallTarget));\n\n        string actions(M, '?');   // '?' will be replaced later\n\n        // ---------- first pass : try to build walls ----------\n        for (int i = 0; i < M; ++i) {\n            HState &st = hst[i];\n            Human &h = humans[i];\n            if (st.state == 1 && st.taskIdx < st.tasks.size()) {\n                const WallTask &wt = st.tasks[st.taskIdx];\n                if (h.x == wt.px && h.y == wt.py && canBuild(wt.tx, wt.ty)) {\n                    actions[i] = wt.dir;               // lower\u2011case\n                    wallTarget[wt.tx][wt.ty] = true;\n                    ++st.taskIdx;\n                    if (st.taskIdx >= st.tasks.size()) st.state = 2;\n                    continue;\n                }\n            }\n            actions[i] = '?';\n        }\n\n        // ---------- second pass : decide movements ----------\n        for (int i = 0; i < M; ++i) {\n            if (actions[i] != '?') continue;   // already a wall action\n            HState &st = hst[i];\n            Human &h = humans[i];\n            char chosen = '.';\n\n            // helper: try a direction, returns true if allowed\n            auto tryDir = [&](int d) -> bool {\n                int nx = h.x + dx[d], ny = h.y + dy[d];\n                if (!inside(nx, ny)) return false;\n                if (wall[nx][ny]) return false;\n                if (wallTarget[nx][ny]) return false;\n                chosen = moveChar[d];\n                return true;\n            };\n\n            if (st.state == 0) {                     // move to centre\n                if (h.x == st.targetX && h.y == st.targetY) {\n                    st.state = 1;                    // start building\n                } else {\n                    // move one step that reduces Manhattan distance\n                    int bestDist = INT_MAX, bestDir = -1;\n                    for (int d = 0; d < 4; ++d) {\n                        int nx = h.x + dx[d], ny = h.y + dy[d];\n                        if (!inside(nx, ny) || wall[nx][ny] || wallTarget[nx][ny]) continue;\n                        int dist = abs(nx - st.targetX) + abs(ny - st.targetY);\n                        if (dist < bestDist) {\n                            bestDist = dist;\n                            bestDir = d;\n                        }\n                    }\n                    if (bestDir != -1) chosen = moveChar[bestDir];\n                }\n            } else if (st.state == 1) {              // building walls\n                if (st.taskIdx < st.tasks.size()) {\n                    const WallTask &wt = st.tasks[st.taskIdx];\n                    if (h.x != wt.px || h.y != wt.py) {\n                        // move towards the required border cell\n                        int bestDist = INT_MAX, bestDir = -1;\n                        for (int d = 0; d < 4; ++d) {\n                            int nx = h.x + dx[d], ny = h.y + dy[d];\n                            if (!inside(nx, ny) || wall[nx][ny] || wallTarget[nx][ny]) continue;\n                            int dist = abs(nx - wt.px) + abs(ny - wt.py);\n                            if (dist < bestDist) {\n                                bestDist = dist;\n                                bestDir = d;\n                            }\n                        }\n                        if (bestDir != -1) chosen = moveChar[bestDir];\n                    } else {\n                        // at required position but cannot build now \u2192 move away from pets\n                        bool petAdj = false;\n                        for (int d = 0; d < 4; ++d) {\n                            int nx = h.x + dx[d], ny = h.y + dy[d];\n                            if (inside(nx, ny) && petOcc[nx][ny]) { petAdj = true; break; }\n                        }\n                        if (petAdj) {\n                            for (int d = 0; d < 4; ++d) {\n                                if (tryDir(d)) break;\n                            }\n                        } else {\n                            chosen = '.';\n                        }\n                    }\n                } else {\n                    // all tasks finished\n                    st.state = 2;\n                    chosen = '.';\n                }\n            } else {                                 // state == 2 (idle)\n                chosen = '.';\n            }\n            actions[i] = chosen;\n        }\n\n        // ---------- output ----------\n        cout << actions << '\\n' << flush;\n\n        // ---------- read pet moves ----------\n        vector<string> petMoves(N);\n        for (int i = 0; i < N; ++i) cin >> petMoves[i];\n\n        // ---------- apply walls ----------\n        for (int i = 0; i < M; ++i) {\n            char c = actions[i];\n            if (c >= 'a' && c <= 'z') {\n                int d = (c == 'u' ? 0 : (c == 'd' ? 1 : (c == 'l' ? 2 : 3)));\n                int tx = humans[i].x + dx[d];\n                int ty = humans[i].y + dy[d];\n                if (inside(tx, ty)) wall[tx][ty] = true;\n            }\n        }\n\n        // ---------- apply movements ----------\n        for (int i = 0; i < M; ++i) {\n            char c = actions[i];\n            if (c >= 'A' && c <= 'Z') {\n                int d = (c == 'U' ? 0 : (c == 'D' ? 1 : (c == 'L' ? 2 : 3)));\n                int nx = humans[i].x + dx[d];\n                int ny = humans[i].y + dy[d];\n                if (inside(nx, ny) && !wall[nx][ny]) {\n                    humans[i].x = nx;\n                    humans[i].y = ny;\n                }\n            }\n        }\n\n        // ---------- apply pet moves ----------\n        for (int i = 0; i < N; ++i) {\n            const string &s = petMoves[i];\n            for (char c : s) {\n                if (c == '.') continue;\n                int d = (c == 'U' ? 0 : (c == 'D' ? 1 : (c == 'L' ? 2 : 3)));\n                pets[i].x += dx[d];\n                pets[i].y += dy[d];\n                // the judge guarantees the move is legal\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 20;                 // grid size\nconstexpr int V = N * N;              // number of cells\nconstexpr int MAXLEN = 200;           // maximal output length\n\n// direction handling\nconst int di[4] = {-1, 1, 0, 0};\nconst int dj[4] = {0, 0, -1, 1};\nconst char dch[4] = {'U', 'D', 'L', 'R'};\ninline int dirIdx(char c) {\n    if (c == 'U') return 0;\n    if (c == 'D') return 1;\n    if (c == 'L') return 2;\n    return 3; // 'R'\n}\n\n// ------------------------------------------------------------\n// evaluate expected score of a given string (exact DP)\ndouble evaluate(const string& s,\n                const array<array<int,4>,V>& nxt,\n                int startId, int targetId, double p)\n{\n    const double stayProb = p;\n    const double moveProb = 1.0 - p;\n\n    static double cur[V];\n    static double nxtdp[V];\n    fill(begin(cur), end(cur), 0.0);\n    cur[startId] = 1.0;\n\n    double expected = 0.0;\n\n    for (int step = 0; step < (int)s.size(); ++step) {\n        fill(begin(nxtdp), end(nxtdp), 0.0);\n        int d = dirIdx(s[step]);\n        for (int v = 0; v < V; ++v) {\n            double prob = cur[v];\n            if (prob == 0.0) continue;\n            if (v == targetId) {\n                nxtdp[v] += prob;               // absorbing\n                continue;\n            }\n            int w = nxt[v][d];\n            // move remembered\n            nxtdp[w] += prob * moveProb;\n            // character forgotten\n            nxtdp[v] += prob * stayProb;\n        }\n        double newArrived = nxtdp[targetId] - cur[targetId];\n        expected += (401.0 - (step + 1)) * newArrived;\n        memcpy(cur, nxtdp, sizeof(cur));\n    }\n    return expected;\n}\n\n// ------------------------------------------------------------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj, ti, tj;\n    double p;\n    if (!(cin >> si >> sj >> ti >> tj >> p)) return 0;\n\n    // read walls\n    vector<string> h(N);          // horizontal, length 19\n    for (int i = 0; i < N; ++i) cin >> h[i];\n    vector<string> v(N-1);        // vertical, length 20\n    for (int i = 0; i < N-1; ++i) cin >> v[i];\n\n    // neighbour table: nxt[cell][direction] = destination cell\n    array<array<int,4>,V> nxt;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int id = i * N + j;\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d];\n                int nj = j + dj[d];\n                bool blocked = false;\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) {\n                    blocked = true;\n                } else {\n                    if (d == 0) { // U\n                        blocked = (v[i-1][j] == '1');\n                    } else if (d == 1) { // D\n                        blocked = (v[i][j] == '1');\n                    } else if (d == 2) { // L\n                        blocked = (h[i][j-1] == '1');\n                    } else { // R\n                        blocked = (h[i][j] == '1');\n                    }\n                }\n                if (blocked) nxt[id][d] = id;\n                else nxt[id][d] = ni * N + nj;\n            }\n        }\n    }\n\n    int startId = si * N + sj;\n    int targetId = ti * N + tj;\n\n    // --------------------------------------------------------\n    // 1) BFS from target to obtain a shortest path\n    vector<int> dist(V, -1);\n    vector<int> prevDir(V, -1);   // direction from predecessor to this cell\n    vector<int> prevCell(V, -1);\n    queue<int> q;\n    dist[targetId] = 0;\n    q.push(targetId);\n    while (!q.empty()) {\n        int vtx = q.front(); q.pop();\n        int vi = vtx / N, vj = vtx % N;\n        for (int d = 0; d < 4; ++d) {\n            int u = nxt[vtx][d];\n            if (u == vtx) continue;               // wall\n            if (dist[u] == -1) {\n                dist[u] = dist[vtx] + 1;\n                prevDir[u] = d ^ 1;               // opposite direction\n                prevCell[u] = vtx;\n                q.push(u);\n            }\n        }\n    }\n\n    // reconstruct one shortest path (forward direction)\n    string basePath;\n    int cur = startId;\n    while (cur != targetId && prevDir[cur] != -1) {\n        basePath.push_back(dch[prevDir[cur]]);\n        cur = prevCell[cur];\n    }\n\n    // --------------------------------------------------------\n    // 2) build initial answer: repeat the shortest path as many times as possible\n    string best;\n    if (!basePath.empty()) {\n        while ((int)best.size() + (int)basePath.size() <= MAXLEN) {\n            best += basePath;\n        }\n        int need = MAXLEN - (int)best.size();\n        if (need > 0 && need <= (int)basePath.size())\n            best += basePath.substr(0, need);\n    }\n    if (best.empty()) { // fallback (should never happen)\n        static const char dirs[4] = {'U','D','L','R'};\n        std::mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n        for (int i = 0; i < MAXLEN; ++i) best.push_back(dirs[rng() % 4]);\n    }\n\n    // --------------------------------------------------------\n    // 3) DP evaluation function (already defined above)\n    double bestScore = evaluate(best, nxt, startId, targetId, p);\n\n    // --------------------------------------------------------\n    // 4) random generator\n    std::mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    const char dirs[4] = {'U','D','L','R'};\n    uniform_real_distribution<double> real01(0.0, 1.0);\n    uniform_int_distribution<int> dirDist(0, 3);\n\n    // --------------------------------------------------------\n    // 5) generate a few biased random strings\n    const int BIASED_CANDIDATES = 500;\n    for (int it = 0; it < BIASED_CANDIDATES; ++it) {\n        string cand;\n        cand.reserve(MAXLEN);\n        int curCell = startId;\n        for (int pos = 0; pos < MAXLEN; ++pos) {\n            // collect the four possible directions\n            vector<int> candDir;\n            candDir.reserve(4);\n            for (int d = 0; d < 4; ++d) candDir.push_back(d);\n            // compute Manhattan distance after each move\n            int bestDist = INT_MAX;\n            for (int d : candDir) {\n                int nb = nxt[curCell][d];\n                int r = nb / N, c = nb % N;\n                int dist = abs(r - ti) + abs(c - tj);\n                if (dist < bestDist) bestDist = dist;\n            }\n            vector<int> good;\n            for (int d : candDir) {\n                int nb = nxt[curCell][d];\n                int r = nb / N, c = nb % N;\n                int dist = abs(r - ti) + abs(c - tj);\n                if (dist == bestDist) good.push_back(d);\n            }\n            int chosen;\n            if (real01(rng) < 0.8 && !good.empty())\n                chosen = good[dirDist(rng) % good.size()];\n            else\n                chosen = candDir[dirDist(rng) % candDir.size()];\n            cand.push_back(dirs[chosen]);\n            curCell = nxt[curCell][chosen];\n        }\n        double sc = evaluate(cand, nxt, startId, targetId, p);\n        if (sc > bestScore) {\n            bestScore = sc;\n            best = cand;\n        }\n    }\n\n    // --------------------------------------------------------\n    // 6) hill\u2011climbing (local search)\n    const double TIME_LIMIT = 1.80; // seconds\n    auto startTime = chrono::steady_clock::now();\n\n    while (true) {\n        double elapsed = chrono::duration<double>(chrono::steady_clock::now() - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        // mutate a copy of the current best string\n        string cand = best;\n        // pick a random position and replace it\n        int pos = uniform_int_distribution<int>(0, (int)cand.size() - 1)(rng);\n        cand[pos] = dirs[dirDist(rng)];\n        double sc = evaluate(cand, nxt, startId, targetId, p);\n        if (sc >= bestScore) {\n            bestScore = sc;\n            best = cand;\n        }\n    }\n\n    // --------------------------------------------------------\n    cout << best << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;\nconstexpr int DIR = 4;\nconstexpr int TOTAL = N * N * DIR;          // 30*30*4 = 3600\nconstexpr int di[DIR] = {0, -1, 0, 1};       // left, up, right, down\nconstexpr int dj[DIR] = {-1, 0, 1, 0};\n\nint tile[N][N];                              // original tile types\n\n// base connection table from the statement\nconst int base_to[8][4] = {\n    { 1, 0,-1,-1},\n    { 3,-1,-1, 0},\n    {-1,-1, 3, 2},\n    {-1, 2, 1,-1},\n    { 1, 0, 3, 2},\n    { 3, 2, 1, 0},\n    { 2,-1, 0,-1},\n    {-1, 3,-1, 1}\n};\n\nint to_rot[8][4][4];                         // after rotation\n\ninline int idx(int i, int j, int d) { return ((i * N + j) * DIR + d); }\n\n// ------------------------------------------------------------\n// fast Xorshift64 PRNG\nstruct XorShift {\n    uint64_t x;\n    XorShift() { x = chrono::steady_clock::now().time_since_epoch().count(); }\n    uint32_t next() {\n        x ^= x << 13;\n        x ^= x >> 7;\n        x ^= x << 17;\n        return static_cast<uint32_t>(x);\n    }\n    uint32_t next(uint32_t n) { return next() % n; }\n    double nextDouble() { return (next() >> 11) * (1.0 / 9007199254740992.0); }\n};\n// ------------------------------------------------------------\n\n// ------------------------------------------------------------\n// compute the score (L1 * L2) for a given rotation vector (size 900)\nint computeScore(const vector<int>& rot) {\n    static int nxt[TOTAL];\n    fill(nxt, nxt + TOTAL, -1);\n\n    // build outgoing edges\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int t = tile[i][j];\n            int r = rot[i * N + j];\n            for (int d = 0; d < DIR; ++d) {\n                int d2 = to_rot[t][r][d];\n                if (d2 == -1) continue;\n                int ni = i + di[d2];\n                int nj = j + dj[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) & 3;\n                nxt[idx(i, j, d)] = idx(ni, nj, nd);\n            }\n        }\n    }\n\n    static uint8_t state[TOTAL];   // 0 = unvisited, 1 = in current walk, 2 = finished\n    static int pos[TOTAL];\n    fill(state, state + TOTAL, 0);\n    fill(pos, pos + TOTAL, -1);\n\n    int best1 = 0, best2 = 0;\n    vector<int> path;\n    path.reserve(TOTAL);\n\n    for (int v = 0; v < TOTAL; ++v) {\n        if (state[v]) continue;\n        int cur = v;\n        while (true) {\n            if (cur == -1) break;\n            if (state[cur] == 0) {\n                state[cur] = 1;\n                pos[cur] = static_cast<int>(path.size());\n                path.push_back(cur);\n                cur = nxt[cur];\n            } else if (state[cur] == 1) {\n                int len = static_cast<int>(path.size()) - pos[cur];\n                if (len > best1) { best2 = best1; best1 = len; }\n                else if (len > best2) { best2 = len; }\n                break;\n            } else { // state[cur] == 2\n                break;\n            }\n        }\n        for (int node : path) {\n            state[node] = 2;\n            pos[node] = -1;\n        }\n        path.clear();\n    }\n    if (best2 == 0) return 0;\n    return best1 * best2;\n}\n// ------------------------------------------------------------\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read input\n    for (int i = 0; i < N; ++i) {\n        string line; cin >> line;\n        for (int j = 0; j < N; ++j) tile[i][j] = line[j] - '0';\n    }\n\n    // pre\u2011compute to_rot\n    for (int t = 0; t < 8; ++t) {\n        for (int r = 0; r < 4; ++r) {\n            for (int d = 0; d < 4; ++d) {\n                int local = (d - r + 4) & 3;\n                int out = base_to[t][local];\n                if (out == -1) to_rot[t][r][d] = -1;\n                else to_rot[t][r][d] = (out + r) & 3;\n            }\n        }\n    }\n\n    XorShift rng;\n    vector<int> cur(900), best(900);\n    for (int i = 0; i < 900; ++i) cur[i] = rng.next(4);\n    int curScore = computeScore(cur);\n    best = cur;\n    int bestScore = curScore;\n\n    const double TIME_LIMIT = 1.9;          // seconds\n    const double T0 = 50000.0;              // initial temperature\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        int idx = rng.next(900);\n        int oldR = cur[idx];\n        int newR = rng.next(4);\n        if (newR == oldR) continue;\n        cur[idx] = newR;\n        int newScore = computeScore(cur);\n        int delta = newScore - curScore;\n\n        bool accept = false;\n        if (delta >= 0) accept = true;\n        else {\n            double T = T0 * (1.0 - elapsed / TIME_LIMIT);\n            if (T < 1e-9) T = 1e-9;\n            double prob = exp(delta / T);\n            if (rng.nextDouble() < prob) accept = true;\n        }\n\n        if (accept) {\n            curScore = newScore;\n            if (newScore > bestScore) {\n                bestScore = newScore;\n                best = cur;\n            }\n        } else {\n            cur[idx] = oldR; // revert\n        }\n    }\n\n    // output best solution\n    string out;\n    out.reserve(900);\n    for (int i = 0; i < 900; ++i) out.push_back(char('0' + best[i]));\n    cout << out << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ------------------------------------------------------------\n// conversion from hexadecimal character to integer mask (0\u201115)\ninline int hexCharToInt(char c) {\n    if ('0' <= c && c <= '9') return c - '0';\n    return 10 + (c - 'a');\n}\n\n// ------------------------------------------------------------\nconstexpr int DR[4] = {-1, 1, 0, 0};          // U D L R\nconstexpr int DC[4] = {0, 0, -1, 1};\nconstexpr char DIR_CHAR[4] = {'U', 'D', 'L', 'R'};\nconstexpr int DIR_MASK[4] = {2, 8, 1, 4};     // up, down, left, right\nconstexpr int OPP[4] = {1, 0, 3, 2};         // opposite direction index\n\n// ------------------------------------------------------------\n// compute the size of the largest tree component\nint largestTreeSize(const vector<uint8_t> &board, int N) {\n    const int SZ = N * N;\n    static bool visited[100];\n    for (int i = 0; i < SZ; ++i) visited[i] = false;\n    int best = 0;\n\n    static int q[100];\n    for (int start = 0; start < SZ; ++start) {\n        if (board[start] == 0 || visited[start]) continue;\n        int head = 0, tail = 0;\n        q[tail++] = start;\n        visited[start] = true;\n        int verts = 0, edges = 0;\n        while (head < tail) {\n            int pos = q[head++];\n            ++verts;\n            int r = pos / N, c = pos % N;\n            int mask = board[pos];\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + DR[d];\n                int nc = c + DC[d];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                int npos = nr * N + nc;\n                if (board[npos] == 0) continue;\n                if ((mask & DIR_MASK[d]) && (board[npos] & DIR_MASK[OPP[d]])) {\n                    // count each undirected edge only once (down or right)\n                    if (d == 1 || d == 3) ++edges;\n                    if (!visited[npos]) {\n                        visited[npos] = true;\n                        q[tail++] = npos;\n                    }\n                }\n            }\n        }\n        if (edges == verts - 1) best = max(best, verts);\n    }\n    return best;\n}\n\n// ------------------------------------------------------------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    long long T;\n    if (!(cin >> N >> T)) return 0;\n    const int SZ = N * N;\n    vector<uint8_t> origBoard(SZ);\n    int emptyPos = -1;\n\n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) {\n            int v = hexCharToInt(row[j]);\n            origBoard[i * N + j] = static_cast<uint8_t>(v);\n            if (v == 0) emptyPos = i * N + j;\n        }\n    }\n\n    const int totalTiles = SZ - 1;\n    string bestSeq;\n    int bestScore = 0;\n\n    // --------------------------------------------------------\n    // 1) Greedy baseline (never accept a decreasing move)\n    {\n        vector<uint8_t> board = origBoard;\n        int empty = emptyPos;\n        string seq;\n        int curScore = largestTreeSize(board, N);\n        int bestLocalScore = curScore;\n        string bestLocalSeq = \"\";\n\n        for (long long step = 0; step < T; ++step) {\n            // legal moves\n            vector<int> cand;\n            int er = empty / N, ec = empty % N;\n            for (int d = 0; d < 4; ++d) {\n                int nr = er + DR[d], nc = ec + DC[d];\n                if (0 <= nr && nr < N && 0 <= nc && nc < N) cand.push_back(d);\n            }\n            if (cand.empty()) break;\n\n            int bestMoveScore = -1;\n            vector<int> bestMoves;\n            for (int d : cand) {\n                int nr = er + DR[d], nc = ec + DC[d];\n                int npos = nr * N + nc;\n                swap(board[empty], board[npos]);\n                int ns = largestTreeSize(board, N);\n                swap(board[empty], board[npos]); // revert\n                if (ns > bestMoveScore) {\n                    bestMoveScore = ns;\n                    bestMoves.clear();\n                    bestMoves.push_back(d);\n                } else if (ns == bestMoveScore) {\n                    bestMoves.push_back(d);\n                }\n            }\n\n            if (bestMoveScore < curScore) break; // no non\u2011decreasing move\n\n            static std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n            int chosen = bestMoves[uniform_int_distribution<int>(0, (int)bestMoves.size() - 1)(rng)];\n            int nr = er + DR[chosen], nc = ec + DC[chosen];\n            int npos = nr * N + nc;\n            swap(board[empty], board[npos]);\n            empty = npos;\n            seq.push_back(DIR_CHAR[chosen]);\n            curScore = bestMoveScore;\n\n            if (curScore > bestLocalScore ||\n                (curScore == bestLocalScore && seq.size() < bestLocalSeq.size())) {\n                bestLocalScore = curScore;\n                bestLocalSeq = seq;\n                if (bestLocalScore == totalTiles) break;\n            }\n        }\n        bestSeq = bestLocalSeq;\n        bestScore = bestLocalScore;\n        if (bestScore == totalTiles) {\n            cout << bestSeq << \"\\n\";\n            return 0;\n        }\n    }\n\n    // --------------------------------------------------------\n    // 2) Simulated annealing (randomised hill\u2011climbing)\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_real_distribution<double> probDist(0.0, 1.0);\n    auto startTime = chrono::steady_clock::now();\n    const double TIME_LIMIT = 2.8; // seconds, leave margin for I/O\n\n    while (true) {\n        // time check\n        double elapsed = chrono::duration<double>(chrono::steady_clock::now() - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        vector<uint8_t> board = origBoard;\n        int empty = emptyPos;\n        string curSeq;\n        int curScore = largestTreeSize(board, N);\n        double temperature = 1.0;\n\n        for (long long step = 0; step < T; ++step) {\n            // legal moves\n            vector<int> cand;\n            int er = empty / N, ec = empty % N;\n            for (int d = 0; d < 4; ++d) {\n                int nr = er + DR[d], nc = ec + DC[d];\n                if (0 <= nr && nr < N && 0 <= nc && nc < N) cand.push_back(d);\n            }\n            if (cand.empty()) break;\n\n            int d = cand[uniform_int_distribution<int>(0, (int)cand.size() - 1)(rng)];\n            int nr = er + DR[d], nc = ec + DC[d];\n            int npos = nr * N + nc;\n            swap(board[empty], board[npos]);\n            int newScore = largestTreeSize(board, N);\n            int delta = newScore - curScore;\n\n            bool accept = false;\n            if (delta >= 0) {\n                accept = true;\n            } else {\n                double prob = exp(delta / temperature);\n                if (probDist(rng) < prob) accept = true;\n            }\n\n            if (accept) {\n                empty = npos;\n                curScore = newScore;\n                curSeq.push_back(DIR_CHAR[d]);\n\n                if (curScore > bestScore ||\n                    (curScore == bestScore && curSeq.size() < bestSeq.size())) {\n                    bestScore = curScore;\n                    bestSeq = curSeq;\n                    if (bestScore == totalTiles) break;\n                }\n            } else {\n                // revert the swap\n                swap(board[empty], board[npos]);\n            }\n\n            temperature *= 0.9995; // slow cooling\n        }\n\n        if (bestScore == totalTiles) break;\n    }\n\n    cout << bestSeq << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, K_input;\n    if (!(cin >> N >> K_input)) return 0;          // K_input is always 100\n    vector<int> a(11);\n    for (int d = 1; d <= 10; ++d) cin >> a[d];\n\n    vector<pair<ll,ll>> strawberries(N);\n    for (int i = 0; i < N; ++i) {\n        ll x, y;\n        cin >> x >> y;\n        strawberries[i] = {x, y};\n    }\n\n    const ll R = 10000;          // cake radius\n    const ll M = 20000;          // far outside the cake, still inside limits\n    const int MAX_CUTS = 100;    // maximal number of cuts (fixed)\n\n    // candidate (V,H) pairs, all satisfy V+H <= 100\n    const vector<pair<int,int>> candidates = {\n        {10,10}, {12,8}, {8,12}, {15,5}, {5,15},\n        {20,0}, {0,20},\n        {30,10}, {10,30},\n        {25,25},\n        {40,20}, {20,40},\n        {50,10}, {10,50}\n    };\n\n    std::mt19937_64 rng(\n        std::chrono::steady_clock::now().time_since_epoch().count());\n\n    int bestScore = -1;\n    int bestV = 0, bestH = 0;\n    int bestOffsetX = 0, bestOffsetY = 0;\n\n    const int ATTEMPTS_PER_SHAPE = 200;   // enough to explore offsets\n\n    for (auto [V, H] : candidates) {\n        if (V + H > MAX_CUTS) continue;   // safety\n\n        int stepV = (V == 0) ? 0 : (int)(2 * R / (V + 1));\n        int stepH = (H == 0) ? 0 : (int)(2 * R / (H + 1));\n\n        for (int att = 0; att < ATTEMPTS_PER_SHAPE; ++att) {\n            int offsetX = (stepV > 0) ? uniform_int_distribution<int>(0, stepV - 1)(rng) : 0;\n            int offsetY = (stepH > 0) ? uniform_int_distribution<int>(0, stepH - 1)(rng) : 0;\n\n            // build line positions\n            vector<int> vlines, hlines;\n            vlines.reserve(V);\n            hlines.reserve(H);\n            for (int i = 1; i <= V; ++i) {\n                ll X = -R + offsetX + (ll)i * stepV;\n                vlines.push_back((int)X);\n            }\n            for (int j = 1; j <= H; ++j) {\n                ll Y = -R + offsetY + (ll)j * stepH;\n                hlines.push_back((int)Y);\n            }\n\n            // piece counters\n            vector<int> cnt((V + 1) * (H + 1), 0);\n\n            for (auto [x, y] : strawberries) {\n                int idxX = 0, idxY = 0;\n\n                if (V > 0) {\n                    auto itx = lower_bound(vlines.begin(), vlines.end(), (int)x);\n                    if (itx != vlines.end() && *itx == (int)x) continue; // on vertical line\n                    idxX = int(itx - vlines.begin());\n                }\n                if (H > 0) {\n                    auto ity = lower_bound(hlines.begin(), hlines.end(), (int)y);\n                    if (ity != hlines.end() && *ity == (int)y) continue; // on horizontal line\n                    idxY = int(ity - hlines.begin());\n                }\n\n                int cell = idxX * (H + 1) + idxY;\n                cnt[cell]++;\n            }\n\n            int b[11] = {0};\n            for (int c : cnt) {\n                if (1 <= c && c <= 10) b[c]++;\n            }\n            int score = 0;\n            for (int d = 1; d <= 10; ++d) score += min(a[d], b[d]);\n\n            if (score > bestScore) {\n                bestScore = score;\n                bestV = V; bestH = H;\n                bestOffsetX = offsetX;\n                bestOffsetY = offsetY;\n            }\n        }\n    }\n\n    // Build the best grid\n    vector<int> vlines, hlines;\n    int stepV = (bestV == 0) ? 0 : (int)(2 * R / (bestV + 1));\n    int stepH = (bestH == 0) ? 0 : (int)(2 * R / (bestH + 1));\n    for (int i = 1; i <= bestV; ++i) {\n        ll X = -R + bestOffsetX + (ll)i * stepV;\n        vlines.push_back((int)X);\n    }\n    for (int j = 1; j <= bestH; ++j) {\n        ll Y = -R + bestOffsetY + (ll)j * stepH;\n        hlines.push_back((int)Y);\n    }\n\n    cout << bestV + bestH << \"\\n\";\n    for (int X : vlines) {\n        cout << X << ' ' << -M << ' ' << X << ' ' << M << \"\\n\";\n    }\n    for (int Y : hlines) {\n        cout << -M << ' ' << Y << ' ' << M << ' ' << Y << \"\\n\";\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int x1, y1, x2, y2, x3, y3, x4, y4;\n};\n\nstruct Cell {\n    int x, y;\n    long long w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<vector<char>> dot(N, vector<char>(N, 0));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        dot[x][y] = 1;\n    }\n\n    // used[x][y][dir] : 0 = right, 1 = up, 2 = left, 3 = down\n    vector<vector<array<char,4>>> used(N, vector<array<char,4>>(N));\n    for (int x = 0; x < N; ++x)\n        for (int y = 0; y < N; ++y)\n            used[x][y].fill(0);\n\n    // cells sorted by weight (farther from centre first)\n    long long c = (N - 1) / 2;\n    vector<Cell> cells;\n    cells.reserve(N * N);\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y < N; ++y) {\n            long long w = (x - c) * (x - c) + (y - c) * (y - c) + 1;\n            cells.push_back({x, y, w});\n        }\n    }\n    sort(cells.begin(), cells.end(),\n         [](const Cell& a, const Cell& b){ return a.w > b.w; });\n\n    // helpers for edge handling\n    auto markEdge = [&](int x, int y, int dir) {\n        used[x][y][dir] = 1;\n        int nx = x + (dir == 0) - (dir == 2);\n        int ny = y + (dir == 1) - (dir == 3);\n        used[nx][ny][dir ^ 2] = 1;\n    };\n    auto edgeFreeHorizontal = [&](int x1, int x2, int y) -> bool {\n        for (int x = x1; x < x2; ++x) if (used[x][y][0]) return false;\n        return true;\n    };\n    auto edgeFreeVertical = [&](int y1, int y2, int x) -> bool {\n        for (int y = y1; y < y2; ++y) if (used[x][y][1]) return false;\n        return true;\n    };\n\n    vector<Op> ops;\n    bool added = true;\n    while (added) {\n        added = false;\n        for (const Cell& cell : cells) {\n            int x = cell.x, y = cell.y;\n            if (dot[x][y]) continue;          // already occupied\n\n            bool done = false;\n\n            // ----- orientation 0 : missing bottom\u2011left (x,y) -----\n            for (int x2 = x + 1; x2 < N && !done; ++x2) {\n                if (!dot[x2][y]) continue;\n                for (int y2 = y + 1; y2 < N && !done; ++y2) {\n                    if (!dot[x][y2] || !dot[x2][y2]) continue;\n\n                    // check perimeter for other dots\n                    bool ok = true;\n                    // bottom side\n                    for (int xx = x; xx <= x2 && ok; ++xx) {\n                        if (xx == x && y == y) continue;\n                        if (xx == x2 && y == y) continue;\n                        if (xx == x && y == y2) continue;\n                        if (xx == x2 && y == y2) continue;\n                        if (dot[xx][y]) ok = false;\n                    }\n                    // top side\n                    for (int xx = x; xx <= x2 && ok; ++xx) {\n                        if (xx == x && y2 == y) continue;\n                        if (xx == x2 && y2 == y) continue;\n                        if (xx == x && y2 == y2) continue;\n                        if (xx == x2 && y2 == y2) continue;\n                        if (dot[xx][y2]) ok = false;\n                    }\n                    // left side\n                    for (int yy = y; yy <= y2 && ok; ++yy) {\n                        if (x == x && yy == y) continue;\n                        if (x2 == x && yy == y) continue;\n                        if (x == x && yy == y2) continue;\n                        if (x2 == x && yy == y2) continue;\n                        if (dot[x][yy]) ok = false;\n                    }\n                    // right side\n                    for (int yy = y; yy <= y2 && ok; ++yy) {\n                        if (x2 == x && yy == y) continue;\n                        if (x2 == x2 && yy == y) continue;\n                        if (x2 == x && yy == y2) continue;\n                        if (x2 == x2 && yy == y2) continue;\n                        if (dot[x2][yy]) ok = false;\n                    }\n                    if (!ok) continue;\n\n                    // edge usage check\n                    if (!edgeFreeHorizontal(x, x2, y)) continue;\n                    if (!edgeFreeHorizontal(x, x2, y2)) continue;\n                    if (!edgeFreeVertical(y, y2, x)) continue;\n                    if (!edgeFreeVertical(y, y2, x2)) continue;\n\n                    // all good \u2013 add rectangle\n                    Op op;\n                    op.x1 = x; op.y1 = y;\n                    op.x2 = x2; op.y2 = y;\n                    op.x3 = x2; op.y3 = y2;\n                    op.x4 = x;  op.y4 = y2;\n                    ops.push_back(op);\n                    dot[x][y] = 1;\n                    // mark edges\n                    for (int xx = x; xx < x2; ++xx) {\n                        markEdge(xx, y, 0);      // bottom\n                        markEdge(xx, y2, 0);     // top\n                    }\n                    for (int yy = y; yy < y2; ++yy) {\n                        markEdge(x, yy, 1);      // left\n                        markEdge(x2, yy, 1);     // right\n                    }\n                    added = true;\n                    done = true;\n                }\n            }\n            if (done) break;\n\n            // ----- orientation 1 : missing bottom\u2011right (x,y) -----\n            for (int x1 = x - 1; x1 >= 0 && !done; --x1) {\n                if (!dot[x1][y]) continue;\n                for (int y2 = y + 1; y2 < N && !done; ++y2) {\n                    if (!dot[x][y2] || !dot[x1][y2]) continue;\n\n                    bool ok = true;\n                    // bottom side\n                    for (int xx = x1; xx <= x && ok; ++xx) {\n                        if (xx == x1 && y == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (xx == x1 && y == y2) continue;\n                        if (xx == x && y == y2) continue;\n                        if (dot[xx][y]) ok = false;\n                    }\n                    // top side\n                    for (int xx = x1; xx <= x && ok; ++xx) {\n                        if (xx == x1 && y2 == y) continue;\n                        if (xx == x && y2 == y) continue;\n                        if (xx == x1 && y2 == y2) continue;\n                        if (xx == x && y2 == y2) continue;\n                        if (dot[xx][y2]) ok = false;\n                    }\n                    // left side\n                    for (int yy = y; yy <= y2 && ok; ++yy) {\n                        if (x1 == x1 && yy == y) continue;\n                        if (x == x1 && yy == y) continue;\n                        if (x1 == x1 && yy == y2) continue;\n                        if (x == x1 && yy == y2) continue;\n                        if (dot[x1][yy]) ok = false;\n                    }\n                    // right side\n                    for (int yy = y; yy <= y2 && ok; ++yy) {\n                        if (x1 == x && yy == y) continue;\n                        if (x == x && yy == y) continue;\n                        if (x1 == x && yy == y2) continue;\n                        if (x == x && yy == y2) continue;\n                        if (dot[x][yy]) ok = false;\n                    }\n                    if (!ok) continue;\n\n                    if (!edgeFreeHorizontal(x1, x, y)) continue;\n                    if (!edgeFreeHorizontal(x1, x, y2)) continue;\n                    if (!edgeFreeVertical(y, y2, x1)) continue;\n                    if (!edgeFreeVertical(y, y2, x)) continue;\n\n                    Op op;\n                    op.x1 = x; op.y1 = y;\n                    op.x2 = x1; op.y2 = y;\n                    op.x3 = x1; op.y3 = y2;\n                    op.x4 = x;  op.y4 = y2;\n                    ops.push_back(op);\n                    dot[x][y] = 1;\n                    for (int xx = x1; xx < x; ++xx) {\n                        markEdge(xx, y, 0);\n                        markEdge(xx, y2, 0);\n                    }\n                    for (int yy = y; yy < y2; ++yy) {\n                        markEdge(x1, yy, 1);\n                        markEdge(x, yy, 1);\n                    }\n                    added = true;\n                    done = true;\n                }\n            }\n            if (done) break;\n\n            // ----- orientation 2 : missing top\u2011left (x,y) -----\n            for (int x2 = x + 1; x2 < N && !done; ++x2) {\n                if (!dot[x2][y]) continue;\n                for (int y1 = y - 1; y1 >= 0 && !done; --y1) {\n                    if (!dot[x][y1] || !dot[x2][y1]) continue;\n\n                    bool ok = true;\n                    // left side\n                    for (int yy = y1; yy <= y && ok; ++yy) {\n                        if (x == x && yy == y1) continue;\n                        if (x2 == x && yy == y1) continue;\n                        if (x == x && yy == y) continue;\n                        if (x2 == x && yy == y) continue;\n                        if (dot[x][yy]) ok = false;\n                    }\n                    // right side\n                    for (int yy = y1; yy <= y && ok; ++yy) {\n                        if (x2 == x2 && yy == y1) continue;\n                        if (x2 == x2 && yy == y) continue;\n                        if (x2 == x2 && yy == y1) continue;\n                        if (x2 == x2 && yy == y) continue;\n                        if (dot[x2][yy]) ok = false;\n                    }\n                    // bottom side\n                    for (int xx = x; xx <= x2 && ok; ++xx) {\n                        if (xx == x && y1 == y) continue;\n                        if (xx == x2 && y1 == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (xx == x2 && y == y) continue;\n                        if (dot[xx][y1]) ok = false;\n                    }\n                    // top side\n                    for (int xx = x; xx <= x2 && ok; ++xx) {\n                        if (xx == x && y == y) continue;\n                        if (xx == x2 && y == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (xx == x2 && y == y) continue;\n                        if (dot[xx][y]) ok = false;\n                    }\n                    if (!ok) continue;\n\n                    if (!edgeFreeHorizontal(x, x2, y1)) continue;\n                    if (!edgeFreeHorizontal(x, x2, y)) continue;\n                    if (!edgeFreeVertical(y1, y, x)) continue;\n                    if (!edgeFreeVertical(y1, y, x2)) continue;\n\n                    Op op;\n                    op.x1 = x; op.y1 = y;\n                    op.x2 = x;  op.y2 = y1;\n                    op.x3 = x2; op.y3 = y1;\n                    op.x4 = x2; op.y4 = y;\n                    ops.push_back(op);\n                    dot[x][y] = 1;\n                    for (int xx = x; xx < x2; ++xx) {\n                        markEdge(xx, y1, 0);\n                        markEdge(xx, y, 0);\n                    }\n                    for (int yy = y1; yy < y; ++yy) {\n                        markEdge(x, yy, 1);\n                        markEdge(x2, yy, 1);\n                    }\n                    added = true;\n                    done = true;\n                }\n            }\n            if (done) break;\n\n            // ----- orientation 3 : missing top\u2011right (x,y) -----\n            for (int x1 = x - 1; x1 >= 0 && !done; --x1) {\n                if (!dot[x1][y]) continue;\n                for (int y1 = y - 1; y1 >= 0 && !done; --y1) {\n                    if (!dot[x][y1] || !dot[x1][y1]) continue;\n\n                    bool ok = true;\n                    // left side\n                    for (int yy = y1; yy <= y && ok; ++yy) {\n                        if (x1 == x1 && yy == y1) continue;\n                        if (x == x1 && yy == y1) continue;\n                        if (x1 == x1 && yy == y) continue;\n                        if (x == x1 && yy == y) continue;\n                        if (dot[x1][yy]) ok = false;\n                    }\n                    // right side\n                    for (int yy = y1; yy <= y && ok; ++yy) {\n                        if (x1 == x && yy == y1) continue;\n                        if (x == x && yy == y1) continue;\n                        if (x1 == x && yy == y) continue;\n                        if (x == x && yy == y) continue;\n                        if (dot[x][yy]) ok = false;\n                    }\n                    // bottom side\n                    for (int xx = x1; xx <= x && ok; ++xx) {\n                        if (xx == x1 && y1 == y) continue;\n                        if (xx == x && y1 == y) continue;\n                        if (xx == x1 && y == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (dot[xx][y1]) ok = false;\n                    }\n                    // top side\n                    for (int xx = x1; xx <= x && ok; ++xx) {\n                        if (xx == x1 && y == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (xx == x1 && y == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (dot[xx][y]) ok = false;\n                    }\n                    if (!ok) continue;\n\n                    if (!edgeFreeHorizontal(x1, x, y1)) continue;\n                    if (!edgeFreeHorizontal(x1, x, y)) continue;\n                    if (!edgeFreeVertical(y1, y, x1)) continue;\n                    if (!edgeFreeVertical(y1, y, x)) continue;\n\n                    Op op;\n                    op.x1 = x; op.y1 = y;\n                    op.x2 = x1; op.y2 = y;\n                    op.x3 = x1; op.y3 = y1;\n                    op.x4 = x;  op.y4 = y1;\n                    ops.push_back(op);\n                    dot[x][y] = 1;\n                    for (int xx = x1; xx < x; ++xx) {\n                        markEdge(xx, y1, 0);\n                        markEdge(xx, y, 0);\n                    }\n                    for (int yy = y1; yy < y; ++yy) {\n                        markEdge(x1, yy, 1);\n                        markEdge(x, yy, 1);\n                    }\n                    added = true;\n                    done = true;\n                }\n            }\n            if (done) break;\n        }\n    }\n\n    cout << ops.size() << \"\\n\";\n    for (const Op& o : ops) {\n        cout << o.x1 << ' ' << o.y1 << ' '\n             << o.x2 << ' ' << o.y2 << ' '\n             << o.x3 << ' ' << o.y3 << ' '\n             << o.x4 << ' ' << o.y4 << \"\\n\";\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* -------------------------------------------------------------\n   Board representation\n   ------------------------------------------------------------- */\nstruct Board {\n    int a[10][10];\n};\n\ninline void tilt(Board &b, char dir) {\n    if (dir == 'L') {\n        for (int i = 0; i < 10; ++i) {\n            int write = 0;\n            for (int j = 0; j < 10; ++j) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != j) {\n                        b.a[i][write] = v;\n                        b.a[i][j] = 0;\n                    }\n                    ++write;\n                }\n            }\n        }\n    } else if (dir == 'R') {\n        for (int i = 0; i < 10; ++i) {\n            int write = 9;\n            for (int j = 9; j >= 0; --j) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != j) {\n                        b.a[i][write] = v;\n                        b.a[i][j] = 0;\n                    }\n                    --write;\n                }\n            }\n        }\n    } else if (dir == 'F') {          // forward = up\n        for (int j = 0; j < 10; ++j) {\n            int write = 0;\n            for (int i = 0; i < 10; ++i) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != i) {\n                        b.a[write][j] = v;\n                        b.a[i][j] = 0;\n                    }\n                    ++write;\n                }\n            }\n        }\n    } else {                         // dir == 'B'  backward = down\n        for (int j = 0; j < 10; ++j) {\n            int write = 9;\n            for (int i = 9; i >= 0; --i) {\n                if (b.a[i][j] != 0) {\n                    int v = b.a[i][j];\n                    if (write != i) {\n                        b.a[write][j] = v;\n                        b.a[i][j] = 0;\n                    }\n                    --write;\n                }\n            }\n        }\n    }\n}\n\n/* -------------------------------------------------------------\n   \u03a3 size\u00b2 of all connected components (four\u2011directional)\n   ------------------------------------------------------------- */\nlong long score(const Board &b) {\n    bool vis[10][10] = {};\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    long long sum = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (b.a[i][j] != 0 && !vis[i][j]) {\n                int flavour = b.a[i][j];\n                int cnt = 0;\n                queue<pair<int,int>> q;\n                q.emplace(i, j);\n                vis[i][j] = true;\n                while (!q.empty()) {\n                    auto [x, y] = q.front(); q.pop();\n                    ++cnt;\n                    for (int k = 0; k < 4; ++k) {\n                        int nx = x + dx[k];\n                        int ny = y + dy[k];\n                        if (0 <= nx && nx < 10 && 0 <= ny && ny < 10 &&\n                            !vis[nx][ny] && b.a[nx][ny] == flavour) {\n                            vis[nx][ny] = true;\n                            q.emplace(nx, ny);\n                        }\n                    }\n                }\n                sum += 1LL * cnt * cnt;\n            }\n        }\n    }\n    return sum;\n}\n\n/* -------------------------------------------------------------\n   place a candy of flavour f into the p\u2011th empty cell (1\u2011based)\n   ------------------------------------------------------------- */\ninline void place(Board &b, int f, int p) {\n    int cnt = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (b.a[i][j] == 0) {\n                ++cnt;\n                if (cnt == p) {\n                    b.a[i][j] = f;\n                    return;\n                }\n            }\n        }\n    }\n}\n\n/* -------------------------------------------------------------\n   collect coordinates of empty cells (row\u2011major order)\n   ------------------------------------------------------------- */\ninline void emptyCells(const Board &b, pair<int,int> *out, int &outCnt) {\n    outCnt = 0;\n    for (int i = 0; i < 10; ++i)\n        for (int j = 0; j < 10; ++j)\n            if (b.a[i][j] == 0)\n                out[outCnt++] = {i, j};\n}\n\n/* -------------------------------------------------------------\n   greedy tilt \u2013 direction that maximises the immediate score\n   ------------------------------------------------------------- */\nchar greedyTilt(const Board &b) {\n    const char dirs[4] = {'F','B','L','R'};\n    long long best = -1;\n    char bestDir = 'F';\n    for (char d : dirs) {\n        Board tmp = b;\n        tilt(tmp, d);\n        long long sc = score(tmp);\n        if (sc > best) {\n            best = sc;\n            bestDir = d;\n        }\n    }\n    return bestDir;\n}\n\n/* -------------------------------------------------------------\n   main\n   ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int TOTAL = 100;\n    vector<int> flavor(TOTAL);\n    for (int i = 0; i < TOTAL; ++i) cin >> flavor[i];\n\n    Board board{};\n    memset(board.a, 0, sizeof(board.a));\n\n    const char DIRS[4] = {'F','B','L','R'};\n    const int K   = 15;          // look\u2011ahead depth\n    const int SIM = 8;           // Monte\u2011Carlo repetitions\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    pair<int,int> empties[100];\n    int emptyCnt;\n\n    for (int t = 0; t < TOTAL; ++t) {\n        int p; cin >> p;\n        place(board, flavor[t], p);\n\n        if (t == TOTAL-1) break;               // last candy \u2013 no tilt needed\n\n        double bestAvg = -1e100;\n        char bestDir = 'F';\n\n        for (char d : DIRS) {\n            Board tmp = board;\n            tilt(tmp, d);\n            long long imm = score(tmp);\n            double total = static_cast<double>(imm);\n\n            for (int sim = 0; sim < SIM; ++sim) {\n                Board simBoard = tmp;\n                int remaining = TOTAL - (t + 1);\n                int steps = min(K, remaining);\n                for (int step = 0; step < steps; ++step) {\n                    // random placement of the known future flavour\n                    emptyCells(simBoard, empties, emptyCnt);\n                    int idx = rng() % emptyCnt;\n                    auto [ri, rj] = empties[idx];\n                    simBoard.a[ri][rj] = flavor[t + 1 + step];\n\n                    // greedy tilt for the simulated step\n                    char d2 = greedyTilt(simBoard);\n                    tilt(simBoard, d2);\n                }\n                total += static_cast<double>(score(simBoard));\n            }\n            double avg = total / (SIM + 1);\n            if (avg > bestAvg) {\n                bestAvg = avg;\n                bestDir = d;\n            }\n        }\n\n        cout << bestDir << '\\n';\n        cout.flush();\n\n        tilt(board, bestDir);          // apply the chosen tilt to the real board\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct GraphInfo {\n    string adjStr;               // binary representation (output)\n    vector<double> feat;         // feature vector (size = 8)\n};\n\ninline double sq(double x) { return x * x; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;          // no input\n\n    const int N = 6;                           // vertex count (small)\n    const int L = N * (N - 1) / 2;             // length of binary string\n    const int maxTri = N * (N - 1) * (N - 2) / 6; // C(N,3)\n    const int maxEdge = L;                     // maximum number of edges\n    const int D = N + 2;                       // feature dimension (8)\n\n    const int POOL = 8000;                     // pool size (\u226b M)\n    mt19937_64 rng(123456789ULL);              // deterministic RNG\n\n    vector<GraphInfo> pool;\n    pool.reserve(POOL);\n    unordered_set<string> usedStr;             // avoid duplicate graphs\n\n    // ---------- 1. generate pool ----------\n    while ((int)pool.size() < POOL) {\n        // ----- random adjacency -----\n        vector<vector<char>> adj(N, vector<char>(N, 0));\n        string s;\n        s.reserve(L);\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                bool edge = (rng() & 1ULL);\n                adj[i][j] = adj[j][i] = edge;\n                s.push_back(edge ? '1' : '0');\n            }\n        }\n        if (usedStr.find(s) != usedStr.end()) continue; // duplicate\n        usedStr.insert(s);\n\n        // ----- degree vector (sorted) -----\n        vector<int> deg(N);\n        for (int i = 0; i < N; ++i) {\n            int cnt = 0;\n            for (int j = 0; j < N; ++j) cnt += adj[i][j];\n            deg[i] = cnt;\n        }\n        sort(deg.begin(), deg.end());\n\n        // ----- edge count -----\n        int edges = 0;\n        for (int d : deg) edges += d;\n        edges /= 2; // each edge counted twice\n\n        // ----- triangle count -----\n        int tri = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = i + 1; j < N; ++j) if (adj[i][j])\n                for (int k = j + 1; k < N; ++k)\n                    if (adj[i][k] && adj[j][k]) ++tri;\n\n        // ----- feature vector -----\n        vector<double> feat;\n        feat.reserve(D);\n        for (int d : deg) feat.push_back(static_cast<double>(d) / (N - 1));\n        feat.push_back(static_cast<double>(edges) / maxEdge);\n        feat.push_back(static_cast<double>(tri) / maxTri);\n\n        GraphInfo gi;\n        gi.adjStr = std::move(s);\n        gi.feat = std::move(feat);\n        pool.push_back(std::move(gi));\n    }\n\n    // ---------- 2. greedy max\u2011min selection ----------\n    vector<int> selectedIdx;                // indices inside pool\n    selectedIdx.reserve(M);\n    vector<char> taken(pool.size(), 0);\n\n    selectedIdx.push_back(0);\n    taken[0] = 1;\n\n    vector<double> minDist(pool.size(), numeric_limits<double>::infinity());\n    auto dist = [&](const vector<double>& a, const vector<double>& b) {\n        double s = 0.0;\n        for (int i = 0; i < D; ++i) {\n            double diff = a[i] - b[i];\n            s += diff * diff;\n        }\n        return s;\n    };\n\n    // initialise distances to the first selected graph\n    for (size_t i = 1; i < pool.size(); ++i) {\n        minDist[i] = dist(pool[0].feat, pool[i].feat);\n    }\n\n    while ((int)selectedIdx.size() < M) {\n        // pick the candidate with maximal minimal distance\n        int best = -1;\n        double bestVal = -1.0;\n        for (size_t i = 0; i < pool.size(); ++i) if (!taken[i]) {\n            if (minDist[i] > bestVal) {\n                bestVal = minDist[i];\n                best = (int)i;\n            }\n        }\n        selectedIdx.push_back(best);\n        taken[best] = 1;\n\n        // update minimal distances\n        for (size_t i = 0; i < pool.size(); ++i) if (!taken[i]) {\n            double d = dist(pool[best].feat, pool[i].feat);\n            if (d < minDist[i]) minDist[i] = d;\n        }\n    }\n\n    // ---------- 3. output the chosen graphs ----------\n    cout << N << \"\\n\";\n    for (int idx : selectedIdx) {\n        cout << pool[idx].adjStr << \"\\n\";\n    }\n    cout.flush();\n\n    // ---------- 4. answer the 100 queries ----------\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // rebuild adjacency matrix of H\n        vector<vector<char>> adj(N, vector<char>(N, 0));\n        int pos = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                bool edge = (H[pos++] == '1');\n                adj[i][j] = adj[j][i] = edge;\n            }\n        }\n\n        // degree vector (sorted)\n        vector<int> deg(N);\n        for (int i = 0; i < N; ++i) {\n            int cnt = 0;\n            for (int j = 0; j < N; ++j) cnt += adj[i][j];\n            deg[i] = cnt;\n        }\n        sort(deg.begin(), deg.end());\n\n        // edge count\n        int edges = 0;\n        for (int d : deg) edges += d;\n        edges /= 2;\n\n        // triangle count\n        int tri = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = i + 1; j < N; ++j) if (adj[i][j])\n                for (int k = j + 1; k < N; ++k)\n                    if (adj[i][k] && adj[j][k]) ++tri;\n\n        // feature vector of H\n        vector<double> feat;\n        feat.reserve(D);\n        for (int d : deg) feat.push_back(static_cast<double>(d) / (N - 1));\n        feat.push_back(static_cast<double>(edges) / maxEdge);\n        feat.push_back(static_cast<double>(tri) / maxTri);\n\n        // nearest neighbour among the selected graphs\n        int bestIdx = 0;\n        double bestDist = numeric_limits<double>::infinity();\n        for (int i = 0; i < M; ++i) {\n            const vector<double>& cand = pool[selectedIdx[i]].feat;\n            double d = 0.0;\n            for (int j = 0; j < D; ++j) {\n                double diff = feat[j] - cand[j];\n                d += diff * diff;\n            }\n            if (d < bestDist) {\n                bestDist = d;\n                bestIdx = i;\n            }\n        }\n        cout << bestIdx << \"\\n\" << flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll INF = (1LL << 60);\n\nstruct Edge {\n    int u, v;\n    int w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[i] = {u, v, w};\n    }\n    // coordinates are irrelevant\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        (void)x; (void)y;\n    }\n\n    // ---------- adjacency ----------\n    vector<vector<tuple<int,int,int>>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u = edges[i].u, v = edges[i].v, w = edges[i].w;\n        adj[u].push_back({v, w, i});\n        adj[v].push_back({u, w, i});\n    }\n\n    // ---------- exact weighted betweenness (Brandes) ----------\n    vector<double> edge_bc(M, 0.0);\n    vector<ll> dist(N);\n    vector<double> sigma(N);\n    vector<double> delta(N);\n    vector<vector<int>> pred(N);\n    vector<vector<int>> pred_e(N);\n    vector<int> order;\n    order.reserve(N);\n\n    for (int s = 0; s < N; ++s) {\n        fill(dist.begin(), dist.end(), INF);\n        fill(sigma.begin(), sigma.end(), 0.0);\n        for (int i = 0; i < N; ++i) {\n            pred[i].clear();\n            pred_e[i].clear();\n        }\n        order.clear();\n\n        dist[s] = 0;\n        sigma[s] = 1.0;\n        using PQItem = pair<ll,int>;\n        priority_queue<PQItem, vector<PQItem>, greater<PQItem>> pq;\n        pq.emplace(0LL, s);\n\n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d != dist[v]) continue;\n            order.push_back(v);\n            for (auto [to, wgt, eid] : adj[v]) {\n                ll nd = d + wgt;\n                if (nd < dist[to]) {\n                    dist[to] = nd;\n                    sigma[to] = sigma[v];\n                    pred[to].clear();\n                    pred_e[to].clear();\n                    pred[to].push_back(v);\n                    pred_e[to].push_back(eid);\n                    pq.emplace(nd, to);\n                } else if (nd == dist[to]) {\n                    sigma[to] += sigma[v];\n                    pred[to].push_back(v);\n                    pred_e[to].push_back(eid);\n                }\n            }\n        }\n\n        fill(delta.begin(), delta.end(), 0.0);\n        for (int idx = (int)order.size() - 1; idx >= 0; --idx) {\n            int w = order[idx];\n            for (size_t i = 0; i < pred[w].size(); ++i) {\n                int v = pred[w][i];\n                int eid = pred_e[w][i];\n                double coeff = (sigma[v] / sigma[w]) * (1.0 + delta[w]);\n                delta[v] += coeff;\n                edge_bc[eid] += coeff; // each direction once\n            }\n        }\n    }\n\n    // ---------- parameters ----------\n    double total_bc = 0.0;\n    for (double x : edge_bc) total_bc += x;\n    double avg_bc = total_bc / M;\n    const double LAMBDA = avg_bc * 0.5;          // adjacency penalty weight\n    const double NOISE_EPS = avg_bc * 1e-6;      // random perturbation amplitude\n\n    // ---------- random engine ----------\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n\n    // ---------- best schedule ----------\n    vector<int> best_day_of_edge;\n    double best_metric = numeric_limits<double>::infinity();\n\n    // time control\n    auto start_all = chrono::steady_clock::now();\n    const double TIME_LIMIT = 5.8; // seconds for the whole algorithm (betweenness already done)\n\n    while (chrono::duration<double>(chrono::steady_clock::now() - start_all).count() < TIME_LIMIT) {\n        // ---- create random order (betweenness + tiny noise) ----\n        vector<double> key(M);\n        for (int i = 0; i < M; ++i) key[i] = edge_bc[i] + std::uniform_real_distribution<double>(-NOISE_EPS, NOISE_EPS)(rng);\n        vector<int> order(M);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) { return key[a] > key[b]; });\n\n        // ---- greedy assignment ----\n        vector<int> day_of_edge(M, -1);\n        vector<double> day_sum(D, 0.0);\n        vector<int> day_cnt(D, 0);\n        vector<vector<int>> inc_cnt(D, vector<int>(N, 0));\n        vector<long long> penalty_adj(D, 0);               // \u03a3_v C(cnt,2)\n        vector<vector<int>> edges_of_day(D);\n\n        for (int eid : order) {\n            const Edge &e = edges[eid];\n            int u = e.u, v = e.v;\n            int best_day = -1;\n            double best_score = numeric_limits<double>::infinity();\n\n            for (int d = 0; d < D; ++d) {\n                if (day_cnt[d] >= K) continue;\n                double new_sum = day_sum[d] + edge_bc[eid];\n                long long new_pen = penalty_adj[d] + inc_cnt[d][u] + inc_cnt[d][v];\n                double score = new_sum + LAMBDA * new_pen;\n                if (score < best_score) {\n                    best_score = score;\n                    best_day = d;\n                }\n            }\n\n            // assign\n            day_of_edge[eid] = best_day;\n            day_sum[best_day] += edge_bc[eid];\n            ++day_cnt[best_day];\n            edges_of_day[best_day].push_back(eid);\n            penalty_adj[best_day] += inc_cnt[best_day][u] + inc_cnt[best_day][v];\n            ++inc_cnt[best_day][u];\n            ++inc_cnt[best_day][v];\n        }\n\n        // ---- local improvement (move & swap) ----\n        auto start_local = chrono::steady_clock::now();\n        const double LOCAL_TIME = 0.35; // seconds per attempt\n        while (chrono::duration<double>(chrono::steady_clock::now() - start_local).count() < LOCAL_TIME) {\n            // compute current day scores\n            vector<double> day_score(D);\n            double cur_max = -1e100, cur_min = 1e100;\n            int day_max = -1, day_min = -1;\n            for (int d = 0; d < D; ++d) {\n                day_score[d] = day_sum[d] + LAMBDA * penalty_adj[d];\n                if (day_score[d] > cur_max) { cur_max = day_score[d]; day_max = d; }\n                if (day_score[d] < cur_min) { cur_min = day_score[d]; day_min = d; }\n            }\n\n            bool improved = false;\n\n            // ----- try moving a random edge from the most loaded day -----\n            if (!edges_of_day[day_max].empty()) {\n                int idx = std::uniform_int_distribution<int>(0, (int)edges_of_day[day_max].size() - 1)(rng);\n                int eid = edges_of_day[day_max][idx];\n                const Edge &e = edges[eid];\n                int u = e.u, v = e.v;\n\n                // collect candidate target days (different from day_max, with free capacity)\n                vector<int> candidates;\n                for (int d = 0; d < D; ++d) if (d != day_max && day_cnt[d] < K) candidates.push_back(d);\n                if (!candidates.empty()) {\n                    int target = candidates[std::uniform_int_distribution<int>(0, (int)candidates.size() - 1)(rng)];\n\n                    // scores after moving\n                    double new_sum_a = day_sum[day_max] - edge_bc[eid];\n                    long long new_pen_a = penalty_adj[day_max] - (inc_cnt[day_max][u] - 1) - (inc_cnt[day_max][v] - 1);\n                    double new_score_a = new_sum_a + LAMBDA * new_pen_a;\n\n                    double new_sum_b = day_sum[target] + edge_bc[eid];\n                    long long new_pen_b = penalty_adj[target] + inc_cnt[target][u] + inc_cnt[target][v];\n                    double new_score_b = new_sum_b + LAMBDA * new_pen_b;\n\n                    double new_max = max({new_score_a, new_score_b});\n                    for (int d = 0; d < D; ++d) {\n                        if (d == day_max || d == target) continue;\n                        new_max = max(new_max, day_score[d]);\n                    }\n\n                    if (new_max + 1e-9 < cur_max) {\n                        // perform move\n                        // erase from day_max (swap\u2011pop)\n                        auto &vec_max = edges_of_day[day_max];\n                        vec_max[idx] = vec_max.back();\n                        vec_max.pop_back();\n\n                        edges_of_day[target].push_back(eid);\n                        day_of_edge[eid] = target;\n\n                        // update structures\n                        day_sum[day_max] = new_sum_a;\n                        day_sum[target] = new_sum_b;\n                        penalty_adj[day_max] = new_pen_a;\n                        penalty_adj[target] = new_pen_b;\n                        --day_cnt[day_max];\n                        ++day_cnt[target];\n                        --inc_cnt[day_max][u];\n                        --inc_cnt[day_max][v];\n                        ++inc_cnt[target][u];\n                        ++inc_cnt[target][v];\n\n                        improved = true;\n                    }\n                }\n            }\n\n            if (improved) continue; // restart loop with updated scores\n\n            // ----- try swapping two random edges from two different days -----\n            // pick two distinct days that both contain at least one edge\n            vector<int> nonempty;\n            for (int d = 0; d < D; ++d) if (!edges_of_day[d].empty()) nonempty.push_back(d);\n            if (nonempty.size() < 2) break;\n            int a = nonempty[std::uniform_int_distribution<int>(0, (int)nonempty.size() - 1)(rng)];\n            int b = a;\n            while (b == a) b = nonempty[std::uniform_int_distribution<int>(0, (int)nonempty.size() - 1)(rng)];\n\n            int idx1 = std::uniform_int_distribution<int>(0, (int)edges_of_day[a].size() - 1)(rng);\n            int idx2 = std::uniform_int_distribution<int>(0, (int)edges_of_day[b].size() - 1)(rng);\n            int e1 = edges_of_day[a][idx1];\n            int e2 = edges_of_day[b][idx2];\n            const Edge &E1 = edges[e1];\n            const Edge &E2 = edges[e2];\n\n            // compute new scores after swap (incremental)\n            double new_sum_a = day_sum[a] - edge_bc[e1] + edge_bc[e2];\n            long long new_pen_a = penalty_adj[a]\n                - (inc_cnt[a][E1.u] - 1) - (inc_cnt[a][E1.v] - 1)\n                + (inc_cnt[a][E2.u]) + (inc_cnt[a][E2.v]);\n\n            double new_sum_b = day_sum[b] - edge_bc[e2] + edge_bc[e1];\n            long long new_pen_b = penalty_adj[b]\n                - (inc_cnt[b][E2.u] - 1) - (inc_cnt[b][E2.v] - 1)\n                + (inc_cnt[b][E1.u]) + (inc_cnt[b][E1.v]);\n\n            double new_score_a = new_sum_a + LAMBDA * new_pen_a;\n            double new_score_b = new_sum_b + LAMBDA * new_pen_b;\n\n            double new_max = max({new_score_a, new_score_b});\n            for (int d = 0; d < D; ++d) {\n                if (d == a || d == b) continue;\n                new_max = max(new_max, day_score[d]);\n            }\n\n            if (new_max + 1e-9 < cur_max) {\n                // keep swap\n                // update vectors\n                edges_of_day[a][idx1] = e2;\n                edges_of_day[b][idx2] = e1;\n                day_of_edge[e1] = b;\n                day_of_edge[e2] = a;\n\n                // update inc_cnt\n                // remove E1 from a, add E2 to a\n                --inc_cnt[a][E1.u];\n                --inc_cnt[a][E1.v];\n                ++inc_cnt[a][E2.u];\n                ++inc_cnt[a][E2.v];\n                // remove E2 from b, add E1 to b\n                --inc_cnt[b][E2.u];\n                --inc_cnt[b][E2.v];\n                ++inc_cnt[b][E1.u];\n                ++inc_cnt[b][E1.v];\n\n                // update sums and penalties\n                day_sum[a] = new_sum_a;\n                day_sum[b] = new_sum_b;\n                penalty_adj[a] = new_pen_a;\n                penalty_adj[b] = new_pen_b;\n\n                improved = true;\n            }\n            if (!improved) break; // no improving move/swap found\n        }\n\n        // ----- evaluate this schedule -----\n        double cur_max_score = -1e100;\n        for (int d = 0; d < D; ++d) {\n            cur_max_score = max(cur_max_score, day_sum[d] + LAMBDA * penalty_adj[d]);\n        }\n        if (cur_max_score < best_metric) {\n            best_metric = cur_max_score;\n            best_day_of_edge = day_of_edge;\n        }\n    }\n\n    // ---------- output ----------\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << best_day_of_edge[i] + 1;   // convert to 1\u2011based\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Block {\n    vector<int> cells;   // indices of unit cubes\n    int len;             // number of cells (for vertical lines)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D;\n    if (!(cin >> D)) return 0;\n    const int N = D * D * D;\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n\n    auto idx = [&](int x, int y, int z) { return x * D * D + y * D + z; };\n\n    // need0 / need1 / shared\n    vector<char> need0(N, 0), need1(N, 0), shared(N, 0);\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                int id = idx(x, y, z);\n                need0[id] = (f[0][z][x] == '1') && (r[0][z][y] == '1');\n                need1[id] = (f[1][z][x] == '1') && (r[1][z][y] == '1');\n                shared[id] = need0[id] && need1[id];\n            }\n        }\n    }\n\n    // output arrays\n    vector<int> b0(N, 0), b1(N, 0);\n    int cur_id = 1;\n\n    // -------------------------------------------------------------\n    // 1) shared components (3\u2011D connectivity)\n    const int dx[6] = {1,-1,0,0,0,0};\n    const int dy[6] = {0,0,1,-1,0,0};\n    const int dz[6] = {0,0,0,0,1,-1};\n\n    vector<char> visited(N, 0);\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                int start = idx(x, y, z);\n                if (!shared[start] || visited[start]) continue;\n                // BFS for this component\n                queue<int> q;\n                vector<int> comp;\n                q.push(start);\n                visited[start] = 1;\n                while (!q.empty()) {\n                    int v = q.front(); q.pop();\n                    comp.push_back(v);\n                    int cx = v / (D * D);\n                    int cy = (v / D) % D;\n                    int cz = v % D;\n                    for (int dir = 0; dir < 6; ++dir) {\n                        int nx = cx + dx[dir];\n                        int ny = cy + dy[dir];\n                        int nz = cz + dz[dir];\n                        if (nx < 0 || nx >= D || ny < 0 || ny >= D || nz < 0 || nz >= D) continue;\n                        int nid = idx(nx, ny, nz);\n                        if (shared[nid] && !visited[nid]) {\n                            visited[nid] = 1;\n                            q.push(nid);\n                        }\n                    }\n                }\n                // assign a new block id to this component (used in both objects)\n                for (int cell : comp) {\n                    b0[cell] = cur_id;\n                    b1[cell] = cur_id;\n                }\n                ++cur_id;\n            }\n        }\n    }\n\n    // -------------------------------------------------------------\n    // 2) exclusive cells (need && !shared)\n    vector<char> excl0(N, 0), excl1(N, 0);\n    for (int i = 0; i < N; ++i) {\n        excl0[i] = need0[i] && !shared[i];\n        excl1[i] = need1[i] && !shared[i];\n    }\n\n    // 3) vertical lines for each object\n    vector<Block> lines0, lines1;\n\n    auto extract_lines = [&](const vector<char>& excl, vector<Block>& out) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                int z = 0;\n                while (z < D) {\n                    int id = idx(x, y, z);\n                    if (!excl[id]) { ++z; continue; }\n                    int start = z;\n                    while (z + 1 < D && excl[idx(x, y, z + 1)]) ++z;\n                    int end = z;\n                    Block blk;\n                    blk.len = end - start + 1;\n                    blk.cells.reserve(blk.len);\n                    for (int zz = start; zz <= end; ++zz)\n                        blk.cells.push_back(idx(x, y, zz));\n                    out.push_back(std::move(blk));\n                    ++z;\n                }\n            }\n        }\n    };\n\n    extract_lines(excl0, lines0);\n    extract_lines(excl1, lines1);\n\n    // 4) match vertical lines of equal length\n    unordered_map<int, vector<int>> map0, map1;   // length -> list of indices\n    for (int i = 0; i < (int)lines0.size(); ++i) map0[lines0[i].len].push_back(i);\n    for (int i = 0; i < (int)lines1.size(); ++i) map1[lines1[i].len].push_back(i);\n\n    vector<char> used0(lines0.size(), 0), used1(lines1.size(), 0);\n\n    for (auto &kv : map0) {\n        int len = kv.first;\n        auto it = map1.find(len);\n        if (it == map1.end()) continue;\n        vector<int> &v0 = kv.second;\n        vector<int> &v1 = it->second;\n        size_t i = 0, j = 0;\n        while (i < v0.size() && j < v1.size()) {\n            int id0 = v0[i];\n            int id1 = v1[j];\n            // shared block\n            for (int cell : lines0[id0].cells) b0[cell] = cur_id;\n            for (int cell : lines1[id1].cells) b1[cell] = cur_id;\n            used0[id0] = 1;\n            used1[id1] = 1;\n            ++cur_id;\n            ++i; ++j;\n        }\n    }\n\n    // 5) remaining exclusive lines become exclusive blocks\n    for (int i = 0; i < (int)lines0.size(); ++i) {\n        if (used0[i]) continue;\n        for (int cell : lines0[i].cells) b0[cell] = cur_id;\n        ++cur_id;\n    }\n    for (int i = 0; i < (int)lines1.size(); ++i) {\n        if (used1[i]) continue;\n        for (int cell : lines1[i].cells) b1[cell] = cur_id;\n        ++cur_id;\n    }\n\n    int n = cur_id - 1;\n    cout << n << \"\\n\";\n    // output b0\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                if (x || y || z) cout << ' ';\n                cout << b0[idx(x, y, z)];\n            }\n        }\n    }\n    cout << \"\\n\";\n    // output b1\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                if (x || y || z) cout << ' ';\n                cout << b1[idx(x, y, z)];\n            }\n        }\n    }\n    cout << \"\\n\";\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ---------- Disjoint Set Union ----------\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\n// integer ceil(sqrt(x)) for x >= 0\nint ceil_sqrt(long long x) {\n    if (x <= 0) return 0;\n    long long s = sqrt((long double)x);\n    while (s * s < x) ++s;\n    while ((s - 1) * (s - 1) >= x) --s;\n    return (int)s;\n}\n\n// ---------- Main ----------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;\n\n    vector<long long> xs(N), ys(N);\n    for (int i = 0; i < N; ++i) cin >> xs[i] >> ys[i];\n\n    struct Edge {\n        int u, v;\n        long long w;\n        int idx;\n    };\n    vector<Edge> edges(M);\n    vector<vector<int>> edgeIdx(N, vector<int>(N, -1));\n    for (int j = 0; j < M; ++j) {\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[j] = {u, v, w, j};\n        edgeIdx[u][v] = edgeIdx[v][u] = j;\n    }\n\n    vector<long long> a(K), b(K);\n    for (int k = 0; k < K; ++k) cin >> a[k] >> b[k];\n\n    // ---------- 1) resident \u2192 station squared distances ----------\n    const long long INF64 = (1LL << 60);\n    vector<vector<long long>> dist2(K, vector<long long>(N));\n    for (int k = 0; k < K; ++k) {\n        for (int i = 0; i < N; ++i) {\n            long long dx = xs[i] - a[k];\n            long long dy = ys[i] - b[k];\n            dist2[k][i] = dx * dx + dy * dy;\n        }\n    }\n\n    // ---------- 2) all\u2011pairs shortest paths (Floyd\u2011Warshall) ----------\n    vector<vector<long long>> sp(N, vector<long long>(N, INF64));\n    vector<vector<int>> nxt(N, vector<int>(N, -1));\n    for (int i = 0; i < N; ++i) {\n        sp[i][i] = 0;\n        nxt[i][i] = i;\n    }\n    for (const auto& e : edges) {\n        int u = e.u, v = e.v;\n        if (e.w < sp[u][v]) {\n            sp[u][v] = sp[v][u] = e.w;\n            nxt[u][v] = v;\n            nxt[v][u] = u;\n        }\n    }\n    for (int k = 0; k < N; ++k) {\n        for (int i = 0; i < N; ++i) if (sp[i][k] != INF64) {\n            for (int j = 0; j < N; ++j) if (sp[k][j] != INF64) {\n                long long nd = sp[i][k] + sp[k][j];\n                if (nd < sp[i][j]) {\n                    sp[i][j] = nd;\n                    nxt[i][j] = nxt[i][k];\n                }\n            }\n        }\n    }\n\n    // ---------- 3) initial assignment (nearest station) ----------\n    vector<vector<int>> residents(N);\n    vector<long long> maxDist2(N, -1);\n    for (int k = 0; k < K; ++k) {\n        long long best = INF64;\n        int bestStation = -1;\n        for (int i = 0; i < N; ++i) {\n            long long d2 = dist2[k][i];\n            if (d2 < best) {\n                best = d2;\n                bestStation = i;\n            }\n        }\n        residents[bestStation].push_back(k);\n        if (maxDist2[bestStation] < best) maxDist2[bestStation] = best;\n    }\n\n    // ---------- 4) terminals (stations with residents) + root ----------\n    const int ROOT = 0;\n    vector<int> terminals;\n    for (int i = 0; i < N; ++i) if (maxDist2[i] != -1) terminals.push_back(i);\n    if (find(terminals.begin(), terminals.end(), ROOT) == terminals.end())\n        terminals.push_back(ROOT);\n\n    // ---------- 5) MST on terminals (using shortest\u2011path distances) ----------\n    struct TermEdge {\n        int u, v;\n        long long w;\n    };\n    vector<TermEdge> termEdges;\n    for (size_t i = 0; i < terminals.size(); ++i) {\n        for (size_t j = i + 1; j < terminals.size(); ++j) {\n            int u = terminals[i], v = terminals[j];\n            termEdges.push_back({u, v, sp[u][v]});\n        }\n    }\n    sort(termEdges.begin(), termEdges.end(),\n         [](const TermEdge& a, const TermEdge& b){ return a.w < b.w; });\n    DSU dsuTerm(N);\n    vector<pair<int,int>> termMST; // pairs (u,v)\n    for (const auto& e : termEdges) {\n        if (dsuTerm.unite(e.u, e.v)) {\n            termMST.emplace_back(e.u, e.v);\n        }\n    }\n\n    // ---------- 6) turn on all edges of the shortest paths of termMST ----------\n    vector<int> B(M, 0);   // edge ON/OFF\n    for (auto [u, v] : termMST) {\n        int cur = u;\n        while (cur != v) {\n            int nxtNode = nxt[cur][v];\n            int idx = edgeIdx[cur][nxtNode];\n            B[idx] = 1;\n            cur = nxtNode;\n        }\n    }\n\n    // ---------- 7) reduce to a tree (MST of the obtained subgraph) ----------\n    vector<Edge> subEdges;\n    for (int j = 0; j < M; ++j) if (B[j]) subEdges.push_back(edges[j]);\n    sort(subEdges.begin(), subEdges.end(),\n         [](const Edge& a, const Edge& b){ return a.w < b.w; });\n    DSU dsuSub(N);\n    vector<int> Btree(M, 0);\n    for (const auto& e : subEdges) {\n        if (dsuSub.unite(e.u, e.v)) {\n            Btree[e.idx] = 1;\n        }\n    }\n    B.swap(Btree);   // now B holds a tree connecting all terminals\n\n    // ---------- 8) leaf pruning loop ----------\n    while (true) {\n        // build adjacency of current tree\n        vector<vector<pair<int,int>>> adj(N);\n        for (int j = 0; j < M; ++j) if (B[j]) {\n            int u = edges[j].u, v = edges[j].v;\n            adj[u].push_back({v, j});\n            adj[v].push_back({u, j});\n        }\n\n        // degree and parent (BFS from root)\n        vector<int> degree(N, 0);\n        for (int i = 0; i < N; ++i) degree[i] = (int)adj[i].size();\n        vector<int> parent(N, -1), parentEdge(N, -1);\n        queue<int> q;\n        q.push(ROOT);\n        parent[ROOT] = ROOT;\n        while (!q.empty()) {\n            int v = q.front(); q.pop();\n            for (auto [to, idx] : adj[v]) {\n                if (parent[to] != -1) continue;\n                parent[to] = v;\n                parentEdge[to] = idx;\n                q.push(to);\n            }\n        }\n\n        // ----- re\u2011assign residents to the nearest *present* station -----\n        for (int i = 0; i < N; ++i) {\n            residents[i].clear();\n            maxDist2[i] = -1;\n        }\n        for (int k = 0; k < K; ++k) {\n            long long best = INF64;\n            int bestStation = -1;\n            for (int i = 0; i < N; ++i) {\n                if (i != ROOT && degree[i] == 0) continue; // not in the tree\n                long long d2 = dist2[k][i];\n                if (d2 < best) {\n                    best = d2;\n                    bestStation = i;\n                }\n            }\n            residents[bestStation].push_back(k);\n            if (maxDist2[bestStation] < best) maxDist2[bestStation] = best;\n        }\n\n        // ----- radii -----\n        vector<int> P(N, 0);\n        vector<char> active(N, 0);\n        for (int i = 0; i < N; ++i) {\n            if (maxDist2[i] == -1) {\n                P[i] = 0;\n                active[i] = 0;\n            } else {\n                P[i] = ceil_sqrt(maxDist2[i]);\n                active[i] = 1;\n            }\n        }\n\n        // ----- try to delete one leaf -----\n        bool removed = false;\n        for (int i = 0; i < N; ++i) {\n            if (i == ROOT) continue;\n            if (degree[i] != 1) continue;          // not a leaf\n            int p = parent[i];\n            // compute new maximal distance for parent after receiving i's residents\n            long long newMax = maxDist2[p];\n            if (newMax == -1) newMax = 0;\n            for (int r : residents[i]) {\n                long long d2 = dist2[r][p];\n                if (d2 > newMax) newMax = d2;\n            }\n            int newP = ceil_sqrt(newMax);\n\n            long long cost_before = (active[i] ? (long long)P[i] * P[i] : 0LL)\n                                   + (long long)P[p] * P[p]\n                                   + edges[parentEdge[i]].w;\n            long long cost_after  = (long long)newP * newP;\n\n            if (cost_after < cost_before) {\n                // perform removal\n                B[parentEdge[i]] = 0;\n                // move residents to the parent\n                residents[p].insert(residents[p].end(),\n                                    residents[i].begin(),\n                                    residents[i].end());\n                removed = true;\n                break;          // restart the whole loop\n            }\n        }\n\n        if (!removed) break;   // no improvement possible\n    }\n\n    // ---------- 9) final radii (already computed in the last loop) ----------\n    // recompute one last time to be safe\n    vector<vector<pair<int,int>>> finalAdj(N);\n    for (int j = 0; j < M; ++j) if (B[j]) {\n        int u = edges[j].u, v = edges[j].v;\n        finalAdj[u].push_back({v, j});\n        finalAdj[v].push_back({u, j});\n    }\n    vector<int> finalDeg(N, 0);\n    for (int i = 0; i < N; ++i) finalDeg[i] = (int)finalAdj[i].size();\n\n    // assignment once more\n    for (int i = 0; i < N; ++i) {\n        residents[i].clear();\n        maxDist2[i] = -1;\n    }\n    for (int k = 0; k < K; ++k) {\n        long long best = INF64;\n        int bestStation = -1;\n        for (int i = 0; i < N; ++i) {\n            if (i != ROOT && finalDeg[i] == 0) continue;\n            long long d2 = dist2[k][i];\n            if (d2 < best) {\n                best = d2;\n                bestStation = i;\n            }\n        }\n        residents[bestStation].push_back(k);\n        if (maxDist2[bestStation] < best) maxDist2[bestStation] = best;\n    }\n    vector<int> P(N, 0);\n    for (int i = 0; i < N; ++i) {\n        if (maxDist2[i] == -1) P[i] = 0;\n        else P[i] = ceil_sqrt(maxDist2[i]);\n    }\n\n    // ---------- 10) output ----------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << P[i];\n    }\n    cout << '\\n';\n    for (int j = 0; j < M; ++j) {\n        if (j) cout << ' ';\n        cout << B[j];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 30;                     // fixed by the statement\n    int a[N][N];                          // a[x][y] , 0 <= y <= x\n\n    // read the triangular input\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            cin >> a[x][y];\n        }\n    }\n\n    vector<Op> ops;\n    ops.reserve(10000);\n\n    // bottom\u2011up heapify (min\u2011heap) using only the two down\u2011edges\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            int cx = x, cy = y;\n            while (cx < N - 1) {                     // while a child exists\n                int bestX = cx, bestY = cy;\n                // down\u2011left child (cx+1 , cy)\n                if (a[bestX][bestY] > a[cx + 1][cy]) {\n                    bestX = cx + 1;\n                    bestY = cy;\n                }\n                // down\u2011right child (cx+1 , cy+1)\n                if (a[bestX][bestY] > a[cx + 1][cy + 1]) {\n                    bestX = cx + 1;\n                    bestY = cy + 1;\n                }\n                if (bestX == cx && bestY == cy) break;   // heap property satisfied\n                swap(a[cx][cy], a[bestX][bestY]);\n                ops.push_back({cx, cy, bestX, bestY});\n                cx = bestX;\n                cy = bestY;\n                // safety: the problem guarantees K <= 10000, but we keep the bound\n                if (ops.size() > 10000) break;\n            }\n            if (ops.size() > 10000) break;\n        }\n        if (ops.size() > 10000) break;\n    }\n\n    // output\n    cout << ops.size() << '\\n';\n    for (const auto &op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' '\n             << op.x2 << ' ' << op.y2 << '\\n';\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- transport phase helper ---------- */\nstruct HeapNode {\n    int number;   // container number\n    int id;       // vertex id\n    bool operator<(HeapNode const& other) const {\n        // priority_queue is a max\u2011heap \u2192 reverse for a min\u2011heap\n        return number > other.number;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    /* ----- input (D is always 9, but read it normally) ----- */\n    int D, N;\n    if (!(cin >> D >> N)) return 0;\n    const int entrance_i = 0;\n    const int entrance_j = (D - 1) / 2;          // (0,4)\n\n    vector<vector<bool>> obstacle(D, vector<bool>(D, false));\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        obstacle[ri][rj] = true;\n    }\n\n    /* ----- BFS \u2013 build the tree ----- */\n    vector<vector<int>> id(D, vector<int>(D, -1));\n    vector<pair<int,int>> coord;   // id \u2192 (i,j)\n    vector<int> depth;             // BFS distance\n    vector<int> parent;            // parent id, -1 for entrance\n\n    queue<pair<int,int>> q;\n    int curId = 0;\n    id[entrance_i][entrance_j] = curId++;\n    coord.emplace_back(entrance_i, entrance_j);\n    depth.push_back(0);\n    parent.push_back(-1);\n    q.emplace(entrance_i, entrance_j);\n\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        int cur = id[i][j];\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= D || nj < 0 || nj >= D) continue;\n            if (obstacle[ni][nj]) continue;\n            if (id[ni][nj] != -1) continue;\n            id[ni][nj] = curId++;\n            coord.emplace_back(ni, nj);\n            depth.push_back(depth[cur] + 1);\n            parent.push_back(cur);\n            q.emplace(ni, nj);\n        }\n    }\n\n    const int totalCells = curId;          // includes entrance\n    const int entranceId = 0;\n    const int M = totalCells - 1;          // number of containers\n    const int maxNumber = M - 1;           // largest possible container number\n\n    /* ----- children list and remaining\u2011children counter ----- */\n    vector<vector<int>> children(totalCells);\n    vector<int> remainingChildren(totalCells, 0);\n    for (int v = 1; v < totalCells; ++v) {\n        int p = parent[v];\n        children[p].push_back(v);\n        ++remainingChildren[p];\n    }\n\n    /* ----- leaf structures (by depth) ----- */\n    int maxDepth = 0;\n    for (int d : depth) maxDepth = max(maxDepth, d);\n    vector<set<int>> leavesByDepth(maxDepth + 1);\n    int leafCount = 0;\n    for (int v = 1; v < totalCells; ++v) {\n        if (remainingChildren[v] == 0) {\n            leavesByDepth[ depth[v] ].insert(v);\n            ++leafCount;\n        }\n    }\n\n    /* ----- placement phase ----- */\n    vector<int> containerNumber(totalCells, -1);   // number assigned to each cell\n    for (int step = 0; step < M; ++step) {\n        int t;               // number of the arriving container\n        cin >> t;\n\n        // rank of t among the remaining numbers (0\u2011based)\n        // target rank among current leaves\n        long long targetRank = (static_cast<long long>(t) * leafCount) / M;\n\n        // find depth whose cumulative leaf count exceeds targetRank\n        int cum = 0, chosenDepth = -1;\n        for (int d = 0; d <= maxDepth; ++d) {\n            cum += static_cast<int>(leavesByDepth[d].size());\n            if (cum > targetRank) {\n                chosenDepth = d;\n                break;\n            }\n        }\n        // safety: should always find a depth\n        if (chosenDepth == -1) chosenDepth = maxDepth;\n\n        // pick any leaf of that depth (smallest id)\n        int v = *leavesByDepth[chosenDepth].begin();\n        leavesByDepth[chosenDepth].erase(leavesByDepth[chosenDepth].begin());\n        --leafCount;\n\n        containerNumber[v] = t;\n        cout << coord[v].first << ' ' << coord[v].second << \"\\n\";\n        cout.flush();   // required after each placement\n\n        // update parent \u2013 it may become a leaf now\n        int p = parent[v];\n        if (p != -1 && p != entranceId) {\n            if (--remainingChildren[p] == 0) {\n                leavesByDepth[ depth[p] ].insert(p);\n                ++leafCount;\n            }\n        }\n    }\n\n    /* ----- transport phase ----- */\n    priority_queue<HeapNode> pq;\n    for (int c : children[entranceId]) {\n        pq.push({containerNumber[c], c});\n    }\n\n    while (!pq.empty()) {\n        auto cur = pq.top(); pq.pop();\n        int v = cur.id;\n        cout << coord[v].first << ' ' << coord[v].second << \"\\n\";\n        for (int c : children[v]) {\n            pq.push({containerNumber[c], c});\n        }\n    }\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    vector<vector<int>> a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (j) cout << ' ';\n            cout << a[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n    vector<long long> w(N);\n    for (int i = 0; i < N; ++i) cin >> w[i];\n\n    long long total = 0;\n    for (auto x : w) total += x;\n    double target = static_cast<double>(total) / D;\n\n    // random generator\n    std::mt19937_64 rng(\n        chrono::steady_clock::now().time_since_epoch().count());\n\n    vector<int> bestAssign(N);\n    double bestScore = numeric_limits<double>::infinity();\n\n    auto computeScore = [&](const vector<long long> &sum) -> double {\n        double sc = 0.0;\n        for (int d = 0; d < D; ++d) {\n            double diff = static_cast<double>(sum[d]) - target;\n            sc += diff * diff;\n        }\n        return sc;\n    };\n\n    // time limit handling\n    const double TIME_LIMIT = 1.8;                // seconds\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        // ----- 1) random order for greedy -----\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) {\n                 if (w[a] != w[b]) return w[a] > w[b];\n                 return (rng() & 1ULL);\n             });\n\n        // ----- 2) greedy assignment -----\n        vector<int> assign(N, -1);\n        vector<long long> sum(D, 0);\n        for (int idx : order) {\n            int bestSet = 0;\n            long long minSum = sum[0];\n            for (int d = 1; d < D; ++d) {\n                if (sum[d] < minSum) {\n                    minSum = sum[d];\n                    bestSet = d;\n                }\n            }\n            assign[idx] = bestSet;\n            sum[bestSet] += w[idx];\n        }\n\n        // ----- 3) local improvement (hill climbing) -----\n        bool improved = true;\n        while (improved) {\n            improved = false;\n\n            // try moving a single item\n            for (int i = 0; i < N && !improved; ++i) {\n                int a = assign[i];\n                long long wi = w[i];\n                double curDiffA = static_cast<double>(sum[a]) - target;\n                for (int b = 0; b < D; ++b) {\n                    if (b == a) continue;\n                    double curDiffB = static_cast<double>(sum[b]) - target;\n                    double newDiffA = static_cast<double>(sum[a] - wi) - target;\n                    double newDiffB = static_cast<double>(sum[b] + wi) - target;\n                    double delta = (newDiffA * newDiffA + newDiffB * newDiffB) -\n                                   (curDiffA * curDiffA + curDiffB * curDiffB);\n                    if (delta < -1e-9) {\n                        // perform move\n                        sum[a] -= wi;\n                        sum[b] += wi;\n                        assign[i] = b;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n\n            if (improved) continue;\n\n            // try swapping two items\n            for (int i = 0; i < N && !improved; ++i) {\n                int a = assign[i];\n                long long wi = w[i];\n                for (int j = i + 1; j < N; ++j) {\n                    int b = assign[j];\n                    if (a == b) continue;\n                    long long wj = w[j];\n                    double curDiffA = static_cast<double>(sum[a]) - target;\n                    double curDiffB = static_cast<double>(sum[b]) - target;\n                    double newDiffA = static_cast<double>(sum[a] - wi + wj) - target;\n                    double newDiffB = static_cast<double>(sum[b] - wj + wi) - target;\n                    double delta = (newDiffA * newDiffA + newDiffB * newDiffB) -\n                                   (curDiffA * curDiffA + curDiffB * curDiffB);\n                    if (delta < -1e-9) {\n                        // perform swap\n                        sum[a] = sum[a] - wi + wj;\n                        sum[b] = sum[b] - wj + wi;\n                        assign[i] = b;\n                        assign[j] = a;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n        }\n\n        // ----- 4) evaluate -----\n        double curScore = computeScore(sum);\n        if (curScore < bestScore) {\n            bestScore = curScore;\n            bestAssign = assign;\n        }\n\n        // ----- 5) time check -----\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n    }\n\n    // ----- 6) output best assignment -----\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << bestAssign[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    const int per = n / m;                 // = 20 for the given data\n    vector<vector<int>> st(m);             // bottom \u2192 top\n    vector<int> pos(n + 1, -1);            // current stack of each box\n\n    for (int i = 0; i < m; ++i) {\n        st[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x; cin >> x;\n            st[i].push_back(x);\n            pos[x] = i;\n        }\n    }\n\n    vector<pair<int,int>> ops;             // (v , i)   i = 0 \u2192 removal\n\n    // helper: choose a destination for the top box w of stack src\n    auto choose_dest = [&](int w, int src) -> int {\n        // 1) empty stack\n        for (int i = 0; i < m; ++i) if (i != src && st[i].empty())\n            return i;\n        // 2) stack whose top is larger than w (pick the smallest such top)\n        int best = -1, bestTop = INT_MAX;\n        for (int i = 0; i < m; ++i) if (i != src && !st[i].empty() && st[i].back() > w) {\n            if (st[i].back() < bestTop) {\n                bestTop = st[i].back();\n                best = i;\n            }\n        }\n        if (best != -1) return best;\n        // 3) fallback \u2013 any other stack, choose the one with smallest size\n        int minSize = INT_MAX;\n        for (int i = 0; i < m; ++i) if (i != src) {\n            if ((int)st[i].size() < minSize) {\n                minSize = (int)st[i].size();\n                best = i;\n            }\n        }\n        return best;   // always exists because m \u2265 2\n    };\n\n    for (int v = 1; v <= n; ++v) {\n        int s = pos[v];                     // stack that currently holds v\n        // bring v to the top\n        while (!st[s].empty() && st[s].back() != v) {\n            int w = st[s].back();           // top box, w > v\n            int d = choose_dest(w, s);\n            // perform the move\n            st[s].pop_back();\n            st[d].push_back(w);\n            pos[w] = d;\n            ops.emplace_back(w, d + 1);     // +1 because stacks are 1\u2011indexed in output\n        }\n        // now v is on the top \u2192 remove it\n        ops.emplace_back(v, 0);\n        st[s].pop_back();\n        pos[v] = -1;\n    }\n\n    // safety check (the problem guarantees 5000 is enough)\n    assert(ops.size() <= 5000);\n\n    for (auto [v, i] : ops) {\n        cout << v << ' ' << i << '\\n';\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> h;                 // (N\u20111) \u00d7 N  : vertical walls\nvector<string> v;                 // N \u00d7 (N\u20111)  : horizontal walls\nvector<vector<int>> d;            // dirt susceptibility\n\n// direction helpers\nconst int dr[4] = {0, 1, 0, -1};\nconst int dc[4] = {1, 0, -1, 0};\nconst char dirChar[4] = {'R', 'D', 'L', 'U'};\n\nchar opposite(char c) {\n    switch (c) {\n        case 'R': return 'L';\n        case 'L': return 'R';\n        case 'U': return 'D';\n        case 'D': return 'U';\n    }\n    return '?';\n}\n\n// true iff we can move from (r,c) to neighbour in direction dir\nbool canMove(int r, int c, int dir) {\n    int nr = r + dr[dir];\n    int nc = c + dc[dir];\n    if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n    if (dir == 0) {               // R\n        return v[r][c] == '0';\n    } else if (dir == 2) {        // L\n        return v[r][c - 1] == '0';\n    } else if (dir == 1) {        // D\n        return h[r][c] == '0';\n    } else {                      // U\n        return h[r - 1][c] == '0';\n    }\n}\n\n/* ----------  BFS : shortest\u2011path tree from (0,0) ---------- */\nvector<vector<int>> dist;\nvector<vector<pair<int,int>>> parent;\nvector<vector<char>> dirFromParent;\n\nvoid bfs() {\n    dist.assign(N, vector<int>(N, -1));\n    parent.assign(N, vector<pair<int,int>>(N, {-1,-1}));\n    dirFromParent.assign(N, vector<char>(N, 0));\n    queue<pair<int,int>> q;\n    dist[0][0] = 0;\n    q.emplace(0,0);\n    while (!q.empty()) {\n        auto [r,c] = q.front(); q.pop();\n        for (int dir = 0; dir < 4; ++dir) {\n            if (!canMove(r,c,dir)) continue;\n            int nr = r + dr[dir];\n            int nc = c + dc[dir];\n            if (dist[nr][nc] != -1) continue;\n            dist[nr][nc] = dist[r][c] + 1;\n            parent[nr][nc] = {r,c};\n            dirFromParent[nr][nc] = dirChar[dir];\n            q.emplace(nr,nc);\n        }\n    }\n}\n\n/* ----------  DFS : base tour that visits every cell once ---------- */\nvector<vector<char>> visited;\nstring answer; // final route\n\nvoid dfs(int r, int c) {\n    visited[r][c] = 1;\n    for (int dir = 0; dir < 4; ++dir) {\n        if (!canMove(r,c,dir)) continue;\n        int nr = r + dr[dir];\n        int nc = c + dc[dir];\n        if (!visited[nr][nc]) {\n            answer.push_back(dirChar[dir]); // go forward\n            dfs(nr,nc);\n            answer.push_back(dirChar[(dir+2)%4]); // go back\n        }\n    }\n}\n\n/* ----------  forward path from (0,0) to (i,j) ---------- */\nstring getForwardPath(int i, int j) {\n    string rev;\n    while (!(i==0 && j==0)) {\n        char c = dirFromParent[i][j];\n        rev.push_back(c);\n        int dirIdx = -1;\n        if (c == 'R') dirIdx = 0;\n        else if (c == 'D') dirIdx = 1;\n        else if (c == 'L') dirIdx = 2;\n        else if (c == 'U') dirIdx = 3;\n        i -= dr[dirIdx];\n        j -= dc[dirIdx];\n    }\n    reverse(rev.begin(), rev.end());\n    return rev;\n}\n\n/* ----------  main ---------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N)) return 0;\n    h.resize(N-1);\n    for (int i = 0; i < N-1; ++i) cin >> h[i];\n    v.resize(N);\n    for (int i = 0; i < N; ++i) cin >> v[i];\n    d.assign(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> d[i][j];\n\n    const int MAXLEN = 100000;\n    answer.reserve(MAXLEN);\n\n    /* 1. BFS for shortest paths */\n    bfs();\n\n    /* 2. DFS base tour */\n    visited.assign(N, vector<char>(N, 0));\n    dfs(0,0);\n    int L0 = (int)answer.size();\n\n    /* 3. total dirtiness */\n    long long Dall = 0;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            Dall += d[i][j];\n\n    /* ----------  candidate loops ---------- */\n    struct Cand {\n        int type;          // 0 = none, 1 = edge, 2 = block\n        int i, j;          // for edge: endpoint (i,j); for block: top\u2011left\n        char dir;          // direction from endpoint to neighbour (edge only)\n        int travel;        // distance from start to chosen endpoint\n        int C;             // cost per repetition (2 or 4)\n        long long Dsum;    // sum of d in the loop\n        int t;             // repetitions to use\n    };\n    Cand best{0, -1,-1,0,0,0,0,0};\n    long double bestScore = numeric_limits<long double>::infinity();\n\n    auto evaluate = [&](int type, int i, int j, char dir,\n                        int travel, int C, long long Dsum) {\n        int a = L0 + 2 * travel;\n        long long B = Dall - Dsum;\n        if (B <= 0) return;               // degenerate\n        int tmax = (MAXLEN - a) / C;\n        if (tmax < 0) return;\n        // analytical optimum (real)\n        long double t_real = sqrt( (long double)Dsum *\n                                   ( (long double)a - (long double)C ) /\n                                   ( (long double)C * (long double)B ) ) - 1.0L;\n        long long t0 = (long long)floor(t_real);\n        if (t0 < 0) t0 = 0;\n        if (t0 > tmax) t0 = tmax;\n\n        auto score = [&](long long t)->long double{\n            long double L = (long double)a + (long double)C * t;\n            long double S = (long double)B + (long double)Dsum / (1.0L + t);\n            return L * S;\n        };\n        // test t0, t0+1, and 0\n        vector<long long> candT = {t0};\n        if (t0 + 1 <= tmax) candT.push_back(t0 + 1);\n        candT.push_back(0);\n        for (long long t : candT) {\n            long double sc = score(t);\n            if (sc < bestScore) {\n                bestScore = sc;\n                best = {type, i, j, dir, travel, C, Dsum, (int)t};\n            }\n        }\n    };\n\n    /* ----- edges ----- */\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            // down edge\n            if (i + 1 < N && h[i][j] == '0') {\n                long long Dsum = (long long)d[i][j] + d[i+1][j];\n                int travel = min(dist[i][j], dist[i+1][j]);\n                char dir = (dist[i][j] <= dist[i+1][j]) ? 'D' : 'U';\n                evaluate(1, i, j, dir, travel, 2, Dsum);\n            }\n            // right edge\n            if (j + 1 < N && v[i][j] == '0') {\n                long long Dsum = (long long)d[i][j] + d[i][j+1];\n                int travel = min(dist[i][j], dist[i][j+1]);\n                char dir = (dist[i][j] <= dist[i][j+1]) ? 'R' : 'L';\n                evaluate(1, i, j, dir, travel, 2, Dsum);\n            }\n        }\n    }\n\n    /* ----- 2\u00d72 blocks ----- */\n    for (int i = 0; i + 1 < N; ++i) {\n        for (int j = 0; j + 1 < N; ++j) {\n            if (v[i][j] != '0') continue;               // (i,j)-(i,j+1)\n            if (h[i][j] != '0') continue;               // (i,j)-(i+1,j)\n            if (v[i+1][j] != '0') continue;             // (i+1,j)-(i+1,j+1)\n            if (h[i][j+1] != '0') continue;             // (i,j+1)-(i+1,j+1)\n\n            long long Dsum = (long long)d[i][j] + d[i][j+1] +\n                             d[i+1][j] + d[i+1][j+1];\n            int travel = dist[i][j];                     // top\u2011left cell\n            evaluate(2, i, j, 0, travel, 4, Dsum);\n        }\n    }\n\n    /* ---------- 6. build the final answer ---------- */\n    if (best.type != 0 && best.t > 0) {\n        // forward path to the chosen endpoint (nearest cell of the loop)\n        string forward = getForwardPath(best.i, best.j);\n        answer += forward;\n\n        if (best.type == 1) {               // edge\n            char c = best.dir;               // direction from endpoint to neighbour\n            for (int k = 0; k < best.t; ++k) {\n                answer.push_back(c);\n                answer.push_back(opposite(c));\n            }\n        } else {                            // block\n            const string loop = \"RDLU\";\n            for (int k = 0; k < best.t; ++k) answer += loop;\n        }\n\n        // reverse of forward path with opposite directions\n        for (int k = (int)forward.size() - 1; k >= 0; --k)\n            answer.push_back(opposite(forward[k]));\n    }\n\n    if ((int)answer.size() > MAXLEN) answer.resize(MAXLEN);\n    cout << answer << '\\n';\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int i, j;\n};\n\nint manhattan(const Pos& a, const Pos& b) {\n    return abs(a.i - b.i) + abs(a.j - b.j);\n}\n\n// compute the longest overlap of suffix of a and prefix of b\nint overlap(const string& a, const string& b) {\n    int maxk = min((int)a.size(), (int)b.size());\n    for (int k = maxk; k > 0; --k) {\n        bool ok = true;\n        for (int t = 0; t < k; ++t) {\n            if (a[a.size() - k + t] != b[t]) {\n                ok = false; break;\n            }\n        }\n        if (ok) return k;\n    }\n    return 0;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n    \n    // positions for each letter\n    vector<Pos> pos[26];\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = board[i][j];\n            pos[c - 'A'].push_back({i, j});\n        }\n    }\n    \n    vector<string> cur(M);\n    for (int k = 0; k < M; ++k) cin >> cur[k];\n    \n    // ---------- 1. greedy shortest common superstring ----------\n    while (cur.size() > 1) {\n        int bestOv = -1;\n        int bestI = -1, bestJ = -1;\n        string bestMerged;\n        int sz = cur.size();\n        for (int i = 0; i < sz; ++i) {\n            for (int j = 0; j < sz; ++j) if (i != j) {\n                int ov = overlap(cur[i], cur[j]);\n                if (ov > bestOv) {\n                    bestOv = ov;\n                    bestI = i;\n                    bestJ = j;\n                    bestMerged = cur[i] + cur[j].substr(ov);\n                }\n            }\n        }\n        // merge bestI and bestJ\n        if (bestI > bestJ) swap(bestI, bestJ); // erase larger index first\n        cur.erase(cur.begin() + bestJ);\n        cur.erase(cur.begin() + bestI);\n        cur.push_back(bestMerged);\n    }\n    string S = cur[0];                 // final output string\n    int L = (int)S.size();\n    \n    // ---------- 2. DP for optimal movement ----------\n    // layerPos[p] = list of cells that can type S[p]\n    vector<vector<Pos>> layerPos(L);\n    for (int p = 0; p < L; ++p) {\n        layerPos[p] = pos[S[p] - 'A'];\n    }\n    \n    const int INF = 1e9;\n    vector<vector<int>> dp(L);\n    vector<vector<int>> parent(L);\n    \n    // first layer\n    dp[0].resize(layerPos[0].size());\n    parent[0].resize(layerPos[0].size(), -1);\n    for (size_t i = 0; i < layerPos[0].size(); ++i) {\n        dp[0][i] = manhattan({si, sj}, layerPos[0][i]) + 1;\n    }\n    \n    // subsequent layers\n    for (int p = 1; p < L; ++p) {\n        const auto& prevCells = layerPos[p-1];\n        const auto& curCells  = layerPos[p];\n        dp[p].assign(curCells.size(), INF);\n        parent[p].assign(curCells.size(), -1);\n        for (size_t ci = 0; ci < curCells.size(); ++ci) {\n            int best = INF;\n            int bestPrev = -1;\n            for (size_t pj = 0; pj < prevCells.size(); ++pj) {\n                int cand = dp[p-1][pj] + manhattan(prevCells[pj], curCells[ci]) + 1;\n                if (cand < best) {\n                    best = cand;\n                    bestPrev = (int)pj;\n                }\n            }\n            dp[p][ci] = best;\n            parent[p][ci] = bestPrev;\n        }\n    }\n    \n    // find minimal cost at the last layer\n    int lastIdx = -1;\n    int bestCost = INF;\n    for (size_t i = 0; i < dp[L-1].size(); ++i) {\n        if (dp[L-1][i] < bestCost) {\n            bestCost = dp[L-1][i];\n            lastIdx = (int)i;\n        }\n    }\n    \n    // reconstruct the sequence of cells\n    vector<Pos> answer(L);\n    int curIdx = lastIdx;\n    for (int p = L-1; p >= 0; --p) {\n        answer[p] = layerPos[p][curIdx];\n        curIdx = parent[p][curIdx];\n    }\n    \n    // ---------- output ----------\n    for (const Pos& p : answer) {\n        cout << p.i << ' ' << p.j << '\\n';\n    }\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    double eps;\n    if (!(cin >> N >> M >> eps)) return 0;   // no input\n\n    // ------------------------------------------------------------\n    // 1. read the M polyomino shapes\n    struct Shape {\n        vector<pair<int,int>> cells;   // coordinates relative to (0,0)\n        int max_i = 0, max_j = 0;      // size of the bounding box\n    };\n    vector<Shape> shapes(M);\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        shapes[k].cells.resize(d);\n        for (int t = 0; t < d; ++t) {\n            int i, j;\n            cin >> i >> j;\n            shapes[k].cells[t] = {i, j};\n            shapes[k].max_i = max(shapes[k].max_i, i);\n            shapes[k].max_j = max(shapes[k].max_j, j);\n        }\n    }\n\n    // ------------------------------------------------------------\n    // 2. compute which squares can possibly be covered\n    vector<vector<char>> possible(N, vector<char>(N, 0));\n    for (const auto& sh : shapes) {\n        int height = sh.max_i + 1;\n        int width  = sh.max_j + 1;\n        for (int di = 0; di <= N - height; ++di) {\n            for (int dj = 0; dj <= N - width; ++dj) {\n                for (auto [ci, cj] : sh.cells) {\n                    possible[di + ci][dj + cj] = 1;\n                }\n            }\n        }\n    }\n\n    // ------------------------------------------------------------\n    // 3. drill all cells that may contain oil\n    vector<pair<int,int>> answer;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!possible[i][j]) continue;          // guaranteed empty\n            cout << \"q 1 \" << i << ' ' << j << '\\n';\n            cout.flush();\n            int v;\n            cin >> v;                               // exact value\n            if (v > 0) answer.emplace_back(i, j);\n        }\n    }\n\n    // ------------------------------------------------------------\n    // 4. output the final answer\n    cout << \"a \" << answer.size();\n    for (auto [i, j] : answer) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << '\\n';\n    cout.flush();\n\n    // read the final verdict (1 = correct, 0 = wrong) \u2013 not used further\n    int verdict;\n    if (cin >> verdict) {\n        // nothing to do\n    }\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int W = 1000;                     // hall size (fixed)\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int W_input, D, N;\n    if (!(cin >> W_input >> D >> N)) return 0;   // W_input is always 1000\n    // we ignore W_input because the geometry is fixed to W = 1000\n\n    vector<vector<long long>> a(D, vector<long long>(N));\n    for (int d = 0; d < D; ++d)\n        for (int k = 0; k < N; ++k)\n            cin >> a[d][k];\n\n    vector<int> curH(N, 0);                 // heights of the previous day\n\n    for (int d = 0; d < D; ++d) {\n        // ----- required heights for this day -----\n        vector<int> need(N);\n        for (int k = 0; k < N; ++k) {\n            need[k] = (int)((a[d][k] + W - 1) / W);   // ceil(a / W)\n            if (need[k] < 1) need[k] = 1;              // safety, a \u2265 1\n        }\n\n        // ----- start from previous heights, increase if necessary -----\n        vector<int> newH = curH;\n        for (int k = 0; k < N; ++k)\n            if (newH[k] < need[k]) newH[k] = need[k];\n\n        int total = 0;\n        for (int h : newH) total += h;\n\n        // ----- if we exceed the hall height, shrink surplus first -----\n        if (total > W) {\n            // surplus = height - need (non\u2011negative after the increase step)\n            priority_queue<pair<int,int>> pq;   // (surplus, index)\n            for (int k = 0; k < N; ++k) {\n                int surplus = newH[k] - need[k];\n                if (surplus > 0) pq.emplace(surplus, k);\n            }\n            while (total > W && !pq.empty()) {\n                auto [s, k] = pq.top(); pq.pop();\n                newH[k]--;                     // reduce by one row\n                total--;\n                s--;\n                if (s > 0) pq.emplace(s, k);\n            }\n            // If still too tall (possible only because \u03a3 need > W),\n            // shrink any strip that is still > 1 (incurs area penalty).\n            int idx = 0;\n            while (total > W) {\n                if (newH[idx] > 1) {\n                    newH[idx]--;\n                    total--;\n                }\n                idx = (idx + 1) % N;\n            }\n        }\n\n        curH.swap(newH);                     // store heights for the next day\n\n        // ----- output the strips for this day -----\n        int row = 0;\n        for (int k = 0; k < N; ++k) {\n            int i0 = row;\n            int i1 = row + curH[k];\n            cout << i0 << ' ' << 0 << ' '\n                 << i1 << ' ' << W << '\\n';\n            row = i1;\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr long long MOD = 998244353LL;\n\n/* -------------------------------------------------------------\n   information for a single possible stamp placement\n   ------------------------------------------------------------- */\nstruct OpInfo {\n    int m, p, q;               // stamp id and top\u2011left board position\n    int idx[9];                // flat board indices (0 \u2026 N*N-1)\n    long long add[9];          // stamp values (already % MOD)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;          // N = 9, M = 20, K = 81\n    const int maxP = N - 3;   // last top\u2011left row where a stamp fits\n    const int maxQ = N - 3;   // last top\u2011left column\n\n    // ---------- read initial board ----------\n    vector<long long> initBoard(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            long long x; cin >> x;\n            initBoard[i * N + j] = x % MOD;\n        }\n    }\n\n    // ---------- read stamps ----------\n    vector<array<long long, 9>> stampVals(M);\n    for (int m = 0; m < M; ++m) {\n        for (int u = 0; u < 3; ++u) {\n            for (int v = 0; v < 3; ++v) {\n                long long x; cin >> x;\n                stampVals[m][u * 3 + v] = x % MOD;\n            }\n        }\n    }\n\n    // ---------- pre\u2011compute all possible operations ----------\n    vector<OpInfo> ops;\n    for (int m = 0; m < M; ++m) {\n        for (int p = 0; p <= maxP; ++p) {\n            for (int q = 0; q <= maxQ; ++q) {\n                OpInfo info;\n                info.m = m; info.p = p; info.q = q;\n                int t = 0;\n                for (int u = 0; u < 3; ++u) {\n                    for (int v = 0; v < 3; ++v) {\n                        info.idx[t] = (p + u) * N + (q + v);\n                        info.add[t] = stampVals[m][u * 3 + v];\n                        ++t;\n                    }\n                }\n                ops.push_back(info);\n            }\n        }\n    }\n    const int totalOps = (int)ops.size();   // = 980\n\n    // ------------------------------------------------------------\n    // helper functions\n    // ------------------------------------------------------------\n    auto computeDelta = [&](const vector<long long> &board,\n                            const OpInfo &op) -> long long {\n        long long delta = 0;\n        for (int t = 0; t < 9; ++t) {\n            long long old = board[op.idx[t]];\n            long long newv = old + op.add[t];\n            if (newv >= MOD) newv -= MOD;\n            delta += (newv - old);\n        }\n        return delta;\n    };\n\n    // apply (+1) or remove (-1) a stamp, return the change of the total sum\n    auto applyOp = [&](vector<long long> &board,\n                       const OpInfo &op,\n                       int sign) -> long long {\n        long long delta = 0;\n        if (sign == +1) {\n            for (int t = 0; t < 9; ++t) {\n                int idx = op.idx[t];\n                long long old = board[idx];\n                long long newv = old + op.add[t];\n                if (newv >= MOD) newv -= MOD;\n                board[idx] = newv;\n                delta += (newv - old);\n            }\n        } else { // sign == -1\n            for (int t = 0; t < 9; ++t) {\n                int idx = op.idx[t];\n                long long old = board[idx];\n                long long newv = old - op.add[t];\n                if (newv < 0) newv += MOD;\n                board[idx] = newv;\n                delta += (newv - old);\n            }\n        }\n        return delta;\n    };\n\n    // greedy fill from a given board, returns list of operation ids\n    auto greedyFill = [&](vector<long long> &board) -> vector<int> {\n        vector<int> chosen;\n        while ((int)chosen.size() < K) {\n            long long bestDelta = LLONG_MIN;\n            int bestId = -1;\n            for (int id = 0; id < totalOps; ++id) {\n                long long d = computeDelta(board, ops[id]);\n                if (d > bestDelta) {\n                    bestDelta = d;\n                    bestId = id;\n                }\n            }\n            if (bestDelta <= 0) break;\n            applyOp(board, ops[bestId], +1);\n            chosen.push_back(bestId);\n        }\n        return chosen;\n    };\n\n    // ------------------------------------------------------------\n    // initial greedy solution\n    // ------------------------------------------------------------\n    vector<long long> board = initBoard;\n    vector<int> bestOps = greedyFill(board);\n    long long bestScore = 0;\n    for (long long v : board) bestScore += v;\n\n    // ------------------------------------------------------------\n    // hill\u2011climbing loop (time\u2011bounded)\n    // ------------------------------------------------------------\n    std::mt19937_64 rng(\n        (uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_real_distribution<double> distReal(0.0, 1.0);\n    const double TIME_LIMIT = 1.9;          // seconds\n    auto startTime = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        // start from the current best solution\n        vector<int> curOps = bestOps;\n        vector<long long> curBoard = initBoard;\n        for (int id : curOps) applyOp(curBoard, ops[id], +1);\n\n        int sz = (int)curOps.size();\n        int moveType = rng() % 3;   // 0 = insert, 1 = delete, 2 = replace\n\n        // ----- INSERT -------------------------------------------------\n        if (moveType == 0 && sz < K) {\n            int pos = rng() % (sz + 1);                 // insertion position\n            int newId = rng() % totalOps;\n            curOps.insert(curOps.begin() + pos, newId);\n            applyOp(curBoard, ops[newId], +1);\n        }\n        // ----- DELETE -------------------------------------------------\n        else if (moveType == 1 && sz > 0) {\n            int pos = rng() % sz;\n            int delId = curOps[pos];\n            applyOp(curBoard, ops[delId], -1);\n            curOps.erase(curOps.begin() + pos);\n        }\n        // ----- REPLACE ------------------------------------------------\n        else if (moveType == 2 && sz > 0) {\n            int pos = rng() % sz;\n            int oldId = curOps[pos];\n            int newId = rng() % totalOps;\n            applyOp(curBoard, ops[oldId], -1);\n            applyOp(curBoard, ops[newId], +1);\n            curOps[pos] = newId;\n        }\n        // if the chosen move was illegal (e.g. insert when size==K) we simply\n        // skip it \u2013 the loop will try another random move next time.\n\n        // ----- greedy completion after the modification -------------\n        while ((int)curOps.size() < K) {\n            long long bestDelta = LLONG_MIN;\n            int bestId = -1;\n            for (int id = 0; id < totalOps; ++id) {\n                long long d = computeDelta(curBoard, ops[id]);\n                if (d > bestDelta) {\n                    bestDelta = d;\n                    bestId = id;\n                }\n            }\n            if (bestDelta <= 0) break;\n            applyOp(curBoard, ops[bestId], +1);\n            curOps.push_back(bestId);\n        }\n\n        // ----- evaluate ------------------------------------------------\n        long long curScore = 0;\n        for (long long v : curBoard) curScore += v;\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestOps.swap(curOps);\n        }\n    }\n\n    // ------------------------------------------------------------\n    // final greedy completion (in case the best solution is not full)\n    // ------------------------------------------------------------\n    board = initBoard;\n    for (int id : bestOps) applyOp(board, ops[id], +1);\n    while ((int)bestOps.size() < K) {\n        long long bestDelta = LLONG_MIN;\n        int bestId = -1;\n        for (int id = 0; id < totalOps; ++id) {\n            long long d = computeDelta(board, ops[id]);\n            if (d > bestDelta) {\n                bestDelta = d;\n                bestId = id;\n            }\n        }\n        if (bestDelta <= 0) break;\n        applyOp(board, ops[bestId], +1);\n        bestOps.push_back(bestId);\n    }\n\n    // ------------------------------------------------------------\n    // output\n    // ------------------------------------------------------------\n    cout << bestOps.size() << \"\\n\";\n    for (int id : bestOps) {\n        const OpInfo &o = ops[id];\n        cout << o.m << ' ' << o.p << ' ' << o.q << \"\\n\";\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\n// generate a Manhattan walk from (r,c) to (tr,tc)\nstatic string walk(int r, int c, int tr, int tc) {\n    string s;\n    while (r > tr) { s.push_back('U'); --r; }\n    while (r < tr) { s.push_back('D'); ++r; }\n    while (c > tc) { s.push_back('L'); --c; }\n    while (c < tc) { s.push_back('R'); ++c; }\n    return s;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> A(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> A[i][j];\n\n    // actions for each crane\n    vector<string> act(N);\n    // small cranes: bomb at turn 0, later do nothing\n    // we will pad them later to the length of the large crane\n    for (int i = 1; i < N; ++i) act[i] = \"B\";\n\n    // large crane (crane 0)\n    string &big = act[0];\n    int curR = 0, curC = 0;               // start position (0,0)\n\n    for (int i = 0; i < N; ++i) {        // receiving gate i\n        for (int j = 0; j < N; ++j) {    // j\u2011th container of this gate\n            // move to (i,0)\n            big += walk(curR, curC, i, 0);\n            curR = i; curC = 0;\n            // pick up\n            big.push_back('P');\n            int b = A[i][j];\n            int dr = b / N;               // destination row\n            // move to dispatch gate (dr, N-1)\n            big += walk(curR, curC, dr, N - 1);\n            curR = dr; curC = N - 1;\n            // release\n            big.push_back('Q');\n            // move back to the receiving gate (i,0)\n            big += walk(curR, curC, i, 0);\n            curR = i; curC = 0;\n        }\n    }\n\n    // pad small cranes with '.' to the length of the longest string\n    size_t L = big.size();\n    for (int i = 1; i < N; ++i) {\n        if (act[i].size() < L) act[i].append(L - act[i].size(), '.');\n    }\n\n    // output\n    for (int i = 0; i < N; ++i) {\n        cout << act[i] << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Node {\n    int x, y;\n    int amt;          // remaining amount to send / receive\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> h[i][j];\n\n    vector<Node> sources, sinks;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (h[i][j] > 0) sources.push_back({i, j, h[i][j]});\n            else if (h[i][j] < 0) sinks.push_back({i, j, -h[i][j]});\n        }\n\n    if (sources.empty() && sinks.empty()) return 0;   // already flat\n\n    // current truck position\n    int curX = 0, curY = 0;\n    vector<string> ops;\n    ops.reserve(40000);\n\n    auto dist = [&](int x1, int y1, int x2, int y2) {\n        return abs(x1 - x2) + abs(y1 - y2);\n    };\n\n    // move from (curX,curY) to (tx,ty) using Manhattan steps\n    auto moveTo = [&](int tx, int ty) {\n        while (curX != tx) {\n            if (curX < tx) {\n                ops.emplace_back(\"D\");\n                ++curX;\n            } else {\n                ops.emplace_back(\"U\");\n                --curX;\n            }\n        }\n        while (curY != ty) {\n            if (curY < ty) {\n                ops.emplace_back(\"R\");\n                ++curY;\n            } else {\n                ops.emplace_back(\"L\");\n                --curY;\n            }\n        }\n    };\n\n    // Main loop: process all sources\n    while (true) {\n        // find the nearest source that still has soil\n        int srcIdx = -1;\n        int best = INT_MAX;\n        for (int i = 0; i < (int)sources.size(); ++i) {\n            if (sources[i].amt == 0) continue;\n            int d = dist(curX, curY, sources[i].x, sources[i].y);\n            if (d < best) {\n                best = d;\n                srcIdx = i;\n            }\n        }\n        if (srcIdx == -1) break;   // all supplies exhausted\n\n        // go to that source (empty)\n        moveTo(sources[srcIdx].x, sources[srcIdx].y);\n\n        // load everything from the source\n        int loadAmt = sources[srcIdx].amt;\n        ops.emplace_back(\"+\" + to_string(loadAmt));\n        sources[srcIdx].amt = 0;\n        int curLoad = loadAmt;   // amount currently on the truck\n\n        // deliver while we still carry soil\n        while (curLoad > 0) {\n            // nearest sink with remaining demand\n            int sinkIdx = -1;\n            best = INT_MAX;\n            for (int i = 0; i < (int)sinks.size(); ++i) {\n                if (sinks[i].amt == 0) continue;\n                int d = dist(curX, curY, sinks[i].x, sinks[i].y);\n                if (d < best) {\n                    best = d;\n                    sinkIdx = i;\n                }\n            }\n            // there must be a sink because total supply = total demand\n            moveTo(sinks[sinkIdx].x, sinks[sinkIdx].y);\n            int unloadAmt = min(curLoad, sinks[sinkIdx].amt);\n            ops.emplace_back(\"-\" + to_string(unloadAmt));\n            curLoad -= unloadAmt;\n            sinks[sinkIdx].amt -= unloadAmt;\n        }\n        // now the truck is empty again, position = last visited sink\n    }\n\n    // output the operation list\n    for (const string& s : ops) {\n        cout << s << '\\n';\n    }\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct PairScore {\n    int i, j;\n    long long score;\n    bool operator<(PairScore const& other) const {\n        return score > other.score; // descending\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    const int S = 2 * N * (N - 1);          // 60 for N = 6\n    const int cells = N * N;               // 36\n\n    // read initial seeds\n    vector<vector<int>> X(S, vector<int>(M));\n    for (int i = 0; i < S; ++i)\n        for (int j = 0; j < M; ++j)\n            cin >> X[i][j];\n\n    // global maxima per component (used as weights)\n    vector<long long> weight(M, 0);\n    for (int l = 0; l < M; ++l) {\n        long long mx = 0;\n        for (int i = 0; i < S; ++i) mx = max(mx, (long long)X[i][l]);\n        weight[l] = mx;\n    }\n\n    // pre\u2011compute the list of edges (cell indices)\n    vector<pair<int,int>> edges;\n    edges.reserve(2 * N * (N - 1));\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            int id = r * N + c;\n            if (c + 1 < N) edges.emplace_back(id, id + 1);          // right neighbor\n            if (r + 1 < N) edges.emplace_back(id, id + N);          // down neighbor\n        }\n    }\n    // edges size = 60 for N = 6\n\n    for (int turn = 0; turn < T; ++turn) {\n        // 1. weighted sum for each seed\n        vector<long long> W(S, 0);\n        for (int i = 0; i < S; ++i) {\n            long long sum = 0;\n            for (int l = 0; l < M; ++l) sum += weight[l] * (long long)X[i][l];\n            W[i] = sum;\n        }\n\n        // 2. compute pair scores\n        vector<PairScore> pairs;\n        pairs.reserve(S * (S - 1) / 2);\n        for (int i = 0; i < S; ++i) {\n            for (int j = i + 1; j < S; ++j) {\n                long long sc = 0;\n                for (int l = 0; l < M; ++l) {\n                    int mx = max(X[i][l], X[j][l]);\n                    sc += weight[l] * (long long)mx;\n                }\n                pairs.push_back({i, j, sc});\n            }\n        }\n        sort(pairs.begin(), pairs.end());\n\n        // 3. board initialisation\n        vector<int> board(cells, -1);\n        vector<char> usedSeed(S, 0);\n        size_t edgePtr = 0;\n\n        // 4. place best pairs on free edges\n        for (const auto& p : pairs) {\n            if (usedSeed[p.i] || usedSeed[p.j]) continue;\n            while (edgePtr < edges.size() &&\n                   (board[edges[edgePtr].first] != -1 ||\n                    board[edges[edgePtr].second] != -1)) {\n                ++edgePtr;\n            }\n            if (edgePtr == edges.size()) break;\n            board[edges[edgePtr].first]  = p.i;\n            board[edges[edgePtr].second] = p.j;\n            usedSeed[p.i] = usedSeed[p.j] = 1;\n            ++edgePtr;\n        }\n\n        // 5. fill remaining cells with best unused seeds\n        vector<int> remaining;\n        remaining.reserve(S);\n        for (int i = 0; i < S; ++i) if (!usedSeed[i]) remaining.push_back(i);\n        sort(remaining.begin(), remaining.end(),\n             [&](int a, int b) { return W[a] > W[b]; });\n\n        size_t rpos = 0;\n        for (int cell = 0; cell < cells; ++cell) {\n            if (board[cell] == -1) {\n                board[cell] = remaining[rpos++];\n            }\n        }\n\n        // 6. output board (row\u2011major)\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (c) cout << ' ';\n                cout << board[r * N + c];\n            }\n            cout << '\\n';\n        }\n        cout.flush();\n\n        // 7. read next batch of seeds\n        for (int i = 0; i < S; ++i)\n            for (int l = 0; l < M; ++l)\n                cin >> X[i][l];\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, V;\n    if (!(cin >> N >> M >> V)) return 0;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) cin >> s[i];\n    for (int i = 0; i < N; ++i) cin >> t[i];\n\n    // collect source cells (initial takoyaki not on target) and target cells (empty)\n    vector<Pos> src, dst;\n    vector<vector<int>> hasTak(N, vector<int>(N, 0));\n    vector<vector<int>> isTarget(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (s[i][j] == '1') hasTak[i][j] = 1;\n            if (t[i][j] == '1') isTarget[i][j] = 1;\n        }\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (hasTak[i][j] && !isTarget[i][j])\n                src.push_back({i, j});\n            if (!hasTak[i][j] && isTarget[i][j])\n                dst.push_back({i, j});\n        }\n\n    const int Vprime = 2;               // root + one leaf\n    // output arm description\n    cout << Vprime << \"\\n\";\n    cout << 0 << \" \" << 1 << \"\\n\";       // parent of vertex 1, length 1\n    cout << 0 << \" \" << 0 << \"\\n\";       // initial root position\n\n    // direction vectors\n    const int dx[4] = {0, 1, 0, -1};\n    const int dy[4] = {1, 0, -1, 0};\n\n    // helper to compute rotation cost\n    auto rotCost = [&](int cur, int target) -> int {\n        int diff = (target - cur + 4) % 4;\n        if (diff == 0) return 0;\n        if (diff == 2) return 2;\n        return 1;\n    };\n\n    // storage for operations\n    vector<string> ops;\n\n    // helper to push a turn\n    auto pushTurn = [&](char mv, char rot, char leafAct) {\n        string s(4, '.');\n        s[0] = mv;\n        s[1] = rot;\n        s[3] = leafAct;\n        ops.push_back(s);\n    };\n\n    // current state\n    int curX = 0, curY = 0;   // root position\n    int curDir = 0;           // leaf points right (dx=0, dy=+1)\n\n    // rotate leaf to target direction (may need 1 or 2 turns)\n    auto rotateTo = [&](int targetDir) {\n        int diff = (targetDir - curDir + 4) % 4;\n        if (diff == 0) return;\n        if (diff == 1) {\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n        } else if (diff == 3) {\n            pushTurn('.', 'L', '.');\n            curDir = (curDir + 3) % 4;\n        } else { // diff == 2\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n        }\n    };\n\n    // move root to (tx,ty) by Manhattan steps\n    auto moveRootTo = [&](int tx, int ty) {\n        while (curX < tx) {\n            pushTurn('D', '.', '.');\n            ++curX;\n        }\n        while (curX > tx) {\n            pushTurn('U', '.', '.');\n            --curX;\n        }\n        while (curY < ty) {\n            pushTurn('R', '.', '.');\n            ++curY;\n        }\n        while (curY > ty) {\n            pushTurn('L', '.', '.');\n            --curY;\n        }\n    };\n\n    // alive flags\n    vector<char> srcAlive(src.size(), 1);\n    vector<char> dstAlive(dst.size(), 1);\n    int remaining = (int)src.size();\n\n    while (remaining > 0) {\n        // ----- choose nearest source -----\n        int bestDist = INT_MAX;\n        int bestIdx = -1, bestDir = -1, bestRx = -1, bestRy = -1;\n        for (int i = 0; i < (int)src.size(); ++i) if (srcAlive[i]) {\n            const Pos &p = src[i];\n            for (int d = 0; d < 4; ++d) {\n                int rx = p.x - dx[d];\n                int ry = p.y - dy[d];\n                if (0 <= rx && rx < N && 0 <= ry && ry < N) {\n                    int dist = abs(curX - rx) + abs(curY - ry);\n                    if (dist < bestDist) {\n                        bestDist = dist;\n                        bestIdx = i;\n                        bestDir = d;\n                        bestRx = rx;\n                        bestRy = ry;\n                    }\n                }\n            }\n        }\n        // move to source\n        rotateTo(bestDir);\n        moveRootTo(bestRx, bestRy);\n        pushTurn('.', '.', 'P');          // pick up\n        srcAlive[bestIdx] = 0;\n        --remaining;\n\n        // ----- choose nearest target -----\n        int bestDist2 = INT_MAX;\n        int bestIdxT = -1, bestDir2 = -1, bestRx2 = -1, bestRy2 = -1;\n        for (int i = 0; i < (int)dst.size(); ++i) if (dstAlive[i]) {\n            const Pos &p = dst[i];\n            for (int d = 0; d < 4; ++d) {\n                int rx = p.x - dx[d];\n                int ry = p.y - dy[d];\n                if (0 <= rx && rx < N && 0 <= ry && ry < N) {\n                    int rotC = rotCost(curDir, d);\n                    int dist = abs(curX - rx) + abs(curY - ry) + rotC;\n                    if (dist < bestDist2) {\n                        bestDist2 = dist;\n                        bestIdxT = i;\n                        bestDir2 = d;\n                        bestRx2 = rx;\n                        bestRy2 = ry;\n                    }\n                }\n            }\n        }\n        // move to target\n        rotateTo(bestDir2);\n        moveRootTo(bestRx2, bestRy2);\n        pushTurn('.', '.', 'P');          // release\n        dstAlive[bestIdxT] = 0;\n    }\n\n    // output operations\n    for (const string &s : ops) cout << s << \"\\n\";\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ull = unsigned long long;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if(!(cin >> N)) return 0;\n    vector<pair<int,int>> mackerel(N);\n    vector<pair<int,int>> sardine(N);\n    for (int i = 0; i < N; ++i) {\n        int x,y; cin >> x >> y;\n        mackerel[i] = {x,y};\n    }\n    unordered_set<ull> sardineSet;\n    sardineSet.reserve(N*2);\n    for (int i = 0; i < N; ++i) {\n        int x,y; cin >> x >> y;\n        sardine[i] = {x,y};\n        ull key = ( (ull)x << 32 ) | (unsigned int) y;\n        sardineSet.insert(key);\n    }\n    \n    // ------------------------------------------------------------\n    // 1) try to isolate a single mackerel with a 1x1 square\n    for (auto [x,y] : mackerel) {\n        if (x >= 100000 || y >= 100000) continue; // would go out of bounds\n        bool ok = true;\n        for (int dx = 0; dx <= 1 && ok; ++dx) {\n            for (int dy = 0; dy <= 1; ++dy) {\n                int nx = x + dx;\n                int ny = y + dy;\n                ull key = ( (ull)nx << 32 ) | (unsigned int) ny;\n                if (sardineSet.find(key) != sardineSet.end()) {\n                    ok = false;\n                    break;\n                }\n            }\n        }\n        if (ok) {\n            // output rectangle [x,x+1] \u00d7 [y,y+1]\n            cout << 4 << \"\\n\";\n            cout << x << \" \" << y << \"\\n\";\n            cout << x+1 << \" \" << y << \"\\n\";\n            cout << x+1 << \" \" << y+1 << \"\\n\";\n            cout << x << \" \" << y+1 << \"\\n\";\n            return 0;\n        }\n    }\n    \n    // ------------------------------------------------------------\n    // 2) grid cell fallback\n    const int G = 2000;                // side length of a cell\n    const int C = 100000 / G;          // 50, divides exactly\n    vector<vector<int>> mCount(C, vector<int>(C, 0));\n    vector<vector<int>> sCount(C, vector<int>(C, 0));\n    \n    auto cellIdx = [&](int coord) -> int {\n        int idx = coord / G;\n        if (idx >= C) idx = C-1;\n        return idx;\n    };\n    \n    for (auto [x,y] : mackerel) {\n        int cx = cellIdx(x);\n        int cy = cellIdx(y);\n        ++mCount[cx][cy];\n    }\n    for (auto [x,y] : sardine) {\n        int cx = cellIdx(x);\n        int cy = cellIdx(y);\n        ++sCount[cx][cy];\n    }\n    \n    int bestCx = -1, bestCy = -1;\n    int bestNet = INT_MIN;\n    for (int cx = 0; cx < C; ++cx) {\n        for (int cy = 0; cy < C; ++cy) {\n            int net = mCount[cx][cy] - sCount[cx][cy];\n            if (net > bestNet) {\n                bestNet = net;\n                bestCx = cx;\n                bestCy = cy;\n            }\n        }\n    }\n    if (bestNet > 0) {\n        int left   = bestCx * G;\n        int right  = (bestCx + 1) * G;\n        int bottom = bestCy * G;\n        int top    = (bestCy + 1) * G;\n        cout << 4 << \"\\n\";\n        cout << left << \" \" << bottom << \"\\n\";\n        cout << right << \" \" << bottom << \"\\n\";\n        cout << right << \" \" << top << \"\\n\";\n        cout << left << \" \" << top << \"\\n\";\n        return 0;\n    }\n    \n    // ------------------------------------------------------------\n    // 3) whole area fallback\n    cout << 4 << \"\\n\";\n    cout << 0 << \" \" << 0 << \"\\n\";\n    cout << 100000 << \" \" << 0 << \"\\n\";\n    cout << 100000 << \" \" << 100000 << \"\\n\";\n    cout << 0 << \" \" << 100000 << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int p;          // rectangle index\n    int r;          // rotation 0/1\n    char d;         // direction 'U' or 'L'\n    int b;          // reference rectangle (-1 or previous index)\n};\n\nstruct Placed {\n    long long x, y; // lower\u2011left corner\n    long long w, h; // size used for placement (estimated)\n};\n\nint N, T;\nlong long sigma;\nvector<long long> wObs, hObs;          // observed values\nvector<long long> obsSum;               // w'+h' for each rectangle\n\n/* ------------------------------------------------------------------ */\n/*  Helper: after a raw sequence (r,d,b) for all rectangles,\n    compute the positions, prefix maxX/Y and drop the best suffix.   */\nvector<Op> trim_ops(const vector<tuple<int,char,int>> &raw,\n                    long long margin) {\n    vector<Placed> placed;\n    vector<long long> prefMaxX, prefMaxY;\n    long long curMaxX = 0, curMaxY = 0;\n\n    for (int i = 0; i < (int)raw.size(); ++i) {\n        int r; char d; int b;\n        tie(r, d, b) = raw[i];\n        long long wi = (r == 0 ? wObs[i] : hObs[i]) + margin;\n        long long hi = (r == 0 ? hObs[i] : wObs[i]) + margin;\n\n        long long x, y;\n        if (d == 'U') {\n            x = (b == -1) ? 0LL : placed[b].x + placed[b].w;\n            y = 0;\n            for (const auto &p : placed) {\n                if (!(x + wi <= p.x || x >= p.x + p.w))\n                    y = max(y, p.y + p.h);\n            }\n        } else { // L\n            y = (b == -1) ? 0LL : placed[b].y + placed[b].h;\n            x = 0;\n            for (const auto &p : placed) {\n                if (!(y + hi <= p.y || y >= p.y + p.h))\n                    x = max(x, p.x + p.w);\n            }\n        }\n        placed.push_back({x, y, wi, hi});\n        curMaxX = max(curMaxX, x + wi);\n        curMaxY = max(curMaxY, y + hi);\n        prefMaxX.push_back(curMaxX);\n        prefMaxY.push_back(curMaxY);\n    }\n\n    // suffix penalty (observed sums)\n    vector<long long> suffix(N + 1, 0);\n    for (int i = N - 1; i >= 0; --i) suffix[i] = suffix[i + 1] + obsSum[i];\n\n    int bestK = (int)raw.size();\n    long long bestScore = (bestK == 0 ? 0 : prefMaxX[bestK - 1])\n                        + (bestK == 0 ? 0 : prefMaxY[bestK - 1])\n                        + suffix[bestK];\n    for (int k = 0; k <= (int)raw.size(); ++k) {\n        long long cur = (k == 0 ? 0 : prefMaxX[k - 1])\n                      + (k == 0 ? 0 : prefMaxY[k - 1])\n                      + suffix[k];\n        if (cur < bestScore) {\n            bestScore = cur;\n            bestK = k;\n        }\n    }\n\n    vector<Op> res;\n    res.reserve(bestK);\n    for (int i = 0; i < bestK; ++i) {\n        int r; char d; int b;\n        tie(r, d, b) = raw[i];\n        res.push_back({i, r, d, b});\n    }\n    return res;\n}\n\n/* ------------------------------------------------------------------ */\n/*  Greedy placement \u2013 try all (r,d,b) (full search)                */\nvector<Op> greedy_full(long long margin) {\n    vector<Op> ops;\n    vector<Placed> placed;\n    vector<long long> prefMaxX, prefMaxY;\n    long long curMaxX = 0, curMaxY = 0;\n\n    for (int i = 0; i < N; ++i) {\n        long long bestScore = (1LL << 62);\n        long long bestX = 0, bestY = 0;\n        int bestB = -1;\n        char bestD = 'U';\n        int bestR = 0;\n        long long bestW = 0, bestH = 0;\n\n        for (int rot = 0; rot <= 1; ++rot) {\n            long long wi = (rot == 0 ? wObs[i] : hObs[i]) + margin;\n            long long hi = (rot == 0 ? hObs[i] : wObs[i]) + margin;\n            for (int b = -1; b <= i - 1; ++b) {\n                // U\n                {\n                    long long x = (b == -1 ? 0LL : placed[b].x + placed[b].w);\n                    long long y = 0;\n                    for (const auto &p : placed) {\n                        if (!(x + wi <= p.x || x >= p.x + p.w))\n                            y = max(y, p.y + p.h);\n                    }\n                    long long newMaxX = max(curMaxX, x + wi);\n                    long long newMaxY = max(curMaxY, y + hi);\n                    long long score = newMaxX + newMaxY;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestX = x; bestY = y;\n                        bestB = b; bestD = 'U';\n                        bestR = rot; bestW = wi; bestH = hi;\n                    }\n                }\n                // L\n                {\n                    long long y = (b == -1 ? 0LL : placed[b].y + placed[b].h);\n                    long long x = 0;\n                    for (const auto &p : placed) {\n                        if (!(y + hi <= p.y || y >= p.y + p.h))\n                            x = max(x, p.x + p.w);\n                    }\n                    long long newMaxX = max(curMaxX, x + wi);\n                    long long newMaxY = max(curMaxY, y + hi);\n                    long long score = newMaxX + newMaxY;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestX = x; bestY = y;\n                        bestB = b; bestD = 'L';\n                        bestR = rot; bestW = wi; bestH = hi;\n                    }\n                }\n            }\n        }\n        ops.push_back({i, bestR, bestD, bestB});\n        placed.push_back({bestX, bestY, bestW, bestH});\n        curMaxX = max(curMaxX, bestX + bestW);\n        curMaxY = max(curMaxY, bestY + bestH);\n        prefMaxX.push_back(curMaxX);\n        prefMaxY.push_back(curMaxY);\n    }\n\n    // suffix penalty and drop suffix\n    vector<long long> suffix(N + 1, 0);\n    for (int i = N - 1; i >= 0; --i) suffix[i] = suffix[i + 1] + obsSum[i];\n\n    int bestK = N;\n    long long bestScore = prefMaxX[N - 1] + prefMaxY[N - 1] + suffix[N];\n    for (int k = 0; k <= N; ++k) {\n        long long cur = (k == 0 ? 0 : prefMaxX[k - 1])\n                      + (k == 0 ? 0 : prefMaxY[k - 1])\n                      + suffix[k];\n        if (cur < bestScore) {\n            bestScore = cur;\n            bestK = k;\n        }\n    }\n    ops.resize(bestK);\n    return ops;\n}\n\n/* ------------------------------------------------------------------ */\n/*  Greedy placement \u2013 only b = -1 or b = i\u20111 (O(N\u00b2))                */\nvector<Op> greedy_limited(long long margin) {\n    vector<Op> ops;\n    vector<Placed> placed;\n    vector<long long> prefMaxX, prefMaxY;\n    long long curMaxX = 0, curMaxY = 0;\n\n    for (int i = 0; i < N; ++i) {\n        long long bestScore = (1LL << 62);\n        long long bestX = 0, bestY = 0;\n        int bestB = -1;\n        char bestD = 'U';\n        int bestR = 0;\n        long long bestW = 0, bestH = 0;\n\n        for (int rot = 0; rot <= 1; ++rot) {\n            long long wi = (rot == 0 ? wObs[i] : hObs[i]) + margin;\n            long long hi = (rot == 0 ? hObs[i] : wObs[i]) + margin;\n            for (int b = -1; b <= i - 1; ++b) {\n                if (b != -1 && b != i - 1) continue;   // only two choices\n                // U\n                {\n                    long long x = (b == -1 ? 0LL : placed[b].x + placed[b].w);\n                    long long y = 0;\n                    for (const auto &p : placed) {\n                        if (!(x + wi <= p.x || x >= p.x + p.w))\n                            y = max(y, p.y + p.h);\n                    }\n                    long long newMaxX = max(curMaxX, x + wi);\n                    long long newMaxY = max(curMaxY, y + hi);\n                    long long score = newMaxX + newMaxY;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestX = x; bestY = y;\n                        bestB = b; bestD = 'U';\n                        bestR = rot; bestW = wi; bestH = hi;\n                    }\n                }\n                // L\n                {\n                    long long y = (b == -1 ? 0LL : placed[b].y + placed[b].h);\n                    long long x = 0;\n                    for (const auto &p : placed) {\n                        if (!(y + hi <= p.y || y >= p.y + p.h))\n                            x = max(x, p.x + p.w);\n                    }\n                    long long newMaxX = max(curMaxX, x + wi);\n                    long long newMaxY = max(curMaxY, y + hi);\n                    long long score = newMaxX + newMaxY;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestX = x; bestY = y;\n                        bestB = b; bestD = 'L';\n                        bestR = rot; bestW = wi; bestH = hi;\n                    }\n                }\n            }\n        }\n        ops.push_back({i, bestR, bestD, bestB});\n        placed.push_back({bestX, bestY, bestW, bestH});\n        curMaxX = max(curMaxX, bestX + bestW);\n        curMaxY = max(curMaxY, bestY + bestH);\n        prefMaxX.push_back(curMaxX);\n        prefMaxY.push_back(curMaxY);\n    }\n\n    // suffix penalty and drop suffix\n    vector<long long> suffix(N + 1, 0);\n    for (int i = N - 1; i >= 0; --i) suffix[i] = suffix[i + 1] + obsSum[i];\n\n    int bestK = N;\n    long long bestScore = prefMaxX[N - 1] + prefMaxY[N - 1] + suffix[N];\n    for (int k = 0; k <= N; ++k) {\n        long long cur = (k == 0 ? 0 : prefMaxX[k - 1])\n                      + (k == 0 ? 0 : prefMaxY[k - 1])\n                      + suffix[k];\n        if (cur < bestScore) {\n            bestScore = cur;\n            bestK = k;\n        }\n    }\n    ops.resize(bestK);\n    return ops;\n}\n\n/* ------------------------------------------------------------------ */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N >> T >> sigma)) return 0;\n    wObs.resize(N);\n    hObs.resize(N);\n    for (int i = 0; i < N; ++i) cin >> wObs[i] >> hObs[i];\n\n    obsSum.resize(N);\n    for (int i = 0; i < N; ++i) obsSum[i] = wObs[i] + hObs[i];\n\n    /* ---------- generate a collection of candidates ---------- */\n    vector<vector<Op>> candidates;\n    const long long MARGIN1 = sigma;          // 1\u00b7\u03c3\n    const long long MARGIN2 = 2 * sigma;      // 2\u00b7\u03c3\n\n    // greedy full (two different margins)\n    candidates.push_back(greedy_full(MARGIN1));\n    candidates.push_back(greedy_full(MARGIN2));\n\n    // greedy limited (two different margins)\n    candidates.push_back(greedy_limited(MARGIN1));\n    candidates.push_back(greedy_limited(MARGIN2));\n\n    // row layout (U, b = i\u20111)\n    {\n        vector<tuple<int,char,int>> raw;\n        raw.reserve(N);\n        for (int i = 0; i < N; ++i) {\n            int r = (hObs[i] > wObs[i]) ? 1 : 0;\n            int b = (i == 0 ? -1 : i - 1);\n            raw.emplace_back(r, 'U', b);\n        }\n        candidates.push_back(trim_ops(raw, MARGIN1));\n    }\n\n    // column layout (L, b = i\u20111)\n    {\n        vector<tuple<int,char,int>> raw;\n        raw.reserve(N);\n        for (int i = 0; i < N; ++i) {\n            int r = (hObs[i] > wObs[i]) ? 1 : 0;\n            int b = (i == 0 ? -1 : i - 1);\n            raw.emplace_back(r, 'L', b);\n        }\n        candidates.push_back(trim_ops(raw, MARGIN1));\n    }\n\n    // a few random candidates\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    const int RANDOM_CAND = 10;\n    for (int c = 0; c < RANDOM_CAND; ++c) {\n        vector<tuple<int,char,int>> raw;\n        raw.reserve(N);\n        for (int i = 0; i < N; ++i) {\n            int r = rng() & 1;\n            char d = (rng() & 1) ? 'U' : 'L';\n            int b = (int)(rng() % (i + 1)) - 1;   // -1 \u2026 i\u20111\n            raw.emplace_back(r, d, b);\n        }\n        candidates.push_back(trim_ops(raw, MARGIN1));\n    }\n\n    /* ---------- interactive loop ---------- */\n    int C = (int)candidates.size();\n    for (int turn = 0; turn < T; ++turn) {\n        const vector<Op> &ops = candidates[turn % C];\n        cout << ops.size() << '\\n';\n        for (const auto &op : ops) {\n            cout << op.p << ' ' << op.r << ' ' << op.d << ' ' << op.b << '\\n';\n        }\n        cout.flush();\n\n        long long Wp, Hp;\n        if (!(cin >> Wp >> Hp)) return 0;   // read the noisy result (ignored)\n    }\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- priority\u2011queue node ---------- */\nstruct PQNode {\n    int depth;\n    int negBeauty;          // -A[v]  (smaller beauty \u2192 larger value)\n    int v;\n    bool operator<(PQNode const& other) const {\n        if (depth != other.depth) return depth < other.depth;          // max\u2011heap by depth\n        return negBeauty < other.negBeauty;                            // max\u2011heap by -A (i.e. smaller A first)\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    if (!(cin >> N >> M >> H)) return 0;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n\n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    // coordinates are irrelevant for the algorithm\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    /* sort neighbours by decreasing beauty \u2013 high\u2011beauty neighbours are examined first */\n    for (int v = 0; v < N; ++v) {\n        sort(adj[v].begin(), adj[v].end(),\n             [&](int a, int b){ return A[a] > A[b]; });\n    }\n\n    const int UNSET = -2;\n    vector<int> parent(N, UNSET);\n    vector<int> depth(N, -1);\n    vector<char> assigned(N, 0);\n    int remaining = N;\n\n    priority_queue<PQNode> pq;\n\n    /* ---------- greedy construction ---------- */\n    while (remaining > 0) {\n        if (pq.empty()) {\n            // start a new tree with the still unassigned vertex of smallest beauty\n            int best = -1, bestA = INT_MAX;\n            for (int i = 0; i < N; ++i) if (!assigned[i] && A[i] < bestA) {\n                bestA = A[i];\n                best = i;\n            }\n            parent[best] = -1;\n            depth[best] = 0;\n            assigned[best] = 1;\n            --remaining;\n            pq.emplace(0, -A[best], best);\n            continue;\n        }\n\n        PQNode cur = pq.top(); pq.pop();\n        int u = cur.v;\n        if (depth[u] != cur.depth) continue;   // outdated entry\n        if (cur.depth == H) continue;          // cannot add children\n\n        // attach all still unassigned neighbours of u\n        for (int w : adj[u]) {\n            if (!assigned[w]) {\n                parent[w] = u;\n                depth[w] = cur.depth + 1;\n                assigned[w] = 1;\n                --remaining;\n                if (depth[w] < H) pq.emplace(depth[w], -A[w], w);\n            }\n        }\n    }\n\n    /* ---------- build children lists ---------- */\n    vector<vector<int>> children(N);\n    for (int v = 0; v < N; ++v) {\n        if (parent[v] != -1) children[parent[v]].push_back(v);\n    }\n\n    /* ---------- initial total score ---------- */\n    long long totalScore = 0;\n    for (int v = 0; v < N; ++v) totalScore += (long long)(depth[v] + 1) * A[v];\n\n    /* ---------- hill\u2011climbing local search ---------- */\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> vertexDist(0, N - 1);\n    const double TIME_LIMIT = 1.90;   // seconds\n    auto startTime = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        int v = vertexDist(rng);\n        if (adj[v].empty()) continue;\n        uniform_int_distribution<int> neighDist(0, (int)adj[v].size() - 1);\n        int u = adj[v][neighDist(rng)];\n\n        // reject if u lies inside the subtree of v (would create a cycle)\n        bool inSub = false;\n        int cur = u;\n        while (cur != -1) {\n            if (cur == v) { inSub = true; break; }\n            cur = parent[cur];\n        }\n        if (inSub) continue;\n\n        int delta = depth[u] + 1 - depth[v];\n        if (delta <= 0) continue;                     // we only want deeper placement\n\n        // collect the whole subtree of v\n        vector<int> stack{v};\n        vector<int> sub;\n        sub.reserve(N);\n        long long sumA = 0;\n        int maxDepthSub = depth[v];\n        while (!stack.empty()) {\n            int x = stack.back(); stack.pop_back();\n            sub.push_back(x);\n            sumA += A[x];\n            maxDepthSub = max(maxDepthSub, depth[x]);\n            for (int c : children[x]) stack.push_back(c);\n        }\n\n        int newDeepest = depth[u] + 1 + (maxDepthSub - depth[v]);\n        if (newDeepest > H) continue;                 // would violate depth limit\n\n        long long deltaScore = (long long)delta * sumA;\n        if (deltaScore <= 0) continue;                // no improvement\n\n        // ----- perform the move -----\n        int oldParent = parent[v];\n        if (oldParent != -1) {\n            auto &vec = children[oldParent];\n            for (size_t i = 0; i < vec.size(); ++i) {\n                if (vec[i] == v) {\n                    vec[i] = vec.back();\n                    vec.pop_back();\n                    break;\n                }\n            }\n        }\n        parent[v] = u;\n        children[u].push_back(v);\n\n        for (int x : sub) depth[x] += delta;\n        totalScore += deltaScore;\n    }\n\n    /* ---------- output ---------- */\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << parent[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DirInfo {\n    char dir;                     // 'L','R','U','D'\n    int idx;                      // row or column index\n    multiset<int> dists;          // distances of assigned Oni\n    int maxDist = 0;              // 0 if empty\n};\n\nstruct OniInfo {\n    vector<int> dirIds;           // safe direction ids\n    vector<int> dists;            // distance for each dirId (same order)\n    int curDir = -1;              // currently assigned direction id\n    int curDist = -1;             // distance for curDir\n};\n\nchar opposite(char d) {\n    if (d == 'L') return 'R';\n    if (d == 'R') return 'L';\n    if (d == 'U') return 'D';\n    return 'U';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    const int MAXN = 20;\n    // create direction ids\n    int dirCnt = 0;\n    int rowL[MAXN], rowR[MAXN], colU[MAXN], colD[MAXN];\n    for (int i = 0; i < N; ++i) {\n        rowL[i] = dirCnt++;\n        rowR[i] = dirCnt++;\n    }\n    for (int j = 0; j < N; ++j) {\n        colU[j] = dirCnt++;\n        colD[j] = dirCnt++;\n    }\n    vector<DirInfo> dirs(dirCnt);\n    for (int i = 0; i < N; ++i) {\n        dirs[rowL[i]] = {'L', i, {}, 0};\n        dirs[rowR[i]] = {'R', i, {}, 0};\n    }\n    for (int j = 0; j < N; ++j) {\n        dirs[colU[j]] = {'U', j, {}, 0};\n        dirs[colD[j]] = {'D', j, {}, 0};\n    }\n\n    // collect Oni\n    vector<OniInfo> ons;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] != 'x') continue;\n            OniInfo o;\n            // safety tests\n            bool safeU = true, safeD = true, safeL = true, safeR = true;\n            for (int k = 0; k < i; ++k) if (board[k][j] == 'o') safeU = false;\n            for (int k = i + 1; k < N; ++k) if (board[k][j] == 'o') safeD = false;\n            for (int k = 0; k < j; ++k) if (board[i][k] == 'o') safeL = false;\n            for (int k = j + 1; k < N; ++k) if (board[i][k] == 'o') safeR = false;\n\n            int dU = i + 1;\n            int dD = N - i;\n            int dL = j + 1;\n            int dR = N - j;\n\n            if (safeU) {\n                o.dirIds.push_back(colU[j]);\n                o.dists.push_back(dU);\n            }\n            if (safeD) {\n                o.dirIds.push_back(colD[j]);\n                o.dists.push_back(dD);\n            }\n            if (safeL) {\n                o.dirIds.push_back(rowL[i]);\n                o.dists.push_back(dL);\n            }\n            if (safeR) {\n                o.dirIds.push_back(rowR[i]);\n                o.dists.push_back(dR);\n            }\n            ons.push_back(std::move(o));\n        }\n    }\n    int M = (int)ons.size();               // = 2*N = 40\n\n    // ---------- initial assignment (cheapest safe direction) ----------\n    for (int id = 0; id < M; ++id) {\n        int bestIdx = -1, bestDist = INT_MAX;\n        for (int k = 0; k < (int)ons[id].dirIds.size(); ++k) {\n            if (ons[id].dists[k] < bestDist) {\n                bestDist = ons[id].dists[k];\n                bestIdx = k;\n            }\n        }\n        int dir = ons[id].dirIds[bestIdx];\n        int dist = ons[id].dists[bestIdx];\n        ons[id].curDir = dir;\n        ons[id].curDist = dist;\n        dirs[dir].dists.insert(dist);\n        dirs[dir].maxDist = max(dirs[dir].maxDist, dist);\n    }\n\n    // total cost = sum 2*maxDist\n    int totalCost = 0;\n    for (auto &d : dirs) if (!d.dists.empty()) totalCost += 2 * d.maxDist;\n\n    // ---------- local improvement ----------\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        int bestDelta = 0;          // negative value = improvement\n        int bestOni = -1, bestFrom = -1, bestTo = -1;\n        int bestCurDist = -1, bestToDist = -1;\n\n        for (int oid = 0; oid < M; ++oid) {\n            int from = ons[oid].curDir;\n            int curDist = ons[oid].curDist;\n            const DirInfo &dFrom = dirs[from];\n            int oldMaxFrom = dFrom.maxDist;\n\n            for (int k = 0; k < (int)ons[oid].dirIds.size(); ++k) {\n                int to = ons[oid].dirIds[k];\n                if (to == from) continue;\n                int toDist = ons[oid].dists[k];\n                const DirInfo &dTo = dirs[to];\n                int oldMaxTo = dTo.maxDist;\n\n                // new max for 'from' after removing curDist\n                int newMaxFrom;\n                if (curDist < oldMaxFrom) {\n                    newMaxFrom = oldMaxFrom;\n                } else { // curDist == oldMaxFrom\n                    int cnt = dFrom.dists.count(oldMaxFrom);\n                    if (cnt >= 2) {\n                        newMaxFrom = oldMaxFrom;\n                    } else {\n                        if (dFrom.dists.size() == 1) newMaxFrom = 0;\n                        else {\n                            auto it = dFrom.dists.rbegin();\n                            ++it; // second largest\n                            newMaxFrom = *it;\n                        }\n                    }\n                }\n\n                // new max for 'to' after inserting toDist\n                int newMaxTo = max(oldMaxTo, toDist);\n\n                int newCost = totalCost - 2 * oldMaxFrom - 2 * oldMaxTo\n                              + 2 * newMaxFrom + 2 * newMaxTo;\n                int delta = newCost - totalCost; // negative = improvement\n                if (delta < bestDelta) {\n                    bestDelta = delta;\n                    bestOni = oid;\n                    bestFrom = from;\n                    bestTo = to;\n                    bestCurDist = curDist;\n                    bestToDist = toDist;\n                }\n            }\n        }\n\n        if (bestDelta < 0) {\n            // apply the best move\n            // erase from old direction\n            auto &setFrom = dirs[bestFrom].dists;\n            auto it = setFrom.find(bestCurDist);\n            setFrom.erase(it);\n            dirs[bestFrom].maxDist = setFrom.empty() ? 0 : *setFrom.rbegin();\n\n            // insert into new direction\n            auto &setTo = dirs[bestTo].dists;\n            setTo.insert(bestToDist);\n            dirs[bestTo].maxDist = *setTo.rbegin();\n\n            // update Oni info\n            ons[bestOni].curDir = bestTo;\n            ons[bestOni].curDist = bestToDist;\n\n            totalCost += bestDelta;\n            improved = true;\n        }\n    }\n\n    // ---------- output ----------\n    vector<pair<char,int>> out;\n    for (int d = 0; d < dirCnt; ++d) {\n        int D = dirs[d].maxDist;\n        if (D == 0) continue;\n        char dir = dirs[d].dir;\n        int idx = dirs[d].idx;\n        for (int k = 0; k < D; ++k) out.emplace_back(dir, idx);\n        for (int k = 0; k < D; ++k) out.emplace_back(opposite(dir), idx);\n    }\n\n    for (auto [c, p] : out) {\n        cout << c << ' ' << p << '\\n';\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\n/* ------------------------------------------------------------\n   Global data (read once in main)\n   ------------------------------------------------------------ */\nint N;                     // number of employees (always 100)\nint L;                     // number of weeks (always 500000)\nvector<int> T;             // target frequencies\n\n/* ------------------------------------------------------------\n   Full simulation \u2013 exact error after L weeks\n   ------------------------------------------------------------ */\nstatic ll simulate_full(const int a[], const int b[]) {\n    static int cnt[200];\n    memset(cnt, 0, N * sizeof(int));\n\n    int cur = 0;\n    for (int step = 0; step < L; ++step) {\n        int t = cnt[cur];\n        ++cnt[cur];\n        cur = (t & 1) ? a[cur] : b[cur];\n    }\n\n    ll err = 0;\n    for (int i = 0; i < N; ++i) err += llabs((ll)cnt[i] - (ll)T[i]);\n    return err;\n}\n\n/* ------------------------------------------------------------\n   Build a random candidate (a,b) respecting the target indegree\n   ------------------------------------------------------------ */\nstatic void build_candidate(int a[], int b[], mt19937_64 &rng) {\n    /* a : random permutation (the base cycle) */\n    vector<int> perm(N);\n    iota(perm.begin(), perm.end(), 0);\n    shuffle(perm.begin(), perm.end(), rng);\n    for (int i = 0; i < N; ++i) a[i] = perm[i];\n\n    /* ----- target indegree ----- */\n    const double factor = (2.0 * N) / static_cast<double>(L);   // = 0.0004\n    vector<double> w(N);\n    for (int i = 0; i < N; ++i) w[i] = T[i] * factor;\n\n    vector<int> extra(N, 0);\n    vector<double> frac(N, -1e9);\n    int baseSum = 0;\n    for (int i = 0; i < N; ++i) {\n        double val = w[i] - 1.0;                // one indegree already from the cycle\n        if (val > 0.0) {\n            int base = static_cast<int>(floor(val));\n            extra[i] = base;\n            frac[i]  = val - base;\n            baseSum  += base;\n        }\n    }\n    int need = N - baseSum;                     // still missing incoming edges\n    if (need > 0) {\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int i, int j){ return frac[i] > frac[j]; });\n        for (int k = 0; k < need; ++k) ++extra[order[k]];\n    }\n\n    /* ----- b : distribute the remaining indegree ----- */\n    vector<int> pool;\n    pool.reserve(N);\n    for (int i = 0; i < N; ++i)\n        for (int k = 0; k < extra[i]; ++k) pool.push_back(i);\n    // safety \u2013 should be exactly N\n    while ((int)pool.size() < N) pool.push_back(rng() % N);\n    while ((int)pool.size() > N) pool.pop_back();\n\n    shuffle(pool.begin(), pool.end(), rng);\n    for (int i = 0; i < N; ++i) b[i] = pool[i];\n}\n\n/* ------------------------------------------------------------ */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N >> L)) return 0;\n    T.resize(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    int best_a[200], best_b[200];\n    int cur_a[200],  cur_b[200];\n    ll best_err = LLONG_MAX;\n\n    /* ---- a few random candidates, keep the best ---- */\n    for (int trial = 0; trial < 6; ++trial) {\n        build_candidate(cur_a, cur_b, rng);\n        ll err = simulate_full(cur_a, cur_b);\n        if (err < best_err) {\n            best_err = err;\n            memcpy(best_a, cur_a, N * sizeof(int));\n            memcpy(best_b, cur_b, N * sizeof(int));\n        }\n    }\n    memcpy(cur_a, best_a, N * sizeof(int));\n    memcpy(cur_b, best_b, N * sizeof(int));\n    ll cur_err = best_err;\n\n    /* ---- light hill climbing (time limited) ---- */\n    const double TIME_LIMIT = 1.75;          // seconds, safe margin\n    const int   CHECK_EVERY = 20;           // check clock every few iterations\n    auto start = chrono::steady_clock::now();\n\n    for (int iter = 0; ; ++iter) {\n        if (iter % CHECK_EVERY == 0) {\n            auto now = chrono::steady_clock::now();\n            double elapsed = chrono::duration<double>(now - start).count();\n            if (elapsed > TIME_LIMIT) break;\n        }\n\n        int move_type = rng() % 100;        // 0\u201159 : swap b, 60\u201179 : swap a, 80\u201199 : flip\n        int i = rng() % N;\n        int j = rng() % N;\n        bool applied = false;\n\n        if (move_type < 60) {               // swap two b\u2011edges\n            if (i == j) continue;\n            swap(cur_b[i], cur_b[j]);\n            applied = true;\n        } else if (move_type < 80) {        // swap two a\u2011edges\n            if (i == j) continue;\n            swap(cur_a[i], cur_a[j]);\n            applied = true;\n        } else {                            // flip a[i] and b[i]\n            i = rng() % N;\n            swap(cur_a[i], cur_b[i]);\n            applied = true;\n        }\n        if (!applied) continue;\n\n        ll err = simulate_full(cur_a, cur_b);\n        if (err < best_err) {\n            best_err = err;\n            memcpy(best_a, cur_a, N * sizeof(int));\n            memcpy(best_b, cur_b, N * sizeof(int));\n        }\n        if (err < cur_err) {\n            cur_err = err;\n        } else {\n            // revert the move\n            if (move_type < 60) swap(cur_b[i], cur_b[j]);\n            else if (move_type < 80) swap(cur_a[i], cur_a[j]);\n            else swap(cur_a[i], cur_b[i]);\n        }\n    }\n\n    /* ---- output the best pair found ---- */\n    for (int i = 0; i < N; ++i) {\n        cout << best_a[i] << ' ' << best_b[i] << '\\n';\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\n/*** Edge for Kruskal on representatives ***/\nstruct RepEdge {\n    int u, v;\n    long long w2;               // squared centre distance\n    bool operator<(RepEdge const& o) const { return w2 < o.w2; }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n    vector<int> G(M);\n    for (int &x : G) cin >> x;\n\n    vector<int> lx(N), rx(N), ly(N), ry(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n\n    /* centre of each rectangle */\n    vector<long long> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        cx[i] = (static_cast<long long>(lx[i]) + rx[i]) / 2;\n        cy[i] = (static_cast<long long>(ly[i]) + ry[i]) / 2;\n    }\n\n    /* ---------- 1. greedy clustering ---------- */\n    vector<char> assigned(N, 0);\n    vector<int> remaining(N);\n    iota(remaining.begin(), remaining.end(), 0);\n    vector<vector<int>> groups;\n    groups.reserve(M);\n\n    for (int gi = 0; gi < M; ++gi) {\n        int need = G[gi];\n        vector<int> group;\n        group.reserve(need);\n\n        /* choose seed = city with smallest cx among remaining */\n        int seed = -1;\n        long long bestX = LLONG_MAX;\n        for (int v : remaining) {\n            if (cx[v] < bestX) {\n                bestX = cx[v];\n                seed = v;\n            }\n        }\n        group.push_back(seed);\n        assigned[seed] = 1;\n        remaining.erase(remove(remaining.begin(), remaining.end(), seed), remaining.end());\n\n        /* bestDist for each still unassigned city (distance to the current group) */\n        const long long INF = (1LL << 62);\n        vector<long long> bestDist(N, INF);\n        for (int v : remaining) {\n            long long dx = cx[v] - cx[seed];\n            long long dy = cy[v] - cy[seed];\n            bestDist[v] = dx * dx + dy * dy;\n        }\n\n        while ((int)group.size() < need) {\n            int bestCity = -1;\n            long long bestD = INF;\n            for (int v : remaining) {\n                if (bestDist[v] < bestD) {\n                    bestD = bestDist[v];\n                    bestCity = v;\n                }\n            }\n            // add bestCity\n            group.push_back(bestCity);\n            assigned[bestCity] = 1;\n            remaining.erase(remove(remaining.begin(), remaining.end(), bestCity), remaining.end());\n\n            // update bestDist for the rest\n            for (int v : remaining) {\n                long long dx = cx[v] - cx[bestCity];\n                long long dy = cy[v] - cy[bestCity];\n                long long d2 = dx * dx + dy * dy;\n                if (d2 < bestDist[v]) bestDist[v] = d2;\n            }\n        }\n        groups.emplace_back(move(group));\n    }\n\n    /* ---------- 2. build roads ---------- */\n    vector<vector<pair<int,int>>> groupEdges(M);\n    int queries_used = 0;\n\n    for (int gi = 0; gi < M; ++gi) {\n        const vector<int> &g = groups[gi];\n        int gsz = (int)g.size();\n        if (gsz <= 1) continue;               // nothing to do\n\n        /* split into chunks of size \u2264 L */\n        vector<vector<int>> chunks;\n        for (int i = 0; i < gsz; ) {\n            int sz = min(L, gsz - i);\n            chunks.emplace_back(g.begin() + i, g.begin() + i + sz);\n            i += sz;\n        }\n\n        /* query each chunk (size \u2265 2) */\n        for (auto &ch : chunks) {\n            int sz = (int)ch.size();\n            if (sz <= 1) continue;\n            cout << \"? \" << sz;\n            for (int v : ch) cout << ' ' << v;\n            cout << \"\\n\" << flush;\n            ++queries_used;\n\n            for (int i = 0; i < sz - 1; ++i) {\n                int a, b;\n                cin >> a >> b;\n                groupEdges[gi].emplace_back(a, b);\n            }\n        }\n\n        /* representatives = first city of each chunk */\n        vector<int> reps;\n        reps.reserve(chunks.size());\n        for (auto &ch : chunks) reps.push_back(ch[0]);\n\n        int c = (int)reps.size();\n        if (c <= 1) continue;                // already connected\n\n        /* build MST on representatives using centre distances */\n        vector<RepEdge> edges;\n        edges.reserve(c * (c - 1) / 2);\n        for (int i = 0; i < c; ++i) {\n            for (int j = i + 1; j < c; ++j) {\n                long long dx = cx[reps[i]] - cx[reps[j]];\n                long long dy = cy[reps[i]] - cy[reps[j]];\n                long long d2 = dx * dx + dy * dy;\n                edges.push_back({reps[i], reps[j], d2});\n            }\n        }\n        sort(edges.begin(), edges.end());\n\n        // map city id -> index in reps (0 \u2026 c\u20111)\n        unordered_map<int,int> idx;\n        idx.reserve(c * 2);\n        for (int i = 0; i < c; ++i) idx[reps[i]] = i;\n\n        DSU dsu(c);\n        for (auto &e : edges) {\n            int u = idx[e.u];\n            int v = idx[e.v];\n            if (dsu.unite(u, v)) {\n                groupEdges[gi].push_back({e.u, e.v});\n            }\n        }\n    }\n\n    /* ---------- 3. output answer ---------- */\n    cout << \"!\\n\";\n    for (int gi = 0; gi < M; ++gi) {\n        const auto &g = groups[gi];\n        for (size_t i = 0; i < g.size(); ++i) {\n            if (i) cout << ' ';\n            cout << g[i];\n        }\n        cout << \"\\n\";\n        for (auto [a,b] : groupEdges[gi]) {\n            cout << a << ' ' << b << \"\\n\";\n        }\n    }\n    cout.flush();\n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct PrevInfo {\n    int prev;      // previous cell id, -1 for start\n    char act;      // 'M' or 'S'\n    char dir;      // 'U','D','L','R'\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    if (!(cin >> N >> M)) return 0;          // read board size and number of points\n\n    vector<pair<int,int>> pos(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> pos[i].first >> pos[i].second;\n    }\n\n    // direction data\n    const char dch[4] = {'U','D','L','R'};\n    const int dr[4] = {-1, 1, 0, 0};\n    const int dc[4] = {0, 0, -1, 1};\n\n    int cur_r = pos[0].first;\n    int cur_c = pos[0].second;\n\n    const int V = N * N;                     // number of cells\n\n    // helper to convert (r,c) to a single id\n    auto id = [&](int r, int c) { return r * N + c; };\n\n    for (int idx = 1; idx < M; ++idx) {\n        int tr = pos[idx].first;\n        int tc = pos[idx].second;\n\n        // ---------- BFS from current position ----------\n        vector<int> dist(V, -1);\n        vector<PrevInfo> prev(V, {-1, 0, 0});\n        queue<int> q;\n\n        int start = id(cur_r, cur_c);\n        dist[start] = 0;\n        q.push(start);\n\n        while (!q.empty()) {\n            int cur = q.front(); q.pop();\n            int r = cur / N;\n            int c = cur % N;\n            int dcur = dist[cur];\n\n            // 4 moves\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + dr[d];\n                int nc = c + dc[d];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                int nid = id(nr, nc);\n                if (dist[nid] == -1) {\n                    dist[nid] = dcur + 1;\n                    prev[nid] = {cur, 'M', dch[d]};\n                    q.push(nid);\n                }\n            }\n\n            // 4 slides \u2013 slide straight to the border in each direction\n            for (int d = 0; d < 4; ++d) {\n                int nr = r, nc = c;\n                if (d == 0) nr = 0;          // up\n                else if (d == 1) nr = N - 1; // down\n                else if (d == 2) nc = 0;     // left\n                else if (d == 3) nc = N - 1; // right\n                if (nr == r && nc == c) continue; // already at border\n                int nid = id(nr, nc);\n                if (dist[nid] == -1) {\n                    dist[nid] = dcur + 1;\n                    prev[nid] = {cur, 'S', dch[d]};\n                    q.push(nid);\n                }\n            }\n        }\n\n        // ---------- reconstruct shortest path ----------\n        int target_id = id(tr, tc);\n        vector<pair<char,char>> actions;   // (action, direction) in reverse order\n        int cur = target_id;\n        while (cur != start) {\n            const PrevInfo &p = prev[cur];\n            actions.emplace_back(p.act, p.dir);\n            cur = p.prev;\n        }\n        reverse(actions.begin(), actions.end());\n\n        // ---------- output ----------\n        for (auto [a, d] : actions) {\n            cout << a << ' ' << d << '\\n';\n        }\n\n        // update current position\n        cur_r = tr;\n        cur_c = tc;\n    }\n\n    return 0;\n}"},"16":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    long long r;\n    int idx;\n};\n\nint n;\nvector<Point> pt;\nvector<int> ans_a, ans_b, ans_c, ans_d;\n\n/* -------------------------------------------------------------\n   leaf rectangle \u2013 try to choose width/height that best matches\n   the desired area while still containing the point.\n   ------------------------------------------------------------- */\nvoid allocate_leaf(int x0, int x1, int y0, int y1, const Point& p) {\n    int width  = x1 - x0;\n    int height = y1 - y0;\n    long long want = p.r;\n\n    int best_w = width, best_h = height;\n    long long best_diff = LLONG_MAX;\n\n    // try all possible widths (1 \u2026 width)\n    for (int w = 1; w <= width; ++w) {\n        // two candidates for height: floor and ceil of want/w\n        long long h_floor = want / w;\n        long long h_ceil  = (want + w - 1) / w;\n\n        for (long long h_raw : {h_floor, h_ceil}) {\n            if (h_raw < 1) continue;\n            if (h_raw > height) continue;\n            int h = (int)h_raw;\n\n            // check that the rectangle can be placed so that (x,y) is inside\n            int a_low  = max(x0, p.x - w + 1);\n            int a_high = min(p.x, x1 - w);\n            if (a_low > a_high) continue;\n            int b_low  = max(y0, p.y - h + 1);\n            int b_high = min(p.y, y1 - h);\n            if (b_low > b_high) continue;\n\n            long long area = 1LL * w * h;\n            long long diff = llabs(area - want);\n            if (diff < best_diff) {\n                best_diff = diff;\n                best_w = w;\n                best_h = h;\n            }\n        }\n    }\n\n    // place the rectangle as far left / bottom as possible inside the leaf\n    int a_low  = max(x0, p.x - best_w + 1);\n    int a_high = min(p.x, x1 - best_w);\n    int a = a_low;                     // any value in [a_low, a_high] works\n    int b_low  = max(y0, p.y - best_h + 1);\n    int b_high = min(p.y, y1 - best_h);\n    int b = b_low;                     // any value in [b_low, b_high] works\n\n    ans_a[p.idx] = a;\n    ans_b[p.idx] = b;\n    ans_c[p.idx] = a + best_w;\n    ans_d[p.idx] = b + best_h;\n}\n\n/* -------------------------------------------------------------\n   recursive guillotine partition\n   ------------------------------------------------------------- */\nvoid solve_region(int x0, int x1, int y0, int y1,\n                  const vector<int>& ids) {\n    if (ids.empty()) return;\n    if (ids.size() == 1) {\n        allocate_leaf(x0, x1, y0, y1, pt[ids[0]]);\n        return;\n    }\n\n    int width  = x1 - x0;\n    int height = y1 - y0;\n    bool vertical = (width >= height);\n\n    if (vertical) {\n        // ----- vertical cut -------------------------------------------------\n        vector<int> sorted = ids;\n        sort(sorted.begin(), sorted.end(),\n             [&](int a, int b){ return pt[a].x < pt[b].x; });\n\n        // prefix sums of r\n        vector<long long> pref(sorted.size());\n        for (size_t i = 0; i < sorted.size(); ++i) {\n            pref[i] = pt[sorted[i]].r + (i ? pref[i-1] : 0);\n        }\n\n        long long bestDiff = LLONG_MAX;\n        int bestX = -1;                     // cut column (absolute coordinate)\n\n        for (size_t k = 0; k + 1 < sorted.size(); ++k) {\n            long long sumLeft = pref[k];\n            int leftMaxX  = pt[sorted[k]].x;\n            int rightMinX = pt[sorted[k+1]].x;\n\n            // ideal width to host sumLeft area\n            long long needW = (sumLeft + height - 1) / height; // ceil\n            int X = x0 + (int)needW;\n\n            // enforce that the cut lies between the two point columns\n            if (X <= leftMaxX) X = leftMaxX + 1;\n            if (X >  rightMinX) X = rightMinX;\n            if (X <= x0) X = x0 + 1;\n            if (X >= x1) X = x1 - 1;\n\n            long long areaLeft = 1LL * (X - x0) * height;\n            long long diff = llabs(areaLeft - sumLeft);\n            if (diff < bestDiff) {\n                bestDiff = diff;\n                bestX = X;\n            }\n        }\n\n        // fallback: split in the middle if no suitable cut was found\n        if (bestX == -1) {\n            bestX = x0 + width / 2;\n            if (bestX == x0) bestX = x0 + 1;\n            if (bestX == x1) bestX = x1 - 1;\n        }\n\n        // partition ids\n        vector<int> leftIds, rightIds;\n        for (int id : ids) {\n            if (pt[id].x < bestX) leftIds.push_back(id);\n            else                 rightIds.push_back(id);\n        }\n\n        // if a side became empty (possible when many points share the same x)\n        if (leftIds.empty() || rightIds.empty()) {\n            bestX = (x0 + x1) / 2;\n            if (bestX == x0) bestX = x0 + 1;\n            if (bestX == x1) bestX = x1 - 1;\n            leftIds.clear(); rightIds.clear();\n            for (int id : ids) {\n                if (pt[id].x < bestX) leftIds.push_back(id);\n                else                 rightIds.push_back(id);\n            }\n        }\n\n        solve_region(x0, bestX, y0, y1, leftIds);\n        solve_region(bestX, x1, y0, y1, rightIds);\n    } else {\n        // ----- horizontal cut ------------------------------------------------\n        vector<int> sorted = ids;\n        sort(sorted.begin(), sorted.end(),\n             [&](int a, int b){ return pt[a].y < pt[b].y; });\n\n        vector<long long> pref(sorted.size());\n        for (size_t i = 0; i < sorted.size(); ++i) {\n            pref[i] = pt[sorted[i]].r + (i ? pref[i-1] : 0);\n        }\n\n        long long bestDiff = LLONG_MAX;\n        int bestY = -1;                     // cut row (absolute coordinate)\n\n        for (size_t k = 0; k + 1 < sorted.size(); ++k) {\n            long long sumTop = pref[k];\n            int topMaxY    = pt[sorted[k]].y;\n            int bottomMinY = pt[sorted[k+1]].y;\n\n            long long needH = (sumTop + width - 1) / width; // ceil\n            int Y = y0 + (int)needH;\n\n            if (Y <= topMaxY)   Y = topMaxY + 1;\n            if (Y >  bottomMinY) Y = bottomMinY;\n            if (Y <= y0) Y = y0 + 1;\n            if (Y >= y1) Y = y1 - 1;\n\n            long long areaTop = 1LL * (Y - y0) * width;\n            long long diff = llabs(areaTop - sumTop);\n            if (diff < bestDiff) {\n                bestDiff = diff;\n                bestY = Y;\n            }\n        }\n\n        if (bestY == -1) {\n            bestY = y0 + height / 2;\n            if (bestY == y0) bestY = y0 + 1;\n            if (bestY == y1) bestY = y1 - 1;\n        }\n\n        vector<int> topIds, botIds;\n        for (int id : ids) {\n            if (pt[id].y < bestY) topIds.push_back(id);\n            else                  botIds.push_back(id);\n        }\n\n        if (topIds.empty() || botIds.empty()) {\n            bestY = (y0 + y1) / 2;\n            if (bestY == y0) bestY = y0 + 1;\n            if (bestY == y1) bestY = y1 - 1;\n            topIds.clear(); botIds.clear();\n            for (int id : ids) {\n                if (pt[id].y < bestY) topIds.push_back(id);\n                else                  botIds.push_back(id);\n            }\n        }\n\n        solve_region(x0, x1, y0, bestY, topIds);\n        solve_region(x0, x1, bestY, y1, botIds);\n    }\n}\n\n/* ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> n)) return 0;\n    pt.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> pt[i].x >> pt[i].y >> pt[i].r;\n        pt[i].idx = i;\n    }\n\n    ans_a.assign(n, 0);\n    ans_b.assign(n, 0);\n    ans_c.assign(n, 0);\n    ans_d.assign(n, 0);\n\n    vector<int> all_ids(n);\n    iota(all_ids.begin(), all_ids.end(), 0);\n    solve_region(0, 10000, 0, 10000, all_ids);\n\n    for (int i = 0; i < n; ++i) {\n        cout << ans_a[i] << ' ' << ans_b[i] << ' '\n             << ans_c[i] << ' ' << ans_d[i] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 50;\nconstexpr int DIRS = 4;\nconstexpr char DIR_CHAR[DIRS] = {'U','D','L','R'};\nconstexpr int DX[DIRS] = {-1, 1, 0, 0};\nconstexpr int DY[DIRS] = {0, 0, -1, 1};\n\nusing Clock = chrono::steady_clock;\nusing ms    = chrono::milliseconds;\n\n/* ---------- bitset helpers (max 2500 tiles) ---------- */\nusing Bitset = array<uint64_t,40>;   // 40*64 = 2560 >= 2500\ninline bool isVisited(const Bitset& b,int t){\n    return (b[t>>6]>> (t&63)) & 1ULL;\n}\ninline void setVisited(Bitset& b,int t){\n    b[t>>6] |= 1ULL << (t&63);\n}\n\n/* ---------- state of the beam ---------- */\nstruct State{\n    int x,y;               // current cell\n    long long score;       // sum of visited p\u2011values\n    string path;           // moves taken so far\n    Bitset visited;        // tiles already used\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si,sj;\n    if(!(cin>>si>>sj)) return 0;\n\n    /* ----- read tiles ----- */\n    vector<vector<int>> tile(N, vector<int>(N));\n    int maxTile = -1;\n    for(int i=0;i<N;++i)\n        for(int j=0;j<N;++j){\n            cin>>tile[i][j];\n            maxTile = max(maxTile, tile[i][j]);\n        }\n    const int M = maxTile + 1;                     // number of tiles\n\n    /* ----- read values ----- */\n    vector<vector<int>> val(N, vector<int>(N));\n    for(int i=0;i<N;++i)\n        for(int j=0;j<N;++j)\n            cin>>val[i][j];\n\n    /* ----- otherP : loss when stepping on a domino ----- */\n    vector<vector<int>> otherP(N, vector<int>(N,0));\n    vector<vector<pair<int,int>>> tileSquares(M);\n    for(int i=0;i<N;++i)\n        for(int j=0;j<N;++j)\n            tileSquares[tile[i][j]].push_back({i,j});\n    for(int t=0;t<M;++t){\n        if(tileSquares[t].size()==2){\n            auto [x1,y1]=tileSquares[t][0];\n            auto [x2,y2]=tileSquares[t][1];\n            otherP[x1][y1]=val[x2][y2];\n            otherP[x2][y2]=val[x1][y1];\n        }\n    }\n\n    /* ----- random generator ----- */\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n\n    /* ----- helpers ----- */\n    auto inside = [&](int x,int y)->bool{\n        return 0<=x && x<N && 0<=y && y<N;\n    };\n    auto degree = [&](int x,int y,const Bitset& vis)->int{\n        int cur = tile[x][y];\n        int deg = 0;\n        for(int d=0;d<DIRS;++d){\n            int nx=x+DX[d], ny=y+DY[d];\n            if(!inside(nx,ny)) continue;\n            int t = tile[nx][ny];\n            if(t==cur) continue;                     // same tile\n            if(!isVisited(vis,t)) ++deg;\n        }\n        return deg;\n    };\n    auto bestNeighbourValue = [&](int x,int y,const Bitset& vis)->int{\n        int best = 0;\n        for(int d=0;d<DIRS;++d){\n            int nx=x+DX[d], ny=y+DY[d];\n            if(!inside(nx,ny)) continue;\n            int t = tile[nx][ny];\n            if(isVisited(vis,t)) continue;\n            best = max(best, val[nx][ny]);\n        }\n        return best;\n    };\n\n    /* ----- main multi\u2011run loop ----- */\n    const int TIME_LIMIT_MS = 1900;                // a little before 2\u202fs\n    const int BEAM_WIDTH = 30;\n    auto startTime = Clock::now();\n\n    string bestPath;\n    long long bestScore = -1;\n\n    while (true){\n        // time check\n        if (chrono::duration_cast<ms>(Clock::now() - startTime).count() > TIME_LIMIT_MS)\n            break;\n\n        // random weights for this run (0 \u2026 1000)\n        int wD = uniform_int_distribution<int>(0,1000)(rng);\n        int wN = uniform_int_distribution<int>(0,1000)(rng);\n        if (wD==0 && wN==0) wD = 1;               // ensure non\u2011zero\n\n        // initial state\n        State init;\n        init.x = si; init.y = sj;\n        init.score = val[si][sj];\n        init.path.clear();\n        init.visited.fill(0ULL);\n        setVisited(init.visited, tile[si][sj]);\n\n        vector<State> beam{init};\n        State bestThisRun = init;\n\n        while (true){\n            vector<pair<long long,State>> candidates;\n            candidates.reserve(beam.size()*4);\n\n            for (const State& s : beam){\n                int order[4] = {0,1,2,3};\n                shuffle(order, order+4, rng);      // random direction order\n                for (int ii=0; ii<4; ++ii){\n                    int d = order[ii];\n                    int nx = s.x + DX[d];\n                    int ny = s.y + DY[d];\n                    if (!inside(nx,ny)) continue;\n                    int t = tile[nx][ny];\n                    if (isVisited(s.visited, t)) continue;   // tile already used\n\n                    State ns = s;                     // copy\n                    ns.x = nx; ns.y = ny;\n                    ns.path.push_back(DIR_CHAR[d]);\n                    ns.score += val[nx][ny];\n                    setVisited(ns.visited, t);\n\n                    // heuristic = current score + weighted degree + weighted best neighbour\n                    int deg = degree(nx, ny, ns.visited);\n                    int best = bestNeighbourValue(nx, ny, ns.visited);\n                    long long h = ns.score + (long long)wD * deg + (long long)wN * best;\n\n                    candidates.emplace_back(h, std::move(ns));\n                }\n            }\n\n            if (candidates.empty()) break;          // dead ends for all states\n\n            // keep only the BEAM_WIDTH best candidates (by heuristic)\n            if ((int)candidates.size() > BEAM_WIDTH){\n                nth_element(candidates.begin(),\n                            candidates.begin() + BEAM_WIDTH,\n                            candidates.end(),\n                            [](const auto& a, const auto& b){ return a.first > b.first; });\n                candidates.resize(BEAM_WIDTH);\n            }\n\n            // rebuild beam and update best state\n            beam.clear();\n            beam.reserve(candidates.size());\n            for (auto &pr : candidates){\n                const State &st = pr.second;\n                beam.push_back(st);\n                if (st.score > bestThisRun.score) bestThisRun = st;\n            }\n        }\n\n        if (bestThisRun.score > bestScore){\n            bestScore = bestThisRun.score;\n            bestPath  = bestThisRun.path;\n        }\n    }\n\n    cout << bestPath << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;                     // grid dimension\nconstexpr int V = N * N;                 // number of vertices\nconstexpr double INF = 1e100;\nconstexpr double MIN_W = 500.0;\nconstexpr double MAX_W = 10000.0;\n\n/* edge indexing helpers */\ninline int horiz_id(int i, int j) { return i * (N - 1) + j; }   // 0 \u2264 i < N, 0 \u2264 j < N\u20111\ninline int vert_id (int i, int j) { return i * N + j; }       // 0 \u2264 i < N\u20111, 0 \u2264 j < N\ninline int node_id (int i, int j) { return i * N + j; }\ninline pair<int,int> id_to_coord(int id) { return {id / N, id % N}; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int Hcnt = N * (N - 1);          // horizontal edges\n    const int Vcnt = (N - 1) * N;          // vertical edges\n\n    /* ----- model parameters ----- */\n    vector<double> base_h(N, 5000.0);      // row bases\n    vector<double> base_v(N, 5000.0);      // column bases\n    vector<double> res_h(Hcnt, 0.0);       // horizontal residuals\n    vector<double> res_v(Vcnt, 0.0);       // vertical   residuals\n\n    vector<int> cntBaseRow(N, 0);         // how many horizontal steps have been used per row\n    vector<int> cntBaseCol(N, 0);         // how many vertical   steps have been used per column\n    vector<int> cntResH(Hcnt, 0);          // per\u2011edge residual update count\n    vector<int> cntResV(Vcnt, 0);\n\n    const double base_lr = 0.5;           // learning rate for bases\n    const double edge_lr = 0.05;          // learning rate for residuals\n\n    for (int q = 0; q < 1000; ++q) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) return 0;   // safety\n        int s = node_id(si, sj);\n        int t = node_id(ti, tj);\n\n        /* ---------- Dijkstra on current weights ---------- */\n        vector<double> dist(V, INF);\n        vector<int>    parent(V, -1);\n        vector<char>   move_dir(V, 0);\n        dist[s] = 0.0;\n        using PQItem = pair<double,int>;\n        priority_queue<PQItem, vector<PQItem>, greater<PQItem>> pq;\n        pq.emplace(0.0, s);\n\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u]) continue;\n            if (u == t) break;\n            auto [i, j] = id_to_coord(u);\n\n            // up\n            if (i > 0) {\n                int nb = node_id(i-1, j);\n                double w = base_v[j] + res_v[vert_id(i-1, j)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move_dir[nb] = 'U';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // down\n            if (i + 1 < N) {\n                int nb = node_id(i+1, j);\n                double w = base_v[j] + res_v[vert_id(i, j)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move_dir[nb] = 'D';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // left\n            if (j > 0) {\n                int nb = node_id(i, j-1);\n                double w = base_h[i] + res_h[horiz_id(i, j-1)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move_dir[nb] = 'L';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n            // right\n            if (j + 1 < N) {\n                int nb = node_id(i, j+1);\n                double w = base_h[i] + res_h[horiz_id(i, j)];\n                if (dist[nb] > d + w) {\n                    dist[nb] = d + w;\n                    parent[nb] = u;\n                    move_dir[nb] = 'R';\n                    pq.emplace(dist[nb], nb);\n                }\n            }\n        }\n\n        /* ---------- reconstruct path (reverse order) ---------- */\n        vector<char> rev_path;\n        vector<pair<bool,int>> rev_edges; // (isHorizontal, edgeId)\n        int cur = t;\n        while (cur != s) {\n            int p = parent[cur];\n            char d = move_dir[cur];\n            rev_path.push_back(d);\n            auto [ci, cj] = id_to_coord(cur);\n            auto [pi, pj] = id_to_coord(p);\n            if (ci == pi + 1 && cj == pj) {               // moved down\n                rev_edges.emplace_back(false, vert_id(pi, pj));\n            } else if (ci == pi - 1 && cj == pj) {        // moved up\n                rev_edges.emplace_back(false, vert_id(ci, cj));\n            } else if (cj == pj + 1 && ci == pi) {        // moved right\n                rev_edges.emplace_back(true, horiz_id(pi, pj));\n            } else if (cj == pj - 1 && ci == pi) {        // moved left\n                rev_edges.emplace_back(true, horiz_id(ci, cj));\n            }\n            cur = p;\n        }\n        reverse(rev_path.begin(), rev_path.end());\n        reverse(rev_edges.begin(), rev_edges.end());\n\n        string out_path;\n        out_path.reserve(rev_path.size());\n        for (char c : rev_path) out_path.push_back(c);\n\n        /* ---------- output and flush ---------- */\n        cout << out_path << '\\n' << flush;\n\n        long long L;\n        if (!(cin >> L)) return 0;   // safety\n\n        /* ---------- collect statistics ---------- */\n        int steps = static_cast<int>(rev_path.size());\n        if (steps == 0) continue;   // should never happen (Manhattan distance \u226510)\n\n        array<int, N> cntRow{}; cntRow.fill(0);\n        array<int, N> cntCol{}; cntCol.fill(0);\n        vector<int> horizEdges;\n        vector<int> vertEdges;\n\n        for (auto &e : rev_edges) {\n            if (e.first) { // horizontal\n                int id = e.second;\n                horizEdges.push_back(id);\n                int row = id / (N - 1);\n                ++cntRow[row];\n            } else {       // vertical\n                int id = e.second;\n                vertEdges.push_back(id);\n                int col = id % N;\n                ++cntCol[col];\n            }\n        }\n\n        /* ---------- current estimate of the path length ---------- */\n        double est = 0.0;\n        for (int id : horizEdges) {\n            int row = id / (N - 1);\n            est += base_h[row] + res_h[id];\n        }\n        for (int id : vertEdges) {\n            int col = id % N;\n            est += base_v[col] + res_v[id];\n        }\n        double err = est - static_cast<double>(L);\n        double grad = err / steps;   // same for every edge of the path\n\n        /* ---------- update bases (row / column) ---------- */\n        for (int i = 0; i < N; ++i) if (cntRow[i] > 0) {\n            double lr = base_lr / sqrt(static_cast<double>(cntBaseRow[i] + 1));\n            base_h[i] -= lr * err * cntRow[i] / steps;\n            if (base_h[i] < MIN_W) base_h[i] = MIN_W;\n            if (base_h[i] > MAX_W) base_h[i] = MAX_W;\n            cntBaseRow[i] += cntRow[i];\n        }\n        for (int j = 0; j < N; ++j) if (cntCol[j] > 0) {\n            double lr = base_lr / sqrt(static_cast<double>(cntBaseCol[j] + 1));\n            base_v[j] -= lr * err * cntCol[j] / steps;\n            if (base_v[j] < MIN_W) base_v[j] = MIN_W;\n            if (base_v[j] > MAX_W) base_v[j] = MAX_W;\n            cntBaseCol[j] += cntCol[j];\n        }\n\n        /* ---------- update residuals (per\u2011edge) ---------- */\n        for (int id : horizEdges) {\n            int row = id / (N - 1);\n            double lr = edge_lr / sqrt(static_cast<double>(cntResH[id] + 1));\n            res_h[id] -= lr * grad;\n            ++cntResH[id];\n            double w = base_h[row] + res_h[id];\n            if (w < MIN_W) res_h[id] = MIN_W - base_h[row];\n            if (w > MAX_W) res_h[id] = MAX_W - base_h[row];\n        }\n        for (int id : vertEdges) {\n            int col = id % N;\n            double lr = edge_lr / sqrt(static_cast<double>(cntResV[id] + 1));\n            res_v[id] -= lr * grad;\n            ++cntResV[id];\n            double w = base_v[col] + res_v[id];\n            if (w < MIN_W) res_v[id] = MIN_W - base_v[col];\n            if (w > MAX_W) res_v[id] = MAX_W - base_v[col];\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int MAX_N = 20;\nconstexpr int MAX_LEN = 12;\nconstexpr uint8_t EMPTY = 8;          // value for '.' (unused after fill)\n\n/* ---------- data structures ---------- */\n\nstruct Placement {\n    uint8_t len;                      // length of the string (\u226412)\n    uint16_t cells[MAX_LEN];          // linear cell indices (0 \u2026 399)\n    uint8_t  need[MAX_LEN];           // required character (0 \u2026 7)\n    int stringId;                     // which string it belongs to\n};\n\nstruct CellPlacementInfo {\n    int pid;          // global placement id\n    uint8_t need;     // needed character for this cell\n};\n\n/* ---------- main ---------- */\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<string> S(M);\n    for (int i = 0; i < M; ++i) cin >> S[i];\n\n    /* ----- generate all placements ----- */\n    vector<Placement> allPl;               // flat list of all placements\n    allPl.reserve(M * 800);\n    vector<vector<int>> plOfString(M);     // placement ids per string\n    vector<vector<CellPlacementInfo>> cellInfo(N * N);\n    for (int sid = 0; sid < M; ++sid) {\n        const string &st = S[sid];\n        int L = (int)st.size();\n        // horizontal\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                Placement p;\n                p.len = (uint8_t)L;\n                p.stringId = sid;\n                for (int k = 0; k < L; ++k) {\n                    int col = (c + k) % N;\n                    p.cells[k] = (uint16_t)(r * N + col);\n                    p.need[k] = (uint8_t)(st[k] - 'A');\n                }\n                int pid = (int)allPl.size();\n                allPl.push_back(p);\n                plOfString[sid].push_back(pid);\n                for (int k = 0; k < L; ++k) {\n                    cellInfo[p.cells[k]].push_back({pid, p.need[k]});\n                }\n            }\n        }\n        // vertical\n        for (int c = 0; c < N; ++c) {\n            for (int r = 0; r < N; ++r) {\n                Placement p;\n                p.len = (uint8_t)L;\n                p.stringId = sid;\n                for (int k = 0; k < L; ++k) {\n                    int row = (r + k) % N;\n                    p.cells[k] = (uint16_t)(row * N + c);\n                    p.need[k] = (uint8_t)(st[k] - 'A');\n                }\n                int pid = (int)allPl.size();\n                allPl.push_back(p);\n                plOfString[sid].push_back(pid);\n                for (int k = 0; k < L; ++k) {\n                    cellInfo[p.cells[k]].push_back({pid, p.need[k]});\n                }\n            }\n        }\n    }\n    const int PL_TOTAL = (int)allPl.size();\n\n    /* ----- random utilities ----- */\n    std::mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> distChar(0, 7);\n    std::uniform_int_distribution<int> distString(0, M - 1);\n\n    const double TIME_LIMIT = 2.9;          // seconds per test case\n    auto startTime = chrono::steady_clock::now();\n\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    vector<int> length(M);\n    for (int i = 0; i < M; ++i) length[i] = (int)S[i].size();\n\n    int bestScore = -1;\n    vector<uint8_t> bestMat(N * N, EMPTY);\n\n    const int MIN_ITER = 30;                // guarantee enough greedy runs\n    int iter = 0;\n\n    /* ----- greedy phase (multiple random orders) ----- */\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT - 0.5 && iter >= MIN_ITER) break; // reserve time for local search\n\n        // choose order\n        if (iter % 2 == 0) {\n            shuffle(order.begin(), order.end(), rng);\n        } else {\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     if (length[a] != length[b]) return length[a] > length[b];\n                     return a < b;\n                 });\n        }\n\n        // greedy placement\n        vector<uint8_t> mat(N * N, EMPTY);\n        for (int sid : order) {\n            const auto &plist = plOfString[sid];\n            int bestPid = -1;\n            int bestOverlap = -1;\n            for (int pid : plist) {\n                const Placement &p = allPl[pid];\n                bool conflict = false;\n                int overlap = 0;\n                for (int k = 0; k < p.len; ++k) {\n                    uint8_t cur = mat[p.cells[k]];\n                    uint8_t need = p.need[k];\n                    if (cur != EMPTY && cur != need) {\n                        conflict = true;\n                        break;\n                    }\n                    if (cur == need) ++overlap;\n                }\n                if (conflict) continue;\n                if (overlap > bestOverlap) {\n                    bestOverlap = overlap;\n                    bestPid = pid;\n                    if (overlap == p.len) break; // perfect match\n                }\n            }\n            if (bestPid != -1) {\n                const Placement &p = allPl[bestPid];\n                for (int k = 0; k < p.len; ++k) {\n                    uint16_t cell = p.cells[k];\n                    if (mat[cell] == EMPTY) mat[cell] = p.need[k];\n                }\n            }\n        }\n\n        // majority\u2011vote fill for remaining empty cells\n        static int freq[400][8];\n        for (int i = 0; i < N * N; ++i)\n            for (int c = 0; c < 8; ++c) freq[i][c] = 0;\n\n        // count compatible placements (still possible)\n        for (int sid = 0; sid < M; ++sid) {\n            const auto &plist = plOfString[sid];\n            for (int pid : plist) {\n                const Placement &p = allPl[pid];\n                bool compatible = true;\n                for (int k = 0; k < p.len; ++k) {\n                    uint8_t cur = mat[p.cells[k]];\n                    if (cur != EMPTY && cur != p.need[k]) {\n                        compatible = false;\n                        break;\n                    }\n                }\n                if (!compatible) continue;\n                for (int k = 0; k < p.len; ++k) {\n                    uint16_t cell = p.cells[k];\n                    if (mat[cell] == EMPTY) ++freq[cell][p.need[k]];\n                }\n            }\n        }\n        for (int i = 0; i < N * N; ++i) {\n            if (mat[i] != EMPTY) continue;\n            int bestChar = 0, bestCnt = -1;\n            for (int c = 0; c < 8; ++c) {\n                if (freq[i][c] > bestCnt) {\n                    bestCnt = freq[i][c];\n                    bestChar = c;\n                }\n            }\n            if (bestCnt <= 0) bestChar = distChar(rng);\n            mat[i] = (uint8_t)bestChar;\n        }\n\n        // count satisfied strings\n        int satisfied = 0;\n        for (int sid = 0; sid < M; ++sid) {\n            const auto &plist = plOfString[sid];\n            bool ok = false;\n            for (int pid : plist) {\n                const Placement &p = allPl[pid];\n                bool good = true;\n                for (int k = 0; k < p.len; ++k) {\n                    if (mat[p.cells[k]] != p.need[k]) {\n                        good = false;\n                        break;\n                    }\n                }\n                if (good) { ok = true; break; }\n            }\n            if (ok) ++satisfied;\n        }\n        if (satisfied > bestScore) {\n            bestScore = satisfied;\n            bestMat = mat;\n        }\n        ++iter;\n    }\n\n    /* ----- prepare data for local search on the best matrix ----- */\n    // mismatch per placement\n    vector<uint8_t> mismatch(PL_TOTAL, 0);\n    vector<int> satCnt(M, 0);\n    for (int pid = 0; pid < PL_TOTAL; ++pid) {\n        const Placement &p = allPl[pid];\n        uint8_t cnt = 0;\n        for (int k = 0; k < p.len; ++k) {\n            if (bestMat[p.cells[k]] != p.need[k]) ++cnt;\n        }\n        mismatch[pid] = cnt;\n        if (cnt == 0) ++satCnt[p.stringId];\n    }\n    int totalSat = 0;\n    for (int i = 0; i < M; ++i) if (satCnt[i] > 0) ++totalSat;\n\n    /* ----- local search (hill climbing) ----- */\n    vector<uint8_t> curMat = bestMat;\n    vector<uint8_t> curMismatch = mismatch;\n    vector<int> curSatCnt = satCnt;\n    int curTotalSat = totalSat;\n\n    const int MAX_LOCAL_ITER = 800;          // safe upper bound\n    int localIter = 0;\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n        if (localIter >= MAX_LOCAL_ITER) break;\n\n        int cell = rng() % (N * N);\n        uint8_t oldChar = curMat[cell];\n        int delta[8] = {0};\n\n        for (const auto &ci : cellInfo[cell]) {\n            int pid = ci.pid;\n            uint8_t need = ci.need;\n            int sid = allPl[pid].stringId;\n            uint8_t mc = curMismatch[pid];\n            bool beforeMatch = (oldChar == need);\n            for (int c = 0; c < 8; ++c) {\n                bool afterMatch = (c == need);\n                if (beforeMatch == afterMatch) continue;\n                if (beforeMatch && !afterMatch) { // breaking a match\n                    if (mc == 0 && curSatCnt[sid] == 1) delta[c] -= 1;\n                } else { // fixing a mismatch\n                    if (mc == 1 && curSatCnt[sid] == 0) delta[c] += 1;\n                }\n            }\n        }\n\n        // choose best character\n        int bestChar = oldChar;\n        int bestDelta = 0;\n        for (int c = 0; c < 8; ++c) {\n            if (delta[c] > bestDelta) {\n                bestDelta = delta[c];\n                bestChar = c;\n            }\n        }\n\n        if (bestDelta > 0) {\n            // apply the change\n            curMat[cell] = (uint8_t)bestChar;\n            for (const auto &ci : cellInfo[cell]) {\n                int pid = ci.pid;\n                uint8_t need = ci.need;\n                int sid = allPl[pid].stringId;\n                uint8_t &mc = curMismatch[pid];\n                bool beforeMatch = (oldChar == need);\n                bool afterMatch = (bestChar == need);\n                if (beforeMatch == afterMatch) continue;\n                if (beforeMatch && !afterMatch) { // breaking a match\n                    if (mc == 0) {\n                        // placement becomes unsatisfied\n                        if (curSatCnt[sid] == 1) --curTotalSat;\n                        --curSatCnt[sid];\n                    }\n                    ++mc;\n                } else { // fixing a mismatch\n                    if (mc == 1) {\n                        // placement becomes satisfied\n                        if (curSatCnt[sid] == 0) ++curTotalSat;\n                        ++curSatCnt[sid];\n                    }\n                    --mc;\n                }\n            }\n            if (curTotalSat > bestScore) {\n                bestScore = curTotalSat;\n                bestMat = curMat;\n            }\n        }\n        ++localIter;\n    }\n\n    /* ----- output ----- */\n    for (int r = 0; r < N; ++r) {\n        string line;\n        line.reserve(N);\n        for (int c = 0; c < N; ++c) {\n            uint8_t v = bestMat[r * N + c];\n            line.push_back(char('A' + v));\n        }\n        cout << line << '\\n';\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll INF = (1LL << 60);\n\n/*** 1.  Input & basic structures ***/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, si, sj;\n    if (!(cin >> N >> si >> sj)) return 0;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n\n    // assign an id to every road cell\n    vector<vector<int>> id(N, vector<int>(N, -1));\n    vector<int> row, col, cost;          // by id\n    int r = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                id[i][j] = r++;\n                row.push_back(i);\n                col.push_back(j);\n                cost.push_back(grid[i][j] - '0');\n            }\n        }\n    }\n    int startId = id[si][sj];\n\n    // adjacency list (directed: moving to neighbour costs neighbour's cost)\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    vector<vector<pair<int,int>>> adj(r);\n    for (int v = 0; v < r; ++v) {\n        int i = row[v], j = col[v];\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d], nj = j + dy[d];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (grid[ni][nj] == '#') continue;\n            int to = id[ni][nj];\n            adj[v].push_back({to, cost[to]});\n        }\n    }\n\n    /*** 2.  Build representatives \u2013 one per maximal segment ***/\n    vector<char> isRep(r, 0);\n    vector<int> reps;               // ids of representatives\n\n    // horizontal segments\n    for (int i = 0; i < N; ++i) {\n        int j = 0;\n        while (j < N) {\n            if (grid[i][j] == '#') { ++j; continue; }\n            int start = j;\n            while (j < N && grid[i][j] != '#') ++j;\n            int repId = id[i][start];          // leftmost cell\n            if (!isRep[repId]) {\n                isRep[repId] = 1;\n                reps.push_back(repId);\n            }\n        }\n    }\n    // vertical segments\n    for (int j = 0; j < N; ++j) {\n        int i = 0;\n        while (i < N) {\n            if (grid[i][j] == '#') { ++i; continue; }\n            int start = i;\n            while (i < N && grid[i][j] != '#') ++i;\n            int repId = id[start][j];          // topmost cell\n            if (!isRep[repId]) {\n                isRep[repId] = 1;\n                reps.push_back(repId);\n            }\n        }\n    }\n    // ensure start cell is a representative\n    if (!isRep[startId]) {\n        isRep[startId] = 1;\n        reps.push_back(startId);\n    }\n\n    int m = (int)reps.size();               // number of representatives\n    unordered_map<int,int> repIdxOfId;\n    repIdxOfId.reserve(m*2);\n    for (int i = 0; i < m; ++i) repIdxOfId[reps[i]] = i;\n\n    /*** 3.  All\u2011pairs shortest paths from each representative ***/\n    vector<vector<ll>> dist(m, vector<ll>(r, INF));\n    vector<vector<int>> parent(m, vector<int>(r, -1));\n\n    using P = pair<ll,int>;\n    for (int k = 0; k < m; ++k) {\n        int src = reps[k];\n        priority_queue<P, vector<P>, greater<P>> pq;\n        dist[k][src] = 0;\n        pq.emplace(0LL, src);\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d != dist[k][u]) continue;\n            for (auto [v, w] : adj[u]) {\n                ll nd = d + w;\n                if (nd < dist[k][v]) {\n                    dist[k][v] = nd;\n                    parent[k][v] = u;\n                    pq.emplace(nd, v);\n                }\n            }\n        }\n    }\n\n    // distance matrix between representatives (directed)\n    vector<vector<ll>> repDist(m, vector<ll>(m, INF));\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < m; ++j) {\n            repDist[i][j] = dist[i][reps[j]];\n        }\n    }\n\n    /*** 4.  Helper: tour length ***/\n    auto tourLength = [&](const vector<int>& t)->ll{\n        ll sum = 0;\n        int sz = (int)t.size();\n        for (int i = 0; i < sz; ++i) {\n            int a = t[i];\n            int b = t[(i+1)%sz];\n            sum += repDist[a][b];\n        }\n        return sum;\n    };\n\n    /*** 5.  2\u2011opt improvement ***/\n    auto twoOpt = [&](vector<int>& tour) {\n        bool improved = true;\n        int passes = 0;\n        const int MAX_PASSES = 5;\n        int sz = (int)tour.size();\n        while (improved && passes < MAX_PASSES) {\n            improved = false;\n            ++passes;\n            for (int i = 0; i < sz; ++i) {\n                for (int j = i + 2; j < sz; ++j) {\n                    if (i == 0 && j == sz - 1) continue; // adjacent in cycle\n                    int a = tour[i];\n                    int b = tour[(i+1)%sz];\n                    int c = tour[j];\n                    int d = tour[(j+1)%sz];\n                    ll curLen = repDist[a][b] + repDist[c][d];\n                    ll newLen = repDist[a][c] + repDist[b][d];\n                    if (newLen < curLen) {\n                        // reverse segment (i+1 .. j)\n                        if (i+1 <= j) reverse(tour.begin() + i + 1, tour.begin() + j + 1);\n                        improved = true;\n                    }\n                }\n            }\n        }\n    };\n\n    /*** 6.  Build initial tour (nearest\u2011neighbour) ***/\n    vector<char> visited(m, 0);\n    vector<int> bestTour;\n    bestTour.reserve(m);\n    int startIdx = repIdxOfId[startId];\n    // deterministic nearest\u2011neighbour\n    {\n        vector<char> vis(m, 0);\n        vector<int> tour;\n        tour.reserve(m);\n        int cur = startIdx;\n        tour.push_back(cur);\n        vis[cur] = 1;\n        for (int cnt = 1; cnt < m; ++cnt) {\n            ll best = INF;\n            int bestIdx = -1;\n            for (int i = 0; i < m; ++i) if (!vis[i]) {\n                if (repDist[cur][i] < best) {\n                    best = repDist[cur][i];\n                    bestIdx = i;\n                }\n            }\n            vis[bestIdx] = 1;\n            tour.push_back(bestIdx);\n            cur = bestIdx;\n        }\n        twoOpt(tour);\n        bestTour = tour;\n    }\n\n    /*** 7.  Randomised improvement within time budget ***/\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    vector<int> otherIdx;\n    otherIdx.reserve(m-1);\n    for (int i = 0; i < m; ++i) if (i != startIdx) otherIdx.push_back(i);\n\n    auto startClock = chrono::steady_clock::now();\n    const double TIME_LIMIT = 2.7; // seconds\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startClock).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        shuffle(otherIdx.begin(), otherIdx.end(), rng);\n        vector<int> tour;\n        tour.reserve(m);\n        tour.push_back(startIdx);\n        tour.insert(tour.end(), otherIdx.begin(), otherIdx.end());\n\n        twoOpt(tour);\n        ll len = tourLength(tour);\n        if (len < tourLength(bestTour)) {\n            bestTour = tour;\n        }\n    }\n\n    /*** 8.  Reconstruct the movement string ***/\n    string answer;\n\n    // helper: output shortest path from srcId to dstId using parent of srcRepIdx\n    auto appendPath = [&](int srcId, int dstId, int srcRepIdx) {\n        vector<int> path;\n        int cur = dstId;\n        while (cur != srcId) {\n            path.push_back(cur);\n            cur = parent[srcRepIdx][cur];\n        }\n        path.push_back(srcId);\n        reverse(path.begin(), path.end());\n        for (size_t k = 1; k < path.size(); ++k) {\n            int a = path[k-1];\n            int b = path[k];\n            int dr = row[b] - row[a];\n            int dc = col[b] - col[a];\n            char ch;\n            if (dr == -1) ch = 'U';\n            else if (dr == 1) ch = 'D';\n            else if (dc == -1) ch = 'L';\n            else /* dc == 1 */ ch = 'R';\n            answer.push_back(ch);\n        }\n    };\n\n    int curId = startId;\n    int curRepIdx = startIdx;\n    for (size_t i = 1; i < bestTour.size(); ++i) {\n        int nxtId = reps[bestTour[i]];\n        appendPath(curId, nxtId, curRepIdx);\n        curId = nxtId;\n        curRepIdx = bestTour[i];\n    }\n    // finally return to start\n    if (curId != startId) {\n        appendPath(curId, startId, curRepIdx);\n    }\n\n    cout << answer << '\\n';\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- data structures ---------- */\n\nstruct ReadyTask {\n    int id;          // task index (0\u2011based)\n    int dp;          // longest path length starting from the task\n    long long sum;   // \u03a3 d_i,k\n    // priority: larger dp first, then larger sum\n    bool operator<(const ReadyTask& other) const {\n        if (dp != other.dp) return dp < other.dp;\n        return sum < other.sum;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    if (!(cin >> N >> M >> K >> R)) return 0;\n\n    /* ----- read required skill vectors ----- */\n    vector<vector<int>> d(N, vector<int>(K));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < K; ++j)\n            cin >> d[i][j];\n\n    /* ----- compute sum of required skills for each task ----- */\n    vector<long long> sum_d(N, 0);\n    for (int i = 0; i < N; ++i) {\n        long long s = 0;\n        for (int j = 0; j < K; ++j) s += d[i][j];\n        sum_d[i] = s;\n    }\n\n    /* ----- read dependencies ----- */\n    vector<vector<int>> adj(N);\n    vector<int> indeg(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        adj[u].push_back(v);\n        ++indeg[v];\n    }\n\n    /* ----- longest path length (critical\u2011path priority) ----- */\n    vector<int> dp(N, 1);\n    for (int i = N - 1; i >= 0; --i) {\n        for (int v : adj[i]) {\n            dp[i] = max(dp[i], dp[v] + 1);\n        }\n    }\n\n    /* ----- initial ready queue ----- */\n    priority_queue<ReadyTask> readyPQ;\n    for (int i = 0; i < N; ++i) {\n        if (indeg[i] == 0) {\n            readyPQ.push({i, dp[i], sum_d[i]});\n        }\n    }\n\n    /* ----- state of members and tasks ----- */\n    vector<int> member_task(M, -1);          // task currently executed, -1 = idle\n    vector<int> task_start_day(N, -1);       // day when the task started\n    vector<char> task_started(N, 0);\n    vector<char> task_completed(N, 0);\n\n    /* ----- statistics for skill estimation ----- */\n    vector<long long> sum_d_done(M, 0);\n    vector<long long> sum_t_done(M, 0);\n    vector<int> cnt_done(M, 0);\n    vector<double> skill_est(M, 0.0);        // estimate of \u03a3 s_j\n\n    int day = 0;\n    while (true) {\n        ++day;\n\n        /* ----- collect idle members ----- */\n        vector<int> idle;\n        for (int j = 0; j < M; ++j)\n            if (member_task[j] == -1) idle.push_back(j);\n\n        /* ----- order idle members by estimated skill (strongest first) ----- */\n        sort(idle.begin(), idle.end(),\n             [&](int a, int b) { return skill_est[a] > skill_est[b]; });\n\n        /* ----- assign tasks ----- */\n        vector<pair<int,int>> assign;   // (member, task) in 1\u2011based form\n        for (int idx = 0; idx < (int)idle.size() && !readyPQ.empty(); ++idx) {\n            int member = idle[idx];\n            ReadyTask rt = readyPQ.top(); readyPQ.pop();\n            int task = rt.id;\n\n            assign.emplace_back(member + 1, task + 1);\n            member_task[member] = task;\n            task_started[task] = 1;\n            task_start_day[task] = day;\n        }\n\n        /* ----- output ----- */\n        cout << assign.size();\n        for (auto &p : assign) cout << ' ' << p.first << ' ' << p.second;\n        cout << \"\\n\" << flush;\n\n        /* ----- read judge response ----- */\n        int n;\n        if (!(cin >> n)) return 0;          // EOF (should not happen)\n        if (n == -1) break;                 // all tasks done or day limit\n        vector<int> finished;\n        finished.reserve(n);\n        for (int i = 0; i < n; ++i) {\n            int f; cin >> f;\n            finished.push_back(f);\n        }\n\n        /* ----- process completions ----- */\n        for (int f : finished) {\n            int member = f - 1;\n            int task = member_task[member];\n            if (task == -1) continue;       // safety, should not happen\n\n            // real duration of the task\n            int duration = day - task_start_day[task] + 1;\n\n            // update skill estimate of the member\n            ++cnt_done[member];\n            sum_d_done[member] += sum_d[task];\n            sum_t_done[member] += duration;\n            double raw = (double)sum_d_done[member] - (double)sum_t_done[member];\n            if (raw < 0) raw = 0;\n            skill_est[member] = raw / cnt_done[member];\n\n            // free the member\n            member_task[member] = -1;\n\n            // mark task as completed\n            task_started[task] = 0;\n            task_completed[task] = 1;\n\n            // make successors ready\n            for (int v : adj[task]) {\n                --indeg[v];\n                if (indeg[v] == 0) {\n                    readyPQ.push({v, dp[v], sum_d[v]});\n                }\n            }\n        }\n    }\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Order {\n    int a, b, c, d;   // pickup (a,b), delivery (c,d)\n    int idx;          // 1\u2011based index in the original list\n    long long cost;  // heuristic cost for selection\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 1000;\n    const int M = 50;\n    const int OFF_X = 400, OFF_Y = 400;\n\n    vector<Order> orders(N);\n    for (int i = 0; i < N; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        long long cost = 0;\n        cost += manhattan(OFF_X, OFF_Y, a, b); // office -> pickup\n        cost += manhattan(a, b, c, d);         // pickup -> delivery\n        cost += manhattan(c, d, OFF_X, OFF_Y); // delivery -> office\n        orders[i] = {a, b, c, d, i + 1, cost};\n    }\n\n    // -----------------------------------------------------------------\n    // 1) select 50 orders with smallest heuristic cost\n    sort(orders.begin(), orders.end(),\n         [](const Order& x, const Order& y) { return x.cost < y.cost; });\n    vector<Order> sel(orders.begin(), orders.begin() + M);\n\n    // -----------------------------------------------------------------\n    // 2) greedy feasible\u2011node walk\n    // status: 0 = not started, 1 = pickup done, 2 = delivered\n    vector<int> status(M, 0);\n    vector<int> chosenIdx;          // order indices in the order we first visit pickup\n    vector<pair<int,int>> route;    // visited points\n\n    int curX = OFF_X, curY = OFF_Y;\n    route.emplace_back(curX, curY);   // start at office\n\n    int remaining = M;   // number of orders not yet delivered\n    while (remaining > 0) {\n        int bestDist = INT_MAX;\n        int bestIdx = -1;\n        bool bestIsPickup = true;   // true -> pickup, false -> delivery\n\n        for (int i = 0; i < M; ++i) {\n            if (status[i] == 0) { // pickup not visited yet\n                int d = manhattan(curX, curY, sel[i].a, sel[i].b);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx = i;\n                    bestIsPickup = true;\n                }\n            } else if (status[i] == 1) { // pickup done, delivery pending\n                int d = manhattan(curX, curY, sel[i].c, sel[i].d);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx = i;\n                    bestIsPickup = false;\n                }\n            }\n        }\n\n        // we must have found a candidate\n        if (bestIsPickup) {\n            // go to pickup\n            curX = sel[bestIdx].a;\n            curY = sel[bestIdx].b;\n            route.emplace_back(curX, curY);\n            status[bestIdx] = 1;\n            chosenIdx.push_back(sel[bestIdx].idx);\n        } else {\n            // go to delivery\n            curX = sel[bestIdx].c;\n            curY = sel[bestIdx].d;\n            route.emplace_back(curX, curY);\n            status[bestIdx] = 2;\n            --remaining;\n        }\n    }\n\n    // return to office\n    route.emplace_back(OFF_X, OFF_Y);\n\n    // -----------------------------------------------------------------\n    // 3) output\n    cout << M;\n    for (int id : chosenIdx) cout << ' ' << id;\n    cout << '\\n';\n\n    cout << route.size();\n    for (auto [x, y] : route) cout << ' ' << x << ' ' << y;\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        sz.assign(n, 1);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\n/*** Edge description ***/\nstruct Edge {\n    int u, v;\n    int d;          // rounded Euclidean distance\n    int idx;        // original index in input order\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        long long dx = (long long)x[u] - x[v];\n        long long dy = (long long)y[u] - y[v];\n        double dist = sqrt((double)dx * dx + (double)dy * dy);\n        int d = (int)lround(dist);          // round to nearest integer\n        edges[i] = {u, v, d, i};\n    }\n\n    /* ---------- build geometric MST (weight = d_i) ---------- */\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a, int b) {\n             if (edges[a].d != edges[b].d) return edges[a].d < edges[b].d;\n             return a < b;\n         });\n\n    DSU dsu_mst(N);\n    vector<char> inMST(M, 0);\n    int taken = 0;\n    for (int id : order) {\n        const Edge &e = edges[id];\n        if (dsu_mst.unite(e.u, e.v)) {\n            inMST[id] = 1;\n            ++taken;\n            if (taken == N - 1) break;\n        }\n    }\n\n    /* ---------- online phase ---------- */\n    DSU dsu(N);\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;                     // true length of edge i\n        bool accept = false;\n        if (inMST[i] && dsu.find(edges[i].u) != dsu.find(edges[i].v)) {\n            accept = true;\n            dsu.unite(edges[i].u, edges[i].v);\n        }\n        cout << (accept ? 1 : 0) << '\\n' << flush;\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pet   { int x, y, type; };\nstruct Human { int x, y; };\nstruct WallTask {\n    int px, py;      // human must stand here\n    char dir;        // lower\u2011case direction to build the wall\n    int tx, ty;      // target wall square\n};\n\nstatic const int H = 30;\ninline bool inside(int x, int y) { return 1 <= x && x <= H && 1 <= y && y <= H; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;  if (!(cin >> N)) return 0;\n    vector<Pet> pets(N);\n    for (auto &p : pets) cin >> p.x >> p.y >> p.type;\n\n    int M;  cin >> M;\n    vector<Human> humans(M);\n    for (auto &h : humans) cin >> h.x >> h.y;\n\n    // ----- board data -----\n    bool wall[31][31] = {};          // impassable squares\n    bool petOcc[31][31];\n    bool humanOcc[31][31];\n    bool wallTarget[31][31];         // squares that will become walls this turn\n\n    // ----- block generation (5\u00d75 blocks, spacing 7) -----\n    const int B = 5;                 // block side length (odd)\n    vector<pair<int,int>> blockTopLeft;\n    for (int rx = 1; rx + B - 1 <= H; rx += B + 2)\n        for (int ry = 1; ry + B - 1 <= H; ry += B + 2)\n            blockTopLeft.emplace_back(rx, ry);\n    vector<bool> blockUsed(blockTopLeft.size(), false);\n\n    // ----- human state machine -----\n    struct HState {\n        int state = 2;               // 0=go to centre, 1=build walls, 2=idle\n        int targetX = -1, targetY = -1;\n        vector<WallTask> tasks;\n        size_t taskIdx = 0;\n    };\n    vector<HState> hst(M);\n\n    // initial pet occupancy (only needed for block selection)\n    memset(petOcc, 0, sizeof(petOcc));\n    for (const auto &p : pets) petOcc[p.x][p.y] = true;\n\n    // assign a block to each human if possible\n    for (int i = 0; i < M; ++i) {\n        bool assigned = false;\n        for (size_t b = 0; b < blockTopLeft.size(); ++b) if (!blockUsed[b]) {\n            int rx = blockTopLeft[b].first;\n            int ry = blockTopLeft[b].second;\n            bool ok = true;\n            for (int x = rx; x < rx + B && ok; ++x)\n                for (int y = ry; y < ry + B; ++y)\n                    if (petOcc[x][y]) { ok = false; break; }\n            if (!ok) continue;\n            blockUsed[b] = true;\n            assigned = true;\n            // centre of the block\n            hst[i].targetX = rx + B/2;\n            hst[i].targetY = ry + B/2;\n            hst[i].state = 0;   // start moving\n            // generate wall tasks (perimeter)\n            vector<WallTask> tasks;\n            // top side (build upward)\n            for (int y = ry; y < ry + B; ++y) {\n                int tx = rx - 1, ty = y;\n                if (inside(tx, ty))\n                    tasks.push_back({rx, y, 'u', tx, ty});\n            }\n            // bottom side (build downward)\n            for (int y = ry; y < ry + B; ++y) {\n                int tx = rx + B, ty = y;\n                if (inside(tx, ty))\n                    tasks.push_back({rx + B - 1, y, 'd', tx, ty});\n            }\n            // left side (build leftward)\n            for (int x = rx; x < rx + B; ++x) {\n                int tx = x, ty = ry - 1;\n                if (inside(tx, ty))\n                    tasks.push_back({x, ry, 'l', tx, ty});\n            }\n            // right side (build rightward)\n            for (int x = rx; x < rx + B; ++x) {\n                int tx = x, ty = ry + B;\n                if (inside(tx, ty))\n                    tasks.push_back({x, ry + B - 1, 'r', tx, ty});\n            }\n            hst[i].tasks = std::move(tasks);\n            break;\n        }\n        if (!assigned) hst[i].state = 2;   // idle (no block)\n    }\n\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    const char moveChar[4] = {'U','D','L','R'};\n    const char wallChar[4] = {'u','d','l','r'};\n\n    auto canBuild = [&](int tx, int ty) -> bool {\n        if (!inside(tx, ty)) return false;\n        if (wall[tx][ty]) return false;\n        if (humanOcc[tx][ty]) return false;\n        if (petOcc[tx][ty]) return false;\n        for (int d = 0; d < 4; ++d) {\n            int nx = tx + dx[d], ny = ty + dy[d];\n            if (inside(nx, ny) && petOcc[nx][ny]) return false;\n        }\n        return true;\n    };\n\n    // ----- main simulation (300 turns) -----\n    for (int turn = 0; turn < 300; ++turn) {\n        // rebuild occupancy maps for the start of this turn\n        memset(petOcc, 0, sizeof(petOcc));\n        for (const auto &p : pets) petOcc[p.x][p.y] = true;\n        memset(humanOcc, 0, sizeof(humanOcc));\n        for (const auto &h : humans) humanOcc[h.x][h.y] = true;\n        memset(wallTarget, 0, sizeof(wallTarget));\n\n        string actions(M, '?');   // '?' will be replaced later\n\n        // ---------- first pass : try to build walls ----------\n        for (int i = 0; i < M; ++i) {\n            HState &st = hst[i];\n            Human &h = humans[i];\n            if (st.state == 1 && st.taskIdx < st.tasks.size()) {\n                const WallTask &wt = st.tasks[st.taskIdx];\n                if (h.x == wt.px && h.y == wt.py && canBuild(wt.tx, wt.ty)) {\n                    actions[i] = wt.dir;               // lower\u2011case\n                    wallTarget[wt.tx][wt.ty] = true;\n                    ++st.taskIdx;\n                    if (st.taskIdx >= st.tasks.size()) st.state = 2;\n                    continue;\n                }\n            }\n            actions[i] = '?';\n        }\n\n        // ---------- second pass : decide movements ----------\n        for (int i = 0; i < M; ++i) {\n            if (actions[i] != '?') continue;   // already a wall action\n            HState &st = hst[i];\n            Human &h = humans[i];\n            char chosen = '.';\n\n            // helper: try a direction, returns true if allowed\n            auto tryDir = [&](int d) -> bool {\n                int nx = h.x + dx[d], ny = h.y + dy[d];\n                if (!inside(nx, ny)) return false;\n                if (wall[nx][ny]) return false;\n                if (wallTarget[nx][ny]) return false;\n                chosen = moveChar[d];\n                return true;\n            };\n\n            if (st.state == 0) {                     // move to centre\n                if (h.x == st.targetX && h.y == st.targetY) {\n                    st.state = 1;                    // start building\n                } else {\n                    // move one step that reduces Manhattan distance\n                    int bestDist = INT_MAX, bestDir = -1;\n                    for (int d = 0; d < 4; ++d) {\n                        int nx = h.x + dx[d], ny = h.y + dy[d];\n                        if (!inside(nx, ny) || wall[nx][ny] || wallTarget[nx][ny]) continue;\n                        int dist = abs(nx - st.targetX) + abs(ny - st.targetY);\n                        if (dist < bestDist) {\n                            bestDist = dist;\n                            bestDir = d;\n                        }\n                    }\n                    if (bestDir != -1) chosen = moveChar[bestDir];\n                }\n            } else if (st.state == 1) {              // building walls\n                if (st.taskIdx < st.tasks.size()) {\n                    const WallTask &wt = st.tasks[st.taskIdx];\n                    if (h.x != wt.px || h.y != wt.py) {\n                        // move towards the required border cell\n                        int bestDist = INT_MAX, bestDir = -1;\n                        for (int d = 0; d < 4; ++d) {\n                            int nx = h.x + dx[d], ny = h.y + dy[d];\n                            if (!inside(nx, ny) || wall[nx][ny] || wallTarget[nx][ny]) continue;\n                            int dist = abs(nx - wt.px) + abs(ny - wt.py);\n                            if (dist < bestDist) {\n                                bestDist = dist;\n                                bestDir = d;\n                            }\n                        }\n                        if (bestDir != -1) chosen = moveChar[bestDir];\n                    } else {\n                        // at required position but cannot build now \u2192 move away from pets\n                        bool petAdj = false;\n                        for (int d = 0; d < 4; ++d) {\n                            int nx = h.x + dx[d], ny = h.y + dy[d];\n                            if (inside(nx, ny) && petOcc[nx][ny]) { petAdj = true; break; }\n                        }\n                        if (petAdj) {\n                            for (int d = 0; d < 4; ++d) {\n                                if (tryDir(d)) break;\n                            }\n                        } else {\n                            chosen = '.';\n                        }\n                    }\n                } else {\n                    // all tasks finished\n                    st.state = 2;\n                    chosen = '.';\n                }\n            } else {                                 // state == 2 (idle)\n                chosen = '.';\n            }\n            actions[i] = chosen;\n        }\n\n        // ---------- output ----------\n        cout << actions << '\\n' << flush;\n\n        // ---------- read pet moves ----------\n        vector<string> petMoves(N);\n        for (int i = 0; i < N; ++i) cin >> petMoves[i];\n\n        // ---------- apply walls ----------\n        for (int i = 0; i < M; ++i) {\n            char c = actions[i];\n            if (c >= 'a' && c <= 'z') {\n                int d = (c == 'u' ? 0 : (c == 'd' ? 1 : (c == 'l' ? 2 : 3)));\n                int tx = humans[i].x + dx[d];\n                int ty = humans[i].y + dy[d];\n                if (inside(tx, ty)) wall[tx][ty] = true;\n            }\n        }\n\n        // ---------- apply movements ----------\n        for (int i = 0; i < M; ++i) {\n            char c = actions[i];\n            if (c >= 'A' && c <= 'Z') {\n                int d = (c == 'U' ? 0 : (c == 'D' ? 1 : (c == 'L' ? 2 : 3)));\n                int nx = humans[i].x + dx[d];\n                int ny = humans[i].y + dy[d];\n                if (inside(nx, ny) && !wall[nx][ny]) {\n                    humans[i].x = nx;\n                    humans[i].y = ny;\n                }\n            }\n        }\n\n        // ---------- apply pet moves ----------\n        for (int i = 0; i < N; ++i) {\n            const string &s = petMoves[i];\n            for (char c : s) {\n                if (c == '.') continue;\n                int d = (c == 'U' ? 0 : (c == 'D' ? 1 : (c == 'L' ? 2 : 3)));\n                pets[i].x += dx[d];\n                pets[i].y += dy[d];\n                // the judge guarantees the move is legal\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 20;                 // grid size\nconstexpr int V = N * N;              // number of cells\nconstexpr int MAXLEN = 200;           // maximal output length\n\n// direction handling\nconst int di[4] = {-1, 1, 0, 0};\nconst int dj[4] = {0, 0, -1, 1};\nconst char dch[4] = {'U', 'D', 'L', 'R'};\ninline int dirIdx(char c) {\n    if (c == 'U') return 0;\n    if (c == 'D') return 1;\n    if (c == 'L') return 2;\n    return 3; // 'R'\n}\n\n// ------------------------------------------------------------\n// evaluate expected score of a given string (exact DP)\ndouble evaluate(const string& s,\n                const array<array<int,4>,V>& nxt,\n                int startId, int targetId, double p)\n{\n    const double stayProb = p;\n    const double moveProb = 1.0 - p;\n\n    static double cur[V];\n    static double nxtdp[V];\n    fill(begin(cur), end(cur), 0.0);\n    cur[startId] = 1.0;\n\n    double expected = 0.0;\n\n    for (int step = 0; step < (int)s.size(); ++step) {\n        fill(begin(nxtdp), end(nxtdp), 0.0);\n        int d = dirIdx(s[step]);\n        for (int v = 0; v < V; ++v) {\n            double prob = cur[v];\n            if (prob == 0.0) continue;\n            if (v == targetId) {\n                nxtdp[v] += prob;               // absorbing\n                continue;\n            }\n            int w = nxt[v][d];\n            // move remembered\n            nxtdp[w] += prob * moveProb;\n            // character forgotten\n            nxtdp[v] += prob * stayProb;\n        }\n        double newArrived = nxtdp[targetId] - cur[targetId];\n        expected += (401.0 - (step + 1)) * newArrived;\n        memcpy(cur, nxtdp, sizeof(cur));\n    }\n    return expected;\n}\n\n// ------------------------------------------------------------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj, ti, tj;\n    double p;\n    if (!(cin >> si >> sj >> ti >> tj >> p)) return 0;\n\n    // read walls\n    vector<string> h(N);          // horizontal, length 19\n    for (int i = 0; i < N; ++i) cin >> h[i];\n    vector<string> v(N-1);        // vertical, length 20\n    for (int i = 0; i < N-1; ++i) cin >> v[i];\n\n    // neighbour table: nxt[cell][direction] = destination cell\n    array<array<int,4>,V> nxt;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int id = i * N + j;\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d];\n                int nj = j + dj[d];\n                bool blocked = false;\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) {\n                    blocked = true;\n                } else {\n                    if (d == 0) { // U\n                        blocked = (v[i-1][j] == '1');\n                    } else if (d == 1) { // D\n                        blocked = (v[i][j] == '1');\n                    } else if (d == 2) { // L\n                        blocked = (h[i][j-1] == '1');\n                    } else { // R\n                        blocked = (h[i][j] == '1');\n                    }\n                }\n                if (blocked) nxt[id][d] = id;\n                else nxt[id][d] = ni * N + nj;\n            }\n        }\n    }\n\n    int startId = si * N + sj;\n    int targetId = ti * N + tj;\n\n    // --------------------------------------------------------\n    // 1) BFS from target to obtain a shortest path\n    vector<int> dist(V, -1);\n    vector<int> prevDir(V, -1);   // direction from predecessor to this cell\n    vector<int> prevCell(V, -1);\n    queue<int> q;\n    dist[targetId] = 0;\n    q.push(targetId);\n    while (!q.empty()) {\n        int vtx = q.front(); q.pop();\n        int vi = vtx / N, vj = vtx % N;\n        for (int d = 0; d < 4; ++d) {\n            int u = nxt[vtx][d];\n            if (u == vtx) continue;               // wall\n            if (dist[u] == -1) {\n                dist[u] = dist[vtx] + 1;\n                prevDir[u] = d ^ 1;               // opposite direction\n                prevCell[u] = vtx;\n                q.push(u);\n            }\n        }\n    }\n\n    // reconstruct one shortest path (forward direction)\n    string basePath;\n    int cur = startId;\n    while (cur != targetId && prevDir[cur] != -1) {\n        basePath.push_back(dch[prevDir[cur]]);\n        cur = prevCell[cur];\n    }\n\n    // --------------------------------------------------------\n    // 2) build initial answer: repeat the shortest path as many times as possible\n    string best;\n    if (!basePath.empty()) {\n        while ((int)best.size() + (int)basePath.size() <= MAXLEN) {\n            best += basePath;\n        }\n        int need = MAXLEN - (int)best.size();\n        if (need > 0 && need <= (int)basePath.size())\n            best += basePath.substr(0, need);\n    }\n    if (best.empty()) { // fallback (should never happen)\n        static const char dirs[4] = {'U','D','L','R'};\n        std::mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n        for (int i = 0; i < MAXLEN; ++i) best.push_back(dirs[rng() % 4]);\n    }\n\n    // --------------------------------------------------------\n    // 3) DP evaluation function (already defined above)\n    double bestScore = evaluate(best, nxt, startId, targetId, p);\n\n    // --------------------------------------------------------\n    // 4) random generator\n    std::mt19937_64 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    const char dirs[4] = {'U','D','L','R'};\n    uniform_real_distribution<double> real01(0.0, 1.0);\n    uniform_int_distribution<int> dirDist(0, 3);\n\n    // --------------------------------------------------------\n    // 5) generate a few biased random strings\n    const int BIASED_CANDIDATES = 500;\n    for (int it = 0; it < BIASED_CANDIDATES; ++it) {\n        string cand;\n        cand.reserve(MAXLEN);\n        int curCell = startId;\n        for (int pos = 0; pos < MAXLEN; ++pos) {\n            // collect the four possible directions\n            vector<int> candDir;\n            candDir.reserve(4);\n            for (int d = 0; d < 4; ++d) candDir.push_back(d);\n            // compute Manhattan distance after each move\n            int bestDist = INT_MAX;\n            for (int d : candDir) {\n                int nb = nxt[curCell][d];\n                int r = nb / N, c = nb % N;\n                int dist = abs(r - ti) + abs(c - tj);\n                if (dist < bestDist) bestDist = dist;\n            }\n            vector<int> good;\n            for (int d : candDir) {\n                int nb = nxt[curCell][d];\n                int r = nb / N, c = nb % N;\n                int dist = abs(r - ti) + abs(c - tj);\n                if (dist == bestDist) good.push_back(d);\n            }\n            int chosen;\n            if (real01(rng) < 0.8 && !good.empty())\n                chosen = good[dirDist(rng) % good.size()];\n            else\n                chosen = candDir[dirDist(rng) % candDir.size()];\n            cand.push_back(dirs[chosen]);\n            curCell = nxt[curCell][chosen];\n        }\n        double sc = evaluate(cand, nxt, startId, targetId, p);\n        if (sc > bestScore) {\n            bestScore = sc;\n            best = cand;\n        }\n    }\n\n    // --------------------------------------------------------\n    // 6) hill\u2011climbing (local search)\n    const double TIME_LIMIT = 1.80; // seconds\n    auto startTime = chrono::steady_clock::now();\n\n    while (true) {\n        double elapsed = chrono::duration<double>(chrono::steady_clock::now() - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        // mutate a copy of the current best string\n        string cand = best;\n        // pick a random position and replace it\n        int pos = uniform_int_distribution<int>(0, (int)cand.size() - 1)(rng);\n        cand[pos] = dirs[dirDist(rng)];\n        double sc = evaluate(cand, nxt, startId, targetId, p);\n        if (sc >= bestScore) {\n            bestScore = sc;\n            best = cand;\n        }\n    }\n\n    // --------------------------------------------------------\n    cout << best << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;\nconstexpr int DIR = 4;\nconstexpr int TOTAL = N * N * DIR;          // 30*30*4 = 3600\nconstexpr int di[DIR] = {0, -1, 0, 1};       // left, up, right, down\nconstexpr int dj[DIR] = {-1, 0, 1, 0};\n\nint tile[N][N];                              // original tile types\n\n// base connection table from the statement\nconst int base_to[8][4] = {\n    { 1, 0,-1,-1},\n    { 3,-1,-1, 0},\n    {-1,-1, 3, 2},\n    {-1, 2, 1,-1},\n    { 1, 0, 3, 2},\n    { 3, 2, 1, 0},\n    { 2,-1, 0,-1},\n    {-1, 3,-1, 1}\n};\n\nint to_rot[8][4][4];                         // after rotation\n\ninline int idx(int i, int j, int d) { return ((i * N + j) * DIR + d); }\n\n// ------------------------------------------------------------\n// fast Xorshift64 PRNG\nstruct XorShift {\n    uint64_t x;\n    XorShift() { x = chrono::steady_clock::now().time_since_epoch().count(); }\n    uint32_t next() {\n        x ^= x << 13;\n        x ^= x >> 7;\n        x ^= x << 17;\n        return static_cast<uint32_t>(x);\n    }\n    uint32_t next(uint32_t n) { return next() % n; }\n    double nextDouble() { return (next() >> 11) * (1.0 / 9007199254740992.0); }\n};\n// ------------------------------------------------------------\n\n// ------------------------------------------------------------\n// compute the score (L1 * L2) for a given rotation vector (size 900)\nint computeScore(const vector<int>& rot) {\n    static int nxt[TOTAL];\n    fill(nxt, nxt + TOTAL, -1);\n\n    // build outgoing edges\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int t = tile[i][j];\n            int r = rot[i * N + j];\n            for (int d = 0; d < DIR; ++d) {\n                int d2 = to_rot[t][r][d];\n                if (d2 == -1) continue;\n                int ni = i + di[d2];\n                int nj = j + dj[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) & 3;\n                nxt[idx(i, j, d)] = idx(ni, nj, nd);\n            }\n        }\n    }\n\n    static uint8_t state[TOTAL];   // 0 = unvisited, 1 = in current walk, 2 = finished\n    static int pos[TOTAL];\n    fill(state, state + TOTAL, 0);\n    fill(pos, pos + TOTAL, -1);\n\n    int best1 = 0, best2 = 0;\n    vector<int> path;\n    path.reserve(TOTAL);\n\n    for (int v = 0; v < TOTAL; ++v) {\n        if (state[v]) continue;\n        int cur = v;\n        while (true) {\n            if (cur == -1) break;\n            if (state[cur] == 0) {\n                state[cur] = 1;\n                pos[cur] = static_cast<int>(path.size());\n                path.push_back(cur);\n                cur = nxt[cur];\n            } else if (state[cur] == 1) {\n                int len = static_cast<int>(path.size()) - pos[cur];\n                if (len > best1) { best2 = best1; best1 = len; }\n                else if (len > best2) { best2 = len; }\n                break;\n            } else { // state[cur] == 2\n                break;\n            }\n        }\n        for (int node : path) {\n            state[node] = 2;\n            pos[node] = -1;\n        }\n        path.clear();\n    }\n    if (best2 == 0) return 0;\n    return best1 * best2;\n}\n// ------------------------------------------------------------\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read input\n    for (int i = 0; i < N; ++i) {\n        string line; cin >> line;\n        for (int j = 0; j < N; ++j) tile[i][j] = line[j] - '0';\n    }\n\n    // pre\u2011compute to_rot\n    for (int t = 0; t < 8; ++t) {\n        for (int r = 0; r < 4; ++r) {\n            for (int d = 0; d < 4; ++d) {\n                int local = (d - r + 4) & 3;\n                int out = base_to[t][local];\n                if (out == -1) to_rot[t][r][d] = -1;\n                else to_rot[t][r][d] = (out + r) & 3;\n            }\n        }\n    }\n\n    XorShift rng;\n    vector<int> cur(900), best(900);\n    for (int i = 0; i < 900; ++i) cur[i] = rng.next(4);\n    int curScore = computeScore(cur);\n    best = cur;\n    int bestScore = curScore;\n\n    const double TIME_LIMIT = 1.9;          // seconds\n    const double T0 = 50000.0;              // initial temperature\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        int idx = rng.next(900);\n        int oldR = cur[idx];\n        int newR = rng.next(4);\n        if (newR == oldR) continue;\n        cur[idx] = newR;\n        int newScore = computeScore(cur);\n        int delta = newScore - curScore;\n\n        bool accept = false;\n        if (delta >= 0) accept = true;\n        else {\n            double T = T0 * (1.0 - elapsed / TIME_LIMIT);\n            if (T < 1e-9) T = 1e-9;\n            double prob = exp(delta / T);\n            if (rng.nextDouble() < prob) accept = true;\n        }\n\n        if (accept) {\n            curScore = newScore;\n            if (newScore > bestScore) {\n                bestScore = newScore;\n                best = cur;\n            }\n        } else {\n            cur[idx] = oldR; // revert\n        }\n    }\n\n    // output best solution\n    string out;\n    out.reserve(900);\n    for (int i = 0; i < 900; ++i) out.push_back(char('0' + best[i]));\n    cout << out << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ------------------------------------------------------------\n// conversion from hexadecimal character to integer mask (0\u201115)\ninline int hexCharToInt(char c) {\n    if ('0' <= c && c <= '9') return c - '0';\n    return 10 + (c - 'a');\n}\n\n// ------------------------------------------------------------\nconstexpr int DR[4] = {-1, 1, 0, 0};          // U D L R\nconstexpr int DC[4] = {0, 0, -1, 1};\nconstexpr char DIR_CHAR[4] = {'U', 'D', 'L', 'R'};\nconstexpr int DIR_MASK[4] = {2, 8, 1, 4};     // up, down, left, right\nconstexpr int OPP[4] = {1, 0, 3, 2};         // opposite direction index\n\n// ------------------------------------------------------------\n// compute the size of the largest tree component\nint largestTreeSize(const vector<uint8_t> &board, int N) {\n    const int SZ = N * N;\n    static bool visited[100];\n    for (int i = 0; i < SZ; ++i) visited[i] = false;\n    int best = 0;\n\n    static int q[100];\n    for (int start = 0; start < SZ; ++start) {\n        if (board[start] == 0 || visited[start]) continue;\n        int head = 0, tail = 0;\n        q[tail++] = start;\n        visited[start] = true;\n        int verts = 0, edges = 0;\n        while (head < tail) {\n            int pos = q[head++];\n            ++verts;\n            int r = pos / N, c = pos % N;\n            int mask = board[pos];\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + DR[d];\n                int nc = c + DC[d];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                int npos = nr * N + nc;\n                if (board[npos] == 0) continue;\n                if ((mask & DIR_MASK[d]) && (board[npos] & DIR_MASK[OPP[d]])) {\n                    // count each undirected edge only once (down or right)\n                    if (d == 1 || d == 3) ++edges;\n                    if (!visited[npos]) {\n                        visited[npos] = true;\n                        q[tail++] = npos;\n                    }\n                }\n            }\n        }\n        if (edges == verts - 1) best = max(best, verts);\n    }\n    return best;\n}\n\n// ------------------------------------------------------------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    long long T;\n    if (!(cin >> N >> T)) return 0;\n    const int SZ = N * N;\n    vector<uint8_t> origBoard(SZ);\n    int emptyPos = -1;\n\n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) {\n            int v = hexCharToInt(row[j]);\n            origBoard[i * N + j] = static_cast<uint8_t>(v);\n            if (v == 0) emptyPos = i * N + j;\n        }\n    }\n\n    const int totalTiles = SZ - 1;\n    string bestSeq;\n    int bestScore = 0;\n\n    // --------------------------------------------------------\n    // 1) Greedy baseline (never accept a decreasing move)\n    {\n        vector<uint8_t> board = origBoard;\n        int empty = emptyPos;\n        string seq;\n        int curScore = largestTreeSize(board, N);\n        int bestLocalScore = curScore;\n        string bestLocalSeq = \"\";\n\n        for (long long step = 0; step < T; ++step) {\n            // legal moves\n            vector<int> cand;\n            int er = empty / N, ec = empty % N;\n            for (int d = 0; d < 4; ++d) {\n                int nr = er + DR[d], nc = ec + DC[d];\n                if (0 <= nr && nr < N && 0 <= nc && nc < N) cand.push_back(d);\n            }\n            if (cand.empty()) break;\n\n            int bestMoveScore = -1;\n            vector<int> bestMoves;\n            for (int d : cand) {\n                int nr = er + DR[d], nc = ec + DC[d];\n                int npos = nr * N + nc;\n                swap(board[empty], board[npos]);\n                int ns = largestTreeSize(board, N);\n                swap(board[empty], board[npos]); // revert\n                if (ns > bestMoveScore) {\n                    bestMoveScore = ns;\n                    bestMoves.clear();\n                    bestMoves.push_back(d);\n                } else if (ns == bestMoveScore) {\n                    bestMoves.push_back(d);\n                }\n            }\n\n            if (bestMoveScore < curScore) break; // no non\u2011decreasing move\n\n            static std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n            int chosen = bestMoves[uniform_int_distribution<int>(0, (int)bestMoves.size() - 1)(rng)];\n            int nr = er + DR[chosen], nc = ec + DC[chosen];\n            int npos = nr * N + nc;\n            swap(board[empty], board[npos]);\n            empty = npos;\n            seq.push_back(DIR_CHAR[chosen]);\n            curScore = bestMoveScore;\n\n            if (curScore > bestLocalScore ||\n                (curScore == bestLocalScore && seq.size() < bestLocalSeq.size())) {\n                bestLocalScore = curScore;\n                bestLocalSeq = seq;\n                if (bestLocalScore == totalTiles) break;\n            }\n        }\n        bestSeq = bestLocalSeq;\n        bestScore = bestLocalScore;\n        if (bestScore == totalTiles) {\n            cout << bestSeq << \"\\n\";\n            return 0;\n        }\n    }\n\n    // --------------------------------------------------------\n    // 2) Simulated annealing (randomised hill\u2011climbing)\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_real_distribution<double> probDist(0.0, 1.0);\n    auto startTime = chrono::steady_clock::now();\n    const double TIME_LIMIT = 2.8; // seconds, leave margin for I/O\n\n    while (true) {\n        // time check\n        double elapsed = chrono::duration<double>(chrono::steady_clock::now() - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        vector<uint8_t> board = origBoard;\n        int empty = emptyPos;\n        string curSeq;\n        int curScore = largestTreeSize(board, N);\n        double temperature = 1.0;\n\n        for (long long step = 0; step < T; ++step) {\n            // legal moves\n            vector<int> cand;\n            int er = empty / N, ec = empty % N;\n            for (int d = 0; d < 4; ++d) {\n                int nr = er + DR[d], nc = ec + DC[d];\n                if (0 <= nr && nr < N && 0 <= nc && nc < N) cand.push_back(d);\n            }\n            if (cand.empty()) break;\n\n            int d = cand[uniform_int_distribution<int>(0, (int)cand.size() - 1)(rng)];\n            int nr = er + DR[d], nc = ec + DC[d];\n            int npos = nr * N + nc;\n            swap(board[empty], board[npos]);\n            int newScore = largestTreeSize(board, N);\n            int delta = newScore - curScore;\n\n            bool accept = false;\n            if (delta >= 0) {\n                accept = true;\n            } else {\n                double prob = exp(delta / temperature);\n                if (probDist(rng) < prob) accept = true;\n            }\n\n            if (accept) {\n                empty = npos;\n                curScore = newScore;\n                curSeq.push_back(DIR_CHAR[d]);\n\n                if (curScore > bestScore ||\n                    (curScore == bestScore && curSeq.size() < bestSeq.size())) {\n                    bestScore = curScore;\n                    bestSeq = curSeq;\n                    if (bestScore == totalTiles) break;\n                }\n            } else {\n                // revert the swap\n                swap(board[empty], board[npos]);\n            }\n\n            temperature *= 0.9995; // slow cooling\n        }\n\n        if (bestScore == totalTiles) break;\n    }\n\n    cout << bestSeq << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, K_input;\n    if (!(cin >> N >> K_input)) return 0;          // K_input is always 100\n    vector<int> a(11);\n    for (int d = 1; d <= 10; ++d) cin >> a[d];\n\n    vector<pair<ll,ll>> strawberries(N);\n    for (int i = 0; i < N; ++i) {\n        ll x, y;\n        cin >> x >> y;\n        strawberries[i] = {x, y};\n    }\n\n    const ll R = 10000;          // cake radius\n    const ll M = 20000;          // far outside the cake, still inside limits\n    const int MAX_CUTS = 100;    // maximal number of cuts (fixed)\n\n    // candidate (V,H) pairs, all satisfy V+H <= 100\n    const vector<pair<int,int>> candidates = {\n        {10,10}, {12,8}, {8,12}, {15,5}, {5,15},\n        {20,0}, {0,20},\n        {30,10}, {10,30},\n        {25,25},\n        {40,20}, {20,40},\n        {50,10}, {10,50}\n    };\n\n    std::mt19937_64 rng(\n        std::chrono::steady_clock::now().time_since_epoch().count());\n\n    int bestScore = -1;\n    int bestV = 0, bestH = 0;\n    int bestOffsetX = 0, bestOffsetY = 0;\n\n    const int ATTEMPTS_PER_SHAPE = 200;   // enough to explore offsets\n\n    for (auto [V, H] : candidates) {\n        if (V + H > MAX_CUTS) continue;   // safety\n\n        int stepV = (V == 0) ? 0 : (int)(2 * R / (V + 1));\n        int stepH = (H == 0) ? 0 : (int)(2 * R / (H + 1));\n\n        for (int att = 0; att < ATTEMPTS_PER_SHAPE; ++att) {\n            int offsetX = (stepV > 0) ? uniform_int_distribution<int>(0, stepV - 1)(rng) : 0;\n            int offsetY = (stepH > 0) ? uniform_int_distribution<int>(0, stepH - 1)(rng) : 0;\n\n            // build line positions\n            vector<int> vlines, hlines;\n            vlines.reserve(V);\n            hlines.reserve(H);\n            for (int i = 1; i <= V; ++i) {\n                ll X = -R + offsetX + (ll)i * stepV;\n                vlines.push_back((int)X);\n            }\n            for (int j = 1; j <= H; ++j) {\n                ll Y = -R + offsetY + (ll)j * stepH;\n                hlines.push_back((int)Y);\n            }\n\n            // piece counters\n            vector<int> cnt((V + 1) * (H + 1), 0);\n\n            for (auto [x, y] : strawberries) {\n                int idxX = 0, idxY = 0;\n\n                if (V > 0) {\n                    auto itx = lower_bound(vlines.begin(), vlines.end(), (int)x);\n                    if (itx != vlines.end() && *itx == (int)x) continue; // on vertical line\n                    idxX = int(itx - vlines.begin());\n                }\n                if (H > 0) {\n                    auto ity = lower_bound(hlines.begin(), hlines.end(), (int)y);\n                    if (ity != hlines.end() && *ity == (int)y) continue; // on horizontal line\n                    idxY = int(ity - hlines.begin());\n                }\n\n                int cell = idxX * (H + 1) + idxY;\n                cnt[cell]++;\n            }\n\n            int b[11] = {0};\n            for (int c : cnt) {\n                if (1 <= c && c <= 10) b[c]++;\n            }\n            int score = 0;\n            for (int d = 1; d <= 10; ++d) score += min(a[d], b[d]);\n\n            if (score > bestScore) {\n                bestScore = score;\n                bestV = V; bestH = H;\n                bestOffsetX = offsetX;\n                bestOffsetY = offsetY;\n            }\n        }\n    }\n\n    // Build the best grid\n    vector<int> vlines, hlines;\n    int stepV = (bestV == 0) ? 0 : (int)(2 * R / (bestV + 1));\n    int stepH = (bestH == 0) ? 0 : (int)(2 * R / (bestH + 1));\n    for (int i = 1; i <= bestV; ++i) {\n        ll X = -R + bestOffsetX + (ll)i * stepV;\n        vlines.push_back((int)X);\n    }\n    for (int j = 1; j <= bestH; ++j) {\n        ll Y = -R + bestOffsetY + (ll)j * stepH;\n        hlines.push_back((int)Y);\n    }\n\n    cout << bestV + bestH << \"\\n\";\n    for (int X : vlines) {\n        cout << X << ' ' << -M << ' ' << X << ' ' << M << \"\\n\";\n    }\n    for (int Y : hlines) {\n        cout << -M << ' ' << Y << ' ' << M << ' ' << Y << \"\\n\";\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int x1, y1, x2, y2, x3, y3, x4, y4;\n};\n\nstruct Cell {\n    int x, y;\n    long long w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<vector<char>> dot(N, vector<char>(N, 0));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        dot[x][y] = 1;\n    }\n\n    // used[x][y][dir] : 0 = right, 1 = up, 2 = left, 3 = down\n    vector<vector<array<char,4>>> used(N, vector<array<char,4>>(N));\n    for (int x = 0; x < N; ++x)\n        for (int y = 0; y < N; ++y)\n            used[x][y].fill(0);\n\n    // cells sorted by weight (farther from centre first)\n    long long c = (N - 1) / 2;\n    vector<Cell> cells;\n    cells.reserve(N * N);\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y < N; ++y) {\n            long long w = (x - c) * (x - c) + (y - c) * (y - c) + 1;\n            cells.push_back({x, y, w});\n        }\n    }\n    sort(cells.begin(), cells.end(),\n         [](const Cell& a, const Cell& b){ return a.w > b.w; });\n\n    // helpers for edge handling\n    auto markEdge = [&](int x, int y, int dir) {\n        used[x][y][dir] = 1;\n        int nx = x + (dir == 0) - (dir == 2);\n        int ny = y + (dir == 1) - (dir == 3);\n        used[nx][ny][dir ^ 2] = 1;\n    };\n    auto edgeFreeHorizontal = [&](int x1, int x2, int y) -> bool {\n        for (int x = x1; x < x2; ++x) if (used[x][y][0]) return false;\n        return true;\n    };\n    auto edgeFreeVertical = [&](int y1, int y2, int x) -> bool {\n        for (int y = y1; y < y2; ++y) if (used[x][y][1]) return false;\n        return true;\n    };\n\n    vector<Op> ops;\n    bool added = true;\n    while (added) {\n        added = false;\n        for (const Cell& cell : cells) {\n            int x = cell.x, y = cell.y;\n            if (dot[x][y]) continue;          // already occupied\n\n            bool done = false;\n\n            // ----- orientation 0 : missing bottom\u2011left (x,y) -----\n            for (int x2 = x + 1; x2 < N && !done; ++x2) {\n                if (!dot[x2][y]) continue;\n                for (int y2 = y + 1; y2 < N && !done; ++y2) {\n                    if (!dot[x][y2] || !dot[x2][y2]) continue;\n\n                    // check perimeter for other dots\n                    bool ok = true;\n                    // bottom side\n                    for (int xx = x; xx <= x2 && ok; ++xx) {\n                        if (xx == x && y == y) continue;\n                        if (xx == x2 && y == y) continue;\n                        if (xx == x && y == y2) continue;\n                        if (xx == x2 && y == y2) continue;\n                        if (dot[xx][y]) ok = false;\n                    }\n                    // top side\n                    for (int xx = x; xx <= x2 && ok; ++xx) {\n                        if (xx == x && y2 == y) continue;\n                        if (xx == x2 && y2 == y) continue;\n                        if (xx == x && y2 == y2) continue;\n                        if (xx == x2 && y2 == y2) continue;\n                        if (dot[xx][y2]) ok = false;\n                    }\n                    // left side\n                    for (int yy = y; yy <= y2 && ok; ++yy) {\n                        if (x == x && yy == y) continue;\n                        if (x2 == x && yy == y) continue;\n                        if (x == x && yy == y2) continue;\n                        if (x2 == x && yy == y2) continue;\n                        if (dot[x][yy]) ok = false;\n                    }\n                    // right side\n                    for (int yy = y; yy <= y2 && ok; ++yy) {\n                        if (x2 == x && yy == y) continue;\n                        if (x2 == x2 && yy == y) continue;\n                        if (x2 == x && yy == y2) continue;\n                        if (x2 == x2 && yy == y2) continue;\n                        if (dot[x2][yy]) ok = false;\n                    }\n                    if (!ok) continue;\n\n                    // edge usage check\n                    if (!edgeFreeHorizontal(x, x2, y)) continue;\n                    if (!edgeFreeHorizontal(x, x2, y2)) continue;\n                    if (!edgeFreeVertical(y, y2, x)) continue;\n                    if (!edgeFreeVertical(y, y2, x2)) continue;\n\n                    // all good \u2013 add rectangle\n                    Op op;\n                    op.x1 = x; op.y1 = y;\n                    op.x2 = x2; op.y2 = y;\n                    op.x3 = x2; op.y3 = y2;\n                    op.x4 = x;  op.y4 = y2;\n                    ops.push_back(op);\n                    dot[x][y] = 1;\n                    // mark edges\n                    for (int xx = x; xx < x2; ++xx) {\n                        markEdge(xx, y, 0);      // bottom\n                        markEdge(xx, y2, 0);     // top\n                    }\n                    for (int yy = y; yy < y2; ++yy) {\n                        markEdge(x, yy, 1);      // left\n                        markEdge(x2, yy, 1);     // right\n                    }\n                    added = true;\n                    done = true;\n                }\n            }\n            if (done) break;\n\n            // ----- orientation 1 : missing bottom\u2011right (x,y) -----\n            for (int x1 = x - 1; x1 >= 0 && !done; --x1) {\n                if (!dot[x1][y]) continue;\n                for (int y2 = y + 1; y2 < N && !done; ++y2) {\n                    if (!dot[x][y2] || !dot[x1][y2]) continue;\n\n                    bool ok = true;\n                    // bottom side\n                    for (int xx = x1; xx <= x && ok; ++xx) {\n                        if (xx == x1 && y == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (xx == x1 && y == y2) continue;\n                        if (xx == x && y == y2) continue;\n                        if (dot[xx][y]) ok = false;\n                    }\n                    // top side\n                    for (int xx = x1; xx <= x && ok; ++xx) {\n                        if (xx == x1 && y2 == y) continue;\n                        if (xx == x && y2 == y) continue;\n                        if (xx == x1 && y2 == y2) continue;\n                        if (xx == x && y2 == y2) continue;\n                        if (dot[xx][y2]) ok = false;\n                    }\n                    // left side\n                    for (int yy = y; yy <= y2 && ok; ++yy) {\n                        if (x1 == x1 && yy == y) continue;\n                        if (x == x1 && yy == y) continue;\n                        if (x1 == x1 && yy == y2) continue;\n                        if (x == x1 && yy == y2) continue;\n                        if (dot[x1][yy]) ok = false;\n                    }\n                    // right side\n                    for (int yy = y; yy <= y2 && ok; ++yy) {\n                        if (x1 == x && yy == y) continue;\n                        if (x == x && yy == y) continue;\n                        if (x1 == x && yy == y2) continue;\n                        if (x == x && yy == y2) continue;\n                        if (dot[x][yy]) ok = false;\n                    }\n                    if (!ok) continue;\n\n                    if (!edgeFreeHorizontal(x1, x, y)) continue;\n                    if (!edgeFreeHorizontal(x1, x, y2)) continue;\n                    if (!edgeFreeVertical(y, y2, x1)) continue;\n                    if (!edgeFreeVertical(y, y2, x)) continue;\n\n                    Op op;\n                    op.x1 = x; op.y1 = y;\n                    op.x2 = x1; op.y2 = y;\n                    op.x3 = x1; op.y3 = y2;\n                    op.x4 = x;  op.y4 = y2;\n                    ops.push_back(op);\n                    dot[x][y] = 1;\n                    for (int xx = x1; xx < x; ++xx) {\n                        markEdge(xx, y, 0);\n                        markEdge(xx, y2, 0);\n                    }\n                    for (int yy = y; yy < y2; ++yy) {\n                        markEdge(x1, yy, 1);\n                        markEdge(x, yy, 1);\n                    }\n                    added = true;\n                    done = true;\n                }\n            }\n            if (done) break;\n\n            // ----- orientation 2 : missing top\u2011left (x,y) -----\n            for (int x2 = x + 1; x2 < N && !done; ++x2) {\n                if (!dot[x2][y]) continue;\n                for (int y1 = y - 1; y1 >= 0 && !done; --y1) {\n                    if (!dot[x][y1] || !dot[x2][y1]) continue;\n\n                    bool ok = true;\n                    // left side\n                    for (int yy = y1; yy <= y && ok; ++yy) {\n                        if (x == x && yy == y1) continue;\n                        if (x2 == x && yy == y1) continue;\n                        if (x == x && yy == y) continue;\n                        if (x2 == x && yy == y) continue;\n                        if (dot[x][yy]) ok = false;\n                    }\n                    // right side\n                    for (int yy = y1; yy <= y && ok; ++yy) {\n                        if (x2 == x2 && yy == y1) continue;\n                        if (x2 == x2 && yy == y) continue;\n                        if (x2 == x2 && yy == y1) continue;\n                        if (x2 == x2 && yy == y) continue;\n                        if (dot[x2][yy]) ok = false;\n                    }\n                    // bottom side\n                    for (int xx = x; xx <= x2 && ok; ++xx) {\n                        if (xx == x && y1 == y) continue;\n                        if (xx == x2 && y1 == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (xx == x2 && y == y) continue;\n                        if (dot[xx][y1]) ok = false;\n                    }\n                    // top side\n                    for (int xx = x; xx <= x2 && ok; ++xx) {\n                        if (xx == x && y == y) continue;\n                        if (xx == x2 && y == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (xx == x2 && y == y) continue;\n                        if (dot[xx][y]) ok = false;\n                    }\n                    if (!ok) continue;\n\n                    if (!edgeFreeHorizontal(x, x2, y1)) continue;\n                    if (!edgeFreeHorizontal(x, x2, y)) continue;\n                    if (!edgeFreeVertical(y1, y, x)) continue;\n                    if (!edgeFreeVertical(y1, y, x2)) continue;\n\n                    Op op;\n                    op.x1 = x; op.y1 = y;\n                    op.x2 = x;  op.y2 = y1;\n                    op.x3 = x2; op.y3 = y1;\n                    op.x4 = x2; op.y4 = y;\n                    ops.push_back(op);\n                    dot[x][y] = 1;\n                    for (int xx = x; xx < x2; ++xx) {\n                        markEdge(xx, y1, 0);\n                        markEdge(xx, y, 0);\n                    }\n                    for (int yy = y1; yy < y; ++yy) {\n                        markEdge(x, yy, 1);\n                        markEdge(x2, yy, 1);\n                    }\n                    added = true;\n                    done = true;\n                }\n            }\n            if (done) break;\n\n            // ----- orientation 3 : missing top\u2011right (x,y) -----\n            for (int x1 = x - 1; x1 >= 0 && !done; --x1) {\n                if (!dot[x1][y]) continue;\n                for (int y1 = y - 1; y1 >= 0 && !done; --y1) {\n                    if (!dot[x][y1] || !dot[x1][y1]) continue;\n\n                    bool ok = true;\n                    // left side\n                    for (int yy = y1; yy <= y && ok; ++yy) {\n                        if (x1 == x1 && yy == y1) continue;\n                        if (x == x1 && yy == y1) continue;\n                        if (x1 == x1 && yy == y) continue;\n                        if (x == x1 && yy == y) continue;\n                        if (dot[x1][yy]) ok = false;\n                    }\n                    // right side\n                    for (int yy = y1; yy <= y && ok; ++yy) {\n                        if (x1 == x && yy == y1) continue;\n                        if (x == x && yy == y1) continue;\n                        if (x1 == x && yy == y) continue;\n                        if (x == x && yy == y) continue;\n                        if (dot[x][yy]) ok = false;\n                    }\n                    // bottom side\n                    for (int xx = x1; xx <= x && ok; ++xx) {\n                        if (xx == x1 && y1 == y) continue;\n                        if (xx == x && y1 == y) continue;\n                        if (xx == x1 && y == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (dot[xx][y1]) ok = false;\n                    }\n                    // top side\n                    for (int xx = x1; xx <= x && ok; ++xx) {\n                        if (xx == x1 && y == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (xx == x1 && y == y) continue;\n                        if (xx == x && y == y) continue;\n                        if (dot[xx][y]) ok = false;\n                    }\n                    if (!ok) continue;\n\n                    if (!edgeFreeHorizontal(x1, x, y1)) continue;\n                    if (!edgeFreeHorizontal(x1, x, y)) continue;\n                    if (!edgeFreeVertical(y1, y, x1)) continue;\n                    if (!edgeFreeVertical(y1, y, x)) continue;\n\n                    Op op;\n                    op.x1 = x; op.y1 = y;\n                    op.x2 = x1; op.y2 = y;\n                    op.x3 = x1; op.y3 = y1;\n                    op.x4 = x;  op.y4 = y1;\n                    ops.push_back(op);\n                    dot[x][y] = 1;\n                    for (int xx = x1; xx < x; ++xx) {\n                        markEdge(xx, y1, 0);\n                        markEdge(xx, y, 0);\n                    }\n                    for (int yy = y1; yy < y; ++yy) {\n                        markEdge(x1, yy, 1);\n                        markEdge(x, yy, 1);\n                    }\n                    added = true;\n                    done = true;\n                }\n            }\n            if (done) break;\n        }\n    }\n\n    cout << ops.size() << \"\\n\";\n    for (const Op& o : ops) {\n        cout << o.x1 << ' ' << o.y1 << ' '\n             << o.x2 << ' ' << o.y2 << ' '\n             << o.x3 << ' ' << o.y3 << ' '\n             << o.x4 << ' ' << o.y4 << \"\\n\";\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* -------------------------------------------------------------\n   fast xorshift64 RNG\n   ------------------------------------------------------------- */\nstatic uint64_t rng_state = chrono::steady_clock::now().time_since_epoch().count();\ninline uint64_t xorshift64() {\n    rng_state ^= rng_state << 13;\n    rng_state ^= rng_state >> 7;\n    rng_state ^= rng_state << 17;\n    return rng_state;\n}\n\n/* -------------------------------------------------------------\n   Board \u2013 0 = empty, 1\u20113 = flavour\n   ------------------------------------------------------------- */\nstruct Board {\n    uint8_t a[100];\n};\n\n/* -------------------------------------------------------------\n   tilt the board in the given direction\n   ------------------------------------------------------------- */\ninline void tilt(Board &b, char dir) {\n    if (dir == 'L') {                     // left\n        for (int r = 0; r < 10; ++r) {\n            int write = r * 10;\n            for (int c = 0; c < 10; ++c) {\n                int idx = r * 10 + c;\n                if (b.a[idx]) {\n                    if (idx != write) {\n                        b.a[write] = b.a[idx];\n                        b.a[idx] = 0;\n                    }\n                    ++write;\n                }\n            }\n        }\n    } else if (dir == 'R') {              // right\n        for (int r = 0; r < 10; ++r) {\n            int write = r * 10 + 9;\n            for (int c = 9; c >= 0; --c) {\n                int idx = r * 10 + c;\n                if (b.a[idx]) {\n                    if (idx != write) {\n                        b.a[write] = b.a[idx];\n                        b.a[idx] = 0;\n                    }\n                    --write;\n                }\n            }\n        }\n    } else if (dir == 'F') {              // forward = up\n        for (int c = 0; c < 10; ++c) {\n            int write = c;\n            for (int r = 0; r < 10; ++r) {\n                int idx = r * 10 + c;\n                if (b.a[idx]) {\n                    if (idx != write) {\n                        b.a[write] = b.a[idx];\n                        b.a[idx] = 0;\n                    }\n                    write += 10;\n                }\n            }\n        }\n    } else {                              // dir == 'B'  backward = down\n        for (int c = 0; c < 10; ++c) {\n            int write = 9 * 10 + c;\n            for (int r = 9; r >= 0; --r) {\n                int idx = r * 10 + c;\n                if (b.a[idx]) {\n                    if (idx != write) {\n                        b.a[write] = b.a[idx];\n                        b.a[idx] = 0;\n                    }\n                    write -= 10;\n                }\n            }\n        }\n    }\n}\n\n/* -------------------------------------------------------------\n   \u03a3 size\u00b2 of all connected components (four\u2011directional)\n   ------------------------------------------------------------- */\ninline long long score(const Board &b) {\n    bool vis[100] = {};\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    long long sum = 0;\n    for (int i = 0; i < 100; ++i) if (b.a[i] && !vis[i]) {\n        uint8_t f = b.a[i];\n        int cnt = 0;\n        int q[100];\n        int qh = 0, qt = 0;\n        q[qt++] = i;\n        vis[i] = true;\n        while (qh < qt) {\n            int cur = q[qh++];\n            ++cnt;\n            int r = cur / 10, c = cur % 10;\n            for (int k = 0; k < 4; ++k) {\n                int nr = r + dx[k], nc = c + dy[k];\n                if (nr >= 0 && nr < 10 && nc >= 0 && nc < 10) {\n                    int nid = nr * 10 + nc;\n                    if (!vis[nid] && b.a[nid] == f) {\n                        vis[nid] = true;\n                        q[qt++] = nid;\n                    }\n                }\n            }\n        }\n        sum += 1LL * cnt * cnt;\n    }\n    return sum;\n}\n\n/* -------------------------------------------------------------\n   place a candy of flavour f into the p\u2011th empty cell (1\u2011based)\n   ------------------------------------------------------------- */\ninline void place(Board &b, uint8_t f, int p) {\n    int cnt = 0;\n    for (int i = 0; i < 100; ++i) {\n        if (b.a[i] == 0) {\n            ++cnt;\n            if (cnt == p) {\n                b.a[i] = f;\n                return;\n            }\n        }\n    }\n}\n\n/* -------------------------------------------------------------\n   collect indices of empty cells (0 \u2026 99)\n   ------------------------------------------------------------- */\ninline int collectEmpty(const Board &b, int *out) {\n    int cnt = 0;\n    for (int i = 0; i < 100; ++i) if (b.a[i] == 0) out[cnt++] = i;\n    return cnt;\n}\n\n/* -------------------------------------------------------------\n   greedy tilt \u2013 direction that maximises the immediate score\n   ------------------------------------------------------------- */\ninline char greedyTilt(const Board &b) {\n    const char dirs[4] = {'F','B','L','R'};\n    long long best = -1;\n    char bestDir = 'F';\n    for (char d : dirs) {\n        Board tmp = b;\n        tilt(tmp, d);\n        long long sc = score(tmp);\n        if (sc > best) {\n            best = sc;\n            bestDir = d;\n        }\n    }\n    return bestDir;\n}\n\n/* -------------------------------------------------------------\n   main\n   ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int TOTAL = 100;\n    vector<uint8_t> flavor(TOTAL);\n    for (int i = 0; i < TOTAL; ++i) {\n        int x; cin >> x;\n        flavor[i] = static_cast<uint8_t>(x);\n    }\n\n    Board board{};\n    memset(board.a, 0, sizeof(board.a));\n\n    const char DIRS[4] = {'F','B','L','R'};\n    const int K   = 30;          // look\u2011ahead depth\n    const int SIM = 20;          // Monte\u2011Carlo repetitions\n\n    int empties[100];\n\n    for (int t = 0; t < TOTAL; ++t) {\n        int p; cin >> p;\n        place(board, flavor[t], p);\n\n        if (t == TOTAL - 1) break;               // last candy \u2013 no tilt required\n\n        double bestEval = -1e100;\n        char bestDir = 'F';\n\n        for (char d : DIRS) {\n            Board tmp = board;\n            tilt(tmp, d);\n            long long imm = score(tmp);\n            double total = static_cast<double>(imm);\n\n            for (int s = 0; s < SIM; ++s) {\n                Board sim = tmp;\n                int curIdx = t + 1;\n                int remaining = TOTAL - curIdx;\n                int steps = min(K, remaining);\n                for (int step = 0; step < steps; ++step, ++curIdx) {\n                    int ecnt = collectEmpty(sim, empties);\n                    int idx = empties[xorshift64() % ecnt];\n                    sim.a[idx] = flavor[curIdx];\n                    char d2 = greedyTilt(sim);\n                    tilt(sim, d2);\n                }\n                total += static_cast<double>(score(sim));\n            }\n\n            double avg = total / (SIM + 1);\n            if (avg > bestEval) {\n                bestEval = avg;\n                bestDir = d;\n            }\n        }\n\n        cout << bestDir << '\\n';\n        cout.flush();\n\n        tilt(board, bestDir);          // apply the chosen tilt to the real board\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct GraphInfo {\n    string adjStr;               // binary representation (output)\n    vector<double> feat;         // feature vector (size = 8)\n};\n\ninline double sq(double x) { return x * x; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;          // no input\n\n    const int N = 6;                           // vertex count (small)\n    const int L = N * (N - 1) / 2;             // length of binary string\n    const int maxTri = N * (N - 1) * (N - 2) / 6; // C(N,3)\n    const int maxEdge = L;                     // maximum number of edges\n    const int D = N + 2;                       // feature dimension (8)\n\n    const int POOL = 8000;                     // pool size (\u226b M)\n    mt19937_64 rng(123456789ULL);              // deterministic RNG\n\n    vector<GraphInfo> pool;\n    pool.reserve(POOL);\n    unordered_set<string> usedStr;             // avoid duplicate graphs\n\n    // ---------- 1. generate pool ----------\n    while ((int)pool.size() < POOL) {\n        // ----- random adjacency -----\n        vector<vector<char>> adj(N, vector<char>(N, 0));\n        string s;\n        s.reserve(L);\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                bool edge = (rng() & 1ULL);\n                adj[i][j] = adj[j][i] = edge;\n                s.push_back(edge ? '1' : '0');\n            }\n        }\n        if (usedStr.find(s) != usedStr.end()) continue; // duplicate\n        usedStr.insert(s);\n\n        // ----- degree vector (sorted) -----\n        vector<int> deg(N);\n        for (int i = 0; i < N; ++i) {\n            int cnt = 0;\n            for (int j = 0; j < N; ++j) cnt += adj[i][j];\n            deg[i] = cnt;\n        }\n        sort(deg.begin(), deg.end());\n\n        // ----- edge count -----\n        int edges = 0;\n        for (int d : deg) edges += d;\n        edges /= 2; // each edge counted twice\n\n        // ----- triangle count -----\n        int tri = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = i + 1; j < N; ++j) if (adj[i][j])\n                for (int k = j + 1; k < N; ++k)\n                    if (adj[i][k] && adj[j][k]) ++tri;\n\n        // ----- feature vector -----\n        vector<double> feat;\n        feat.reserve(D);\n        for (int d : deg) feat.push_back(static_cast<double>(d) / (N - 1));\n        feat.push_back(static_cast<double>(edges) / maxEdge);\n        feat.push_back(static_cast<double>(tri) / maxTri);\n\n        GraphInfo gi;\n        gi.adjStr = std::move(s);\n        gi.feat = std::move(feat);\n        pool.push_back(std::move(gi));\n    }\n\n    // ---------- 2. greedy max\u2011min selection ----------\n    vector<int> selectedIdx;                // indices inside pool\n    selectedIdx.reserve(M);\n    vector<char> taken(pool.size(), 0);\n\n    selectedIdx.push_back(0);\n    taken[0] = 1;\n\n    vector<double> minDist(pool.size(), numeric_limits<double>::infinity());\n    auto dist = [&](const vector<double>& a, const vector<double>& b) {\n        double s = 0.0;\n        for (int i = 0; i < D; ++i) {\n            double diff = a[i] - b[i];\n            s += diff * diff;\n        }\n        return s;\n    };\n\n    // initialise distances to the first selected graph\n    for (size_t i = 1; i < pool.size(); ++i) {\n        minDist[i] = dist(pool[0].feat, pool[i].feat);\n    }\n\n    while ((int)selectedIdx.size() < M) {\n        // pick the candidate with maximal minimal distance\n        int best = -1;\n        double bestVal = -1.0;\n        for (size_t i = 0; i < pool.size(); ++i) if (!taken[i]) {\n            if (minDist[i] > bestVal) {\n                bestVal = minDist[i];\n                best = (int)i;\n            }\n        }\n        selectedIdx.push_back(best);\n        taken[best] = 1;\n\n        // update minimal distances\n        for (size_t i = 0; i < pool.size(); ++i) if (!taken[i]) {\n            double d = dist(pool[best].feat, pool[i].feat);\n            if (d < minDist[i]) minDist[i] = d;\n        }\n    }\n\n    // ---------- 3. output the chosen graphs ----------\n    cout << N << \"\\n\";\n    for (int idx : selectedIdx) {\n        cout << pool[idx].adjStr << \"\\n\";\n    }\n    cout.flush();\n\n    // ---------- 4. answer the 100 queries ----------\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // rebuild adjacency matrix of H\n        vector<vector<char>> adj(N, vector<char>(N, 0));\n        int pos = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                bool edge = (H[pos++] == '1');\n                adj[i][j] = adj[j][i] = edge;\n            }\n        }\n\n        // degree vector (sorted)\n        vector<int> deg(N);\n        for (int i = 0; i < N; ++i) {\n            int cnt = 0;\n            for (int j = 0; j < N; ++j) cnt += adj[i][j];\n            deg[i] = cnt;\n        }\n        sort(deg.begin(), deg.end());\n\n        // edge count\n        int edges = 0;\n        for (int d : deg) edges += d;\n        edges /= 2;\n\n        // triangle count\n        int tri = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = i + 1; j < N; ++j) if (adj[i][j])\n                for (int k = j + 1; k < N; ++k)\n                    if (adj[i][k] && adj[j][k]) ++tri;\n\n        // feature vector of H\n        vector<double> feat;\n        feat.reserve(D);\n        for (int d : deg) feat.push_back(static_cast<double>(d) / (N - 1));\n        feat.push_back(static_cast<double>(edges) / maxEdge);\n        feat.push_back(static_cast<double>(tri) / maxTri);\n\n        // nearest neighbour among the selected graphs\n        int bestIdx = 0;\n        double bestDist = numeric_limits<double>::infinity();\n        for (int i = 0; i < M; ++i) {\n            const vector<double>& cand = pool[selectedIdx[i]].feat;\n            double d = 0.0;\n            for (int j = 0; j < D; ++j) {\n                double diff = feat[j] - cand[j];\n                d += diff * diff;\n            }\n            if (d < bestDist) {\n                bestDist = d;\n                bestIdx = i;\n            }\n        }\n        cout << bestIdx << \"\\n\" << flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll INF = (1LL << 60);\n\nstruct Edge {\n    int u, v;\n    int w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[i] = {u, v, w};\n    }\n    // coordinates are irrelevant\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        (void)x; (void)y;\n    }\n\n    // ---------- adjacency ----------\n    vector<vector<tuple<int,int,int>>> adj(N);\n    vector<int> deg(N, 0);\n    for (int i = 0; i < M; ++i) {\n        int u = edges[i].u, v = edges[i].v, w = edges[i].w;\n        adj[u].push_back({v, w, i});\n        adj[v].push_back({u, w, i});\n        ++deg[u];\n        ++deg[v];\n    }\n\n    // ---------- exact weighted betweenness (Brandes) ----------\n    vector<double> edge_bc(M, 0.0);\n    vector<ll> dist(N);\n    vector<double> sigma(N);\n    vector<double> delta(N);\n    vector<vector<int>> pred(N);\n    vector<vector<int>> pred_e(N);\n    vector<int> order;\n    order.reserve(N);\n\n    for (int s = 0; s < N; ++s) {\n        fill(dist.begin(), dist.end(), INF);\n        fill(sigma.begin(), sigma.end(), 0.0);\n        for (int i = 0; i < N; ++i) {\n            pred[i].clear();\n            pred_e[i].clear();\n        }\n        order.clear();\n\n        dist[s] = 0;\n        sigma[s] = 1.0;\n        using PQItem = pair<ll,int>;\n        priority_queue<PQItem, vector<PQItem>, greater<PQItem>> pq;\n        pq.emplace(0LL, s);\n\n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d != dist[v]) continue;\n            order.push_back(v);\n            for (auto [to, wgt, eid] : adj[v]) {\n                ll nd = d + wgt;\n                if (nd < dist[to]) {\n                    dist[to] = nd;\n                    sigma[to] = sigma[v];\n                    pred[to].clear();\n                    pred_e[to].clear();\n                    pred[to].push_back(v);\n                    pred_e[to].push_back(eid);\n                    pq.emplace(nd, to);\n                } else if (nd == dist[to]) {\n                    sigma[to] += sigma[v];\n                    pred[to].push_back(v);\n                    pred_e[to].push_back(eid);\n                }\n            }\n        }\n\n        fill(delta.begin(), delta.end(), 0.0);\n        for (int idx = (int)order.size() - 1; idx >= 0; --idx) {\n            int w = order[idx];\n            for (size_t i = 0; i < pred[w].size(); ++i) {\n                int v = pred[w][i];\n                int eid = pred_e[w][i];\n                double coeff = (sigma[v] / sigma[w]) * (1.0 + delta[w]);\n                delta[v] += coeff;\n                edge_bc[eid] += coeff; // each direction once\n            }\n        }\n    }\n\n    // ---------- parameters ----------\n    double total_bc = 0.0;\n    for (double x : edge_bc) total_bc += x;\n    double avg_bc = total_bc / M;\n    const double LAMBDA = avg_bc * 0.5;          // balance factor\n    const double NOISE_EPS = avg_bc * 1e-6;      // tiny random noise\n\n    // ---------- random engine ----------\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n\n    // ---------- best schedule ----------\n    vector<int> best_day_of_edge;\n    double best_metric = numeric_limits<double>::infinity();\n\n    // time control\n    auto start_all = chrono::steady_clock::now();\n    const double TIME_LIMIT = 5.8; // seconds for the whole algorithm (betweenness already done)\n    const int MAX_ATTEMPTS = 12;\n\n    for (int attempt = 0; attempt < MAX_ATTEMPTS; ++attempt) {\n        if (chrono::duration<double>(chrono::steady_clock::now() - start_all).count() > TIME_LIMIT) break;\n\n        // ---- random order (betweenness + tiny noise) ----\n        vector<double> key(M);\n        for (int i = 0; i < M; ++i) key[i] = edge_bc[i] + std::uniform_real_distribution<double>(-NOISE_EPS, NOISE_EPS)(rng);\n        vector<int> order(M);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) { return key[a] > key[b]; });\n\n        // ---- greedy assignment ----\n        vector<int> day_of_edge(M, -1);\n        vector<double> day_sum(D, 0.0);\n        vector<int> day_cnt(D, 0);\n        vector<vector<int>> cnt(D, vector<int>(N, 0));\n        vector<long long> penalty_adj(D, 0); // \u03a3 C(cnt,2)\n        vector<vector<int>> edges_of_day(D);\n\n        for (int eid : order) {\n            const Edge &e = edges[eid];\n            int u = e.u, v = e.v;\n            int best_day = -1;\n            double best_score = numeric_limits<double>::infinity();\n\n            for (int d = 0; d < D; ++d) {\n                if (day_cnt[d] >= K) continue;\n                double new_sum = day_sum[d] + edge_bc[eid];\n                long long new_pen = penalty_adj[d] + cnt[d][u] + cnt[d][v];\n                double score = new_sum + LAMBDA * new_pen;\n                if (score < best_score) {\n                    best_score = score;\n                    best_day = d;\n                }\n            }\n\n            // assign\n            day_of_edge[eid] = best_day;\n            day_sum[best_day] += edge_bc[eid];\n            ++day_cnt[best_day];\n            edges_of_day[best_day].push_back(eid);\n            penalty_adj[best_day] += cnt[best_day][u] + cnt[best_day][v];\n            ++cnt[best_day][u];\n            ++cnt[best_day][v];\n        }\n\n        // ---- hill\u2011climbing local search ----\n        const double LOCAL_TIME = 4.5; // seconds for local search\n        auto start_local = chrono::steady_clock::now();\n\n        // current day scores\n        vector<double> day_score(D);\n        double cur_max = -1e100;\n        for (int d = 0; d < D; ++d) {\n            day_score[d] = day_sum[d] + LAMBDA * penalty_adj[d];\n            cur_max = max(cur_max, day_score[d]);\n        }\n\n        while (chrono::duration<double>(chrono::steady_clock::now() - start_local).count() < LOCAL_TIME) {\n            // ----- random move -----\n            {\n                int eid = std::uniform_int_distribution<int>(0, M - 1)(rng);\n                int src = day_of_edge[eid];\n                if (day_cnt[src] == 0) continue;\n                int dst = -1;\n                for (int tries = 0; tries < 5 && dst == -1; ++tries) {\n                    int cand = std::uniform_int_distribution<int>(0, D - 1)(rng);\n                    if (cand != src && day_cnt[cand] < K) dst = cand;\n                }\n                if (dst == -1) continue;\n\n                const Edge &e = edges[eid];\n                int u = e.u, v = e.v;\n\n                double new_sum_src = day_sum[src] - edge_bc[eid];\n                double new_sum_dst = day_sum[dst] + edge_bc[eid];\n                long long new_pen_src = penalty_adj[src] - (cnt[src][u] - 1) - (cnt[src][v] - 1);\n                long long new_pen_dst = penalty_adj[dst] + cnt[dst][u] + cnt[dst][v];\n                double new_score_src = new_sum_src + LAMBDA * new_pen_src;\n                double new_score_dst = new_sum_dst + LAMBDA * new_pen_dst;\n\n                double new_max = max(new_score_src, new_score_dst);\n                for (int d = 0; d < D; ++d) {\n                    if (d == src || d == dst) continue;\n                    new_max = max(new_max, day_score[d]);\n                }\n\n                if (new_max + 1e-9 < cur_max) {\n                    // commit move\n                    auto &vec_src = edges_of_day[src];\n                    auto it = find(vec_src.begin(), vec_src.end(), eid);\n                    if (it != vec_src.end()) {\n                        *it = vec_src.back();\n                        vec_src.pop_back();\n                    }\n                    edges_of_day[dst].push_back(eid);\n                    day_of_edge[eid] = dst;\n\n                    day_sum[src] = new_sum_src;\n                    day_sum[dst] = new_sum_dst;\n                    penalty_adj[src] = new_pen_src;\n                    penalty_adj[dst] = new_pen_dst;\n                    --cnt[src][u];\n                    --cnt[src][v];\n                    ++cnt[dst][u];\n                    ++cnt[dst][v];\n                    --day_cnt[src];\n                    ++day_cnt[dst];\n\n                    day_score[src] = new_score_src;\n                    day_score[dst] = new_score_dst;\n                    cur_max = new_max;\n                    continue;\n                }\n            }\n\n            // ----- random swap (limited) -----\n            {\n                // pick two distinct days that both contain at least one edge\n                int a = -1, b = -1;\n                for (int tries = 0; tries < 5 && (a == -1 || b == -1); ++tries) {\n                    int d1 = std::uniform_int_distribution<int>(0, D - 1)(rng);\n                    int d2 = std::uniform_int_distribution<int>(0, D - 1)(rng);\n                    if (d1 != d2 && !edges_of_day[d1].empty() && !edges_of_day[d2].empty()) {\n                        a = d1; b = d2;\n                    }\n                }\n                if (a == -1) break;\n\n                int eid1 = edges_of_day[a][std::uniform_int_distribution<int>(0, (int)edges_of_day[a].size() - 1)(rng)];\n                int eid2 = edges_of_day[b][std::uniform_int_distribution<int>(0, (int)edges_of_day[b].size() - 1)(rng)];\n                const Edge &E1 = edges[eid1];\n                const Edge &E2 = edges[eid2];\n                int u1 = E1.u, v1 = E1.v, u2 = E2.u, v2 = E2.v;\n\n                double new_sum_a = day_sum[a] - edge_bc[eid1] + edge_bc[eid2];\n                double new_sum_b = day_sum[b] - edge_bc[eid2] + edge_bc[eid1];\n                long long new_pen_a = penalty_adj[a]\n                                     - (cnt[a][u1] - 1) - (cnt[a][v1] - 1)\n                                     + cnt[a][u2] + cnt[a][v2];\n                long long new_pen_b = penalty_adj[b]\n                                     - (cnt[b][u2] - 1) - (cnt[b][v2] - 1)\n                                     + cnt[b][u1] + cnt[b][v1];\n                double new_score_a = new_sum_a + LAMBDA * new_pen_a;\n                double new_score_b = new_sum_b + LAMBDA * new_pen_b;\n\n                double new_max = max(new_score_a, new_score_b);\n                for (int d = 0; d < D; ++d) {\n                    if (d == a || d == b) continue;\n                    new_max = max(new_max, day_score[d]);\n                }\n\n                if (new_max + 1e-9 < cur_max) {\n                    // commit swap\n                    auto &vec_a = edges_of_day[a];\n                    auto &vec_b = edges_of_day[b];\n                    auto it_a = find(vec_a.begin(), vec_a.end(), eid1);\n                    auto it_b = find(vec_b.begin(), vec_b.end(), eid2);\n                    if (it_a != vec_a.end()) *it_a = eid2;\n                    if (it_b != vec_b.end()) *it_b = eid1;\n                    day_of_edge[eid1] = b;\n                    day_of_edge[eid2] = a;\n\n                    day_sum[a] = new_sum_a;\n                    day_sum[b] = new_sum_b;\n                    penalty_adj[a] = new_pen_a;\n                    penalty_adj[b] = new_pen_b;\n\n                    --cnt[a][u1]; --cnt[a][v1];\n                    ++cnt[a][u2]; ++cnt[a][v2];\n                    --cnt[b][u2]; --cnt[b][v2];\n                    ++cnt[b][u1]; ++cnt[b][v1];\n\n                    day_score[a] = new_score_a;\n                    day_score[b] = new_score_b;\n                    cur_max = new_max;\n                    continue;\n                }\n            }\n\n            // no improving move or swap found\n            break;\n        }\n\n        // ----- evaluate this schedule -----\n        if (cur_max < best_metric) {\n            best_metric = cur_max;\n            best_day_of_edge = day_of_edge;\n        }\n    }\n\n    // ---------- output ----------\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << best_day_of_edge[i] + 1;   // convert to 1\u2011based\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* 24 orientation\u2011preserving rotations of a cube */\nstruct Rot {\n    int perm[3];   // which original axis goes to x',y',z'\n    int sign[3];   // +/-1 for each axis\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D;\n    if (!(cin >> D)) return 0;\n    const int N = D * D * D;\n\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n\n    auto idx = [&](int x, int y, int z) { return x * D * D + y * D + z; };\n    const int dx[6] = {1,-1,0,0,0,0};\n    const int dy[6] = {0,0,1,-1,0,0};\n    const int dz[6] = {0,0,0,0,1,-1};\n\n    // -------------------------------------------------\n    // 1) need0 , need1 , shared\n    vector<char> need0(N,0), need1(N,0), shared(N,0);\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                int id = idx(x, y, z);\n                need0[id] = (f[0][z][x] == '1') && (r[0][z][y] == '1');\n                need1[id] = (f[1][z][x] == '1') && (r[1][z][y] == '1');\n                shared[id] = need0[id] && need1[id];\n            }\n        }\n    }\n\n    vector<int> b0(N,0), b1(N,0);\n    int cur_id = 1;\n\n    // -------------------------------------------------\n    // 2) shared components (appear in both objects)\n    vector<char> visited(N,0);\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                int start = idx(x, y, z);\n                if (!shared[start] || visited[start]) continue;\n                queue<int> q;\n                q.push(start);\n                visited[start] = 1;\n                while (!q.empty()) {\n                    int v = q.front(); q.pop();\n                    b0[v] = b1[v] = cur_id;\n                    int cx = v / (D * D);\n                    int cy = (v / D) % D;\n                    int cz = v % D;\n                    for (int dir = 0; dir < 6; ++dir) {\n                        int nx = cx + dx[dir];\n                        int ny = cy + dy[dir];\n                        int nz = cz + dz[dir];\n                        if (nx < 0 || nx >= D || ny < 0 || ny >= D || nz < 0 || nz >= D) continue;\n                        int nid = idx(nx, ny, nz);\n                        if (shared[nid] && !visited[nid]) {\n                            visited[nid] = 1;\n                            q.push(nid);\n                        }\n                    }\n                }\n                ++cur_id;\n            }\n        }\n    }\n\n    // -------------------------------------------------\n    // 3) exclusive components\n    vector<char> excl0(N,0), excl1(N,0);\n    for (int i = 0; i < N; ++i) {\n        excl0[i] = need0[i] && !shared[i];\n        excl1[i] = need1[i] && !shared[i];\n    }\n\n    struct Component {\n        vector<int> cells;                // linear indices\n        vector<array<int,3>> coord;       // (x,y,z) for each cell\n    };\n    vector<Component> comp0, comp1;\n\n    auto bfs_components = [&](const vector<char>& mask,\n                              vector<Component>& out) {\n        vector<char> seen(N,0);\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    int start = idx(x, y, z);\n                    if (!mask[start] || seen[start]) continue;\n                    Component c;\n                    queue<int> q;\n                    q.push(start);\n                    seen[start] = 1;\n                    while (!q.empty()) {\n                        int v = q.front(); q.pop();\n                        c.cells.push_back(v);\n                        int cx = v / (D * D);\n                        int cy = (v / D) % D;\n                        int cz = v % D;\n                        c.coord.push_back({cx,cy,cz});\n                        for (int dir = 0; dir < 6; ++dir) {\n                            int nx = cx + dx[dir];\n                            int ny = cy + dy[dir];\n                            int nz = cz + dz[dir];\n                            if (nx < 0 || nx >= D || ny < 0 || ny >= D || nz < 0 || nz >= D) continue;\n                            int nid = idx(nx, ny, nz);\n                            if (mask[nid] && !seen[nid]) {\n                                seen[nid] = 1;\n                                q.push(nid);\n                            }\n                        }\n                    }\n                    out.push_back(std::move(c));\n                }\n            }\n        }\n    };\n\n    bfs_components(excl0, comp0);\n    bfs_components(excl1, comp1);\n\n    // -------------------------------------------------\n    // 4) generate the 24 rotations\n    vector<Rot> rots;\n    array<int,3> perm = {0,1,2};\n    sort(perm.begin(), perm.end());\n    do {\n        int inv = 0;\n        for (int i=0;i<3;i++) for (int j=i+1;j<3;j++) if (perm[i] > perm[j]) ++inv;\n        int permSign = (inv%2==0) ? 1 : -1;\n        for (int sx : {1,-1})\n            for (int sy : {1,-1})\n                for (int sz : {1,-1}) {\n                    if (permSign * sx * sy * sz != 1) continue; // orientation preserving only\n                    Rot r;\n                    r.perm[0]=perm[0]; r.perm[1]=perm[1]; r.perm[2]=perm[2];\n                    r.sign[0]=sx; r.sign[1]=sy; r.sign[2]=sz;\n                    rots.push_back(r);\n                }\n    } while (next_permutation(perm.begin(), perm.end()));\n    // rots.size() == 24\n\n    // -------------------------------------------------\n    // 5) canonical key for a component\n    auto canonical = [&](const vector<array<int,3>>& pts)->string{\n        string best;\n        for (const Rot& r : rots) {\n            vector<array<int,3>> tr;\n            tr.reserve(pts.size());\n            for (auto &p : pts) {\n                int c[3] = {p[0],p[1],p[2]};\n                int nx = r.sign[0] * c[r.perm[0]];\n                int ny = r.sign[1] * c[r.perm[1]];\n                int nz = r.sign[2] * c[r.perm[2]];\n                tr.push_back({nx,ny,nz});\n            }\n            int minx = tr[0][0], miny = tr[0][1], minz = tr[0][2];\n            for (auto &p : tr) {\n                minx = min(minx, p[0]);\n                miny = min(miny, p[1]);\n                minz = min(minz, p[2]);\n            }\n            for (auto &p : tr) {\n                p[0] -= minx;\n                p[1] -= miny;\n                p[2] -= minz;\n            }\n            sort(tr.begin(), tr.end(),\n                [](const array<int,3>& a, const array<int,3>& b){\n                    if (a[0]!=b[0]) return a[0]<b[0];\n                    if (a[1]!=b[1]) return a[1]<b[1];\n                    return a[2]<b[2];\n                });\n            string s;\n            s.reserve(tr.size()*6);\n            for (auto &p : tr) {\n                s += to_string(p[0]); s += ',';\n                s += to_string(p[1]); s += ',';\n                s += to_string(p[2]); s += ';';\n            }\n            if (best.empty() || s < best) best = s;\n        }\n        return best;\n    };\n\n    // -------------------------------------------------\n    // 6) match components of equal shape\n    unordered_map<string, vector<int>> map0, map1;\n    vector<string> key0(comp0.size()), key1(comp1.size());\n\n    for (int i = 0; i < (int)comp0.size(); ++i) {\n        key0[i] = canonical(comp0[i].coord);\n        map0[key0[i]].push_back(i);\n    }\n    for (int i = 0; i < (int)comp1.size(); ++i) {\n        key1[i] = canonical(comp1[i].coord);\n        map1[key1[i]].push_back(i);\n    }\n\n    vector<char> used0(comp0.size(),0), used1(comp1.size(),0);\n    for (auto &kv : map0) {\n        const string &k = kv.first;\n        auto it = map1.find(k);\n        if (it == map1.end()) continue;\n        vector<int> &v0 = kv.second;\n        vector<int> &v1 = it->second;\n        while (!v0.empty() && !v1.empty()) {\n            int id0 = v0.back(); v0.pop_back();\n            int id1 = v1.back(); v1.pop_back();\n            for (int c : comp0[id0].cells) b0[c] = cur_id;\n            for (int c : comp1[id1].cells) b1[c] = cur_id;\n            used0[id0] = used1[id1] = 1;\n            ++cur_id;\n        }\n    }\n\n    // -------------------------------------------------\n    // 7) remaining cells become vertical lines\n    struct Line {\n        vector<int> cells;   // linear indices, ordered by increasing z\n        int pos = 0;         // first unused cell\n        int length() const { return (int)cells.size() - pos; }\n    };\n    vector<Line> lines0, lines1;\n\n    auto extract_lines = [&](const vector<char>& mask,\n                             vector<Line>& out) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                int z = 0;\n                while (z < D) {\n                    int id = idx(x, y, z);\n                    if (!mask[id]) { ++z; continue; }\n                    int start = z;\n                    while (z + 1 < D && mask[idx(x, y, z + 1)]) ++z;\n                    int end = z;\n                    Line ln;\n                    ln.cells.reserve(end - start + 1);\n                    for (int zz = start; zz <= end; ++zz)\n                        ln.cells.push_back(idx(x, y, zz));\n                    out.push_back(std::move(ln));\n                    ++z;\n                }\n            }\n        }\n    };\n\n    // build masks of still\u2011unfilled exclusive cells\n    vector<char> remMask0(N,0), remMask1(N,0);\n    for (int i = 0; i < N; ++i) {\n        if (need0[i] && !shared[i] && b0[i]==0) remMask0[i]=1;\n        if (need1[i] && !shared[i] && b1[i]==0) remMask1[i]=1;\n    }\n    extract_lines(remMask0, lines0);\n    extract_lines(remMask1, lines1);\n\n    using Elem = pair<int,int>;               // (remaining length , line id)\n    struct Cmp { bool operator()(Elem const& a, Elem const& b) const {\n        return a.first < b.first; } };       // max\u2011heap\n    priority_queue<Elem, vector<Elem>, Cmp> pq0, pq1;\n\n    for (int i = 0; i < (int)lines0.size(); ++i)\n        if (!lines0[i].cells.empty())\n            pq0.emplace((int)lines0[i].cells.size(), i);\n    for (int i = 0; i < (int)lines1.size(); ++i)\n        if (!lines1[i].cells.empty())\n            pq1.emplace((int)lines1[i].cells.size(), i);\n\n    while (!pq0.empty() && !pq1.empty()) {\n        int id0 = -1, len0 = 0;\n        while (!pq0.empty()) {\n            auto [l,i] = pq0.top(); pq0.pop();\n            if (lines0[i].length() == l) { id0 = i; len0 = l; break; }\n        }\n        int id1 = -1, len1 = 0;\n        while (!pq1.empty()) {\n            auto [l,i] = pq1.top(); pq1.pop();\n            if (lines1[i].length() == l) { id1 = i; len1 = l; break; }\n        }\n        if (id0==-1 || id1==-1) break;\n\n        int use = min(len0, len1);\n        Line &L0 = lines0[id0];\n        Line &L1 = lines1[id1];\n        for (int k = 0; k < use; ++k) {\n            b0[L0.cells[L0.pos + k]] = cur_id;\n            b1[L1.cells[L1.pos + k]] = cur_id;\n        }\n        L0.pos += use;\n        L1.pos += use;\n        ++cur_id;\n\n        if (L0.length() > 0) pq0.emplace(L0.length(), id0);\n        if (L1.length() > 0) pq1.emplace(L1.length(), id1);\n    }\n\n    // -------------------------------------------------\n    // 8) leftover cells become exclusive unit blocks\n    for (int i = 0; i < N; ++i) {\n        if (need0[i] && !shared[i] && b0[i]==0) { b0[i] = cur_id++; }\n        if (need1[i] && !shared[i] && b1[i]==0) { b1[i] = cur_id++; }\n    }\n\n    // -------------------------------------------------\n    // 9) output\n    int n = cur_id - 1;\n    cout << n << \"\\n\";\n    // b0\n    for (int x = 0; x < D; ++x)\n        for (int y = 0; y < D; ++y)\n            for (int z = 0; z < D; ++z) {\n                if (x || y || z) cout << ' ';\n                cout << b0[idx(x, y, z)];\n            }\n    cout << \"\\n\";\n    // b1\n    for (int x = 0; x < D; ++x)\n        for (int y = 0; y < D; ++y)\n            for (int z = 0; z < D; ++z) {\n                if (x || y || z) cout << ' ';\n                cout << b1[idx(x, y, z)];\n            }\n    cout << \"\\n\";\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ---------- Disjoint Set Union ----------\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\n// integer ceil(sqrt(x)) for x >= 0\nint ceil_sqrt(long long x) {\n    if (x <= 0) return 0;\n    long long s = sqrt((long double)x);\n    while (s * s < x) ++s;\n    while ((s - 1) * (s - 1) >= x) --s;\n    return (int)s;\n}\n\n// ---------- Main ----------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;\n\n    vector<long long> xs(N), ys(N);\n    for (int i = 0; i < N; ++i) cin >> xs[i] >> ys[i];\n\n    struct Edge {\n        int u, v;\n        long long w;\n        int idx;\n    };\n    vector<Edge> edges(M);\n    vector<vector<int>> edgeIdx(N, vector<int>(N, -1));\n    for (int j = 0; j < M; ++j) {\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[j] = {u, v, w, j};\n        edgeIdx[u][v] = edgeIdx[v][u] = j;\n    }\n\n    vector<long long> a(K), b(K);\n    for (int k = 0; k < K; ++k) cin >> a[k] >> b[k];\n\n    // ---------- 1) resident \u2192 station squared distances ----------\n    const long long INF64 = (1LL << 60);\n    vector<vector<long long>> dist2(K, vector<long long>(N));\n    for (int k = 0; k < K; ++k) {\n        for (int i = 0; i < N; ++i) {\n            long long dx = xs[i] - a[k];\n            long long dy = ys[i] - b[k];\n            dist2[k][i] = dx * dx + dy * dy;\n        }\n    }\n\n    // ---------- 2) all\u2011pairs shortest paths (Floyd\u2011Warshall) ----------\n    vector<vector<long long>> sp(N, vector<long long>(N, INF64));\n    vector<vector<int>> nxt(N, vector<int>(N, -1));\n    for (int i = 0; i < N; ++i) {\n        sp[i][i] = 0;\n        nxt[i][i] = i;\n    }\n    for (const auto& e : edges) {\n        int u = e.u, v = e.v;\n        if (e.w < sp[u][v]) {\n            sp[u][v] = sp[v][u] = e.w;\n            nxt[u][v] = v;\n            nxt[v][u] = u;\n        }\n    }\n    for (int k = 0; k < N; ++k) {\n        for (int i = 0; i < N; ++i) if (sp[i][k] != INF64) {\n            for (int j = 0; j < N; ++j) if (sp[k][j] != INF64) {\n                long long nd = sp[i][k] + sp[k][j];\n                if (nd < sp[i][j]) {\n                    sp[i][j] = nd;\n                    nxt[i][j] = nxt[i][k];\n                }\n            }\n        }\n    }\n\n    // ---------- 3) initial assignment (nearest station) ----------\n    vector<vector<int>> residents(N);\n    vector<long long> maxDist2(N, -1);\n    for (int k = 0; k < K; ++k) {\n        long long best = INF64;\n        int bestStation = -1;\n        for (int i = 0; i < N; ++i) {\n            long long d2 = dist2[k][i];\n            if (d2 < best) {\n                best = d2;\n                bestStation = i;\n            }\n        }\n        residents[bestStation].push_back(k);\n        if (maxDist2[bestStation] < best) maxDist2[bestStation] = best;\n    }\n\n    // ---------- 4) terminals (stations with residents) + root ----------\n    const int ROOT = 0;\n    vector<int> terminals;\n    for (int i = 0; i < N; ++i) if (maxDist2[i] != -1) terminals.push_back(i);\n    if (find(terminals.begin(), terminals.end(), ROOT) == terminals.end())\n        terminals.push_back(ROOT);\n\n    // ---------- 5) MST on terminals (using shortest\u2011path distances) ----------\n    struct TermEdge {\n        int u, v;\n        long long w;\n    };\n    vector<TermEdge> termEdges;\n    for (size_t i = 0; i < terminals.size(); ++i) {\n        for (size_t j = i + 1; j < terminals.size(); ++j) {\n            int u = terminals[i], v = terminals[j];\n            termEdges.push_back({u, v, sp[u][v]});\n        }\n    }\n    sort(termEdges.begin(), termEdges.end(),\n         [](const TermEdge& a, const TermEdge& b){ return a.w < b.w; });\n    DSU dsuTerm(N);\n    vector<pair<int,int>> termMST; // pairs (u,v)\n    for (const auto& e : termEdges) {\n        if (dsuTerm.unite(e.u, e.v)) {\n            termMST.emplace_back(e.u, e.v);\n        }\n    }\n\n    // ---------- 6) turn on all edges of the shortest paths of termMST ----------\n    vector<int> B(M, 0);   // edge ON/OFF\n    for (auto [u, v] : termMST) {\n        int cur = u;\n        while (cur != v) {\n            int nxtNode = nxt[cur][v];\n            int idx = edgeIdx[cur][nxtNode];\n            B[idx] = 1;\n            cur = nxtNode;\n        }\n    }\n\n    // ---------- 7) reduce to a tree (MST of the obtained subgraph) ----------\n    vector<Edge> subEdges;\n    for (int j = 0; j < M; ++j) if (B[j]) subEdges.push_back(edges[j]);\n    sort(subEdges.begin(), subEdges.end(),\n         [](const Edge& a, const Edge& b){ return a.w < b.w; });\n    DSU dsuSub(N);\n    vector<int> Btree(M, 0);\n    for (const auto& e : subEdges) {\n        if (dsuSub.unite(e.u, e.v)) {\n            Btree[e.idx] = 1;\n        }\n    }\n    B.swap(Btree);   // now B holds a tree connecting all terminals\n\n    // ---------- 8) leaf pruning loop ----------\n    while (true) {\n        // build adjacency of current tree\n        vector<vector<pair<int,int>>> adj(N);\n        for (int j = 0; j < M; ++j) if (B[j]) {\n            int u = edges[j].u, v = edges[j].v;\n            adj[u].push_back({v, j});\n            adj[v].push_back({u, j});\n        }\n\n        // degree and parent (BFS from root)\n        vector<int> degree(N, 0);\n        for (int i = 0; i < N; ++i) degree[i] = (int)adj[i].size();\n        vector<int> parent(N, -1), parentEdge(N, -1);\n        queue<int> q;\n        q.push(ROOT);\n        parent[ROOT] = ROOT;\n        while (!q.empty()) {\n            int v = q.front(); q.pop();\n            for (auto [to, idx] : adj[v]) {\n                if (parent[to] != -1) continue;\n                parent[to] = v;\n                parentEdge[to] = idx;\n                q.push(to);\n            }\n        }\n\n        // ----- re\u2011assign residents to the nearest *present* station -----\n        for (int i = 0; i < N; ++i) {\n            residents[i].clear();\n            maxDist2[i] = -1;\n        }\n        for (int k = 0; k < K; ++k) {\n            long long best = INF64;\n            int bestStation = -1;\n            for (int i = 0; i < N; ++i) {\n                if (i != ROOT && degree[i] == 0) continue; // not in the tree\n                long long d2 = dist2[k][i];\n                if (d2 < best) {\n                    best = d2;\n                    bestStation = i;\n                }\n            }\n            residents[bestStation].push_back(k);\n            if (maxDist2[bestStation] < best) maxDist2[bestStation] = best;\n        }\n\n        // ----- radii -----\n        vector<int> P(N, 0);\n        vector<char> active(N, 0);\n        for (int i = 0; i < N; ++i) {\n            if (maxDist2[i] == -1) {\n                P[i] = 0;\n                active[i] = 0;\n            } else {\n                P[i] = ceil_sqrt(maxDist2[i]);\n                active[i] = 1;\n            }\n        }\n\n        // ----- try to delete one leaf -----\n        bool removed = false;\n        for (int i = 0; i < N; ++i) {\n            if (i == ROOT) continue;\n            if (degree[i] != 1) continue;          // not a leaf\n            int p = parent[i];\n            // compute new maximal distance for parent after receiving i's residents\n            long long newMax = maxDist2[p];\n            if (newMax == -1) newMax = 0;\n            for (int r : residents[i]) {\n                long long d2 = dist2[r][p];\n                if (d2 > newMax) newMax = d2;\n            }\n            int newP = ceil_sqrt(newMax);\n\n            long long cost_before = (active[i] ? (long long)P[i] * P[i] : 0LL)\n                                   + (long long)P[p] * P[p]\n                                   + edges[parentEdge[i]].w;\n            long long cost_after  = (long long)newP * newP;\n\n            if (cost_after < cost_before) {\n                // perform removal\n                B[parentEdge[i]] = 0;\n                // move residents to the parent\n                residents[p].insert(residents[p].end(),\n                                    residents[i].begin(),\n                                    residents[i].end());\n                removed = true;\n                break;          // restart the whole loop\n            }\n        }\n\n        if (!removed) break;   // no improvement possible\n    }\n\n    // ---------- 9) final radii (already computed in the last loop) ----------\n    // recompute one last time to be safe\n    vector<vector<pair<int,int>>> finalAdj(N);\n    for (int j = 0; j < M; ++j) if (B[j]) {\n        int u = edges[j].u, v = edges[j].v;\n        finalAdj[u].push_back({v, j});\n        finalAdj[v].push_back({u, j});\n    }\n    vector<int> finalDeg(N, 0);\n    for (int i = 0; i < N; ++i) finalDeg[i] = (int)finalAdj[i].size();\n\n    // assignment once more\n    for (int i = 0; i < N; ++i) {\n        residents[i].clear();\n        maxDist2[i] = -1;\n    }\n    for (int k = 0; k < K; ++k) {\n        long long best = INF64;\n        int bestStation = -1;\n        for (int i = 0; i < N; ++i) {\n            if (i != ROOT && finalDeg[i] == 0) continue;\n            long long d2 = dist2[k][i];\n            if (d2 < best) {\n                best = d2;\n                bestStation = i;\n            }\n        }\n        residents[bestStation].push_back(k);\n        if (maxDist2[bestStation] < best) maxDist2[bestStation] = best;\n    }\n    vector<int> P(N, 0);\n    for (int i = 0; i < N; ++i) {\n        if (maxDist2[i] == -1) P[i] = 0;\n        else P[i] = ceil_sqrt(maxDist2[i]);\n    }\n\n    // ---------- 10) output ----------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << P[i];\n    }\n    cout << '\\n';\n    for (int j = 0; j < M; ++j) {\n        if (j) cout << ' ';\n        cout << B[j];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 30;                     // fixed by the statement\n    int a[N][N];                          // a[x][y] , 0 <= y <= x\n\n    // read the triangular input\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            cin >> a[x][y];\n        }\n    }\n\n    vector<Op> ops;\n    ops.reserve(10000);\n\n    // bottom\u2011up heapify (min\u2011heap) using only the two down\u2011edges\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            int cx = x, cy = y;\n            while (cx < N - 1) {                     // while a child exists\n                int bestX = cx, bestY = cy;\n                // down\u2011left child (cx+1 , cy)\n                if (a[bestX][bestY] > a[cx + 1][cy]) {\n                    bestX = cx + 1;\n                    bestY = cy;\n                }\n                // down\u2011right child (cx+1 , cy+1)\n                if (a[bestX][bestY] > a[cx + 1][cy + 1]) {\n                    bestX = cx + 1;\n                    bestY = cy + 1;\n                }\n                if (bestX == cx && bestY == cy) break;   // heap property satisfied\n                swap(a[cx][cy], a[bestX][bestY]);\n                ops.push_back({cx, cy, bestX, bestY});\n                cx = bestX;\n                cy = bestY;\n                // safety: the problem guarantees K <= 10000, but we keep the bound\n                if (ops.size() > 10000) break;\n            }\n            if (ops.size() > 10000) break;\n        }\n        if (ops.size() > 10000) break;\n    }\n\n    // output\n    cout << ops.size() << '\\n';\n    for (const auto &op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' '\n             << op.x2 << ' ' << op.y2 << '\\n';\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- transport phase helper ---------- */\nstruct HeapNode {\n    int number;   // container number\n    int id;       // vertex id\n    bool operator<(HeapNode const& other) const {\n        // priority_queue is a max\u2011heap \u2192 reverse for a min\u2011heap\n        return number > other.number;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    /* ----- input (D is always 9, but read it normally) ----- */\n    int D, N;\n    if (!(cin >> D >> N)) return 0;\n    const int entrance_i = 0;\n    const int entrance_j = (D - 1) / 2;          // (0,4)\n\n    vector<vector<bool>> obstacle(D, vector<bool>(D, false));\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        obstacle[ri][rj] = true;\n    }\n\n    /* ----- BFS \u2013 build the tree ----- */\n    vector<vector<int>> id(D, vector<int>(D, -1));\n    vector<pair<int,int>> coord;   // id \u2192 (i,j)\n    vector<int> depth;             // BFS distance\n    vector<int> parent;            // parent id, -1 for entrance\n\n    queue<pair<int,int>> q;\n    int curId = 0;\n    id[entrance_i][entrance_j] = curId++;\n    coord.emplace_back(entrance_i, entrance_j);\n    depth.push_back(0);\n    parent.push_back(-1);\n    q.emplace(entrance_i, entrance_j);\n\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        int cur = id[i][j];\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= D || nj < 0 || nj >= D) continue;\n            if (obstacle[ni][nj]) continue;\n            if (id[ni][nj] != -1) continue;\n            id[ni][nj] = curId++;\n            coord.emplace_back(ni, nj);\n            depth.push_back(depth[cur] + 1);\n            parent.push_back(cur);\n            q.emplace(ni, nj);\n        }\n    }\n\n    const int totalCells = curId;          // includes entrance\n    const int entranceId = 0;\n    const int M = totalCells - 1;          // number of containers\n    const int maxNumber = M - 1;           // largest possible container number\n\n    /* ----- children list and remaining\u2011children counter ----- */\n    vector<vector<int>> children(totalCells);\n    vector<int> remainingChildren(totalCells, 0);\n    for (int v = 1; v < totalCells; ++v) {\n        int p = parent[v];\n        children[p].push_back(v);\n        ++remainingChildren[p];\n    }\n\n    /* ----- leaf structures (by depth) ----- */\n    int maxDepth = 0;\n    for (int d : depth) maxDepth = max(maxDepth, d);\n    vector<set<int>> leavesByDepth(maxDepth + 1);\n    int leafCount = 0;\n    for (int v = 1; v < totalCells; ++v) {\n        if (remainingChildren[v] == 0) {\n            leavesByDepth[ depth[v] ].insert(v);\n            ++leafCount;\n        }\n    }\n\n    /* ----- placement phase ----- */\n    vector<int> containerNumber(totalCells, -1);   // number assigned to each cell\n    for (int step = 0; step < M; ++step) {\n        int t;               // number of the arriving container\n        cin >> t;\n\n        // rank of t among the remaining numbers (0\u2011based)\n        // target rank among current leaves\n        long long targetRank = (static_cast<long long>(t) * leafCount) / M;\n\n        // find depth whose cumulative leaf count exceeds targetRank\n        int cum = 0, chosenDepth = -1;\n        for (int d = 0; d <= maxDepth; ++d) {\n            cum += static_cast<int>(leavesByDepth[d].size());\n            if (cum > targetRank) {\n                chosenDepth = d;\n                break;\n            }\n        }\n        // safety: should always find a depth\n        if (chosenDepth == -1) chosenDepth = maxDepth;\n\n        // pick any leaf of that depth (smallest id)\n        int v = *leavesByDepth[chosenDepth].begin();\n        leavesByDepth[chosenDepth].erase(leavesByDepth[chosenDepth].begin());\n        --leafCount;\n\n        containerNumber[v] = t;\n        cout << coord[v].first << ' ' << coord[v].second << \"\\n\";\n        cout.flush();   // required after each placement\n\n        // update parent \u2013 it may become a leaf now\n        int p = parent[v];\n        if (p != -1 && p != entranceId) {\n            if (--remainingChildren[p] == 0) {\n                leavesByDepth[ depth[p] ].insert(p);\n                ++leafCount;\n            }\n        }\n    }\n\n    /* ----- transport phase ----- */\n    priority_queue<HeapNode> pq;\n    for (int c : children[entranceId]) {\n        pq.push({containerNumber[c], c});\n    }\n\n    while (!pq.empty()) {\n        auto cur = pq.top(); pq.pop();\n        int v = cur.id;\n        cout << coord[v].first << ' ' << coord[v].second << \"\\n\";\n        for (int c : children[v]) {\n            pq.push({containerNumber[c], c});\n        }\n    }\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    vector<vector<int>> a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (j) cout << ' ';\n            cout << a[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n    vector<long long> w(N);\n    for (int i = 0; i < N; ++i) cin >> w[i];\n\n    long long total = 0;\n    for (auto x : w) total += x;\n    double target = static_cast<double>(total) / D;\n\n    // random generator\n    std::mt19937_64 rng(\n        chrono::steady_clock::now().time_since_epoch().count());\n\n    vector<int> bestAssign(N);\n    double bestScore = numeric_limits<double>::infinity();\n\n    auto computeScore = [&](const vector<long long> &sum) -> double {\n        double sc = 0.0;\n        for (int d = 0; d < D; ++d) {\n            double diff = static_cast<double>(sum[d]) - target;\n            sc += diff * diff;\n        }\n        return sc;\n    };\n\n    // time limit handling\n    const double TIME_LIMIT = 1.8;                // seconds\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        // ----- 1) random order for greedy -----\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) {\n                 if (w[a] != w[b]) return w[a] > w[b];\n                 return (rng() & 1ULL);\n             });\n\n        // ----- 2) greedy assignment -----\n        vector<int> assign(N, -1);\n        vector<long long> sum(D, 0);\n        for (int idx : order) {\n            int bestSet = 0;\n            long long minSum = sum[0];\n            for (int d = 1; d < D; ++d) {\n                if (sum[d] < minSum) {\n                    minSum = sum[d];\n                    bestSet = d;\n                }\n            }\n            assign[idx] = bestSet;\n            sum[bestSet] += w[idx];\n        }\n\n        // ----- 3) local improvement (hill climbing) -----\n        bool improved = true;\n        while (improved) {\n            improved = false;\n\n            // try moving a single item\n            for (int i = 0; i < N && !improved; ++i) {\n                int a = assign[i];\n                long long wi = w[i];\n                double curDiffA = static_cast<double>(sum[a]) - target;\n                for (int b = 0; b < D; ++b) {\n                    if (b == a) continue;\n                    double curDiffB = static_cast<double>(sum[b]) - target;\n                    double newDiffA = static_cast<double>(sum[a] - wi) - target;\n                    double newDiffB = static_cast<double>(sum[b] + wi) - target;\n                    double delta = (newDiffA * newDiffA + newDiffB * newDiffB) -\n                                   (curDiffA * curDiffA + curDiffB * curDiffB);\n                    if (delta < -1e-9) {\n                        // perform move\n                        sum[a] -= wi;\n                        sum[b] += wi;\n                        assign[i] = b;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n\n            if (improved) continue;\n\n            // try swapping two items\n            for (int i = 0; i < N && !improved; ++i) {\n                int a = assign[i];\n                long long wi = w[i];\n                for (int j = i + 1; j < N; ++j) {\n                    int b = assign[j];\n                    if (a == b) continue;\n                    long long wj = w[j];\n                    double curDiffA = static_cast<double>(sum[a]) - target;\n                    double curDiffB = static_cast<double>(sum[b]) - target;\n                    double newDiffA = static_cast<double>(sum[a] - wi + wj) - target;\n                    double newDiffB = static_cast<double>(sum[b] - wj + wi) - target;\n                    double delta = (newDiffA * newDiffA + newDiffB * newDiffB) -\n                                   (curDiffA * curDiffA + curDiffB * curDiffB);\n                    if (delta < -1e-9) {\n                        // perform swap\n                        sum[a] = sum[a] - wi + wj;\n                        sum[b] = sum[b] - wj + wi;\n                        assign[i] = b;\n                        assign[j] = a;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n        }\n\n        // ----- 4) evaluate -----\n        double curScore = computeScore(sum);\n        if (curScore < bestScore) {\n            bestScore = curScore;\n            bestAssign = assign;\n        }\n\n        // ----- 5) time check -----\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_LIMIT) break;\n    }\n\n    // ----- 6) output best assignment -----\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << bestAssign[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    const int per = n / m;                 // = 20 for the given data\n    vector<vector<int>> st(m);             // bottom \u2192 top\n    vector<int> pos(n + 1, -1);            // current stack of each box\n\n    for (int i = 0; i < m; ++i) {\n        st[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x; cin >> x;\n            st[i].push_back(x);\n            pos[x] = i;\n        }\n    }\n\n    vector<pair<int,int>> ops;             // (v , i)   i = 0 \u2192 removal\n\n    // helper: choose a destination for the top box w of stack src\n    auto choose_dest = [&](int w, int src) -> int {\n        // 1) empty stack\n        for (int i = 0; i < m; ++i) if (i != src && st[i].empty())\n            return i;\n        // 2) stack whose top is larger than w (pick the smallest such top)\n        int best = -1, bestTop = INT_MAX;\n        for (int i = 0; i < m; ++i) if (i != src && !st[i].empty() && st[i].back() > w) {\n            if (st[i].back() < bestTop) {\n                bestTop = st[i].back();\n                best = i;\n            }\n        }\n        if (best != -1) return best;\n        // 3) fallback \u2013 any other stack, choose the one with smallest size\n        int minSize = INT_MAX;\n        for (int i = 0; i < m; ++i) if (i != src) {\n            if ((int)st[i].size() < minSize) {\n                minSize = (int)st[i].size();\n                best = i;\n            }\n        }\n        return best;   // always exists because m \u2265 2\n    };\n\n    for (int v = 1; v <= n; ++v) {\n        int s = pos[v];                     // stack that currently holds v\n        // bring v to the top\n        while (!st[s].empty() && st[s].back() != v) {\n            int w = st[s].back();           // top box, w > v\n            int d = choose_dest(w, s);\n            // perform the move\n            st[s].pop_back();\n            st[d].push_back(w);\n            pos[w] = d;\n            ops.emplace_back(w, d + 1);     // +1 because stacks are 1\u2011indexed in output\n        }\n        // now v is on the top \u2192 remove it\n        ops.emplace_back(v, 0);\n        st[s].pop_back();\n        pos[v] = -1;\n    }\n\n    // safety check (the problem guarantees 5000 is enough)\n    assert(ops.size() <= 5000);\n\n    for (auto [v, i] : ops) {\n        cout << v << ' ' << i << '\\n';\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> h;                 // (N\u20111) \u00d7 N  : vertical walls\nvector<string> v;                 // N \u00d7 (N\u20111)  : horizontal walls\nvector<vector<int>> d;            // dirt susceptibility\n\n// direction helpers\nconst int dr[4] = {0, 1, 0, -1};\nconst int dc[4] = {1, 0, -1, 0};\nconst char dirChar[4] = {'R', 'D', 'L', 'U'};\n\nchar opposite(char c) {\n    switch (c) {\n        case 'R': return 'L';\n        case 'L': return 'R';\n        case 'U': return 'D';\n        case 'D': return 'U';\n    }\n    return '?';\n}\n\n// true iff we can move from (r,c) to neighbour in direction dir\nbool canMove(int r, int c, int dir) {\n    int nr = r + dr[dir];\n    int nc = c + dc[dir];\n    if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n    if (dir == 0) {               // R\n        return v[r][c] == '0';\n    } else if (dir == 2) {        // L\n        return v[r][c - 1] == '0';\n    } else if (dir == 1) {        // D\n        return h[r][c] == '0';\n    } else {                      // U\n        return h[r - 1][c] == '0';\n    }\n}\n\n/* ----------  BFS : shortest\u2011path tree from (0,0) ---------- */\nvector<vector<int>> dist;\nvector<vector<pair<int,int>>> parent;\nvector<vector<char>> dirFromParent;\n\nvoid bfs() {\n    dist.assign(N, vector<int>(N, -1));\n    parent.assign(N, vector<pair<int,int>>(N, {-1,-1}));\n    dirFromParent.assign(N, vector<char>(N, 0));\n    queue<pair<int,int>> q;\n    dist[0][0] = 0;\n    q.emplace(0,0);\n    while (!q.empty()) {\n        auto [r,c] = q.front(); q.pop();\n        for (int dir = 0; dir < 4; ++dir) {\n            if (!canMove(r,c,dir)) continue;\n            int nr = r + dr[dir];\n            int nc = c + dc[dir];\n            if (dist[nr][nc] != -1) continue;\n            dist[nr][nc] = dist[r][c] + 1;\n            parent[nr][nc] = {r,c};\n            dirFromParent[nr][nc] = dirChar[dir];\n            q.emplace(nr,nc);\n        }\n    }\n}\n\n/* ----------  DFS : base tour that visits every cell once ---------- */\nvector<vector<char>> visited;\nstring answer; // final route\n\nvoid dfs(int r, int c) {\n    visited[r][c] = 1;\n    for (int dir = 0; dir < 4; ++dir) {\n        if (!canMove(r,c,dir)) continue;\n        int nr = r + dr[dir];\n        int nc = c + dc[dir];\n        if (!visited[nr][nc]) {\n            answer.push_back(dirChar[dir]); // go forward\n            dfs(nr,nc);\n            answer.push_back(dirChar[(dir+2)%4]); // go back\n        }\n    }\n}\n\n/* ----------  forward path from (0,0) to (i,j) ---------- */\nstring getForwardPath(int i, int j) {\n    string rev;\n    while (!(i==0 && j==0)) {\n        char c = dirFromParent[i][j];\n        rev.push_back(c);\n        int dirIdx = -1;\n        if (c == 'R') dirIdx = 0;\n        else if (c == 'D') dirIdx = 1;\n        else if (c == 'L') dirIdx = 2;\n        else if (c == 'U') dirIdx = 3;\n        i -= dr[dirIdx];\n        j -= dc[dirIdx];\n    }\n    reverse(rev.begin(), rev.end());\n    return rev;\n}\n\n/* ----------  main ---------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N)) return 0;\n    h.resize(N-1);\n    for (int i = 0; i < N-1; ++i) cin >> h[i];\n    v.resize(N);\n    for (int i = 0; i < N; ++i) cin >> v[i];\n    d.assign(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> d[i][j];\n\n    const int MAXLEN = 100000;\n    answer.reserve(MAXLEN);\n\n    /* 1. BFS for shortest paths */\n    bfs();\n\n    /* 2. DFS base tour */\n    visited.assign(N, vector<char>(N, 0));\n    dfs(0,0);\n    int L0 = (int)answer.size();\n\n    /* 3. total dirtiness */\n    long long Dall = 0;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            Dall += d[i][j];\n\n    /* ----------  candidate loops ---------- */\n    struct Cand {\n        int type;          // 0 = none, 1 = edge, 2 = block\n        int i, j;          // for edge: endpoint (i,j); for block: top\u2011left\n        char dir;          // direction from endpoint to neighbour (edge only)\n        int travel;        // distance from start to chosen endpoint\n        int C;             // cost per repetition (2 or 4)\n        long long Dsum;    // sum of d in the loop\n        int t;             // repetitions to use\n    };\n    Cand best{0, -1,-1,0,0,0,0,0};\n    long double bestScore = numeric_limits<long double>::infinity();\n\n    auto evaluate = [&](int type, int i, int j, char dir,\n                        int travel, int C, long long Dsum) {\n        int a = L0 + 2 * travel;\n        long long B = Dall - Dsum;\n        if (B <= 0) return;               // degenerate\n        int tmax = (MAXLEN - a) / C;\n        if (tmax < 0) return;\n        // analytical optimum (real)\n        long double t_real = sqrt( (long double)Dsum *\n                                   ( (long double)a - (long double)C ) /\n                                   ( (long double)C * (long double)B ) ) - 1.0L;\n        long long t0 = (long long)floor(t_real);\n        if (t0 < 0) t0 = 0;\n        if (t0 > tmax) t0 = tmax;\n\n        auto score = [&](long long t)->long double{\n            long double L = (long double)a + (long double)C * t;\n            long double S = (long double)B + (long double)Dsum / (1.0L + t);\n            return L * S;\n        };\n        // test t0, t0+1, and 0\n        vector<long long> candT = {t0};\n        if (t0 + 1 <= tmax) candT.push_back(t0 + 1);\n        candT.push_back(0);\n        for (long long t : candT) {\n            long double sc = score(t);\n            if (sc < bestScore) {\n                bestScore = sc;\n                best = {type, i, j, dir, travel, C, Dsum, (int)t};\n            }\n        }\n    };\n\n    /* ----- edges ----- */\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            // down edge\n            if (i + 1 < N && h[i][j] == '0') {\n                long long Dsum = (long long)d[i][j] + d[i+1][j];\n                int travel = min(dist[i][j], dist[i+1][j]);\n                char dir = (dist[i][j] <= dist[i+1][j]) ? 'D' : 'U';\n                evaluate(1, i, j, dir, travel, 2, Dsum);\n            }\n            // right edge\n            if (j + 1 < N && v[i][j] == '0') {\n                long long Dsum = (long long)d[i][j] + d[i][j+1];\n                int travel = min(dist[i][j], dist[i][j+1]);\n                char dir = (dist[i][j] <= dist[i][j+1]) ? 'R' : 'L';\n                evaluate(1, i, j, dir, travel, 2, Dsum);\n            }\n        }\n    }\n\n    /* ----- 2\u00d72 blocks ----- */\n    for (int i = 0; i + 1 < N; ++i) {\n        for (int j = 0; j + 1 < N; ++j) {\n            if (v[i][j] != '0') continue;               // (i,j)-(i,j+1)\n            if (h[i][j] != '0') continue;               // (i,j)-(i+1,j)\n            if (v[i+1][j] != '0') continue;             // (i+1,j)-(i+1,j+1)\n            if (h[i][j+1] != '0') continue;             // (i,j+1)-(i+1,j+1)\n\n            long long Dsum = (long long)d[i][j] + d[i][j+1] +\n                             d[i+1][j] + d[i+1][j+1];\n            int travel = dist[i][j];                     // top\u2011left cell\n            evaluate(2, i, j, 0, travel, 4, Dsum);\n        }\n    }\n\n    /* ---------- 6. build the final answer ---------- */\n    if (best.type != 0 && best.t > 0) {\n        // forward path to the chosen endpoint (nearest cell of the loop)\n        string forward = getForwardPath(best.i, best.j);\n        answer += forward;\n\n        if (best.type == 1) {               // edge\n            char c = best.dir;               // direction from endpoint to neighbour\n            for (int k = 0; k < best.t; ++k) {\n                answer.push_back(c);\n                answer.push_back(opposite(c));\n            }\n        } else {                            // block\n            const string loop = \"RDLU\";\n            for (int k = 0; k < best.t; ++k) answer += loop;\n        }\n\n        // reverse of forward path with opposite directions\n        for (int k = (int)forward.size() - 1; k >= 0; --k)\n            answer.push_back(opposite(forward[k]));\n    }\n\n    if ((int)answer.size() > MAXLEN) answer.resize(MAXLEN);\n    cout << answer << '\\n';\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int i, j;\n};\n\nint manhattan(const Pos& a, const Pos& b) {\n    return abs(a.i - b.i) + abs(a.j - b.j);\n}\n\n// compute the longest overlap of suffix of a and prefix of b\nint overlap(const string& a, const string& b) {\n    int maxk = min((int)a.size(), (int)b.size());\n    for (int k = maxk; k > 0; --k) {\n        bool ok = true;\n        for (int t = 0; t < k; ++t) {\n            if (a[a.size() - k + t] != b[t]) {\n                ok = false; break;\n            }\n        }\n        if (ok) return k;\n    }\n    return 0;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n    \n    // positions for each letter\n    vector<Pos> pos[26];\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = board[i][j];\n            pos[c - 'A'].push_back({i, j});\n        }\n    }\n    \n    vector<string> cur(M);\n    for (int k = 0; k < M; ++k) cin >> cur[k];\n    \n    // ---------- 1. greedy shortest common superstring ----------\n    while (cur.size() > 1) {\n        int bestOv = -1;\n        int bestI = -1, bestJ = -1;\n        string bestMerged;\n        int sz = cur.size();\n        for (int i = 0; i < sz; ++i) {\n            for (int j = 0; j < sz; ++j) if (i != j) {\n                int ov = overlap(cur[i], cur[j]);\n                if (ov > bestOv) {\n                    bestOv = ov;\n                    bestI = i;\n                    bestJ = j;\n                    bestMerged = cur[i] + cur[j].substr(ov);\n                }\n            }\n        }\n        // merge bestI and bestJ\n        if (bestI > bestJ) swap(bestI, bestJ); // erase larger index first\n        cur.erase(cur.begin() + bestJ);\n        cur.erase(cur.begin() + bestI);\n        cur.push_back(bestMerged);\n    }\n    string S = cur[0];                 // final output string\n    int L = (int)S.size();\n    \n    // ---------- 2. DP for optimal movement ----------\n    // layerPos[p] = list of cells that can type S[p]\n    vector<vector<Pos>> layerPos(L);\n    for (int p = 0; p < L; ++p) {\n        layerPos[p] = pos[S[p] - 'A'];\n    }\n    \n    const int INF = 1e9;\n    vector<vector<int>> dp(L);\n    vector<vector<int>> parent(L);\n    \n    // first layer\n    dp[0].resize(layerPos[0].size());\n    parent[0].resize(layerPos[0].size(), -1);\n    for (size_t i = 0; i < layerPos[0].size(); ++i) {\n        dp[0][i] = manhattan({si, sj}, layerPos[0][i]) + 1;\n    }\n    \n    // subsequent layers\n    for (int p = 1; p < L; ++p) {\n        const auto& prevCells = layerPos[p-1];\n        const auto& curCells  = layerPos[p];\n        dp[p].assign(curCells.size(), INF);\n        parent[p].assign(curCells.size(), -1);\n        for (size_t ci = 0; ci < curCells.size(); ++ci) {\n            int best = INF;\n            int bestPrev = -1;\n            for (size_t pj = 0; pj < prevCells.size(); ++pj) {\n                int cand = dp[p-1][pj] + manhattan(prevCells[pj], curCells[ci]) + 1;\n                if (cand < best) {\n                    best = cand;\n                    bestPrev = (int)pj;\n                }\n            }\n            dp[p][ci] = best;\n            parent[p][ci] = bestPrev;\n        }\n    }\n    \n    // find minimal cost at the last layer\n    int lastIdx = -1;\n    int bestCost = INF;\n    for (size_t i = 0; i < dp[L-1].size(); ++i) {\n        if (dp[L-1][i] < bestCost) {\n            bestCost = dp[L-1][i];\n            lastIdx = (int)i;\n        }\n    }\n    \n    // reconstruct the sequence of cells\n    vector<Pos> answer(L);\n    int curIdx = lastIdx;\n    for (int p = L-1; p >= 0; --p) {\n        answer[p] = layerPos[p][curIdx];\n        curIdx = parent[p][curIdx];\n    }\n    \n    // ---------- output ----------\n    for (const Pos& p : answer) {\n        cout << p.i << ' ' << p.j << '\\n';\n    }\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Shape {\n    vector<pair<int,int>> cells;   // coordinates relative to (0,0)\n    int max_i = 0, max_j = 0;      // size of bounding box\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    double eps;\n    if (!(cin >> N >> M >> eps)) return 0;   // no input\n\n    // ------------------------------------------------------------\n    // 1. read the M polyomino shapes and store them\n    vector<Shape> shapes(M);\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        shapes[k].cells.resize(d);\n        int mx_i = 0, mx_j = 0;\n        for (int t = 0; t < d; ++t) {\n            int i, j;\n            cin >> i >> j;\n            shapes[k].cells[t] = {i, j};\n            mx_i = max(mx_i, i);\n            mx_j = max(mx_j, j);\n        }\n        shapes[k].max_i = mx_i;\n        shapes[k].max_j = mx_j;\n    }\n\n    // ------------------------------------------------------------\n    // 2. compute possible cells and forced cells\n    vector<vector<char>> possible(N, vector<char>(N, 0));\n    vector<vector<char>> forced(N, vector<char>(N, 0));\n\n    for (const auto &sh : shapes) {\n        int h = sh.max_i + 1;\n        int w = sh.max_j + 1;\n\n        // intersection of all placements of this shape\n        vector<vector<char>> inter(N, vector<char>(N, 1)); // start true\n\n        bool first = true;\n        for (int dx = 0; dx <= N - h; ++dx) {\n            for (int dy = 0; dy <= N - w; ++dy) {\n                // cells occupied by this placement\n                vector<vector<char>> occ(N, vector<char>(N, 0));\n                for (auto [ci, cj] : sh.cells) {\n                    int ii = dx + ci;\n                    int jj = dy + cj;\n                    occ[ii][jj] = 1;\n                    possible[ii][jj] = 1;   // mark as possibly covered\n                }\n                // update intersection\n                if (first) {\n                    inter = occ;\n                    first = false;\n                } else {\n                    for (int i = 0; i < N; ++i)\n                        for (int j = 0; j < N; ++j)\n                            inter[i][j] &= occ[i][j];\n                }\n            }\n        }\n        // cells that are in every placement of this shape become forced\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                if (inter[i][j]) forced[i][j] = 1;\n    }\n\n    // ------------------------------------------------------------\n    // 3. query all non\u2011forced possible cells and collect answer\n    vector<pair<int,int>> answer;\n\n    // first add forced cells (cost 0)\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (forced[i][j]) answer.emplace_back(i, j);\n\n    // then drill the remaining possible cells\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!possible[i][j] || forced[i][j]) continue; // skip\n            cout << \"q 1 \" << i << ' ' << j << '\\n';\n            cout.flush();\n            int v;\n            if (!(cin >> v)) return 0;   // EOF or error\n            if (v > 0) answer.emplace_back(i, j);\n        }\n    }\n\n    // ------------------------------------------------------------\n    // 4. output final answer\n    cout << \"a \" << answer.size();\n    for (auto [i, j] : answer) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << '\\n';\n    cout.flush();\n\n    // optional final verdict\n    int verdict;\n    if (cin >> verdict) {\n        // nothing to do\n    }\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int W = 1000;                     // hall size (fixed)\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int W_input, D, N;\n    if (!(cin >> W_input >> D >> N)) return 0;   // W_input is always 1000\n    // we ignore W_input because the geometry is fixed to W = 1000\n\n    vector<vector<long long>> a(D, vector<long long>(N));\n    for (int d = 0; d < D; ++d)\n        for (int k = 0; k < N; ++k)\n            cin >> a[d][k];\n\n    vector<int> curH(N, 0);                 // heights of the previous day\n\n    for (int d = 0; d < D; ++d) {\n        // ----- required heights for this day -----\n        vector<int> need(N);\n        for (int k = 0; k < N; ++k) {\n            need[k] = (int)((a[d][k] + W - 1) / W);   // ceil(a / W)\n            if (need[k] < 1) need[k] = 1;              // safety, a \u2265 1\n        }\n\n        // ----- start from previous heights, increase if necessary -----\n        vector<int> newH = curH;\n        for (int k = 0; k < N; ++k)\n            if (newH[k] < need[k]) newH[k] = need[k];\n\n        int total = 0;\n        for (int h : newH) total += h;\n\n        // ----- if we exceed the hall height, shrink surplus first -----\n        if (total > W) {\n            // surplus = height - need (non\u2011negative after the increase step)\n            priority_queue<pair<int,int>> pq;   // (surplus, index)\n            for (int k = 0; k < N; ++k) {\n                int surplus = newH[k] - need[k];\n                if (surplus > 0) pq.emplace(surplus, k);\n            }\n            while (total > W && !pq.empty()) {\n                auto [s, k] = pq.top(); pq.pop();\n                newH[k]--;                     // reduce by one row\n                total--;\n                s--;\n                if (s > 0) pq.emplace(s, k);\n            }\n            // If still too tall (possible only because \u03a3 need > W),\n            // shrink any strip that is still > 1 (incurs area penalty).\n            int idx = 0;\n            while (total > W) {\n                if (newH[idx] > 1) {\n                    newH[idx]--;\n                    total--;\n                }\n                idx = (idx + 1) % N;\n            }\n        }\n\n        curH.swap(newH);                     // store heights for the next day\n\n        // ----- output the strips for this day -----\n        int row = 0;\n        for (int k = 0; k < N; ++k) {\n            int i0 = row;\n            int i1 = row + curH[k];\n            cout << i0 << ' ' << 0 << ' '\n                 << i1 << ' ' << W << '\\n';\n            row = i1;\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr long long MOD = 998244353LL;\n\n/* -------------------------------------------------------------\n   information for a single possible stamp placement\n   ------------------------------------------------------------- */\nstruct OpInfo {\n    int m, p, q;               // stamp id and top\u2011left board position\n    int idx[9];                // flat board indices (0 \u2026 N*N-1)\n    long long add[9];          // stamp values (already % MOD)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;          // N = 9, M = 20, K = 81\n    const int maxP = N - 3;   // last top\u2011left row where a stamp fits\n    const int maxQ = N - 3;   // last top\u2011left column\n\n    // ---------- read initial board ----------\n    vector<long long> initBoard(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            long long x; cin >> x;\n            initBoard[i * N + j] = x % MOD;\n        }\n    }\n\n    // ---------- read stamps ----------\n    vector<array<long long, 9>> stampVals(M);\n    for (int m = 0; m < M; ++m) {\n        for (int u = 0; u < 3; ++u) {\n            for (int v = 0; v < 3; ++v) {\n                long long x; cin >> x;\n                stampVals[m][u * 3 + v] = x % MOD;\n            }\n        }\n    }\n\n    // ---------- pre\u2011compute all possible operations ----------\n    vector<OpInfo> ops;\n    for (int m = 0; m < M; ++m) {\n        for (int p = 0; p <= maxP; ++p) {\n            for (int q = 0; q <= maxQ; ++q) {\n                OpInfo info;\n                info.m = m; info.p = p; info.q = q;\n                int t = 0;\n                for (int u = 0; u < 3; ++u) {\n                    for (int v = 0; v < 3; ++v) {\n                        info.idx[t] = (p + u) * N + (q + v);\n                        info.add[t] = stampVals[m][u * 3 + v];\n                        ++t;\n                    }\n                }\n                ops.push_back(info);\n            }\n        }\n    }\n    const int totalOps = (int)ops.size();   // = 980\n\n    // ------------------------------------------------------------\n    // helper functions\n    // ------------------------------------------------------------\n    auto computeDelta = [&](const vector<long long> &board,\n                            const OpInfo &op) -> long long {\n        long long delta = 0;\n        for (int t = 0; t < 9; ++t) {\n            long long old = board[op.idx[t]];\n            long long newv = old + op.add[t];\n            if (newv >= MOD) newv -= MOD;\n            delta += (newv - old);\n        }\n        return delta;\n    };\n\n    // apply (+1) or remove (-1) a stamp, return the change of the total sum\n    auto applyOp = [&](vector<long long> &board,\n                       const OpInfo &op,\n                       int sign) -> long long {\n        long long delta = 0;\n        if (sign == +1) {\n            for (int t = 0; t < 9; ++t) {\n                int idx = op.idx[t];\n                long long old = board[idx];\n                long long newv = old + op.add[t];\n                if (newv >= MOD) newv -= MOD;\n                board[idx] = newv;\n                delta += (newv - old);\n            }\n        } else { // sign == -1\n            for (int t = 0; t < 9; ++t) {\n                int idx = op.idx[t];\n                long long old = board[idx];\n                long long newv = old - op.add[t];\n                if (newv < 0) newv += MOD;\n                board[idx] = newv;\n                delta += (newv - old);\n            }\n        }\n        return delta;\n    };\n\n    // greedy fill from a given board, returns list of operation ids\n    auto greedyFill = [&](vector<long long> &board) -> vector<int> {\n        vector<int> chosen;\n        while ((int)chosen.size() < K) {\n            long long bestDelta = LLONG_MIN;\n            int bestId = -1;\n            for (int id = 0; id < totalOps; ++id) {\n                long long d = computeDelta(board, ops[id]);\n                if (d > bestDelta) {\n                    bestDelta = d;\n                    bestId = id;\n                }\n            }\n            if (bestDelta <= 0) break;\n            applyOp(board, ops[bestId], +1);\n            chosen.push_back(bestId);\n        }\n        return chosen;\n    };\n\n    // ------------------------------------------------------------\n    // initial greedy solution\n    // ------------------------------------------------------------\n    vector<long long> board = initBoard;\n    vector<int> bestOps = greedyFill(board);\n    long long bestScore = 0;\n    for (long long v : board) bestScore += v;\n\n    // ------------------------------------------------------------\n    // hill\u2011climbing loop (time\u2011bounded)\n    // ------------------------------------------------------------\n    std::mt19937_64 rng(\n        (uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_real_distribution<double> distReal(0.0, 1.0);\n    const double TIME_LIMIT = 1.9;          // seconds\n    auto startTime = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        // start from the current best solution\n        vector<int> curOps = bestOps;\n        vector<long long> curBoard = initBoard;\n        for (int id : curOps) applyOp(curBoard, ops[id], +1);\n\n        int sz = (int)curOps.size();\n        int moveType = rng() % 3;   // 0 = insert, 1 = delete, 2 = replace\n\n        // ----- INSERT -------------------------------------------------\n        if (moveType == 0 && sz < K) {\n            int pos = rng() % (sz + 1);                 // insertion position\n            int newId = rng() % totalOps;\n            curOps.insert(curOps.begin() + pos, newId);\n            applyOp(curBoard, ops[newId], +1);\n        }\n        // ----- DELETE -------------------------------------------------\n        else if (moveType == 1 && sz > 0) {\n            int pos = rng() % sz;\n            int delId = curOps[pos];\n            applyOp(curBoard, ops[delId], -1);\n            curOps.erase(curOps.begin() + pos);\n        }\n        // ----- REPLACE ------------------------------------------------\n        else if (moveType == 2 && sz > 0) {\n            int pos = rng() % sz;\n            int oldId = curOps[pos];\n            int newId = rng() % totalOps;\n            applyOp(curBoard, ops[oldId], -1);\n            applyOp(curBoard, ops[newId], +1);\n            curOps[pos] = newId;\n        }\n        // if the chosen move was illegal (e.g. insert when size==K) we simply\n        // skip it \u2013 the loop will try another random move next time.\n\n        // ----- greedy completion after the modification -------------\n        while ((int)curOps.size() < K) {\n            long long bestDelta = LLONG_MIN;\n            int bestId = -1;\n            for (int id = 0; id < totalOps; ++id) {\n                long long d = computeDelta(curBoard, ops[id]);\n                if (d > bestDelta) {\n                    bestDelta = d;\n                    bestId = id;\n                }\n            }\n            if (bestDelta <= 0) break;\n            applyOp(curBoard, ops[bestId], +1);\n            curOps.push_back(bestId);\n        }\n\n        // ----- evaluate ------------------------------------------------\n        long long curScore = 0;\n        for (long long v : curBoard) curScore += v;\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestOps.swap(curOps);\n        }\n    }\n\n    // ------------------------------------------------------------\n    // final greedy completion (in case the best solution is not full)\n    // ------------------------------------------------------------\n    board = initBoard;\n    for (int id : bestOps) applyOp(board, ops[id], +1);\n    while ((int)bestOps.size() < K) {\n        long long bestDelta = LLONG_MIN;\n        int bestId = -1;\n        for (int id = 0; id < totalOps; ++id) {\n            long long d = computeDelta(board, ops[id]);\n            if (d > bestDelta) {\n                bestDelta = d;\n                bestId = id;\n            }\n        }\n        if (bestDelta <= 0) break;\n        applyOp(board, ops[bestId], +1);\n        bestOps.push_back(bestId);\n    }\n\n    // ------------------------------------------------------------\n    // output\n    // ------------------------------------------------------------\n    cout << bestOps.size() << \"\\n\";\n    for (int id : bestOps) {\n        const OpInfo &o = ops[id];\n        cout << o.m << ' ' << o.p << ' ' << o.q << \"\\n\";\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\n// generate a Manhattan walk from (r,c) to (tr,tc)\nstatic string walk(int r, int c, int tr, int tc) {\n    string s;\n    while (r > tr) { s.push_back('U'); --r; }\n    while (r < tr) { s.push_back('D'); ++r; }\n    while (c > tc) { s.push_back('L'); --c; }\n    while (c < tc) { s.push_back('R'); ++c; }\n    return s;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> A(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> A[i][j];\n\n    // actions for each crane\n    vector<string> act(N);\n    // small cranes: bomb at turn 0, later do nothing\n    // we will pad them later to the length of the large crane\n    for (int i = 1; i < N; ++i) act[i] = \"B\";\n\n    // large crane (crane 0)\n    string &big = act[0];\n    int curR = 0, curC = 0;               // start position (0,0)\n\n    for (int i = 0; i < N; ++i) {        // receiving gate i\n        for (int j = 0; j < N; ++j) {    // j\u2011th container of this gate\n            // move to (i,0)\n            big += walk(curR, curC, i, 0);\n            curR = i; curC = 0;\n            // pick up\n            big.push_back('P');\n            int b = A[i][j];\n            int dr = b / N;               // destination row\n            // move to dispatch gate (dr, N-1)\n            big += walk(curR, curC, dr, N - 1);\n            curR = dr; curC = N - 1;\n            // release\n            big.push_back('Q');\n            // move back to the receiving gate (i,0)\n            big += walk(curR, curC, i, 0);\n            curR = i; curC = 0;\n        }\n    }\n\n    // pad small cranes with '.' to the length of the longest string\n    size_t L = big.size();\n    for (int i = 1; i < N; ++i) {\n        if (act[i].size() < L) act[i].append(L - act[i].size(), '.');\n    }\n\n    // output\n    for (int i = 0; i < N; ++i) {\n        cout << act[i] << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Node {\n    int x, y;\n    int amt;          // remaining amount to send / receive\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> h[i][j];\n\n    vector<Node> sources, sinks;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (h[i][j] > 0) sources.push_back({i, j, h[i][j]});\n            else if (h[i][j] < 0) sinks.push_back({i, j, -h[i][j]});\n        }\n\n    if (sources.empty() && sinks.empty()) return 0;   // already flat\n\n    // current truck position\n    int curX = 0, curY = 0;\n    vector<string> ops;\n    ops.reserve(40000);\n\n    auto dist = [&](int x1, int y1, int x2, int y2) {\n        return abs(x1 - x2) + abs(y1 - y2);\n    };\n\n    // move from (curX,curY) to (tx,ty) using Manhattan steps\n    auto moveTo = [&](int tx, int ty) {\n        while (curX != tx) {\n            if (curX < tx) {\n                ops.emplace_back(\"D\");\n                ++curX;\n            } else {\n                ops.emplace_back(\"U\");\n                --curX;\n            }\n        }\n        while (curY != ty) {\n            if (curY < ty) {\n                ops.emplace_back(\"R\");\n                ++curY;\n            } else {\n                ops.emplace_back(\"L\");\n                --curY;\n            }\n        }\n    };\n\n    // Main loop: process all sources\n    while (true) {\n        // find the nearest source that still has soil\n        int srcIdx = -1;\n        int best = INT_MAX;\n        for (int i = 0; i < (int)sources.size(); ++i) {\n            if (sources[i].amt == 0) continue;\n            int d = dist(curX, curY, sources[i].x, sources[i].y);\n            if (d < best) {\n                best = d;\n                srcIdx = i;\n            }\n        }\n        if (srcIdx == -1) break;   // all supplies exhausted\n\n        // go to that source (empty)\n        moveTo(sources[srcIdx].x, sources[srcIdx].y);\n\n        // load everything from the source\n        int loadAmt = sources[srcIdx].amt;\n        ops.emplace_back(\"+\" + to_string(loadAmt));\n        sources[srcIdx].amt = 0;\n        int curLoad = loadAmt;   // amount currently on the truck\n\n        // deliver while we still carry soil\n        while (curLoad > 0) {\n            // nearest sink with remaining demand\n            int sinkIdx = -1;\n            best = INT_MAX;\n            for (int i = 0; i < (int)sinks.size(); ++i) {\n                if (sinks[i].amt == 0) continue;\n                int d = dist(curX, curY, sinks[i].x, sinks[i].y);\n                if (d < best) {\n                    best = d;\n                    sinkIdx = i;\n                }\n            }\n            // there must be a sink because total supply = total demand\n            moveTo(sinks[sinkIdx].x, sinks[sinkIdx].y);\n            int unloadAmt = min(curLoad, sinks[sinkIdx].amt);\n            ops.emplace_back(\"-\" + to_string(unloadAmt));\n            curLoad -= unloadAmt;\n            sinks[sinkIdx].amt -= unloadAmt;\n        }\n        // now the truck is empty again, position = last visited sink\n    }\n\n    // output the operation list\n    for (const string& s : ops) {\n        cout << s << '\\n';\n    }\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    const int S = 2 * N * (N - 1);          // 60 for N = 6\n    const int CELLS = N * N;               // 36\n    const int EDGE_COUNT = 2 * N * (N - 1); // 60\n    const long long BASE = 1'000'000LL;    // weight for max edge\n\n    // ---------- read initial seeds ----------\n    vector<vector<int>> X(S, vector<int>(M));\n    for (int i = 0; i < S; ++i)\n        for (int j = 0; j < M; ++j)\n            cin >> X[i][j];\n\n    // ---------- edges and degrees ----------\n    vector<pair<int,int>> edges;\n    edges.reserve(EDGE_COUNT);\n    vector<int> degree(CELLS, 0);\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            int id = r * N + c;\n            if (c + 1 < N) {\n                edges.emplace_back(id, id + 1);\n                ++degree[id];\n                ++degree[id + 1];\n            }\n            if (r + 1 < N) {\n                edges.emplace_back(id, id + N);\n                ++degree[id];\n                ++degree[id + N];\n            }\n        }\n    }\n\n    // cells sorted by decreasing degree (interior first)\n    vector<int> cellsByDeg(CELLS);\n    iota(cellsByDeg.begin(), cellsByDeg.end(), 0);\n    sort(cellsByDeg.begin(), cellsByDeg.end(),\n         [&](int a, int b){ return degree[a] > degree[b]; });\n\n    // adjacency: incident edges for each cell\n    vector<vector<int>> incEdges(CELLS);\n    for (int e = 0; e < (int)edges.size(); ++e) {\n        incEdges[edges[e].first].push_back(e);\n        incEdges[edges[e].second].push_back(e);\n    }\n\n    // random generator\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> cellDist(0, CELLS - 1);\n    std::uniform_real_distribution<double> probDist(0.0, 1.0);\n\n    const int ITER = 600000;          // annealing iterations\n    const double START_T = 2e4;\n    const double END_T   = 5e-3;\n    const int K_SPECIAL = 24;         // number of special edges\n\n    for (int turn = 0; turn < T; ++turn) {\n        /* ---------- 1. ordinary sums V[i] ---------- */\n        vector<int> V(S);\n        for (int i = 0; i < S; ++i) {\n            int sum = 0;\n            for (int l = 0; l < M; ++l) sum += X[i][l];\n            V[i] = sum;\n        }\n\n        /* ---------- 2. pair scores P[i][j] ---------- */\n        static int P[60][60];\n        vector<tuple<int,int,int>> pairList; // (score,i,j)\n        pairList.reserve(S * (S - 1) / 2);\n        for (int i = 0; i < S; ++i) {\n            P[i][i] = 0;\n            for (int j = i + 1; j < S; ++j) {\n                int sc = 0;\n                for (int l = 0; l < M; ++l) sc += max(X[i][l], X[j][l]);\n                P[i][j] = P[j][i] = sc;\n                pairList.emplace_back(sc, i, j);\n            }\n        }\n        sort(pairList.begin(), pairList.end(),\n             [&](const auto& a, const auto& b){ return get<0>(a) > get<0>(b); });\n\n        /* ---------- 3. greedy placement of special edges ---------- */\n        // edges sorted by degree\u2011sum descending\n        vector<int> edgeOrder(edges.size());\n        iota(edgeOrder.begin(), edgeOrder.end(), 0);\n        sort(edgeOrder.begin(), edgeOrder.end(),\n             [&](int a, int b){\n                 int da = degree[edges[a].first] + degree[edges[a].second];\n                 int db = degree[edges[b].first] + degree[edges[b].second];\n                 return da > db;\n             });\n\n        vector<int> board(CELLS, -1);\n        vector<char> usedSeed(S, 0);\n        vector<char> usedCell(CELLS, 0);\n        int placedSpecial = 0;\n\n        for (int ei : edgeOrder) {\n            if (placedSpecial >= K_SPECIAL) break;\n            int u = edges[ei].first;\n            int v = edges[ei].second;\n            if (usedCell[u] || usedCell[v]) continue;\n\n            bool found = false;\n            for (auto &tp : pairList) {\n                int i = get<1>(tp);\n                int j = get<2>(tp);\n                if (!usedSeed[i] && !usedSeed[j]) {\n                    board[u] = i;\n                    board[v] = j;\n                    usedSeed[i] = usedSeed[j] = 1;\n                    usedCell[u] = usedCell[v] = 1;\n                    ++placedSpecial;\n                    found = true;\n                    break;\n                }\n            }\n            if (!found) break;\n        }\n\n        /* ---------- 4. fill remaining cells ---------- */\n        vector<int> remainingSeeds;\n        remainingSeeds.reserve(S);\n        for (int i = 0; i < S; ++i) if (!usedSeed[i]) remainingSeeds.push_back(i);\n        sort(remainingSeeds.begin(), remainingSeeds.end(),\n             [&](int a, int b){ return V[a] > V[b]; });\n\n        size_t pos = 0;\n        for (int cell : cellsByDeg) {\n            if (!usedCell[cell]) {\n                board[cell] = remainingSeeds[pos++];\n                usedCell[cell] = 1;\n            }\n        }\n\n        /* ---------- 5. initialise scores ---------- */\n        vector<int> edgeScore(EDGE_COUNT);\n        long long curSum = 0;\n        int curMax = 0;\n        for (int e = 0; e < EDGE_COUNT; ++e) {\n            int u = edges[e].first, v = edges[e].second;\n            int val = P[board[u]][board[v]];\n            edgeScore[e] = val;\n            curSum += val;\n            curMax = max(curMax, val);\n        }\n        long long curScore = curMax * BASE + curSum;\n        long long bestScore = curScore;\n        vector<int> bestBoard = board;\n\n        /* ---------- 6. simulated annealing ---------- */\n        for (int it = 0; it < ITER; ++it) {\n            double temperature = START_T * (1.0 - double(it) / ITER) +\n                                 END_T   * (double(it) / ITER);\n\n            int a = cellDist(rng);\n            int b = cellDist(rng);\n            if (a == b) continue;\n\n            int aSeed = board[a];\n            int bSeed = board[b];\n\n            // delta of the sum (only edges incident to a or b)\n            long long delta = 0;\n            for (int e : incEdges[a]) {\n                int other = (edges[e].first == a) ? edges[e].second : edges[e].first;\n                delta += P[bSeed][board[other]] - P[board[a]][board[other]];\n            }\n            for (int e : incEdges[b]) {\n                int other = (edges[e].first == b) ? edges[e].second : edges[e].first;\n                if (other == a) continue; // edge a\u2011b already handled\n                delta += P[aSeed][board[other]] - P[board[b]][board[other]];\n            }\n            long long newSum = curSum + delta;\n\n            // update edgeScore for edges incident to a and b\n            for (int e : incEdges[a]) {\n                int other = (edges[e].first == a) ? edges[e].second : edges[e].first;\n                edgeScore[e] = P[bSeed][board[other]];\n            }\n            for (int e : incEdges[b]) {\n                int other = (edges[e].first == b) ? edges[e].second : edges[e].first;\n                edgeScore[e] = P[aSeed][board[other]];\n            }\n\n            // recompute maximal edge value\n            int newMax = 0;\n            for (int e = 0; e < EDGE_COUNT; ++e) newMax = max(newMax, edgeScore[e]);\n\n            long long newScore = newMax * BASE + newSum;\n\n            bool accept = false;\n            if (newScore > curScore) {\n                accept = true;\n            } else {\n                double prob = exp((newScore - curScore) / temperature);\n                if (probDist(rng) < prob) accept = true;\n            }\n\n            if (accept) {\n                swap(board[a], board[b]);\n                curSum = newSum;\n                curMax = newMax;\n                curScore = newScore;\n                if (curScore > bestScore) {\n                    bestScore = curScore;\n                    bestBoard = board;\n                }\n            } else {\n                // revert edgeScore to original values (board unchanged)\n                for (int e : incEdges[a]) {\n                    int other = (edges[e].first == a) ? edges[e].second : edges[e].first;\n                    edgeScore[e] = P[board[a]][board[other]];\n                }\n                for (int e : incEdges[b]) {\n                    int other = (edges[e].first == b) ? edges[e].second : edges[e].first;\n                    edgeScore[e] = P[board[b]][board[other]];\n                }\n            }\n        }\n\n        /* ---------- 7. deterministic hill\u2011climbing ---------- */\n        const int MAX_PASSES = 10;\n        for (int pass = 0; pass < MAX_PASSES; ++pass) {\n            bool improved = false;\n            for (int a = 0; a < CELLS; ++a) {\n                for (int b = a + 1; b < CELLS; ++b) {\n                    int aSeed = board[a];\n                    int bSeed = board[b];\n\n                    long long delta = 0;\n                    for (int e : incEdges[a]) {\n                        int other = (edges[e].first == a) ? edges[e].second : edges[e].first;\n                        delta += P[bSeed][board[other]] - P[board[a]][board[other]];\n                    }\n                    for (int e : incEdges[b]) {\n                        int other = (edges[e].first == b) ? edges[e].second : edges[e].first;\n                        if (other == a) continue;\n                        delta += P[aSeed][board[other]] - P[board[b]][board[other]];\n                    }\n                    long long newSum = curSum + delta;\n\n                    // temporary update of edgeScore\n                    vector<int> savedA, savedB;\n                    for (int e : incEdges[a]) {\n                        savedA.push_back(edgeScore[e]);\n                        int other = (edges[e].first == a) ? edges[e].second : edges[e].first;\n                        edgeScore[e] = P[bSeed][board[other]];\n                    }\n                    for (int e : incEdges[b]) {\n                        savedB.push_back(edgeScore[e]);\n                        int other = (edges[e].first == b) ? edges[e].second : edges[e].first;\n                        edgeScore[e] = P[aSeed][board[other]];\n                    }\n\n                    int newMax = 0;\n                    for (int e = 0; e < EDGE_COUNT; ++e) newMax = max(newMax, edgeScore[e]);\n\n                    long long newScore = newMax * BASE + newSum;\n\n                    if (newScore > curScore) {\n                        swap(board[a], board[b]);\n                        curSum = newSum;\n                        curMax = newMax;\n                        curScore = newScore;\n                        improved = true;\n                        if (curScore > bestScore) {\n                            bestScore = curScore;\n                            bestBoard = board;\n                        }\n                    } else {\n                        // revert edgeScore\n                        int idx = 0;\n                        for (int e : incEdges[a]) edgeScore[e] = savedA[idx++];\n                        idx = 0;\n                        for (int e : incEdges[b]) edgeScore[e] = savedB[idx++];\n                    }\n                }\n            }\n            if (!improved) break;\n        }\n\n        /* ---------- 8. output best board ---------- */\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (j) cout << ' ';\n                cout << bestBoard[i * N + j];\n            }\n            cout << '\\n';\n        }\n        cout.flush();\n\n        /* ---------- 9. read next batch of seeds ---------- */\n        for (int i = 0; i < S; ++i)\n            for (int l = 0; l < M; ++l)\n                cin >> X[i][l];\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, V;\n    if (!(cin >> N >> M >> V)) return 0;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) cin >> s[i];\n    for (int i = 0; i < N; ++i) cin >> t[i];\n\n    // collect source cells (initial takoyaki not on target) and target cells (empty)\n    vector<Pos> src, dst;\n    vector<vector<int>> hasTak(N, vector<int>(N, 0));\n    vector<vector<int>> isTarget(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (s[i][j] == '1') hasTak[i][j] = 1;\n            if (t[i][j] == '1') isTarget[i][j] = 1;\n        }\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (hasTak[i][j] && !isTarget[i][j])\n                src.push_back({i, j});\n            if (!hasTak[i][j] && isTarget[i][j])\n                dst.push_back({i, j});\n        }\n\n    const int Vprime = 2;               // root + one leaf\n    // output arm description\n    cout << Vprime << \"\\n\";\n    cout << 0 << \" \" << 1 << \"\\n\";       // parent of vertex 1, length 1\n    cout << 0 << \" \" << 0 << \"\\n\";       // initial root position\n\n    // direction vectors\n    const int dx[4] = {0, 1, 0, -1};\n    const int dy[4] = {1, 0, -1, 0};\n\n    // helper to compute rotation cost\n    auto rotCost = [&](int cur, int target) -> int {\n        int diff = (target - cur + 4) % 4;\n        if (diff == 0) return 0;\n        if (diff == 2) return 2;\n        return 1;\n    };\n\n    // storage for operations\n    vector<string> ops;\n\n    // helper to push a turn\n    auto pushTurn = [&](char mv, char rot, char leafAct) {\n        string s(4, '.');\n        s[0] = mv;\n        s[1] = rot;\n        s[3] = leafAct;\n        ops.push_back(s);\n    };\n\n    // current state\n    int curX = 0, curY = 0;   // root position\n    int curDir = 0;           // leaf points right (dx=0, dy=+1)\n\n    // rotate leaf to target direction (may need 1 or 2 turns)\n    auto rotateTo = [&](int targetDir) {\n        int diff = (targetDir - curDir + 4) % 4;\n        if (diff == 0) return;\n        if (diff == 1) {\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n        } else if (diff == 3) {\n            pushTurn('.', 'L', '.');\n            curDir = (curDir + 3) % 4;\n        } else { // diff == 2\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n            pushTurn('.', 'R', '.');\n            curDir = (curDir + 1) % 4;\n        }\n    };\n\n    // move root to (tx,ty) by Manhattan steps\n    auto moveRootTo = [&](int tx, int ty) {\n        while (curX < tx) {\n            pushTurn('D', '.', '.');\n            ++curX;\n        }\n        while (curX > tx) {\n            pushTurn('U', '.', '.');\n            --curX;\n        }\n        while (curY < ty) {\n            pushTurn('R', '.', '.');\n            ++curY;\n        }\n        while (curY > ty) {\n            pushTurn('L', '.', '.');\n            --curY;\n        }\n    };\n\n    // alive flags\n    vector<char> srcAlive(src.size(), 1);\n    vector<char> dstAlive(dst.size(), 1);\n    int remaining = (int)src.size();\n\n    while (remaining > 0) {\n        // ----- choose nearest source -----\n        int bestDist = INT_MAX;\n        int bestIdx = -1, bestDir = -1, bestRx = -1, bestRy = -1;\n        for (int i = 0; i < (int)src.size(); ++i) if (srcAlive[i]) {\n            const Pos &p = src[i];\n            for (int d = 0; d < 4; ++d) {\n                int rx = p.x - dx[d];\n                int ry = p.y - dy[d];\n                if (0 <= rx && rx < N && 0 <= ry && ry < N) {\n                    int dist = abs(curX - rx) + abs(curY - ry);\n                    if (dist < bestDist) {\n                        bestDist = dist;\n                        bestIdx = i;\n                        bestDir = d;\n                        bestRx = rx;\n                        bestRy = ry;\n                    }\n                }\n            }\n        }\n        // move to source\n        rotateTo(bestDir);\n        moveRootTo(bestRx, bestRy);\n        pushTurn('.', '.', 'P');          // pick up\n        srcAlive[bestIdx] = 0;\n        --remaining;\n\n        // ----- choose nearest target -----\n        int bestDist2 = INT_MAX;\n        int bestIdxT = -1, bestDir2 = -1, bestRx2 = -1, bestRy2 = -1;\n        for (int i = 0; i < (int)dst.size(); ++i) if (dstAlive[i]) {\n            const Pos &p = dst[i];\n            for (int d = 0; d < 4; ++d) {\n                int rx = p.x - dx[d];\n                int ry = p.y - dy[d];\n                if (0 <= rx && rx < N && 0 <= ry && ry < N) {\n                    int rotC = rotCost(curDir, d);\n                    int dist = abs(curX - rx) + abs(curY - ry) + rotC;\n                    if (dist < bestDist2) {\n                        bestDist2 = dist;\n                        bestIdxT = i;\n                        bestDir2 = d;\n                        bestRx2 = rx;\n                        bestRy2 = ry;\n                    }\n                }\n            }\n        }\n        // move to target\n        rotateTo(bestDir2);\n        moveRootTo(bestRx2, bestRy2);\n        pushTurn('.', '.', 'P');          // release\n        dstAlive[bestIdxT] = 0;\n    }\n\n    // output operations\n    for (const string &s : ops) cout << s << \"\\n\";\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ull = unsigned long long;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if(!(cin >> N)) return 0;\n    vector<pair<int,int>> mackerel(N);\n    vector<pair<int,int>> sardine(N);\n    for (int i = 0; i < N; ++i) {\n        int x,y; cin >> x >> y;\n        mackerel[i] = {x,y};\n    }\n    unordered_set<ull> sardineSet;\n    sardineSet.reserve(N*2);\n    for (int i = 0; i < N; ++i) {\n        int x,y; cin >> x >> y;\n        sardine[i] = {x,y};\n        ull key = ( (ull)x << 32 ) | (unsigned int) y;\n        sardineSet.insert(key);\n    }\n    \n    // ------------------------------------------------------------\n    // 1) try to isolate a single mackerel with a 1x1 square\n    for (auto [x,y] : mackerel) {\n        if (x >= 100000 || y >= 100000) continue; // would go out of bounds\n        bool ok = true;\n        for (int dx = 0; dx <= 1 && ok; ++dx) {\n            for (int dy = 0; dy <= 1; ++dy) {\n                int nx = x + dx;\n                int ny = y + dy;\n                ull key = ( (ull)nx << 32 ) | (unsigned int) ny;\n                if (sardineSet.find(key) != sardineSet.end()) {\n                    ok = false;\n                    break;\n                }\n            }\n        }\n        if (ok) {\n            // output rectangle [x,x+1] \u00d7 [y,y+1]\n            cout << 4 << \"\\n\";\n            cout << x << \" \" << y << \"\\n\";\n            cout << x+1 << \" \" << y << \"\\n\";\n            cout << x+1 << \" \" << y+1 << \"\\n\";\n            cout << x << \" \" << y+1 << \"\\n\";\n            return 0;\n        }\n    }\n    \n    // ------------------------------------------------------------\n    // 2) grid cell fallback\n    const int G = 2000;                // side length of a cell\n    const int C = 100000 / G;          // 50, divides exactly\n    vector<vector<int>> mCount(C, vector<int>(C, 0));\n    vector<vector<int>> sCount(C, vector<int>(C, 0));\n    \n    auto cellIdx = [&](int coord) -> int {\n        int idx = coord / G;\n        if (idx >= C) idx = C-1;\n        return idx;\n    };\n    \n    for (auto [x,y] : mackerel) {\n        int cx = cellIdx(x);\n        int cy = cellIdx(y);\n        ++mCount[cx][cy];\n    }\n    for (auto [x,y] : sardine) {\n        int cx = cellIdx(x);\n        int cy = cellIdx(y);\n        ++sCount[cx][cy];\n    }\n    \n    int bestCx = -1, bestCy = -1;\n    int bestNet = INT_MIN;\n    for (int cx = 0; cx < C; ++cx) {\n        for (int cy = 0; cy < C; ++cy) {\n            int net = mCount[cx][cy] - sCount[cx][cy];\n            if (net > bestNet) {\n                bestNet = net;\n                bestCx = cx;\n                bestCy = cy;\n            }\n        }\n    }\n    if (bestNet > 0) {\n        int left   = bestCx * G;\n        int right  = (bestCx + 1) * G;\n        int bottom = bestCy * G;\n        int top    = (bestCy + 1) * G;\n        cout << 4 << \"\\n\";\n        cout << left << \" \" << bottom << \"\\n\";\n        cout << right << \" \" << bottom << \"\\n\";\n        cout << right << \" \" << top << \"\\n\";\n        cout << left << \" \" << top << \"\\n\";\n        return 0;\n    }\n    \n    // ------------------------------------------------------------\n    // 3) whole area fallback\n    cout << 4 << \"\\n\";\n    cout << 0 << \" \" << 0 << \"\\n\";\n    cout << 100000 << \" \" << 0 << \"\\n\";\n    cout << 100000 << \" \" << 100000 << \"\\n\";\n    cout << 0 << \" \" << 100000 << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int p;          // rectangle index\n    int r;          // rotation 0/1\n    char d;         // direction 'U' or 'L'\n    int b;          // reference rectangle (-1 or previous index)\n};\n\nstruct Placed {\n    long long x, y; // lower\u2011left corner\n    long long w, h; // size used for placement (estimated)\n};\n\nint N, T;\nlong long sigma;\nvector<long long> wObs, hObs;          // observed values\nvector<long long> obsSum;               // w'+h' for each rectangle\n\n/* ------------------------------------------------------------------ */\n/*  Helper: after a raw sequence (r,d,b) for all rectangles,\n    compute the positions, prefix maxX/Y and drop the best suffix.   */\nvector<Op> trim_ops(const vector<tuple<int,char,int>> &raw,\n                    long long margin) {\n    vector<Placed> placed;\n    vector<long long> prefMaxX, prefMaxY;\n    long long curMaxX = 0, curMaxY = 0;\n\n    for (int i = 0; i < (int)raw.size(); ++i) {\n        int r; char d; int b;\n        tie(r, d, b) = raw[i];\n        long long wi = (r == 0 ? wObs[i] : hObs[i]) + margin;\n        long long hi = (r == 0 ? hObs[i] : wObs[i]) + margin;\n\n        long long x, y;\n        if (d == 'U') {\n            x = (b == -1) ? 0LL : placed[b].x + placed[b].w;\n            y = 0;\n            for (const auto &p : placed) {\n                if (!(x + wi <= p.x || x >= p.x + p.w))\n                    y = max(y, p.y + p.h);\n            }\n        } else { // L\n            y = (b == -1) ? 0LL : placed[b].y + placed[b].h;\n            x = 0;\n            for (const auto &p : placed) {\n                if (!(y + hi <= p.y || y >= p.y + p.h))\n                    x = max(x, p.x + p.w);\n            }\n        }\n        placed.push_back({x, y, wi, hi});\n        curMaxX = max(curMaxX, x + wi);\n        curMaxY = max(curMaxY, y + hi);\n        prefMaxX.push_back(curMaxX);\n        prefMaxY.push_back(curMaxY);\n    }\n\n    // suffix penalty (observed sums)\n    vector<long long> suffix(N + 1, 0);\n    for (int i = N - 1; i >= 0; --i) suffix[i] = suffix[i + 1] + obsSum[i];\n\n    int bestK = (int)raw.size();\n    long long bestScore = (bestK == 0 ? 0 : prefMaxX[bestK - 1])\n                        + (bestK == 0 ? 0 : prefMaxY[bestK - 1])\n                        + suffix[bestK];\n    for (int k = 0; k <= (int)raw.size(); ++k) {\n        long long cur = (k == 0 ? 0 : prefMaxX[k - 1])\n                      + (k == 0 ? 0 : prefMaxY[k - 1])\n                      + suffix[k];\n        if (cur < bestScore) {\n            bestScore = cur;\n            bestK = k;\n        }\n    }\n\n    vector<Op> res;\n    res.reserve(bestK);\n    for (int i = 0; i < bestK; ++i) {\n        int r; char d; int b;\n        tie(r, d, b) = raw[i];\n        res.push_back({i, r, d, b});\n    }\n    return res;\n}\n\n/* ------------------------------------------------------------------ */\n/*  Greedy placement \u2013 try all (r,d,b) (full search)                */\nvector<Op> greedy_full(long long margin) {\n    vector<Op> ops;\n    vector<Placed> placed;\n    vector<long long> prefMaxX, prefMaxY;\n    long long curMaxX = 0, curMaxY = 0;\n\n    for (int i = 0; i < N; ++i) {\n        long long bestScore = (1LL << 62);\n        long long bestX = 0, bestY = 0;\n        int bestB = -1;\n        char bestD = 'U';\n        int bestR = 0;\n        long long bestW = 0, bestH = 0;\n\n        for (int rot = 0; rot <= 1; ++rot) {\n            long long wi = (rot == 0 ? wObs[i] : hObs[i]) + margin;\n            long long hi = (rot == 0 ? hObs[i] : wObs[i]) + margin;\n            for (int b = -1; b <= i - 1; ++b) {\n                // U\n                {\n                    long long x = (b == -1 ? 0LL : placed[b].x + placed[b].w);\n                    long long y = 0;\n                    for (const auto &p : placed) {\n                        if (!(x + wi <= p.x || x >= p.x + p.w))\n                            y = max(y, p.y + p.h);\n                    }\n                    long long newMaxX = max(curMaxX, x + wi);\n                    long long newMaxY = max(curMaxY, y + hi);\n                    long long score = newMaxX + newMaxY;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestX = x; bestY = y;\n                        bestB = b; bestD = 'U';\n                        bestR = rot; bestW = wi; bestH = hi;\n                    }\n                }\n                // L\n                {\n                    long long y = (b == -1 ? 0LL : placed[b].y + placed[b].h);\n                    long long x = 0;\n                    for (const auto &p : placed) {\n                        if (!(y + hi <= p.y || y >= p.y + p.h))\n                            x = max(x, p.x + p.w);\n                    }\n                    long long newMaxX = max(curMaxX, x + wi);\n                    long long newMaxY = max(curMaxY, y + hi);\n                    long long score = newMaxX + newMaxY;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestX = x; bestY = y;\n                        bestB = b; bestD = 'L';\n                        bestR = rot; bestW = wi; bestH = hi;\n                    }\n                }\n            }\n        }\n        ops.push_back({i, bestR, bestD, bestB});\n        placed.push_back({bestX, bestY, bestW, bestH});\n        curMaxX = max(curMaxX, bestX + bestW);\n        curMaxY = max(curMaxY, bestY + bestH);\n        prefMaxX.push_back(curMaxX);\n        prefMaxY.push_back(curMaxY);\n    }\n\n    // suffix penalty and drop suffix\n    vector<long long> suffix(N + 1, 0);\n    for (int i = N - 1; i >= 0; --i) suffix[i] = suffix[i + 1] + obsSum[i];\n\n    int bestK = N;\n    long long bestScore = prefMaxX[N - 1] + prefMaxY[N - 1] + suffix[N];\n    for (int k = 0; k <= N; ++k) {\n        long long cur = (k == 0 ? 0 : prefMaxX[k - 1])\n                      + (k == 0 ? 0 : prefMaxY[k - 1])\n                      + suffix[k];\n        if (cur < bestScore) {\n            bestScore = cur;\n            bestK = k;\n        }\n    }\n    ops.resize(bestK);\n    return ops;\n}\n\n/* ------------------------------------------------------------------ */\n/*  Greedy placement \u2013 only b = -1 or b = i\u20111 (O(N\u00b2))                */\nvector<Op> greedy_limited(long long margin) {\n    vector<Op> ops;\n    vector<Placed> placed;\n    vector<long long> prefMaxX, prefMaxY;\n    long long curMaxX = 0, curMaxY = 0;\n\n    for (int i = 0; i < N; ++i) {\n        long long bestScore = (1LL << 62);\n        long long bestX = 0, bestY = 0;\n        int bestB = -1;\n        char bestD = 'U';\n        int bestR = 0;\n        long long bestW = 0, bestH = 0;\n\n        for (int rot = 0; rot <= 1; ++rot) {\n            long long wi = (rot == 0 ? wObs[i] : hObs[i]) + margin;\n            long long hi = (rot == 0 ? hObs[i] : wObs[i]) + margin;\n            for (int b = -1; b <= i - 1; ++b) {\n                if (b != -1 && b != i - 1) continue;   // only two choices\n                // U\n                {\n                    long long x = (b == -1 ? 0LL : placed[b].x + placed[b].w);\n                    long long y = 0;\n                    for (const auto &p : placed) {\n                        if (!(x + wi <= p.x || x >= p.x + p.w))\n                            y = max(y, p.y + p.h);\n                    }\n                    long long newMaxX = max(curMaxX, x + wi);\n                    long long newMaxY = max(curMaxY, y + hi);\n                    long long score = newMaxX + newMaxY;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestX = x; bestY = y;\n                        bestB = b; bestD = 'U';\n                        bestR = rot; bestW = wi; bestH = hi;\n                    }\n                }\n                // L\n                {\n                    long long y = (b == -1 ? 0LL : placed[b].y + placed[b].h);\n                    long long x = 0;\n                    for (const auto &p : placed) {\n                        if (!(y + hi <= p.y || y >= p.y + p.h))\n                            x = max(x, p.x + p.w);\n                    }\n                    long long newMaxX = max(curMaxX, x + wi);\n                    long long newMaxY = max(curMaxY, y + hi);\n                    long long score = newMaxX + newMaxY;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestX = x; bestY = y;\n                        bestB = b; bestD = 'L';\n                        bestR = rot; bestW = wi; bestH = hi;\n                    }\n                }\n            }\n        }\n        ops.push_back({i, bestR, bestD, bestB});\n        placed.push_back({bestX, bestY, bestW, bestH});\n        curMaxX = max(curMaxX, bestX + bestW);\n        curMaxY = max(curMaxY, bestY + bestH);\n        prefMaxX.push_back(curMaxX);\n        prefMaxY.push_back(curMaxY);\n    }\n\n    // suffix penalty and drop suffix\n    vector<long long> suffix(N + 1, 0);\n    for (int i = N - 1; i >= 0; --i) suffix[i] = suffix[i + 1] + obsSum[i];\n\n    int bestK = N;\n    long long bestScore = prefMaxX[N - 1] + prefMaxY[N - 1] + suffix[N];\n    for (int k = 0; k <= N; ++k) {\n        long long cur = (k == 0 ? 0 : prefMaxX[k - 1])\n                      + (k == 0 ? 0 : prefMaxY[k - 1])\n                      + suffix[k];\n        if (cur < bestScore) {\n            bestScore = cur;\n            bestK = k;\n        }\n    }\n    ops.resize(bestK);\n    return ops;\n}\n\n/* ------------------------------------------------------------------ */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N >> T >> sigma)) return 0;\n    wObs.resize(N);\n    hObs.resize(N);\n    for (int i = 0; i < N; ++i) cin >> wObs[i] >> hObs[i];\n\n    obsSum.resize(N);\n    for (int i = 0; i < N; ++i) obsSum[i] = wObs[i] + hObs[i];\n\n    /* ---------- generate a collection of candidates ---------- */\n    vector<vector<Op>> candidates;\n    const long long MARGIN1 = sigma;          // 1\u00b7\u03c3\n    const long long MARGIN2 = 2 * sigma;      // 2\u00b7\u03c3\n\n    // greedy full (two different margins)\n    candidates.push_back(greedy_full(MARGIN1));\n    candidates.push_back(greedy_full(MARGIN2));\n\n    // greedy limited (two different margins)\n    candidates.push_back(greedy_limited(MARGIN1));\n    candidates.push_back(greedy_limited(MARGIN2));\n\n    // row layout (U, b = i\u20111)\n    {\n        vector<tuple<int,char,int>> raw;\n        raw.reserve(N);\n        for (int i = 0; i < N; ++i) {\n            int r = (hObs[i] > wObs[i]) ? 1 : 0;\n            int b = (i == 0 ? -1 : i - 1);\n            raw.emplace_back(r, 'U', b);\n        }\n        candidates.push_back(trim_ops(raw, MARGIN1));\n    }\n\n    // column layout (L, b = i\u20111)\n    {\n        vector<tuple<int,char,int>> raw;\n        raw.reserve(N);\n        for (int i = 0; i < N; ++i) {\n            int r = (hObs[i] > wObs[i]) ? 1 : 0;\n            int b = (i == 0 ? -1 : i - 1);\n            raw.emplace_back(r, 'L', b);\n        }\n        candidates.push_back(trim_ops(raw, MARGIN1));\n    }\n\n    // a few random candidates\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    const int RANDOM_CAND = 10;\n    for (int c = 0; c < RANDOM_CAND; ++c) {\n        vector<tuple<int,char,int>> raw;\n        raw.reserve(N);\n        for (int i = 0; i < N; ++i) {\n            int r = rng() & 1;\n            char d = (rng() & 1) ? 'U' : 'L';\n            int b = (int)(rng() % (i + 1)) - 1;   // -1 \u2026 i\u20111\n            raw.emplace_back(r, d, b);\n        }\n        candidates.push_back(trim_ops(raw, MARGIN1));\n    }\n\n    /* ---------- interactive loop ---------- */\n    int C = (int)candidates.size();\n    for (int turn = 0; turn < T; ++turn) {\n        const vector<Op> &ops = candidates[turn % C];\n        cout << ops.size() << '\\n';\n        for (const auto &op : ops) {\n            cout << op.p << ' ' << op.r << ' ' << op.d << ' ' << op.b << '\\n';\n        }\n        cout.flush();\n\n        long long Wp, Hp;\n        if (!(cin >> Wp >> Hp)) return 0;   // read the noisy result (ignored)\n    }\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- priority\u2011queue node ---------- */\nstruct PQNode {\n    int depth;\n    int negBeauty;          // -A[v]  (smaller beauty \u2192 larger value)\n    int v;\n    bool operator<(PQNode const& other) const {\n        if (depth != other.depth) return depth < other.depth;          // max\u2011heap by depth\n        return negBeauty < other.negBeauty;                            // max\u2011heap by -A (i.e. smaller A first)\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    if (!(cin >> N >> M >> H)) return 0;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n\n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    // coordinates are irrelevant for the algorithm\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    /* sort neighbours by decreasing beauty \u2013 high\u2011beauty neighbours are examined first */\n    for (int v = 0; v < N; ++v) {\n        sort(adj[v].begin(), adj[v].end(),\n             [&](int a, int b){ return A[a] > A[b]; });\n    }\n\n    const int UNSET = -2;\n    vector<int> parent(N, UNSET);\n    vector<int> depth(N, -1);\n    vector<char> assigned(N, 0);\n    int remaining = N;\n\n    priority_queue<PQNode> pq;\n\n    /* ---------- greedy construction ---------- */\n    while (remaining > 0) {\n        if (pq.empty()) {\n            // start a new tree with the still unassigned vertex of smallest beauty\n            int best = -1, bestA = INT_MAX;\n            for (int i = 0; i < N; ++i) if (!assigned[i] && A[i] < bestA) {\n                bestA = A[i];\n                best = i;\n            }\n            parent[best] = -1;\n            depth[best] = 0;\n            assigned[best] = 1;\n            --remaining;\n            pq.emplace(0, -A[best], best);\n            continue;\n        }\n\n        PQNode cur = pq.top(); pq.pop();\n        int u = cur.v;\n        if (depth[u] != cur.depth) continue;   // outdated entry\n        if (cur.depth == H) continue;          // cannot add children\n\n        // attach all still unassigned neighbours of u\n        for (int w : adj[u]) {\n            if (!assigned[w]) {\n                parent[w] = u;\n                depth[w] = cur.depth + 1;\n                assigned[w] = 1;\n                --remaining;\n                if (depth[w] < H) pq.emplace(depth[w], -A[w], w);\n            }\n        }\n    }\n\n    /* ---------- build children lists ---------- */\n    vector<vector<int>> children(N);\n    for (int v = 0; v < N; ++v) {\n        if (parent[v] != -1) children[parent[v]].push_back(v);\n    }\n\n    /* ---------- initial total score ---------- */\n    long long totalScore = 0;\n    for (int v = 0; v < N; ++v) totalScore += (long long)(depth[v] + 1) * A[v];\n\n    /* ---------- hill\u2011climbing local search ---------- */\n    std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> vertexDist(0, N - 1);\n    const double TIME_LIMIT = 1.90;   // seconds\n    auto startTime = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed > TIME_LIMIT) break;\n\n        int v = vertexDist(rng);\n        if (adj[v].empty()) continue;\n        uniform_int_distribution<int> neighDist(0, (int)adj[v].size() - 1);\n        int u = adj[v][neighDist(rng)];\n\n        // reject if u lies inside the subtree of v (would create a cycle)\n        bool inSub = false;\n        int cur = u;\n        while (cur != -1) {\n            if (cur == v) { inSub = true; break; }\n            cur = parent[cur];\n        }\n        if (inSub) continue;\n\n        int delta = depth[u] + 1 - depth[v];\n        if (delta <= 0) continue;                     // we only want deeper placement\n\n        // collect the whole subtree of v\n        vector<int> stack{v};\n        vector<int> sub;\n        sub.reserve(N);\n        long long sumA = 0;\n        int maxDepthSub = depth[v];\n        while (!stack.empty()) {\n            int x = stack.back(); stack.pop_back();\n            sub.push_back(x);\n            sumA += A[x];\n            maxDepthSub = max(maxDepthSub, depth[x]);\n            for (int c : children[x]) stack.push_back(c);\n        }\n\n        int newDeepest = depth[u] + 1 + (maxDepthSub - depth[v]);\n        if (newDeepest > H) continue;                 // would violate depth limit\n\n        long long deltaScore = (long long)delta * sumA;\n        if (deltaScore <= 0) continue;                // no improvement\n\n        // ----- perform the move -----\n        int oldParent = parent[v];\n        if (oldParent != -1) {\n            auto &vec = children[oldParent];\n            for (size_t i = 0; i < vec.size(); ++i) {\n                if (vec[i] == v) {\n                    vec[i] = vec.back();\n                    vec.pop_back();\n                    break;\n                }\n            }\n        }\n        parent[v] = u;\n        children[u].push_back(v);\n\n        for (int x : sub) depth[x] += delta;\n        totalScore += deltaScore;\n    }\n\n    /* ---------- output ---------- */\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << parent[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DirInfo {\n    char dir;                     // 'L','R','U','D'\n    int idx;                      // row or column index\n    multiset<int> dists;          // distances of assigned Oni\n    int maxDist = 0;              // 0 if empty\n};\n\nstruct OniInfo {\n    vector<int> dirIds;           // safe direction ids\n    vector<int> dists;            // distance for each dirId (same order)\n    int curDir = -1;              // currently assigned direction id\n    int curDist = -1;             // distance for curDir\n};\n\nchar opposite(char d) {\n    if (d == 'L') return 'R';\n    if (d == 'R') return 'L';\n    if (d == 'U') return 'D';\n    return 'U';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    const int MAXN = 20;\n    // create direction ids\n    int dirCnt = 0;\n    int rowL[MAXN], rowR[MAXN], colU[MAXN], colD[MAXN];\n    for (int i = 0; i < N; ++i) {\n        rowL[i] = dirCnt++;\n        rowR[i] = dirCnt++;\n    }\n    for (int j = 0; j < N; ++j) {\n        colU[j] = dirCnt++;\n        colD[j] = dirCnt++;\n    }\n    vector<DirInfo> dirs(dirCnt);\n    for (int i = 0; i < N; ++i) {\n        dirs[rowL[i]] = {'L', i, {}, 0};\n        dirs[rowR[i]] = {'R', i, {}, 0};\n    }\n    for (int j = 0; j < N; ++j) {\n        dirs[colU[j]] = {'U', j, {}, 0};\n        dirs[colD[j]] = {'D', j, {}, 0};\n    }\n\n    // collect Oni\n    vector<OniInfo> ons;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] != 'x') continue;\n            OniInfo o;\n            // safety tests\n            bool safeU = true, safeD = true, safeL = true, safeR = true;\n            for (int k = 0; k < i; ++k) if (board[k][j] == 'o') safeU = false;\n            for (int k = i + 1; k < N; ++k) if (board[k][j] == 'o') safeD = false;\n            for (int k = 0; k < j; ++k) if (board[i][k] == 'o') safeL = false;\n            for (int k = j + 1; k < N; ++k) if (board[i][k] == 'o') safeR = false;\n\n            int dU = i + 1;\n            int dD = N - i;\n            int dL = j + 1;\n            int dR = N - j;\n\n            if (safeU) {\n                o.dirIds.push_back(colU[j]);\n                o.dists.push_back(dU);\n            }\n            if (safeD) {\n                o.dirIds.push_back(colD[j]);\n                o.dists.push_back(dD);\n            }\n            if (safeL) {\n                o.dirIds.push_back(rowL[i]);\n                o.dists.push_back(dL);\n            }\n            if (safeR) {\n                o.dirIds.push_back(rowR[i]);\n                o.dists.push_back(dR);\n            }\n            ons.push_back(std::move(o));\n        }\n    }\n    int M = (int)ons.size();               // = 2*N = 40\n\n    // ---------- initial assignment (cheapest safe direction) ----------\n    for (int id = 0; id < M; ++id) {\n        int bestIdx = -1, bestDist = INT_MAX;\n        for (int k = 0; k < (int)ons[id].dirIds.size(); ++k) {\n            if (ons[id].dists[k] < bestDist) {\n                bestDist = ons[id].dists[k];\n                bestIdx = k;\n            }\n        }\n        int dir = ons[id].dirIds[bestIdx];\n        int dist = ons[id].dists[bestIdx];\n        ons[id].curDir = dir;\n        ons[id].curDist = dist;\n        dirs[dir].dists.insert(dist);\n        dirs[dir].maxDist = max(dirs[dir].maxDist, dist);\n    }\n\n    // total cost = sum 2*maxDist\n    int totalCost = 0;\n    for (auto &d : dirs) if (!d.dists.empty()) totalCost += 2 * d.maxDist;\n\n    // ---------- local improvement ----------\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        int bestDelta = 0;          // negative value = improvement\n        int bestOni = -1, bestFrom = -1, bestTo = -1;\n        int bestCurDist = -1, bestToDist = -1;\n\n        for (int oid = 0; oid < M; ++oid) {\n            int from = ons[oid].curDir;\n            int curDist = ons[oid].curDist;\n            const DirInfo &dFrom = dirs[from];\n            int oldMaxFrom = dFrom.maxDist;\n\n            for (int k = 0; k < (int)ons[oid].dirIds.size(); ++k) {\n                int to = ons[oid].dirIds[k];\n                if (to == from) continue;\n                int toDist = ons[oid].dists[k];\n                const DirInfo &dTo = dirs[to];\n                int oldMaxTo = dTo.maxDist;\n\n                // new max for 'from' after removing curDist\n                int newMaxFrom;\n                if (curDist < oldMaxFrom) {\n                    newMaxFrom = oldMaxFrom;\n                } else { // curDist == oldMaxFrom\n                    int cnt = dFrom.dists.count(oldMaxFrom);\n                    if (cnt >= 2) {\n                        newMaxFrom = oldMaxFrom;\n                    } else {\n                        if (dFrom.dists.size() == 1) newMaxFrom = 0;\n                        else {\n                            auto it = dFrom.dists.rbegin();\n                            ++it; // second largest\n                            newMaxFrom = *it;\n                        }\n                    }\n                }\n\n                // new max for 'to' after inserting toDist\n                int newMaxTo = max(oldMaxTo, toDist);\n\n                int newCost = totalCost - 2 * oldMaxFrom - 2 * oldMaxTo\n                              + 2 * newMaxFrom + 2 * newMaxTo;\n                int delta = newCost - totalCost; // negative = improvement\n                if (delta < bestDelta) {\n                    bestDelta = delta;\n                    bestOni = oid;\n                    bestFrom = from;\n                    bestTo = to;\n                    bestCurDist = curDist;\n                    bestToDist = toDist;\n                }\n            }\n        }\n\n        if (bestDelta < 0) {\n            // apply the best move\n            // erase from old direction\n            auto &setFrom = dirs[bestFrom].dists;\n            auto it = setFrom.find(bestCurDist);\n            setFrom.erase(it);\n            dirs[bestFrom].maxDist = setFrom.empty() ? 0 : *setFrom.rbegin();\n\n            // insert into new direction\n            auto &setTo = dirs[bestTo].dists;\n            setTo.insert(bestToDist);\n            dirs[bestTo].maxDist = *setTo.rbegin();\n\n            // update Oni info\n            ons[bestOni].curDir = bestTo;\n            ons[bestOni].curDist = bestToDist;\n\n            totalCost += bestDelta;\n            improved = true;\n        }\n    }\n\n    // ---------- output ----------\n    vector<pair<char,int>> out;\n    for (int d = 0; d < dirCnt; ++d) {\n        int D = dirs[d].maxDist;\n        if (D == 0) continue;\n        char dir = dirs[d].dir;\n        int idx = dirs[d].idx;\n        for (int k = 0; k < D; ++k) out.emplace_back(dir, idx);\n        for (int k = 0; k < D; ++k) out.emplace_back(opposite(dir), idx);\n    }\n\n    for (auto [c, p] : out) {\n        cout << c << ' ' << p << '\\n';\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\n/* ------------------------------------------------------------\n   Global data (read once in main)\n   ------------------------------------------------------------ */\nint N;                     // number of employees (always 100)\nint L;                     // number of weeks (always 500000)\nvector<int> T;             // target frequencies\n\n/* ------------------------------------------------------------\n   Full simulation \u2013 exact error after L weeks\n   ------------------------------------------------------------ */\nstatic ll simulate_full(const int a[], const int b[]) {\n    static int cnt[200];\n    memset(cnt, 0, N * sizeof(int));\n\n    int cur = 0;\n    for (int step = 0; step < L; ++step) {\n        int t = cnt[cur];\n        ++cnt[cur];\n        cur = (t & 1) ? a[cur] : b[cur];\n    }\n\n    ll err = 0;\n    for (int i = 0; i < N; ++i) err += llabs((ll)cnt[i] - (ll)T[i]);\n    return err;\n}\n\n/* ------------------------------------------------------------\n   Build a random candidate (a,b) respecting the target indegree\n   ------------------------------------------------------------ */\nstatic void build_candidate(int a[], int b[], mt19937_64 &rng) {\n    /* a : random permutation (the base cycle) */\n    vector<int> perm(N);\n    iota(perm.begin(), perm.end(), 0);\n    shuffle(perm.begin(), perm.end(), rng);\n    for (int i = 0; i < N; ++i) a[i] = perm[i];\n\n    /* ----- target indegree ----- */\n    const double factor = (2.0 * N) / static_cast<double>(L);   // = 0.0004\n    vector<double> w(N);\n    for (int i = 0; i < N; ++i) w[i] = T[i] * factor;\n\n    vector<int> extra(N, 0);\n    vector<double> frac(N, -1e9);\n    int baseSum = 0;\n    for (int i = 0; i < N; ++i) {\n        double val = w[i] - 1.0;                // one indegree already from the cycle\n        if (val > 0.0) {\n            int base = static_cast<int>(floor(val));\n            extra[i] = base;\n            frac[i]  = val - base;\n            baseSum  += base;\n        }\n    }\n    int need = N - baseSum;                     // still missing incoming edges\n    if (need > 0) {\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int i, int j){ return frac[i] > frac[j]; });\n        for (int k = 0; k < need; ++k) ++extra[order[k]];\n    }\n\n    /* ----- b : distribute the remaining indegree ----- */\n    vector<int> pool;\n    pool.reserve(N);\n    for (int i = 0; i < N; ++i)\n        for (int k = 0; k < extra[i]; ++k) pool.push_back(i);\n    // safety \u2013 should be exactly N\n    while ((int)pool.size() < N) pool.push_back(rng() % N);\n    while ((int)pool.size() > N) pool.pop_back();\n\n    shuffle(pool.begin(), pool.end(), rng);\n    for (int i = 0; i < N; ++i) b[i] = pool[i];\n}\n\n/* ------------------------------------------------------------ */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N >> L)) return 0;\n    T.resize(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    int best_a[200], best_b[200];\n    int cur_a[200],  cur_b[200];\n    ll best_err = LLONG_MAX;\n\n    /* ---- a few random candidates, keep the best ---- */\n    for (int trial = 0; trial < 6; ++trial) {\n        build_candidate(cur_a, cur_b, rng);\n        ll err = simulate_full(cur_a, cur_b);\n        if (err < best_err) {\n            best_err = err;\n            memcpy(best_a, cur_a, N * sizeof(int));\n            memcpy(best_b, cur_b, N * sizeof(int));\n        }\n    }\n    memcpy(cur_a, best_a, N * sizeof(int));\n    memcpy(cur_b, best_b, N * sizeof(int));\n    ll cur_err = best_err;\n\n    /* ---- light hill climbing (time limited) ---- */\n    const double TIME_LIMIT = 1.75;          // seconds, safe margin\n    const int   CHECK_EVERY = 20;           // check clock every few iterations\n    auto start = chrono::steady_clock::now();\n\n    for (int iter = 0; ; ++iter) {\n        if (iter % CHECK_EVERY == 0) {\n            auto now = chrono::steady_clock::now();\n            double elapsed = chrono::duration<double>(now - start).count();\n            if (elapsed > TIME_LIMIT) break;\n        }\n\n        int move_type = rng() % 100;        // 0\u201159 : swap b, 60\u201179 : swap a, 80\u201199 : flip\n        int i = rng() % N;\n        int j = rng() % N;\n        bool applied = false;\n\n        if (move_type < 60) {               // swap two b\u2011edges\n            if (i == j) continue;\n            swap(cur_b[i], cur_b[j]);\n            applied = true;\n        } else if (move_type < 80) {        // swap two a\u2011edges\n            if (i == j) continue;\n            swap(cur_a[i], cur_a[j]);\n            applied = true;\n        } else {                            // flip a[i] and b[i]\n            i = rng() % N;\n            swap(cur_a[i], cur_b[i]);\n            applied = true;\n        }\n        if (!applied) continue;\n\n        ll err = simulate_full(cur_a, cur_b);\n        if (err < best_err) {\n            best_err = err;\n            memcpy(best_a, cur_a, N * sizeof(int));\n            memcpy(best_b, cur_b, N * sizeof(int));\n        }\n        if (err < cur_err) {\n            cur_err = err;\n        } else {\n            // revert the move\n            if (move_type < 60) swap(cur_b[i], cur_b[j]);\n            else if (move_type < 80) swap(cur_a[i], cur_a[j]);\n            else swap(cur_a[i], cur_b[i]);\n        }\n    }\n\n    /* ---- output the best pair found ---- */\n    for (int i = 0; i < N; ++i) {\n        cout << best_a[i] << ' ' << best_b[i] << '\\n';\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\n/*** Edge for Kruskal on representatives ***/\nstruct RepEdge {\n    int u, v;\n    long long w2;               // squared centre distance\n    bool operator<(RepEdge const& o) const { return w2 < o.w2; }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n    vector<int> G(M);\n    for (int &x : G) cin >> x;\n\n    vector<int> lx(N), rx(N), ly(N), ry(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n\n    /* centre of each rectangle */\n    vector<long long> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        cx[i] = (static_cast<long long>(lx[i]) + rx[i]) / 2;\n        cy[i] = (static_cast<long long>(ly[i]) + ry[i]) / 2;\n    }\n\n    /* ---------- 1. greedy clustering ---------- */\n    vector<char> assigned(N, 0);\n    vector<int> remaining(N);\n    iota(remaining.begin(), remaining.end(), 0);\n    vector<vector<int>> groups;\n    groups.reserve(M);\n\n    for (int gi = 0; gi < M; ++gi) {\n        int need = G[gi];\n        vector<int> group;\n        group.reserve(need);\n\n        /* choose seed = city with smallest cx among remaining */\n        int seed = -1;\n        long long bestX = LLONG_MAX;\n        for (int v : remaining) {\n            if (cx[v] < bestX) {\n                bestX = cx[v];\n                seed = v;\n            }\n        }\n        group.push_back(seed);\n        assigned[seed] = 1;\n        remaining.erase(remove(remaining.begin(), remaining.end(), seed), remaining.end());\n\n        /* bestDist for each still unassigned city (distance to the current group) */\n        const long long INF = (1LL << 62);\n        vector<long long> bestDist(N, INF);\n        for (int v : remaining) {\n            long long dx = cx[v] - cx[seed];\n            long long dy = cy[v] - cy[seed];\n            bestDist[v] = dx * dx + dy * dy;\n        }\n\n        while ((int)group.size() < need) {\n            int bestCity = -1;\n            long long bestD = INF;\n            for (int v : remaining) {\n                if (bestDist[v] < bestD) {\n                    bestD = bestDist[v];\n                    bestCity = v;\n                }\n            }\n            // add bestCity\n            group.push_back(bestCity);\n            assigned[bestCity] = 1;\n            remaining.erase(remove(remaining.begin(), remaining.end(), bestCity), remaining.end());\n\n            // update bestDist for the rest\n            for (int v : remaining) {\n                long long dx = cx[v] - cx[bestCity];\n                long long dy = cy[v] - cy[bestCity];\n                long long d2 = dx * dx + dy * dy;\n                if (d2 < bestDist[v]) bestDist[v] = d2;\n            }\n        }\n        groups.emplace_back(move(group));\n    }\n\n    /* ---------- 2. build roads ---------- */\n    vector<vector<pair<int,int>>> groupEdges(M);\n    int queries_used = 0;\n\n    for (int gi = 0; gi < M; ++gi) {\n        const vector<int> &g = groups[gi];\n        int gsz = (int)g.size();\n        if (gsz <= 1) continue;               // nothing to do\n\n        /* split into chunks of size \u2264 L */\n        vector<vector<int>> chunks;\n        for (int i = 0; i < gsz; ) {\n            int sz = min(L, gsz - i);\n            chunks.emplace_back(g.begin() + i, g.begin() + i + sz);\n            i += sz;\n        }\n\n        /* query each chunk (size \u2265 2) */\n        for (auto &ch : chunks) {\n            int sz = (int)ch.size();\n            if (sz <= 1) continue;\n            cout << \"? \" << sz;\n            for (int v : ch) cout << ' ' << v;\n            cout << \"\\n\" << flush;\n            ++queries_used;\n\n            for (int i = 0; i < sz - 1; ++i) {\n                int a, b;\n                cin >> a >> b;\n                groupEdges[gi].emplace_back(a, b);\n            }\n        }\n\n        /* representatives = first city of each chunk */\n        vector<int> reps;\n        reps.reserve(chunks.size());\n        for (auto &ch : chunks) reps.push_back(ch[0]);\n\n        int c = (int)reps.size();\n        if (c <= 1) continue;                // already connected\n\n        /* build MST on representatives using centre distances */\n        vector<RepEdge> edges;\n        edges.reserve(c * (c - 1) / 2);\n        for (int i = 0; i < c; ++i) {\n            for (int j = i + 1; j < c; ++j) {\n                long long dx = cx[reps[i]] - cx[reps[j]];\n                long long dy = cy[reps[i]] - cy[reps[j]];\n                long long d2 = dx * dx + dy * dy;\n                edges.push_back({reps[i], reps[j], d2});\n            }\n        }\n        sort(edges.begin(), edges.end());\n\n        // map city id -> index in reps (0 \u2026 c\u20111)\n        unordered_map<int,int> idx;\n        idx.reserve(c * 2);\n        for (int i = 0; i < c; ++i) idx[reps[i]] = i;\n\n        DSU dsu(c);\n        for (auto &e : edges) {\n            int u = idx[e.u];\n            int v = idx[e.v];\n            if (dsu.unite(u, v)) {\n                groupEdges[gi].push_back({e.u, e.v});\n            }\n        }\n    }\n\n    /* ---------- 3. output answer ---------- */\n    cout << \"!\\n\";\n    for (int gi = 0; gi < M; ++gi) {\n        const auto &g = groups[gi];\n        for (size_t i = 0; i < g.size(); ++i) {\n            if (i) cout << ' ';\n            cout << g[i];\n        }\n        cout << \"\\n\";\n        for (auto [a,b] : groupEdges[gi]) {\n            cout << a << ' ' << b << \"\\n\";\n        }\n    }\n    cout.flush();\n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct PrevInfo {\n    int prev;      // previous cell id, -1 for start\n    char act;      // 'M' or 'S'\n    char dir;      // 'U','D','L','R'\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    if (!(cin >> N >> M)) return 0;          // read board size and number of points\n\n    vector<pair<int,int>> pos(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> pos[i].first >> pos[i].second;\n    }\n\n    // direction data\n    const char dch[4] = {'U','D','L','R'};\n    const int dr[4] = {-1, 1, 0, 0};\n    const int dc[4] = {0, 0, -1, 1};\n\n    int cur_r = pos[0].first;\n    int cur_c = pos[0].second;\n\n    const int V = N * N;                     // number of cells\n\n    // helper to convert (r,c) to a single id\n    auto id = [&](int r, int c) { return r * N + c; };\n\n    for (int idx = 1; idx < M; ++idx) {\n        int tr = pos[idx].first;\n        int tc = pos[idx].second;\n\n        // ---------- BFS from current position ----------\n        vector<int> dist(V, -1);\n        vector<PrevInfo> prev(V, {-1, 0, 0});\n        queue<int> q;\n\n        int start = id(cur_r, cur_c);\n        dist[start] = 0;\n        q.push(start);\n\n        while (!q.empty()) {\n            int cur = q.front(); q.pop();\n            int r = cur / N;\n            int c = cur % N;\n            int dcur = dist[cur];\n\n            // 4 moves\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + dr[d];\n                int nc = c + dc[d];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                int nid = id(nr, nc);\n                if (dist[nid] == -1) {\n                    dist[nid] = dcur + 1;\n                    prev[nid] = {cur, 'M', dch[d]};\n                    q.push(nid);\n                }\n            }\n\n            // 4 slides \u2013 slide straight to the border in each direction\n            for (int d = 0; d < 4; ++d) {\n                int nr = r, nc = c;\n                if (d == 0) nr = 0;          // up\n                else if (d == 1) nr = N - 1; // down\n                else if (d == 2) nc = 0;     // left\n                else if (d == 3) nc = N - 1; // right\n                if (nr == r && nc == c) continue; // already at border\n                int nid = id(nr, nc);\n                if (dist[nid] == -1) {\n                    dist[nid] = dcur + 1;\n                    prev[nid] = {cur, 'S', dch[d]};\n                    q.push(nid);\n                }\n            }\n        }\n\n        // ---------- reconstruct shortest path ----------\n        int target_id = id(tr, tc);\n        vector<pair<char,char>> actions;   // (action, direction) in reverse order\n        int cur = target_id;\n        while (cur != start) {\n            const PrevInfo &p = prev[cur];\n            actions.emplace_back(p.act, p.dir);\n            cur = p.prev;\n        }\n        reverse(actions.begin(), actions.end());\n\n        // ---------- output ----------\n        for (auto [a, d] : actions) {\n            cout << a << ' ' << d << '\\n';\n        }\n\n        // update current position\n        cur_r = tr;\n        cur_c = tc;\n    }\n\n    return 0;\n}"}}}