{"model_name":"nemotron-3-super","codes":{"1":{"ahc001":"#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<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    const int W = 10000, H = 10000;\n    size_t totalCells = static_cast<size_t>(W) * H;\n    vector<uint8_t> occ(totalCells, 0); // 0 = free, else company id+1\n    vector<int> a(n), b(n), c(n), d(n);\n    vector<long long> area(n, 1);\n    for (int i = 0; i < n; ++i) {\n        a[i] = x[i];\n        b[i] = y[i];\n        c[i] = x[i] + 1;\n        d[i] = y[i] + 1;\n        occ[static_cast<size_t>(b[i]) * W + a[i]] = static_cast<uint8_t>(i + 1);\n    }\n\n    auto try_expand = [&](int i) -> bool {\n        if (area[i] >= r[i]) return false;\n        long long deficit = r[i] - area[i];\n        int best_dir = -1; // 0:left,1:right,2:down,3:up        int best_strip = 0;\n\n        int width = c[i] - a[i];\n        int height = d[i] - b[i];\n\n        // left\n        if (a[i] > 0) {\n            int strip = height; // area added by expanding left one column\n            if (strip <= deficit) {\n                int xcol = a[i] - 1;\n                bool free = true;\n                for (size_t yc = b[i]; yc < d[i]; ++yc) {\n                    if (occ[static_cast<size_t>(yc) * W + xcol]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 0;\n                    best_strip = strip;\n                }\n            }\n        }\n        // right\n        if (c[i] < W) {\n            int strip = height;\n            if (strip <= deficit) {\n                int xcol = c[i];\n                bool free = true;\n                for (size_t yc = b[i]; yc < d[i]; ++yc) {\n                    if (occ[static_cast<size_t>(yc) * W + xcol]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 1;\n                    best_strip = strip;\n                }\n            }\n        }\n        // down\n        if (b[i] > 0) {\n            int strip = width;\n            if (strip <= deficit) {\n                int yrow = b[i] - 1;\n                bool free = true;\n                for (size_t xc = a[i]; xc < c[i]; ++xc) {\n                    if (occ[static_cast<size_t>(yrow) * W + xc]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 2;\n                    best_strip = strip;\n                }\n            }\n        }\n        // up        if (d[i] < H) {\n            int strip = width;\n            if (strip <= deficit) {\n                int yrow = d[i];\n                bool free = true;\n                for (size_t xc = a[i]; xc < c[i]; ++xc) {\n                    if (occ[static_cast<size_t>(yrow) * W + xc]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 3;\n                    best_strip = strip;\n                }\n            }\n        }\n        if (best_dir == -1) return false;\n\n        // perform the expansion\n        switch (best_dir) {\n            case 0: { // left\n                int xcol = a[i] - 1;\n                for (size_t yc = b[i]; yc < d[i]; ++yc) {\n                    occ[static_cast<size_t>(yc) * W + xcol] = static_cast<uint8_t>(i + 1);\n                }\n                a[i] -= 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 1: { // right\n                int xcol = c[i];\n                for (size_t yc = b[i]; yc < d[i]; ++yc) {\n                    occ[static_cast<size_t>(yc) * W + xcol] = static_cast<uint8_t>(i + 1);\n                }\n                c[i] += 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 2: { // down\n                int yrow = b[i] - 1;\n                for (size_t xc = a[i]; xc < c[i]; ++xc) {\n                    occ[static_cast<size_t>(yrow) * W + xc] = static_cast<uint8_t>(i + 1);\n                }\n                b[i] -= 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 3: { // up\n                int yrow = d[i];\n                for (size_t xc = a[i]; xc < c[i]; ++xc) {\n                    occ[static_cast<size_t>(yrow) * W + xc] = static_cast<uint8_t>(i + 1);\n                }\n                d[i] += 1;\n                area[i] += best_strip;\n                break;\n            }\n        }\n        return true;\n    };\n\n    vector<bool> active(n, true);\n    deque<int> q;\n    for (int i = 0; i < n; ++i) {\n        if (area[i] < r[i]) q.push_back(i);\n        else active[i] = false;\n    }\n\n    while (!q.empty()) {\n        int i = q.front();\n        q.pop_front();\n        if (!active[i]) continue;\n        if (area[i] >= r[i]) {\n            active[i] = false;\n            continue;\n        }\n        if (try_expand(i)) {\n            if (area[i] < r[i]) {\n                q.push_back(i);\n            }\n        } else {\n            active[i] = false;\n        }\n    }\n\n    for (int i = 0; i < n; ++i) {\n        cout << a[i] << ' ' << b[i] << ' ' << c[i] << ' ' << d[i] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Result {\n    string path;\n    int score;\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        vector<vector<int>> t(50, vector<int>(50));\n    vector<vector<int>> p(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            cin >> t[i][j];\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            cin >> p[i][j];\n    \n    // Determine number of tiles (M) and max tile id\n    int maxTileId = 0;\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            maxTileId = max(maxTileId, t[i][j]);\n    int M = maxTileId + 1; // tiles are numbered 0..M-1\n    \n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char dirChar[4] = {'U', 'D', 'L', 'R'};\n    \n    // Helper to simulate one walk with given seed\n    auto simulate = [&](int seed) -> Result {\n        vector<vector<bool>> visited(50, vector<bool>(50, false));\n        vector<bool> tileVisited(M, false);\n        \n        int ci = si, cj = sj;\n        visited[ci][cj] = true;\n        int startTile = t[ci][cj];\n        tileVisited[startTile] = true;\n        \n        string path;\n        int score = p[ci][cj];\n        int visitedTiles = 1;\n        mt19937 rng(seed);\n        \n        while (true) {\n            vector<int> cand;\n            for (int d = 0; d < 4; ++d) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                if (ni < 0 || ni >= 50 || nj < 0 || nj >= 50) continue;\n                if (visited[ni][nj]) continue;\n                int tid = t[ni][nj];\n                if (tileVisited[tid]) continue; // tile already used                cand.push_back(d);\n            }\n            if (cand.empty()) break;\n            \n            // Warnsdorff: choose neighbor with minimal onward degree\n            int bestForward = 1e9;\n            vector<int> bestDirs;\n            for (int d : cand) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                int forward = 0;\n                for (int d2 = 0; d2 < 4; ++d2) {\n                    int ni2 = ni + di[d2];\n                    int nj2 = nj + dj[d2];\n                    if (ni2 < 0 || ni2 >= 50 || nj2 < 0 || nj2 >= 50) continue;\n                    if (visited[ni2][nj2]) continue;\n                    int tid2 = t[ni2][nj2];\n                    if (tileVisited[tileVisible(tid2)]) continue; // placeholder\n                    // Actually we need to check tileVisited for neighbor cell\n                    if (tileVisited[tid2]) continue;\n                    ++forward;\n                }\n                if (forward < bestForward) {\n                    bestForward = forward;\n                    bestDirs.clear();\n                    bestDirs.push_back(d);\n                } else if (forward == bestForward) {\n                    bestDirs.push_back(d);\n                }\n            }\n                        // Among ties, prefer higher p value            int bestP = -1;\n            vector<int> bestDirs2;\n            for (int d : bestDirs) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                if (p[ni][nj] > bestP) {\n                    bestP = p[ni][nj];\n                    bestDirs2.clear();\n                    bestDirs2.push_back(d);\n                } else if (p[ni][nj] == bestP) {\n                    bestDirs2.push_back(d);\n                }\n            }\n            uniform_int_distribution<int> dist(0, (int)bestDirs2.size() - 1);\n            int chosen = bestDirs2[dist(rng)];\n            \n            ci += di[chosen];\n            cj += dj[chosen];\n            visited[ci][cj] = true;\n            int tid = t[ci][cj];\n            tileVisited[tid] = true;\n            ++visitedTiles;\n            path.push_back(dirChar[chosen]);\n            score += p[ci][cj];\n            \n            // Early stop if we have visited all tiles\n            if (visitedTiles == M) break;\n        }\n        return {path, score};\n    };\n    \n    // Run multiple random restarts and keep the best path\n    const int ITER = 50; // adjust if needed\n    Result best;\n    best.score = -1;\n    for (int it = 0; it < ITER; ++it) {\n        int seed = chrono::steady_clock::now().time_since_epoch().count() + it * 123457;\n        Result cur = simulate(seed);\n        if (cur.score > best.score) {\n            best = cur;\n        }\n    }\n    \n    cout << best.path << '\\n';\n    return 0;\n}","ahc003":"","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20; // fixed\n\nstruct CellEntry {\n    int pid;      // placement id    uint8_t off;  // offset within the placement\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    cin >> N >> M; // N is always 20, but read anyway\n    vector<string> strs(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strs[i];\n    }\n\n    // convert strings to integer representation 0-7 for A-H, 8 for '.'\n    vector<string> raw = strs; // keep original for required char lookup\n    vector<vector<int>> a(N, vector<int>(N, 0));\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_val(0, 7); // A-H only for initial matrix\n    int dot_cnt = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            a[i][j] = dist_val(rng);\n        }\n    }\n\n    // placement data\n    vector<int> placement_sid; // placement -> string id    vector<vector<vector<CellEntry>>> cell_entries(N, vector<vector<CellEntry>>(N));\n    vector<int> placement_mismatch; // per placement\n    vector<int> match_cnt_str(M, 0); // number of matching placements per string\n    int satisfied = 0;\n\n    const int dr[2] = {0, 1};\n    const int dc[2] = {1, 0};\n\n    // Build placements and initial mismatch counts\n    for (int sid = 0; sid < M; ++sid) {\n        const string& s = raw[sid];\n        int L = (int)s.size();\n        for (int dir = 0; dir < 2; ++dir) {\n            for (int sr = 0; sr < N; ++sr) {\n                for (int sc = 0; sc < N; ++sc) {\n                    int pid = (int)placement_sid.size();\n                    placement_sid.push_back(sid);\n                    int mis = 0;\n                    for (int k = 0; k < L; ++k) {\n                        int r = (sr + dr[dir] * k) % N;\n                        int c = (sc + dc[dir] * k) % N;\n                        cell_entries[r][c].push_back({pid, (uint8_t)k});\n                        int required = raw[sid][k] - 'A';\n                        if (a[r][c] != required) ++mis;\n                    }\n                    placement_mismatch.push_back(mis);\n                    if (mis == 0) {\n                        ++match_cnt_str[sid];\n                    }\n                }\n            }\n        }\n    }\n    for (int sid = 0; sid < M; ++sid) {\n        if (match_cnt_str[sid] > 0) ++satisfied;\n    }\n\n    // Helper lambdas for evaluating and applying a cell change\n    auto evaluate_delta = [&](int r, int c, int new_val) -> int {\n        int old_val = a[r][c];\n        if (old_val == new_val) return 0;\n        static vector<int> delta_match;\n        static vector<int> touched;\n        if ((int)delta_match.size() < M) delta_match.assign(M, 0);\n        else fill(delta_match.begin(), delta_match.end(), 0);\n        touched.clear();\n\n        for (const auto& e : cell_entries[r][c]) {\n            int pid = e.pid;\n            int off = e.off;\n            int sid = placement_sid[pid];\n            int required = raw[sid][off] - 'A';\n            int old_matched = (old_val == required);\n            int new_matched = (new_val == required);\n            int delta_mismatch = old_matched - new_matched; // change in mismatch count\n            int old_mis = placement_mismatch[pid];\n            bool old_match = (old_mis == 0);\n            int new_mis = old_mis + delta_mismatch;\n            bool new_match = (new_mis == 0);\n            if (old_match != new_match) {\n                int delta = new_match ? 1 : -1;\n                if (delta_match[sid] == 0) touched.push_back(sid);\n                delta_match[sid] += delta;\n            }\n        }\n\n        int delta_sat = 0;\n        for (int sid : touched) {\n            int old_match_cnt = match_cnt_str[sid];\n            bool old_sat = (old_match_cnt > 0);\n            int new_match_cnt = old_match_cnt + delta_match[sid];\n            bool new_sat = (new_match_cnt > 0);\n            if (!old_sat && new_sat) ++delta_sat;\n            else if (old_sat && !new_sat) --delta_sat;\n            delta_match[sid] = 0; // reset for next use\n        }\n        touched.clear();\n        return delta_sat;\n    };\n\n    auto apply_change = [&](int r, int c, int new_val) {\n        int old_val = a[r][c];\n        if (old_val == new_val) return;\n        a[r][c] = new_val;\n        // update dot count\n        if (old_val == 8) --dot_cnt;\n        if (new_val == 8) ++dot_cnt;\n\n        for (const auto& e : cell_entries[r][c]) {\n            int pid = e.pid;\n            int off = e.off;\n            int sid = placement_sid[pid];\n            int required = raw[sid][off] - 'A';\n            int old_matched = (old_val == required);\n            int new_matched = (new_val == required);\n            int delta_mismatch = old_matched - new_matched;\n            int& mis = placement_mismatch[pid];\n            int old_mis = mis;\n            bool old_match = (old_mis == 0);\n            mis += delta_mismatch;\n            bool new_match = (mis == 0);\n            if (old_match != new_match) {\n                int delta = new_match ? 1 : -1;\n                int old_match_cnt = match_cnt_str[sid];\n                match_cnt_str[sid] += delta;\n                int new_match_cnt = match_cnt_str[sid];\n                bool old_sat = (old_match_cnt > 0);\n                bool new_sat = (new_match_cnt > 0);\n                if (!old_sat && new_sat) ++satisfied;\n                else if (old_sat && !new_sat) --satisfied;\n            }\n        }\n    };\n\n    // Simulated annealing to maximize number of satisfied strings\n    const int MAX_ITER = 20000;\n    double start_temp = 2.0;\n    double end_temp = 0.001;\n    uniform_int_distribution<int> dist_cell(0, N - 1);\n    uniform_int_distribution<int> dist_val_full(0, 8); // 0-7 letters, 8 for '.'\n    uniform_real_distribution<double> dist_real(0.0, 1.0);\n\n    for (int it = 0; it < MAX_ITER; ++it) {\n        double t = start_temp * pow(end_temp / start_temp, (double)it / MAX_ITER);\n        int r = dist_cell(rng);\n        int c = dist_cell(rng);\n        int cur = a[r][c];\n        int nv = dist_val_full(rng);\n        if (nv == cur) continue;\n        int delta = evaluate_delta(r, c, nv);\n        bool accept = false;\n        if (delta > 0) accept = true;\n        else if (delta == 0 && dist_real(rng) < 0.1) accept = true;\n        else if (dist_real(rng) < exp(delta / t)) accept = true;\n        if (accept) {\n            apply_change(r, c, nv);\n        }\n    }\n\n    // Greedy phase: turn non-dot cells into '.' if it does not break any satisfied string\n    bool improved;\n    do {\n        improved = false;\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (a[r][c] == 8) continue; // already dot\n                if (evaluate_delta(r, c, 8) == 0) {\n                    apply_change(r, c, 8);\n                    improved = true;\n                }\n            }\n        }\n    } while (improved);\n\n    // Output the matrix    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int v = a[i][j];\n            if (v == 8) putchar('.');\n            else putchar('A' + v);\n        }\n        putchar('\\n');\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\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    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    string ans;\n\n    auto dirChar = [&](int i, int j, int ni, int nj) -> char {\n        if (ni == i - 1) return 'U';\n        if (ni == i + 1) return 'D';\n        if (nj == j - 1) return 'L';\n        if (nj == j + 1) return 'R';\n        return '?';\n    };\n\n    function<void(int, int)> dfs = [&](int i, int j) {\n        visited[i][j] = true;\n        int di[4] = {-1, 1, 0, 0};\n        int dj[4] = {0, 0, -1, 1};\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + di[d];\n            int nj = j + dj[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            ans.push_back(dirChar(i, j, ni, nj));\n            dfs(ni, nj);\n            ans.push_back(dirChar(ni, nj, i, j));\n        }\n    };\n\n    dfs(si, sj);\n    cout << ans << '\\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 task difficulty vectors\n    vector<array<int, 20>> d(N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    // build dependency graph (edges u -> v, u < v)\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    // dp[i] = length of longest path (in edges) starting from i\n    vector<int> dp(N, 0);\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    // priority queue of ready tasks: higher dp first\n    using TaskInfo = pair<int, int>; // dp, task index\n    priority_queue<TaskInfo> pq;\n    vector<int> task_state(N, 0); // 0 = not started, 1 = started, 2 = completed    for (int i = 0; i < N; ++i) {\n        if (indeg[i] == 0 && task_state[i] == 0) {\n            pq.push({dp[i], i});\n        }\n    }\n\n    // worker state\n    vector<int> worker_task(M, -1);       // task assigned to worker, -1 = idle\n    vector<int> worker_start_day(M, 0);   // start day of current task (valid if not idle)\n    vector<bool> worker_idle(M, true);    // true if idle\n    vector<int> finished_today;           // workers that finished at end of previous day\n\n    int day = 1;\n    while (true) {\n        // 1) process completions from previous day        for (int w : finished_today) {\n            int task = worker_task[w];\n            // t = (day-1) - start_day + 1 = day - start_day            int t = day - worker_start_day[w];\n            // (optional) could use t to infer skill levels here\n\n            // mark task as completed\n            if (task_state[task] != 1) {\n                // defensive: should not happen\n            }\n            task_state[task] = 2;\n            for (int succ : adj[task]) {\n                if (--indeg[succ] == 0 && task_state[succ] == 0) {\n                    pq.push({dp[succ], succ});\n                }\n            }\n            worker_task[w] = -1;\n            worker_idle[w] = true;\n        }\n        finished_today.clear();\n\n        // 2) assign tasks to idle workers\n        vector<pair<int, int>> assignments; // (worker+1, task+1)\n        for (int w = 0; w < M; ++w) {\n            if (!worker_idle[w]) continue;\n            if (pq.empty()) break;\n            auto [dpval, task] = pq.top(); pq.pop();\n            worker_task[w] = task;\n            worker_start_day[w] = day;\n            worker_idle[w] = false;\n            task_state[task] = 1;\n            assignments.emplace_back(w + 1, task + 1);\n        }\n\n        // 3) output assignments for today\n        cout << assignments.size();\n        for (auto &p : assignments) {\n            cout << ' ' << p.first << ' ' << p.second;\n        }\n        cout << '\\n';\n        cout.flush();\n\n        // 4) read response (workers that finished at end of today)\n        string line;\n        if (!getline(cin, line)) break;\n        stringstream ss(line);\n        int first;\n        if (!(ss >> first)) break;\n        if (first == -1) break; // all tasks done or day limit exceeded\n        int n = first;\n        finished_today.clear();\n        for (int i = 0; i < n; ++i) {\n            int w;\n            ss >> w;\n            finished_today.push_back(w - 1);\n        }\n\n        ++day;\n        // safety stop (judge will send -1 after day 2000 anyway)\n        if (day > 2000) {\n            // we will still rely on -1 to break\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Point = pair<int, int>;\n\nconst int CENTER_X = 400;\nconst int CENTER_Y = 400;\nconst int MAX_ORDERS = 1000;\nconst int SELECT_SIZE = 50;\n\nint A[MAX_ORDERS], B[MAX_ORDERS], C[MAX_ORDERS], D[MAX_ORDERS];\n\nstruct Result {\n    ll dist;\n    vector<int> order;          // order of pickups (1\u2011based)\n    vector<Point> route;        // full route including start/end\n};\n\ninline int manh(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Build a feasible route for the given set of orders (indices 0\u2011based).\nResult computeRoute(const vector<int>& sel) {\n    vector<bool> visPick(MAX_ORDERS, false), visDel(MAX_ORDERS, false);\n    vector<Point> route;\n    route.emplace_back(CENTER_X, CENTER_Y);\n    int curX = CENTER_X, curY = CENTER_Y;\n    vector<int> orderVis;\n    int remaining = 2 * (int)sel.size();\n\n    while (remaining > 0) {\n        int bestId = -1;\n        bool isPick = false;\n        int bestDist = INT_MAX;\n        for (int id : sel) {\n            if (!visPick[id]) {\n                int d = manh(curX, curY, A[id], B[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = true;\n                }\n            }\n            if (visPick[id] && !visDel[id]) {\n                int d = manh(curX, curY, C[id], D[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = false;\n                }\n            }\n        }\n        if (isPick) {\n            route.emplace_back(A[bestId], B[bestId]);\n            visPick[bestId] = true;\n            orderVis.push_back(bestId + 1); // store 1\u2011based index\n            curX = A[bestId]; curY = B[bestId];\n        } else {\n            route.emplace_back(C[bestId], D[bestId]);\n            visDel[bestId] = true;\n            curX = C[bestId]; curY = D[bestId];\n        }\n        --remaining;\n    }\n    route.emplace_back(CENTER_X, CENTER_Y);\n\n    ll total = 0;\n    for (size_t i = 0; i + 1 < route.size(); ++i) {\n        total += manh(route[i].first, route[i].second,\n                      route[i+1].first, route[i+1].second);\n    }\n    return {total, orderVis, route};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int i = 0; i < MAX_ORDERS; ++i) {\n        cin >> A[i] >> B[i] >> C[i] >> D[i];\n    }\n\n    // ----- initial selection based on simple round\u2011trip score -----\n    vector<int> idx(MAX_ORDERS);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](int i, int j) {\n        int wi = manh(CENTER_X, CENTER_Y, A[i], B[i]) +\n                 manh(A[i], B[i], C[i], D[i]) +\n                 manh(C[i], D[i], CENTER_X, CENTER_Y);\n        int wj = manh(CENTER_X, CENTER_Y, A[j], B[j]) +\n                 manh(A[j], B[j], C[j], D[j]) +\n                 manh(C[j], D[j], CENTER_X, CENTER_Y);\n        return wi < wj;\n    });\n\n    vector<vector<int>> initialSelections;\n    {\n        vector<int> top50(idx.begin(), idx.begin() + SELECT_SIZE);\n        initialSelections.push_back(top50);\n    }\n    {\n        // random selection\n        vector<int> rnd(SELECT_SIZE);\n        mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n        uniform_int_distribution<int> dist(0, MAX_ORDERS-1);\n        vector<bool> taken(MAX_ORDERS, false);\n        int cnt = 0;\n        while (cnt < SELECT_SIZE) {\n            int x = dist(rng);\n            if (!taken[x]) {\n                taken[x] = true;\n                rnd[cnt++] = x;\n            }\n        }\n        initialSelections.push_back(rnd);\n    }\n    {\n        // selection by nearest pickup to center only\n        vector<int> orderByPickup = idx;\n        sort(orderByPickup.begin(), orderByPickup.end(),\n             [&](int i, int j) {\n                 return manh(CENTER_X, CENTER_Y, A[i], B[i]) <\n                        manh(CENTER_X, CENTER_Y, A[j], B[j]);\n             });\n        vector<int> pick50(orderByPickup.begin(),\n                           orderByPickup.begin() + SELECT_SIZE);\n        initialSelections.push_back(pick50);\n    }\n\n    const int MAX_ITER = 2000;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distPos(0, SELECT_SIZE-1);\n    uniform_int_distribution<int> distId(0, MAX_ORDERS-1);\n\n    ll bestDist = LLONG_MAX;\n    vector<int> bestOrder;\n    vector<Point> bestRoute;\n\n    auto currentTime = []() {\n        return chrono::duration<double>(\n            chrono::steady_clock::now().time_since_epoch()\n        ).count();\n    };\n    double startTime = currentTime();\n    double timeLimit = 1.9; // leave some margin    for (const auto& initSel : initialSelections) {\n        if (currentTime() - startTime > timeLimit) break;\n        vector<int> curSel = initSel;\n        vector<bool> inSel(MAX_ORDERS, false);\n        for (int id : curSel) inSel[id] = true;\n\n        auto [dist, order, route] = computeRoute(curSel);\n        if (dist < bestDist) {\n            bestDist = dist;\n            bestOrder = order;\n            bestRoute = route;\n        }\n\n        for (int it = 0; it < MAX_ITER; ++it) {\n            if (currentTime() - startTime > timeLimit) break;\n            int pos = distPos(rng);\n            int outId = curSel[pos];\n            int inId;\n            do {\n                inId = distId(rng);\n            } while (inSel[inId]);\n\n            // perform swap\n            curSel[pos] = inId;\n            inSel[outId] = false;\n            inSel[inId] = true;\n\n            auto [ndist, norder, nroute] = computeRoute(curSel);\n            if (ndist < bestDist) {\n                bestDist = ndist;\n                bestOrder = norder;\n                bestRoute = nroute;\n            } else {\n                // revert\n                curSel[pos] = outId;\n                inSel[outId] = true;\n                inSel[inId] = false;\n            }\n        }\n    }\n\n    // Output    cout << SELECT_SIZE << ' ';\n    for (size_t i = 0; i < bestOrder.size(); ++i) {\n        if (i) cout << ' ';\n        cout << bestOrder[i];\n    }\n    cout << '\\n';\n    cout << bestRoute.size();\n    for (auto &p : bestRoute) {\n        cout << ' ' << p.first << ' ' << p.second;\n    }\n    cout << '\\n';\n    cout << flush;\n    return```cpp\n#include<bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Point = pair<int, int>;\n\nconst int CENTER_X = 400;\nconst int CENTER_Y = 400;\nconst int MAX_ORDERS = 1000;\nconst int SELECT_SIZE = 50;\n\nint A[MAX_ORDERS], B[MAX_ORDERS], C[MAX_ORDERS], D[MAX_ORDERS];\n\nstruct Result {\n    ll dist;\n    vector<int> order;          // order of pickups (1\u2011based)\n    vector<Point> route;        // full route including start/end\n};\n\ninline int manh(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Build a feasible route for the given set of orders (indices 0\u2011based).\nResult computeRoute(const vector<int>& sel) {\n    vector<bool> visPick(MAX_ORDERS, false), visDel(MAX_ORDERS, false);\n    vector<Point> route;\n    route.emplace_back(CENTER_X, CENTER_Y);\n    int curX = CENTER_X, curY = CENTER_Y;\n    vector<int> orderVis;\n    int remaining = 2 * (int)sel.size();\n\n    while (remaining > 0) {\n        int bestId = -1;\n        bool isPick = false;\n        int bestDist = INT_MAX;\n        for (int id : sel) {\n            if (!visPick[id]) {\n                int d = manh(curX, curY, A[id], B[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = true;\n                }\n            }\n            if (visPick[id] && !visDel[id]) {\n                int d = manh(curX, curY, C[id], D[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = false;\n                }\n            }\n        }\n        if (isPick) {\n            route.emplace_back(A[bestId], B[bestId]);\n            visPick[bestId] = true;\n            orderVis.push_back(bestId + 1); // store 1\u2011based index\n            curX = A[bestId]; curY = B[bestId];\n        } else {\n            route.emplace_back(C[bestId], D[bestId]);\n            visDel[bestId] = true;\n            curX = C[bestId]; curY = D[bestId];\n        }\n        --remaining;\n    }\n    route.emplace_back(CENTER_X, CENTER_Y);\n\n    ll total = 0;\n    for (size_t i = 0; i + 1 < route.size(); ++i) {\n        total += manh(route[i].first, route[i].second,\n                      route[i+1].first, route[i+1].second);\n    }\n    return {total, orderVis, route};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int i = 0; i < MAX_ORDERS; ++i) {\n        cin >> A[i] >> B[i] >> C[i] >> D[i];\n    }\n\n    // ----- initial selection based on simple round\u2011trip score -----\n    vector<int> idx(MAX_ORDERS);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](int i, int j) {\n        int wi = manh(CENTER_X, CENTER_Y, A[i], B[i]) +\n                 manh(A[i], B[i], C[i], D[i]) +\n                 manh(C[i], D[i], CENTER_X, CENTER_Y);\n        int wj = manh(CENTER_X, CENTER_Y, A[j], B[j]) +\n                 manh(A[j], B[j], C[j], D[j]) +\n                 mangan(C[j], D[j], CENTER_X, CENTER_Y);\n        return wi < wj;\n    });\n\n    vector<vector<int>> initialSelections;\n    {\n        vector<int> top50(idx.begin(), idx.begin() + SELECT_SIZE);\n        initialSelections.push_back(top50);\n    }\n    {\n        // random selection\n        vector<int> rnd(SELECT_SIZE);\n        mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n        uniform_int_distribution<int> dist(0, MAX_ORDERS-1);\n        vector<bool> taken(MAX_ORDERS, false);\n        int cnt = 0;\n        while (cnt < SELECT_SIZE) {\n            int x = dist(rng);\n            if (!taken[x]) {\n                taken[x] = true;\n                rnd[cnt++] = x;\n            }\n        }\n        initialSelections.push_back(rnd);\n    }\n    {\n        // selection by nearest pickup to center only        vector<int> orderByPickup = idx;\n        sort(orderByPickup.begin(), orderByPickup.end(),\n             [&](int i, int j) {\n                 return manh(CENTER_X, CENTER_Y, A[i], B[i]) <\n                        manh(CENTER_X, CENTER_Y, A[j], B[j]);\n             });\n        vector<int> pick50(orderByPickup.begin(),\n                           orderByPickup.begin() + SELECT_SIZE);\n        initialSelections.push_back(pick50);\n    }\n\n    const int MAX_ITER = 2000;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distPos(0, SELECT_SIZE-1);\n    uniform_int_distribution<int> distId(0, MAX_ORDERS-1);\n\n    ll bestDist = LLONG_MAX;\n    vector<int> bestOrder;\n    vector<Point> bestRoute;\n\n    auto currentTime = []() {\n        return chrono::duration<double>(\n            chrono::steady_clock::now().time_since_epoch()\n        ).count();\n    };\n    double startTime = currentTime();\n    double timeLimit = 1.9; // leave some margin\n\n    for (const auto& initSel : initialSelections) {\n        if (currentTime() - startTime > timeLimit) break;\n        vector<int> curSel = initSel;\n        vector<bool> inSel(MAX_ORDERS, false);\n        for (int id : curSel) inSel[id] = true;\n\n        auto [dist, order, route] = computeRoute(curSel);\n        if (dist < bestDist) {\n            bestDist = dist;\n            bestOrder = order;\n            bestRoute = route;\n        }\n\n        for (int it = 0; it < MAX_ITER; ++it) {\n            if (currentTime() - startTime > timeLimit) break;\n            int pos = distPos(rng);\n            int outId = curSel[pos];\n            int inId;\n            do {\n                inId = distId(rng);\n            } while (inSel[inId]);\n\n            // perform swap\n            curSel[pos] = inId;\n            inSel[outId] = false;\n            inSel[inId] = true;\n\n            auto [ndist, norder, nroute] = computeRoute(curSel);\n            if (ndist < bestDist) {\n                bestDist = ndist;\n                bestOrder = norder;\n                bestRoute = nroute;\n            } else {\n                // revert\n                curSel[pos] = outId;\n                inSel[outId] = true;\n                inSel[inId] = false;\n            }\n        }\n    }\n\n    // Output\n    cout << SELECT_SIZE << ' ';\n    for (size_t i = 0; i < bestOrder.size(); ++i) {\n        if (i) cout << ' ';\n        cout << bestOrder[i];\n    }\n    cout << '\\n';\n    cout << bestRoute.size();\n    for (auto &p : bestRoute) {\n        cout << ' ' << p.first << ' ' << p.second;\n    }\n    cout << '\\n';\n    cout << flush;\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }\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 (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\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) cin >> x[i] >> y[i];\n\n    vector<int> u(M), v(M);\n    for (int i = 0; i < M; ++i) cin >> u[i] >> v[i];\n\n    vector<int> d(M);\n    for (int i = 0; i < M; ++i) {\n        long long dx = 1LL * x[u[i]] - x[v[i]];\n        long long dy = 1LL * y[u[i]] - y[v[i]];\n        long long dist2 = dx * dx + dy * dy;\n        double dist = sqrt((double)dist2);\n        d[i] = (int)round(dist);\n    }\n\n    DSU dsu(N);\n    int components = N;\n\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;\n        bool useful = (dsu.find(u[i]) != dsu.find(v[i]));\n        bool take = false;\n        if (useful) {\n            if (l <= 2 * d[i])          // accept relatively short edges\n                take = true;\n            else {\n                // If even assuming all remaining edges are useful we cannot\n                // reach connectivity, we must take this useful edge now.\n                int remaining = M - i - 1;\n                if (components - 1 > remaining)\n                    take = true;\n            }\n        }\n        if (take) {\n            cout << '1' << '\\n';\n            cout.flush();\n            dsu.unite(u[i], v[i]);\n            --components;\n        } else {\n            cout << '0' << '\\n';\n            cout.flush();\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;\n    vector<int> px(N), py(N), pt(N);\n    for (int i = 0; i < N; ++i) cin >> px[i] >> py[i] >> pt[i];\n\n    int M;\n    cin >> M;\n    vector<int> hx(M), hy(M);\n    for (int i = 0; i < M; ++i) cin >> hx[i] >> hy[i];\n\n    string action(M, '.');   // all humans do nothing each turn\n\n    for (int turn = 0; turn < 300; ++turn) {\n        cout << action << '\\n';\n        cout.flush();\n\n        // read pets' movement strings for this turn\n        string mv;\n        for (int i = 0; i < N; ++i) {\n            if (!(cin >> mv)) return 0;   // input ended unexpectedly\n        }\n    }\n    return 0;\n}","ahc009":"#include<bits/stdc++.h>\nusing namespace std;\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 lines, each 19 chars)\n    for (int i = 0; i < 20; ++i) {\n        string line;\n        cin >> line;\n    }\n    // Read vertical walls (20 lines, each 20 chars)\n    for (int i = 0; i < 20; ++i) {\n        string line;\n        cin >> line;\n    }\n    \n    // Output any valid string, e.g., 200 'R's (length <= 200)\n    string ans(200, 'R');\n    cout << ans << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    array<array<int, 30>, 30> tile{};\n    for (int i = 0; i < 30; ++i) {\n        string line;\n        getline(cin, line);\n        line.erase(remove(line.begin(), line.end(), ' '), line.end());\n        for (int j = 0; j < 30; ++j) tile[i][j] = line[j] - '0';\n    }\n\n    const int di[4] = {0, -1, 0, 1};\n    const int dj[4] = {-1, 0, 1, 0};\n\n    // base to[t][d] as given in the statement    const int toBase[8][4] = {\n        {1, 0, -1, -1}, //0\n        {3, -1, -1, 0}, //1\n        {-1, -1, 3, 2}, //2        {-1, 2, 1, -1}, //3\n        {1, 0, 3, 2},   //4\n        {3, 2, 1, 0},   //5        {2, -1, 0, -1}, //6\n        {-1, 3, -1, 1}  //7\n    };\n\n    // toRot[t][rot][d] = exit direction or -1 after rotating tile t by rot (90*rot CCW)\n    int toRot[8][4][4] = {};\n    for (int t = 0; t < 8; ++t) {\n        for (int rot = 0; rot < 4; ++rot) {\n            for (int d = 0; d < 4; ++d) {\n                int baseDir = (d + rot) % 4;\n                int baseExit = toBase[t][baseDir];\n                if (baseExit == -1) {\n                    toRot[t][rot][d] = -1;\n                } else {\n                    int exitDir = (baseExit - rot + 4) % 4;\n                    toRot[t][rot][d] = exitDir;\n                }\n            }\n        }\n    }\n\n    auto computeScore = [&](const vector<vector<int>>& rot) -> long long {\n        const int N = 30 * 30 * 4; // 3600\n        int stateOut[N];\n        // build stateOut\n        for (int i = 0; i < 30; ++i) {\n            for (int j = 0; j < 30; ++j) {\n                int t = tile[i][j];\n                int r = rot[i][j];\n                for (int d = 0; d < 4; ++d) {\n                    int nd = toRot[t][r][d];\n                    int id = ((i * 30) + j) * 4 + d;\n                    if (nd == -1) {\n                        stateOut[id] = -1;\n                    } else {\n                        int ni = i + di[nd];\n                        int nj = j + dj[nd];\n                        if (ni < 0 || ni >= 30 || nj < 0 || nj >= 30) {\n                            stateOut[id] = -1;\n                        } else {\n                            int opp = (nd + 2) % 4;\n                            int t2 = tile[ni][nj];\n                            int r2 = rot[ni][nj];\n                            if (toRot[t2][r2][opp] == -1) {\n                                stateOut[id] = -1;\n                            } else {\n                                int nid = ((ni * 30) + nj) * 4 + opp;\n                                stateOut[id] = nid;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        int color[N] = {0};            // 0 unvisited, 1 visiting, 2 visited\n        int posInPath[N];\n        fill(posInPath, posInPath + N, -1);\n        vector<int> path;\n        path.reserve(N);\n        long long max1 = 0, max2 = 0;\n\n        for (int u = 0; u < N; ++u) {\n            if (color[u]) continue;\n            int v = u;\n            while (true) {\n                if (color[v] == 0) {\n                    color[v] = 1;\n                    posInPath[v] = (int)path.size();\n                    path.push_back(v);\n                    int nxt = stateOut[v];\n                    if (nxt == -1) break;\n                    v = nxt;\n                    continue;\n                }\n                if (color[v] == 1) {\n                    int startIdx = posInPath[v];\n                    long long len = (long long)path.size() - startIdx;\n                    if (len > max1) {\n                        max2 = max1;\n                        max1 = len;\n                    } else if (len > max2) {\n                        max2 = len;\n                    }\n                    break;\n                }\n                if (color[v] == 2) {\n                    break;\n                }\n            }\n            for (int node : path) {\n                color[node] = 2;\n                posInPath[node] = -1;\n            }\n            path.clear();\n        }\n        return max1 * max2;\n    };\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distTile(0, 29);\n    uniform_int_distribution<int> distRot(0, 3);\n\n    long long bestScore = -1;\n    vector<vector<int>> bestRot(30, vector<int>(30, 0));\n\n    for (int rest = 0; rest < 5; ++rest) {\n        vector<vector<int>> curRot(30, vector<int>(30, 0));\n        for (int i = 0; i < 30; ++i)\n            for (int j = 0; j < 30; ++j)\n                curRot[i][j] = distRot(rng);\n        long long curScore = computeScore(curRot);\n        for (int it = 0; it < 200; ++it) {\n            int i = distTile(rng);\n            int j = distTile(rng);\n            int cur = curRot[i][j];\n            int nr = distRot(rng);\n            if (nr == cur) continue;\n            curRot[i][j] = nr;\n            long long ns = computeScore(curRot);\n            if (ns > curScore) {\n                curScore = ns;\n            } else {\n                curRot[i][j] = cur;\n            }\n        }\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestRot = curRot;\n        }\n    }\n\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            cout << bestRot[i][j];\n        }\n    }\n    cout << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions for empty movement: U, D, L, R\nconst int dr[4] = {-1, 1, 0, 0};\nconst int dc[4] = {0, 0, -1, 1};\nconst char dirChar[4] = {'U', 'D', 'L', 'R'};\nconst char oppChar[4] = {'D', 'U', 'R', 'L'}; // opposite direction for empty movement (tile moves opposite)\n\n// Compute size of largest tree component (acyclic connected component)\nint computeLargestTreeSize(const vector<vector<int>>& board) {\n    int N = (int)board.size();\n    vector<vector<int>> deg(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int v = board[i][j];\n            if (v == 0) continue;\n            // up\n            if (i > 0 && board[i-1][j] != 0) {\n                if ((v & 2) && (board[i-1][j] & 8)) ++deg[i][j];\n            }\n            // down\n            if (i+1 < N && board[i+1][j] != 0) {\n                if ((v & 8) && (board[i+1][j] & 2)) ++deg[i][j];\n            }\n            // left\n            if (j > 0 && board[i][j-1] != 0) {\n                if ((v & 1) && (board[i][j-1] & 4)) ++deg[i][j];\n            }\n            // right\n            if (j+1 < N && board[i][j+1] != 0) {\n                if ((v & 4) && (board[i][j+1] & 1)) ++deg[i][j];\n            }\n        }\n    }\n    vector<vector<char>> vis(N, vector<char>(0));\n    int best = 0;\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 cnt = 0;\n            int sumdeg = 0;\n            queue<pair<int,int>> q;\n            q.push({i, j});\n            vis[i][j] = 1;\n            while (!q.empty()) {\n                auto [x, y] = q.front(); q.pop();\n                ++cnt;\n                sumdeg += deg[x][y];\n                for (int d = 0; d < 4; ++d) {\n                    int nx = x + dr[d];\n                    int ny = y + dc[d];\n                    if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                    if (board[nx][ny] == 0) continue;\n                    if (vis[nx][ny]) continue;\n                    int a = board[x][y];\n                    int b = board[nx][ny];\n                    bool edge = false;\n                    if (nx == x-1 && ny == y) { // up\n                        if ((a & 2) && (b & 8)) edge = true;\n                    } else if (nx == x+1 && ny == y) { // down\n                        if ((a & 8) && (b & 2)) edge = true;\n                    } else if (nx == x && ny == y-1) { // left\n                        if ((a & 1) && (b & 4)) edge = true;\n                    } else if (nx == x && ny == y+1) { // right\n                        if ((a & 4) && (b & 1)) edge = true;\n                    }\n                    if (edge) {\n                        vis[nx][ny] = 1;\n                        q.push({nx, ny});\n                    }\n                }\n            }\n            int edges = sumdeg / 2;\n            if (edges == cnt - 1) { // tree component\n                if (cnt > best) best = cnt;\n            }\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, T;\n    if (!(cin >> N >> T)) return 0;\n    vector<string> raw(N);\n    for (int i = 0; i < N; ++i) cin >> raw[i];\n\n    // Build board and locate empty\n    vector<vector<int>> board(N, vector<int>(N));\n    int er = -1, ec = -1;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char ch = raw[i][j];\n            int v = (ch >= '0' && ch <= '9') ? ch - '0' : ch - 'a' + 10;\n            board[i][j] = v;\n            if (v == 0) { er = i; ec = j; }\n        }\n    }\n\n    const int full = N * N - 1;\n    string ans;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    auto validMoves = [&](int r, int c, vector<int>& out) {\n        out.clear();\n        if (r > 0) out.push_back(0); // U\n        if (r + 1 < N) out.push_back(1); // D\n        if (c > 0) out.push_back(2); // L\n        if (c + 1 < N) out.push_back(3); // R\n    };\n\n    auto simulateMove = [&](int dir) -> int {\n        int nr = er + dr[dir];\n        int nc = ec + dc[dir];\n        swap(board[er][ec], board[nr][nc]);\n        int res = computeLargestTreeSize(board);\n        swap(board[er][ec], board[nr][nc]); // revert\n        return res;\n    };\n\n    for (int step = 0; step < T; ++step) {\n        if (computeLargestTreeSize(board) == full) break; // already optimal\n\n        vector<int> mvds;\n        validMoves(er, ec, mvds);\n        shuffle(mvds.begin(), mvds.end(), rng);\n\n        int bestDir = -1;\n        int bestScore = computeLargestTreeSize(board);\n        for (int d : mvds) {\n            int s = simulateMove(d);\n            if (s > bestScore) {\n                bestScore = s;\n                bestDir = d;\n            }\n        }\n\n        if (bestDir != -1 && bestScore > computeLargestTreeSize(board)) {\n            // accept best improving move\n            int nr = er + dr[bestDir];\n            int nc = ec + dc[bestDir];\n            swap(board[er][ec], board[nr][nc]);\n            er = nr;\n            ec = nc;\n            ans.push_back(dirChar[bestDir]);\n        } else {\n            // no improving move; take a random move to keep searching\n            int idx = uniform_int_distribution<int>(0, (int)mvds.size() - 1)(rng);\n            int d = mvds[idx];\n            int nr = er + dr[d];\n            int nc = ec + dc[d];\n            swap(board[er][ec], board[nr][nc]);\n            er = nr;\n            ec = nc;\n            ans.push_back(dirChar[d]);\n        }\n        // optional early stop if ans gets too long (should not exceed T)\n        if ((int)ans.size() > T) break;\n    }\n\n    cout << ans << '\\n';\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nstruct Line {\n    ll x1, y1, x2, y2;\n    Line() {}\n    Line(ll a, ll b, ll c, ll d) : x1(a), y1(b), x2(c), y2(d) {}\n};\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    int sumA = 0;\n    for (int d = 1; d <= 10; ++d) {\n        cin >> a[d];\n        sumA += a[d];\n    }\n    vector<pair<ll, ll>> pts(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pts[i].first >> pts[i].second;\n    }\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<ll> dist(-1000000000LL, 1000000000LL);\n    uniform_int_distribution<int> distSmall(0, 1);\n\n    const int MAX_ITER = 40; // number of random attempts\n    int bestScore = -1;\n    vector<Line> bestLines;\n\n    for (int it = 0; it < MAX_ITER; ++it) {\n        vector<Line> lines;\n        lines.reserve(K);\n        // generate K random lines        for (int i = 0; i < K; ++i) {\n            while (true) {\n                ll x1 = dist(rng);\n                ll y1 = dist(rng);\n                ll x2 = dist(rng);\n                ll y2 = dist(rng);\n                if (x1 == x2 && y1 == y2) continue;\n                lines.emplace_back(x1, y1, x2, y2);\n                break;\n            }\n        }\n\n        // count strawberries per region\n        unordered_map<string, int> cnt; // region signature -> number of strawberries\n        for (auto &[x, y] : pts) {\n            bitset<100> signature;\n            bool onLine = false;\n            for (int i = 0; i < K; ++i) {\n                const Line &ln = lines[i];\n                ll cross = (ln.y2 - ln.y1) * (x - ln.x1) - (ln.x2 - ln.x1) * (y - ln.y1);\n                if (cross == 0) {\n                    onLine = true;\n                    break;\n                }\n                signature[i] = (cross > 0);\n            }\n            if (onLine) continue; // strawberry is cut, ignore\n            string key = signature.to_string();\n            cnt[key]++;\n        }\n\n        // compute b[d]\n        vector<int> b(11, 0);\n        for (auto &[_, c] : cnt) {\n            if (c >= 1 && c <= 10) {\n                b[c]++;\n            }\n            // if c > 10 we ignore because it cannot contribute to score\n        }\n\n        // compute score\n        int score = 0;\n        for (int d = 1; d <= 10; ++d) {\n            score += min(a[d], b[d]);\n        }\n\n        if (score > bestScore) {\n            bestScore = score;\n            bestLines = lines;\n        }\n    }\n\n    // output best solution\n    cout << K << '\\n';\n    for (const auto &ln : bestLines) {\n        cout << ln.x1 << ' ' << ln.y1 << ' ' << ln.x2 << ' ' << ln.y2 << '\\n';\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    bool operator==(const Point& other) const { return x == other.x && y == other.y; }\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    const int c = (N - 1) / 2;\n    vector<vector<bool>> dot(N, vector<bool>(N, false));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        dot[x][y] = true;\n    }\n\n    // Edge usage arrays\n    vector<vector<bool>> hor(N, vector<bool>(N, false)); // hor[x][y] : (x,y)-(x+1,y)\n    vector<vector<bool>> ver(N, vector<bool>(N, false)); // ver[x][y] : (x,y)-(x,y+1)\n    vector<vector<bool>> diag1(N, vector<bool>(N, false)); // diag1[x][y] : (x+1,y)-(x,y+1)\n    vector<vector<bool>> diag2(N, vector<vector<bool>>(N, false)); // diag2[x][y] : (x-1,y)-(x,y+1)\n    // Fix diag2 initialization\n    for (auto& row : diag2) fill(row.begin(), row.end(), false);\n\n    // Point -> list of shape indices containing this point as a corner    vector<vector<vector<int>>> point_shapes(N, vector<vector<int>>(N));\n\n    struct Shape {\n        int type; // 0: square (x,y lower-left), 1: diamond (cx,cy center)\n        int a, b; // parameters\n    };\n    vector<Shape> shapes;\n\n    // Squares\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y < N - 1; ++y) {\n            Shape s{0, x, y};\n            int id = (int)shapes.size();\n            shapes.push_back(s);\n            vector<Point> corners = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};\n            for (auto& p : corners) point_shapes[p.x][p.y].push_back(id);\n        }\n    }\n\n    // Diamonds\n    for (int cx = 1; cx < N - 1; ++cx) {\n        for (int cy = 1; cy < N - 1; ++cy) {\n            Shape s{1, cx, cy};\n            int id = (int)shapes.size();\n            shapes.push_back(s);\n            vector<Point> corners = {{cx + 1, cy}, {cx - 1, cy}, {cx, cy + 1}, {cx, cy - 1}};\n            for (auto& p : corners) point_shapes[p.x][p.y].push_back(id);\n        }\n    }\n\n    int S = (int)shapes.size();\n    vector<int> dot_count(S, 0);\n    for (int id = 0; id < S; ++id) {\n        const Shape& sh = shapes[id];\n        int cnt = 0;\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            vector<Point> corners = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};\n            for (auto& p : corners) if (dot[p.x][p.y]) ++cnt;\n        } else {\n            int cx = sh.a, cy = sh.b;\n            vector<Point> corners = {{cx + 1, cy}, {cx - 1, cy}, {cx, cy + 1}, {cx, cy - 1}};\n            for (auto& p : corners) if (dot[p.x][p.y]) ++cnt;\n        }\n        dot_count[id] = cnt;\n    }\n\n    auto get_missing = [&](int id, Point& missing) -> bool {\n        const Shape& sh = shapes[id];\n        vector<Point> corners;\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            corners = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};\n        } else {\n            int cx = sh.a, cy = sh.b;\n            corners = {{cx + 1, cy}, {cx - 1, cy}, {cx, cy + 1}, {cx, cy - 1}};\n        }\n        for (auto& p : corners) {\n            if (!dot[p.x][p.y]) {\n                missing = p;\n                return true;\n            }\n        }\n        return false; // should not happen when dot_count==3\n    };\n\n    auto edges_unused = [&](int id) -> bool {\n        const Shape& sh = shapes[id];\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            if (hor[x][y] || hor[x][y + 1] || ver[x][y] || ver[x + 1][y]) return false;\n        } else {\n            int cx = sh.a, cy = sh.b;\n            if (diag1[cx][cy] || diag2[cx][cy] || diag1[cx - 1][cy - 1] || diag2[cx][cy - 1])\n                return false;\n        }\n        return true;\n    };\n\n    auto mark_edges_used = [&](int id) {\n        const Shape& sh = shapes[id];\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            hor[x][y] = true;\n            hor[x][y + 1] = true;\n            ver[x][y] = true;\n            ver[x + 1][y] = true;\n        } else {\n            int cx = sh.a, cy = sh.b;\n            diag1[cx][cy] = true;\n            diag2[cx][cy] = true;\n            diag1[cx - 1][cy - 1] = true;\n            diag2[cx][cy - 1] = true;\n        }\n    };\n\n    auto push_if_eligible = [&](int id) {\n        if (dot_count[id] != 3) return;\n        Point missing;\n        if (!get_missing(id, missing)) return;\n        if (!edges_unused(id)) return;\n        int w = (missing.x - c) * (missing.x - c) + (missing.y - c) * (missing.y - c) + 1;\n        pq.push({w, id});\n    };\n\n    priority_queue<pair<int, int>> pq; // max-heap by weight\n    for (int id = 0; id < S; ++id) push_if_eligible(id);\n\n    using Op = tuple<int, int, int, int, int, int, int, int>;\n    vector<Op> ops;\n\n    auto process_shape = [&](int id) {\n        if (dot_count[id] != 3) return false;\n        Point missing;\n        if (!get_missing(id, missing)) return false;\n        if (!edges_unused(id)) return false;\n        const Shape& sh = shapes[id];\n        vector<Point> corners;\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            corners = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};\n        } else {\n            int cx = sh.a, cy = sh.b;\n            corners = {{cx + 1, cy}, {cx - 1, cy}, {cx, cy + 1}, {cx, cy - 1}};\n        }\n        int missing_idx = -1;\n        for (int i = 0; i < 4; ++i) {\n            if (corners[i] == missing) { missing_idx = i; break; }\n        }\n        vector<Point> ordered;\n        for (int k = 0; k < 4; ++k) {\n            ordered.push_back(corners[(missing_idx + k) % 4]);\n        }\n        ops.emplace_back(\n            ordered[0].x, ordered[0].y,\n            ordered[1].x, ordered[1].y,\n            ordered[2].x, ordered[2].y,\n            ordered[3].x, ordered[3].y\n        );\n        dot[missing.x][missing.y] = true;\n        mark_edges_used(id);\n        for (int sid : point_shapes[missing.x][missing.y]) {\n            ++dot_count[sid];\n            if (dot_count[sid] == 3) push_if_eligible(sid);\n        }\n        return true;\n    };\n\n    while (!pq.empty()) {\n        auto [w, id] = pq.top();\n        pq.pop();\n        process_shape(id);\n    }\n\n    cout << ops.size() << '\\n';\n    for (auto& op : ops) {\n        int x1, y1, x2, y2, x3, y3, x4, y4;\n        tie(x1, y1, x2, y2, x3, y3, x4, y4) = op;\n        cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << ' '\n             << x3 << ' ' << y3 << ' ' << x4 << ' ' << y4 << '\\n';\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*------------------------------------------------------------*/\n/*  board utilities                                            */\n/*------------------------------------------------------------*/\nusing Board = array<array<int,10>,10>;\n\n/* place a candy of given flavour into the p-th empty cell (1-indexed) */\nvoid place_candy(Board &bd, int flavour, int p) {\n    int cnt = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (bd[i][j] == 0) {\n                if (++cnt == p) {\n                    bd[i][j] = flavour;\n                    return;\n                }\n            }\n        }\n    }\n    // should never happen because p is guaranteed valid\n}\n\n/* tilt the board in the given direction:\n   0 = F (up), 1 = B (down), 2 = L (left), 3 = R (right) */\nBoard tilt(const Board &bd, int dir) {\n    Board nb{}; // all zero\n    if (dir == 0) {               // F : up\n        for (int j = 0; j < 10; ++j) {\n            int r = 0;\n            for (int i = 0; i < 10; ++i)\n                if (bd[i][j]) nb[r++][j] = bd[i][j];\n        }\n    } else if (dir == 1) {        // B : down\n        for (int i = 0; i < 10; ++i) {\n            int r = 9;\n            for (int j = 9; j >= 0; --j)\n                if (bd[i][j]) nb[i][r--] = bd[i][j];\n        }\n    } else if (dir == 2) {        // L : left\n        for (int i = 0; i < 10; ++i) {\n            int c = 0;\n            for (int j = 0; j < 10; ++j)\n                if (bd[i][j]) nb[i][c++] = bd[i][j];\n        }\n    } else {                      // dir == 3 : R : right\n        for (int i = 0; i < 10; ++i) {\n            int c = 9;\n            for (int j = 9; j >= 0; --j)\n                if (bd[i][j]) nb[i][c--] = bd[i][j];\n        }\n    }\n    return nb;\n}\n\n/* compute sum of squares of component sizes */\nint compute_score(const Board &bd) {\n    bool seen[10][10] = {};\n    int sum = 0;\n    const int dr[4] = {-1,1,0,0};\n    const int dc[4] = {0,0,-1,1};\n\n    auto bfs = [&](int sr, int sc) -> int {\n        int f = bd[sr][sc];\n        queue<pair<int,int>> q;\n        q.emplace(sr,sc);\n        seen[sr][sc] = true;\n        int sz = 0;\n        while (!q.empty()) {\n            auto [r,c] = q.front(); q.pop();\n            ++sz;\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + dr[d], nc = c + dc[d];\n                if (nr < 0 || nr >= 10 || nc < 0 || nc >= 10) continue;\n                if (seen[nr][nc] || bd[nr][nc] != f) continue;\n                seen[nr][nc] = true;\n                q.emplace(nr,nc);\n            }\n        }\n        return sz;\n    };\n\n    for (int i = 0; i < 10; ++i)\n        for (int j = 0; j < 10; ++j)\n            if (bd[i][j] != 0 && !seen[i][j]) {\n                int sz = bfs(i,j);\n                sum += sz*sz;\n            }\n    return sum;\n}\n\n/*------------------------------------------------------------*/\n/*  main                                                       */\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int flavour[100];\n    for (int i = 0; i < 100; ++i) cin >> flavour[i];\n\n    Board board{}; // all zero\n\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        if (!(cin >> p)) break;          // safety, should not happen        place_candy(board, flavour[t], p);\n\n        if (t == 99) break;              // last candy \u2013 no output        int best_dir = -1;\n        int best_val = -1;\n        for (int dir = 0; dir < 4; ++dir) {\n            Board tmp = tilt(board, dir);\n            int val = compute_score(tmp);\n            if (val > best_val) {\n                best_val = val;\n                best_dir = dir;\n            }\n        }\n        char out;\n        switch(best_dir) {\n            case 0: out = 'F'; break;\n            case 1: out = 'B'; break;\n            case 2: out = 'L'; break;\n            case 3: out = 'R'; break;\n        }\n        cout << out << '\\n';\n        cout.flush();\n\n        // really apply the chosen tilt\n        board = tilt(board, best_dir);\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    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n    const int N = 100; // maximum allowed vertices\n    const long long L = 1LL * N * (N - 1) / 2;\n\n    // Precompute expected triangle and edge counts for clique sizes k = 1..M\n    vector<double> expTri(M + 1), expEdge(M + 1);\n    for (int k = 1; k <= M; ++k) {\n        long long C3k = (k >= 3) ? 1LL * k * (k - 1) * (k - 2) / 6 : 0LL;\n        long long C2k = (k >= 2) ? 1LL * k * (k - 1) / 2 : 0LL;\n        long long iso = N - k;\n        long long C2iso = (iso >= 2) ? 1LL * iso * (iso - 1) / 2 : 0LL;\n        long long C3iso = (iso >= 3) ? 1LL * iso * (iso - 2) * (iso - 3) / 6 : 0LL; // actually iso*(iso-1)*(iso-2)/6\n\n        double oneMinusEps = 1.0 - eps;\n        double p3 = oneMinusEps * oneMinusEps * oneMinusEps;\n        double p2 = oneMinusEps * eps * eps;\n        double p1 = eps * eps * eps;\n\n        expTri[k] = C3k * p3 +\n                    C2k * iso * p2 +\n                    (1.0LL * k * C2iso + C3iso) * p1;\n\n        expEdge[k] = C2k * oneMinusEps + (L - C2k) * eps;\n    }\n\n    // Output N and the M graphs\n    cout << N << endl;\n    for (int s = 0; s < M; ++s) {\n        int k = s + 1; // clique size\n        string str;\n        str.reserve(L);\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                bool edge = (i < k && j < k); // both in the clique\n                str.push_back(edge ? '1' : '0');\n            }\n        }\n        cout << str << '\\n';\n    }\n    cout.flush();\n\n    // Process 100 queries\n    for (int qq = 0; qq < 100; ++qq) {\n        string H;\n        if (!(cin >> H)) break;\n        long long triObs = 0;\n        long long edgeObs = 0;\n        // Build adjacency and count edges\n        vector<bitset<100>> adj(N);\n        int pos = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                char c = H[pos++];\n                if (c == '1') {\n                    adj[i][j] = true;\n                    adj[j][i] = true;\n                    ++edgeObs;\n                }\n            }\n        }\n        // Count triangles\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (adj[i][j]) {\n                    triObs += ((adj[i] & adj[j]) >> (j + 1)).count();\n                }\n            }\n        }\n\n        // Find best s\n        int bestS = 0;\n        double bestDist = 1e100;\n        for (int s = 0; s < M; ++s) {\n            int k = s + 1;\n            double dt = triObs - expTri[k];\n            double de = edgeObs - expEdge[k];\n            double dist = dt * dt + de * de;\n            if (dist < bestDist) {\n                bestDist = dist;\n                bestS = s;\n            }\n        }\n        cout << bestS << '\\n';\n        cout.flush();\n    }\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    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n    // read edges (ignore their data)\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n    }\n    // read coordinates (ignore)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    // assign each edge to day in round\u2011robin fashion\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << (i % D) + 1;\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Voxel {\n    int x, y, z;\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\n    // Read silhouettes\n    vector<vector<string>> fStr(2, vector<string>(D));\n    vector<vector<string>> rStr(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> fStr[i][k];\n        }\n    }\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> rStr[i][k];\n        }\n    }\n\n    // Convert to bool arrays\n    vector<vector<vector<bool>>> f(2, vector<vector<bool>>(D, vector<bool>(D)));\n    vector<vector<vector<bool>>> r(2, vector<vector<bool>>(D, vector<bool>(D)));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int x = 0; x < D; ++x) {\n                f[i][z][x] = (fStr[i][zvoid solve() {\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int y = 0; y < D; ++y) {\n                r[i][z][y] = (rStr[i][z][y] == '1');\n            }\n        }\n    }\n}\n\n    // Collect voxels that satisfy both projections\n    vector<Voxel> vox[2];\n    for (int i = 0; i < 2; ++i) {\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[i][z][x] && r[i][z][y]) {\n                        vox[i].push_back({x, y, z});\n                    }\n                }\n            }\n        }\n    }\n\n    int v0 = (int)vox[0].size();\n    int v1 = (int)vox[1].size();\n    int n = max(v0, v1);\n\n    int size = D * D * D;\n    vector<int> b0(size, 0);\n    vector<int> b1(size, 0);\n\n    for (int i = 0; i < n; ++i) {\n        if (i < v0) {\n            const Voxel& v = vox[0][i];\n            int idx = v.x * D * D + v.y * D + v.z;\n            b0[idx] = i + 1;\n        }\n        if (i < v1) {\n            const Voxel& v = vox[1][i];\n            int idx = v.x * D * D + v.y * D + v.z;\n            b1[idx] = i + 1;\n        }\n    }\n\n    cout << n << '\\n';\n    for (int i = 0; i < size; ++i) {\n        if i > 0) cout << ' ';\n        cout << b0[i];\n    }\n    cout << '\\n';\n    for (int i = 0; i < size; ++i) {\n        if (i > 0) cout << ' ';\n        cout << b1[i];\n    }\n    cout << '\\n';\n    return 0;\n}\nint main() {\n    solve();\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\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    // skip vertex coordinates\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    // skip edges\n    for (int j = 0; j < M; ++j) {\n        int u, v, w;\n        cin >> u >> v >> w;\n    }\n    // skip resident coordinates\n    for (int k = 0; k < K; ++k) {\n        int a, b;\n        cin >> a >> b;\n    }\n    \n    // output P_i = 0 for all i\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << 0;\n    }\n    cout << '\\n';\n    // output B_j = 0 for all j\n    for (int j = 0; j < M; ++j) {\n        if (j) cout << ' ';\n        cout << 0;\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    // Read and discard the input pyramid.\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            int v;\n            cin >> v;\n        }\n    }\n    // Perform zero operations.\n    cout << 0 << '\\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 ent_r = 0;\n    const int ent_c = (D - 1) / 2;\n\n    vector<vector<bool>> blocked(D, vector<bool>(D, false));\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            blocked[i][j] = false;\n        }\n    }\n    for (int k = 0; k < N; ++k) {\n        int r, j;\n        cin >> r >> j;\n        blocked[r][j] = true;\n    }\n    // entrance is never blocked\n    blocked[ent_r][ent_c] = false;\n\n    // Precompute distances from entrance ignoring obstacles (static)\n    vector<vector<int>> dist(D, vector<int>(D, -1));\n    queue<pair<int,int>> q;\n    dist[ent_r][ent_c] = 0;\n    q.emplace(ent_r, ent_c);\n    const int dr[4] = {-1,1,0,0};\n    const int dc[4] = {0,0,-1,1};\n    while (!q.empty()) {\n        auto [r,c] = q.front(); q.pop();\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 >= D || nc < 0 || nc >= D) continue;\n            if (blocked[nr][nc]) continue;\n            if (dist[nr][nc] != -1) continue;\n            dist[nr][nc] = dist[r][c] + 1;\n            q.emplace(nr, nc);\n        }\n    }\n\n    // Build list L of eligible cells (non-obstacle, non-entrance)\n    vector<pair<int,int>> L;\n    L.reserve(D*D);\n    vector<vector<int>> idx(D, vector<int>(D, -1));\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            if (blocked[i][j]) continue;\n            if (i == ent_r && j == ent_c) continue;\n            L.emplace_back(i, j);\n            idx[i][j] = (int)L.size() - 1;\n        }\n    }\n    const int M = (int)L.size();\n    // sort L by distance, then row, then column\n    sort(L.begin(), L.end(), [&](const auto& a, const auto& b) {\n        if (dist[a.first][a.second] != dist[b.first][b.second])\n            return dist[a.first][a.second] < dist[b.first][b.second];\n        if (a.first != b.first) return a.first < b.first;\n        return a.second < b.second;\n    });\n    // rebuild idx after sorting\n    for (int i = 0; i < D; ++i) for (int j = 0; j < D; ++j) idx[i][j] = -1;\n    for (int p = 0; p < M; ++p) {\n        auto [r,c] = L[p];\n        idx[r][c] = p;\n    }\n\n    vector<vector<bool>> occupied(D, vector<bool>(D, false));\n    auto bfsReachable = [&](const vector<vector<bool>>& occ) -> vector<vector<bool>> {\n        vector<vector<bool>> reach(D, vector<bool>(D, false));\n        queue<pair<int,int>> qq;\n        if (!blocked[ent_r][ent_c] && !occ[ent_r][ent_c]) {\n            reach[ent_r][ent_c] = true;\n            qq.emplace(ent_r, ent_c);\n        }\n        while (!qq.empty()) {\n            auto [r,c] = qq.front(); qq.pop();\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 >= D || nc < 0 || nc >= D) continue;\n                if (blocked[nr][nc] || occ[nr][nc]) continue;\n                if (reach[nr][nc]) continue;\n                reach[nr][nc] = true;\n                qq.emplace(nr, nc);\n            }\n        }\n        return reach;\n    };\n\n    // articulation points on the subgraph induced by reachable cells (which is connected)\n    auto getArticulation = [&](const vector<vector<bool>>& reach) -> vector<vector<bool>> {\n        vector<vector<bool>> isArt(D, vector<bool>(D, false));\n        vector<int> tin(D*D, -1), low(D*D, -1);\n        vector<char> visited(D*D, false);\n        int timer = 0;\n        function<void(int,int,int,int)> dfs = [&](int r, int c, int pr, int pc) {\n            int id = r*D + c;\n            visited[id] = true;\n            tin[id] = low[id] = timer++;\n            int children = 0;\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 >= D || nc < 0 || nc >= D) continue;\n                if (!blocked[nr][nc] && !occ[nr][nc] && reach[nr][nc]) {\n                    int nid = nr*D + nc;\n                    if (visited[nid]) {\n                        low[id] = min(low[id], tin[nid]);\n                    } else {\n                        ++children;\n                        dfs(nr, nc, r, c);\n                        low[id] = min(low[id], low[nid]);\n                        if (pr != -1 && low[nid] >= tin[id]) {\n                            isArt[r][c] = true;\n                        }\n                    }\n                }\n            }\n            if (pr == -1 && children > 1) {\n                isArt[r][c] = true;\n            }\n        };\n        // entrance is guaranteed reachable\n        dfs(ent_r, ent_c, -1, -1);\n        return isArt;\n    };\n\n    // Main loop: place M containers\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;\n        vector<vector<bool>> reach = bfsReachable(occupied);\n        vector<vector<bool>> isArt = getArticulation(reach);\n        // gather candidates: reachable, not entrance, not occupied, not articulation        int best_r = -1, best_c = -1;\n        int best_cost = INT_MAX;\n        for (int i = 0; i < D; ++i) {\n            for (int j = 0; j < D; ++j) {\n                if (!reach[i][j]) continue;\n                if (i == ent_r && j == ent_c) continue;\n                if (occupied[i][j]) continue;\n                if (isArt[i][j]) continue;\n                int cost = abs(idx[i][j] - t);\n                if (cost < best_cost || (cost == best_cost && (i < best_r || (i == best_r && j < best_c)))) {\n                    best_cost = cost;\n                    best_r = i;\n                    best_c = j;\n                }\n            }\n        }\n        // fallback: if no candidate (should not happen), pick any reachable non-entrance non-occupied\n        if (best_r == -1) {\n            for (int i = 0; i < D; ++i) {\n                for (int j = 0; j < D; ++j) {\n                    if (!reach[i][j]) continue;\n                    if (i == ent_r && j == ent_c) continue;\n                    if (occupied[i][j]) continue;\n                    best_r = i; best_c = j;\n                    break;\n                }\n                if (best_r != -1) break;\n            }\n        }\n        occupied[best_r][best_c] = true;\n        cout << best_r << ' ' << best_c << '\\n';\n        cout.flush();\n    }\n\n    // Output transport order: increasing distance (L order)\n    for (auto [r,c] : L) {\n        cout << r << ' ' << c << '\\n';\n    }\n    // optional final flush\n    cout.flush();\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*------------------------------------------------------------*/\n/*  Constants and directions                                  */\nconst int dx[4] = {1, -1, 0, 0};\nconst int dy[4] = {0, 0, 1, -1};\n\n/*------------------------------------------------------------*/\nstruct Solver {\n    int n, m;\n    vector<vector<short>> grid;          // current colours\n    vector<int> cnt;                     // number of cells of each colour (>0)\n    vector<vector<int>> adj;             // current adjacency counts\n    vector<vector<int>> adjOrig;         // original adjacency counts (constant)\n\n    Solver(int n_, int m_) : n(n_), m(m_) {\n        grid.assign(n, vector<short>(n, 0));\n        cnt.assign(m + 1, 0);\n        adj.assign(m + 1, vector<short>(m + 1, 0));\n        adjOrig.assign(m + 1, vector<short>(m + 1, 0));\n    }\n\n    /*--------------------------------------------------------*/\n    // read the input\n    void read() {\n        cin >> n >> m;\n        grid.assign(n, vector<short>(n));\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) {\n                cin >> grid[i][j];\n                if (grid[i][j] > 0) ++cnt[grid[i][j]];\n            }\n    }\n\n    /*--------------------------------------------------------*/\n    // compute adjacency matrix from a given grid\n    void computeAdj(const vector<vector<short>>& g, vector<vector<int>>& out) {\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) {\n                int c = g[i][j];\n                for (int d = 0; d < 4; ++d) {\n                    int ni = i + dx[d], nj = j + dy[d];\n                    int nb = 0;               // outside\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n)\n                        nb = g[ni][nj];\n                    if (c == nb) continue;   // same colour \u2013 we do not store c\u2011c\n                    out[c][nb]++;\n                    out[nb][c]++;\n                }\n            }\n    }\n\n    /*--------------------------------------------------------*/\n    // zero\u2011neighbour test (outside counts as zero)\n    bool hasZeroNeighbour(int i, int j) const {\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) return true;   // outside\n            if (grid[ni][nj] == 0) return true;\n        }\n        return false;\n    }\n\n    /*--------------------------------------------------------*/\n    // BFS to check connectivity of a given colour (>0)\n    bool connectedColour(int col) const {\n        // find any cell of this colour\n        int si = -1, sj = -1;\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (grid[i][j] == col) { si = i; sj = j; break; }\n            if (si != -1) break;\n        if (si == -1) return false;   // should never happen because cnt[col]>0 checked before\n        vector<vector<char>> vis(n, vector<char>(0, false));\n        queue<pair<int,int>> q;\n        q.emplace(si, sj);\n        vis[si][sj] = 1;\n        int reached = 0;\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            ++reached;\n            for (int d = 0; d < 4; ++d) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;\n                if (grid[nx][ny] != col) continue;\n                if (vis[nx][ny]) continue;\n                vis[nx][ny] = 1;\n                q.emplace(nx, ny);\n            }\n        }\n        return reached == cnt[col];\n    }\n\n    /*--------------------------------------------------------*/\n    // check that all zero cells are reachable from the outside\n    bool zeroConnected() const {\n        vector<vector<char>> vis(n, vector<char>(0, false));\n        queue<pair<int,int>> q;\n        // start from all boundary zero cells (they touch the outside)\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] == 0 && (i == 0 || i == n-1 || j == 0 || j == n-1)) {\n                    q.emplace(i, j);\n                    vis[i][j] = 1;\n                }\n            }\n        }\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;\n                if (grid[nx][ny] != 0) continue;\n                if (vis[nx][ny]) continue;\n                vis[nx][ny] = 1;\n                q.emplace(nx, ny);\n            }\n        }\n        // any zero cell not visited?\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (grid[i][j] == 0 && !vis[i][j]) return false;\n        return true;\n    }\n\n    /*--------------------------------------------------------*/\n    // try to delete cell (i,j); return true iff deletion really happened\n    bool tryDelete(int i, int j) {\n        int col = grid[i][j];\n        if (col == 0) return false;\n        if (!hasZeroNeighbour(i, j)) return false;\n\n        // backup        int backupCnt = cnt[col];\n        vector<tuple<int,int,int>> changes;   // (a,b,delta) to be added to adj[a][b]\n\n        // process the four neighbours        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d], nj = y + dy[d];\n            int nb;\n            bool outside = false;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) { nb = 0; outside = true; }\n            else nb = grid[ni][nj];\n\n            if (nb == col) continue;          // internal edge, nothing to change\n\n            // erase edge col \u2013 nb\n            changes.emplace_back(col, nb, -1);\n            changes.emplace_back(nb, col, -1);\n\n            if (nb != 0 && !outside) {\n                // create edge 0 \u2013 nb\n                changes.emplace_back(0, nb, +1);\n                changes.emplace_back(nb, 0, +1);\n            }\n            // if nb == 0 (inside zero or outside) we only removed a col\u20110 edge\n        }\n\n        // apply changes to adj\n        for (auto &ch : changes) {\n            int a = get<0>(ch), b = get<1>(ch), delta = get<2>(ch);\n            adj[a][b] += delta;\n        }\n\n        // actually delete the cell\n        grid[i][j] = 0;\n        --cnt[col];\n\n        // ----- tests -----\n        bool ok = true;\n        if (cnt[col] == 0) ok = false;                // colour must stay non\u2011empty\n\n        if (ok) {\n            // adjacency matrix must stay exactly the same (as Boolean)\n            for (int x = 0; x <= m && ok; ++x)\n                for (int y = x; y <= m && ok; ++y)\n                    bool cur = (adj[x][y] > 0);\n                    bool orig = (adjOrig[x][y] > 0);\n                    if (cur != orig) { ok = false; break; }\n        }\n        if (ok) {\n            if (!connectedColour(col)) ok = false;\n        }\n        if (ok) {\n            if (!zeroConnected()) ok = false;\n        }\n\n        if (!ok) {\n            // ----- revert -----            grid[i][j] = col;\n            cnt[col] = backupCnt;\n            for (auto &ch : changes) {\n                int a = get<0>(ch), b = get<1>(ch), delta = get<2>(ch);\n                adj[a][b] -= delta;   // undo the addition\n            }\n            return false;\n        }\n        return true;\n    }\n\n    /*--------------------------------------------------------*/\n    void solve() {\n        read();\n        computeAdj(grid, adjOrig);\n        adj = adjOrig;          // start with the original adjacency\n\n        bool progress;\n        do {\n            progress = false;\n            vector<pair<int,int>> cand;\n            for (int i = 0; i < n; ++i)\n                for (int j = 0; j < n; ++j)\n                    if (grid[i][j] > 0)\n                        cand.emplace_back(i, j);\n            std::shuffle(cand.begin(), cand.end(),\n                         std::mt19937{std::random_device{}()});\n            for (auto &p : cand)\n                if (tryDelete(p.first, p.second))\n                    progress = true;\n        } while (progress);\n\n        // output the final grid\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << grid[i][j];\n                if (j + 1 < n) cout << ' ';\n            }\n            cout << '\\n';\n        }\n    }\n};\n\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m;\n    cin >> n >> m;\n    Solver solver(n, m);\n    solver.solve();\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    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n\n    int query_cnt = 0;\n    auto ask = [&](int a, int b) -> char {\n        assert(query_cnt < Q);\n        cout << 1 << ' ' << 1 << ' ' << a << ' ' << b << '\\n';\n        cout.flush();\n        string res;\n        cin >> res;\n        ++query_cnt;\n        return res[0];\n    };\n\n    // ---------- 1. obtain an order by (partial) comparison sort ----------\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);   // 0,1,2,...,N-1    bool exhausted = false;\n\n    for (int i = 1; i < N && !exhausted; ++i) {\n        int key = order[i];\n        int lo = 0, hi = i;                // search in [lo, hi)\n        while (lo < hi && !exhausted) {\n            if (query_cnt >= Q) { exhausted = true; break; }\n            int mid = (lo + hi) / 2;\n            char res = ask(key, order[mid]);\n            if (res == '<') {\n                hi = mid;\n            } else if (res == '>') {\n                lo = mid + 1;\n            } else { // '=' \u2013 treat as not less                lo = mid + 1;\n            }\n        }\n        if (exhausted) break;\n        int pos = lo;\n        // shift elements to make room for key\n        for (int j = i; j > pos; --j) order[j] = order[j-1];\n        order[pos] = key;\n    }\n\n    // ---------- 2. consume remaining queries with dummy comparisons ----------\n    while (query_cnt < Q) {\n        // N >= 30, so items 0 and 1 exist        ask(0, 1);\n    }\n\n    // ---------- 3. estimate weights from the obtained order ----------\n    vector<int> weight(N);               // weight estimate = rank in order    for (int i = 0; i < N; ++i) {\n        weight[order[i]] = i;            // 0 = lightest, N-1 = heaviest\n    }\n\n    // ---------- 4. LPT (greedy) partition into D groups ----------\n    vector<int64_t> group_sum(D, 0);\n    vector<int> answer(N);\n\n    // items sorted by decreasing estimated weight\n    vector<int> items(N);\n    iota(items.begin(), items.end(), 0);\n    sort(items.begin(), items.end(),\n         [&](int x, int y) { return weight[x] > weight[y]; });\n\n    for (int v : items) {\n        int g = 0;\n        for (int j = 1; j < D; ++j) {\n            if (group_sum[j] < group_sum[g]) g = j;\n        }\n        answer[v] = g;\n        group_sum[g] += weight[v];\n    }\n\n    // ---------- 5. output the partition ----------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << answer[i];\n    }\n    cout << '\\n';\n    cout.flush();\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    int per = n / m;\n    vector<vector<int>> stacks(m);\n    for (int i = 0; i < m; ++i) {\n        stacks[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x;\n            cin >> x;\n            stacks[i].push_back(x);\n        }\n    }\n\n    vector<pair<int,int>> ops;\n    ops.reserve(2 * n); // at most 2 operations per box\n\n    for (int v = 1; v <= n; ++v) {\n        int src = -1, pos = -1;\n        for (int i = 0; i < m; ++i) {\n            auto &st = stacks[i];\n            for (size_t j = 0; j < st.size(); ++j) {\n                if (st[j] == v) {\n                    src = i;\n                    pos = j;\n                    break;\n                }\n            }\n            if (src != -1) break;\n        }\n\n        int height = (int)stacks[src].size();\n        int above = height - 1 - pos; // boxes strictly above v\n\n        if (above == 0) {\n            // v is already on top, just carry it out\n            ops.emplace_back(v, 0);\n            stacks[src].pop_back();\n            continue;\n        }\n\n        // choose destination stack with minimal height (different from src)\n        int best = -1;\n        int bestHeight = 1e9;\n        for (int i = 0; i < m; ++i) {\n            if (i == src) continue;\n            int h = (int)stacks[i].size();\n            if (h < bestHeight) {\n                bestHeight = h;\n                best = i;\n            }\n        }\n        int dest = best; // guaranteed to exist because m >= 2\n\n        // move the suffix above v (pos+1 .. end) to destination stack\n        vector<int> moved;\n        moved.reserve(above);\n        for (size_t j = pos + 1; j < stacks[src].size(); ++j) {\n            moved.push_back(stacks[src][j]);\n        }\n        // erase them from source stack\n        stacks[src].erase(stacks[src].begin() + pos + 1, stacks[src].end());\n        // append to destination stack (preserving order)\n        stacks[dest].insert(stacks[dest].end(), moved.begin(), moved.end());\n\n        // operation 1: move the suffix above v\n        ops.emplace_back(v, dest + 1); // destination index is 1\u2011based in output\n        // now v is on top of its source stack\n        ops.emplace_back(v, 0);        // operation 2: carry out v        stacks[src].pop_back();        // remove v\n    }\n\n    for (auto &p : ops) {\n        cout << p.first << ' ' << p.second << '\\n';\n    }\n    return 0;\n}","ahc027":"#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\n    vector<string> h(N - 1), v(N);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    vector<vector<int>> d(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    /* ---------- adjacency helpers ---------- */\n    auto canUp = [&](int i, int j) {\n        return i > 0 && h[i - 1][j] == '0';\n    };\n    auto canDown = [&](int i, int j) {\n        return i + 1 < N && h[i][j] == '0';\n    };\n    auto canLeft = [&](int i, int j) {\n        return j > 0 && v[i][j - 1] == '0';\n    };\n    auto canRight = [&](int i, int j) {\n        return j + 1 < N && v[i][j] == '0';\n    };\n\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 oppChar[4] = {'D', 'U', 'R', 'L'};\n\n    /* ---------- DFS to visit all cells ---------- */\n    vector<string> visitedStr(N, string(N, '0'));\n    vector<vector<bool>> vis(N, vector<bool>(N, false));\n    string moves;          // the answer being built\n\n    function<void(int, int)> dfs = [&](int x, int y) {\n        vis[x][y] = true;\n        for (int dir = 0; dir < 4; ++dir) {\n            int nx = x + dx[dir];\n            int ny = y + dy[dir];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            bool ok = false;\n            if (dir == 0) ok = canUp(x, y);\n            else if (dir == 2) ok = canLeft(x, y);\n            else if (dir == 1) ok = canDown(x, y);\n            else if (dir == 3) ok = canRight(x, y);\n            if (!ok || vis[nx][ny]) continue;\n            moves.push_back(dirChar[dir]);\n            dfs(nx, ny);\n            moves.push_back(oppChar[dir]);\n        }\n    };\n    dfs(0, 0);\n\n    int baseLen = (int)moves.size();\n\n    /* ---------- choose best neighbour of (0,0) for loops ---------- */\n    struct NB {\n        char dir;\n        int ni, nj;\n        int val;\n        double rnd;\n    };\n    vector<NB> cand;\n    for (int dir = 0; dir < 4; ++dir) {\n        int nx = dx[dir];\n        int ny = dy[dir];\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n        bool ok = false;\n        if (dir == 0) ok = canUp(0, 0);\n        else if (dir == 2) ok = canLeft(0, 0);\n        else if (dir == 1) ok = canDown(0, 0);\n        else if (dir == 3) ok = canRight(0, 0);\n        if (!ok) continue;\n        cand.push_back({dir, nx, ny, d[nx][ny],\n                        (double)rand() / RAND_MAX});\n    }\n    /* sort by descending d, break ties randomly */\n    auto rng = mt19937(chrono::steady_clock::now().time_since_epoch().count());\n    shuffle(cand.begin(), cand.end(), rng);\n    sort(cand.begin(), cand.end(),\n         [](const NB& a, const NB& b) {\n             if (a.val != b.val) return a.val > b.val;\n             return a.rnd < b.rnd;\n         });\n\n    const int MAX_LEN = 100000;\n    int loops = 0;\n    if (!cand.empty())\n        loops = (MAX_LEN - baseLen) / 2;\n    if (loops < 0) loops = 0;\n\n    for (int i = 0; i < loops; ++i) {\n        const NB& nb = cand[i % (int)cand.size()];\n        moves.push_back(nb.dir);\n        moves.push_back(oppChar[nb.dir]);\n    }\n\n    cout << moves << '\\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    \n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n    \n    for (int k = 0; k < M; ++k) {\n        string t;\n        cin >> t;\n    }\n    \n    // Output zero operations (empty output) \u2013 a valid lucky string (empty) yields K=0.\n    // No lines are printed.\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;\n\n    // Read and ignore the shapes of oil fields (not needed for this simple strategy)\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < 2 * d; ++i) {\n            int x;\n            cin >> x;\n        }\n    }\n\n    vector<pair<int, int>> oil;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << \"q 1 \" << i << ' ' << j << endl;\n            int v;\n            cin >> v;\n            if (v > 0) {\n                oil.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Output the answer\n    cout << \"a \" << oil.size();\n    for (auto [i, j] : oil) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << endl;\n\n    // Read verdict (1 if correct, 0 otherwise). Terminate regardless.\n    int verdict;\n    cin >> verdict;\n    return 0;\n}","ahc031":"","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll MOD = 998244353LL;\n\nstruct Op {\n    int m, p, q;\n    Op() {}\n    Op(int _m, int _p, int _q) : m(_m), p(_p), q(_q) {}\n};\n\nll add_mod(ll x, ll v) {\n    ll res = x + v;\n    if (res >= MOD) res -= MOD;\n    return res;\n}\nll sub_mod(ll x, ll v) {\n    ll res = x - v;\n    if (res < 0) res += MOD;\n    return res;\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    vector<vector<ll>> a(N, vector<ll>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> a[i][j];\n    vector<array<array<ll, 3>, 3>> stamps(M);\n    for (int m = 0; m < M; ++m)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> stamps[m][i][j];\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_stamp(0, M-1);\n    uniform_int_distribution<int> dist_pos(0, N-3); // 0..6\n    uniform_int_distribution<int> dist_cell(0, N-1); // not used\n\n    ll best_score = -1;\n    vector<Op> best_ops;\n\n    auto start_time = chrono::high_resolution_clock::now();\n    const double time_limit = 1.95; // seconds\n\n    for (int restart = 0; restart < 5; ++restart) {\n        auto now = chrono::high_resolution_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed >= time_limit) break;\n\n        vector<vector<ll>> cur_val = a;\n        ll score = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                score += cur_val[i][j];\n\n        vector<Op> ops;\n        // optional random initialization\n        int init_add = 5;\n        for (int t = 0; t < init_add; ++t) {\n            int m = dist_stamp(rng);\n            int p = dist_pos(rng);\n            int q = dist_pos(rng);\n            ll delta = 0;\n            for (int di = 0; di < 3; ++di)\n                for (int dj = 0; dj < 3; ++dj) {\n                    int i = p + di, j = q + dj;\n                    ll v = stamps[m][di][dj];\n                    ll nx = cur_val[i][j] + v;\n                    if (nx >= MOD) nx -= MOD;\n                    delta += nx - cur_val[i][j];\n                    cur_val[i][j] = nx;\n                }\n            score += delta;\n            ops.emplace_back(m, p, q);\n        }\n\n        // hill climbing with add/remove/swap\n        while (true) {\n            auto now2 = chrono::high_resolution_clock::now();\n            double elapsed2 = chrono::duration<double>(now2 - start).count();\n            if (elapsed2 >= time_limit) break;\n\n            ll best_delta = 0;\n            int best_type = 0; // 1=add, 2=remove, 3=swap\n            int best_m = -1, best_p = -1, best_q = -1;\n            int best_idx = -1; // for remove or swap (old op index)\n            int best_m2 = -1, best_p2 = -1, best_q2 = -1; // for swap (new op)\n\n            // try add\n            if ((int)ops.size() < K) {\n                for (int m = 0; m < M; ++m) {\n                    for (int p = 0; p <= N - 3; ++p) {\n                        for (int q = 0; q <= N - 3; ++q) {\n                            ll delta = 0;\n                            for (int di = 0; di < 3; ++di)\n                                for (int dj = 0; dj < 3; ++dj) {\n                                    int i = p + di, j = q + dj;\n                                    ll v = stamps[m][di][dj];\n                                    ll nx = cur_val[i][j] + v;\n                                    if (nx >= MOD) nx -= MOD;\n                                    delta += nx - cur_val[i][j];\n                                }\n                            if (delta > best_delta) {\n                                best_delta = delta;\n                                best_type = 1;\n                                best_m = m; best_p = p; best_q = q;\n                            }\n                        }\n                    }\n                }\n            }\n\n            // try remove\n            if ((int)ops.size() > 0) {\n                for (size_t idx = 0; idx < ops.size(); ++idx) {\n                    const Op& op = ops[idx];\n                    ll delta = 0;\n                    int m = op.m, p = op.p, q = op.q;\n                    for (int di = 0; di < 3; ++di)\n                        for (int dj = 0; dj < 3; ++dj) {\n                            int i = p + di, j = q + dj;\n                            ll v = stamps[m][di][dj];\n                            ll nx = cur_val[i][j] - v;\n                            if (nx < 0) nx += MOD;\n                            delta += nx - cur_val[i][j];\n                        }\n                    if (delta > best_delta) {\n                        best_delta = delta;\n                        best_type = 2;\n                        best_idx = (int)idx;\n                    }\n                }\n            }\n\n            // try swap (remove old, add new)\n            if ((int)ops.size() > 0 && (int)ops.size() < K) {\n                for (size_t idx_old = 0; idx_old < ops.size(); ++idx_old) {\n                    const Op& op_old = ops[idx_old];\n                    int m_old = op_old.m, p_old = op_old.p, q_old = op_old.q;\n                    for (int m_new = 0; m_new < M; ++m_new) {\n                        for (int p_new = 0; p_new <= N - 3; ++p_new) {\n                            for (int q_new = 0; q_new <= N - 3; ++q_new) {\n                                // optional: skip if same as old (no effect)\n                                if (m_old == m_new && p_old == p_new && q_old == q_new) continue;\n                                ll delta = 0;\n                                for (int i = 0; i < N; ++i) {\n                                    for (int j = 0; j < N; ++j) {\n                                        ll val = cur_val[i][j];\n                                        bool in_old = (i >= p_old && i < p_old + 3 && j >= q_old && j < q_old + 3);\n                                        bool in_new = (i >= p_new && i < p_new + 3 && j >= q_new && j < q_new + 3);\n                                        if (in_old) {\n                                            ll v_old = stamps[m_old][i - p_old][j - q_old];\n                                            val = val - v_old;\n                                            if (val < 0) val += MOD;\n                                        }\n                                        if (in_new) {\n                                            ll v_new = stamps[m_new][i - p_new][j - q_new];\n                                            val = val + v_new;\n                                            if (val >= MOD) val -= MOD;\n                                        }\n                                        delta += val - cur_val[i][j];\n                                    }\n                                }\n                                if (delta > best_delta) {\n                                    best_delta = delta;\n                                    best_type = 3;\n                                    best_idx = (int)idx_old;\n                                    best_m2 = m_new; best_p2 = p_new; best_q2 = q_new;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            if (best_delta <= 0) break;\n\n            // apply the best move\n            if (best_type == 1) { // add\n                ll delta_apply = 0;\n                for (int di = 0; di < 3; ++di)\n                    for (int dj = 0; dj < 3; ++dj) {\n                        int i = best_p + di, j = best_q + dj;\n                        ll v = stamps[best_m][di][dj];\n                        ll nx = cur_val[i][j] + v;\n                        if (nx >= MOD) nx -= MOD;\n                        delta_apply += nx - cur_val[i][j];\n                        cur_val[i][j] = nx;\n                    }\n                score += best_delta;\n                ops.emplace_back(best_m, best_p, best_q);\n            } else if (best_type == 2) { // remove\n                const Op& op = ops[best_idx];\n                ll delta_apply = 0;\n                int m = op.m, p = op.p, q = op.q;\n                for (int di = 0; di < 3; ++di)\n                    for (int dj = 0; dj < 3; ++dj) {\n                        int i = p + di, j = q + dj;\n                        ll v = stamps[m][di][dj];\n                        ll nx = cur_val[i][j] - v;\n                        if (nx < 0) nx += MOD;\n                        delta_apply += nx - cur_val[i][j];\n                        cur_val[i][j] = nx;\n                    }\n                score += best_delta;\n                ops.erase(ops.begin() + best_idx);\n            } else { // swap\n                const Op& op_old = ops[best_idx];\n                ll delta_apply = 0;\n                int m_old = op_old.m, p_old = op_old.p, q_old = op_old.q;\n                int m_new = best_m2, p_new = best_p2, q_new = best_q2;\n                for (int i = 0; i < N; ++i) {\n                    for (int j = 0; j < N; ++j) {\n                        ll val = cur_val[i][j];\n                        bool in_old = (i >= p_old && i < p_old + 3 && j >= q_old && j < q_old + 3);\n                        bool in_new = (i >= p_new && i < p_new + 3 && j >= q_new && j < q_new + 3);\n                        if (in_old) {\n                            ll v_old = stamps[m_old][i - p_old][j - q_old];\n                            val = val - v_old;\n                            if (val < 0) val += MOD;\n                        }\n                        if (in_new) {\n                            ll v_new = stamps[m_new][i - p_new][j - q_new];\n                            val = val + v_new;\n                            if (val >= MOD) val -= MOD;\n                        }\n                        delta_apply += val - cur_val[i][j];\n                        cur_val[i][j] = val;\n                    }\n                }\n                score += best_delta;\n                ops[best_idx] = Op(m_new, p_new, q_new);\n            }\n        }\n\n        if (score > best_score) {\n            best_score = score;\n            best_ops = ops;\n        }\n    }\n\n    cout << best_ops.size() << '\\n';\n    for (const Op& op : best_ops) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_TURNS = 10000;\nconst int DX[4] = {0, 0, -1, 1};\nconst int DY[4] = {-1, 1, 0, 0};\nconst char DIR_CHAR[4] = {'L', 'R', 'U', 'D'};\n\nstruct Pos {\n    int r, c;\n    bool operator==(const Pos& other) const { return r == other.r && c == other.c; }\n    bool operator<(const Pos& other) const {\n        if (r != other.r) return r < other.r;\n        return c < other.c;\n    }\n};\n\nint N;\nvector<vector<int>> A;\nint grid[5][5];\nint next_needed[5];\nint next_arrival[5];\nbool crane_holding = false;\nint held_id = -1;\nint crane_r = 0, crane_c = 0;\nlong long dispatched_count = 0;\nbool done = false;\n\nbool inside(int r, int c) {\n    return r >= 0 && r < N && c >= 0 && c < N;\n}\n\nchar move_step(int& cr, int& cc, int tr, int tc) {\n    if (cr < tr) { ++cr; return 'D'; }\n    else if (cr > tr) { --cr; return 'U'; }\n    else if (cc < tc) { ++cc; return 'R'; }\n    else if (cc > tc) { --cc; return 'L'; }\n    else return '.';\n}\n\n// Find an empty cell suitable for storage (columns 1..N-2, or column 0 if arrivals done for that row)\nPos find_empty_storage_cell() {\n    for (int r = 0; r < N; ++r) {\n        for (int c = 1; c <= N-2; ++c) {\n            if (grid[r][c] == -1) return {r, c};\n        }\n        if (next_arrival[r] == N && grid[r][0] == -1) return {r, 0};\n    }\n    // fallback (should not happen)\n    return {0, 0};\n}\n\n// Find a cell containing the specific container id (search everywhere except dispatch gates)\nPos find_container(int val) {\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            if (c == N-1) continue; // avoid dispatch gates\n            if (grid[r][c] == val) return {r, c};\n        }\n    }\n    return {-1, -1}; // not found\n}\n\n// Choose a target for pickup when not holding.\n// Sets globals: pickup_target, pickup_from_gate, pickup_row/pickup_id.\n// Returns true if a target was found.\nbool choose_pickup_target() {\n    // 1. Gate with needed container    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] != -1) {\n            int val = grid[i][0];\n            if (val == next_needed[i]) {\n                pickup_target = {i, 0};\n                pickup_from_gate = true;\n                pickup_row = i;\n                return true;\n            }\n        }\n    }\n    // 2. Gate with any container\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] != -1) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    // 3. Needed container in storage (any column except dispatch gate)\n    for (int i = 0; i < N; ++i) {\n        int need = next_needed[i];\n        if (need < i * N + N) { // still needed\n            Pos p = find_container(need);\n            if (p.r != -1) {\n                pickup_target = p;\n                pickup_from_gate = false;\n                pickup_id = need;\n                return true;\n            }\n        }\n    }\n    // 4. Gate with pending arrivals (wait for container to appear)\n    for (int i = 0; i < N; ++i) {\n        if (next_arrival[i] < N) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    return false;\n}\n\n// Release target computation after picking up\nPos pickup_target;\nbool pickup_from_gate;\nint pickup_row; // valid if pickup_from_gate\nint pickup_id;  // valid if !pickup_from_gate\nPos release_target;\n\nvoid compute_release_target_after_pickup() {\n    if (pickup_from_gate) {\n        int val = grid[pickup_target.r][pickup_target.c]; // still present before pick\n        if (val == next_needed[pickup_row]) {\n            release_target = {pickup_row, N-1};\n        } else {\n            release_target = find_empty_storage_cell();\n        }\n    } else {\n        // picked up from storage, it's a needed container\n        int row = pickup_id / N;\n        release_target = {row, N-1};\n    }\n}\n\nvoid process_arrivals() {\n    for (int i = 0; i < N; ++i) {\n        if (next_arrival[i] >= N) continue;\n        if (grid[i][0] == -1 && !(crane_holding && crane_r == i && crane_c == 0)) {\n            int container = A[i][next_arrival[i]];\n            grid[i][0] = container;\n            ++next_arrival[i];\n        }\n    }\n}\n\nvoid process_dispatch() {\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][4] != -1) {\n            grid[i][4] = -1; // dispatched and removed\n            // dispatched_count already incremented when we released at dispatch gate\n        }\n    }\n}\n\nchar decide_action() {\n    if (done) return '.';\n    if (phase == IDLE) {\n        if (crane_holding) {\n            return '.'; // should not happen\n        }\n        if (!choose_pickup_target()) {\n            done = true;\n            return '.';\n        }\n        phase = MOVING_TO_PICKUP;\n        // fall through    }\n    if (phase == MOVING_TO_PICKUP) {\n        char ch = move_step(crane_r, crane_c, pickup_target.r, pickup_target.c);\n        if (crane_r == pickup_target.r && crane_c == pickup_target.c) {\n            phase = AT_PICKUP;\n        }\n        return ch;\n    }\n    if (phase == AT_PICKUP) {\n        if (!crane_holding && grid[crane_r][crane_c] != -1) {\n            // we will pick up\n            // compute release target now\n            compute_release_target_after_pickup();\n            phase = MOVING_TO_RELEASE;\n            return 'P';\n        } else {\n            return '.';\n        }\n    }\n    if (phase == MOVING_TO_RELEASE) {\n        char ch = move_step(crane_r, crane_c, release_target.r, release_target.c);\n        if (crane_r == release_target.r && crane_c == release_target.c) {\n            phase = AT_RELEASE;\n        }\n        return ch;\n    }\n    if (phase == AT_RELEASE) {\n        if (crane_holding) {\n            phase = IDLE;\n            return 'Q';\n        } else {\n            return '.';\n        }\n    }\n    return '.';\n}\n\nvoid apply_action(char ch) {\n    if (ch == '.') return;\n    if (ch == 'U') { /* already moved in move_step */ }\n    else if (ch == 'D') { /* moved */ }\n    else if (ch == 'L') { /* moved */ }\n    else if (ch == 'R') { /* moved */ }\n    else if (ch == 'P') {\n        // pick up\n        assert(!crane_holding);\n        assert(grid[crane_r][crane_c] != -1);\n        held_id = grid[crane_r][crane_c];\n        crane_holding = true;\n        grid[crane_r][crane_c] = -1;\n        // nothing else to update\n    } else if (ch == 'Q') {\n        // release\n        assert(crane_holding);\n        assert(grid[crane_r][crane_c] == -1);\n        grid[crane_r][crane_c] = held_id;\n        if (crane_c == N-1) { // dispatch gate\n            int row = crane_r;\n            ++next_needed[row];\n            ++dispatched_count;\n        } else {\n            // storage cell, nothing else        }\n        crane_holding = false;\n        held_id = -1;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> N;\n    A.assign(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    }\n    // init\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = -1;\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        next_needed[i] = i * N;\n        next_arrival[i] = 0;\n    }\n    crane_r = 0; crane_c = 0;\n    crane_holding = false;\n    held_id = -1;\n    dispatched_count = 0;\n    done = false;\n    phase = IDLE;\n\n    string actions_large;\n    int turn = 0;\n    while (!turn >= MAX_TURNS && !done) {\n        process_arrivals();\n        char ch = decide_action();\n        actions_large += ch;\n        apply_action(ch);\n        process_dispatch();\n        ++turn;\n        if (dispatched_count == N * N) done = true;\n    }\n    // output\n    cout << actions_large << \"\\n\";\n    string small = \"B\";\n    if ((int)actions_large.size() > 1) {\n        small += string(actions_large.size() - 1, '.');\n    } else {\n        small += \".\"; // ensure at least length 1\n    }\n    for (int i = 1; i < N; ++i) {\n        cout << small << \"\\n\";\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int r, c;\n    int amt; // >0 for source, <0 for target (store as positive need)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    ios::cin.tie(nullptr);\n    vector<string> ops;\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    }\n\n    vector<Cell> sources, targets;\n    for(int i=0;i<N;i++) {\n        for(int j=0;j<N;j++) {\n            int val = h[i][j];\n            if(val > 0) {\n                sources.push_back({i, j, val});\n            } else if(val < 0) {\n                targets.push_back({i, j, -val});\n            }\n        }\n    }\n\n    struct Transfer {\n        int sr, sc, tr, tc;\n        int amt;\n    };\n    vector<Transfer> transfers;\n\n    while(true) {\n        int best_i = -1, best_j = -1;\n        int best_dist = INT_MAX;\n        for(size_t i=0;i<sources.size();++i) {\n            if(sources[i].amt <= 0) continue;\n            for(size_t j=0;j<targets.size();++j) {\n                if(targets[j].need <= 0) continue;\n                int dist = abs(sources[i].r - targets[j].r) + abs(sources[i].c - targets[j].c);\n                if(dist < best_dist) {\n                    best_dist = dist;\n                    best_i = (int)i;\n                    best_j = (int)j;\n                }\n            }\n        }\n        if(best_i==-1) break;\n        int take = min(sources[best_i].amt, targets[best_j].need);\n        transfers.push_back({sources[best_i].r, sources[best_i].c,\n                             targets[best_j].r, targets[best_j].c, take});\n        sources[best_i].amt -= take;\n        targets[best_j].need -= take;\n    }\n\n    auto add_move = [&](int &r, int &c, int tr, int tc) {\n        while(r < tr) { ops.push_back(\"D\"); ++r; }\n        while(r > tr) { ops.push_back(\"U\"); --r; }\n        while(c < tc) { ops.push_back(\"R\"); ++c; }\n        while(c > tc) { ops.push_back(\"L\"); --c; }\n        r = tr; c = tc;\n    };\n\n    int cr = 0, cc = 0;\n    long long load = 0; // not strictly needed but kept for safety\n    for(const Transfer &t : transfers) {\n        // depot -> source (empty)\n        add_move(cr, cc, t.sr, t.sc);\n        // load\n        ops.push_back(\"+\" + to_string(t.amt));\n        load += t.amt;\n        // source -> target (loaded)\n        add_move(t.sr, t.sc, t.tr, t.tc);\n        // unload\n        ops.push_back(\"-\" + to_string(t.amt));\n        load -= t.amt;\n        // target -> depot (empty)\n        add_move(t.tr, t.tc, 0, 0);\n        cr = 0; cc = 0;\n        // load should be zero now\n        assert(load == 0);\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    int N, M, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> X(seed_count, vector<int>(M));\n    for (int i = 0; i < seed_count; ++i) {\n        for (int j = 0; j < M; ++j) {\n            cin >> X[i][j];\n        }\n    }\n\n    // Order of cells: higher degree first (inner -> edges -> corners)\n    struct Cell { int deg, int i, int j; };\n    vector<Cell> cells;\n    cells.reserve(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int deg = (i > 0) + (i < N - 1) + (j > 0) + (j < N - 1);\n            cells.push_back({deg, i, j});\n        }\n    }\n    sort(cells.begin(), cells.end(), [](const Cell& a, const Cell& b) {\n        return a.deg > b.deg;\n    });\n    vector<pair<int,int>> pos_order;\n    pos_order.reserve(N * N);\n    for (const auto& c : cells) {\n        pos_order.emplace_back(c.i, c.j);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        // Max value per attribute\n        vector<int> max_attr(M, 0);\n        for (int id = 0; id < seed_count; ++id) {\n            for (int l = 0; l < M; ++l) {\n                if (X[id][l] > max_attr[l]) max_attr[l] = X[id][l];\n            }\n        }\n\n        // Score: (#attributes at max) * 10000 + sum of values\n        using SeedScore = pair<long long, int>;\n        vector<SeedScore> scores;\n        scores.reserve(seed_count);\n        for (int id = 0; id < seed_count; ++id) {\n            int w = 0;\n            long long sum = 0;\n            for (int l = 0; l < M; ++l) {\n                sum += X[id][l];\n                if (X[id][l] == max_attr[l]) ++w;\n            }\n            long long score = (long long)w * 10000LL + sum;\n            scores.emplace_back(score, id);\n        }\n        sort(scores.begin(), scores.end(),\n             [](const SeedScore& a, const SeedScore& b) { return a.first > b.first; });\n\n        // Assign top N^2 seeds to cells in pos_order\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        for (int idx = 0; idx < N * N; ++idx) {\n            int sid = scores[idx].second;\n            int i = pos_order[idx].first;\n            int j = pos_order[idx].second;\n            A[i][j] = sid;\n        }\n\n        // Output placement\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << A[i][j];\n                if (j + 1 < N) cout << ' ';\n                else cout << '\\n';\n            }\n        }\n        cout.flush();\n\n        // Read next generation\n        for (int id = 0; id < seed_count; ++id) {\n            for (int l = 0; l < M; ++l) {\n                if (!(cin >> X[id][l])) return 0;\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#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, 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    // We'll use a simple 2-vertex tree: root (0) and one leaf (1) with edge length 1.\n    const int Vp = 2;\n    cout << Vp << '\\n';\n    cout << \"0 1\" << '\\n';   // parent of vertex 1 is 0, length = 1\n    cout << \"0 0\" << '\\n';   // initial root position (top-left corner)\n        // Direction vectors: 0=right,1=down,2=left,3=up\n    const int DX[4] = {0, 1, 0, -1};\n    const int DY[4] = {1, 0, -1, 0};\n    const char DIR_CHAR[4] = {'R', 'D', 'L', 'U'};\n    \n    // Current state of takoyaki on the grid (modifiable)\n    vector<vector<int>> cur(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cur[i][j] = s[i][j] - '0';\n    \n    // Target grid    vector<vector<int>> target(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            target[i][j] = t[i][j] - '0';\n    \n    int rootX = 0, rootY = 0;\n    int leafDir = 0; // initially edge extends to the right\n    bool holding = false;\n    \n    // Number of turns: choose a moderate value (well below 1e5)\n    const int TURN = 5000;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distMove(0, 3); // 0..3 for directions\n    uniform_int_distribution<int> distRot(0, 2);  // 0: none, 1: left, 2: right\n        for (int turn = 0; turn < TURN; ++turn) {\n        string op(4, '.'); // format: [move][rot][root action][leaf action]\n        \n        // 1. Move the whole arm\n        int d = distMove(rng);\n        int nx = rootX + DX[d];\n        int ny = rootY + DY[d];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N) {\n            rootX = nx;\n            rootY = ny;\n            op[0] = DIR_CHAR[d];\n        } // else op[0] stays '.'\n        \n        // 2. Rotate the subtree rooted at vertex 1 (the leaf)\n        int r = distRot(rng);\n        if (r == 1) { // rotate left (counterclockwise)\n            op[1] = 'L';\n            leafDir = (leafDir + 3) & 3;\n        } else if (r == 2) { // rotate right (clockwise)\n            op[1] = 'R';\n            leafDir = (leafDir + 1) & 3;\n        } // else op[1] stays '.'\n        \n        // 3. Action at fingertips (only vertex 1 is a leaf)\n        // Root (vertex 0) is not a leaf -> op[2] stays '.'\n        int leafX = rootX + DX[leafDir];\n        int leafY = rootY + DY[leafDir];\n        bool changed = false;\n        if (leafX >= 0 && leafX < N && leafY >= 0 && leafY < N) {\n            if (!holding && cur[leafX][leafY] == 1 && target[leafX][leafY] == 0) {\n                // Pick up a takoyaki that is not needed here\n                cur[leafX][leafY] = 0;\n                holding = true;\n                changed = true;\n            } else if (holding && cur[leafX][leafY] == 0 && target[leafX][leafY] == 1) {\n                // Drop a takoyaki onto a needed empty spot                cur[leafX][leafY] = 1;\n                holding = false;\n                changed = true;\n            }\n        }\n        op[3] = changed ? 'P' : '.';\n        \n        cout << op << '\\n';\n    }\n    \n    return 0;\n}","ahc039":"#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    const int MAXC = 100000;\n    vector<tuple<int, int, int>> pts;\n    pts.reserve(2 * N);\n    for (int i = 0; i < 2 * N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        int w = (i < N) ? 1 : -1; // +1 for mackerel, -1 for sardine\n        pts.emplace_back(x, y, w);\n    }\n\n    // Build maps: x -> list of (y, weight), y -> list of (x, weight)\n    unordered_map<int, vector<pair<int, int>>> x_to_ys;\n    unordered_map<int, vector<pair<int, int>>> y_to_xs;\n    for (auto &[x, y, w] : pts) {\n        x_to_ys[x].emplace_back(y, w);\n        y_to_xs[y].emplace_back(x, w);\n    }\n    for (auto &kv : x_to_ys) sort(kv.second.begin(), kv.second.end());\n    for (auto &kv : y_to_xs) sort(kv.second.begin(), kv.second.end());\n\n    // Helper to sum weights of points with fixed x and y in [y1, y2] (inclusive)\n    auto sumVert = [&](int x, int y1, int y2) -> int {\n        auto it = x_to_ys.find(x);\n        if (it == x_to_ys.end()) return 0;\n        const auto &vec = it->second;\n        int s = 0;\n        for (auto [y, w] : vec) {\n            if (y < y1) continue;\n            if (y > y2) break;\n            s += w;\n        }\n        return s;\n    };\n    // Helper to sum weights of points with fixed y and x in [x1, x2] (inclusive)\n    auto sumHoriz = [&](int y, int x1, int x2) -> int {\n        auto it = y_to_xs.find(y);\n        if (it == y_to_xs.end()) return 0;\n        const auto &vec = it->second;\n        int s = 0;\n        for (auto [x, w] : vec) {\n            if (x < x1) continue;\n            if (x > x2) break;\n            s += w;\n        }\n        return s;\n    };\n\n    long long bestScore = LLONG_MIN;\n    int bestX1 = 0, bestX2 = 0, bestY1 = 0, bestY2 = 0;\n\n    // Try each mackerel as a seed point\n    for (int i = 0; i < N; ++i) {\n        int mx = get<0>(pts[i]);\n        int my = get<1>(pts[i]);\n        int x1 = mx, x2 = mx, y1 = my, y2 = my;\n        long long score = 1; // weight of the seed mackerel\n\n        // ----- Expansion phase -----        const int maxExpansions = 200;\n        int expansions = 0;\n        while (expansions < maxExpansions) {\n            int width = x2 - x1;\n            int height = y2 - y1;\n            int remaining = 200000 - (width + height); // max extra width+height allowed\n            if (remaining <= 0) break;\n\n            int bestGain = 0, bestDir = -1;\n            // left\n            if (x1 > 0) {\n                int g = sumVert(x1 - 1, y1, y2);\n                if (g > bestGain) { bestGain = g; bestDir = 0; }\n            }\n            // right\n            if (x2 < MAXC) {\n                int g = sumVert(x2 + 1, y1, y2);\n                if (g > bestGain) { bestGain = g; bestDir = 1; }\n            }\n            // down\n            if (y1 > 0) {\n                int g = sumHoriz(y1 - 1, x1, x2);\n                if (g > bestGain) { bestGain = g; bestDir = 2; }\n            }\n            // up\n            if (y2 < MAXC) {\n                int g = sumHoriz(y2 + 1, x1, x2);\n                if (g > bestGain) { bestGain = g; bestDir = 3; }\n            }\n            if (bestGain <= 0) break; // no profitable side\n\n            // apply expansion\n            switch (bestDir) {\n                case 0: x1--; break;\n                case 1: x2++; break;\n                case 2: y1--; break;\n                case 3: y2++; break;\n            }\n            score += bestGain;\n            ++expansions;\n        }\n\n        // ----- Shrinking phase -----\n        while (true) {\n            int width = x2 - x1;\n            int height = y2 - y1;\n            int bestGain = 0; // we look for the most negative gain\n            int bestDir = -1;\n\n            if (width >= 2) {\n                int gl = sumVert(x1, y1, y2);\n                int gr = sumVert(x2, y1, y2);\n                if (gl < bestGain) { bestGain = gl; bestDir = 0; }\n                if (gr < bestGain) { bestGain = gr; bestDir = 1; }\n            }\n            if (height >= 2) {\n                int gd = sumHoriz(y1, x1, x2);\n                int gu = sumHoriz(y2, x1, x2);\n                if (gd < bestGain) { bestGain = gd; bestDir = 2; }\n                if (gu < bestGain) { bestGain = gu; bestDir = 3; }\n            }\n            if (bestGain >= 0) break; // no side whose removal improves score\n\n            // remove the chosen side\n            switch (bestDir) {\n                case 0: x1++; score -= bestGain; break;\n                case 1: x2--; score -= bestGain; break;\n                case 2: y1++; score -= bestGain; break;\n                case 3: y2--; score -= bestGain; break;\n            }\n        }\n\n        // Ensure at least 1x1 rectangle (avoid zero-area)\n        if (x1 == x2) {\n            if (x2 < MAXC) ++x2;\n            else if (x1 > 0) --x1;\n        }\n        if (y1 == y2) {\n            if (y2 < MAXC) ++y2;\n            else if (y1 > 0) --y1;\n        }\n\n        if (score > bestScore) {\n            bestScore = score;\n            bestX1 = x1; bestX2 = x2; bestY1 = y1; bestY2 = y2;\n        }\n    }\n\n    // Output the rectangle (counter\u2011clockwise)\n    cout << 4 << '\\n';\n    cout << bestX1 << ' ' << bestY1 << '\\n';\n    cout << bestX2 << ' ' << bestY1 << '\\n';\n    cout << bestX2 << ' ' << bestY2 << '\\n';\n    cout << bestX1 << ' ' << bestY2 << '\\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, sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    // Read the observed (noisy) widths and heights; they are not needed for the trivial strategy.\n    vector<pair<int,int>> obs(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> obs[i].first >> obs[i].second;\n    }\n\n    // Repeat T times: output an empty placement (n = 0) and read the dummy measurement.\n    for (int t = 0; t < T; ++t) {\n        cout << 0 << '\\n';\n        cout.flush();\n\n        int Wp, Hp;\n        if (!(cin >> Wp >> Hp)) break;   // end if input fails (should not happen)\n        // The measured values are ignored; we simply proceed to the next turn.\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    // read edges\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n    }\n    // read coordinates (unused)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    // output all roots: parent = -1\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << -1;\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 Move {\n        char d;\n        int p;\n    };\n    vector<Move> moves;\n    moves.reserve(4 * N * N);   // enough space\n\n    auto shiftColUp = [&](int j) {\n        for (int i = 0; i + 1 < N; ++i) board[i][j] = board[i + 1][j];\n        board[N - 1][j] = '.';\n    };\n    auto shiftColDown = [&](int j) {\n        for (int i = N - 1; i > 0; --i) board[i][j] = board[i - 1][j];\n        board[0][j] = '.';\n    };\n    auto shiftRowLeft = [&](int i) {\n        for (int j = 0; j + 1 < N; ++j) board[i][j] = board[i][j + 1];\n        board[i][N - 1] = '.';\n    };\n    auto shiftRowRight = [&](int i) {\n        for (int j = N - 1; j > 0; --j) board[i][j] = board[i][j - 1];\n        board[i][0] = '.';\n    };\n\n    while (true) {\n        int si = -1, sj = -1;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (board[i][j] == 'x') {\n                    si = i; sj = j;\n                    break;\n                }\n            }\n            if (si != -1) break;\n        }\n        if (si == -1) break;   // no Oni left\n\n        int i = si, j = sj;\n        bool up = true, down = true, left = true, right = true;\n        for (int ii = 0; ii < i; ++ii)\n            if (board[ii][j] == 'o') { up = false; break; }\n        for (int ii = i + 1; ii < N; ++ii)\n            if (board[ii][j] == 'o') { down = false; break; }\n        for (int jj = 0; jj < j; ++jj)\n            if (board[i][jj] == 'o') { left = false; break; }\n        for (int jj = j + 1; jj < N; ++jj)\n            if (board[i][jj] == 'o') { right = false; break; }\n\n        int dir; // 0:U,1:D,2:L,3:R        if (up) dir = 0;\n        else if (down) dir = 1;\n        else if (left) dir = 2;\n        else dir = 3;\n\n        if (dir == 0) { // U column j upward\n            for (int k = 0; k <= i; ++k) {\n                moves.push_back({'U', j});\n                shiftColUp(j);\n            }\n        } else if (dir == 1) { // D column j downward\n            for (int k = 0; k < N - i; ++k) {\n                moves.push_back({'D', j});\n                shiftColDown(j);\n            }\n        } else if (dir == 2) { // L row i left\n            for (int k = 0; k <= j; ++k) {\n                moves.push_back({'L', i});\n                shiftRowLeft(i);\n            }\n        } else { // R row i right\n            for (int k = 0; k < N - j; ++k) {\n                moves.push_back({'R', i});\n                shiftRowRight(i);\n            }\n        }\n    }\n\n    // safety check (can be removed in final version)\n    assert((int)moves.size() <= 4 * N * N);\n\n    for (auto &mv : moves)\n        cout << mv.d << ' ' << mv.p << '\\n';\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nll simulate(const vector<int>& a, const vector<int>& b, const vector<int>& target, vector<int>& cnt) {\n    int N = (int)a.size();\n    int L = (int)target.size();\n    cnt.assign(N, 0);\n    int cur = 0;\n    cnt[cur] = 1; // week 1    for (int week = 2; week <= L; ++week) {\n        int nx = (cnt[cur] & 1) ? a[cur] : b[cur];\n        cur = nx;\n        ++cnt[cur];\n    }\n    ll err = 0;\n    for (int i = 0; i < N; ++i) {\n        ll diff = (ll)cnt[i] - (ll)target[i];\n        if (diff < 0) diff = -diff;\n        err += diff;\n    }\n    return err;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, L;\n    cin >> N >> L;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    // initial solution: round-robin\n    vector<int> a(N), b(N);\n    for (int i = 0; i < N; ++i) {\n        a[i] = b[i] = (i + 1) % N;\n    }\n\n    vector<int> cnt(N);\n    ll cur_err = simulate(a, b, T, cnt);\n    ll best_err = cur_err;\n    vector<int> best_a = a, best_b = b;\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_node(0, N - 1);\n    uniform_int_distribution<int> dist_choice(0, 1); // 0 -> a, 1 -> b    uniform_real_distribution<double> dist_real(0.0, 1.0);\n\n    auto guided_move = [&](const vector<int>& cnt_cur, int& i, int& which, int& j) {\n        vector<int> deficit(N);\n        int total_over = 0, total_under = 0;\n        for (int k = 0; k < N; ++k) {\n            int d = T[k] - cnt_cur[k];\n            deficit[k] = d;\n            if (d > 0) total_under += d;\n            else if (d < 0) total_over -= d;\n        }\n        if (total_over == 0) return false; // fallback to random\n        // pick over node i with probability proportional to -deficit[i]\n        int r = uniform_int_distribution<int>(0, total_over - 1)(rng);\n        int acc = 0;\n        i = 0;\n        while (i < N) {\n            int d = -deficit[i];\n            if (d > 0) {\n                if (r < acc + d) break;\n                acc += d;\n            }\n            ++i;\n        }\n        // pick under node j with probability proportional to deficit[j]\n        int r2 = uniform_int_distribution<int>(0, total_under - 1)(rng);\n        int acc2 = 0;\n        j = 0;\n        while (j < N) {\n            int d = deficit[j];\n            if (d > 0) {\n                if (r2 < acc2 + d) break;\n                acc2 += d;\n            }\n            ++j;\n        }\n        which = dist_choice(rng); // random choose a or b to modify\n        return true;\n    };\n\n    const int MAX_ITER = 500;\n    const double COOLING = 0.998;\n\n    for (int restart = 0; restart < 3; ++restart) {\n        // reset to round-robin for each restart (optional)\n        for (int i = 0; i < N; ++i) a[i] = b[i] = (i + 1) % N;\n        cur_err = simulate(a, b, T, cnt);\n        if (cur_err < best_err) {\n            best_err = cur_err;\n            best_a = a;\n            best_b = b;\n        }\n        double Ttemp = (double)cur_err; // temperature\n        for (int it = 0; it < MAX_ITER; ++it) {\n            int i, which, j;\n            bool use_guided = guided_move(cnt, i, which, j);\n            if (!use_guided) {\n                i = dist_node(rng);\n                which = dist_choice(rng);\n                j = dist_node(rng);\n            }\n            // apply move\n            vector<int> a2 = a, b2 = b;\n            if (which == 0) a2[i] = j;\n            else b2[i] = j;\n            // simulate move\n            vector<int> cnt2(N);\n            ll err2 = simulate(a2, b2, T, cnt2);\n            bool accept = false;\n            if (err2 < cur_err) accept = true;\n            else {\n                double prob = exp((cur_err - err2) / Ttemp);\n                if (dist_real(rng) < prob) accept = true;\n            }\n            if (accept) {\n                a = a2;\n                b = b2;\n                cur_err = err2;\n                cnt = cnt2;\n                if (err2 < best_err) {\n                    best_err = err2;\n                    best_a = a;\n                    best_b = b;\n                }\n            }\n            Ttemp *= COOLING;\n            if (Ttemp < 1e-5) break;\n        }\n    }\n\n    // output best solution    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    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 (integer division)\n    vector<int> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        cx[i] = (lx[i] + rx[i]) / 2;\n        cy[i] = (ly[i] + ry[i]) / 2;\n    }\n    \n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](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 k = 0; k < M; ++k) {\n        int sz = G[k];\n        vector<int> grp;\n        grp.reserve(sz);\n        for (int i = 0; i < sz; ++i) grp.push_back(idx[pos++]);\n        groups.push_back(move(grp));\n    }\n    \n    // answer edges per group\n    vector<vector<pair<int,int>>> ansEdges(M);\n    ansEdges.reserve(M);\n    int usedQueries = 0;\n        for (int k = 0; k < M; ++k) {\n        const auto& g = groups[k];\n        int sz = (int)g.size();\n        for (int i = 0; i + 1 < sz; i += 2) {\n            if (i + 2 < sz) {\n                // query a triple\n                int a = g[i];\n                int b = g[i+1];\n                int c = g[i+2];\n                cout << \"? 3 \" << a << ' ' << b << ' ' << c << '\\n';\n                cout.flush();\n                ++usedQueries;\n                int u1, v1, u2, v2;\n                cin >> u1 >> v1;\n                cin >> u2 >> v2;\n                ansEdges[k].emplace_back(u1, v1);\n                ansEdges[k].emplace_back(u2, v2);\n            } else {\n                // only a pair left, no query needed\n                ansEdges[k].emplace_back(g[i], g[i+1]);\n            }\n        }\n    }\n    \n    // output the answer\n    cout << \"!\\n\";\n    cout.flush();\n    for (int k = 0; k < M; ++k) {\n        // cities of the group\n        for (size_t i = 0; i < groups[k].size(); ++i) {\n            if i) cout << ' ';\n            cout << groups[k][i];\n        }\n        cout << '\\n';\n        // edges of the group\n        for (auto &e : ansEdges[k]) {\n            cout << e.first << ' ' << e.second << '\\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>> pts(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> pts[i].first >> pts[i].second;\n    }\n    \n    for (int k = 0; k + 1 < M; ++k) {\n        int ci = pts[k].first, cj = pts[k].second;\n        int ni = pts[k+1].first, nj = pts[k+1].second;\n        \n        while (ci < ni) { cout << \"M D\\n\"; ++ci; }\n        while (ci > ni) { cout << \"M U\\n\"; --ci; }\n        while (cj < nj) { cout << \"M R\\n\"; ++cj; }\n        while (cj > nj) { cout << \"M L\\n\"; --cj; }\n    }\n    \n    return 0;\n}"},"2":{"ahc001":"#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<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    const int W = 10000, H = 10000;\n    size_t totalCells = static_cast<size_t>(W) * H;\n    vector<uint8_t> occ(totalCells, 0); // 0 = free, else company id+1\n    vector<int> a(n), b(n), c(n), d(n);\n    vector<long long> area(n, 1);\n    for (int i = 0; i < n; ++i) {\n        a[i] = x[i];\n        b[i] = y[i];\n        c[i] = x[i] + 1;\n        d[i] = y[i] + 1;\n        occ[static_cast<size_t>(b[i]) * W + a[i]] = static_cast<uint8_t>(i + 1);\n    }\n\n    auto try_expand = [&](int i) -> bool {\n        if (area[i] >= r[i]) return false;\n        long long deficit = r[i] - area[i];\n        int best_dir = -1; // 0:left,1:right,2:down,3:up\n        int best_strip = 0;\n\n        int width  = c[i] - a[i];\n        int height = d[i] - b[i];\n\n        // left\n        if (a[i] > 0) {\n            int strip = height; // area added by expanding left one column\n            if (strip <= deficit) {\n                int xcol = a[i] - 1;\n                bool free = true;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    if (occ[static_cast<size_t>(yc) * W + xcol]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 0;\n                    best_strip = strip;\n                }\n            }\n        }\n        // right\n        if (c[i] < W) {\n            int strip = height;\n            if (strip <= deficit) {\n                int xcol = c[i];\n                bool free = true;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    if (occ[static_cast<size_t>(yc) * W + xcol]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 1;\n                    best_strip = strip;\n                }\n            }\n        }\n        // down\n        if (b[i] > 0) {\n            int strip = width;\n            if (strip <= deficit) {\n                int yrow = b[i] - 1;\n                bool free = true;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    if (occ[static_cast<size_t>(yrow) * W + xc]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 2;\n                    best_strip = strip;\n                }\n            }\n        }\n        // up\n        if (d[i] < H) {\n            int strip = width;\n            if (strip <= deficit) {\n                int yrow = d[i];\n                bool free = true;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    if (occ[static_cast<size_t>(yrow) * W + xc]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 3;\n                    best_strip = strip;\n                }\n            }\n        }\n        if (best_dir == -1) return false;\n\n        // perform the expansion\n        switch (best_dir) {\n            case 0: { // left\n                int xcol = a[i] - 1;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    occ[static_cast<size_t>(yc) * W + xcol] = static_cast<uint8_t>(i + 1);\n                }\n                a[i] -= 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 1: { // right\n                int xcol = c[i];\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    occ[static_cast<size_t>(yc) * W + xcol] = static_cast<uint8_t>(i + 1);\n                }\n                c[i] += 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 2: { // down\n                int yrow = b[i] - 1;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    occ[static_cast<size_t>(yrow) * W + xc] = static_cast<uint8_t>(i + 1);\n                }\n                b[i] -= 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 3: { // up\n                int yrow = d[i];\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    occ[static_cast<size_t>(yrow) * W + xc] = static_cast<uint8_t>(i + 1);\n                }\n                d[i] += 1;\n                area[i] += best_strip;\n                break;\n            }\n        }\n        return true;\n    };\n\n    vector<bool> active(n, true);\n    deque<int> q;\n    for (int i = 0; i < n; ++i) {\n        if (area[i] < r[i]) q.push_back(i);\n        else active[i] = false;\n    }\n\n    while (!q.empty()) {\n        int i = q.front();\n        q.pop_front();\n        if (!active[i]) continue;\n        if (area[i] >= r[i]) {\n            active[i] = false;\n            continue;\n        }\n        if (try_expand(i)) {\n            if (area[i] < r[i]) {\n                q.push_back(i);\n            }\n        } else {\n            active[i] = false;\n        }\n    }\n\n    for (int i = 0; i < n; ++i) {\n        cout << a[i] << ' ' << b[i] << ' ' << c[i] << ' ' << d[i] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Result {\n    string path;\n    int score;\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        vector<vector<int>> t(50, vector<int>(50));\n    vector<vector<int>> p(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            cin >> t[i][j];\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            cin >> p[i][j];\n    \n    // Determine number of tiles (M) and max tile id\n    int maxTileId = 0;\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            maxTileId = max(maxTileId, t[i][j]);\n    int M = maxTileId + 1; // tiles are numbered 0..M-1\n    \n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char dirChar[4] = {'U', 'D', 'L', 'R'};\n    \n    // Helper to simulate one walk with given seed\n    auto simulate = [&](int seed) -> Result {\n        vector<vector<bool>> visited(50, vector<bool>(50, false));\n        vector<bool> tileVisited(M, false);\n        \n        int ci = si, cj = sj;\n        visited[ci][cj] = true;\n        int startTile = t[ci][cj];\n        tileVisited[startTile] = true;\n        \n        string path;\n        int score = p[ci][cj];\n        int visitedTiles = 1;\n        mt19937 rng(seed);\n        \n        while (true) {\n            vector<int> cand;\n            for (int d = 0; d < 4; ++d) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                if (ni < 0 || ni >= 50 || nj < 0 || nj >= 50) continue;\n                if (visited[ni][nj]) continue;\n                int tid = t[ni][nj];\n                if (tileVisited[tid]) continue; // tile already used                cand.push_back(d);\n            }\n            if (cand.empty()) break;\n            \n            // Warnsdorff: choose neighbor with minimal onward degree\n            int bestForward = 1e9;\n            vector<int> bestDirs;\n            for (int d : cand) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                int forward = 0;\n                for (int d2 = 0; d2 < 4; ++d2) {\n                    int ni2 = ni + di[d2];\n                    int nj2 = nj + dj[d2];\n                    if (ni2 < 0 || ni2 >= 50 || nj2 < 0 || nj2 >= 50) continue;\n                    if (visited[ni2][nj2]) continue;\n                    int tid2 = t[ni2][nj2];\n                    if (tileVisited[tileVisible(tid2)]) continue; // placeholder\n                    // Actually we need to check tileVisited for neighbor cell\n                    if (tileVisited[tid2]) continue;\n                    ++forward;\n                }\n                if (forward < bestForward) {\n                    bestForward = forward;\n                    bestDirs.clear();\n                    bestDirs.push_back(d);\n                } else if (forward == bestForward) {\n                    bestDirs.push_back(d);\n                }\n            }\n                        // Among ties, prefer higher p value            int bestP = -1;\n            vector<int> bestDirs2;\n            for (int d : bestDirs) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                if (p[ni][nj] > bestP) {\n                    bestP = p[ni][nj];\n                    bestDirs2.clear();\n                    bestDirs2.push_back(d);\n                } else if (p[ni][nj] == bestP) {\n                    bestDirs2.push_back(d);\n                }\n            }\n            uniform_int_distribution<int> dist(0, (int)bestDirs2.size() - 1);\n            int chosen = bestDirs2[dist(rng)];\n            \n            ci += di[chosen];\n            cj += dj[chosen];\n            visited[ci][cj] = true;\n            int tid = t[ci][cj];\n            tileVisited[tid] = true;\n            ++visitedTiles;\n            path.push_back(dirChar[chosen]);\n            score += p[ci][cj];\n            \n            // Early stop if we have visited all tiles\n            if (visitedTiles == M) break;\n        }\n        return {path, score};\n    };\n    \n    // Run multiple random restarts and keep the best path\n    const int ITER = 50; // adjust if needed\n    Result best;\n    best.score = -1;\n    for (int it = 0; it < ITER; ++it) {\n        int seed = chrono::steady_clock::now().time_since_epoch().count() + it * 123457;\n        Result cur = simulate(seed);\n        if (cur.score > best.score) {\n            best = cur;\n        }\n    }\n    \n    cout << best.path << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;                     // grid size\nconst int HN = N;                     // rows for horizontal edges\nconst int WN = N - 1;                 // columns for horizontal edges\nconst int VN = N - 1;                 // rows for vertical edges\nconst int VM = N;                     // columns for vertical edges\n\nusing EdgeWeight = double;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // ----- estimates of edge lengths -----\n    vector<vector<EdgeWeight>> h(HN, vector<EdgeWeight>(WN, 5000.0)); // horizontal edges\n    vector<vector<EdgeWeight>> v(VN, vector<EdgeWeight>(VM, 5000.0)); // vertical   edges\n\n    const double eta = 0.2;          // learning rate\n    const double MINW = 500.0, MAXW = 15000.0;\n\n    for (int query = 0; query < 1000; ++query) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) break;   // end of input\n\n        // ---------- Dijkstra on current estimates ----------\n        const int V = N * N;\n        const double INF = 1e100;\n        vector<double> dist(V, INF);\n        vector<int> prev(V, -1);\n        using State = pair<double, int>;\n        priority_queue<State, vector<State>, greater<State>> pq;\n\n        auto idx = [&](int i, int j) { return i * N + j; };\n        int s = idx(si, sj);\n        int t = idx(ti, tj);\n        dist[s] = 0.0;\n        pq.emplace(0.0, s);\n\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u] + 1e-12) continue;\n            int ui = u / N, uj = u % N;\n            // up\n            if (ui > 0) {\n                int ni = ui - 1, nj = uj;\n                double w = static_cast<double>(v[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // down\n            if (ui < N - 1) {\n                int ni = ui + 1, nj = uj;\n                double w = static_cast<double>(v[ui][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // left\n            if (uj > 0) {\n                int ni = ui, nj = uj - 1;\n                double w = static_cast<double>(h[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // right\n            if (uj < N - 1) {\n                int ni = ui, nj = uj + 1;\n                double w = static_cast<double>(h[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n        }\n\n        // ---------- reconstruct path ----------\n        vector<int> rev;\n        for (int cur = t; cur != -1; cur = prev[cur]) rev.push_back(cur);\n        reverse(rev.begin(), rev.end());\n\n        string moves;\n        moves.reserve(rev.size() * 2);\n        double predicted = 0.0;\n        int path_len = 0;\n\n        for (size_t i = 1; i < rev.size(); ++i) {\n            int a = rev[i - 1], b = rev[i];\n            int ai = a / N, aj = a % N;\n            int bi = b / N, bj = b % N;\n            char ch;\n            if (ai == bi && aj == bj + 1) { ch = 'L'; predicted += h[ai][bj]; --aj; }\n            else if (ai == bi && aj == bj - 1) { ch = 'R'; predicted += h[ai][aj]; ++aj; }\n            else if (aj == bj && ai == bi + 1) { ch = 'U'; predicted += v[bi][aj]; --ai; }\n            else if (aj == bj && ai == bi - 1) { ch = 'D'; predicted += v[ai][aj]; ++ai; }\n            else { ch = '?'; } // should never happen\n            moves.push_back(ch);\n            ++path_len;\n        }\n\n        cout << moves << '\\n';\n        cout.flush();\n\n        // ---------- read judge feedback ----------\n        int y;\n        if (!(cin >> y)) break;   // defensive\n\n        // ---------- SGD update ----------\n        if (path_len > 0) {\n            double error = static_cast<double>(y) - predicted;\n            double delta = eta * error / static_cast<double>(path_len);\n\n            int ci = si, cj = sj;\n            for (char ch : moves) {\n                if (ch == 'U') {\n                    v[ci - 1][cj] += delta;\n                    if (v[ci - 1][cj] < MINW) v[ci - 1][cj] = MINW;\n                    if (v[ci - 1][cj] > MAXW) v[ci - 1][cj] = MAXW;\n                    --ci;\n                } else if (ch == 'D') {\n                    v[ci][cj] += delta;\n                    if (v[ci][cj] < MINW) v[ci][cj] = MINW;\n                    if (v[ci][cj] > MAXW) v[ci][cj] = MAXW;\n                    ++ci;\n                } else if (ch == 'L') {\n                    h[ci][cj - 1] += delta;\n                    if (h[ci][cj - 1] < MINW) h[ci][cj - 1] = MINW;\n                    if (h[ci][cj - 1] > MAXW) h[ci][cj - 1] = MAXW;\n                    --cj;\n                } else if (ch == 'R') {\n                    h[ci][cj] += delta;\n                    if (h[ci][cj] < MINW) h[ci][cj] = MINW;\n                    if (h[ci][cj] > MAXW) h[ci][cj] = MAXW;\n                    ++cj;\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20; // fixed\n\nstruct CellEntry {\n    int pid;      // placement id    uint8_t off;  // offset within the placement\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    cin >> N >> M; // N is always 20, but read anyway\n    vector<string> strs(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strs[i];\n    }\n\n    // convert strings to integer representation 0-7 for A-H, 8 for '.'\n    vector<string> raw = strs; // keep original for required char lookup\n    vector<vector<int>> a(N, vector<int>(N, 0));\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_val(0, 7); // A-H only for initial matrix\n    int dot_cnt = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            a[i][j] = dist_val(rng);\n        }\n    }\n\n    // placement data\n    vector<int> placement_sid; // placement -> string id    vector<vector<vector<CellEntry>>> cell_entries(N, vector<vector<CellEntry>>(N));\n    vector<int> placement_mismatch; // per placement\n    vector<int> match_cnt_str(M, 0); // number of matching placements per string\n    int satisfied = 0;\n\n    const int dr[2] = {0, 1};\n    const int dc[2] = {1, 0};\n\n    // Build placements and initial mismatch counts\n    for (int sid = 0; sid < M; ++sid) {\n        const string& s = raw[sid];\n        int L = (int)s.size();\n        for (int dir = 0; dir < 2; ++dir) {\n            for (int sr = 0; sr < N; ++sr) {\n                for (int sc = 0; sc < N; ++sc) {\n                    int pid = (int)placement_sid.size();\n                    placement_sid.push_back(sid);\n                    int mis = 0;\n                    for (int k = 0; k < L; ++k) {\n                        int r = (sr + dr[dir] * k) % N;\n                        int c = (sc + dc[dir] * k) % N;\n                        cell_entries[r][c].push_back({pid, (uint8_t)k});\n                        int required = raw[sid][k] - 'A';\n                        if (a[r][c] != required) ++mis;\n                    }\n                    placement_mismatch.push_back(mis);\n                    if (mis == 0) {\n                        ++match_cnt_str[sid];\n                    }\n                }\n            }\n        }\n    }\n    for (int sid = 0; sid < M; ++sid) {\n        if (match_cnt_str[sid] > 0) ++satisfied;\n    }\n\n    // Helper lambdas for evaluating and applying a cell change\n    auto evaluate_delta = [&](int r, int c, int new_val) -> int {\n        int old_val = a[r][c];\n        if (old_val == new_val) return 0;\n        static vector<int> delta_match;\n        static vector<int> touched;\n        if ((int)delta_match.size() < M) delta_match.assign(M, 0);\n        else fill(delta_match.begin(), delta_match.end(), 0);\n        touched.clear();\n\n        for (const auto& e : cell_entries[r][c]) {\n            int pid = e.pid;\n            int off = e.off;\n            int sid = placement_sid[pid];\n            int required = raw[sid][off] - 'A';\n            int old_matched = (old_val == required);\n            int new_matched = (new_val == required);\n            int delta_mismatch = old_matched - new_matched; // change in mismatch count\n            int old_mis = placement_mismatch[pid];\n            bool old_match = (old_mis == 0);\n            int new_mis = old_mis + delta_mismatch;\n            bool new_match = (new_mis == 0);\n            if (old_match != new_match) {\n                int delta = new_match ? 1 : -1;\n                if (delta_match[sid] == 0) touched.push_back(sid);\n                delta_match[sid] += delta;\n            }\n        }\n\n        int delta_sat = 0;\n        for (int sid : touched) {\n            int old_match_cnt = match_cnt_str[sid];\n            bool old_sat = (old_match_cnt > 0);\n            int new_match_cnt = old_match_cnt + delta_match[sid];\n            bool new_sat = (new_match_cnt > 0);\n            if (!old_sat && new_sat) ++delta_sat;\n            else if (old_sat && !new_sat) --delta_sat;\n            delta_match[sid] = 0; // reset for next use\n        }\n        touched.clear();\n        return delta_sat;\n    };\n\n    auto apply_change = [&](int r, int c, int new_val) {\n        int old_val = a[r][c];\n        if (old_val == new_val) return;\n        a[r][c] = new_val;\n        // update dot count\n        if (old_val == 8) --dot_cnt;\n        if (new_val == 8) ++dot_cnt;\n\n        for (const auto& e : cell_entries[r][c]) {\n            int pid = e.pid;\n            int off = e.off;\n            int sid = placement_sid[pid];\n            int required = raw[sid][off] - 'A';\n            int old_matched = (old_val == required);\n            int new_matched = (new_val == required);\n            int delta_mismatch = old_matched - new_matched;\n            int& mis = placement_mismatch[pid];\n            int old_mis = mis;\n            bool old_match = (old_mis == 0);\n            mis += delta_mismatch;\n            bool new_match = (mis == 0);\n            if (old_match != new_match) {\n                int delta = new_match ? 1 : -1;\n                int old_match_cnt = match_cnt_str[sid];\n                match_cnt_str[sid] += delta;\n                int new_match_cnt = match_cnt_str[sid];\n                bool old_sat = (old_match_cnt > 0);\n                bool new_sat = (new_match_cnt > 0);\n                if (!old_sat && new_sat) ++satisfied;\n                else if (old_sat && !new_sat) --satisfied;\n            }\n        }\n    };\n\n    // Simulated annealing to maximize number of satisfied strings\n    const int MAX_ITER = 20000;\n    double start_temp = 2.0;\n    double end_temp = 0.001;\n    uniform_int_distribution<int> dist_cell(0, N - 1);\n    uniform_int_distribution<int> dist_val_full(0, 8); // 0-7 letters, 8 for '.'\n    uniform_real_distribution<double> dist_real(0.0, 1.0);\n\n    for (int it = 0; it < MAX_ITER; ++it) {\n        double t = start_temp * pow(end_temp / start_temp, (double)it / MAX_ITER);\n        int r = dist_cell(rng);\n        int c = dist_cell(rng);\n        int cur = a[r][c];\n        int nv = dist_val_full(rng);\n        if (nv == cur) continue;\n        int delta = evaluate_delta(r, c, nv);\n        bool accept = false;\n        if (delta > 0) accept = true;\n        else if (delta == 0 && dist_real(rng) < 0.1) accept = true;\n        else if (dist_real(rng) < exp(delta / t)) accept = true;\n        if (accept) {\n            apply_change(r, c, nv);\n        }\n    }\n\n    // Greedy phase: turn non-dot cells into '.' if it does not break any satisfied string\n    bool improved;\n    do {\n        improved = false;\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (a[r][c] == 8) continue; // already dot\n                if (evaluate_delta(r, c, 8) == 0) {\n                    apply_change(r, c, 8);\n                    improved = true;\n                }\n            }\n        }\n    } while (improved);\n\n    // Output the matrix    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int v = a[i][j];\n            if (v == 8) putchar('.');\n            else putchar('A' + v);\n        }\n        putchar('\\n');\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\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    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    string ans;\n\n    auto dirChar = [&](int i, int j, int ni, int nj) -> char {\n        if (ni == i - 1) return 'U';\n        if (ni == i + 1) return 'D';\n        if (nj == j - 1) return 'L';\n        if (nj == j + 1) return 'R';\n        return '?';\n    };\n\n    function<void(int, int)> dfs = [&](int i, int j) {\n        visited[i][j] = true;\n        int di[4] = {-1, 1, 0, 0};\n        int dj[4] = {0, 0, -1, 1};\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + di[d];\n            int nj = j + dj[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            ans.push_back(dirChar(i, j, ni, nj));\n            dfs(ni, nj);\n            ans.push_back(dirChar(ni, nj, i, j));\n        }\n    };\n\n    dfs(si, sj);\n    cout << ans << '\\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 task difficulty vectors\n    vector<array<int, 20>> d(N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    // build dependency graph (edges u -> v, u < v)\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    // dp[i] = length of longest path (in edges) starting from i\n    vector<int> dp(N, 0);\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    // priority queue of ready tasks: higher dp first\n    using TaskInfo = pair<int, int>; // dp, task index\n    priority_queue<TaskInfo> pq;\n    vector<int> task_state(N, 0); // 0 = not started, 1 = started, 2 = completed    for (int i = 0; i < N; ++i) {\n        if (indeg[i] == 0 && task_state[i] == 0) {\n            pq.push({dp[i], i});\n        }\n    }\n\n    // worker state\n    vector<int> worker_task(M, -1);       // task assigned to worker, -1 = idle\n    vector<int> worker_start_day(M, 0);   // start day of current task (valid if not idle)\n    vector<bool> worker_idle(M, true);    // true if idle\n    vector<int> finished_today;           // workers that finished at end of previous day\n\n    int day = 1;\n    while (true) {\n        // 1) process completions from previous day        for (int w : finished_today) {\n            int task = worker_task[w];\n            // t = (day-1) - start_day + 1 = day - start_day            int t = day - worker_start_day[w];\n            // (optional) could use t to infer skill levels here\n\n            // mark task as completed\n            if (task_state[task] != 1) {\n                // defensive: should not happen\n            }\n            task_state[task] = 2;\n            for (int succ : adj[task]) {\n                if (--indeg[succ] == 0 && task_state[succ] == 0) {\n                    pq.push({dp[succ], succ});\n                }\n            }\n            worker_task[w] = -1;\n            worker_idle[w] = true;\n        }\n        finished_today.clear();\n\n        // 2) assign tasks to idle workers\n        vector<pair<int, int>> assignments; // (worker+1, task+1)\n        for (int w = 0; w < M; ++w) {\n            if (!worker_idle[w]) continue;\n            if (pq.empty()) break;\n            auto [dpval, task] = pq.top(); pq.pop();\n            worker_task[w] = task;\n            worker_start_day[w] = day;\n            worker_idle[w] = false;\n            task_state[task] = 1;\n            assignments.emplace_back(w + 1, task + 1);\n        }\n\n        // 3) output assignments for today\n        cout << assignments.size();\n        for (auto &p : assignments) {\n            cout << ' ' << p.first << ' ' << p.second;\n        }\n        cout << '\\n';\n        cout.flush();\n\n        // 4) read response (workers that finished at end of today)\n        string line;\n        if (!getline(cin, line)) break;\n        stringstream ss(line);\n        int first;\n        if (!(ss >> first)) break;\n        if (first == -1) break; // all tasks done or day limit exceeded\n        int n = first;\n        finished_today.clear();\n        for (int i = 0; i < n; ++i) {\n            int w;\n            ss >> w;\n            finished_today.push_back(w - 1);\n        }\n\n        ++day;\n        // safety stop (judge will send -1 after day 2000 anyway)\n        if (day > 2000) {\n            // we will still rely on -1 to break\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Point = pair<int, int>;\n\nconst int CENTER_X = 400;\nconst int CENTER_Y = 400;\nconst int MAX_ORDERS = 1000;\nconst int SELECT_SIZE = 50;\n\nint A[MAX_ORDERS], B[MAX_ORDERS], C[MAX_ORDERS], D[MAX_ORDERS];\n\nstruct Result {\n    ll dist;\n    vector<int> order;          // order of pickups (1\u2011based)\n    vector<Point> route;        // full route including start/end\n};\n\ninline int manh(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Build a feasible route for the given set of orders (indices 0\u2011based).\nResult computeRoute(const vector<int>& sel) {\n    vector<bool> visPick(MAX_ORDERS, false), visDel(MAX_ORDERS, false);\n    vector<Point> route;\n    route.emplace_back(CENTER_X, CENTER_Y);\n    int curX = CENTER_X, curY = CENTER_Y;\n    vector<int> orderVis;\n    int remaining = 2 * (int)sel.size();\n\n    while (remaining > 0) {\n        int bestId = -1;\n        bool isPick = false;\n        int bestDist = INT_MAX;\n        for (int id : sel) {\n            if (!visPick[id]) {\n                int d = manh(curX, curY, A[id], B[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = true;\n                }\n            }\n            if (visPick[id] && !visDel[id]) {\n                int d = manh(curX, curY, C[id], D[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = false;\n                }\n            }\n        }\n        if (isPick) {\n            route.emplace_back(A[bestId], B[bestId]);\n            visPick[bestId] = true;\n            orderVis.push_back(bestId + 1); // store 1\u2011based index\n            curX = A[bestId]; curY = B[bestId];\n        } else {\n            route.emplace_back(C[bestId], D[bestId]);\n            visDel[bestId] = true;\n            curX = C[bestId]; curY = D[bestId];\n        }\n        --remaining;\n    }\n    route.emplace_back(CENTER_X, CENTER_Y);\n\n    ll total = 0;\n    for (size_t i = 0; i + 1 < route.size(); ++i) {\n        total += manh(route[i].first, route[i].second,\n                      route[i+1].first, route[i+1].second);\n    }\n    return {total, orderVis, route};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int i = 0; i < MAX_ORDERS; ++i) {\n        cin >> A[i] >> B[i] >> C[i] >> D[i];\n    }\n\n    // ----- initial selection based on simple round\u2011trip score -----\n    vector<int> idx(MAX_ORDERS);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](int i, int j) {\n        int wi = manh(CENTER_X, CENTER_Y, A[i], B[i]) +\n                 manh(A[i], B[i], C[i], D[i]) +\n                 manh(C[i], D[i], CENTER_X, CENTER_Y);\n        int wj = manh(CENTER_X, CENTER_Y, A[j], B[j]) +\n                 manh(A[j], B[j], C[j], D[j]) +\n                 manh(C[j], D[j], CENTER_X, CENTER_Y);\n        return wi < wj;\n    });\n\n    vector<vector<int>> initialSelections;\n    {\n        vector<int> top50(idx.begin(), idx.begin() + SELECT_SIZE);\n        initialSelections.push_back(top50);\n    }\n    {\n        // random selection\n        vector<int> rnd(SELECT_SIZE);\n        mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n        uniform_int_distribution<int> dist(0, MAX_ORDERS-1);\n        vector<bool> taken(MAX_ORDERS, false);\n        int cnt = 0;\n        while (cnt < SELECT_SIZE) {\n            int x = dist(rng);\n            if (!taken[x]) {\n                taken[x] = true;\n                rnd[cnt++] = x;\n            }\n        }\n        initialSelections.push_back(rnd);\n    }\n    {\n        // selection by nearest pickup to center only\n        vector<int> orderByPickup = idx;\n        sort(orderByPickup.begin(), orderByPickup.end(),\n             [&](int i, int j) {\n                 return manh(CENTER_X, CENTER_Y, A[i], B[i]) <\n                        manh(CENTER_X, CENTER_Y, A[j], B[j]);\n             });\n        vector<int> pick50(orderByPickup.begin(),\n                           orderByPickup.begin() + SELECT_SIZE);\n        initialSelections.push_back(pick50);\n    }\n\n    const int MAX_ITER = 2000;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distPos(0, SELECT_SIZE-1);\n    uniform_int_distribution<int> distId(0, MAX_ORDERS-1);\n\n    ll bestDist = LLONG_MAX;\n    vector<int> bestOrder;\n    vector<Point> bestRoute;\n\n    auto currentTime = []() {\n        return chrono::duration<double>(\n            chrono::steady_clock::now().time_since_epoch()\n        ).count();\n    };\n    double startTime = currentTime();\n    double timeLimit = 1.9; // leave some margin    for (const auto& initSel : initialSelections) {\n        if (currentTime() - startTime > timeLimit) break;\n        vector<int> curSel = initSel;\n        vector<bool> inSel(MAX_ORDERS, false);\n        for (int id : curSel) inSel[id] = true;\n\n        auto [dist, order, route] = computeRoute(curSel);\n        if (dist < bestDist) {\n            bestDist = dist;\n            bestOrder = order;\n            bestRoute = route;\n        }\n\n        for (int it = 0; it < MAX_ITER; ++it) {\n            if (currentTime() - startTime > timeLimit) break;\n            int pos = distPos(rng);\n            int outId = curSel[pos];\n            int inId;\n            do {\n                inId = distId(rng);\n            } while (inSel[inId]);\n\n            // perform swap\n            curSel[pos] = inId;\n            inSel[outId] = false;\n            inSel[inId] = true;\n\n            auto [ndist, norder, nroute] = computeRoute(curSel);\n            if (ndist < bestDist) {\n                bestDist = ndist;\n                bestOrder = norder;\n                bestRoute = nroute;\n            } else {\n                // revert\n                curSel[pos] = outId;\n                inSel[outId] = true;\n                inSel[inId] = false;\n            }\n        }\n    }\n\n    // Output    cout << SELECT_SIZE << ' ';\n    for (size_t i = 0; i < bestOrder.size(); ++i) {\n        if (i) cout << ' ';\n        cout << bestOrder[i];\n    }\n    cout << '\\n';\n    cout << bestRoute.size();\n    for (auto &p : bestRoute) {\n        cout << ' ' << p.first << ' ' << p.second;\n    }\n    cout << '\\n';\n    cout << flush;\n    return```cpp\n#include<bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Point = pair<int, int>;\n\nconst int CENTER_X = 400;\nconst int CENTER_Y = 400;\nconst int MAX_ORDERS = 1000;\nconst int SELECT_SIZE = 50;\n\nint A[MAX_ORDERS], B[MAX_ORDERS], C[MAX_ORDERS], D[MAX_ORDERS];\n\nstruct Result {\n    ll dist;\n    vector<int> order;          // order of pickups (1\u2011based)\n    vector<Point> route;        // full route including start/end\n};\n\ninline int manh(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Build a feasible route for the given set of orders (indices 0\u2011based).\nResult computeRoute(const vector<int>& sel) {\n    vector<bool> visPick(MAX_ORDERS, false), visDel(MAX_ORDERS, false);\n    vector<Point> route;\n    route.emplace_back(CENTER_X, CENTER_Y);\n    int curX = CENTER_X, curY = CENTER_Y;\n    vector<int> orderVis;\n    int remaining = 2 * (int)sel.size();\n\n    while (remaining > 0) {\n        int bestId = -1;\n        bool isPick = false;\n        int bestDist = INT_MAX;\n        for (int id : sel) {\n            if (!visPick[id]) {\n                int d = manh(curX, curY, A[id], B[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = true;\n                }\n            }\n            if (visPick[id] && !visDel[id]) {\n                int d = manh(curX, curY, C[id], D[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = false;\n                }\n            }\n        }\n        if (isPick) {\n            route.emplace_back(A[bestId], B[bestId]);\n            visPick[bestId] = true;\n            orderVis.push_back(bestId + 1); // store 1\u2011based index\n            curX = A[bestId]; curY = B[bestId];\n        } else {\n            route.emplace_back(C[bestId], D[bestId]);\n            visDel[bestId] = true;\n            curX = C[bestId]; curY = D[bestId];\n        }\n        --remaining;\n    }\n    route.emplace_back(CENTER_X, CENTER_Y);\n\n    ll total = 0;\n    for (size_t i = 0; i + 1 < route.size(); ++i) {\n        total += manh(route[i].first, route[i].second,\n                      route[i+1].first, route[i+1].second);\n    }\n    return {total, orderVis, route};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int i = 0; i < MAX_ORDERS; ++i) {\n        cin >> A[i] >> B[i] >> C[i] >> D[i];\n    }\n\n    // ----- initial selection based on simple round\u2011trip score -----\n    vector<int> idx(MAX_ORDERS);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](int i, int j) {\n        int wi = manh(CENTER_X, CENTER_Y, A[i], B[i]) +\n                 manh(A[i], B[i], C[i], D[i]) +\n                 manh(C[i], D[i], CENTER_X, CENTER_Y);\n        int wj = manh(CENTER_X, CENTER_Y, A[j], B[j]) +\n                 manh(A[j], B[j], C[j], D[j]) +\n                 mangan(C[j], D[j], CENTER_X, CENTER_Y);\n        return wi < wj;\n    });\n\n    vector<vector<int>> initialSelections;\n    {\n        vector<int> top50(idx.begin(), idx.begin() + SELECT_SIZE);\n        initialSelections.push_back(top50);\n    }\n    {\n        // random selection\n        vector<int> rnd(SELECT_SIZE);\n        mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n        uniform_int_distribution<int> dist(0, MAX_ORDERS-1);\n        vector<bool> taken(MAX_ORDERS, false);\n        int cnt = 0;\n        while (cnt < SELECT_SIZE) {\n            int x = dist(rng);\n            if (!taken[x]) {\n                taken[x] = true;\n                rnd[cnt++] = x;\n            }\n        }\n        initialSelections.push_back(rnd);\n    }\n    {\n        // selection by nearest pickup to center only        vector<int> orderByPickup = idx;\n        sort(orderByPickup.begin(), orderByPickup.end(),\n             [&](int i, int j) {\n                 return manh(CENTER_X, CENTER_Y, A[i], B[i]) <\n                        manh(CENTER_X, CENTER_Y, A[j], B[j]);\n             });\n        vector<int> pick50(orderByPickup.begin(),\n                           orderByPickup.begin() + SELECT_SIZE);\n        initialSelections.push_back(pick50);\n    }\n\n    const int MAX_ITER = 2000;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distPos(0, SELECT_SIZE-1);\n    uniform_int_distribution<int> distId(0, MAX_ORDERS-1);\n\n    ll bestDist = LLONG_MAX;\n    vector<int> bestOrder;\n    vector<Point> bestRoute;\n\n    auto currentTime = []() {\n        return chrono::duration<double>(\n            chrono::steady_clock::now().time_since_epoch()\n        ).count();\n    };\n    double startTime = currentTime();\n    double timeLimit = 1.9; // leave some margin\n\n    for (const auto& initSel : initialSelections) {\n        if (currentTime() - startTime > timeLimit) break;\n        vector<int> curSel = initSel;\n        vector<bool> inSel(MAX_ORDERS, false);\n        for (int id : curSel) inSel[id] = true;\n\n        auto [dist, order, route] = computeRoute(curSel);\n        if (dist < bestDist) {\n            bestDist = dist;\n            bestOrder = order;\n            bestRoute = route;\n        }\n\n        for (int it = 0; it < MAX_ITER; ++it) {\n            if (currentTime() - startTime > timeLimit) break;\n            int pos = distPos(rng);\n            int outId = curSel[pos];\n            int inId;\n            do {\n                inId = distId(rng);\n            } while (inSel[inId]);\n\n            // perform swap\n            curSel[pos] = inId;\n            inSel[outId] = false;\n            inSel[inId] = true;\n\n            auto [ndist, norder, nroute] = computeRoute(curSel);\n            if (ndist < bestDist) {\n                bestDist = ndist;\n                bestOrder = norder;\n                bestRoute = nroute;\n            } else {\n                // revert\n                curSel[pos] = outId;\n                inSel[outId] = true;\n                inSel[inId] = false;\n            }\n        }\n    }\n\n    // Output\n    cout << SELECT_SIZE << ' ';\n    for (size_t i = 0; i < bestOrder.size(); ++i) {\n        if (i) cout << ' ';\n        cout << bestOrder[i];\n    }\n    cout << '\\n';\n    cout << bestRoute.size();\n    for (auto &p : bestRoute) {\n        cout << ' ' << p.first << ' ' << p.second;\n    }\n    cout << '\\n';\n    cout << flush;\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }\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 (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\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) cin >> x[i] >> y[i];\n\n    vector<int> u(M), v(M);\n    for (int i = 0; i < M; ++i) cin >> u[i] >> v[i];\n\n    vector<int> d(M);\n    for (int i = 0; i < M; ++i) {\n        long long dx = 1LL * x[u[i]] - x[v[i]];\n        long long dy = 1LL * y[u[i]] - y[v[i]];\n        long long dist2 = dx * dx + dy * dy;\n        double dist = sqrt((double)dist2);\n        d[i] = (int)round(dist);\n    }\n\n    DSU dsu(N);\n    int components = N;\n\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;\n        bool useful = (dsu.find(u[i]) != dsu.find(v[i]));\n        bool take = false;\n        if (useful) {\n            if (l <= 2 * d[i])          // accept relatively short edges\n                take = true;\n            else {\n                // If even assuming all remaining edges are useful we cannot\n                // reach connectivity, we must take this useful edge now.\n                int remaining = M - i - 1;\n                if (components - 1 > remaining)\n                    take = true;\n            }\n        }\n        if (take) {\n            cout << '1' << '\\n';\n            cout.flush();\n            dsu.unite(u[i], v[i]);\n            --components;\n        } else {\n            cout << '0' << '\\n';\n            cout.flush();\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;\n    vector<int> px(N), py(N), pt(N);\n    for (int i = 0; i < N; ++i) cin >> px[i] >> py[i] >> pt[i];\n\n    int M;\n    cin >> M;\n    vector<int> hx(M), hy(M);\n    for (int i = 0; i < M; ++i) cin >> hx[i] >> hy[i];\n\n    string action(M, '.');   // all humans do nothing each turn\n\n    for (int turn = 0; turn < 300; ++turn) {\n        cout << action << '\\n';\n        cout.flush();\n\n        // read pets' movement strings for this turn\n        string mv;\n        for (int i = 0; i < N; ++i) {\n            if (!(cin >> mv)) return 0;   // input ended unexpectedly\n        }\n    }\n    return 0;\n}","ahc009":"#include<bits/stdc++.h>\nusing namespace std;\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 lines, each 19 chars)\n    for (int i = 0; i < 20; ++i) {\n        string line;\n        cin >> line;\n    }\n    // Read vertical walls (20 lines, each 20 chars)\n    for (int i = 0; i < 20; ++i) {\n        string line;\n        cin >> line;\n    }\n    \n    // Output any valid string, e.g., 200 'R's (length <= 200)\n    string ans(200, 'R');\n    cout << ans << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    array<array<int, 30>, 30> tile{};\n    for (int i = 0; i < 30; ++i) {\n        string line;\n        getline(cin, line);\n        line.erase(remove(line.begin(), line.end(), ' '), line.end());\n        for (int j = 0; j < 30; ++j) tile[i][j] = line[j] - '0';\n    }\n\n    const int di[4] = {0, -1, 0, 1};\n    const int dj[4] = {-1, 0, 1, 0};\n\n    // base to[t][d] as given in the statement    const int toBase[8][4] = {\n        {1, 0, -1, -1}, //0\n        {3, -1, -1, 0}, //1\n        {-1, -1, 3, 2}, //2        {-1, 2, 1, -1}, //3\n        {1, 0, 3, 2},   //4\n        {3, 2, 1, 0},   //5        {2, -1, 0, -1}, //6\n        {-1, 3, -1, 1}  //7\n    };\n\n    // toRot[t][rot][d] = exit direction or -1 after rotating tile t by rot (90*rot CCW)\n    int toRot[8][4][4] = {};\n    for (int t = 0; t < 8; ++t) {\n        for (int rot = 0; rot < 4; ++rot) {\n            for (int d = 0; d < 4; ++d) {\n                int baseDir = (d + rot) % 4;\n                int baseExit = toBase[t][baseDir];\n                if (baseExit == -1) {\n                    toRot[t][rot][d] = -1;\n                } else {\n                    int exitDir = (baseExit - rot + 4) % 4;\n                    toRot[t][rot][d] = exitDir;\n                }\n            }\n        }\n    }\n\n    auto computeScore = [&](const vector<vector<int>>& rot) -> long long {\n        const int N = 30 * 30 * 4; // 3600\n        int stateOut[N];\n        // build stateOut\n        for (int i = 0; i < 30; ++i) {\n            for (int j = 0; j < 30; ++j) {\n                int t = tile[i][j];\n                int r = rot[i][j];\n                for (int d = 0; d < 4; ++d) {\n                    int nd = toRot[t][r][d];\n                    int id = ((i * 30) + j) * 4 + d;\n                    if (nd == -1) {\n                        stateOut[id] = -1;\n                    } else {\n                        int ni = i + di[nd];\n                        int nj = j + dj[nd];\n                        if (ni < 0 || ni >= 30 || nj < 0 || nj >= 30) {\n                            stateOut[id] = -1;\n                        } else {\n                            int opp = (nd + 2) % 4;\n                            int t2 = tile[ni][nj];\n                            int r2 = rot[ni][nj];\n                            if (toRot[t2][r2][opp] == -1) {\n                                stateOut[id] = -1;\n                            } else {\n                                int nid = ((ni * 30) + nj) * 4 + opp;\n                                stateOut[id] = nid;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        int color[N] = {0};            // 0 unvisited, 1 visiting, 2 visited\n        int posInPath[N];\n        fill(posInPath, posInPath + N, -1);\n        vector<int> path;\n        path.reserve(N);\n        long long max1 = 0, max2 = 0;\n\n        for (int u = 0; u < N; ++u) {\n            if (color[u]) continue;\n            int v = u;\n            while (true) {\n                if (color[v] == 0) {\n                    color[v] = 1;\n                    posInPath[v] = (int)path.size();\n                    path.push_back(v);\n                    int nxt = stateOut[v];\n                    if (nxt == -1) break;\n                    v = nxt;\n                    continue;\n                }\n                if (color[v] == 1) {\n                    int startIdx = posInPath[v];\n                    long long len = (long long)path.size() - startIdx;\n                    if (len > max1) {\n                        max2 = max1;\n                        max1 = len;\n                    } else if (len > max2) {\n                        max2 = len;\n                    }\n                    break;\n                }\n                if (color[v] == 2) {\n                    break;\n                }\n            }\n            for (int node : path) {\n                color[node] = 2;\n                posInPath[node] = -1;\n            }\n            path.clear();\n        }\n        return max1 * max2;\n    };\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distTile(0, 29);\n    uniform_int_distribution<int> distRot(0, 3);\n\n    long long bestScore = -1;\n    vector<vector<int>> bestRot(30, vector<int>(30, 0));\n\n    for (int rest = 0; rest < 5; ++rest) {\n        vector<vector<int>> curRot(30, vector<int>(30, 0));\n        for (int i = 0; i < 30; ++i)\n            for (int j = 0; j < 30; ++j)\n                curRot[i][j] = distRot(rng);\n        long long curScore = computeScore(curRot);\n        for (int it = 0; it < 200; ++it) {\n            int i = distTile(rng);\n            int j = distTile(rng);\n            int cur = curRot[i][j];\n            int nr = distRot(rng);\n            if (nr == cur) continue;\n            curRot[i][j] = nr;\n            long long ns = computeScore(curRot);\n            if (ns > curScore) {\n                curScore = ns;\n            } else {\n                curRot[i][j] = cur;\n            }\n        }\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestRot = curRot;\n        }\n    }\n\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            cout << bestRot[i][j];\n        }\n    }\n    cout << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions for empty movement: U, D, L, R\nconst int dr[4] = {-1, 1, 0, 0};\nconst int dc[4] = {0, 0, -1, 1};\nconst char dirChar[4] = {'U', 'D', 'L', 'R'};\nconst char oppChar[4] = {'D', 'U', 'R', 'L'}; // opposite direction for empty movement (tile moves opposite)\n\n// Compute size of largest tree component (acyclic connected component)\nint computeLargestTreeSize(const vector<vector<int>>& board) {\n    int N = (int)board.size();\n    vector<vector<int>> deg(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int v = board[i][j];\n            if (v == 0) continue;\n            // up\n            if (i > 0 && board[i-1][j] != 0) {\n                if ((v & 2) && (board[i-1][j] & 8)) ++deg[i][j];\n            }\n            // down\n            if (i+1 < N && board[i+1][j] != 0) {\n                if ((v & 8) && (board[i+1][j] & 2)) ++deg[i][j];\n            }\n            // left\n            if (j > 0 && board[i][j-1] != 0) {\n                if ((v & 1) && (board[i][j-1] & 4)) ++deg[i][j];\n            }\n            // right\n            if (j+1 < N && board[i][j+1] != 0) {\n                if ((v & 4) && (board[i][j+1] & 1)) ++deg[i][j];\n            }\n        }\n    }\n    vector<vector<char>> vis(N, vector<char>(0));\n    int best = 0;\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 cnt = 0;\n            int sumdeg = 0;\n            queue<pair<int,int>> q;\n            q.push({i, j});\n            vis[i][j] = 1;\n            while (!q.empty()) {\n                auto [x, y] = q.front(); q.pop();\n                ++cnt;\n                sumdeg += deg[x][y];\n                for (int d = 0; d < 4; ++d) {\n                    int nx = x + dr[d];\n                    int ny = y + dc[d];\n                    if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                    if (board[nx][ny] == 0) continue;\n                    if (vis[nx][ny]) continue;\n                    int a = board[x][y];\n                    int b = board[nx][ny];\n                    bool edge = false;\n                    if (nx == x-1 && ny == y) { // up\n                        if ((a & 2) && (b & 8)) edge = true;\n                    } else if (nx == x+1 && ny == y) { // down\n                        if ((a & 8) && (b & 2)) edge = true;\n                    } else if (nx == x && ny == y-1) { // left\n                        if ((a & 1) && (b & 4)) edge = true;\n                    } else if (nx == x && ny == y+1) { // right\n                        if ((a & 4) && (b & 1)) edge = true;\n                    }\n                    if (edge) {\n                        vis[nx][ny] = 1;\n                        q.push({nx, ny});\n                    }\n                }\n            }\n            int edges = sumdeg / 2;\n            if (edges == cnt - 1) { // tree component\n                if (cnt > best) best = cnt;\n            }\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, T;\n    if (!(cin >> N >> T)) return 0;\n    vector<string> raw(N);\n    for (int i = 0; i < N; ++i) cin >> raw[i];\n\n    // Build board and locate empty\n    vector<vector<int>> board(N, vector<int>(N));\n    int er = -1, ec = -1;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char ch = raw[i][j];\n            int v = (ch >= '0' && ch <= '9') ? ch - '0' : ch - 'a' + 10;\n            board[i][j] = v;\n            if (v == 0) { er = i; ec = j; }\n        }\n    }\n\n    const int full = N * N - 1;\n    string ans;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    auto validMoves = [&](int r, int c, vector<int>& out) {\n        out.clear();\n        if (r > 0) out.push_back(0); // U\n        if (r + 1 < N) out.push_back(1); // D\n        if (c > 0) out.push_back(2); // L\n        if (c + 1 < N) out.push_back(3); // R\n    };\n\n    auto simulateMove = [&](int dir) -> int {\n        int nr = er + dr[dir];\n        int nc = ec + dc[dir];\n        swap(board[er][ec], board[nr][nc]);\n        int res = computeLargestTreeSize(board);\n        swap(board[er][ec], board[nr][nc]); // revert\n        return res;\n    };\n\n    for (int step = 0; step < T; ++step) {\n        if (computeLargestTreeSize(board) == full) break; // already optimal\n\n        vector<int> mvds;\n        validMoves(er, ec, mvds);\n        shuffle(mvds.begin(), mvds.end(), rng);\n\n        int bestDir = -1;\n        int bestScore = computeLargestTreeSize(board);\n        for (int d : mvds) {\n            int s = simulateMove(d);\n            if (s > bestScore) {\n                bestScore = s;\n                bestDir = d;\n            }\n        }\n\n        if (bestDir != -1 && bestScore > computeLargestTreeSize(board)) {\n            // accept best improving move\n            int nr = er + dr[bestDir];\n            int nc = ec + dc[bestDir];\n            swap(board[er][ec], board[nr][nc]);\n            er = nr;\n            ec = nc;\n            ans.push_back(dirChar[bestDir]);\n        } else {\n            // no improving move; take a random move to keep searching\n            int idx = uniform_int_distribution<int>(0, (int)mvds.size() - 1)(rng);\n            int d = mvds[idx];\n            int nr = er + dr[d];\n            int nc = ec + dc[d];\n            swap(board[er][ec], board[nr][nc]);\n            er = nr;\n            ec = nc;\n            ans.push_back(dirChar[d]);\n        }\n        // optional early stop if ans gets too long (should not exceed T)\n        if ((int)ans.size() > T) break;\n    }\n\n    cout << ans << '\\n';\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nstruct Line {\n    ll x1, y1, x2, y2;\n    Line() {}\n    Line(ll a, ll b, ll c, ll d) : x1(a), y1(b), x2(c), y2(d) {}\n};\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    int sumA = 0;\n    for (int d = 1; d <= 10; ++d) {\n        cin >> a[d];\n        sumA += a[d];\n    }\n    vector<pair<ll, ll>> pts(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pts[i].first >> pts[i].second;\n    }\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<ll> dist(-1000000000LL, 1000000000LL);\n\n    const int MAX_ITER = 60;   // number of random attempts\n    int bestScore = -1;\n    vector<Line> bestLines;\n\n    for (int it = 0; it < MAX_ITER; ++it) {\n        // ---- generate K random lines ----\n        vector<Line> lines;\n        lines.reserve(K);\n        for (int i = 0; i < K; ++i) {\n            while (true) {\n                ll x1 = dist(rng);\n                ll y1 = dist(rng);\n                ll x2 = dist(rng);\n                ll y2 = dist(rng);\n                if (x1 == x2 && y1 == y2) continue;\n                lines.emplace_back(x1, y1, x2, y2);\n                break;\n            }\n        }\n\n        // ---- evaluate the partition ----\n        unordered_map<string, int> cnt; // signature -> number of strawberries\n        for (auto &[x, y] : pts) {\n            string sig;\n            bool onLine = false;\n            sig.reserve(K);\n            for (int i = 0; i < K; ++i) {\n                const Line &ln = lines[i];\n                ll cross = (ln.y2 - ln.y1) * (x - ln.x1) - (ln.x2 - ln.x1) * (y - ln.y1);\n                if (cross == 0) {\n                    onLine = true;\n                    break;\n                }\n                sig.push_back(cross > 0 ? '1' : '0');\n            }\n            if (onLine) continue; // strawberry is cut, ignore\n            cnt[sig]++;\n        }\n\n        // ---- compute b[d] ----\n        vector<int> b(11, 0);\n        for (auto &[_, c] : cnt) {\n            if (c >= 1 && c <= 10) b[c]++;\n        }\n\n        // ---- compute score ----\n        int score = 0;\n        for (int d = 1; d <= 10; ++d) {\n            score += min(a[d], b[d]);\n        }\n\n        if (score > bestScore) {\n            bestScore = score;\n            bestLines = lines;\n        }\n    }\n\n    // ---- output the best solution ----\n    cout << K << '\\n';\n    for (const auto &ln : bestLines) {\n        cout << ln.x1 << ' ' << ln.y1 << ' ' << ln.x2 << ' ' << ln.y2 << '\\n';\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    bool operator==(const Point& other) const { return x == other.x && y == other.y; }\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    const int c = (N - 1) / 2;\n    vector<vector<bool>> dot(N, vector<bool>(N, false));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        dot[x][y] = true;\n    }\n\n    // Edge usage arrays\n    vector<vector<bool>> hor(N, vector<bool>(N, false)); // hor[x][y] : (x,y)-(x+1,y)\n    vector<vector<bool>> ver(N, vector<bool>(N, false)); // ver[x][y] : (x,y)-(x,y+1)\n    vector<vector<bool>> diag1(N, vector<bool>(N, false)); // diag1[x][y] : (x+1,y)-(x,y+1)\n    vector<vector<bool>> diag2(N, vector<vector<bool>>(N, false)); // diag2[x][y] : (x-1,y)-(x,y+1)\n    // Fix diag2 initialization\n    for (auto& row : diag2) fill(row.begin(), row.end(), false);\n\n    // Point -> list of shape indices containing this point as a corner    vector<vector<vector<int>>> point_shapes(N, vector<vector<int>>(N));\n\n    struct Shape {\n        int type; // 0: square (x,y lower-left), 1: diamond (cx,cy center)\n        int a, b; // parameters\n    };\n    vector<Shape> shapes;\n\n    // Squares\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y < N - 1; ++y) {\n            Shape s{0, x, y};\n            int id = (int)shapes.size();\n            shapes.push_back(s);\n            vector<Point> corners = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};\n            for (auto& p : corners) point_shapes[p.x][p.y].push_back(id);\n        }\n    }\n\n    // Diamonds\n    for (int cx = 1; cx < N - 1; ++cx) {\n        for (int cy = 1; cy < N - 1; ++cy) {\n            Shape s{1, cx, cy};\n            int id = (int)shapes.size();\n            shapes.push_back(s);\n            vector<Point> corners = {{cx + 1, cy}, {cx - 1, cy}, {cx, cy + 1}, {cx, cy - 1}};\n            for (auto& p : corners) point_shapes[p.x][p.y].push_back(id);\n        }\n    }\n\n    int S = (int)shapes.size();\n    vector<int> dot_count(S, 0);\n    for (int id = 0; id < S; ++id) {\n        const Shape& sh = shapes[id];\n        int cnt = 0;\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            vector<Point> corners = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};\n            for (auto& p : corners) if (dot[p.x][p.y]) ++cnt;\n        } else {\n            int cx = sh.a, cy = sh.b;\n            vector<Point> corners = {{cx + 1, cy}, {cx - 1, cy}, {cx, cy + 1}, {cx, cy - 1}};\n            for (auto& p : corners) if (dot[p.x][p.y]) ++cnt;\n        }\n        dot_count[id] = cnt;\n    }\n\n    auto get_missing = [&](int id, Point& missing) -> bool {\n        const Shape& sh = shapes[id];\n        vector<Point> corners;\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            corners = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};\n        } else {\n            int cx = sh.a, cy = sh.b;\n            corners = {{cx + 1, cy}, {cx - 1, cy}, {cx, cy + 1}, {cx, cy - 1}};\n        }\n        for (auto& p : corners) {\n            if (!dot[p.x][p.y]) {\n                missing = p;\n                return true;\n            }\n        }\n        return false; // should not happen when dot_count==3\n    };\n\n    auto edges_unused = [&](int id) -> bool {\n        const Shape& sh = shapes[id];\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            if (hor[x][y] || hor[x][y + 1] || ver[x][y] || ver[x + 1][y]) return false;\n        } else {\n            int cx = sh.a, cy = sh.b;\n            if (diag1[cx][cy] || diag2[cx][cy] || diag1[cx - 1][cy - 1] || diag2[cx][cy - 1])\n                return false;\n        }\n        return true;\n    };\n\n    auto mark_edges_used = [&](int id) {\n        const Shape& sh = shapes[id];\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            hor[x][y] = true;\n            hor[x][y + 1] = true;\n            ver[x][y] = true;\n            ver[x + 1][y] = true;\n        } else {\n            int cx = sh.a, cy = sh.b;\n            diag1[cx][cy] = true;\n            diag2[cx][cy] = true;\n            diag1[cx - 1][cy - 1] = true;\n            diag2[cx][cy - 1] = true;\n        }\n    };\n\n    auto push_if_eligible = [&](int id) {\n        if (dot_count[id] != 3) return;\n        Point missing;\n        if (!get_missing(id, missing)) return;\n        if (!edges_unused(id)) return;\n        int w = (missing.x - c) * (missing.x - c) + (missing.y - c) * (missing.y - c) + 1;\n        pq.push({w, id});\n    };\n\n    priority_queue<pair<int, int>> pq; // max-heap by weight\n    for (int id = 0; id < S; ++id) push_if_eligible(id);\n\n    using Op = tuple<int, int, int, int, int, int, int, int>;\n    vector<Op> ops;\n\n    auto process_shape = [&](int id) {\n        if (dot_count[id] != 3) return false;\n        Point missing;\n        if (!get_missing(id, missing)) return false;\n        if (!edges_unused(id)) return false;\n        const Shape& sh = shapes[id];\n        vector<Point> corners;\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            corners = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};\n        } else {\n            int cx = sh.a, cy = sh.b;\n            corners = {{cx + 1, cy}, {cx - 1, cy}, {cx, cy + 1}, {cx, cy - 1}};\n        }\n        int missing_idx = -1;\n        for (int i = 0; i < 4; ++i) {\n            if (corners[i] == missing) { missing_idx = i; break; }\n        }\n        vector<Point> ordered;\n        for (int k = 0; k < 4; ++k) {\n            ordered.push_back(corners[(missing_idx + k) % 4]);\n        }\n        ops.emplace_back(\n            ordered[0].x, ordered[0].y,\n            ordered[1].x, ordered[1].y,\n            ordered[2].x, ordered[2].y,\n            ordered[3].x, ordered[3].y\n        );\n        dot[missing.x][missing.y] = true;\n        mark_edges_used(id);\n        for (int sid : point_shapes[missing.x][missing.y]) {\n            ++dot_count[sid];\n            if (dot_count[sid] == 3) push_if_eligible(sid);\n        }\n        return true;\n    };\n\n    while (!pq.empty()) {\n        auto [w, id] = pq.top();\n        pq.pop();\n        process_shape(id);\n    }\n\n    cout << ops.size() << '\\n';\n    for (auto& op : ops) {\n        int x1, y1, x2, y2, x3, y3, x4, y4;\n        tie(x1, y1, x2, y2, x3, y3, x4, y4) = op;\n        cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << ' '\n             << x3 << ' ' << y3 << ' ' << x4 << ' ' << y4 << '\\n';\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*------------------------------------------------------------*/\n/*  board utilities                                            */\n/*------------------------------------------------------------*/\nusing Board = array<array<int,10>,10>;\n\n/* place a candy of given flavour into the p-th empty cell (1-indexed) */\nvoid place_candy(Board &bd, int flavour, int p) {\n    int cnt = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (bd[i][j] == 0) {\n                if (++cnt == p) {\n                    bd[i][j] = flavour;\n                    return;\n                }\n            }\n        }\n    }\n}\n\n/* tilt the board in the given direction:\n   0 = F (up), 1 = B (down), 2 = L (left), 3 = R (right) */\nBoard tilt(const Board &bd, int dir) {\n    Board nb{}; // all zero\n    if (dir == 0) {               // F : up\n        for (int j = 0; j < 10; ++j) {\n            int r = 0;\n            for (int i = 0; i < 10; ++i)\n                if (bd[i][j]) nb[r++][j] = bd[i][j];\n        }\n    } else if (dir == 1) {        // B : down\n        for (int i = 0; i < 10; ++i) {\n            int r = 9;\n            for (int j = 9; j >= 0; --j)\n                if (bd[i][j]) nb[i][r--] = bd[i][j];\n        }\n    } else if (dir == 2) {        // L : left\n        for (int i = 0; i < 10; ++i) {\n            int c = 0;\n            for (int j = 0; j < 10; ++j)\n                if (bd[i][j]) nb[i][c++] = bd[i][j];\n        }\n    } else {                      // dir == 3 : R : right\n        for (int i = 0; i < 10; ++i) {\n            int c = 9;\n            for (int j = 9; j >= 0; --j)\n                if (bd[i][j]) nb[i][c--] = bd[i][j];\n        }\n    }\n    return nb;\n}\n\n/* compute sum of squares of component sizes */\nint compute_score(const Board &bd) {\n    bool seen[10][10] = {};\n    int sum = 0;\n    const int dr[4] = {-1,1,0,0};\n    const int dc[4] = {0,0,-1,1};\n\n    auto bfs = [&](int sr, int sc) -> int {\n        int f = bd[sr][sc];\n        queue<pair<int,int>> q;\n        q.emplace(sr,sc);\n        seen[sr][sc] = true;\n        int sz = 0;\n        while (!q.empty()) {\n            auto [r,c] = q.front(); q.pop();\n            ++sz;\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + dr[d], nc = c + dc[d];\n                if (nr < 0 || nr >= 10 || nc < 0 || nc >= 10) continue;\n                if (seen[nr][nc] || bd[nr][nc] != f) continue;\n                seen[nr][nc] = true;\n                q.emplace(nr,nc);\n            }\n        }\n        return sz;\n    };\n\n    for (int i = 0; i < 10; ++i)\n        for (int j = 0; j < 10; ++j)\n            if (bd[i][j] != 0 && !seen[i][j]) {\n                int sz = bfs(i,j);\n                sum += sz*sz;\n            }\n    return sum;\n}\n\n/*------------------------------------------------------------*/\n/*  main                                                       */\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int flavour[100];\n    for (int i = 0; i < 100; ++i) cin >> flavour[i];\n\n    Board board{}; // all zero\n\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        if (!(cin >> p)) break;          // safety, should not happen\n        place_candy(board, flavour[t], p);\n\n        if (t == 99) break;              // last candy \u2013 no output\n\n        int best_dir = -1;\n        int best_val = -1;\n        for (int dir = 0; dir < 4; ++dir) {\n            Board tmp = tilt(board, dir);\n            int val = compute_score(tmp);\n            if (val > best_val) {\n                best_val = val;\n                best_dir = dir;\n            }\n        }\n        char out;\n        switch(best_dir) {\n            case 0: out = 'F'; break;\n            case 1: out = 'B'; break;\n            case 2: out = 'L'; break;\n            case 3: out = 'R'; break;\n        }\n        cout << out << '\\n';\n        cout.flush();\n\n        // really apply the chosen tilt\n        board = tilt(board, best_dir);\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    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n    const int N = 100;                       // number of vertices (max allowed)\n    const long long L = 1LL * N * (N - 1) / 2; // total possible edges    // Pre\u2011compute expected triangle and edge counts for clique sizes k = 1..M\n    vector<double> expTri(M + 1), expEdge(M + 1);\n    for (int k = 1; k <= M; ++k) {\n        long long C3k = (k >= 3) ? 1LL * k * (k - 1) * (k - 2) / 6 : 0LL;\n        long long C2k = (k >= 2) ? 1LL * k * (k - 1) / 2 : 0LL;\n        long long iso = N - k;\n        long long C2iso = (iso >= 2) ? 1LL * iso * (iso - 1) / 2 : 0LL;\n        long long C3iso = (iso >= 3) ? 1LL * iso * (iso - 1) * (iso - 2) / 6 : 0LL;\n\n        double oneMinusEps = 1.0 - eps;\n        double p3 = oneMinusEps * oneMinusEps * oneMinusEps; // (1-\u03b5)^3\n        double p2 = oneMinusEps * eps * eps;                // (1-\u03b5)*\u03b5^2\n        double p1 = eps * eps * eps;                        // \u03b5^3\n\n        // Expected number of triangles\n        expTri[k] = C3k * p3 +\n                    C2k * iso * p2 +\n                    (static_cast<double>(k) * C2iso + C3iso) * p1;\n\n        // Expected number of edges\n        expEdge[k] = C2k * oneMinusEps + (L - C2k) * eps;\n    }\n\n    // Output N and the M graphs (clique of size s+1 on first s+1 vertices)\n    cout << N << '\\n';\n    for (int s = 0; s < M; ++s) {\n        int k = s + 1; // clique size\n        string str;\n        str.reserve(L);\n        for (int i = 0; i < N; ++i)\n            for (int j = i + 1; j < N; ++j)\n                str.push_back((i < k && j < k) ? '1' : '0');\n        cout << str << '\\n';\n    }\n    cout.flush();\n\n    // Process 100 queries\n    for (int qq = 0; qq < 100; ++qq) {\n        string H;\n        if (!(cin >> H)) break;\n        long long triObs = 0;\n        long long edgeObs = 0;\n        vector<bitset<100>> adj(N);\n        int pos = 0;\n        // Build adjacency and count edges\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                char c = H[pos++];\n                if (c == '1') {\n                    adj[i][j] = true;\n                    adj[j][i] = true;\n                    ++edgeObs;\n                }\n            }\n        }\n        // Count triangles: for each edge (i,j) count common neighbours > j\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (adj[i][j]) {\n                    triObs += ((adj[i] & adj[j]) >> (j + 1)).count();\n                }\n            }\n        }\n\n        // Choose s with minimal squared distance to expected (tri, edge)\n        int bestS = 0;\n        double bestDist = 1e100;\n        for (int s = 0; s < M; ++s) {\n            int k = s + 1;\n            double dt = triObs - expTri[k];\n            double de = edgeObs - expEdge[k];\n            double dist = dt * dt + de * de;\n            if (dist < bestDist) {\n                bestDist = dist;\n                bestS = s;\n            }\n        }\n        cout << bestS << '\\n';\n        cout.flush();\n    }\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    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n    // read edges (ignore their data)\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n    }\n    // read coordinates (ignore)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    // assign each edge to day in round\u2011robin fashion\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << (i % D) + 1;\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Voxel {\n    int x, y, z;\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\n    // Read silhouettes\n    vector<vector<string>> fStr(2, vector<string>(D));\n    vector<vector<string>> rStr(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> fStr[i][k];\n        }\n    }\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> rStr[i][k];\n        }\n    }\n\n    // Convert to bool arrays\n    vector<vector<vector<bool>>> f(2, vector<vector<bool>>(D, vector<bool>(D)));\n    vector<vector<vector<bool>>> r(2, vector<vector<bool>>(D, vector<bool>(D)));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int x = 0; x < D; ++x) {\n                f[i][z][x] = (fStr[i][zvoid solve() {\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int y = 0; y < D; ++y) {\n                r[i][z][y] = (rStr[i][z][y] == '1');\n            }\n        }\n    }\n}\n\n    // Collect voxels that satisfy both projections\n    vector<Voxel> vox[2];\n    for (int i = 0; i < 2; ++i) {\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[i][z][x] && r[i][z][y]) {\n                        vox[i].push_back({x, y, z});\n                    }\n                }\n            }\n        }\n    }\n\n    int v0 = (int)vox[0].size();\n    int v1 = (int)vox[1].size();\n    int n = max(v0, v1);\n\n    int size = D * D * D;\n    vector<int> b0(size, 0);\n    vector<int> b1(size, 0);\n\n    for (int i = 0; i < n; ++i) {\n        if (i < v0) {\n            const Voxel& v = vox[0][i];\n            int idx = v.x * D * D + v.y * D + v.z;\n            b0[idx] = i + 1;\n        }\n        if (i < v1) {\n            const Voxel& v = vox[1][i];\n            int idx = v.x * D * D + v.y * D + v.z;\n            b1[idx] = i + 1;\n        }\n    }\n\n    cout << n << '\\n';\n    for (int i = 0; i < size; ++i) {\n        if i > 0) cout << ' ';\n        cout << b0[i];\n    }\n    cout << '\\n';\n    for (int i = 0; i < size; ++i) {\n        if (i > 0) cout << ' ';\n        cout << b1[i];\n    }\n    cout << '\\n';\n    return 0;\n}\nint main() {\n    solve();\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge {\n    int to;\n    long long w;\n    int id;\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    \n    vector<int> xs(N), ys(N);\n    for (int i = 0; i < N; ++i) cin >> xs[i] >> ys[i];\n    \n    vector<tuple<int,int,long long>> edgesRaw; // (u,v,w)\n    edgesRaw.reserve(M);\n    vector<vector<Edge>> adj(N);\n    for (int j = 0; j < M; ++j) {\n        int u, v; long long w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edgesRaw.emplace_back(u, v, w);\n        adj[u].push_back({v, w, j});\n        adj[v].push_back({u, w, j});\n    }\n    \n    vector<pair<int,int>> residents(K);\n    for (int k = 0; k < K; ++k) {\n        cin >> residents[k].first >> residents[k].second;\n    }\n    \n    /* ---------- Dijkstra from vertex 0 (station 1) ---------- */\n    const long long INF = (1LL<<60);\n    vector<long long> dist(N, INF);\n    vector<int> parentEdge(N, -1); // edge id that connects v to its parent\n    vector<int> parentVertex(N, -1);\n    using State = pair<long long,int>;\n    priority_queue<State, vector<State>, greater<State>> pq;\n    dist[0] = 0;\n    pq.emplace(0, 0);\n    while (!pq.empty()) {\n        auto [d, v] = pq.top(); pq.pop();\n        if (d != dist[v]) continue;\n        for (const auto &e : adj[v]) {\n            if (dist[e.to] > d + e.w) {\n                dist[e.to] = d + e.w;\n                parentEdge[e.to] = e.id;\n                parentVertex[e.to] = v;\n                pq.emplace(dist[e.to], e.to);\n            }\n        }\n    }\n    \n    /* ---------- Build tree adjacency (undirected) ---------- */\n    vector<vector<pair<int,int>>> tree(N); // (neighbor, edgeId)\n    for (int v = 1; v < N; ++v) {\n        int eid = parentEdge[v];\n        int u = parentVertex[v];\n        tree[u].emplace_back(v, eid);\n        tree[v].emplace_back(u, eid);\n    }\n    \n    /* ---------- Assign residents to nearest vertex ---------- */\n    vector<int> need(N, 0); // required power (radius) for each vertex\n    for (auto [ax, ay] : residents) {\n        long long bestDist2 = LLONG_MAX;\n        int bestV = -1;\n        for (int v = 0; v < N; ++v) {\n            long long dx = xs[v] - ax;\n            long long dy = ys[v] - ay;\n            long long d2 = dx*dx + dy*dy;\n            if (d2 < bestDist2) {\n                bestDist2 = d2;\n                bestV = v;\n            }\n        }\n        double dist = sqrt((double)bestDist2);\n        int radius = (int)ceil(dist - 1e-9); // safe ceil\n        if (radius < 0) radius = 0;\n        if (radius > 5000) radius = 5000;\n        need[bestV] = max(need[bestV], radius);\n    }\n    \n    /* ---------- Prune the tree ---------- */\n    vector<char> answerB(M, 0);\n    vector<int> answerP(N);\n    for (int i = 0; i < N; ++i) answerP[i] = need[i];\n        function<bool(int,int)> dfs = [&](int v, int p) -> bool {\n        bool subtreeNeed = (need[v] > 0);\n        for (auto [to, eid] : tree[v]) {\n            if (to == p) continue;\n            bool childNeed = dfs(to, v);\n            if (childNeed) answerB[eid] = 1;\n            else answerB[eid] = 0;\n            subtreeNeed |= childNeed;\n        }\n        return subtreeNeed;\n    };\n    dfs(0, -1);\n    \n    /* ---------- Output ---------- */\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << answerP[i];\n    }\n    cout << '\\n';\n    for (int j = 0; j < M; ++j) {\n        if (j) cout << ' ';\n        cout << (int)answerB[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 total = N * (N + 1) / 2; // 465\n\n    // Precompute level and coordinates for each index in level\u2011order (heap) layout.\n    vector<int> level(total), cx(total), cy(total);\n    int idx = 0;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            level[idx] = x;\n            cx[idx] = x;\n            cy[idx] = y;\n            ++idx;\n        }\n    }\n\n    // Read the initial permutation into the heap\u2011order array.\n    vector<int> val(total);\n    idx = 0;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int v;\n            cin >> v;\n            val[idx++] = v;\n        }\n    }\n\n    struct Op { int x1, y1, x2, y2; };\n    vector<Op> ops;\n    ops.reserve(7000); // rough upper bound\n\n    // Helper to get children indices of a node in heap layout.\n    auto children = [&](int i) {\n        int lev = level[i];\n        int left = i + lev + 1;     // left child (same y)\n        int right = i + lev + 2;    // right child (y+1)\n        return make_pair(left, right);\n    };\n\n    // Sift\u2011down procedure.\n    auto siftDown = [&](int i) {\n        while (true) {\n            auto [l, r] = children(i);\n            int smallest = i;\n            if (l < total && val[l] < val[smallest]) smallest = l;\n            if (r < total && val[r] < val[smallest]) smallest = r;\n            if (smallest == i) break;\n            // swap values\n            swap(val[i], val[smallest]);\n            // record swap (coordinates)\n            ops.push_back({cx[i], cy[i], cx[smallest], cy[smallest]});\n            i = smallest;\n        }\n    };\n\n    // Build\u2011heap: sift down from the last parent upwards.\n    for (int i = total / 2 - 1; i >= 0; --i) {\n        siftDown(i);\n    }\n\n    // Output the sequence of swaps.\n    cout << ops.size() << '\\n';\n    for (const auto& op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' ' << 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 ent_r = 0;\n    const int ent_c = (D - 1) / 2;\n\n    vector<vector<bool>> blocked(D, vector<bool>(D, false));\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            blocked[i][j] = false;\n        }\n    }\n    for (int k = 0; k < N; ++k) {\n        int r, j;\n        cin >> r >> j;\n        blocked[r][j] = true;\n    }\n    // entrance is never blocked\n    blocked[ent_r][ent_c] = false;\n\n    // Precompute distances from entrance ignoring obstacles (static)\n    vector<vector<int>> dist(D, vector<int>(D, -1));\n    queue<pair<int,int>> q;\n    dist[ent_r][ent_c] = 0;\n    q.emplace(ent_r, ent_c);\n    const int dr[4] = {-1,1,0,0};\n    const int dc[4] = {0,0,-1,1};\n    while (!q.empty()) {\n        auto [r,c] = q.front(); q.pop();\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 >= D || nc < 0 || nc >= D) continue;\n            if (blocked[nr][nc]) continue;\n            if (dist[nr][nc] != -1) continue;\n            dist[nr][nc] = dist[r][c] + 1;\n            q.emplace(nr, nc);\n        }\n    }\n\n    // Build list L of eligible cells (non-obstacle, non-entrance)\n    vector<pair<int,int>> L;\n    L.reserve(D*D);\n    vector<vector<int>> idx(D, vector<int>(D, -1));\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            if (blocked[i][j]) continue;\n            if (i == ent_r && j == ent_c) continue;\n            L.emplace_back(i, j);\n            idx[i][j] = (int)L.size() - 1;\n        }\n    }\n    const int M = (int)L.size();\n    // sort L by distance, then row, then column\n    sort(L.begin(), L.end(), [&](const auto& a, const auto& b) {\n        if (dist[a.first][a.second] != dist[b.first][b.second])\n            return dist[a.first][a.second] < dist[b.first][b.second];\n        if (a.first != b.first) return a.first < b.first;\n        return a.second < b.second;\n    });\n    // rebuild idx after sorting\n    for (int i = 0; i < D; ++i) for (int j = 0; j < D; ++j) idx[i][j] = -1;\n    for (int p = 0; p < M; ++p) {\n        auto [r,c] = L[p];\n        idx[r][c] = p;\n    }\n\n    vector<vector<bool>> occupied(D, vector<bool>(D, false));\n    auto bfsReachable = [&](const vector<vector<bool>>& occ) -> vector<vector<bool>> {\n        vector<vector<bool>> reach(D, vector<bool>(D, false));\n        queue<pair<int,int>> qq;\n        if (!blocked[ent_r][ent_c] && !occ[ent_r][ent_c]) {\n            reach[ent_r][ent_c] = true;\n            qq.emplace(ent_r, ent_c);\n        }\n        while (!qq.empty()) {\n            auto [r,c] = qq.front(); qq.pop();\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 >= D || nc < 0 || nc >= D) continue;\n                if (blocked[nr][nc] || occ[nr][nc]) continue;\n                if (reach[nr][nc]) continue;\n                reach[nr][nc] = true;\n                qq.emplace(nr, nc);\n            }\n        }\n        return reach;\n    };\n\n    // articulation points on the subgraph induced by reachable cells (which is connected)\n    auto getArticulation = [&](const vector<vector<bool>>& reach) -> vector<vector<bool>> {\n        vector<vector<bool>> isArt(D, vector<bool>(D, false));\n        vector<int> tin(D*D, -1), low(D*D, -1);\n        vector<char> visited(D*D, false);\n        int timer = 0;\n        function<void(int,int,int,int)> dfs = [&](int r, int c, int pr, int pc) {\n            int id = r*D + c;\n            visited[id] = true;\n            tin[id] = low[id] = timer++;\n            int children = 0;\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 >= D || nc < 0 || nc >= D) continue;\n                if (!blocked[nr][nc] && !occ[nr][nc] && reach[nr][nc]) {\n                    int nid = nr*D + nc;\n                    if (visited[nid]) {\n                        low[id] = min(low[id], tin[nid]);\n                    } else {\n                        ++children;\n                        dfs(nr, nc, r, c);\n                        low[id] = min(low[id], low[nid]);\n                        if (pr != -1 && low[nid] >= tin[id]) {\n                            isArt[r][c] = true;\n                        }\n                    }\n                }\n            }\n            if (pr == -1 && children > 1) {\n                isArt[r][c] = true;\n            }\n        };\n        // entrance is guaranteed reachable\n        dfs(ent_r, ent_c, -1, -1);\n        return isArt;\n    };\n\n    // Main loop: place M containers\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;\n        vector<vector<bool>> reach = bfsReachable(occupied);\n        vector<vector<bool>> isArt = getArticulation(reach);\n        // gather candidates: reachable, not entrance, not occupied, not articulation        int best_r = -1, best_c = -1;\n        int best_cost = INT_MAX;\n        for (int i = 0; i < D; ++i) {\n            for (int j = 0; j < D; ++j) {\n                if (!reach[i][j]) continue;\n                if (i == ent_r && j == ent_c) continue;\n                if (occupied[i][j]) continue;\n                if (isArt[i][j]) continue;\n                int cost = abs(idx[i][j] - t);\n                if (cost < best_cost || (cost == best_cost && (i < best_r || (i == best_r && j < best_c)))) {\n                    best_cost = cost;\n                    best_r = i;\n                    best_c = j;\n                }\n            }\n        }\n        // fallback: if no candidate (should not happen), pick any reachable non-entrance non-occupied\n        if (best_r == -1) {\n            for (int i = 0; i < D; ++i) {\n                for (int j = 0; j < D; ++j) {\n                    if (!reach[i][j]) continue;\n                    if (i == ent_r && j == ent_c) continue;\n                    if (occupied[i][j]) continue;\n                    best_r = i; best_c = j;\n                    break;\n                }\n                if (best_r != -1) break;\n            }\n        }\n        occupied[best_r][best_c] = true;\n        cout << best_r << ' ' << best_c << '\\n';\n        cout.flush();\n    }\n\n    // Output transport order: increasing distance (L order)\n    for (auto [r,c] : L) {\n        cout << r << ' ' << c << '\\n';\n    }\n    // optional final flush\n    cout.flush();\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*------------------------------------------------------------*/\n/*  Constants and directions                                  */\nconst int dx[4] = {1, -1, 0, 0};\nconst int dy[4] = {0, 0, 1, -1};\n\n/*------------------------------------------------------------*/\nstruct Solver {\n    int n, m;\n    vector<vector<short>> grid;          // current colours\n    vector<int> cnt;                     // number of cells of each colour (>0)\n    vector<vector<int>> adj;             // current adjacency counts\n    vector<vector<int>> adjOrig;         // original adjacency counts (constant)\n\n    Solver(int n_, int m_) : n(n_), m(m_) {\n        grid.assign(n, vector<short>(n, 0));\n        cnt.assign(m + 1, 0);\n        adj.assign(m + 1, vector<short>(m + 1, 0));\n        adjOrig.assign(m + 1, vector<short>(m + 1, 0));\n    }\n\n    /*--------------------------------------------------------*/\n    // read the input\n    void read() {\n        cin >> n >> m;\n        grid.assign(n, vector<short>(n));\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) {\n                cin >> grid[i][j];\n                if (grid[i][j] > 0) ++cnt[grid[i][j]];\n            }\n    }\n\n    /*--------------------------------------------------------*/\n    // compute adjacency matrix from a given grid\n    void computeAdj(const vector<vector<short>>& g, vector<vector<int>>& out) {\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) {\n                int c = g[i][j];\n                for (int d = 0; d < 4; ++d) {\n                    int ni = i + dx[d], nj = j + dy[d];\n                    int nb = 0;               // outside\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n)\n                        nb = g[ni][nj];\n                    if (c == nb) continue;   // same colour \u2013 we do not store c\u2011c\n                    out[c][nb]++;\n                    out[nb][c]++;\n                }\n            }\n    }\n\n    /*--------------------------------------------------------*/\n    // zero\u2011neighbour test (outside counts as zero)\n    bool hasZeroNeighbour(int i, int j) const {\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) return true;   // outside\n            if (grid[ni][nj] == 0) return true;\n        }\n        return false;\n    }\n\n    /*--------------------------------------------------------*/\n    // BFS to check connectivity of a given colour (>0)\n    bool connectedColour(int col) const {\n        // find any cell of this colour\n        int si = -1, sj = -1;\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (grid[i][j] == col) { si = i; sj = j; break; }\n            if (si != -1) break;\n        if (si == -1) return false;   // should never happen because cnt[col]>0 checked before\n        vector<vector<char>> vis(n, vector<char>(0, false));\n        queue<pair<int,int>> q;\n        q.emplace(si, sj);\n        vis[si][sj] = 1;\n        int reached = 0;\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            ++reached;\n            for (int d = 0; d < 4; ++d) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;\n                if (grid[nx][ny] != col) continue;\n                if (vis[nx][ny]) continue;\n                vis[nx][ny] = 1;\n                q.emplace(nx, ny);\n            }\n        }\n        return reached == cnt[col];\n    }\n\n    /*--------------------------------------------------------*/\n    // check that all zero cells are reachable from the outside\n    bool zeroConnected() const {\n        vector<vector<char>> vis(n, vector<char>(0, false));\n        queue<pair<int,int>> q;\n        // start from all boundary zero cells (they touch the outside)\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] == 0 && (i == 0 || i == n-1 || j == 0 || j == n-1)) {\n                    q.emplace(i, j);\n                    vis[i][j] = 1;\n                }\n            }\n        }\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;\n                if (grid[nx][ny] != 0) continue;\n                if (vis[nx][ny]) continue;\n                vis[nx][ny] = 1;\n                q.emplace(nx, ny);\n            }\n        }\n        // any zero cell not visited?\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (grid[i][j] == 0 && !vis[i][j]) return false;\n        return true;\n    }\n\n    /*--------------------------------------------------------*/\n    // try to delete cell (i,j); return true iff deletion really happened\n    bool tryDelete(int i, int j) {\n        int col = grid[i][j];\n        if (col == 0) return false;\n        if (!hasZeroNeighbour(i, j)) return false;\n\n        // backup        int backupCnt = cnt[col];\n        vector<tuple<int,int,int>> changes;   // (a,b,delta) to be added to adj[a][b]\n\n        // process the four neighbours        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d], nj = y + dy[d];\n            int nb;\n            bool outside = false;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) { nb = 0; outside = true; }\n            else nb = grid[ni][nj];\n\n            if (nb == col) continue;          // internal edge, nothing to change\n\n            // erase edge col \u2013 nb\n            changes.emplace_back(col, nb, -1);\n            changes.emplace_back(nb, col, -1);\n\n            if (nb != 0 && !outside) {\n                // create edge 0 \u2013 nb\n                changes.emplace_back(0, nb, +1);\n                changes.emplace_back(nb, 0, +1);\n            }\n            // if nb == 0 (inside zero or outside) we only removed a col\u20110 edge\n        }\n\n        // apply changes to adj\n        for (auto &ch : changes) {\n            int a = get<0>(ch), b = get<1>(ch), delta = get<2>(ch);\n            adj[a][b] += delta;\n        }\n\n        // actually delete the cell\n        grid[i][j] = 0;\n        --cnt[col];\n\n        // ----- tests -----\n        bool ok = true;\n        if (cnt[col] == 0) ok = false;                // colour must stay non\u2011empty\n\n        if (ok) {\n            // adjacency matrix must stay exactly the same (as Boolean)\n            for (int x = 0; x <= m && ok; ++x)\n                for (int y = x; y <= m && ok; ++y)\n                    bool cur = (adj[x][y] > 0);\n                    bool orig = (adjOrig[x][y] > 0);\n                    if (cur != orig) { ok = false; break; }\n        }\n        if (ok) {\n            if (!connectedColour(col)) ok = false;\n        }\n        if (ok) {\n            if (!zeroConnected()) ok = false;\n        }\n\n        if (!ok) {\n            // ----- revert -----            grid[i][j] = col;\n            cnt[col] = backupCnt;\n            for (auto &ch : changes) {\n                int a = get<0>(ch), b = get<1>(ch), delta = get<2>(ch);\n                adj[a][b] -= delta;   // undo the addition\n            }\n            return false;\n        }\n        return true;\n    }\n\n    /*--------------------------------------------------------*/\n    void solve() {\n        read();\n        computeAdj(grid, adjOrig);\n        adj = adjOrig;          // start with the original adjacency\n\n        bool progress;\n        do {\n            progress = false;\n            vector<pair<int,int>> cand;\n            for (int i = 0; i < n; ++i)\n                for (int j = 0; j < n; ++j)\n                    if (grid[i][j] > 0)\n                        cand.emplace_back(i, j);\n            std::shuffle(cand.begin(), cand.end(),\n                         std::mt19937{std::random_device{}()});\n            for (auto &p : cand)\n                if (tryDelete(p.first, p.second))\n                    progress = true;\n        } while (progress);\n\n        // output the final grid\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << grid[i][j];\n                if (j + 1 < n) cout << ' ';\n            }\n            cout << '\\n';\n        }\n    }\n};\n\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m;\n    cin >> n >> m;\n    Solver solver(n, m);\n    solver.solve();\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    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n\n    int query_cnt = 0;\n    auto ask = [&](int a, int b) -> char {\n        assert(query_cnt < Q);\n        cout << 1 << ' ' << 1 << ' ' << a << ' ' << b << '\\n';\n        cout.flush();\n        string res;\n        cin >> res;\n        ++query_cnt;\n        return res[0];\n    };\n\n    // ---------- 1. obtain an order by (partial) comparison sort ----------\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);   // 0,1,2,...,N-1\n\n    bool exhausted = false;\n    for (int i = 1; i < N && !exhausted; ++i) {\n        int key = order[i];\n        int lo = 0, hi = i;                // search in [lo, hi)\n        while (lo < hi && !exhausted) {\n            if (query_cnt >= Q) { exhausted = true; break; }\n            int mid = (lo + hi) / 2;\n            char res = ask(key, order[mid]);\n            if (res == '<') {\n                hi = mid;\n            } else if (res == '>') {\n                lo = mid + 1;\n            } else { // '=' \u2013 treat as not less\n                lo = mid + 1;\n            }\n        }\n        if (exhausted) break;\n        int pos = lo;\n        // shift elements to make room for key        for (int j = i; j > pos; --j) order[j] = order[j-1];\n        order[pos] = key;\n    }\n\n    // ---------- 2. consume remaining queries with dummy comparisons ----------\n    while (query_cnt < Q) {\n        // N >= 30, so items 0 and 1 exist\n        ask(0, 1);\n    }\n\n    // ---------- 3. estimate weights from the obtained order ----------\n    vector<int> weight(N);               // weight estimate = rank in order\n    for (int idx = 0; idx < N; ++idx) {\n        weight[order[idx]] = idx;        // 0 = lightest, N-1 = heaviest\n    }\n\n    // ---------- 4. LPT (greedy) partition into D groups ----------\n    vector<int64_t> group_sum(D, 0);\n    vector<int> answer(N);\n\n    // items sorted by decreasing estimated weight\n    vector<int> items(N);\n    iota(items.begin(), items.end(), 0);\n    sort(items.begin(), items.end(),\n         [&](int x, int y) { return weight[x] > weight[y]; });\n\n    for (int v : items) {\n        int g = 0;\n        for (int j = 1; j < D; ++j) {\n            if (group_sum[j] < group_sum[g]) g = j;\n        }\n        answer[v] = g;\n        group_sum[g] += weight[v];\n    }\n\n    // ---------- 5. output the partition ----------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << answer[i];\n    }\n    cout << '\\n';\n    cout.flush();\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    int per = n / m;\n    vector<vector<int>> stacks(m);\n    for (int i = 0; i < m; ++i) {\n        stacks[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x;\n            cin >> x;\n            stacks[i].push_back(x);\n        }\n    }\n\n    vector<pair<int,int>> ops;\n    ops.reserve(2 * n); // at most 2 operations per box\n\n    for (int v = 1; v <= n; ++v) {\n        int src = -1, pos = -1;\n        for (int i = 0; i < m; ++i) {\n            auto &st = stacks[i];\n            for (size_t j = 0; j < st.size(); ++j) {\n                if (st[j] == v) {\n                    src = i;\n                    pos = j;\n                    break;\n                }\n            }\n            if (src != -1) break;\n        }\n\n        int height = (int)stacks[src].size();\n        int above = height - 1 - pos; // boxes strictly above v\n\n        if (above == 0) {\n            // v is already on top, just carry it out\n            ops.emplace_back(v, 0);\n            stacks[src].pop_back();\n            continue;\n        }\n\n        // choose destination stack with minimal height (different from src)\n        int best = -1;\n        int bestHeight = 1e9;\n        for (int i = 0; i < m; ++i) {\n            if (i == src) continue;\n            int h = (int)stacks[i].size();\n            if (h < bestHeight) {\n                bestHeight = h;\n                best = i;\n            }\n        }\n        int dest = best; // guaranteed to exist because m >= 2\n\n        // move the suffix above v (pos+1 .. end) to destination stack\n        vector<int> moved;\n        moved.reserve(above);\n        for (size_t j = pos + 1; j < stacks[src].size(); ++j) {\n            moved.push_back(stacks[src][j]);\n        }\n        // erase them from source stack\n        stacks[src].erase(stacks[src].begin() + pos + 1, stacks[src].end());\n        // append to destination stack (preserving order)\n        stacks[dest].insert(stacks[dest].end(), moved.begin(), moved.end());\n\n        // operation 1: move the suffix above v\n        ops.emplace_back(v, dest + 1); // destination index is 1\u2011based in output\n        // now v is on top of its source stack\n        ops.emplace_back(v, 0);        // operation 2: carry out v        stacks[src].pop_back();        // remove v\n    }\n\n    for (auto &p : ops) {\n        cout << p.first << ' ' << p.second << '\\n';\n    }\n    return 0;\n}","ahc027":"#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\n    vector<string> h(N - 1), v(N);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    vector<vector<int>> d(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    /* ----- helpers to test walls ----- */\n    auto canUp = [&](int i, int j) { return i > 0 && h[i - 1][j] == '0'; };\n    auto canDown = [&](int i, int j) { return i + 1 < N && h[i][j] == '0'; };\n    auto canLeft = [&](int i, int j) { return j > 0 && v[i][j - 1] == '0'; };\n    auto canRight = [&](int i, int j) { return j + 1 < N && v[i][j] == '0'; };\n\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 oppChar[4] = {'D', 'U', 'R', 'L'};\n\n    /* ----- DFS to visit every cell ----- */\n    vector<string> visitedStr(N, string(N, '0'));\n    vector<vector<bool>> vis(N, vector<bool>(N, false));\n    string moves;\n\n    function<void(int, int)> dfs = [&](int x, int y) {\n        vis[x][y] = true;\n        for (int dir = 0; dir < 4; ++dir) {\n            int nx = x + dx[dir];\n            int ny = y + dy[dir];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            bool ok = false;\n            if (dir == 0) ok = canUp(x, y);\n            else if (dir == 2) ok = canLeft(x, y);\n            else if (dir == 1) ok = canDown(x, y);\n            else if (dir == 3) ok = canRight(x, y);\n            if (!ok || vis[nx][ny]) continue;\n            moves.push_back(dirChar[dir]);\n            dfs(nx, ny);\n            moves.push_back(oppChar[dir]);\n        }\n    };\n    dfs(0, 0);\n\n    int baseLen = (int)moves.size();\n\n    /* ----- choose neighbour of (0,0) for back\u2011and\u2011forth loops ----- */\n    struct NB {\n        int dir;          // 0:U,1:D,2:L,3:R\n        int ni, nj;\n        int val;\n        double rnd;\n    };\n    vector<NB> cand;\n    for (int dir = 0; dir < 4; ++dir) {\n        int nx = dx[dir];\n        int ny = dy[dir];\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n        bool ok = false;\n        if (dir == 0) ok = canUp(0, 0);\n        else if (dir == 2) ok = canLeft(0, 0);\n        else if (dir == 1) ok = canDown(0, 0);\n        else if (dir == 3) ok = canRight(0, 0);\n        if (!ok) continue;\n        cand.push_back({dir, nx, ny, d[nx][ny],\n                        (double)rand() / RAND_MAX});\n    }\n    /* sort by descending d, break ties randomly */\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    shuffle(cand.begin(), cand.end(), rng);\n    sort(cand.begin(), cand.end(),\n         [](const NB& a, const NB& b) {\n             if (a.val != b.val) return a.val > b.val;\n             return a.rnd < b.rnd;\n         });\n\n    const int MAX_LEN = 100000;\n    int loops = 0;\n    if (!cand.empty())\n        loops = max(0, (MAX_LEN - baseLen) / 2);\n\n    for (int i = 0; i < loops; ++i) {\n        const NB& nb = cand[i % (int)cand.size()];\n        moves.push_back(dirChar[nb.dir]);\n        moves.push_back(oppChar[nb.dir]);\n    }\n\n    cout << moves << '\\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        int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n    \n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) cin >> t[i];\n    \n    // Build the concatenated string (all t_i in given order)\n    string S;\n    for (const string& str : t) S += str;\n    int L = (int)S.size(); // L = 5 * M = 1000\n    \n    // Positions of each letter in the grid\n    vector<vector<int>> pos(26);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int idx = i * N + j;\n            pos[grid[i][j] - 'A'].push_back(idx);\n        }\n    }\n    \n    const int INF = 1e9;\n    auto manhattan = [&](int a, int b) {\n        int r1 = a / N, c1 = a % N;\n        int r2 = b / N, c2 = b % N;\n        return abs(r1 - r2) + abs(c1 - r2);\n    };\n    // Actually the lambda above has a bug: c2 should be b%N, not b%N? Let's fix later.\n        // Correct lambda:\n    auto dist = [&](int a, int b) {\n        int r1 = a / N, c1 = a % N;\n        int r2 = b / N, c2 = b % N;\n        return abs(r1 - r2) + abs(c1 - c2);\n    };\n    \n    // DP arrays: dpPrev[id] = min cost to end at cell id after processing current prefix\n    vector<int> dpPrev(N * N, INF);\n    // prev[i][id] = previous cell id for position i (0-indexed in S) ending at id\n    vector<vector<int>> prev(L, vector<int>(N * N, -1));\n    \n    // Initialize for first character\n    char firstChar = S[0];\n    for (int id : pos[firstChar - 'A']) {\n        int d = dist(si * N + sj, id);\n        dpPrev[id] = d + 1; // move + press\n        prev[0][id] = -2; // marks start\n    }\n    \n    // Iterate over the rest of S\n    for (int i = 1; i < L; ++i) {\n        char curChar = S[i];\n        char prevChar = S[i-1];\n        vector<int> dpCurr(N * N, INF);\n        for (int id : pos[curChar - 'A']) {\n            int bestCost = INF;\n            int bestPrev = -1;\n            for (int pid : pos[prevChar - 'A']) {\n                if (dpPrev[pid] == INF) continue;\n                int cand = dpPrev[pid] + dist(pid, id) + 1;\n                if (cand < bestCost) {\n                    bestCost = cand;\n                    bestPrev = pid;\n                }\n            }\n            dpCurr[id] = bestCost;\n            prev[i][id] = bestPrev;\n        }\n        dpPrev.swap(dpCurr);\n    }\n        // Find best ending cell for the whole string\n    int lastId = -1;\n    int minCost = INF;\n    char lastChar = S.back();\n    for (int id : pos[lastChar - 'A']) {\n        if (dpPrev[id] < minCost) {\n            minCost = dpPrev[id];\n            lastId = id;\n        }\n    }\n    \n    // Reconstruct path\n    vector<int> path(L);\n    path[L-1] = lastId;\n    for (int i = L-1; i > 0; --i) {\n        path[i-1] = prev[i][path[i]];\n    }\n    \n    // Output the sequence of operations\n    for (int id : path) {\n        int r = id / N;\n        int c = id % N;\n        cout << r << ' ' << c << '\\n';\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;\n\n    // Read and ignore the shapes of oil fields (not needed for this simple strategy)\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < 2 * d; ++i) {\n            int x;\n            cin >> x;\n        }\n    }\n\n    vector<pair<int, int>> oil;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << \"q 1 \" << i << ' ' << j << endl;\n            int v;\n            cin >> v;\n            if (v > 0) {\n                oil.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Output the answer\n    cout << \"a \" << oil.size();\n    for (auto [i, j] : oil) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << endl;\n\n    // Read verdict (1 if correct, 0 otherwise). Terminate regardless.\n    int verdict;\n    cin >> verdict;\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    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            int x; cin >> x;\n        }\n    }\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << k << \" 0 \" << k+1 << \" \" << W << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll MOD = 998244353LL;\n\nstruct Op {\n    int m, p, q;\n    Op() {}\n    Op(int _m, int _p, int _q) : m(_m), p(_p), q(_q) {}\n};\n\nll add_mod(ll x, ll v) {\n    ll res = x + v;\n    if (res >= MOD) res -= MOD;\n    return res;\n}\nll sub_mod(ll x, ll v) {\n    ll res = x - v;\n    if (res < 0) res += MOD;\n    return res;\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    vector<vector<ll>> a(N, vector<ll>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> a[i][j];\n    vector<array<array<ll, 3>, 3>> stamps(M);\n    for (int m = 0; m < M; ++m)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> stamps[m][i][j];\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_stamp(0, M-1);\n    uniform_int_distribution<int> dist_pos(0, N-3); // 0..6\n\n    ll best_score = -1;\n    vector<Op> best_ops;\n\n    auto start_time = chrono::high_resolution_clock::now();\n    const double time_limit = 1.95; // seconds\n\n    for (int restart = 0; restart < 5; ++restart) {\n        auto now = chrono::high_resolution_clock::now();\n        double elapsed = chrono::duration<double>(now - start_time).count();\n        if (elapsed >= time_limit) break;\n\n        vector<vector<ll>> cur_val = a;\n        ll score = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                score += cur_val[i][j];\n\n        vector<Op> ops;\n        // optional random initialization\n        int init_add = 5;\n        for (int t = 0; t < init_add; ++t) {\n            int m = dist_stamp(rng);\n            int p = dist_pos(rng);\n            int q = dist_pos(rng);\n            ll delta = 0;\n            for (int di = 0; di < 3; ++di)\n                for (int dj = 0; dj < 3; ++dj) {\n                    int i = p + di, j = q + dj;\n                    ll v = stamps[m][di][dj];\n                    ll nx = cur_val[i][j] + v;\n                    if (nx >= MOD) nx -= MOD;\n                    delta += nx - cur_val[i][j];\n                    cur_val[i][j] = nx;\n                }\n            score += delta;\n            ops.emplace_back(m, p, q);\n        }\n\n        // hill climbing with add/remove/swap\n        while (true) {\n            auto now2 = chrono::high_resolution_clock::now();\n            double elapsed2 = chrono::duration<double>(now2 - start_time).count();\n            if (elapsed2 >= time_limit) break;\n\n            ll best_delta = 0;\n            int best_type = 0; // 1=add, 2=remove, 3=swap\n            int best_m = -1, best_p = -1, best_q = -1;\n            int best_idx = -1; // for remove or swap (old op index)\n            int best_m2 = -1, best_p2 = -1, best_q2 = -1; // for swap (new op)\n\n            // try add\n            if ((int)ops.size() < K) {\n                for (int m = 0; m < M; ++m) {\n                    for (int p = 0; p <= N - 3; ++p) {\n                        for (int q = 0; q <= N - 3; ++q) {\n                            ll delta = 0;\n                            for (int di = 0; di < 3; ++di)\n                                for (int dj = 0; dj < 3; ++dj) {\n                                    int i = p + di, j = q + dj;\n                                    ll v = stamps[m][di][dj];\n                                    ll nx = cur_val[i][j] + v;\n                                    if (nx >= MOD) nx -= MOD;\n                                    delta += nx - cur_val[i][j];\n                                }\n                            if (delta > best_delta) {\n                                best_delta = delta;\n                                best_type = 1;\n                                best_m = m; best_p = p; best_q = q;\n                            }\n                        }\n                    }\n                }\n            }\n\n            // try remove\n            if ((int)ops.size() > 0) {\n                for (size_t idx = 0; idx < ops.size(); ++idx) {\n                    const Op& op = ops[idx];\n                    ll delta = 0;\n                    int m = op.m, p = op.p, q = op.q;\n                    for (int di = 0; di < 3; ++di)\n                        for (int dj = 0; dj < 3; ++dj) {\n                            int i = p + di, j = q + dj;\n                            ll v = stamps[m][di][dj];\n                            ll nx = cur_val[i][j] - v;\n                            if (nx < 0) nx += MOD;\n                            delta += nx - cur_val[i][j];\n                        }\n                    if (delta > best_delta) {\n                        best_delta = delta;\n                        best_type = 2;\n                        best_idx = (int)idx;\n                    }\n                }\n            }\n\n            // try swap (remove old, add new)\n            if ((int)ops.size() > 0 && (int)ops.size() < K) {\n                for (size_t idx_old = 0; idx_old < ops.size(); ++idx_old) {\n                    const Op& op_old = ops[idx_old];\n                    int m_old = op_old.m, p_old = op_old.p, q_old = op_old.q;\n                    for (int m_new = 0; m_new < M; ++m_new) {\n                        for (int p_new = 0; p_new <= N - 3; ++p_new) {\n                            for (int q_new = 0; q_new <= N - 3; ++q_new) {\n                                // optional: skip if same as old (no effect)\n                                if (m_old == m_new && p_old == p_new && q_old == q_new) continue;\n                                ll delta = 0;\n                                for (int i = 0; i < N; ++i) {\n                                    for (int j = 0; j < N; ++j) {\n                                        ll val = cur_val[i][j];\n                                        bool in_old = (i >= p_old && i < p_old + 3 && j >= q_old && j < q_old + 3);\n                                        bool in_new = (i >= p_new && i < p_new + 3 && j >= q_new && j < q_new + 3);\n                                        if (in_old) {\n                                            ll v_old = stamps[m_old][i - p_old][j - q_old];\n                                            val = val - v_old;\n                                            if (val < 0) val += MOD;\n                                        }\n                                        if (in_new) {\n                                            ll v_new = stamps[m_new][i - p_new][j - q_new];\n                                            val = val + v_new;\n                                            if (val >= MOD) val -= MOD;\n                                        }\n                                        delta += val - cur_val[i][j];\n                                    }\n                                }\n                                if (delta > best_delta) {\n                                    best_delta = delta;\n                                    best_type = 3;\n                                    best_idx = (int)idx_old;\n                                    best_m2 = m_new; best_p2 = p_new; best_q2 = q_new;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            if (best_delta <= 0) break;\n\n            // apply the best move\n            if (best_type == 1) { // add\n                ll delta_apply = 0;\n                for (int di = 0; di < 3; ++di)\n                    for (int dj = 0; dj < 3; ++dj) {\n                        int i = best_p + di, j = best_q + dj;\n                        ll v = stamps[best_m][di][dj];\n                        ll nx = cur_val[i][j] + v;\n                        if (nx >= MOD) nx -= MOD;\n                        delta_apply += nx - cur_val[i][j];\n                        cur_val[i][j] = nx;\n                    }\n                score += best_delta;\n                ops.emplace_back(best_m, best_p, best_q);\n            } else if (best_type == 2) { // remove\n                const Op& op = ops[best_idx];\n                ll delta_apply = 0;\n                int m = op.m, p = op.p, q = op.q;\n                for (int di = 0; di < 3; ++di)\n                    for (int dj = 0; dj < 3; ++dj) {\n                        int i = p + di, j = q + dj;\n                        ll v = stamps[m][di][dj];\n                        ll nx = cur_val[i][j] - v;\n                        if (nx < 0) nx += MOD;\n                        delta_apply += nx - cur_val[i][j];\n                        cur_val[i][j] = nx;\n                    }\n                score += best_delta;\n                ops.erase(ops.begin() + best_idx);\n            } else { // swap\n                const Op& op_old = ops[best_idx];\n                ll delta_apply = 0;\n                int m_old = op_old.m, p_old = op_old.p, q_old = op_old.q;\n                int m_new = best_m2, p_new = best_p2, q_new = best_q2;\n                for (int i = 0; i < N; ++i) {\n                    for (int j = 0; j < N; ++j) {\n                        ll val = cur_val[i][j];\n                        bool in_old = (i >= p_old && i < p_old + 3 && j >= q_old && j < q_old + 3);\n                        bool in_new = (i >= p_new && i < p_new + 3 && j >= q_new && j < q_new + 3);\n                        if (in_old) {\n                            ll v_old = stamps[m_old][i - p_old][j - q_old];\n                            val = val - v_old;\n                            if (val < 0) val += MOD;\n                        }\n                        if (in_new) {\n                            ll v_new = stamps[m_new][i - p_new][j - q_new];\n                            val = val + v_new;\n                            if (val >= MOD) val -= MOD;\n                        }\n                        delta_apply += val - cur_val[i][j];\n                        cur_val[i][j] = val;\n                    }\n                }\n                score += best_delta;\n                ops[best_idx] = Op(m_new, p_new, q_new);\n            }\n        }\n\n        if (score > best_score) {\n            best_score = score;\n            best_ops = ops;\n        }\n    }\n\n    cout << best_ops.size() << '\\n';\n    for (const Op& op : best_ops) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_TURNS = 10000;\nconst int DX[4] = {0, 0, -1, 1};\nconst int DY[4] = {-1, 1, 0, 0};\nconst char DIR_CHAR[4] = {'L', 'R', 'U', 'D'};\n\nstruct Pos {\n    int r, c;\n    bool operator==(const Pos& other) const { return r == other.r && c == other.c; }\n    bool operator<(const Pos& other) const {\n        if (r != other.r) return r < other.r;\n        return c < other.c;\n    }\n};\n\nint N;\nvector<vector<int>> A;\nint grid[5][5];\nint next_needed[5];\nint next_arrival[5];\nbool crane_holding = false;\nint held_id = -1;\nint crane_r = 0, crane_c = 0;\nlong long dispatched_count = 0;\nbool done = false;\n\nbool inside(int r, int c) {\n    return r >= 0 && r < N && c >= 0 && c < N;\n}\n\nchar move_step(int& cr, int& cc, int tr, int tc) {\n    if (cr < tr) { ++cr; return 'D'; }\n    else if (cr > tr) { --cr; return 'U'; }\n    else if (cc < tc) { ++cc; return 'R'; }\n    else if (cc > tc) { --cc; return 'L'; }\n    else return '.';\n}\n\n// Find an empty cell suitable for storage (columns 1..N-2, or column 0 if arrivals done for that row)\nPos find_empty_storage_cell() {\n    for (int r = 0; r < N; ++r) {\n        for (int c = 1; c <= N-2; ++c) {\n            if (grid[r][c] == -1) return {r, c};\n        }\n        if (next_arrival[r] == N && grid[r][0] == -1) return {r, 0};\n    }\n    // fallback (should not happen)\n    return {0, 0};\n}\n\n// Find a cell containing the specific container id (search everywhere except dispatch gates)\nPos find_container(int val) {\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            if (c == N-1) continue; // avoid dispatch gates\n            if (grid[r][c] == val) return {r, c};\n        }\n    }\n    return {-1, -1}; // not found\n}\n\n// Choose a target for pickup when not holding.\n// Sets globals: pickup_target, pickup_from_gate, pickup_row/pickup_id.\n// Returns true if a target was found.\nbool choose_pickup_target() {\n    // 1. Gate with needed container    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] != -1) {\n            int val = grid[i][0];\n            if (val == next_needed[i]) {\n                pickup_target = {i, 0};\n                pickup_from_gate = true;\n                pickup_row = i;\n                return true;\n            }\n        }\n    }\n    // 2. Gate with any container\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] != -1) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    // 3. Needed container in storage (any column except dispatch gate)\n    for (int i = 0; i < N; ++i) {\n        int need = next_needed[i];\n        if (need < i * N + N) { // still needed\n            Pos p = find_container(need);\n            if (p.r != -1) {\n                pickup_target = p;\n                pickup_from_gate = false;\n                pickup_id = need;\n                return true;\n            }\n        }\n    }\n    // 4. Gate with pending arrivals (wait for container to appear)\n    for (int i = 0; i < N; ++i) {\n        if (next_arrival[i] < N) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    return false;\n}\n\n// Release target computation after picking up\nPos pickup_target;\nbool pickup_from_gate;\nint pickup_row; // valid if pickup_from_gate\nint pickup_id;  // valid if !pickup_from_gate\nPos release_target;\n\nvoid compute_release_target_after_pickup() {\n    if (pickup_from_gate) {\n        int val = grid[pickup_target.r][pickup_target.c]; // still present before pick\n        if (val == next_needed[pickup_row]) {\n            release_target = {pickup_row, N-1};\n        } else {\n            release_target = find_empty_storage_cell();\n        }\n    } else {\n        // picked up from storage, it's a needed container\n        int row = pickup_id / N;\n        release_target = {row, N-1};\n    }\n}\n\nvoid process_arrivals() {\n    for (int i = 0; i < N; ++i) {\n        if (next_arrival[i] >= N) continue;\n        if (grid[i][0] == -1 && !(crane_holding && crane_r == i && crane_c == 0)) {\n            int container = A[i][next_arrival[i]];\n            grid[i][0] = container;\n            ++next_arrival[i];\n        }\n    }\n}\n\nvoid process_dispatch() {\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][4] != -1) {\n            grid[i][4] = -1; // dispatched and removed\n            // dispatched_count already incremented when we released at dispatch gate\n        }\n    }\n}\n\nchar decide_action() {\n    if (done) return '.';\n    if (phase == IDLE) {\n        if (crane_holding) {\n            return '.'; // should not happen\n        }\n        if (!choose_pickup_target()) {\n            done = true;\n            return '.';\n        }\n        phase = MOVING_TO_PICKUP;\n        // fall through    }\n    if (phase == MOVING_TO_PICKUP) {\n        char ch = move_step(crane_r, crane_c, pickup_target.r, pickup_target.c);\n        if (crane_r == pickup_target.r && crane_c == pickup_target.c) {\n            phase = AT_PICKUP;\n        }\n        return ch;\n    }\n    if (phase == AT_PICKUP) {\n        if (!crane_holding && grid[crane_r][crane_c] != -1) {\n            // we will pick up\n            // compute release target now\n            compute_release_target_after_pickup();\n            phase = MOVING_TO_RELEASE;\n            return 'P';\n        } else {\n            return '.';\n        }\n    }\n    if (phase == MOVING_TO_RELEASE) {\n        char ch = move_step(crane_r, crane_c, release_target.r, release_target.c);\n        if (crane_r == release_target.r && crane_c == release_target.c) {\n            phase = AT_RELEASE;\n        }\n        return ch;\n    }\n    if (phase == AT_RELEASE) {\n        if (crane_holding) {\n            phase = IDLE;\n            return 'Q';\n        } else {\n            return '.';\n        }\n    }\n    return '.';\n}\n\nvoid apply_action(char ch) {\n    if (ch == '.') return;\n    if (ch == 'U') { /* already moved in move_step */ }\n    else if (ch == 'D') { /* moved */ }\n    else if (ch == 'L') { /* moved */ }\n    else if (ch == 'R') { /* moved */ }\n    else if (ch == 'P') {\n        // pick up\n        assert(!crane_holding);\n        assert(grid[crane_r][crane_c] != -1);\n        held_id = grid[crane_r][crane_c];\n        crane_holding = true;\n        grid[crane_r][crane_c] = -1;\n        // nothing else to update\n    } else if (ch == 'Q') {\n        // release\n        assert(crane_holding);\n        assert(grid[crane_r][crane_c] == -1);\n        grid[crane_r][crane_c] = held_id;\n        if (crane_c == N-1) { // dispatch gate\n            int row = crane_r;\n            ++next_needed[row];\n            ++dispatched_count;\n        } else {\n            // storage cell, nothing else        }\n        crane_holding = false;\n        held_id = -1;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> N;\n    A.assign(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    }\n    // init\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = -1;\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        next_needed[i] = i * N;\n        next_arrival[i] = 0;\n    }\n    crane_r = 0; crane_c = 0;\n    crane_holding = false;\n    held_id = -1;\n    dispatched_count = 0;\n    done = false;\n    phase = IDLE;\n\n    string actions_large;\n    int turn = 0;\n    while (!turn >= MAX_TURNS && !done) {\n        process_arrivals();\n        char ch = decide_action();\n        actions_large += ch;\n        apply_action(ch);\n        process_dispatch();\n        ++turn;\n        if (dispatched_count == N * N) done = true;\n    }\n    // output\n    cout << actions_large << \"\\n\";\n    string small = \"B\";\n    if ((int)actions_large.size() > 1) {\n        small += string(actions_large.size() - 1, '.');\n    } else {\n        small += \".\"; // ensure at least length 1\n    }\n    for (int i = 1; i < N; ++i) {\n        cout << small << \"\\n\";\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int r, c;\n    int amt; // >0 for source, <0 for target (store as positive need)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    ios::cin.tie(nullptr);\n    vector<string> ops;\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    }\n\n    vector<Cell> sources, targets;\n    for(int i=0;i<N;i++) {\n        for(int j=0;j<N;j++) {\n            int val = h[i][j];\n            if(val > 0) {\n                sources.push_back({i, j, val});\n            } else if(val < 0) {\n                targets.push_back({i, j, -val});\n            }\n        }\n    }\n\n    struct Transfer {\n        int sr, sc, tr, tc;\n        int amt;\n    };\n    vector<Transfer> transfers;\n\n    while(true) {\n        int best_i = -1, best_j = -1;\n        int best_dist = INT_MAX;\n        for(size_t i=0;i<sources.size();++i) {\n            if(sources[i].amt <= 0) continue;\n            for(size_t j=0;j<targets.size();++j) {\n                if(targets[j].need <= 0) continue;\n                int dist = abs(sources[i].r - targets[j].r) + abs(sources[i].c - targets[j].c);\n                if(dist < best_dist) {\n                    best_dist = dist;\n                    best_i = (int)i;\n                    best_j = (int)j;\n                }\n            }\n        }\n        if(best_i==-1) break;\n        int take = min(sources[best_i].amt, targets[best_j].need);\n        transfers.push_back({sources[best_i].r, sources[best_i].c,\n                             targets[best_j].r, targets[best_j].c, take});\n        sources[best_i].amt -= take;\n        targets[best_j].need -= take;\n    }\n\n    auto add_move = [&](int &r, int &c, int tr, int tc) {\n        while(r < tr) { ops.push_back(\"D\"); ++r; }\n        while(r > tr) { ops.push_back(\"U\"); --r; }\n        while(c < tc) { ops.push_back(\"R\"); ++c; }\n        while(c > tc) { ops.push_back(\"L\"); --c; }\n        r = tr; c = tc;\n    };\n\n    int cr = 0, cc = 0;\n    long long load = 0; // not strictly needed but kept for safety\n    for(const Transfer &t : transfers) {\n        // depot -> source (empty)\n        add_move(cr, cc, t.sr, t.sc);\n        // load\n        ops.push_back(\"+\" + to_string(t.amt));\n        load += t.amt;\n        // source -> target (loaded)\n        add_move(t.sr, t.sc, t.tr, t.tc);\n        // unload\n        ops.push_back(\"-\" + to_string(t.amt));\n        load -= t.amt;\n        // target -> depot (empty)\n        add_move(t.tr, t.tc, 0, 0);\n        cr = 0; cc = 0;\n        // load should be zero now\n        assert(load == 0);\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    int N, M, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> X(seed_count, vector<int>(M));\n    for (int i = 0; i < seed_count; ++i) {\n        for (int j = 0; j < M; ++j) {\n            cin >> X[i][j];\n        }\n    }\n\n    // Order of cells: higher degree first (inner -> edges -> corners)\n    struct Cell { int deg, i, j; };\n    vector<Cell> cells;\n    cells.reserve(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int deg = (i > 0) + (i < N - 1) + (j > 0) + (j < N - 1);\n            cells.push_back({deg, i, j});\n        }\n    }\n    sort(cells.begin(), cells.end(), [](const Cell& a, const Cell& b) {\n        return a.deg > b.deg;\n    });\n    vector<pair<int,int>> pos_order;\n    pos_order.reserve(N * N);\n    for (const auto& c : cells) {\n        pos_order.emplace_back(c.i, c.j);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        // Max value per attribute\n        vector<int> max_attr(M, 0);\n        for (int id = 0; id < seed_count; ++id) {\n            for (int l = 0; l < M; ++l) {\n                if (X[id][l] > max_attr[l]) max_attr[l] = X[id][l];\n            }\n        }\n\n        // Score: (#attributes at max) * 10000 + sum of values\n        using SeedScore = pair<long long, int>;\n        vector<SeedScore> scores;\n        scores.reserve(seed_count);\n        for (int id = 0; id < seed_count; ++id) {\n            int w = 0;\n            long long sum = 0;\n            for (int l = 0; l < M; ++l) {\n                sum += X[id][l];\n                if (X[id][l] == max_attr[l]) ++w;\n            }\n            long long score = (long long)w * 10000LL + sum;\n            scores.emplace_back(score, id);\n        }\n        sort(scores.begin(), scores.end(),\n             [](const SeedScore& a, const SeedScore& b) { return a.first > b.first; });\n\n        // Assign top N^2 seeds to cells in pos_order\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        for (int idx = 0; idx < N * N; ++idx) {\n            int sid = scores[idx].second;\n            int i = pos_order[idx].first;\n            int j = pos_order[idx].second;\n            A[i][j] = sid;\n        }\n\n        // Output placement\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << A[i][j];\n                if (j + 1 < N) cout << ' ';\n                else cout << '\\n';\n            }\n        }\n        cout.flush();\n\n        // Read next generation\n        for (int id = 0; id < seed_count; ++id) {\n            for (int l = 0; l < M; ++l) {\n                if (!(cin >> X[id][l])) return 0;\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\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    // Use a simple 2-vertex tree: root (0) and one leaf (1) with edge length 1.\n    const int Vp = 2;\n    cout << Vp << '\\n';\n    cout << \"0 1\" << '\\n';   // parent of vertex 1 is 0, length = 1\n    cout << \"0 0\" << '\\n';   // initial root position (top-left corner)\n    \n    // Direction vectors: 0=right,1=down,2=left,3=up\n    const int DX[4] = {0, 1, 0, -1};\n    const int DY[4] = {1, 0, -1, 0};\n    const char DIR_CHAR[4] = {'R', 'D', 'L', 'U'};\n    \n    // Current state of takoyaki on the grid (modifiable)\n    vector<vector<int>> cur(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cur[i][j] = s[i][j] - '0';\n    \n    // Target grid\n    vector<vector<int>> target(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            target[i][j] = t[i][j] - '0';\n    \n    int rootX = 0, rootY = 0;\n    int leafDir = 0; // initially edge extends to the right\n    bool holding = false;\n    \n    // Number of turns: choose a moderate value (well below 1e5)\n    const int TURN = 5000;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distMove(0, 3); // 0..3 for directions\n    uniform_int_distribution<int> distRot(0, 2);  // 0: none, 1: left, 2: right\n    \n    for (int turn = 0; turn < TURN; ++turn) {\n        string op(4, '.'); // format: [move][rot][root action][leaf action]\n        \n        // 1. Move the whole arm\n        int d = distMove(rng);\n        int nx = rootX + DX[d];\n        int ny = rootY + DY[d];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N) {\n            rootX = nx;\n            rootY = ny;\n            op[0] = DIR_CHAR[d];\n        } // else op[0] stays '.'\n        \n        // 2. Rotate the subtree rooted at vertex 1 (the leaf)\n        int r = distRot(rng);\n        if (r == 1) { // rotate left (counterclockwise)\n            op[1] = 'L';\n            leafDir = (leafDir + 3) & 3;\n        } else if (r == 2) { // rotate right (clockwise)\n            op[1] = 'R';\n            leafDir = (leafDir + 1) & 3;\n        } // else op[1] stays '.'\n        \n        // 3. Action at fingertips (only vertex 1 is a leaf)\n        // Root (vertex 0) is not a leaf -> op[2] stays '.'\n        int leafX = rootX + DX[leafDir];\n        int leafY = rootY + DY[leafDir];\n        bool changed = false;\n        if (leafX >= 0 && leafX < N && leafY >= 0 && leafY < N) {\n            if (!holding && cur[leafX][leafY] == 1 && target[leafX][leafY] == 0) {\n                // Pick up a takoyaki that is not needed here\n                cur[leafX][leafY] = 0;\n                holding = true;\n                changed = true;\n            } else if (holding && cur[leafX][leafY] == 0 && target[leafX][leafY] == 1) {\n                // Drop a takoyaki onto a needed empty spot\n                cur[leafX][leafY] = 1;\n                holding = false;\n                changed = true;\n            }\n        }\n        op[3] = changed ? 'P' : '.';\n                cout << op << '\\n';\n    }\n    \n    return 0;\n}","ahc039":"#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    const int MAXC = 100000;\n    vector<tuple<int, int, int>> pts;\n    pts.reserve(2 * N);\n    for (int i = 0; i < 2 * N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        int w = (i < N) ? 1 : -1; // +1 for mackerel, -1 for sardine\n        pts.emplace_back(x, y, w);\n    }\n\n    // Build maps: x -> list of (y, weight), y -> list of (x, weight)\n    unordered_map<int, vector<pair<int, int>>> x_to_ys;\n    unordered_map<int, vector<pair<int, int>>> y_to_xs;\n    for (auto &[x, y, w] : pts) {\n        x_to_ys[x].emplace_back(y, w);\n        y_to_xs[y].emplace_back(x, w);\n    }\n    for (auto &kv : x_to_ys) sort(kv.second.begin(), kv.second.end());\n    for (auto &kv : y_to_xs) sort(kv.second.begin(), kv.second.end());\n\n    // Helper to sum weights of points with fixed x and y in [y1, y2] (inclusive)\n    auto sumVert = [&](int x, int y1, int y2) -> int {\n        auto it = x_to_ys.find(x);\n        if (it == x_to_ys.end()) return 0;\n        const auto &vec = it->second;\n        int s = 0;\n        for (auto [y, w] : vec) {\n            if (y < y1) continue;\n            if (y > y2) break;\n            s += w;\n        }\n        return s;\n    };\n    // Helper to sum weights of points with fixed y and x in [x1, x2] (inclusive)\n    auto sumHoriz = [&](int y, int x1, int x2) -> int {\n        auto it = y_to_xs.find(y);\n        if (it == y_to_xs.end()) return 0;\n        const auto &vec = it->second;\n        int s = 0;\n        for (auto [x, w] : vec) {\n            if (x < x1) continue;\n            if (x > x2) break;\n            s += w;\n        }\n        return s;\n    };\n\n    long long bestScore = LLONG_MIN;\n    int bestX1 = 0, bestX2 = 0, bestY1 = 0, bestY2 = 0;\n\n    // Try each mackerel as a seed point\n    for (int i = 0; i < N; ++i) {\n        int mx = get<0>(pts[i]);\n        int my = get<1>(pts[i]);\n        int x1 = mx, x2 = mx, y1 = my, y2 = my;\n        long long score = 1; // weight of the seed mackerel\n\n        // ----- Expansion phase -----        const int maxExpansions = 200;\n        int expansions = 0;\n        while (expansions < maxExpansions) {\n            int width = x2 - x1;\n            int height = y2 - y1;\n            int remaining = 200000 - (width + height); // max extra width+height allowed\n            if (remaining <= 0) break;\n\n            int bestGain = 0, bestDir = -1;\n            // left\n            if (x1 > 0) {\n                int g = sumVert(x1 - 1, y1, y2);\n                if (g > bestGain) { bestGain = g; bestDir = 0; }\n            }\n            // right\n            if (x2 < MAXC) {\n                int g = sumVert(x2 + 1, y1, y2);\n                if (g > bestGain) { bestGain = g; bestDir = 1; }\n            }\n            // down\n            if (y1 > 0) {\n                int g = sumHoriz(y1 - 1, x1, x2);\n                if (g > bestGain) { bestGain = g; bestDir = 2; }\n            }\n            // up\n            if (y2 < MAXC) {\n                int g = sumHoriz(y2 + 1, x1, x2);\n                if (g > bestGain) { bestGain = g; bestDir = 3; }\n            }\n            if (bestGain <= 0) break; // no profitable side\n\n            // apply expansion\n            switch (bestDir) {\n                case 0: x1--; break;\n                case 1: x2++; break;\n                case 2: y1--; break;\n                case 3: y2++; break;\n            }\n            score += bestGain;\n            ++expansions;\n        }\n\n        // ----- Shrinking phase -----\n        while (true) {\n            int width = x2 - x1;\n            int height = y2 - y1;\n            int bestGain = 0; // we look for the most negative gain\n            int bestDir = -1;\n\n            if (width >= 2) {\n                int gl = sumVert(x1, y1, y2);\n                int gr = sumVert(x2, y1, y2);\n                if (gl < bestGain) { bestGain = gl; bestDir = 0; }\n                if (gr < bestGain) { bestGain = gr; bestDir = 1; }\n            }\n            if (height >= 2) {\n                int gd = sumHoriz(y1, x1, x2);\n                int gu = sumHoriz(y2, x1, x2);\n                if (gd < bestGain) { bestGain = gd; bestDir = 2; }\n                if (gu < bestGain) { bestGain = gu; bestDir = 3; }\n            }\n            if (bestGain >= 0) break; // no side whose removal improves score\n\n            // remove the chosen side\n            switch (bestDir) {\n                case 0: x1++; score -= bestGain; break;\n                case 1: x2--; score -= bestGain; break;\n                case 2: y1++; score -= bestGain; break;\n                case 3: y2--; score -= bestGain; break;\n            }\n        }\n\n        // Ensure at least 1x1 rectangle (avoid zero-area)\n        if (x1 == x2) {\n            if (x2 < MAXC) ++x2;\n            else if (x1 > 0) --x1;\n        }\n        if (y1 == y2) {\n            if (y2 < MAXC) ++y2;\n            else if (y1 > 0) --y1;\n        }\n\n        if (score > bestScore) {\n            bestScore = score;\n            bestX1 = x1; bestX2 = x2; bestY1 = y1; bestY2 = y2;\n        }\n    }\n\n    // Output the rectangle (counter\u2011clockwise)\n    cout << 4 << '\\n';\n    cout << bestX1 << ' ' << bestY1 << '\\n';\n    cout << bestX2 << ' ' << bestY1 << '\\n';\n    cout << bestX2 << ' ' << bestY2 << '\\n';\n    cout << bestX1 << ' ' << bestY2 << '\\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, sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    // Read the observed (noisy) widths and heights; they are not needed for the trivial strategy.\n    vector<pair<int,int>> obs(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> obs[i].first >> obs[i].second;\n    }\n\n    // Repeat T times: output an empty placement (n = 0) and read the dummy measurement.\n    for (int t = 0; t < T; ++t) {\n        cout << 0 << '\\n';\n        cout.flush();\n\n        int Wp, Hp;\n        if (!(cin >> Wp >> Hp)) break;   // end if input fails (should not happen)\n        // The measured values are ignored; we simply proceed to the next turn.\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    // read edges\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n    }\n    // read coordinates (unused)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    // output all roots: parent = -1\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << -1;\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 Move {\n        char d;\n        int p;\n    };\n    vector<Move> moves;\n    moves.reserve(4 * N * N);   // enough space\n\n    auto shiftColUp = [&](int j) {\n        for (int i = 0; i + 1 < N; ++i) board[i][j] = board[i + 1][j];\n        board[N - 1][j] = '.';\n    };\n    auto shiftColDown = [&](int j) {\n        for (int i = N - 1; i > 0; --i) board[i][j] = board[i - 1][j];\n        board[0][j] = '.';\n    };\n    auto shiftRowLeft = [&](int i) {\n        for (int j = 0; j + 1 < N; ++j) board[i][j] = board[i][j + 1];\n        board[i][N - 1] = '.';\n    };\n    auto shiftRowRight = [&](int i) {\n        for (int j = N - 1; j > 0; --j) board[i][j] = board[i][j - 1];\n        board[i][0] = '.';\n    };\n\n    while (true) {\n        int si = -1, sj = -1;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (board[i][j] == 'x') {\n                    si = i; sj = j;\n                    break;\n                }\n            }\n            if (si != -1) break;\n        }\n        if (si == -1) break;   // no Oni left\n\n        int i = si, j = sj;\n        bool up = true, down = true, left = true, right = true;\n        for (int ii = 0; ii < i; ++ii)\n            if (board[ii][j] == 'o') { up = false; break; }\n        for (int ii = i + 1; ii < N; ++ii)\n            if (board[ii][j] == 'o') { down = false; break; }\n        for (int jj = 0; jj < j; ++jj)\n            if (board[i][jj] == 'o') { left = false; break; }\n        for (int jj = j + 1; jj < N; ++jj)\n            if (board[i][jj] == 'o') { right = false; break; }\n\n        int dir; // 0:U,1:D,2:L,3:R        if (up) dir = 0;\n        else if (down) dir = 1;\n        else if (left) dir = 2;\n        else dir = 3;\n\n        if (dir == 0) { // U column j upward\n            for (int k = 0; k <= i; ++k) {\n                moves.push_back({'U', j});\n                shiftColUp(j);\n            }\n        } else if (dir == 1) { // D column j downward\n            for (int k = 0; k < N - i; ++k) {\n                moves.push_back({'D', j});\n                shiftColDown(j);\n            }\n        } else if (dir == 2) { // L row i left\n            for (int k = 0; k <= j; ++k) {\n                moves.push_back({'L', i});\n                shiftRowLeft(i);\n            }\n        } else { // R row i right\n            for (int k = 0; k < N - j; ++k) {\n                moves.push_back({'R', i});\n                shiftRowRight(i);\n            }\n        }\n    }\n\n    // safety check (can be removed in final version)\n    assert((int)moves.size() <= 4 * N * N);\n\n    for (auto &mv : moves)\n        cout << mv.d << ' ' << mv.p << '\\n';\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nll simulate(const vector<int>& a, const vector<int>& b, const vector<int>& target, vector<int>& cnt) {\n    int N = (int)a.size();\n    int L = (int)target.size();\n    cnt.assign(N, 0);\n    int cur = 0;\n    cnt[cur] = 1; // week 1    for (int week = 2; week <= L; ++week) {\n        int nx = (cnt[cur] & 1) ? a[cur] : b[cur];\n        cur = nx;\n        ++cnt[cur];\n    }\n    ll err = 0;\n    for (int i = 0; i < N; ++i) {\n        ll diff = (ll)cnt[i] - (ll)target[i];\n        if (diff < 0) diff = -diff;\n        err += diff;\n    }\n    return err;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, L;\n    cin >> N >> L;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    // initial solution: round-robin\n    vector<int> a(N), b(N);\n    for (int i = 0; i < N; ++i) {\n        a[i] = b[i] = (i + 1) % N;\n    }\n\n    vector<int> cnt(N);\n    ll cur_err = simulate(a, b, T, cnt);\n    ll best_err = cur_err;\n    vector<int> best_a = a, best_b = b;\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_node(0, N - 1);\n    uniform_int_distribution<int> dist_choice(0, 1); // 0 -> a, 1 -> b    uniform_real_distribution<double> dist_real(0.0, 1.0);\n\n    auto guided_move = [&](const vector<int>& cnt_cur, int& i, int& which, int& j) {\n        vector<int> deficit(N);\n        int total_over = 0, total_under = 0;\n        for (int k = 0; k < N; ++k) {\n            int d = T[k] - cnt_cur[k];\n            deficit[k] = d;\n            if (d > 0) total_under += d;\n            else if (d < 0) total_over -= d;\n        }\n        if (total_over == 0) return false; // fallback to random\n        // pick over node i with probability proportional to -deficit[i]\n        int r = uniform_int_distribution<int>(0, total_over - 1)(rng);\n        int acc = 0;\n        i = 0;\n        while (i < N) {\n            int d = -deficit[i];\n            if (d > 0) {\n                if (r < acc + d) break;\n                acc += d;\n            }\n            ++i;\n        }\n        // pick under node j with probability proportional to deficit[j]\n        int r2 = uniform_int_distribution<int>(0, total_under - 1)(rng);\n        int acc2 = 0;\n        j = 0;\n        while (j < N) {\n            int d = deficit[j];\n            if (d > 0) {\n                if (r2 < acc2 + d) break;\n                acc2 += d;\n            }\n            ++j;\n        }\n        which = dist_choice(rng); // random choose a or b to modify\n        return true;\n    };\n\n    const int MAX_ITER = 500;\n    const double COOLING = 0.998;\n\n    for (int restart = 0; restart < 3; ++restart) {\n        // reset to round-robin for each restart (optional)\n        for (int i = 0; i < N; ++i) a[i] = b[i] = (i + 1) % N;\n        cur_err = simulate(a, b, T, cnt);\n        if (cur_err < best_err) {\n            best_err = cur_err;\n            best_a = a;\n            best_b = b;\n        }\n        double Ttemp = (double)cur_err; // temperature\n        for (int it = 0; it < MAX_ITER; ++it) {\n            int i, which, j;\n            bool use_guided = guided_move(cnt, i, which, j);\n            if (!use_guided) {\n                i = dist_node(rng);\n                which = dist_choice(rng);\n                j = dist_node(rng);\n            }\n            // apply move\n            vector<int> a2 = a, b2 = b;\n            if (which == 0) a2[i] = j;\n            else b2[i] = j;\n            // simulate move\n            vector<int> cnt2(N);\n            ll err2 = simulate(a2, b2, T, cnt2);\n            bool accept = false;\n            if (err2 < cur_err) accept = true;\n            else {\n                double prob = exp((cur_err - err2) / Ttemp);\n                if (dist_real(rng) < prob) accept = true;\n            }\n            if (accept) {\n                a = a2;\n                b = b2;\n                cur_err = err2;\n                cnt = cnt2;\n                if (err2 < best_err) {\n                    best_err = err2;\n                    best_a = a;\n                    best_b = b;\n                }\n            }\n            Ttemp *= COOLING;\n            if (Ttemp < 1e-5) break;\n        }\n    }\n\n    // output best solution    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    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        // centre of each rectangle (integer division)\n    vector<int> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        cx[i] = (lx[i] + rx[i]) / 2;\n        cy[i] = (ly[i] + ry[i]) / 2;\n    }\n    \n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](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 k = 0; k < M; ++k) {\n        int sz = G[k];\n        vector<int> grp;\n        grp.reserve(sz);\n        for (int i = 0; i < sz; ++i) grp.push_back(idx[pos++]);\n        groups.push_back(move(grp));\n    }\n    \n    // answer edges per group\n    vector<vector<pair<int,int>>> ansEdges(M);\n    ansEdges.reserve(M);\n    int usedQueries = 0;\n    for (int k = 0; k < M; ++k) {\n        const auto& g = groups[k];\n        int sz = (int)g.size();\n        for (int i = 0; i + 1 < sz; i += 2) {\n            if (i + 2 < sz) {\n                // query a triple\n                int a = g[i];\n                int b = g[i+1];\n                int c = g[i+2];\n                cout << \"? 3 \" << a << ' ' << b << ' ' << c << '\\n';\n                cout.flush();\n                ++usedQueries;\n                int u1, v1, u2, v2;\n                cin >> u1 >> v1;\n                cin >> u2 >> v2;\n                ansEdges[k].emplace_back(u1, v1);\n                ansEdges[k].emplace_back(u2, v2);\n            } else {\n                // only a pair left, no query needed\n                ansEdges[k].emplace_back(g[i], g[i+1]);\n            }\n        }\n    }\n    \n    // output the answer\n    cout << \"!\\n\";\n    cout.flush();\n    for (int k = 0; k < M; ++k) {\n        // cities of the group\n        for (size_t i = 0; i < groups[k].size(); ++i) {\n            if (i) cout << ' ';\n            cout << groups[k][i];\n        }\n        cout << '\\n';\n        // edges of the group\n        for (auto &e : ansEdges[k]) {\n            cout << e.first << ' ' << e.second << '\\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>> pts(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> pts[i].first >> pts[i].second;\n    }\n    \n    for (int k = 0; k + 1 < M; ++k) {\n        int ci = pts[k].first, cj = pts[k].second;\n        int ni = pts[k+1].first, nj = pts[k+1].second;\n        \n        while (ci < ni) { cout << \"M D\\n\"; ++ci; }\n        while (ci > ni) { cout << \"M U\\n\"; --ci; }\n        while (cj < nj) { cout << \"M R\\n\"; ++cj; }\n        while (cj > nj) { cout << \"M L\\n\"; --cj; }\n    }\n    \n    return 0;\n}"},"4":{"ahc001":"#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<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    const int W = 10000, H = 10000;\n    size_t totalCells = static_cast<size_t>(W) * H;\n    vector<uint8_t> occ(totalCells, 0); // 0 = free, else company id+1\n    vector<int> a(n), b(n), c(n), d(n);\n    vector<long long> area(n, 1);\n    for (int i = 0; i < n; ++i) {\n        a[i] = x[i];\n        b[i] = y[i];\n        c[i] = x[i] + 1;\n        d[i] = y[i] + 1;\n        occ[static_cast<size_t>(b[i]) * W + a[i]] = static_cast<uint8_t>(i + 1);\n    }\n\n    auto try_expand = [&](int i) -> bool {\n        if (area[i] >= r[i]) return false;\n        long long deficit = r[i] - area[i];\n        int best_dir = -1; // 0:left,1:right,2:down,3:up\n        int best_strip = 0;\n\n        int width  = c[i] - a[i];\n        int height = d[i] - b[i];\n\n        // left\n        if (a[i] > 0) {\n            int strip = height; // area added by expanding left one column\n            if (strip <= deficit) {\n                int xcol = a[i] - 1;\n                bool free = true;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    if (occ[static_cast<size_t>(yc) * W + xcol]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 0;\n                    best_strip = strip;\n                }\n            }\n        }\n        // right\n        if (c[i] < W) {\n            int strip = height;\n            if (strip <= deficit) {\n                int xcol = c[i];\n                bool free = true;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    if (occ[static_cast<size_t>(yc) * W + xcol]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 1;\n                    best_strip = strip;\n                }\n            }\n        }\n        // down\n        if (b[i] > 0) {\n            int strip = width;\n            if (strip <= deficit) {\n                int yrow = b[i] - 1;\n                bool free = true;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    if (occ[static_cast<size_t>(yrow) * W + xc]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 2;\n                    best_strip = strip;\n                }\n            }\n        }\n        // up\n        if (d[i] < H) {\n            int strip = width;\n            if (strip <= deficit) {\n                int yrow = d[i];\n                bool free = true;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    if (occ[static_cast<size_t>(yrow) * W + xc]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 3;\n                    best_strip = strip;\n                }\n            }\n        }\n        if (best_dir == -1) return false;\n\n        // perform the expansion\n        switch (best_dir) {\n            case 0: { // left\n                int xcol = a[i] - 1;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    occ[static_cast<size_t>(yc) * W + xcol] = static_cast<uint8_t>(i + 1);\n                }\n                a[i] -= 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 1: { // right\n                int xcol = c[i];\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    occ[static_cast<size_t>(yc) * W + xcol] = static_cast<uint8_t>(i + 1);\n                }\n                c[i] += 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 2: { // down\n                int yrow = b[i] - 1;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    occ[static_cast<size_t>(yrow) * W + xc] = static_cast<uint8_t>(i + 1);\n                }\n                b[i] -= 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 3: { // up\n                int yrow = d[i];\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    occ[static_cast<size_t>(yrow) * W + xc] = static_cast<uint8_t>(i + 1);\n                }\n                d[i] += 1;\n                area[i] += best_strip;\n                break;\n            }\n        }\n        return true;\n    };\n\n    vector<bool> active(n, true);\n    deque<int> q;\n    for (int i = 0; i < n; ++i) {\n        if (area[i] < r[i]) q.push_back(i);\n        else active[i] = false;\n    }\n\n    while (!q.empty()) {\n        int i = q.front();\n        q.pop_front();\n        if (!active[i]) continue;\n        if (area[i] >= r[i]) {\n            active[i] = false;\n            continue;\n        }\n        if (try_expand(i)) {\n            if (area[i] < r[i]) {\n                q.push_back(i);\n            }\n        } else {\n            active[i] = false;\n        }\n    }\n\n    for (int i = 0; i < n; ++i) {\n        cout << a[i] << ' ' << b[i] << ' ' << c[i] << ' ' << d[i] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Result {\n    string path;\n    int score;\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    vector<vector<int>> t(50, vector<int>(50));\n    vector<vector<int>> p(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            cin >> t[i][j];\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            cin >> p[i][j];\n    \n    // number of different tiles (ids are 0 .. M-1)\n    int maxTileId = 0;\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            maxTileId = max(maxTileId, t[i][j]);\n    int M = maxTileId + 1;\n    \n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char dirChar[4] = {'U', 'D', 'L', 'R'};\n    \n    // ----- simulation with a given seed -----\n    auto simulate = [&](int seed) -> Result {\n        vector<vector<bool>> visCell(50, vector<bool>(50, false));\n        vector<bool> visTile(M, false);\n        \n        int ci = si, cj = sj;\n        visCell[ci][cj] = true;\n        int startTile = t[ci][cj];\n        visTile[startTile] = true;\n        \n        string path;\n        int score = p[ci][cj];\n        int visitedTiles = 1;\n        mt19937 rng(seed);\n        \n        while (true) {\n            // ---- collect feasible moves ----\n            vector<int> cand;\n            for (int d = 0; d < 4; ++d) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                if (ni < 0 || ni >= 50 || nj < 0 || nj >= 50) continue;\n                if (visCell[ni][nj]) continue;\n                int tid = t[ni][nj];\n                if (visTile[tid]) continue;          // tile already used\n                cand.push_back(d);\n            }\n            if (cand.empty()) break;\n            \n            // ---- Warnsdorff: choose move with minimal onward degree ----\n            int bestForward = 1e9;\n            vector<int> bestDirs;\n            for (int d : cand) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                int forward = 0;\n                for (int d2 = 0; d2 < 4; ++d2) {\n                    int ni2 = ni + di[d2];\n                    int nj2 = nj + dj[d2];\n                    if (ni2 < 0 || ni2 >= 50 || nj2 < 0 || nj2 >= 50) continue;\n                    if (visCell[ni2][nj2]) continue;\n                    int tid2 = t[ni2][nj2];\n                    if (visTile[tid2]) continue;\n                    ++forward;\n                }\n                if (forward < bestForward) {\n                    bestForward = forward;\n                    bestDirs.clear();\n                    bestDirs.push_back(d);\n                } else if (forward == bestForward) {\n                    bestDirs.push_back(d);\n                }\n            }\n            \n            // ---- tie\u2011break: higher cell value, then random ----\n            int bestP = -1;\n            vector<int> bestDirs2;\n            for (int d : bestDirs) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                if (p[ni][nj] > bestP) {\n                    bestP = p[ni][nj];\n                    bestDirs2.clear();\n                    bestDirs2.push_back(d);\n                } else if (p[ni][nj] == bestP) {\n                    bestDirs2.push_back(d);\n                }\n            }\n            uniform_int_distribution<int> dist(0, (int)bestDirs2.size() - 1);\n            int chosen = bestDirs2[dist(rng)];\n            \n            // ---- apply the move ----\n            ci += di[chosen];\n            cj += dj[chosen];\n            visCell[ci][cj] = true;\n            int tid = t[ci][cj];\n            visTile[tid] = true;\n            ++visitedTiles;\n            path.push_back(dirChar[chosen]);\n            score += p[ci][cj];\n                        // optional early stop when every tile has been used\n            if (visitedTiles == M) break;\n        }\n        return {path, score};\n    };\n    \n    // ----- multiple random restarts -----\n    const int ITER = 50;          // number of trials (adjustable)\n    Result best;\n    best.score = -1;\n    for (int it = 0; it < ITER; ++it) {\n        unsigned seed = chrono::steady_clock::now().time_since_epoch().count() + it * 123457u;\n        Result cur = simulate(seed);\n        if (cur.score > best.score) {\n            best = cur;\n        }\n    }\n    \n    cout << best.path << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;                     // grid size\nconst int HN = N;                     // rows for horizontal edges\nconst int WN = N - 1;                 // columns for horizontal edges\nconst int VN = N - 1;                 // rows for vertical edges\nconst int VM = N;                     // columns for vertical edges\n\nusing EdgeWeight = double;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // ----- estimates of edge lengths -----\n    vector<vector<EdgeWeight>> h(HN, vector<EdgeWeight>(WN, 5000.0)); // horizontal edges\n    vector<vector<EdgeWeight>> v(VN, vector<EdgeWeight>(VM, 5000.0)); // vertical   edges\n\n    const double eta = 0.2;          // learning rate\n    const double MINW = 500.0, MAXW = 15000.0;\n\n    for (int query = 0; query < 1000; ++query) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) break;   // end of input\n\n        // ---------- Dijkstra on current estimates ----------\n        const int V = N * N;\n        const double INF = 1e100;\n        vector<double> dist(V, INF);\n        vector<int> prev(V, -1);\n        using State = pair<double, int>;\n        priority_queue<State, vector<State>, greater<State>> pq;\n\n        auto idx = [&](int i, int j) { return i * N + j; };\n        int s = idx(si, sj);\n        int t = idx(ti, tj);\n        dist[s] = 0.0;\n        pq.emplace(0.0, s);\n\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u] + 1e-12) continue;\n            int ui = u / N, uj = u % N;\n            // up\n            if (ui > 0) {\n                int ni = ui - 1, nj = uj;\n                double w = static_cast<double>(v[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // down\n            if (ui < N - 1) {\n                int ni = ui + 1, nj = uj;\n                double w = static_cast<double>(v[ui][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // left\n            if (uj > 0) {\n                int ni = ui, nj = uj - 1;\n                double w = static_cast<double>(h[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // right\n            if (uj < N - 1) {\n                int ni = ui, nj = uj + 1;\n                double w = static_cast<double>(h[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n        }\n\n        // ---------- reconstruct path ----------\n        vector<int> rev;\n        for (int cur = t; cur != -1; cur = prev[cur]) rev.push_back(cur);\n        reverse(rev.begin(), rev.end());\n\n        string moves;\n        moves.reserve(rev.size() * 2);\n        double predicted = 0.0;\n        int path_len = 0;\n\n        for (size_t i = 1; i < rev.size(); ++i) {\n            int a = rev[i - 1], b = rev[i];\n            int ai = a / N, aj = a % N;\n            int bi = b / N, bj = b % N;\n            char ch;\n            if (ai == bi && aj == bj + 1) { ch = 'L'; predicted += h[ai][bj]; --aj; }\n            else if (ai == bi && aj == bj - 1) { ch = 'R'; predicted += h[ai][aj]; ++aj; }\n            else if (aj == bj && ai == bi + 1) { ch = 'U'; predicted += v[bi][aj]; --ai; }\n            else if (aj == bj && ai == bi - 1) { ch = 'D'; predicted += v[ai][aj]; ++ai; }\n            else { ch = '?'; } // should never happen\n            moves.push_back(ch);\n            ++path_len;\n        }\n\n        cout << moves << '\\n';\n        cout.flush();\n\n        // ---------- read judge feedback ----------\n        int y;\n        if (!(cin >> y)) break;   // defensive\n\n        // ---------- SGD update ----------\n        if (path_len > 0) {\n            double error = static_cast<double>(y) - predicted;\n            double delta = eta * error / static_cast<double>(path_len);\n\n            int ci = si, cj = sj;\n            for (char ch : moves) {\n                if (ch == 'U') {\n                    v[ci - 1][cj] += delta;\n                    if (v[ci - 1][cj] < MINW) v[ci - 1][cj] = MINW;\n                    if (v[ci - 1][cj] > MAXW) v[ci - 1][cj] = MAXW;\n                    --ci;\n                } else if (ch == 'D') {\n                    v[ci][cj] += delta;\n                    if (v[ci][cj] < MINW) v[ci][cj] = MINW;\n                    if (v[ci][cj] > MAXW) v[ci][cj] = MAXW;\n                    ++ci;\n                } else if (ch == 'L') {\n                    h[ci][cj - 1] += delta;\n                    if (h[ci][cj - 1] < MINW) h[ci][cj - 1] = MINW;\n                    if (h[ci][cj - 1] > MAXW) h[ci][cj - 1] = MAXW;\n                    --cj;\n                } else if (ch == 'R') {\n                    h[ci][cj] += delta;\n                    if (h[ci][cj] < MINW) h[ci][cj] = MINW;\n                    if (h[ci][cj] > MAXW) h[ci][cj] = MAXW;\n                    ++cj;\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20; // fixed\n\nstruct CellEntry {\n    int pid;      // placement id    uint8_t off;  // offset within the placement\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    cin >> N >> M; // N is always 20, but read anyway\n    vector<string> strs(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strs[i];\n    }\n\n    // convert strings to integer representation 0-7 for A-H, 8 for '.'\n    vector<string> raw = strs; // keep original for required char lookup\n    vector<vector<int>> a(N, vector<int>(N, 0));\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_val(0, 7); // A-H only for initial matrix\n    int dot_cnt = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            a[i][j] = dist_val(rng);\n        }\n    }\n\n    // placement data\n    vector<int> placement_sid; // placement -> string id    vector<vector<vector<CellEntry>>> cell_entries(N, vector<vector<CellEntry>>(N));\n    vector<int> placement_mismatch; // per placement\n    vector<int> match_cnt_str(M, 0); // number of matching placements per string\n    int satisfied = 0;\n\n    const int dr[2] = {0, 1};\n    const int dc[2] = {1, 0};\n\n    // Build placements and initial mismatch counts\n    for (int sid = 0; sid < M; ++sid) {\n        const string& s = raw[sid];\n        int L = (int)s.size();\n        for (int dir = 0; dir < 2; ++dir) {\n            for (int sr = 0; sr < N; ++sr) {\n                for (int sc = 0; sc < N; ++sc) {\n                    int pid = (int)placement_sid.size();\n                    placement_sid.push_back(sid);\n                    int mis = 0;\n                    for (int k = 0; k < L; ++k) {\n                        int r = (sr + dr[dir] * k) % N;\n                        int c = (sc + dc[dir] * k) % N;\n                        cell_entries[r][c].push_back({pid, (uint8_t)k});\n                        int required = raw[sid][k] - 'A';\n                        if (a[r][c] != required) ++mis;\n                    }\n                    placement_mismatch.push_back(mis);\n                    if (mis == 0) {\n                        ++match_cnt_str[sid];\n                    }\n                }\n            }\n        }\n    }\n    for (int sid = 0; sid < M; ++sid) {\n        if (match_cnt_str[sid] > 0) ++satisfied;\n    }\n\n    // Helper lambdas for evaluating and applying a cell change\n    auto evaluate_delta = [&](int r, int c, int new_val) -> int {\n        int old_val = a[r][c];\n        if (old_val == new_val) return 0;\n        static vector<int> delta_match;\n        static vector<int> touched;\n        if ((int)delta_match.size() < M) delta_match.assign(M, 0);\n        else fill(delta_match.begin(), delta_match.end(), 0);\n        touched.clear();\n\n        for (const auto& e : cell_entries[r][c]) {\n            int pid = e.pid;\n            int off = e.off;\n            int sid = placement_sid[pid];\n            int required = raw[sid][off] - 'A';\n            int old_matched = (old_val == required);\n            int new_matched = (new_val == required);\n            int delta_mismatch = old_matched - new_matched; // change in mismatch count\n            int old_mis = placement_mismatch[pid];\n            bool old_match = (old_mis == 0);\n            int new_mis = old_mis + delta_mismatch;\n            bool new_match = (new_mis == 0);\n            if (old_match != new_match) {\n                int delta = new_match ? 1 : -1;\n                if (delta_match[sid] == 0) touched.push_back(sid);\n                delta_match[sid] += delta;\n            }\n        }\n\n        int delta_sat = 0;\n        for (int sid : touched) {\n            int old_match_cnt = match_cnt_str[sid];\n            bool old_sat = (old_match_cnt > 0);\n            int new_match_cnt = old_match_cnt + delta_match[sid];\n            bool new_sat = (new_match_cnt > 0);\n            if (!old_sat && new_sat) ++delta_sat;\n            else if (old_sat && !new_sat) --delta_sat;\n            delta_match[sid] = 0; // reset for next use\n        }\n        touched.clear();\n        return delta_sat;\n    };\n\n    auto apply_change = [&](int r, int c, int new_val) {\n        int old_val = a[r][c];\n        if (old_val == new_val) return;\n        a[r][c] = new_val;\n        // update dot count\n        if (old_val == 8) --dot_cnt;\n        if (new_val == 8) ++dot_cnt;\n\n        for (const auto& e : cell_entries[r][c]) {\n            int pid = e.pid;\n            int off = e.off;\n            int sid = placement_sid[pid];\n            int required = raw[sid][off] - 'A';\n            int old_matched = (old_val == required);\n            int new_matched = (new_val == required);\n            int delta_mismatch = old_matched - new_matched;\n            int& mis = placement_mismatch[pid];\n            int old_mis = mis;\n            bool old_match = (old_mis == 0);\n            mis += delta_mismatch;\n            bool new_match = (mis == 0);\n            if (old_match != new_match) {\n                int delta = new_match ? 1 : -1;\n                int old_match_cnt = match_cnt_str[sid];\n                match_cnt_str[sid] += delta;\n                int new_match_cnt = match_cnt_str[sid];\n                bool old_sat = (old_match_cnt > 0);\n                bool new_sat = (new_match_cnt > 0);\n                if (!old_sat && new_sat) ++satisfied;\n                else if (old_sat && !new_sat) --satisfied;\n            }\n        }\n    };\n\n    // Simulated annealing to maximize number of satisfied strings\n    const int MAX_ITER = 20000;\n    double start_temp = 2.0;\n    double end_temp = 0.001;\n    uniform_int_distribution<int> dist_cell(0, N - 1);\n    uniform_int_distribution<int> dist_val_full(0, 8); // 0-7 letters, 8 for '.'\n    uniform_real_distribution<double> dist_real(0.0, 1.0);\n\n    for (int it = 0; it < MAX_ITER; ++it) {\n        double t = start_temp * pow(end_temp / start_temp, (double)it / MAX_ITER);\n        int r = dist_cell(rng);\n        int c = dist_cell(rng);\n        int cur = a[r][c];\n        int nv = dist_val_full(rng);\n        if (nv == cur) continue;\n        int delta = evaluate_delta(r, c, nv);\n        bool accept = false;\n        if (delta > 0) accept = true;\n        else if (delta == 0 && dist_real(rng) < 0.1) accept = true;\n        else if (dist_real(rng) < exp(delta / t)) accept = true;\n        if (accept) {\n            apply_change(r, c, nv);\n        }\n    }\n\n    // Greedy phase: turn non-dot cells into '.' if it does not break any satisfied string\n    bool improved;\n    do {\n        improved = false;\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (a[r][c] == 8) continue; // already dot\n                if (evaluate_delta(r, c, 8) == 0) {\n                    apply_change(r, c, 8);\n                    improved = true;\n                }\n            }\n        }\n    } while (improved);\n\n    // Output the matrix    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int v = a[i][j];\n            if (v == 8) putchar('.');\n            else putchar('A' + v);\n        }\n        putchar('\\n');\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }\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 (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\nstruct Edge {\n    int u, v;\n    long long cost;\n    bool operator<(const Edge& other) const {\n        return cost < other.cost;\n    }\n};\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    vector<vector<int>> id(N, vector<int>(N, -1));\n    vector<pair<int,int>> pos;\n    vector<int> w;\n    auto get_id = [&](int i, int j) -> int {\n        if (id[i][j] != -1) return id[i][j];\n        int cur = (int)pos.size();\n        id[i][j] = cur;\n        pos.emplace_back(i, j);\n        w.push_back(grid[i][j] - '0');\n        return cur;\n    };\n\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (grid[i][j] != '#')\n                get_id(i, j);\n\n    int V = (int)pos.size();\n    if (V == 0) { cout << '\\n'; return 0; }\n\n    vector<Edge> edges;\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == '#') continue;\n            int uid = id[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d], nj = j + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                if (grid[ni][nj] == '#') continue;\n                int vid = id[ni][nj];\n                if (uid < vid) {\n                    edges.push_back({uid, vid, (long long)w[uid] + w[vid]});\n                }\n            }\n        }\n\n    sort(edges.begin(), edges.end());\n    DSU dsu(V);\n    vector<vector<int>> tree(V);\n    for (const auto& e : edges) {\n        if (dsu.unite(e.u, e.v)) {\n            tree[e.u].push_back(e.v);\n            tree[e.v].push_back(e.u);\n        }\n    }\n\n    int start = id[si][sj];\n    string ans;\n    auto dir_char = [&](int from, int to) -> char {\n        int x1 = pos[from].first, y1 = pos[from].second;\n        int x2 = pos[to].first,   y2 = pos[to].second;\n        if (x2 == x1 - 1) return 'U';\n        if (x2 == x1 + 1) return 'D';\n        if (y2 == y1 - 1) return 'L';\n        if (y2 == y1 + 1) return 'R';\n        return '?';\n    };\n\n    function<void(int, int)> dfs = [&](int u, int p) {\n        for (int v : tree[u]) {\n            if (v == p) continue;\n            ans.push_back(dir_char(u, v));\n            dfs(v, u);\n            ans.push_back(dir_char(v, u));\n        }\n    };\n\n    dfs(start, -1);\n    cout << ans << '\\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 task difficulty vectors\n    vector<array<int, 20>> d(N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    // build dependency graph (edges u -> v, u < v)\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    // dp[i] = length of longest path (in edges) starting from i\n    vector<int> dp(N, 0);\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    // priority queue of ready tasks: higher dp first\n    using TaskInfo = pair<int, int>; // dp, task index\n    priority_queue<TaskInfo> pq;\n    vector<int> task_state(N, 0); // 0 = not started, 1 = started, 2 = completed    for (int i = 0; i < N; ++i) {\n        if (indeg[i] == 0 && task_state[i] == 0) {\n            pq.push({dp[i], i});\n        }\n    }\n\n    // worker state\n    vector<int> worker_task(M, -1);       // task assigned to worker, -1 = idle\n    vector<int> worker_start_day(M, 0);   // start day of current task (valid if not idle)\n    vector<bool> worker_idle(M, true);    // true if idle\n    vector<int> finished_today;           // workers that finished at end of previous day\n\n    int day = 1;\n    while (true) {\n        // 1) process completions from previous day        for (int w : finished_today) {\n            int task = worker_task[w];\n            // t = (day-1) - start_day + 1 = day - start_day            int t = day - worker_start_day[w];\n            // (optional) could use t to infer skill levels here\n\n            // mark task as completed\n            if (task_state[task] != 1) {\n                // defensive: should not happen\n            }\n            task_state[task] = 2;\n            for (int succ : adj[task]) {\n                if (--indeg[succ] == 0 && task_state[succ] == 0) {\n                    pq.push({dp[succ], succ});\n                }\n            }\n            worker_task[w] = -1;\n            worker_idle[w] = true;\n        }\n        finished_today.clear();\n\n        // 2) assign tasks to idle workers\n        vector<pair<int, int>> assignments; // (worker+1, task+1)\n        for (int w = 0; w < M; ++w) {\n            if (!worker_idle[w]) continue;\n            if (pq.empty()) break;\n            auto [dpval, task] = pq.top(); pq.pop();\n            worker_task[w] = task;\n            worker_start_day[w] = day;\n            worker_idle[w] = false;\n            task_state[task] = 1;\n            assignments.emplace_back(w + 1, task + 1);\n        }\n\n        // 3) output assignments for today\n        cout << assignments.size();\n        for (auto &p : assignments) {\n            cout << ' ' << p.first << ' ' << p.second;\n        }\n        cout << '\\n';\n        cout.flush();\n\n        // 4) read response (workers that finished at end of today)\n        string line;\n        if (!getline(cin, line)) break;\n        stringstream ss(line);\n        int first;\n        if (!(ss >> first)) break;\n        if (first == -1) break; // all tasks done or day limit exceeded\n        int n = first;\n        finished_today.clear();\n        for (int i = 0; i < n; ++i) {\n            int w;\n            ss >> w;\n            finished_today.push_back(w - 1);\n        }\n\n        ++day;\n        // safety stop (judge will send -1 after day 2000 anyway)\n        if (day > 2000) {\n            // we will still rely on -1 to break\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Point = pair<int, int>;\n\nconst int CENTER_X = 400;\nconst int CENTER_Y = 400;\nconst int MAX_ORDERS = 1000;\nconst int SELECT_SIZE = 50;\n\nint A[MAX_ORDERS], B[MAX_ORDERS], C[MAX_ORDERS], D[MAX_ORDERS];\n\nstruct Result {\n    ll dist;\n    vector<int> order;          // 1\u2011based indices of chosen orders in pickup order\n    vector<Point> route;        // full route (starts/ends at center)\n};\n\ninline int manh(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Build a feasible route for a given set of order indices (0\u2011based).\nResult computeRoute(const vector<int>& sel) {\n    vector<bool> visPick(MAX_ORDERS, false), visDel(MAX_ORDERS, false);\n    vector<Point> route;\n    route.emplace_back(CENTER_X, CENTER_Y);\n    int curX = CENTER_X, curY = CENTER_Y;\n    vector<int> orderVis;\n    int remaining = 2 * (int)sel.size();\n\n    while (remaining > 0) {\n        int bestId = -1;\n        bool isPick = false;\n        int bestDist = INT_MAX;\n        for (int id : sel) {\n            if (!visPick[id]) {\n                int d = manh(curX, curY, A[id], B[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = true;\n                }\n            }\n            if (visPick[id] && !visDel[id]) {\n                int d = manh(curX, curY, C[id], D[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = false;\n                }\n            }\n        }\n        if (isPick) {\n            route.emplace_back(A[bestId], B[bestId]);\n            visPick[bestId] = true;\n            orderVis.push_back(bestId + 1); // store 1\u2011based index\n            curX = A[bestId]; curY = B[bestId];\n        } else {\n            route.emplace_back(C[bestId], D[bestId]);\n            visDel[bestId] = true;\n            curX = C[bestId]; curY = D[bestId];\n        }\n        --remaining;\n    }\n    route.emplace_back(CENTER_X, CENTER_Y);\n\n    ll total = 0;\n    for (size_t i = 0; i + 1 < route.size(); ++i) {\n        total += manh(route[i].first, route[i].second,\n                      route[i+1].first, route[i+1].second);\n    }\n    return {total, orderVis, route};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    for (int i = 0; i < MAX_ORDERS; ++i) {\n        cin >> A[i] >> B[i] >> C[i] >> D[i];\n    }\n\n    // ---- initial selections -------------------------------------------------\n    vector<int> idx(MAX_ORDERS);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](int i, int j) {\n        int wi = manh(CENTER_X, CENTER_Y, A[i], B[i]) +\n                 manh(A[i], B[i], C[i], D[i]) +\n                 manh(C[i], D[i], CENTER_X, CENTER_Y);\n        int wj = manh(CENTER_X, CENTER_Y, A[j], B[j]) +\n                 manh(A[j], B[j], C[j], D[j]) +\n                 manh(C[j], D[j], CENTER_X, CENTER_Y);\n        return wi < wj;\n    });\n\n    vector<vector<int>> initialSelections;\n    {\n        vector<int> top50(idx.begin(), idx.begin() + SELECT_SIZE);\n        initialSelections.push_back(top50);\n    }\n    {\n        // random selection\n        vector<int> rnd(SELECT_SIZE);\n        mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n        uniform_int_distribution<int> dist(0, MAX_ORDERS - 1);\n        vector<bool> taken(MAX_ORDERS, false);\n        int cnt = 0;\n        while (cnt < SELECT_SIZE) {\n            int x = dist(rng);\n            if (!taken[x]) {\n                taken[x] = true;\n                rnd[cnt++] = x;\n            }\n        }\n        initialSelections.push_back(rnd);\n    }\n    {\n        // selection by nearest pickup to center only\n        vector<int> orderByPickup = idx;\n        sort(orderByPickup.begin(), orderByPickup.end(),\n             [&](int i, int j) {\n                 return manh(CENTER_X, CENTER_Y, A[i], B[i]) <                        manh(CENTER_X, CENTER_Y, A[j], B[j]);\n             });\n        vector<int> pick50(orderByPickup.begin(),\n                           orderByPickup.begin() + SELECT_SIZE);\n        initialSelections.push_back(pick50);\n    }\n\n    // ---- local search -------------------------------------------------------\n    const int MAX_ITER = 2000;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distPos(0, SELECT_SIZE - 1);\n    uniform_int_distribution<int> distId(0, MAX_ORDERS - 1);\n\n    ll bestDist = LLONG_MAX;\n    vector<int> bestOrder;\n    vector<Point> bestRoute;\n\n    auto currentTime = []() {\n        return chrono::duration<double>(\n            chrono::steady_clock::now().time_since_epoch()\n        ).count();\n    };\n    double startTime = currentTime();\n    double timeLimit = 1.9; // seconds\n\n    for (const auto& initSel : initialSelections) {\n        if (currentTime() - startTime > timeLimit) break;\n        vector<int> curSel = initSel;\n        vector<bool> inSel(MAX_ORDERS, false);\n        for (int id : curSel) inSel[id] = true;\n\n        auto [dist, order, route] = computeRoute(curSel);\n        if (dist < bestDist) {\n            bestDist = dist;\n            bestOrder = order;\n            bestRoute = route;\n        }\n\n        for (int it = 0; it < MAX_ITER; ++it) {\n            if (currentTime() - startTime > timeLimit) break;\n            int pos = distPos(rng);\n            int outId = curSel[pos];\n            int inId;\n            do {\n                inId = distId(rng);\n            } while (inSel[inId]);\n\n            // perform swap\n            curSel[pos] = inId;\n            inSel[outId] = false;\n            inSel[inId] = true;\n\n            auto [ndist, norder, nroute] = computeRoute(curSel);\n            if (ndist < bestDist) {\n                bestDist = ndist;\n                bestOrder = norder;\n                bestRoute = nroute;\n            } else {\n                // revert swap\n                curSel[pos] = outId;\n                inSel[outId] = true;\n                inSel[inId] = false;\n            }\n        }\n    }\n\n    // ---- output -------------------------------------------------------------\n    cout << SELECT_SIZE << ' ';\n    for (size_t i = 0; i < bestOrder.size(); ++i) {\n        if (i) cout << ' ';\n        cout << bestOrder[i];\n    }\n    cout << '\\n';\n    cout << bestRoute.size();\n    for (auto &p : bestRoute) {\n        cout << ' ' << p.first << ' ' << p.second;\n    }\n    cout << '\\n';\n    cout << flush;\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }\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 (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\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) cin >> x[i] >> y[i];\n\n    vector<int> u(M), v(M);\n    for (int i = 0; i < M; ++i) cin >> u[i] >> v[i];\n\n    vector<int> d(M);\n    for (int i = 0; i < M; ++i) {\n        long long dx = 1LL * x[u[i]] - x[v[i]];\n        long long dy = 1LL * y[u[i]] - y[v[i]];\n        long long dist2 = dx * dx + dy * dy;\n        double dist = sqrt((double)dist2);\n        d[i] = (int)round(dist);\n    }\n\n    DSU dsu(N);\n    int components = N;\n\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;\n        bool useful = (dsu.find(u[i]) != dsu.find(v[i]));\n        bool take = false;\n        if (useful) {\n            if (l <= 2 * d[i])          // accept relatively short edges\n                take = true;\n            else {\n                // If even assuming all remaining edges are useful we cannot\n                // reach connectivity, we must take this useful edge now.\n                int remaining = M - i - 1;\n                if (components - 1 > remaining)\n                    take = true;\n            }\n        }\n        if (take) {\n            cout << '1' << '\\n';\n            cout.flush();\n            dsu.unite(u[i], v[i]);\n            --components;\n        } else {\n            cout << '0' << '\\n';\n            cout.flush();\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;\n    vector<int> px(N), py(N), pt(N);\n    for (int i = 0; i < N; ++i) cin >> px[i] >> py[i] >> pt[i];\n\n    int M;\n    cin >> M;\n    vector<int> hx(M), hy(M);\n    for (int i = 0; i < M; ++i) cin >> hx[i] >> hy[i];\n\n    string action(M, '.');   // all humans do nothing each turn\n\n    for (int turn = 0; turn < 300; ++turn) {\n        cout << action << '\\n';\n        cout.flush();\n\n        // read pets' movement strings for this turn\n        string mv;\n        for (int i = 0; i < N; ++i) {\n            if (!(cin >> mv)) return 0;   // input ended unexpectedly\n        }\n    }\n    return 0;\n}","ahc009":"#include<bits/stdc++.h>\nusing namespace std;\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 lines, each 19 chars)\n    for (int i = 0; i < 20; ++i) {\n        string line;\n        cin >> line;\n    }\n    // Read vertical walls (20 lines, each 20 chars)\n    for (int i = 0; i < 20; ++i) {\n        string line;\n        cin >> line;\n    }\n    \n    // Output any valid string, e.g., 200 'R's (length <= 200)\n    string ans(200, 'R');\n    cout << ans << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    array<array<int, 30>, 30> tile{};\n    for (int i = 0; i < 30; ++i) {\n        string line;\n        getline(cin, line);\n        line.erase(remove(line.begin(), line.end(), ' '), line.end());\n        for (int j = 0; j < 30; ++j) tile[i][j] = line[j] - '0';\n    }\n\n    const int di[4] = {0, -1, 0, 1};\n    const int dj[4] = {-1, 0, 1, 0};\n\n    // base to[t][d] as given in the statement    const int toBase[8][4] = {\n        {1, 0, -1, -1}, //0\n        {3, -1, -1, 0}, //1\n        {-1, -1, 3, 2}, //2        {-1, 2, 1, -1}, //3\n        {1, 0, 3, 2},   //4\n        {3, 2, 1, 0},   //5        {2, -1, 0, -1}, //6\n        {-1, 3, -1, 1}  //7\n    };\n\n    // toRot[t][rot][d] = exit direction or -1 after rotating tile t by rot (90*rot CCW)\n    int toRot[8][4][4] = {};\n    for (int t = 0; t < 8; ++t) {\n        for (int rot = 0; rot < 4; ++rot) {\n            for (int d = 0; d < 4; ++d) {\n                int baseDir = (d + rot) % 4;\n                int baseExit = toBase[t][baseDir];\n                if (baseExit == -1) {\n                    toRot[t][rot][d] = -1;\n                } else {\n                    int exitDir = (baseExit - rot + 4) % 4;\n                    toRot[t][rot][d] = exitDir;\n                }\n            }\n        }\n    }\n\n    auto computeScore = [&](const vector<vector<int>>& rot) -> long long {\n        const int N = 30 * 30 * 4; // 3600\n        int stateOut[N];\n        // build stateOut\n        for (int i = 0; i < 30; ++i) {\n            for (int j = 0; j < 30; ++j) {\n                int t = tile[i][j];\n                int r = rot[i][j];\n                for (int d = 0; d < 4; ++d) {\n                    int nd = toRot[t][r][d];\n                    int id = ((i * 30) + j) * 4 + d;\n                    if (nd == -1) {\n                        stateOut[id] = -1;\n                    } else {\n                        int ni = i + di[nd];\n                        int nj = j + dj[nd];\n                        if (ni < 0 || ni >= 30 || nj < 0 || nj >= 30) {\n                            stateOut[id] = -1;\n                        } else {\n                            int opp = (nd + 2) % 4;\n                            int t2 = tile[ni][nj];\n                            int r2 = rot[ni][nj];\n                            if (toRot[t2][r2][opp] == -1) {\n                                stateOut[id] = -1;\n                            } else {\n                                int nid = ((ni * 30) + nj) * 4 + opp;\n                                stateOut[id] = nid;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        int color[N] = {0};            // 0 unvisited, 1 visiting, 2 visited\n        int posInPath[N];\n        fill(posInPath, posInPath + N, -1);\n        vector<int> path;\n        path.reserve(N);\n        long long max1 = 0, max2 = 0;\n\n        for (int u = 0; u < N; ++u) {\n            if (color[u]) continue;\n            int v = u;\n            while (true) {\n                if (color[v] == 0) {\n                    color[v] = 1;\n                    posInPath[v] = (int)path.size();\n                    path.push_back(v);\n                    int nxt = stateOut[v];\n                    if (nxt == -1) break;\n                    v = nxt;\n                    continue;\n                }\n                if (color[v] == 1) {\n                    int startIdx = posInPath[v];\n                    long long len = (long long)path.size() - startIdx;\n                    if (len > max1) {\n                        max2 = max1;\n                        max1 = len;\n                    } else if (len > max2) {\n                        max2 = len;\n                    }\n                    break;\n                }\n                if (color[v] == 2) {\n                    break;\n                }\n            }\n            for (int node : path) {\n                color[node] = 2;\n                posInPath[node] = -1;\n            }\n            path.clear();\n        }\n        return max1 * max2;\n    };\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distTile(0, 29);\n    uniform_int_distribution<int> distRot(0, 3);\n\n    long long bestScore = -1;\n    vector<vector<int>> bestRot(30, vector<int>(30, 0));\n\n    for (int rest = 0; rest < 5; ++rest) {\n        vector<vector<int>> curRot(30, vector<int>(30, 0));\n        for (int i = 0; i < 30; ++i)\n            for (int j = 0; j < 30; ++j)\n                curRot[i][j] = distRot(rng);\n        long long curScore = computeScore(curRot);\n        for (int it = 0; it < 200; ++it) {\n            int i = distTile(rng);\n            int j = distTile(rng);\n            int cur = curRot[i][j];\n            int nr = distRot(rng);\n            if (nr == cur) continue;\n            curRot[i][j] = nr;\n            long long ns = computeScore(curRot);\n            if (ns > curScore) {\n                curScore = ns;\n            } else {\n                curRot[i][j] = cur;\n            }\n        }\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestRot = curRot;\n        }\n    }\n\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            cout << bestRot[i][j];\n        }\n    }\n    cout << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions for empty movement: U, D, L, R\nconst int dr[4] = {-1, 1, 0, 0};\nconst int dc[4] = {0, 0, -1, 1};\nconst char dirChar[4] = {'U', 'D', 'L', 'R'};\n\nint computeLargestTreeSize(const vector<vector<int>>& board) {\n    int N = (int)board.size();\n    vector<vector<int>> deg(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int v = board[i][j];\n            if (v == 0) continue;\n            // up\n            if (i > 0 && board[i-1][j] != 0) {\n                if ((v & 2) && (board[i-1][j] & 8)) ++deg[i][j];\n            }\n            // down\n            if (i+1 < N && board[i+1][j] != 0) {\n                if ((v & 8) && (board[i+1][j] & 2)) ++deg[i][j];\n            }\n            // left\n            if (j > 0 && board[i][j-1] != 0) {\n                if ((v & 1) && (board[i][j-1] & 4)) ++deg[i][j];\n            }\n            // right\n            if (j+1 < N && board[i][j+1] != 0) {\n                if ((v & 4) && (board[i][j+1] & 1)) ++deg[i][j];\n            }\n        }\n    }\n    vector<vector<char>> vis(N, vector<char>(N, 0));\n    int best = 0;\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 cnt = 0;\n            int sumdeg = 0;\n            queue<pair<int,int>> q;\n            q.push({i, j});\n            vis[i][j] = 1;\n            while (!q.empty()) {\n                auto [x, y] = q.front(); q.pop();\n                ++cnt;\n                sumdeg += deg[x][y];\n                for (int d = 0; d < 4; ++d) {\n                    int nx = x + dr[d];\n                    int ny = y + dc[d];\n                    if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                    if (board[nx][ny] == 0) continue;\n                    if (vis[nx][ny]) continue;\n                    int a = board[x][y];\n                    int b = board[nx][ny];\n                    bool edge = false;\n                    if (nx == x-1 && ny == y) { // up\n                        if ((a & 2) && (b & 8)) edge = true;\n                    } else if (nx == x+1 && ny == y) { // down\n                        if ((a & 8) && (b & 2)) edge = true;\n                    } else if (nx == x && ny == y-1) { // left\n                        if ((a & 1) && (b & 4)) edge = true;\n                    } else if (nx == x && ny == y+1) { // right\n                        if ((a & 4) && (b & 1)) edge = true;\n                    }\n                    if (edge) {\n                        vis[nx][ny] = 1;\n                        q.push({nx, ny});\n                    }\n                }\n            }\n            int edges = sumdeg / 2;\n            if (edges == cnt - 1) { // tree component\n                if (cnt > best) best = cnt;\n            }\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, T;\n    if (!(cin >> N >> T)) return 0;\n    vector<string> raw(N);\n    for (int i = 0; i < N; ++i) cin >> raw[i];\n\n    // Build board and locate empty\n    vector<vector<int>> board(N, vector<int>(N));\n    int er = -1, ec = -1;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char ch = raw[i][j];\n            int v = (ch >= '0' && ch <= '9') ? ch - '0' : ch - 'a' + 10;\n            board[i][j] = v;\n            if (v == 0) { er = i; ec = j; }\n        }\n    }\n\n    const int full = N * N - 1;\n    string ans;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    auto validMoves = [&](int r, int c, vector<int>& out) {\n        out.clear();\n        if (r > 0) out.push_back(0); // U\n        if (r + 1 < N) out.push_back(1); // D\n        if (c > 0) out.push_back(2); // L\n        if (c + 1 < N) out.push_back(3); // R\n    };\n\n    auto simulateMove = [&](int dir) -> int {\n        int nr = er + dr[dir];\n        int nc = ec + dc[dir];\n        swap(board[er][ec], board[nr][nc]);\n        int res = computeLargestTreeSize(board);\n        swap(board[er][ec], board[nr][nc]); // revert\n        return res;\n    };\n\n    while ((int)ans.size() < T && computeLargestTreeSize(board) < full) {\n        vector<int> mvds;\n        validMoves(er, ec, mvds);\n        shuffle(mvds.begin(), mvds.end(), rng);\n\n        int bestDir = -1;\n        int bestScore = computeLargestTreeSize(board);\n        for (int d : mvds) {\n            int s = simulateMove(d);\n            if (s > bestScore) {\n                bestScore = s;\n                bestDir = d;\n            }\n        }\n\n        if (bestDir != -1 && bestScore > computeLargestTreeSize(board)) {\n            int nr = er + dr[bestDir];\n            int nc = ec + dc[bestDir];\n            swap(board[er][ec], board[nr][nc]);\n            er = nr;\n            ec = nc;\n            ans.push_back(dirChar[bestDir]);\n        } else {\n            // no improving move; take a random move\n            int idx = uniform_int_distribution<int>(0, (int)mvds.size() - 1)(rng);\n            int d = mvds[idx];\n            int nr = er + dr[d];\n            int nc = ec + dc[d];\n            swap(board[er][ec], board[nr][nc]);\n            er = nr;\n            ec = nc;\n            ans.push_back(dirChar[d]);\n        }\n    }\n\n    cout << ans << '\\n';\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nstruct Line {\n    ll x1, y1, x2, y2;\n    Line() {}\n    Line(ll a, ll b, ll c, ll d) : x1(a), y1(b), x2(c), y2(d) {}\n};\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    int sumA = 0;\n    for (int d = 1; d <= 10; ++d) {\n        cin >> a[d];\n        sumA += a[d];\n    }\n    vector<pair<ll, ll>> pts(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pts[i].first >> pts[i].second;\n    }\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<ll> dist(-1000000000LL, 1000000000LL);\n\n    const int MAX_ITER = 60;   // number of random attempts\n    int bestScore = -1;\n    vector<Line> bestLines;\n\n    for (int it = 0; it < MAX_ITER; ++it) {\n        // ---- generate K random lines ----\n        vector<Line> lines;\n        lines.reserve(K);\n        for (int i = 0; i < K; ++i) {\n            while (true) {\n                ll x1 = dist(rng);\n                ll y1 = dist(rng);\n                ll x2 = dist(rng);\n                ll y2 = dist(rng);\n                if (x1 == x2 && y1 == y2) continue;\n                lines.emplace_back(x1, y1, x2, y2);\n                break;\n            }\n        }\n\n        // ---- evaluate the partition ----\n        unordered_map<string, int> cnt; // signature -> number of strawberries\n        for (auto &[x, y] : pts) {\n            string sig;\n            bool onLine = false;\n            sig.reserve(K);\n            for (int i = 0; i < K; ++i) {\n                const Line &ln = lines[i];\n                ll cross = (ln.y2 - ln.y1) * (x - ln.x1) - (ln.x2 - ln.x1) * (y - ln.y1);\n                if (cross == 0) {\n                    onLine = true;\n                    break;\n                }\n                sig.push_back(cross > 0 ? '1' : '0');\n            }\n            if (onLine) continue; // strawberry is cut, ignore\n            cnt[sig]++;\n        }\n\n        // ---- compute b[d] ----\n        vector<int> b(11, 0);\n        for (auto &[_, c] : cnt) {\n            if (c >= 1 && c <= 10) b[c]++;\n        }\n\n        // ---- compute score ----\n        int score = 0;\n        for (int d = 1; d <= 10; ++d) {\n            score += min(a[d], b[d]);\n        }\n\n        if (score > bestScore) {\n            bestScore = score;\n            bestLines = lines;\n        }\n    }\n\n    // ---- output the best solution ----\n    cout << K << '\\n';\n    for (const auto &ln : bestLines) {\n        cout << ln.x1 << ' ' << ln.y1 << ' ' << ln.x2 << ' ' << ln.y2 << '\\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    int N, M;\n    cin >> N >> M;\n    // Read and discard the initial dots\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    // Output zero operations\n    cout << 0 << '\\n';\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*------------------------------------------------------------*/\n/*  board utilities                                            */\n/*------------------------------------------------------------*/\nusing Board = array<array<int,10>,10>;\n\n/* place a candy of given flavour into the p-th empty cell (1-indexed) */\nvoid place_candy(Board &bd, int flavour, int p) {\n    int cnt = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (bd[i][j] == 0) {\n                if (++cnt == p) {\n                    bd[i][j] = flavour;\n                    return;\n                }\n            }\n        }\n    }\n}\n\n/* tilt the board in the given direction:\n   0 = F (up), 1 = B (down), 2 = L (left), 3 = R (right) */\nBoard tilt(const Board &bd, int dir) {\n    Board nb{}; // all zero\n    if (dir == 0) {               // F : up\n        for (int j = 0; j < 10; ++j) {\n            int r = 0;\n            for (int i = 0; i < 10; ++i)\n                if (bd[i][j]) nb[r++][j] = bd[i][j];\n        }\n    } else if (dir == 1) {        // B : down\n        for (int i = 0; i < 10; ++i) {\n            int r = 9;\n            for (int j = 9; j >= 0; --j)\n                if (bd[i][j]) nb[i][r--] = bd[i][j];\n        }\n    } else if (dir == 2) {        // L : left\n        for (int i = 0; i < 10; ++i) {\n            int c = 0;\n            for (int j = 0; j < 10; ++j)\n                if (bd[i][j]) nb[i][c++] = bd[i][j];\n        }\n    } else {                      // dir == 3 : R : right\n        for (int i = 0; i < 10; ++i) {\n            int c = 9;\n            for (int j = 9; j >= 0; --j)\n                if (bd[i][j]) nb[i][c--] = bd[i][j];\n        }\n    }\n    return nb;\n}\n\n/* compute sum of squares of component sizes */\nint compute_score(const Board &bd) {\n    bool seen[10][10] = {};\n    int sum = 0;\n    const int dr[4] = {-1,1,0,0};\n    const int dc[4] = {0,0,-1,1};\n\n    auto bfs = [&](int sr, int sc) -> int {\n        int f = bd[sr][sc];\n        queue<pair<int,int>> q;\n        q.emplace(sr,sc);\n        seen[sr][sc] = true;\n        int sz = 0;\n        while (!q.empty()) {\n            auto [r,c] = q.front(); q.pop();\n            ++sz;\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + dr[d], nc = c + dc[d];\n                if (nr < 0 || nr >= 10 || nc < 0 || nc >= 10) continue;\n                if (seen[nr][nc] || bd[nr][nc] != f) continue;\n                seen[nr][nc] = true;\n                q.emplace(nr,nc);\n            }\n        }\n        return sz;\n    };\n\n    for (int i = 0; i < 10; ++i)\n        for (int j = 0; j < 10; ++j)\n            if (bd[i][j] != 0 && !seen[i][j]) {\n                int sz = bfs(i,j);\n                sum += sz*sz;\n            }\n    return sum;\n}\n\n/*------------------------------------------------------------*/\n/*  main                                                       */\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int flavour[100];\n    for (int i = 0; i < 100; ++i) cin >> flavour[i];\n\n    Board board{}; // all zero\n\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        if (!(cin >> p)) break;          // safety, should not happen\n        place_candy(board, flavour[t], p);\n\n        if (t == 99) break;              // last candy \u2013 no output\n\n        int best_dir = -1;\n        int best_val = -1;\n        for (int dir = 0; dir < 4; ++dir) {\n            Board tmp = tilt(board, dir);\n            int val = compute_score(tmp);\n            if (val > best_val) {\n                best_val = val;\n                best_dir = dir;\n            }\n        }\n        char out;\n        switch(best_dir) {\n            case 0: out = 'F'; break;\n            case 1: out = 'B'; break;\n            case 2: out = 'L'; break;\n            case 3: out = 'R'; break;\n        }\n        cout << out << '\\n';\n        cout.flush();\n\n        // really apply the chosen tilt\n        board = tilt(board, best_dir);\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    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n    const int N = 100;                       // number of vertices (max allowed)\n    const long long L = 1LL * N * (N - 1) / 2; // total possible edges    // Pre\u2011compute expected triangle and edge counts for clique sizes k = 1..M\n    vector<double> expTri(M + 1), expEdge(M + 1);\n    for (int k = 1; k <= M; ++k) {\n        long long C3k = (k >= 3) ? 1LL * k * (k - 1) * (k - 2) / 6 : 0LL;\n        long long C2k = (k >= 2) ? 1LL * k * (k - 1) / 2 : 0LL;\n        long long iso = N - k;\n        long long C2iso = (iso >= 2) ? 1LL * iso * (iso - 1) / 2 : 0LL;\n        long long C3iso = (iso >= 3) ? 1LL * iso * (iso - 1) * (iso - 2) / 6 : 0LL;\n\n        double oneMinusEps = 1.0 - eps;\n        double p3 = oneMinusEps * oneMinusEps * oneMinusEps; // (1-\u03b5)^3\n        double p2 = oneMinusEps * eps * eps;                // (1-\u03b5)*\u03b5^2\n        double p1 = eps * eps * eps;                        // \u03b5^3\n\n        // Expected number of triangles\n        expTri[k] = C3k * p3 +\n                    C2k * iso * p2 +\n                    (static_cast<double>(k) * C2iso + C3iso) * p1;\n\n        // Expected number of edges\n        expEdge[k] = C2k * oneMinusEps + (L - C2k) * eps;\n    }\n\n    // Output N and the M graphs (clique of size s+1 on first s+1 vertices)\n    cout << N << '\\n';\n    for (int s = 0; s < M; ++s) {\n        int k = s + 1; // clique size\n        string str;\n        str.reserve(L);\n        for (int i = 0; i < N; ++i)\n            for (int j = i + 1; j < N; ++j)\n                str.push_back((i < k && j < k) ? '1' : '0');\n        cout << str << '\\n';\n    }\n    cout.flush();\n\n    // Process 100 queries\n    for (int qq = 0; qq < 100; ++qq) {\n        string H;\n        if (!(cin >> H)) break;\n        long long triObs = 0;\n        long long edgeObs = 0;\n        vector<bitset<100>> adj(N);\n        int pos = 0;\n        // Build adjacency and count edges\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                char c = H[pos++];\n                if (c == '1') {\n                    adj[i][j] = true;\n                    adj[j][i] = true;\n                    ++edgeObs;\n                }\n            }\n        }\n        // Count triangles: for each edge (i,j) count common neighbours > j\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (adj[i][j]) {\n                    triObs += ((adj[i] & adj[j]) >> (j + 1)).count();\n                }\n            }\n        }\n\n        // Choose s with minimal squared distance to expected (tri, edge)\n        int bestS = 0;\n        double bestDist = 1e100;\n        for (int s = 0; s < M; ++s) {\n            int k = s + 1;\n            double dt = triObs - expTri[k];\n            double de = edgeObs - expEdge[k];\n            double dist = dt * dt + de * de;\n            if (dist < bestDist) {\n                bestDist = dist;\n                bestS = s;\n            }\n        }\n        cout << bestS << '\\n';\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing db = double;\n\nconst db INF = 1e100;\n\nstruct Edge {\n    int u, v, w, idx;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n        int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n    \n    vector<Edge> edges(M);\n    vector<vector<tuple<int,int,int>>> adj(N); // to, weight, edge index\n    vector<vector<int>> edge_idx(N, vector<int>(N, -1));\n    \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, i};\n        adj[u].emplace_back(v, w, i);\n        adj[v].emplace_back(u, w, i);\n        edge_idx[u][v] = edge_idx[v][u] = i;\n    }\n    // read and ignore coordinates\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    vector<db> betw(M, 0.0); // edge betweenness (undirected)\n    \n    for (int s = 0; s < N; ++s) {\n        vector<db> dist(N, INF);\n        vector<db> sigma(N, 0.0);\n        vector<vector<int>> pred(N);\n        using State = pair<db, int>;\n        priority_queue<State, vector<State>, greater<State>> pq;\n        \n        dist[s] = 0;\n        sigma[s] = 1.0;\n        pq.emplace(0, s);\n        \n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d > dist[v] + 1e-12) continue;\n            for (auto [to, w, _] : adj[v]) {\n                db nd = d + w;\n                if (nd < dist[to] - 1e-12) {\n                    dist[to] = nd;\n                    sigma[to] = sigma[v];\n                    pred[to].clear();\n                    pred[to].push_back(v);\n                    pq.emplace(nd, to);\n                } else if (fabs(nd - dist[to]) <= 1e-12) {\n                    sigma[to] += sigma[v];\n                    pred[to].push_back(v);\n                }\n            }\n        }\n        \n        // vertices ordered by distance decreasing\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) { return dist[a] > dist[b]; });\n        \n        vector<db> delta(N, 0.0);\n        for (int v : order) {\n            if (v == s) continue;\n            for (int p : pred[v]) {\n                db c = (sigma[p] / sigma[v]) * (1.0 + delta[v]);\n                int e = edge_idx[p][v];\n                betw[e] += c;\n                delta[p] += c;\n            }\n        }\n    }\n        // each undirected edge counted twice\n    for (int i = 0; i < M; ++i) betw[i] *= 0.5;\n    \n    // order edges by decreasing betweenness\n    vector<int> ord(M);\n    iota(ord.begin(), ord.end(), 0);\n    sort(ord.begin(), ord.end(),\n         [&](int a, int b) { return betw[a] > betw[b]; });\n    \n    vector<int> ans(M, 0);\n    for (size_t i = 0; i < ord.size(); ++i) {\n        int day = (i % D) + 1; // days 1..D\n        ans[ord[i]] = day;\n    }\n        for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << ans[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Voxel {\n    int x, y, z;\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\n    // Read silhouettes\n    vector<vector<string>> fStr(2, vector<string>(D));\n    vector<vector<string>> rStr(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> fStr[i][k];\n        }\n    }\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> rStr[i][k];\n        }\n    }\n\n    // Convert to bool arrays\n    vector<vector<vector<bool>>> f(2, vector<vector<bool>>(D, vector<bool>(D)));\n    vector<vector<vector<bool>>> r(2, vector<vector<bool>>(D, vector<bool>(D)));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int x = 0; x < D; ++x) {\n                f[i][z][x] = (fStr[i][zvoid solve() {\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int y = 0; y < D; ++y) {\n                r[i][z][y] = (rStr[i][z][y] == '1');\n            }\n        }\n    }\n}\n\n    // Collect voxels that satisfy both projections\n    vector<Voxel> vox[2];\n    for (int i = 0; i < 2; ++i) {\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[i][z][x] && r[i][z][y]) {\n                        vox[i].push_back({x, y, z});\n                    }\n                }\n            }\n        }\n    }\n\n    int v0 = (int)vox[0].size();\n    int v1 = (int)vox[1].size();\n    int n = max(v0, v1);\n\n    int size = D * D * D;\n    vector<int> b0(size, 0);\n    vector<int> b1(size, 0);\n\n    for (int i = 0; i < n; ++i) {\n        if (i < v0) {\n            const Voxel& v = vox[0][i];\n            int idx = v.x * D * D + v.y * D + v.z;\n            b0[idx] = i + 1;\n        }\n        if (i < v1) {\n            const Voxel& v = vox[1][i];\n            int idx = v.x * D * D + v.y * D + v.z;\n            b1[idx] = i + 1;\n        }\n    }\n\n    cout << n << '\\n';\n    for (int i = 0; i < size; ++i) {\n        if i > 0) cout << ' ';\n        cout << b0[i];\n    }\n    cout << '\\n';\n    for (int i = 0; i < size; ++i) {\n        if (i > 0) cout << ' ';\n        cout << b1[i];\n    }\n    cout << '\\n';\n    return 0;\n}\nint main() {\n    solve();\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge {\n    int to;\n    long long w;\n    int id;\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    \n    vector<int> xs(N), ys(N);\n    for (int i = 0; i < N; ++i) cin >> xs[i] >> ys[i];\n    \n    vector<tuple<int,int,long long>> edgesRaw; // (u,v,w)\n    edgesRaw.reserve(M);\n    vector<vector<Edge>> adj(N);\n    for (int j = 0; j < M; ++j) {\n        int u, v; long long w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edgesRaw.emplace_back(u, v, w);\n        adj[u].push_back({v, w, j});\n        adj[v].push_back({u, w, j});\n    }\n    \n    vector<pair<int,int>> residents(K);\n    for (int k = 0; k < K; ++k) {\n        cin >> residents[k].first >> residents[k].second;\n    }\n    \n    /* ---------- Dijkstra from vertex 0 (station 1) ---------- */\n    const long long INF = (1LL<<60);\n    vector<long long> dist(N, INF);\n    vector<int> parentEdge(N, -1); // edge id that connects v to its parent\n    vector<int> parentVertex(N, -1);\n    using State = pair<long long,int>;\n    priority_queue<State, vector<State>, greater<State>> pq;\n    dist[0] = 0;\n    pq.emplace(0, 0);\n    while (!pq.empty()) {\n        auto [d, v] = pq.top(); pq.pop();\n        if (d != dist[v]) continue;\n        for (const auto &e : adj[v]) {\n            if (dist[e.to] > d + e.w) {\n                dist[e.to] = d + e.w;\n                parentEdge[e.to] = e.id;\n                parentVertex[e.to] = v;\n                pq.emplace(dist[e.to], e.to);\n            }\n        }\n    }\n    \n    /* ---------- Build tree adjacency (undirected) ---------- */\n    vector<vector<pair<int,int>>> tree(N); // (neighbor, edgeId)\n    for (int v = 1; v < N; ++v) {\n        int eid = parentEdge[v];\n        int u = parentVertex[v];\n        tree[u].emplace_back(v, eid);\n        tree[v].emplace_back(u, eid);\n    }\n    \n    /* ---------- Assign residents to nearest vertex ---------- */\n    vector<int> need(N, 0); // required power (radius) for each vertex\n    for (auto [ax, ay] : residents) {\n        long long bestDist2 = LLONG_MAX;\n        int bestV = -1;\n        for (int v = 0; v < N; ++v) {\n            long long dx = xs[v] - ax;\n            long long dy = ys[v] - ay;\n            long long d2 = dx*dx + dy*dy;\n            if (d2 < bestDist2) {\n                bestDist2 = d2;\n                bestV = v;\n            }\n        }\n        double dist = sqrt((double)bestDist2);\n        int radius = (int)ceil(dist - 1e-9); // safe ceil\n        if (radius < 0) radius = 0;\n        if (radius > 5000) radius = 5000;\n        need[bestV] = max(need[bestV], radius);\n    }\n    \n    /* ---------- Prune the tree ---------- */\n    vector<char> answerB(M, 0);\n    vector<int> answerP(N);\n    for (int i = 0; i < N; ++i) answerP[i] = need[i];\n        function<bool(int,int)> dfs = [&](int v, int p) -> bool {\n        bool subtreeNeed = (need[v] > 0);\n        for (auto [to, eid] : tree[v]) {\n            if (to == p) continue;\n            bool childNeed = dfs(to, v);\n            if (childNeed) answerB[eid] = 1;\n            else answerB[eid] = 0;\n            subtreeNeed |= childNeed;\n        }\n        return subtreeNeed;\n    };\n    dfs(0, -1);\n    \n    /* ---------- Output ---------- */\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << answerP[i];\n    }\n    cout << '\\n';\n    for (int j = 0; j < M; ++j) {\n        if (j) cout << ' ';\n        cout << (int)answerB[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 total = N * (N + 1) / 2; // 465\n\n    // Precompute level and coordinates for each index in level\u2011order (heap) layout.\n    vector<int> level(total), cx(total), cy(total);\n    int idx = 0;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            level[idx] = x;\n            cx[idx] = x;\n            cy[idx] = y;\n            ++idx;\n        }\n    }\n\n    // Read the initial permutation.\n    vector<int> val(total);\n    idx = 0;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int v;\n            cin >> v;\n            val[idx++] = v;\n        }\n    }\n\n    struct Op { int x1, y1, x2, y2; };\n    vector<Op> ops;\n    ops.reserve(10000);\n\n    auto children = [&](int i) {\n        int lev = level[i];\n        int left = i + lev + 1;   // left child (same y)\n        int right = i + lev + 2;  // right child (y+1)\n        return make_pair(left, right);\n    };\n\n    // Helper to check if a node (not in bottom tier) violates the heap condition.\n    auto isViolation = [&](int i) {\n        if (level[i] >= N - 1) return false; // bottom tier has no children\n        auto [l, r] = children(i);\n        return (l < total && val[i] > val[l]) || (r < total && val[i] > val[r]);\n    };\n\n    // Main loop: fix violations by swapping with the smaller child.\n    while ((int)ops.size() < 10000) {\n        int violate = -1;\n        int bestDiff = -1; // we want to fix the biggest excess first\n        for (int i = 0; i < total; ++i) {\n            if (isViolation(i)) {\n                auto [l, r] = children(i);\n                int childVal = total; // large sentinel\n                int childIdx = -1;\n                if (l < total && val[l] < childVal) { childVal = val[l]; childIdx = l; }\n                if (r < total && val[r] < childVal) { childVal = val[r]; childIdx = r; }\n                int diff = val[i] - childVal; // how much parent exceeds the smaller child\n                if (diff > bestDiff) {\n                    bestDiff = diff;\n                    violate = i;\n                }\n            }\n        }\n        if (violate == -1) break; // no violations left\n\n        auto [l, r] = children(violate);\n        // choose the smaller child to swap with\n        int child = (l < total && (r >= total || val[l] < val[r])) ? l : r;\n        // perform swap\n        swap(val[violate], val[child]);\n        ops.push_back({cx[violate], cy[violate], cx[child], cy[child]});\n    }\n\n    // Output\n    cout << ops.size() << '\\n';\n    for (const auto& op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' ' << 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 ent_r = 0;\n    const int ent_c = (D - 1) / 2;\n\n    vector<vector<bool>> blocked(D, vector<bool>(D, false));\n    for (int k = 0; k < N; ++k) {\n        int r, j;\n        cin >> r >> j;\n        blocked[r][j] = true;\n    }\n    blocked[ent_r][ent_c] = false;\n\n    vector<vector<int>> dist(D, vector<int>(D, -1));\n    queue<pair<int,int>> q;\n    dist[ent_r][ent_c] = 0;\n    q.emplace(ent_r, ent_c);\n    const int dr[4] = {-1,1,0,0};\n    const int dc[4] = {0,0,-1,1};\n    while (!q.empty()) {\n        auto [r,c] = q.front(); q.pop();\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 >= D || nc < 0 || nc >= D) continue;\n            if (blocked[nr][nc]) continue;\n            if (dist[nr][nc] != -1) continue;\n            dist[nr][nc] = dist[r][c] + 1;\n            q.emplace(nr, nc);\n        }\n    }\n\n    vector<pair<int,int>> L;\n    vector<vector<int>> idx(D, vector<int>(D, -1));\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            if (blocked[i][j]) continue;\n            if (i == ent_r && j == ent_c) continue;\n            L.emplace_back(i, j);\n            idx[i][j] = (int)L.size() - 1;\n        }\n    }\n    const int M = (int)L.size();\n    sort(L.begin(), L.end(), [&](const pair<int,int>& a, const pair<int,int>& b) {\n        if (dist[a.first][a.second] != dist[b.first][b.second])\n            return dist[a.first][a.second] < dist[b.first][b.second];\n        if (a.first != b.first) return a.first < b.first;\n        return a.second < b.second;\n    });\n    for (int i = 0; i < D; ++i) for (int j = 0; j < D; ++j) idx[i][j] = -1;\n    for (int p = 0; p < M; ++p) {\n        auto [r,c] = L[p];\n        idx[r][c] = p;\n    }\n\n    vector<vector<bool>> occupied(D, vector<bool>(D, false));\n    auto bfsReachable = [&](const vector<vector<bool>>& occ) -> vector<vector<bool>> {\n        vector<vector<bool>> reach(D, vector<bool>(D, false));\n        queue<pair<int,int>> qq;\n        if (!blocked[ent_r][ent_c] && !occ[ent_r][ent_c]) {\n            reach[ent_r][ent_c] = true;\n            qq.emplace(ent_r, ent_c);\n        }\n        while (!qq.empty()) {\n            auto [r,c] = qq.front(); qq.pop();\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 >= D || nc < 0 || nc >= D) continue;\n                if (blocked[nr][nc] || occ[nr][nc]) continue;\n                if (reach[nr][nc]) continue;\n                reach[nr][nc] = true;\n                qq.emplace(nr, nc);\n            }\n        }\n        return reach;\n    };\n\n    auto getArticulation = [&](const vector<vector<bool>>& reach, const vector<vector<bool>>& occ) -> vector<vector<bool>> {\n        vector<vector<bool>> isArt(D, vector<bool>(D, false));\n        vector<int> tin(D*D, -1), low(D*D, -1);\n        vector<char> visited(D*D, false);\n        int timer = 0;\n        function<void(int,int,int)> dfs = [&](int r, int c, int pr) {\n            int id = r*D + c;\n            visited[id] = true;\n            tin[id] = low[id] = timer++;\n            int children = 0;\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 >= D || nc < 0 || nc >= D) continue;\n                if (!blocked[nr][nc] && !occ[nr][nc] && reach[nr][nc]) {\n                    int nid = nr*D + nc;\n                    if (visited[nid]) {\n                        low[id] = min(low[id], tin[nid]);\n                    } else {\n                        ++children;\n                        dfs(nr, nc, id);\n                        low[id] = min(low[id], low[nid]);\n                        if (pr != -1 && low[nid] >= tin[id]) {\n                            isArt[r][c] = true;\n                        }\n                    }\n                }\n            }\n            if (pr == -1 && children > 1) {\n                isArt[r][c] = true;\n            }\n        };\n        dfs(ent_r, ent_c, -1);\n        return isArt;\n    };\n\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;\n        vector<vector<bool>> reach = bfsReachable(occupied);\n        vector<vector<bool>> isArt = getArticulation(reach, occupied);\n\n        int best_r = -1, best_c = -1;\n        int best_cost = INT_MAX;\n        for (int i = 0; i < D; ++i) {\n            for (int j = 0; j < D; ++j) {\n                if (!reach[i][j]) continue;\n                if (i == ent_r && j == ent_c) continue;\n                if (occupied[i][j]) continue;\n                if (isArt[i][j]) continue;\n                int cost = abs(idx[i][j] - t);\n                if (cost < best_cost || (cost == best_cost && (i < best_r || (i == best_r && j < best_c)))) {\n                    best_cost = cost;\n                    best_r = i;\n                    best_c = j;\n                }\n            }\n        }\n        if (best_r == -1) {\n            for (int i = 0; i < D; ++i) {\n                for (int j = 0; j < D; ++j) {\n                    if (!reach[i][j]) continue;\n                    if (i == ent_r && j == ent_c) continue;\n                    if (occupied[i][j]) continue;\n                    best_r = i; best_c = j;\n                    break;\n                }\n                if (best_r != -1) break;\n            }\n        }\n        occupied[best_r][best_c] = true;\n        cout << best_r << ' ' << best_c << '\\n';\n        cout.flush();\n    }\n\n    for (auto [r,c] : L) {\n        cout << r << ' ' << c << '\\n';\n    }\n    cout.flush();\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*------------------------------------------------------------*/\n/*  Constants and directions                                  */\nconst int dx[4] = {1, -1, 0, 0};\nconst int dy[4] = {0, 0, 1, -1};\n\n/*------------------------------------------------------------*/\nstruct Solver {\n    int n, m;\n    vector<vector<short>> grid;          // current colours\n    vector<int> cnt;                     // number of cells of each colour (>0)\n    vector<vector<int>> adj;             // current adjacency counts\n    vector<vector<int>> adjOrig;         // original adjacency counts (constant)\n\n    Solver(int n_, int m_) : n(n_), m(m_) {\n        grid.assign(n, vector<short>(n, 0));\n        cnt.assign(m + 1, 0);\n        adj.assign(m + 1, vector<short>(m + 1, 0));\n        adjOrig.assign(m + 1, vector<short>(m + 1, 0));\n    }\n\n    /*--------------------------------------------------------*/\n    // read the input\n    void read() {\n        cin >> n >> m;\n        grid.assign(n, vector<short>(n));\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) {\n                cin >> grid[i][j];\n                if (grid[i][j] > 0) ++cnt[grid[i][j]];\n            }\n    }\n\n    /*--------------------------------------------------------*/\n    // compute adjacency matrix from a given grid\n    void computeAdj(const vector<vector<short>>& g, vector<vector<int>>& out) {\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) {\n                int c = g[i][j];\n                for (int d = 0; d < 4; ++d) {\n                    int ni = i + dx[d], nj = j + dy[d];\n                    int nb = 0;               // outside\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n)\n                        nb = g[ni][nj];\n                    if (c == nb) continue;   // same colour \u2013 we do not store c\u2011c\n                    out[c][nb]++;\n                    out[nb][c]++;\n                }\n            }\n    }\n\n    /*--------------------------------------------------------*/\n    // zero\u2011neighbour test (outside counts as zero)\n    bool hasZeroNeighbour(int i, int j) const {\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) return true;   // outside\n            if (grid[ni][nj] == 0) return true;\n        }\n        return false;\n    }\n\n    /*--------------------------------------------------------*/\n    // BFS to check connectivity of a given colour (>0)\n    bool connectedColour(int col) const {\n        // find any cell of this colour\n        int si = -1, sj = -1;\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (grid[i][j] == col) { si = i; sj = j; break; }\n            if (si != -1) break;\n        if (si == -1) return false;   // should never happen because cnt[col]>0 checked before\n        vector<vector<char>> vis(n, vector<char>(0, false));\n        queue<pair<int,int>> q;\n        q.emplace(si, sj);\n        vis[si][sj] = 1;\n        int reached = 0;\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            ++reached;\n            for (int d = 0; d < 4; ++d) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;\n                if (grid[nx][ny] != col) continue;\n                if (vis[nx][ny]) continue;\n                vis[nx][ny] = 1;\n                q.emplace(nx, ny);\n            }\n        }\n        return reached == cnt[col];\n    }\n\n    /*--------------------------------------------------------*/\n    // check that all zero cells are reachable from the outside\n    bool zeroConnected() const {\n        vector<vector<char>> vis(n, vector<char>(0, false));\n        queue<pair<int,int>> q;\n        // start from all boundary zero cells (they touch the outside)\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] == 0 && (i == 0 || i == n-1 || j == 0 || j == n-1)) {\n                    q.emplace(i, j);\n                    vis[i][j] = 1;\n                }\n            }\n        }\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;\n                if (grid[nx][ny] != 0) continue;\n                if (vis[nx][ny]) continue;\n                vis[nx][ny] = 1;\n                q.emplace(nx, ny);\n            }\n        }\n        // any zero cell not visited?\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (grid[i][j] == 0 && !vis[i][j]) return false;\n        return true;\n    }\n\n    /*--------------------------------------------------------*/\n    // try to delete cell (i,j); return true iff deletion really happened\n    bool tryDelete(int i, int j) {\n        int col = grid[i][j];\n        if (col == 0) return false;\n        if (!hasZeroNeighbour(i, j)) return false;\n\n        // backup        int backupCnt = cnt[col];\n        vector<tuple<int,int,int>> changes;   // (a,b,delta) to be added to adj[a][b]\n\n        // process the four neighbours        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d], nj = y + dy[d];\n            int nb;\n            bool outside = false;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) { nb = 0; outside = true; }\n            else nb = grid[ni][nj];\n\n            if (nb == col) continue;          // internal edge, nothing to change\n\n            // erase edge col \u2013 nb\n            changes.emplace_back(col, nb, -1);\n            changes.emplace_back(nb, col, -1);\n\n            if (nb != 0 && !outside) {\n                // create edge 0 \u2013 nb\n                changes.emplace_back(0, nb, +1);\n                changes.emplace_back(nb, 0, +1);\n            }\n            // if nb == 0 (inside zero or outside) we only removed a col\u20110 edge\n        }\n\n        // apply changes to adj\n        for (auto &ch : changes) {\n            int a = get<0>(ch), b = get<1>(ch), delta = get<2>(ch);\n            adj[a][b] += delta;\n        }\n\n        // actually delete the cell\n        grid[i][j] = 0;\n        --cnt[col];\n\n        // ----- tests -----\n        bool ok = true;\n        if (cnt[col] == 0) ok = false;                // colour must stay non\u2011empty\n\n        if (ok) {\n            // adjacency matrix must stay exactly the same (as Boolean)\n            for (int x = 0; x <= m && ok; ++x)\n                for (int y = x; y <= m && ok; ++y)\n                    bool cur = (adj[x][y] > 0);\n                    bool orig = (adjOrig[x][y] > 0);\n                    if (cur != orig) { ok = false; break; }\n        }\n        if (ok) {\n            if (!connectedColour(col)) ok = false;\n        }\n        if (ok) {\n            if (!zeroConnected()) ok = false;\n        }\n\n        if (!ok) {\n            // ----- revert -----            grid[i][j] = col;\n            cnt[col] = backupCnt;\n            for (auto &ch : changes) {\n                int a = get<0>(ch), b = get<1>(ch), delta = get<2>(ch);\n                adj[a][b] -= delta;   // undo the addition\n            }\n            return false;\n        }\n        return true;\n    }\n\n    /*--------------------------------------------------------*/\n    void solve() {\n        read();\n        computeAdj(grid, adjOrig);\n        adj = adjOrig;          // start with the original adjacency\n\n        bool progress;\n        do {\n            progress = false;\n            vector<pair<int,int>> cand;\n            for (int i = 0; i < n; ++i)\n                for (int j = 0; j < n; ++j)\n                    if (grid[i][j] > 0)\n                        cand.emplace_back(i, j);\n            std::shuffle(cand.begin(), cand.end(),\n                         std::mt19937{std::random_device{}()});\n            for (auto &p : cand)\n                if (tryDelete(p.first, p.second))\n                    progress = true;\n        } while (progress);\n\n        // output the final grid\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << grid[i][j];\n                if (j + 1 < n) cout << ' ';\n            }\n            cout << '\\n';\n        }\n    }\n};\n\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m;\n    cin >> n >> m;\n    Solver solver(n, m);\n    solver.solve();\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    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n\n    // cached comparison results: 0 = unknown, '<', '>', '='\n    vector<vector<char>> known(N, vector<char>(N, 0));\n    int query_cnt = 0;\n\n    auto ask = [&](int a, int b) -> char {\n        // precondition: query_cnt < Q (checked by caller)\n        cout << 1 << ' ' << 1 << ' ' << a << ' ' << b << '\\n';\n        cout.flush();\n        string res;\n        cin >> res;               // judge replies with one of \"<\", \">\", \"=\"\n        ++query_cnt;\n        char c = res[0];\n        known[a][b] = c;\n        known[b][a] = (c == '<' ? '>' : (c == '>' ? '<' : '='));\n        return c;\n    };\n\n    vector<bool> used(N, false);\n    vector<int> top;               // heaviest items found, in decreasing order\n\n    // ---------- 1. select as many heaviest items as query budget allows ----------\n    for (int k = 0; k < D; ++k) {\n        if (query_cnt >= Q) break;          // no queries left\n        int best = -1;\n        for (int i = 0; i < N; ++i) {\n            if (used[i]) continue;\n            if (best == -1) { best = i; continue; }\n            if (query_cnt >= Q) break;      // stop inner loop as well\n            char res = ask(i, best);\n            if (res == '>') best = i;\n        }\n        if (best == -1) break;              // no remaining items\n        top.push_back(best);\n        used[best] = true;\n    }\n\n    // ---------- 2. build the partition (round\u2011robin) ----------\n    vector<int> answer(N, -1);\n    int grp = 0;\n    // distribute the found heavy items\n    for (size_t idx = 0; idx < top.size(); ++idx) {\n        answer[top[idx]] = grp;\n        grp = (grp + 1) % D;\n    }\n    // distribute the rest\n    for (int i = 0; i < N; ++i) {\n        if (answer[i] == -1) {\n            answer[i] = grp;\n            grp = (grp + 1) % D;\n        }\n    }\n\n    // ---------- 3. consume remaining queries with dummy comparisons ----------\n    while (query_cnt < Q) {\n        // N \u2265 30, so items 0 and 1 exist and are different\n        ask(0, 1);\n    }\n\n    // ---------- 4. output the partition ----------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << answer[i];\n    }\n    cout << '\\n';\n    cout.flush();\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    int per = n / m;\n    vector<vector<int>> stacks(m);\n    for (int i = 0; i < m; ++i) {\n        stacks[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x;\n            cin >> x;\n            stacks[i].push_back(x);\n        }\n    }\n\n    using pii = pair<int, int>;\n    vector<pii> ops;\n    ops.reserve(2 * n);   // at most two operations per box\n\n    for (int v = 1; v <= n; ++v) {\n        int src = -1, pos = -1;\n        for (int i = 0; i < m; ++i) {\n            auto &st = stacks[i];\n            for (size_t j = 0; j < st.size(); ++j) {\n                if (st[j] == v) {\n                    src = i;\n                    pos = static_cast<int>(j);\n                    break;\n                }\n            }\n            if (src != -1) break;\n        }\n\n        int sz = (int)stacks[src].size();\n        if (pos == sz - 1) {                 // already on top\n            ops.emplace_back(v, 0);          // operation 2\n            stacks[src].pop_back();\n            continue;\n        }\n\n        int w = stacks[src][pos + 1];        // box directly above v\n\n        // Find destination stack != src with minimal height.\n        // If several have the same height, pick the one with the largest top value\n        // (to avoid burying small numbers that will be processed soon).\n        int best = -1;\n        int bestHeight = 1e9;\n        int bestTop = -1;                    // top value of the best stack (meaningless if empty)\n        for (int i = 0; i < m; ++i) {\n            if (i == src) continue;\n            int h = (int)stacks[i].size();\n            int top = stacks[i].empty() ? -1 : stacks[i].back();\n            if (h < bestHeight || (h == bestHeight && top > bestTop)) {\n                bestHeight = h;\n                bestTop = top;\n                best = i;\n            }\n        }\n        int dest = best;                     // guaranteed to exist (m >= 2)\n\n        // Move the suffix [w ... top] from src to dest\n        vector<int> moved;\n        moved.reserve(sz - (pos + 1));\n        for (size_t j = pos + 1; j < stacks[src].size(); ++j)\n            moved.push_back(stacks[src][j]);\n\n        stacks[src].erase(stacks[src].begin() + pos + 1, stacks[src].end());\n        stacks[dest].insert(stacks[dest].end(), moved.begin(), moved.end());\n\n        // Operation 1: move w (and everything above it)\n        ops.emplace_back(w, dest + 1);       // output uses 1\u2011based index\n        // Now v is on top of its source stack\n        ops.emplace_back(v, 0);              // operation 2: carry out v\n        stacks[src].pop_back();              // remove v\n    }\n\n    for (auto &p : ops)\n        cout << p.first << ' ' << p.second << '\\n';\n    return 0;\n}","ahc027":"#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\n    vector<string> h(N - 1), v(N);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    vector<vector<int>> d(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    /* ----- helpers to test walls ----- */\n    auto canUp = [&](int i, int j) { return i > 0 && h[i - 1][j] == '0'; };\n    auto canDown = [&](int i, int j) { return i + 1 < N && h[i][j] == '0'; };\n    auto canLeft = [&](int i, int j) { return j > 0 && v[i][j - 1] == '0'; };\n    auto canRight = [&](int i, int j) { return j + 1 < N && v[i][j] == '0'; };\n\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 oppChar[4] = {'D', 'U', 'R', 'L'};\n\n    /* ----- DFS to visit every cell ----- */\n    vector<string> visitedStr(N, string(N, '0'));\n    vector<vector<bool>> vis(N, vector<bool>(N, false));\n    string moves;\n\n    function<void(int, int)> dfs = [&](int x, int y) {\n        vis[x][y] = true;\n        for (int dir = 0; dir < 4; ++dir) {\n            int nx = x + dx[dir];\n            int ny = y + dy[dir];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            bool ok = false;\n            if (dir == 0) ok = canUp(x, y);\n            else if (dir == 2) ok = canLeft(x, y);\n            else if (dir == 1) ok = canDown(x, y);\n            else if (dir == 3) ok = canRight(x, y);\n            if (!ok || vis[nx][ny]) continue;\n            moves.push_back(dirChar[dir]);\n            dfs(nx, ny);\n            moves.push_back(oppChar[dir]);\n        }\n    };\n    dfs(0, 0);\n\n    int baseLen = (int)moves.size();\n\n    /* ----- choose neighbour of (0,0) for back\u2011and\u2011forth loops ----- */\n    struct NB {\n        int dir;          // 0:U,1:D,2:L,3:R\n        int ni, nj;\n        int val;\n        double rnd;\n    };\n    vector<NB> cand;\n    for (int dir = 0; dir < 4; ++dir) {\n        int nx = dx[dir];\n        int ny = dy[dir];\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n        bool ok = false;\n        if (dir == 0) ok = canUp(0, 0);\n        else if (dir == 2) ok = canLeft(0, 0);\n        else if (dir == 1) ok = canDown(0, 0);\n        else if (dir == 3) ok = canRight(0, 0);\n        if (!ok) continue;\n        cand.push_back({dir, nx, ny, d[nx][ny],\n                        (double)rand() / RAND_MAX});\n    }\n    /* sort by descending d, break ties randomly */\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    shuffle(cand.begin(), cand.end(), rng);\n    sort(cand.begin(), cand.end(),\n         [](const NB& a, const NB& b) {\n             if (a.val != b.val) return a.val > b.val;\n             return a.rnd < b.rnd;\n         });\n\n    const int MAX_LEN = 100000;\n    int loops = 0;\n    if (!cand.empty())\n        loops = max(0, (MAX_LEN - baseLen) / 2);\n\n    for (int i = 0; i < loops; ++i) {\n        const NB& nb = cand[i % (int)cand.size()];\n        moves.push_back(dirChar[nb.dir]);\n        moves.push_back(oppChar[nb.dir]);\n    }\n\n    cout << moves << '\\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        int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n    \n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) cin >> t[i];\n    \n    // Build the concatenated string (all t_i in given order)\n    string S;\n    for (const string& str : t) S += str;\n    int L = (int)S.size(); // L = 5 * M = 1000\n    \n    // Positions of each letter in the grid\n    vector<vector<int>> pos(26);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int idx = i * N + j;\n            pos[grid[i][j] - 'A'].push_back(idx);\n        }\n    }\n    \n    const int INF = 1e9;\n    auto manhattan = [&](int a, int b) {\n        int r1 = a / N, c1 = a % N;\n        int r2 = b / N, c2 = b % N;\n        return abs(r1 - r2) + abs(c1 - r2);\n    };\n    // Actually the lambda above has a bug: c2 should be b%N, not b%N? Let's fix later.\n        // Correct lambda:\n    auto dist = [&](int a, int b) {\n        int r1 = a / N, c1 = a % N;\n        int r2 = b / N, c2 = b % N;\n        return abs(r1 - r2) + abs(c1 - c2);\n    };\n    \n    // DP arrays: dpPrev[id] = min cost to end at cell id after processing current prefix\n    vector<int> dpPrev(N * N, INF);\n    // prev[i][id] = previous cell id for position i (0-indexed in S) ending at id\n    vector<vector<int>> prev(L, vector<int>(N * N, -1));\n    \n    // Initialize for first character\n    char firstChar = S[0];\n    for (int id : pos[firstChar - 'A']) {\n        int d = dist(si * N + sj, id);\n        dpPrev[id] = d + 1; // move + press\n        prev[0][id] = -2; // marks start\n    }\n    \n    // Iterate over the rest of S\n    for (int i = 1; i < L; ++i) {\n        char curChar = S[i];\n        char prevChar = S[i-1];\n        vector<int> dpCurr(N * N, INF);\n        for (int id : pos[curChar - 'A']) {\n            int bestCost = INF;\n            int bestPrev = -1;\n            for (int pid : pos[prevChar - 'A']) {\n                if (dpPrev[pid] == INF) continue;\n                int cand = dpPrev[pid] + dist(pid, id) + 1;\n                if (cand < bestCost) {\n                    bestCost = cand;\n                    bestPrev = pid;\n                }\n            }\n            dpCurr[id] = bestCost;\n            prev[i][id] = bestPrev;\n        }\n        dpPrev.swap(dpCurr);\n    }\n        // Find best ending cell for the whole string\n    int lastId = -1;\n    int minCost = INF;\n    char lastChar = S.back();\n    for (int id : pos[lastChar - 'A']) {\n        if (dpPrev[id] < minCost) {\n            minCost = dpPrev[id];\n            lastId = id;\n        }\n    }\n    \n    // Reconstruct path\n    vector<int> path(L);\n    path[L-1] = lastId;\n    for (int i = L-1; i > 0; --i) {\n        path[i-1] = prev[i][path[i]];\n    }\n    \n    // Output the sequence of operations\n    for (int id : path) {\n        int r = id / N;\n        int c = id % N;\n        cout << r << ' ' << c << '\\n';\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;\n\n    // Read and ignore the shapes of oil fields (not needed for this simple strategy)\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < 2 * d; ++i) {\n            int x;\n            cin >> x;\n        }\n    }\n\n    vector<pair<int, int>> oil;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << \"q 1 \" << i << ' ' << j << endl;\n            int v;\n            cin >> v;\n            if (v > 0) {\n                oil.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Output the answer\n    cout << \"a \" << oil.size();\n    for (auto [i, j] : oil) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << endl;\n\n    // Read verdict (1 if correct, 0 otherwise). Terminate regardless.\n    int verdict;\n    cin >> verdict;\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    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            int x; cin >> x;\n        }\n    }\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << k << \" 0 \" << k+1 << \" \" << W << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll MOD = 998244353LL;\n\nstruct Op {\n    int m, p, q;\n    Op() {}\n    Op(int _m, int _p, int _q) : m(_m), p(_p), q(_q) {}\n};\n\nll add_mod(ll x, ll v) {\n    ll res = x + v;\n    if (res >= MOD) res -= MOD;\n    return res;\n}\nll sub_mod(ll x, ll v) {\n    ll res = x - v;\n    if (res < 0) res += MOD;\n    return res;\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    vector<vector<ll>> a(N, vector<ll>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> a[i][j];\n    vector<array<array<ll, 3>, 3>> stamps(M);\n    for (int m = 0; m < M; ++m)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> stamps[m][i][j];\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_stamp(0, M-1);\n    uniform_int_distribution<int> dist_pos(0, N-3); // 0..6\n\n    ll best_score = -1;\n    vector<Op> best_ops;\n\n    auto start_time = chrono::high_resolution_clock::now();\n    const double time_limit = 1.95; // seconds\n\n    for (int restart = 0; restart < 5; ++restart) {\n        auto now = chrono::high_resolution_clock::now();\n        double elapsed = chrono::duration<double>(now - start_time).count();\n        if (elapsed >= time_limit) break;\n\n        vector<vector<ll>> cur_val = a;\n        ll score = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                score += cur_val[i][j];\n\n        vector<Op> ops;\n        // optional random initialization\n        int init_add = 5;\n        for (int t = 0; t < init_add; ++t) {\n            int m = dist_stamp(rng);\n            int p = dist_pos(rng);\n            int q = dist_pos(rng);\n            ll delta = 0;\n            for (int di = 0; di < 3; ++di)\n                for (int dj = 0; dj < 3; ++dj) {\n                    int i = p + di, j = q + dj;\n                    ll v = stamps[m][di][dj];\n                    ll nx = cur_val[i][j] + v;\n                    if (nx >= MOD) nx -= MOD;\n                    delta += nx - cur_val[i][j];\n                    cur_val[i][j] = nx;\n                }\n            score += delta;\n            ops.emplace_back(m, p, q);\n        }\n\n        // hill climbing with add/remove/swap\n        while (true) {\n            auto now2 = chrono::high_resolution_clock::now();\n            double elapsed2 = chrono::duration<double>(now2 - start_time).count();\n            if (elapsed2 >= time_limit) break;\n\n            ll best_delta = 0;\n            int best_type = 0; // 1=add, 2=remove, 3=swap\n            int best_m = -1, best_p = -1, best_q = -1;\n            int best_idx = -1; // for remove or swap (old op index)\n            int best_m2 = -1, best_p2 = -1, best_q2 = -1; // for swap (new op)\n\n            // try add\n            if ((int)ops.size() < K) {\n                for (int m = 0; m < M; ++m) {\n                    for (int p = 0; p <= N - 3; ++p) {\n                        for (int q = 0; q <= N - 3; ++q) {\n                            ll delta = 0;\n                            for (int di = 0; di < 3; ++di)\n                                for (int dj = 0; dj < 3; ++dj) {\n                                    int i = p + di, j = q + dj;\n                                    ll v = stamps[m][di][dj];\n                                    ll nx = cur_val[i][j] + v;\n                                    if (nx >= MOD) nx -= MOD;\n                                    delta += nx - cur_val[i][j];\n                                }\n                            if (delta > best_delta) {\n                                best_delta = delta;\n                                best_type = 1;\n                                best_m = m; best_p = p; best_q = q;\n                            }\n                        }\n                    }\n                }\n            }\n\n            // try remove\n            if ((int)ops.size() > 0) {\n                for (size_t idx = 0; idx < ops.size(); ++idx) {\n                    const Op& op = ops[idx];\n                    ll delta = 0;\n                    int m = op.m, p = op.p, q = op.q;\n                    for (int di = 0; di < 3; ++di)\n                        for (int dj = 0; dj < 3; ++dj) {\n                            int i = p + di, j = q + dj;\n                            ll v = stamps[m][di][dj];\n                            ll nx = cur_val[i][j] - v;\n                            if (nx < 0) nx += MOD;\n                            delta += nx - cur_val[i][j];\n                        }\n                    if (delta > best_delta) {\n                        best_delta = delta;\n                        best_type = 2;\n                        best_idx = (int)idx;\n                    }\n                }\n            }\n\n            // try swap (remove old, add new)\n            if ((int)ops.size() > 0 && (int)ops.size() < K) {\n                for (size_t idx_old = 0; idx_old < ops.size(); ++idx_old) {\n                    const Op& op_old = ops[idx_old];\n                    int m_old = op_old.m, p_old = op_old.p, q_old = op_old.q;\n                    for (int m_new = 0; m_new < M; ++m_new) {\n                        for (int p_new = 0; p_new <= N - 3; ++p_new) {\n                            for (int q_new = 0; q_new <= N - 3; ++q_new) {\n                                // optional: skip if same as old (no effect)\n                                if (m_old == m_new && p_old == p_new && q_old == q_new) continue;\n                                ll delta = 0;\n                                for (int i = 0; i < N; ++i) {\n                                    for (int j = 0; j < N; ++j) {\n                                        ll val = cur_val[i][j];\n                                        bool in_old = (i >= p_old && i < p_old + 3 && j >= q_old && j < q_old + 3);\n                                        bool in_new = (i >= p_new && i < p_new + 3 && j >= q_new && j < q_new + 3);\n                                        if (in_old) {\n                                            ll v_old = stamps[m_old][i - p_old][j - q_old];\n                                            val = val - v_old;\n                                            if (val < 0) val += MOD;\n                                        }\n                                        if (in_new) {\n                                            ll v_new = stamps[m_new][i - p_new][j - q_new];\n                                            val = val + v_new;\n                                            if (val >= MOD) val -= MOD;\n                                        }\n                                        delta += val - cur_val[i][j];\n                                    }\n                                }\n                                if (delta > best_delta) {\n                                    best_delta = delta;\n                                    best_type = 3;\n                                    best_idx = (int)idx_old;\n                                    best_m2 = m_new; best_p2 = p_new; best_q2 = q_new;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            if (best_delta <= 0) break;\n\n            // apply the best move\n            if (best_type == 1) { // add\n                ll delta_apply = 0;\n                for (int di = 0; di < 3; ++di)\n                    for (int dj = 0; dj < 3; ++dj) {\n                        int i = best_p + di, j = best_q + dj;\n                        ll v = stamps[best_m][di][dj];\n                        ll nx = cur_val[i][j] + v;\n                        if (nx >= MOD) nx -= MOD;\n                        delta_apply += nx - cur_val[i][j];\n                        cur_val[i][j] = nx;\n                    }\n                score += best_delta;\n                ops.emplace_back(best_m, best_p, best_q);\n            } else if (best_type == 2) { // remove\n                const Op& op = ops[best_idx];\n                ll delta_apply = 0;\n                int m = op.m, p = op.p, q = op.q;\n                for (int di = 0; di < 3; ++di)\n                    for (int dj = 0; dj < 3; ++dj) {\n                        int i = p + di, j = q + dj;\n                        ll v = stamps[m][di][dj];\n                        ll nx = cur_val[i][j] - v;\n                        if (nx < 0) nx += MOD;\n                        delta_apply += nx - cur_val[i][j];\n                        cur_val[i][j] = nx;\n                    }\n                score += best_delta;\n                ops.erase(ops.begin() + best_idx);\n            } else { // swap\n                const Op& op_old = ops[best_idx];\n                ll delta_apply = 0;\n                int m_old = op_old.m, p_old = op_old.p, q_old = op_old.q;\n                int m_new = best_m2, p_new = best_p2, q_new = best_q2;\n                for (int i = 0; i < N; ++i) {\n                    for (int j = 0; j < N; ++j) {\n                        ll val = cur_val[i][j];\n                        bool in_old = (i >= p_old && i < p_old + 3 && j >= q_old && j < q_old + 3);\n                        bool in_new = (i >= p_new && i < p_new + 3 && j >= q_new && j < q_new + 3);\n                        if (in_old) {\n                            ll v_old = stamps[m_old][i - p_old][j - q_old];\n                            val = val - v_old;\n                            if (val < 0) val += MOD;\n                        }\n                        if (in_new) {\n                            ll v_new = stamps[m_new][i - p_new][j - q_new];\n                            val = val + v_new;\n                            if (val >= MOD) val -= MOD;\n                        }\n                        delta_apply += val - cur_val[i][j];\n                        cur_val[i][j] = val;\n                    }\n                }\n                score += best_delta;\n                ops[best_idx] = Op(m_new, p_new, q_new);\n            }\n        }\n\n        if (score > best_score) {\n            best_score = score;\n            best_ops = ops;\n        }\n    }\n\n    cout << best_ops.size() << '\\n';\n    for (const Op& op : best_ops) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_TURNS = 10000;\nconst int DX[4] = {0, 0, -1, 1};\nconst int DY[4] = {-1, 1, 0, 0};\nconst char DIR_CHAR[4] = {'L', 'R', 'U', 'D'};\n\nstruct Pos {\n    int r, c;\n    bool operator==(const Pos& other) const { return r == other.r && c == other.c; }\n    bool operator<(const Pos& other) const {\n        if (r != other.r) return r < other.r;\n        return c < other.c;\n    }\n};\n\nint N;\nvector<vector<int>> A;\nint grid[5][5];\nint next_needed[5];\nint next_arrival[5];\nbool crane_holding = false;\nint held_id = -1;\nint crane_r = 0, crane_c = 0;\nlong long dispatched_count = 0;\nbool done = false;\n\nbool inside(int r, int c) {\n    return r >= 0 && r < N && c >= 0 && c < N;\n}\n\nchar move_step(int& cr, int& cc, int tr, int tc) {\n    if (cr < tr) { ++cr; return 'D'; }\n    else if (cr > tr) { --cr; return 'U'; }\n    else if (cc < tc) { ++cc; return 'R'; }\n    else if (cc > tc) { --cc; return 'L'; }\n    else return '.';\n}\n\n// Find an empty cell suitable for storage (columns 1..N-2, or column 0 if arrivals done for that row)\nPos find_empty_storage_cell() {\n    for (int r = 0; r < N; ++r) {\n        for (int c = 1; c <= N-2; ++c) {\n            if (grid[r][c] == -1) return {r, c};\n        }\n        if (next_arrival[r] == N && grid[r][0] == -1) return {r, 0};\n    }\n    // fallback (should not happen)\n    return {0, 0};\n}\n\n// Find a cell containing the specific container id (search everywhere except dispatch gates)\nPos find_container(int val) {\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            if (c == N-1) continue; // avoid dispatch gates\n            if (grid[r][c] == val) return {r, c};\n        }\n    }\n    return {-1, -1}; // not found\n}\n\n// Choose a target for pickup when not holding.\n// Sets globals: pickup_target, pickup_from_gate, pickup_row/pickup_id.\n// Returns true if a target was found.\nbool choose_pickup_target() {\n    // 1. Gate with needed container    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] != -1) {\n            int val = grid[i][0];\n            if (val == next_needed[i]) {\n                pickup_target = {i, 0};\n                pickup_from_gate = true;\n                pickup_row = i;\n                return true;\n            }\n        }\n    }\n    // 2. Gate with any container\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] != -1) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    // 3. Needed container in storage (any column except dispatch gate)\n    for (int i = 0; i < N; ++i) {\n        int need = next_needed[i];\n        if (need < i * N + N) { // still needed\n            Pos p = find_container(need);\n            if (p.r != -1) {\n                pickup_target = p;\n                pickup_from_gate = false;\n                pickup_id = need;\n                return true;\n            }\n        }\n    }\n    // 4. Gate with pending arrivals (wait for container to appear)\n    for (int i = 0; i < N; ++i) {\n        if (next_arrival[i] < N) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    return false;\n}\n\n// Release target computation after picking up\nPos pickup_target;\nbool pickup_from_gate;\nint pickup_row; // valid if pickup_from_gate\nint pickup_id;  // valid if !pickup_from_gate\nPos release_target;\n\nvoid compute_release_target_after_pickup() {\n    if (pickup_from_gate) {\n        int val = grid[pickup_target.r][pickup_target.c]; // still present before pick\n        if (val == next_needed[pickup_row]) {\n            release_target = {pickup_row, N-1};\n        } else {\n            release_target = find_empty_storage_cell();\n        }\n    } else {\n        // picked up from storage, it's a needed container\n        int row = pickup_id / N;\n        release_target = {row, N-1};\n    }\n}\n\nvoid process_arrivals() {\n    for (int i = 0; i < N; ++i) {\n        if (next_arrival[i] >= N) continue;\n        if (grid[i][0] == -1 && !(crane_holding && crane_r == i && crane_c == 0)) {\n            int container = A[i][next_arrival[i]];\n            grid[i][0] = container;\n            ++next_arrival[i];\n        }\n    }\n}\n\nvoid process_dispatch() {\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][4] != -1) {\n            grid[i][4] = -1; // dispatched and removed\n            // dispatched_count already incremented when we released at dispatch gate\n        }\n    }\n}\n\nchar decide_action() {\n    if (done) return '.';\n    if (phase == IDLE) {\n        if (crane_holding) {\n            return '.'; // should not happen\n        }\n        if (!choose_pickup_target()) {\n            done = true;\n            return '.';\n        }\n        phase = MOVING_TO_PICKUP;\n        // fall through    }\n    if (phase == MOVING_TO_PICKUP) {\n        char ch = move_step(crane_r, crane_c, pickup_target.r, pickup_target.c);\n        if (crane_r == pickup_target.r && crane_c == pickup_target.c) {\n            phase = AT_PICKUP;\n        }\n        return ch;\n    }\n    if (phase == AT_PICKUP) {\n        if (!crane_holding && grid[crane_r][crane_c] != -1) {\n            // we will pick up\n            // compute release target now\n            compute_release_target_after_pickup();\n            phase = MOVING_TO_RELEASE;\n            return 'P';\n        } else {\n            return '.';\n        }\n    }\n    if (phase == MOVING_TO_RELEASE) {\n        char ch = move_step(crane_r, crane_c, release_target.r, release_target.c);\n        if (crane_r == release_target.r && crane_c == release_target.c) {\n            phase = AT_RELEASE;\n        }\n        return ch;\n    }\n    if (phase == AT_RELEASE) {\n        if (crane_holding) {\n            phase = IDLE;\n            return 'Q';\n        } else {\n            return '.';\n        }\n    }\n    return '.';\n}\n\nvoid apply_action(char ch) {\n    if (ch == '.') return;\n    if (ch == 'U') { /* already moved in move_step */ }\n    else if (ch == 'D') { /* moved */ }\n    else if (ch == 'L') { /* moved */ }\n    else if (ch == 'R') { /* moved */ }\n    else if (ch == 'P') {\n        // pick up\n        assert(!crane_holding);\n        assert(grid[crane_r][crane_c] != -1);\n        held_id = grid[crane_r][crane_c];\n        crane_holding = true;\n        grid[crane_r][crane_c] = -1;\n        // nothing else to update\n    } else if (ch == 'Q') {\n        // release\n        assert(crane_holding);\n        assert(grid[crane_r][crane_c] == -1);\n        grid[crane_r][crane_c] = held_id;\n        if (crane_c == N-1) { // dispatch gate\n            int row = crane_r;\n            ++next_needed[row];\n            ++dispatched_count;\n        } else {\n            // storage cell, nothing else        }\n        crane_holding = false;\n        held_id = -1;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> N;\n    A.assign(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    }\n    // init\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = -1;\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        next_needed[i] = i * N;\n        next_arrival[i] = 0;\n    }\n    crane_r = 0; crane_c = 0;\n    crane_holding = false;\n    held_id = -1;\n    dispatched_count = 0;\n    done = false;\n    phase = IDLE;\n\n    string actions_large;\n    int turn = 0;\n    while (!turn >= MAX_TURNS && !done) {\n        process_arrivals();\n        char ch = decide_action();\n        actions_large += ch;\n        apply_action(ch);\n        process_dispatch();\n        ++turn;\n        if (dispatched_count == N * N) done = true;\n    }\n    // output\n    cout << actions_large << \"\\n\";\n    string small = \"B\";\n    if ((int)actions_large.size() > 1) {\n        small += string(actions_large.size() - 1, '.');\n    } else {\n        small += \".\"; // ensure at least length 1\n    }\n    for (int i = 1; i < N; ++i) {\n        cout << small << \"\\n\";\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int r, c;\n    int amt; // amount of soil to move (positive for both sources and targets)\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>> 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<Cell> sources, targets;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            int val = h[i][j];\n            if (val > 0)\n                sources.push_back({i, j, val});\n            else if (val < 0)\n                targets.push_back({i, j, -val});\n        }\n\n    struct Transfer {\n        int sr, sc, tr, tc;\n        int amt;\n    };\n    vector<Transfer> transfers;\n\n    while (true) {\n        int best_i = -1, best_j = -1;\n        int best_dist = INT_MAX;\n        for (size_t i = 0; i < sources.size(); ++i) {\n            if (sources[i].amt <= 0) continue;\n            for (size_t j = 0; j < targets.size(); ++j) {\n                if (targets[j].amt <= 0) continue;\n                int dist = abs(sources[i].r - targets[j].r) + abs(sources[i].c - targets[j].c);\n                if (dist < best_dist) {\n                    best_dist = dist;\n                    best_i = (int)i;\n                    best_j = (int)j;\n                }\n            }\n        }\n        if (best_i == -1) break;\n        int take = min(sources[best_i].amt, targets[best_j].amt);\n        transfers.push_back({sources[best_i].r, sources[best_i].c,\n                             targets[best_j].r, targets[best_j].c, take});\n        sources[best_i].amt -= take;\n        targets[best_j].amt -= take;\n    }\n\n    vector<string> ops;\n    auto add_move = [&](int &r, int &c, int tr, int tc) {\n        while (r < tr) { ops.push_back(\"D\"); ++r; }\n        while (r > tr) { ops.push_back(\"U\"); --r; }\n        while (c < tc) { ops.push_back(\"R\"); ++c; }\n        while (c > tc) { ops.push_back(\"L\"); --c; }\n        r = tr; c = tc;\n    };\n\n    int cr = 0, cc = 0;\n    long long load = 0;\n    for (Transfer &t : transfers) {\n        // depot -> source (empty)\n        add_move(cr, cc, t.sr, t.sc);\n        // load\n        ops.push_back(\"+\" + to_string(t.amt));\n        load += t.amt;\n        // source -> target (loaded)\n        add_move(t.sr, t.sc, t.tr, t.tc);\n        // unload\n        ops.push_back(\"-\" + to_string(t.amt));\n        load -= t.amt;\n        // target -> depot (empty)\n        add_move(t.tr, t.tc, 0, 0);\n        cr = 0; cc = 0;\n        assert(load == 0);\n    }\n\n    for (const string &s : ops)\n        cout << s << '\\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    int N, M, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> X(seed_count, vector<int>(M));\n    for (int i = 0; i < seed_count; ++i) {\n        for (int j = 0; j < M; ++j) {\n            cin >> X[i][j];\n        }\n    }\n\n    // Order of cells: higher degree first (inner -> edges -> corners)\n    struct Cell { int deg, i, j; };\n    vector<Cell> cells;\n    cells.reserve(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int deg = (i > 0) + (i < N - 1) + (j > 0) + (j < N - 1);\n            cells.push_back({deg, i, j});\n        }\n    }\n    sort(cells.begin(), cells.end(), [](const Cell& a, const Cell& b) {\n        return a.deg > b.deg;\n    });\n    vector<pair<int,int>> pos_order;\n    pos_order.reserve(N * N);\n    for (const auto& c : cells) {\n        pos_order.emplace_back(c.i, c.j);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        // Max value per attribute\n        vector<int> max_attr(M, 0);\n        for (int id = 0; id < seed_count; ++id) {\n            for (int l = 0; l < M; ++l) {\n                if (X[id][l] > max_attr[l]) max_attr[l] = X[id][l];\n            }\n        }\n\n        // Score: (#attributes at max) * 10000 + sum of values\n        using SeedScore = pair<long long, int>;\n        vector<SeedScore> scores;\n        scores.reserve(seed_count);\n        for (int id = 0; id < seed_count; ++id) {\n            int w = 0;\n            long long sum = 0;\n            for (int l = 0; l < M; ++l) {\n                sum += X[id][l];\n                if (X[id][l] == max_attr[l]) ++w;\n            }\n            long long score = (long long)w * 10000LL + sum;\n            scores.emplace_back(score, id);\n        }\n        sort(scores.begin(), scores.end(),\n             [](const SeedScore& a, const SeedScore& b) { return a.first > b.first; });\n\n        // Assign top N^2 seeds to cells in pos_order\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        for (int idx = 0; idx < N * N; ++idx) {\n            int sid = scores[idx].second;\n            int i = pos_order[idx].first;\n            int j = pos_order[idx].second;\n            A[i][j] = sid;\n        }\n\n        // Output placement\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << A[i][j];\n                if (j + 1 < N) cout << ' ';\n                else cout << '\\n';\n            }\n        }\n        cout.flush();\n\n        // Read next generation\n        for (int id = 0; id < seed_count; ++id) {\n            for (int l = 0; l < M; ++l) {\n                if (!(cin >> X[id][l])) return 0;\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\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    // Current and target grids\n    vector<vector<int>> cur(N, vector<int>(N));\n    vector<vector<int>> target(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            cur[i][j] = s[i][j] - '0';\n            target[i][j] = t[i][j] - '0';\n        }\n    \n    // Design a simple 2-vertex arm: root (0) and leaf (1) with edge length 1.\n    const int Vp = 2;\n    cout << Vp << '\\n';\n    cout << \"0 1\" << '\\n';   // parent of vertex 1 is 0, length = 1\n    cout << \"0 0\" << '\\n';   // initial root position (top\u2011left)\n    \n    // Direction vectors: 0=right,1=down,2=left,3=up\n    const int DX[4] = {0, 1, 0, -1};\n    const int DY[4] = {1, 0, -1, 0};\n    const char DIR_CHAR[4] = {'R', 'D', 'L', 'U'};\n    \n    int rootX = 0, rootY = 0;   // root coordinates\n    int leafDir = 0;            // current direction of edge (0,1)\n    bool holding = false;       // whether the leaf holds a takoyaki\n    \n    const int MAX_TURNS = 50000;\n    vector<string> ops;\n    ops.reserve(MAX_TURNS);\n    \n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        // Check if all takoyaki are already at targets\n        int srcCnt = 0, dstCnt = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j) {\n                if (cur[i][j] == 1 && target[i][j] == 0) ++srcCnt;\n                if (cur[i][j] == 0 && target[i][j] == 1) ++dstCnt;\n            }\n        if (srcCnt == 0 && dstCnt == 0) break;\n        \n        // Determine desired root position and leaf direction\n        int desiredRX = -1, desiredRY = -1;\n        int desiredDir = -1;\n        \n        if (!holding) {\n            // Look for any source cell (needs to pick up)\n            bool found = false;\n            for (int i = 0; i < N && !found; ++i)\n                for (int j = 0; j < N && !found; ++j) {\n                    if (cur[i][j] == 1 && target[i][j] == 0) {\n                        // Try the four ways to place the leaf on (i,j)\n                        for (int d = 0; d < 4; ++d) {\n                            int rx = i - DX[d];\n                            int ry = j - DY[d];\n                            if (rx >= 0 && rx < N && ry >= 0 && ry < N) {\n                                desiredRX = rx;\n                                desiredRY = ry;\n                                desiredDir = d;\n                                found = true;\n                                break;\n                            }\n                        }\n                    }\n                }\n            if (!found) {   // should not happen because N>=15                // fallback: do nothing\n                ops.emplace_back(\"....\");\n                continue;\n            }\n        } else {\n            // Look for any target cell (needs to drop)\n            bool found = false;\n            for (int i = 0; i < N && !found; ++i)\n                for (int j = 0; j < N && !found; ++j) {\n                    if (cur[i][j] == 0 && target[i][j] == 1) {\n                        for (int d = 0; d < 4; ++d) {\n                            int rx = i - DX[d];\n                            int ry = j - DY[d];\n                            if (rx >= 0 && rx < N && ry >= 0 && ry < N) {\n                                desiredRX = rx;\n                                desiredRY = ry;\n                                desiredDir = d;\n                                found = true;\n                                break;\n                            }\n                        }\n                    }\n                }\n            if (!found) {\n                ops.emplace_back(\"....\");\n                continue;\n            }\n        }\n        \n        // ---- Operation 1: move the whole arm ----\n        char moveChar = '.';\n        if (rootX < desiredRX) { moveChar = 'D'; ++rootX; }\n        else if (rootX > desiredRX) { moveChar = 'U'; --rootX; }\n        else if (rootY < desiredRY) { moveChar = 'R'; ++rootY; }\n        else if (rootY > desiredRY) { moveChar = 'L'; --rootY; }\n        // else stay\n        \n        // ---- Operation 2: rotate subtree at vertex 1 (the leaf) ----\n        char rotChar = '.';\n        int diff = (desiredDir - leafDir + 4) & 3;\n        if (diff != 0) {\n            if (diff == 2) {          // two steps either way; choose right\n                rotChar = 'R';\n                leafDir = (leafDir + 1) & 3;\n            } else if (diff == 1) {   // need one clockwise step\n                rotChar = 'R';\n                leafDir = (leafDir + 1) & 3;\n            } else {                  // diff == 3 -> one counter\u2011clockwise step\n                rotChar = 'L';\n                leafDir = (leafDir + 3) & 3;\n            }\n        }\n                // ---- Operation 3: action at fingertips ----\n        // Vertex 0 (root) is never a leaf -> op[2] stays '.'\n        int leafX = rootX + DX[leafDir];\n        int leafY = rootY + DY[leafDir];\n        bool act = false;\n        if (leafX >= 0 && leafX < N && leafY >= 0 && leafY < N) {\n            if (!holding && cur[leafX][leafY] == 1 && target[leafX][leafY] == 0) {\n                // pick up\n                cur[leafX][leafY] = 0;\n                holding = true;\n                act = true;\n            } else if (holding && cur[leafX][leafY] == 0 && target[leafX][leafY] == 1) {\n                // drop\n                cur[leafX][leafY] = 1;\n                holding = false;\n                act = true;\n            }\n        }\n        char actChar = act ? 'P' : '.';\n        \n        // Build operation string: [move][rot][root action][leaf action]\n        string op(4, '.');\n        op[0] = moveChar;\n        op[1] = rotChar;\n        op[2] = '.';          // root is not a leaf\n        op[3] = actChar;\n        ops.push_back(op);\n    }\n    \n    // Output the operation sequence\n    for (const string& line : ops) cout << line << '\\n';\n    return 0;\n}","ahc039":"#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    const int MAXC = 100000;\n    vector<tuple<int, int, int>> pts;\n    pts.reserve(2 * N);\n    for (int i = 0; i < 2 * N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        int w = (i < N) ? 1 : -1; // +1 for mackerel, -1 for sardine        pts.emplace_back(x, y, w);\n    }\n\n    // Build maps: x -> list of (y, weight), y -> list of (x, weight)\n    unordered_map<int, vector<pair<int, int>>> x_to_ys;\n    unordered_map<int, vector<pair<int, int>>> y_to_xs;\n    for (auto &[x, y, w] : pts) {\n        x_to_ys[x].emplace_back(y, w);\n        y_to_xs[y].emplace_back(x, w);\n    }\n    for (auto &kv : x_to_ys) sort(kv.second.begin(), kv.second.end());\n    for (auto &kv : y_to_xs) sort(kv.second.begin(), kv.second.end());\n\n    // Helper to sum weights of points with fixed x and y in [y1, y2] (inclusive)\n    auto sumVert = [&](int x, int y1, int y2) -> int {\n        auto it = x_to_ys.find(x);\n        if (it == x_to_ys.end()) return 0;\n        const auto &vec = it->second;\n        int s = 0;\n        for (auto [y, w] : vec) {\n            if (y < y1) continue;\n            if (y > y2) break;\n            s += w;\n        }\n        return s;\n    };\n    // Helper to sum weights of points with fixed y and x in [x1, x2] (inclusive)\n    auto sumHoriz = [&](int y, int x1, int x2) -> int {\n        auto it = y_to_xs.find(y);\n        if (it == y_to_xs.end()) return 0;\n        const auto &vec = it->second;\n        int s = 0;\n        for (auto [x, w] : vec) {\n            if (x < x1) continue;\n            if (x > x2) break;\n            s += w;\n        }\n        return s;\n    };\n\n    long long bestScore = LLONG_MIN;\n    int bestX1 = 0, bestX2 = 0, bestY1 = 0, bestY2 = 0;\n\n    // Use a subset of mackerels as seeds to reduce time\n    const int seedCount = min(N, 100);\n    vector<int> seeds;\n    for (int i = 0; i < seedCount; ++i) seeds.push_back(i);\n    random_shuffle(seeds.begin(), seeds.end());\n\n    for (int idx : seeds) {\n        int mx = get<0>(pts[idx]);\n        int my = get<1>(pts[idx]);\n        int x1 = mx, x2 = mx, y1 = my, y2 = my;\n        long long score = 1; // weight of the seed mackerel        // ----- Expansion phase -----\n        const int maxExpansions = 200;\n        int expansions = 0;\n        while (expansions < maxExpansions) {\n            int width = x2 - x1;\n            int height = y2 - y1;\n            int remaining = 200000 - (width + height); // max extra width+height allowed\n            if (remaining <= 0) break;\n\n            int bestGain = 0, bestDir = -1;\n            // left\n            if (x1 > 0) {\n                int g = sumVert(x1 - 1, y1, y2);\n                if (g > bestGain) { bestGain = g; bestDir = 0; }\n            }\n            // right\n            if (x2 < MAXC) {\n                int g = sumVert(x2 + 1, y1, y2);\n                if (g > bestGain) { bestGain = g; bestDir = 1; }\n            }\n            // down\n            if (y1 > 0) {\n                int g = sumHoriz(y1 - 1, x1, x2);\n                if (g > bestGain) { bestGain = g; bestDir = 2; }\n            }\n            // up\n            if (y2 < MAXC) {\n                int g = sumHoriz(y2 + 1, x1, x2);\n                if (g > bestGain) { bestGain = g; bestDir = 3; }\n            }\n            if (bestGain <= 0) break; // no profitable side\n\n            // apply expansion\n            switch (bestDir) {\n                case 0: { x1--; break; }\n                case 1: { x2++; break; }\n                case 2: { y1--; break; }\n                case 3: { y2++; break; }\n            }\n            score += bestGain;\n            ++expansions;\n        }\n\n        // ----- Shrinking phase -----\n        while (true) {\n            int width = x2 - x1;\n            int height = y2 - y1;\n            int bestGain = 0; // we look for the most negative gain\n            int bestDir = -1;\n\n            if (width >= 2) {\n                int gl = sumVert(x1, y1, y2);\n                int gr = sumVert(x2, y1, y2);\n                if (gl < bestGain) { bestGain = gl; bestDir = 0; }\n                if (gr < bestGain) { bestGain = gr; bestDir = 1; }\n            }\n            if (height >= 2) {\n                int gd = sumHoriz(y1, x1, x2);\n                int gu = sumHoriz(y2, x1, x2);\n                if (gd < bestGain) { bestGain = gd; bestDir = 2; }\n                if (gu < bestGain) { bestGain = gu; bestDir = 3; }\n            }\n            if (bestGain >= 0) break; // no side whose removal improves score\n\n            // remove the chosen side\n            switch (bestDir) {\n                case 0: { x1++; score -= bestGain; break; }\n                case 1: { x2--; score -= bestGain; break; }\n                case 2: { y1++; score -= bestGain; break; }\n                case 3: { y2--; score -= bestGain; break; }\n            }\n        }\n\n        // Ensure at least 1x1 rectangle (avoid zero-area)\n        if (x1 == x2) {\n            if (x2 < MAXC) ++x2;\n            else if (x1 > 0) --x1;\n        }\n        if (y1 == y2) {\n            if (y2 < MAXC) ++y2;\n            else if (y1 > 0) --y1;\n        }\n\n        if (score > bestScore) {\n            bestScore = score;\n            bestX1 = x1; bestX2 = x2; bestY1 = y1; bestY2 = y2;\n        }\n    }\n\n    // Output the rectangle (counter\u2011clockwise)\n    cout << 4 << '\\n';\n    cout << bestX1 << ' ' << bestY1 << '\\n';\n    cout << bestX2 << ' ' << bestY1 << '\\n';\n    cout << bestX2 << ' ' << bestY2 << '\\n';\n    cout << bestX1 << ' ' << bestY2 << '\\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, sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    // Read the observed (noisy) widths and heights; they are not needed for the trivial strategy.\n    vector<pair<int,int>> obs(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> obs[i].first >> obs[i].second;\n    }\n\n    // Repeat T times: output an empty placement (n = 0) and read the dummy measurement.\n    for (int t = 0; t < T; ++t) {\n        cout << 0 << '\\n';\n        cout.flush();\n\n        int Wp, Hp;\n        if (!(cin >> Wp >> Hp)) break;   // end if input fails (should not happen)\n        // The measured values are ignored; we simply proceed to the next turn.\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    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    // read and ignore coordinates\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    const int trials = 80; // number of random orders to try\n    long long bestScore = LLONG_MIN;\n    vector<int> bestParent(N, -1);\n    \n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    for (int t = 0; t < trials; ++t) {\n        // generate random tie\u2011breaker keys\n        vector<uint64_t> key(N);\n        for (int i = 0; i < N; ++i) key[i] = uniform_int_distribution<uint64_t>(0, UINT64_MAX)(rng);\n        \n        // order by increasing beauty, then by random key\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 (A[a] != A[b]) return A[a] < A[b];\n                 return key[a] < key[b];\n             });\n        \n        vector<int> depth(N, -1);\n        vector<int> parent(N, -1);\n        long long curScore = 0;\n        \n        for (int v : order) {\n            bool assigned = false;\n            // try to attach at the largest possible depth (<= H)\n            for (int d = H; d >= 1; --d) {\n                int need = d - 1;\n                for (int u : adj[v]) {\n                    if (depth[u] == need) {\n                        parent[v] = u;\n                        depth[v] = d;\n                        assigned = true;\n                        break;\n                    }\n                }\n                if (assigned) break;\n            }\n            if (!assigned) {\n                depth[v] = 0;   // root\n                parent[v] = -1;\n            }\n            curScore += 1LL * (depth[v] + 1) * A[v];\n        }\n        \n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestParent = parent;\n        }\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << bestParent[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 Move { char d; int p; };\n    vector<Move> moves;\n    moves.reserve(4 * N * N);\n\n    auto shiftColUp = [&](int j) {\n        for (int i = 0; i + 1 < N; ++i) board[i][j] = board[i + 1][j];\n        board[N - 1][j] = '.';\n    };\n    auto shiftColDown = [&](int j) {\n        for (int i = N - 1; i > 0; --i) board[i][j] = board[i - 1][j];\n        board[0][j] = '.';\n    };\n    auto shiftRowLeft = [&](int i) {\n        for (int j = 0; j + 1 < N; ++j) board[i][j] = board[i][j + 1];\n        board[i][N - 1] = '.';\n    };\n    auto shiftRowRight = [&](int i) {\n        for (int j = N - 1; j > 0; --j) board[i][j] = board[i][j - 1];\n        board[i][0] = '.';\n    };\n\n    while (true) {\n        int si = -1, sj = -1;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (board[i][j] == 'x') {\n                    si = i; sj = j;\n                    break;\n                }\n            }\n            if (si != -1) break;\n        }\n        if (si == -1) break;   // no Oni left\n\n        int i = si, j = sj;\n        bool up = true, down = true, left = true, right = true;\n        for (int ii = 0; ii < i; ++ii)\n            if (board[ii][j] == 'o') { up = false; break; }\n        for (int ii = i + 1; ii < N; ++ii)\n            if (board[ii][j] == 'o') { down = false; break; }\n        for (int jj = 0; jj < j; ++jj)\n            if (board[i][jj] == 'o') { left = false; break; }\n        for (int jj = j + 1; jj < N; ++jj)\n            if (board[i][jj] == 'o') { right = false; break; }\n\n        int dir; // 0:U, 1:D, 2:L, 3:R\n        if (up) dir = 0;\n        else if (down) dir = 1;\n        else if (left) dir = 2;\n        else dir = 3;\n\n        if (dir == 0) { // shift column j upward\n            for (int k = 0; k <= i; ++k) {\n                moves.push_back({ 'U', j });\n                shiftColUp(j);\n            }\n        } else if (dir == 1) { // shift column j downward\n            for (int k = 0; k < N - i; ++k) {\n                moves.push_back({ 'D', j });\n                shiftColDown(j);\n            }\n        } else if (dir == 2) { // shift row i left\n            for (int k = 0; k <= j; ++k) {\n                moves.push_back({ 'L', i });\n                shiftRowLeft(i);\n            }\n        } else { // shift row i right\n            for (int k = 0; k < N - j; ++k) {\n                moves.push_back({ 'R', i });\n                shiftRowRight(i);\n            }\n        }\n    }\n\n    // safety check (can be removed in final version)\n    assert((int)moves.size() <= 4 * N * N);\n\n    for (auto &mv : moves)\n        cout << mv.d << ' ' << mv.p << '\\n';\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nll simulate(const vector<int>& a, const vector<int>& b, const vector<int>& target, vector<int>& cnt) {\n    int N = (int)a.size();\n    int L = (int)target.size();\n    cnt.assign(N, 0);\n    int cur = 0;\n    cnt[cur] = 1; // week 1    for (int week = 2; week <= L; ++week) {\n        int nx = (cnt[cur] & 1) ? a[cur] : b[cur];\n        cur = nx;\n        ++cnt[cur];\n    }\n    ll err = 0;\n    for (int i = 0; i < N; ++i) {\n        ll diff = (ll)cnt[i] - (ll)target[i];\n        if (diff < 0) diff = -diff;\n        err += diff;\n    }\n    return err;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, L;\n    cin >> N >> L;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    // initial solution: round-robin\n    vector<int> a(N), b(N);\n    for (int i = 0; i < N; ++i) {\n        a[i] = b[i] = (i + 1) % N;\n    }\n\n    vector<int> cnt(N);\n    ll cur_err = simulate(a, b, T, cnt);\n    ll best_err = cur_err;\n    vector<int> best_a = a, best_b = b;\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_node(0, N - 1);\n    uniform_int_distribution<int> dist_choice(0, 1); // 0 -> a, 1 -> b    uniform_real_distribution<double> dist_real(0.0, 1.0);\n\n    auto guided_move = [&](const vector<int>& cnt_cur, int& i, int& which, int& j) {\n        vector<int> deficit(N);\n        int total_over = 0, total_under = 0;\n        for (int k = 0; k < N; ++k) {\n            int d = T[k] - cnt_cur[k];\n            deficit[k] = d;\n            if (d > 0) total_under += d;\n            else if (d < 0) total_over -= d;\n        }\n        if (total_over == 0) return false; // fallback to random\n        // pick over node i with probability proportional to -deficit[i]\n        int r = uniform_int_distribution<int>(0, total_over - 1)(rng);\n        int acc = 0;\n        i = 0;\n        while (i < N) {\n            int d = -deficit[i];\n            if (d > 0) {\n                if (r < acc + d) break;\n                acc += d;\n            }\n            ++i;\n        }\n        // pick under node j with probability proportional to deficit[j]\n        int r2 = uniform_int_distribution<int>(0, total_under - 1)(rng);\n        int acc2 = 0;\n        j = 0;\n        while (j < N) {\n            int d = deficit[j];\n            if (d > 0) {\n                if (r2 < acc2 + d) break;\n                acc2 += d;\n            }\n            ++j;\n        }\n        which = dist_choice(rng); // random choose a or b to modify\n        return true;\n    };\n\n    const int MAX_ITER = 500;\n    const double COOLING = 0.998;\n\n    for (int restart = 0; restart < 3; ++restart) {\n        // reset to round-robin for each restart (optional)\n        for (int i = 0; i < N; ++i) a[i] = b[i] = (i + 1) % N;\n        cur_err = simulate(a, b, T, cnt);\n        if (cur_err < best_err) {\n            best_err = cur_err;\n            best_a = a;\n            best_b = b;\n        }\n        double Ttemp = (double)cur_err; // temperature\n        for (int it = 0; it < MAX_ITER; ++it) {\n            int i, which, j;\n            bool use_guided = guided_move(cnt, i, which, j);\n            if (!use_guided) {\n                i = dist_node(rng);\n                which = dist_choice(rng);\n                j = dist_node(rng);\n            }\n            // apply move\n            vector<int> a2 = a, b2 = b;\n            if (which == 0) a2[i] = j;\n            else b2[i] = j;\n            // simulate move\n            vector<int> cnt2(N);\n            ll err2 = simulate(a2, b2, T, cnt2);\n            bool accept = false;\n            if (err2 < cur_err) accept = true;\n            else {\n                double prob = exp((cur_err - err2) / Ttemp);\n                if (dist_real(rng) < prob) accept = true;\n            }\n            if (accept) {\n                a = a2;\n                b = b2;\n                cur_err = err2;\n                cnt = cnt2;\n                if (err2 < best_err) {\n                    best_err = err2;\n                    best_a = a;\n                    best_b = b;\n                }\n            }\n            Ttemp *= COOLING;\n            if (Ttemp < 1e-5) break;\n        }\n    }\n\n    // output best solution    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    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        // centre of each rectangle (integer division)\n    vector<int> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        cx[i] = (lx[i] + rx[i]) / 2;\n        cy[i] = (ly[i] + ry[i]) / 2;\n    }\n    \n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](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 k = 0; k < M; ++k) {\n        int sz = G[k];\n        vector<int> grp;\n        grp.reserve(sz);\n        for (int i = 0; i < sz; ++i) grp.push_back(idx[pos++]);\n        groups.push_back(move(grp));\n    }\n    \n    // answer edges per group\n    vector<vector<pair<int,int>>> ansEdges(M);\n    ansEdges.reserve(M);\n    int usedQueries = 0;\n    for (int k = 0; k < M; ++k) {\n        const auto& g = groups[k];\n        int sz = (int)g.size();\n        for (int i = 0; i + 1 < sz; i += 2) {\n            if (i + 2 < sz) {\n                // query a triple\n                int a = g[i];\n                int b = g[i+1];\n                int c = g[i+2];\n                cout << \"? 3 \" << a << ' ' << b << ' ' << c << '\\n';\n                cout.flush();\n                ++usedQueries;\n                int u1, v1, u2, v2;\n                cin >> u1 >> v1;\n                cin >> u2 >> v2;\n                ansEdges[k].emplace_back(u1, v1);\n                ansEdges[k].emplace_back(u2, v2);\n            } else {\n                // only a pair left, no query needed\n                ansEdges[k].emplace_back(g[i], g[i+1]);\n            }\n        }\n    }\n    \n    // output the answer\n    cout << \"!\\n\";\n    cout.flush();\n    for (int k = 0; k < M; ++k) {\n        // cities of the group\n        for (size_t i = 0; i < groups[k].size(); ++i) {\n            if (i) cout << ' ';\n            cout << groups[k][i];\n        }\n        cout << '\\n';\n        // edges of the group\n        for (auto &e : ansEdges[k]) {\n            cout << e.first << ' ' << e.second << '\\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>> pts(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> pts[i].first >> pts[i].second;\n    }\n    \n    for (int k = 0; k + 1 < M; ++k) {\n        int ci = pts[k].first, cj = pts[k].second;\n        int ni = pts[k+1].first, nj = pts[k+1].second;\n        \n        while (ci < ni) { cout << \"M D\\n\"; ++ci; }\n        while (ci > ni) { cout << \"M U\\n\"; --ci; }\n        while (cj < nj) { cout << \"M R\\n\"; ++cj; }\n        while (cj > nj) { cout << \"M L\\n\"; --cj; }\n    }\n    \n    return 0;\n}"},"8":{"ahc001":"#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<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    const int W = 10000, H = 10000;\n    size_t totalCells = static_cast<size_t>(W) * H;\n    vector<uint8_t> occ(totalCells, 0); // 0 = free, else company id+1\n    vector<int> a(n), b(n), c(n), d(n);\n    vector<long long> area(n, 1);\n    for (int i = 0; i < n; ++i) {\n        a[i] = x[i];\n        b[i] = y[i];\n        c[i] = x[i] + 1;\n        d[i] = y[i] + 1;\n        occ[static_cast<size_t>(b[i]) * W + a[i]] = static_cast<uint8_t>(i + 1);\n    }\n\n    auto try_expand = [&](int i) -> bool {\n        if (area[i] >= r[i]) return false;\n        long long deficit = r[i] - area[i];\n        int best_dir = -1; // 0:left,1:right,2:down,3:up\n        int best_strip = 0;\n\n        int width  = c[i] - a[i];\n        int height = d[i] - b[i];\n\n        // left\n        if (a[i] > 0) {\n            int strip = height; // area added by expanding left one column\n            if (strip <= deficit) {\n                int xcol = a[i] - 1;\n                bool free = true;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    if (occ[static_cast<size_t>(yc) * W + xcol]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 0;\n                    best_strip = strip;\n                }\n            }\n        }\n        // right\n        if (c[i] < W) {\n            int strip = height;\n            if (strip <= deficit) {\n                int xcol = c[i];\n                bool free = true;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    if (occ[static_cast<size_t>(yc) * W + xcol]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 1;\n                    best_strip = strip;\n                }\n            }\n        }\n        // down\n        if (b[i] > 0) {\n            int strip = width;\n            if (strip <= deficit) {\n                int yrow = b[i] - 1;\n                bool free = true;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    if (occ[static_cast<size_t>(yrow) * W + xc]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 2;\n                    best_strip = strip;\n                }\n            }\n        }\n        // up\n        if (d[i] < H) {\n            int strip = width;\n            if (strip <= deficit) {\n                int yrow = d[i];\n                bool free = true;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    if (occ[static_cast<size_t>(yrow) * W + xc]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 3;\n                    best_strip = strip;\n                }\n            }\n        }\n        if (best_dir == -1) return false;\n\n        // perform the expansion\n        switch (best_dir) {\n            case 0: { // left\n                int xcol = a[i] - 1;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    occ[static_cast<size_t>(yc) * W + xcol] = static_cast<uint8_t>(i + 1);\n                }\n                a[i] -= 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 1: { // right\n                int xcol = c[i];\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    occ[static_cast<size_t>(yc) * W + xcol] = static_cast<uint8_t>(i + 1);\n                }\n                c[i] += 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 2: { // down\n                int yrow = b[i] - 1;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    occ[static_cast<size_t>(yrow) * W + xc] = static_cast<uint8_t>(i + 1);\n                }\n                b[i] -= 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 3: { // up\n                int yrow = d[i];\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    occ[static_cast<size_t>(yrow) * W + xc] = static_cast<uint8_t>(i + 1);\n                }\n                d[i] += 1;\n                area[i] += best_strip;\n                break;\n            }\n        }\n        return true;\n    };\n\n    vector<bool> active(n, true);\n    deque<int> q;\n    for (int i = 0; i < n; ++i) {\n        if (area[i] < r[i]) q.push_back(i);\n        else active[i] = false;\n    }\n\n    while (!q.empty()) {\n        int i = q.front();\n        q.pop_front();\n        if (!active[i]) continue;\n        if (area[i] >= r[i]) {\n            active[i] = false;\n            continue;\n        }\n        if (try_expand(i)) {\n            if (area[i] < r[i]) {\n                q.push_back(i);\n            }\n        } else {\n            active[i] = false;\n        }\n    }\n\n    for (int i = 0; i < n; ++i) {\n        cout << a[i] << ' ' << b[i] << ' ' << c[i] << ' ' << d[i] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Result {\n    string path;\n    int score;\n};\n\nResult simulate(int si, int sj, const vector<vector<int>>& t,\n                const vector<vector<int>>& p, int M, int seed) {\n    vector<vector<bool>> usedCell(50, vector<bool>(50, false));\n    vector<bool> usedTile(M, false);\n    \n    int ci = si, cj = sj;\n    usedCell[ci][cj] = true;\n    int startTile = t[ci][cj];\n    usedTile[startTile] = true;\n    \n    string path;\n    int score = p[ci][cj];\n    int visitedTiles = 1;\n    mt19937 rng(seed);\n        const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char dirChar[4] = {'U', 'D', 'L', 'R'};\n    \n    while (true) {\n        struct Candidate {\n            int dir;      // 0..3\n            int forward;  // onward degree\n            int val;      // p of neighbour\n        };\n        vector<Candidate> cand;\n        for (int d = 0; d < 4; ++d) {\n            int ni = ci + di[d];\n            int nj = cj + dj[d];\n            if (ni < 0 || ni >= 50 || nj < 0 || nj >= 50) continue;\n            if (usedCell[ni][nj]) continue;\n            int tid = t[ni][nj];\n            if (usedTile[tid]) continue;\n            \n            int fwd = 0;\n            for (int d2 = 0; d2 < 4; ++d2) {\n                int ni2 = ni + di[d2];\n                int nj2 = nj + dj[d2];\n                if (ni2 < 0 || ni2 >= 50 || nj2 < 0 || nj2 >= 50) continue;\n                if (usedCell[ni2][nj2]) continue;\n                int tid2 = t[ni2][nj2];\n                if (usedTile[tid2]) continue;\n                ++fwd;\n            }\n            cand.push_back({d, fwd, p[ni][nj]});\n        }\n        if (cand.empty()) break;\n        \n        // exploration probability: higher early, lower later\n        double explore = 0.1 * (1.0 - visitedTiles / (double)M);\n        uniform_real_distribution<double> realDist(0.0, 1.0);\n        int chosen;\n        if (realDist(rng) < explore) {\n            // random move\n            uniform_int_distribution<int> intDist(0, (int)cand.size() - 1);\n            chosen = cand[intDist(rng)].dir;\n        } else {\n            // greedy move: maximize value - lambda * forward\n            const double lambda = 0.6;\n            double bestScore = -1e9;\n            vector<int> bestDirs;\n            for (auto &c : cand) {\n                double sc = (double)c.val - lambda * (double)c.forward;\n                if (sc > bestScore + 1e-12) {\n                    bestScore = sc;\n                    bestDirs.clear();\n                    bestDirs.push_back(c.dir);\n                } else if (abs(sc - bestScore) <= 1e-12) {\n                    bestDirs.push_back(c.dir);\n                }\n            }\n            uniform_int_distribution<int> intDist(0, (int)bestDirs.size() - 1);\n            chosen = bestDirs[intDist(rng)];\n        }\n        \n        // apply move\n        ci += di[chosen];\n        cj += dj[chosen];\n        usedCell[ci][cj] = true;\n        int tid = t[ci][cj];\n        usedTile[tid] = true;\n        ++visitedTiles;\n        path.push_back(dirChar[chosen]);\n        score += p[ci][cj];\n        \n        if (visitedTiles == M) break;   // all tiles used\n    }\n    return {path, score};\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    vector<vector<int>> t(50, vector<int>(50));\n    vector<vector<int>> p(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            cin >> t[i][j];\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            cin >> p[i][j];\n        int maxTileId = 0;\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            maxTileId = max(maxTileId, t[i][j]);\n    int M = maxTileId + 1;\n    \n    const int ITER = 300;   // increased number of trials\n    Result best;\n    best.score = -1;\n    for (int it = 0; it < ITER; ++it) {\n        unsigned seed = chrono::steady_clock::now().time_since_epoch().count() + it * 123457u;\n        Result cur = simulate(si, sj, t, p, M, seed);\n        if (cur.score > best.score) {\n            best = cur;\n        }\n    }\n        cout << best.path << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;                     // grid size\nconst int HN = N;                     // rows for horizontal edges\nconst int WN = N - 1;                 // columns for horizontal edges\nconst int VN = N - 1;                 // rows for vertical edges\nconst int VM = N;                     // columns for vertical edges\n\nusing EdgeWeight = double;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // ----- estimates of edge lengths -----\n    vector<vector<EdgeWeight>> h(HN, vector<EdgeWeight>(WN, 5000.0)); // horizontal edges\n    vector<vector<EdgeWeight>> v(VN, vector<EdgeWeight>(VM, 5000.0)); // vertical   edges\n\n    const double eta = 0.2;          // learning rate\n    const double MINW = 500.0, MAXW = 15000.0;\n\n    for (int query = 0; query < 1000; ++query) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) break;   // end of input\n\n        // ---------- Dijkstra on current estimates ----------\n        const int V = N * N;\n        const double INF = 1e100;\n        vector<double> dist(V, INF);\n        vector<int> prev(V, -1);\n        using State = pair<double, int>;\n        priority_queue<State, vector<State>, greater<State>> pq;\n\n        auto idx = [&](int i, int j) { return i * N + j; };\n        int s = idx(si, sj);\n        int t = idx(ti, tj);\n        dist[s] = 0.0;\n        pq.emplace(0.0, s);\n\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u] + 1e-12) continue;\n            int ui = u / N, uj = u % N;\n            // up\n            if (ui > 0) {\n                int ni = ui - 1, nj = uj;\n                double w = static_cast<double>(v[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // down\n            if (ui < N - 1) {\n                int ni = ui + 1, nj = uj;\n                double w = static_cast<double>(v[ui][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // left\n            if (uj > 0) {\n                int ni = ui, nj = uj - 1;\n                double w = static_cast<double>(h[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // right\n            if (uj < N - 1) {\n                int ni = ui, nj = uj + 1;\n                double w = static_cast<double>(h[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n        }\n\n        // ---------- reconstruct path ----------\n        vector<int> rev;\n        for (int cur = t; cur != -1; cur = prev[cur]) rev.push_back(cur);\n        reverse(rev.begin(), rev.end());\n\n        string moves;\n        moves.reserve(rev.size() * 2);\n        double predicted = 0.0;\n        int path_len = 0;\n\n        for (size_t i = 1; i < rev.size(); ++i) {\n            int a = rev[i - 1], b = rev[i];\n            int ai = a / N, aj = a % N;\n            int bi = b / N, bj = b % N;\n            char ch;\n            if (ai == bi && aj == bj + 1) { ch = 'L'; predicted += h[ai][bj]; --aj; }\n            else if (ai == bi && aj == bj - 1) { ch = 'R'; predicted += h[ai][aj]; ++aj; }\n            else if (aj == bj && ai == bi + 1) { ch = 'U'; predicted += v[bi][aj]; --ai; }\n            else if (aj == bj && ai == bi - 1) { ch = 'D'; predicted += v[ai][aj]; ++ai; }\n            else { ch = '?'; } // should never happen\n            moves.push_back(ch);\n            ++path_len;\n        }\n\n        cout << moves << '\\n';\n        cout.flush();\n\n        // ---------- read judge feedback ----------\n        int y;\n        if (!(cin >> y)) break;   // defensive\n\n        // ---------- SGD update ----------\n        if (path_len > 0) {\n            double error = static_cast<double>(y) - predicted;\n            double delta = eta * error / static_cast<double>(path_len);\n\n            int ci = si, cj = sj;\n            for (char ch : moves) {\n                if (ch == 'U') {\n                    v[ci - 1][cj] += delta;\n                    if (v[ci - 1][cj] < MINW) v[ci - 1][cj] = MINW;\n                    if (v[ci - 1][cj] > MAXW) v[ci - 1][cj] = MAXW;\n                    --ci;\n                } else if (ch == 'D') {\n                    v[ci][cj] += delta;\n                    if (v[ci][cj] < MINW) v[ci][cj] = MINW;\n                    if (v[ci][cj] > MAXW) v[ci][cj] = MAXW;\n                    ++ci;\n                } else if (ch == 'L') {\n                    h[ci][cj - 1] += delta;\n                    if (h[ci][cj - 1] < MINW) h[ci][cj - 1] = MINW;\n                    if (h[ci][cj - 1] > MAXW) h[ci][cj - 1] = MAXW;\n                    --cj;\n                } else if (ch == 'R') {\n                    h[ci][cj] += delta;\n                    if (h[ci][cj] < MINW) h[ci][cj] = MINW;\n                    if (h[ci][cj] > MAXW) h[ci][cj] = MAXW;\n                    ++cj;\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20; // fixed\n\nstruct CellEntry {\n    int pid;      // placement id    uint8_t off;  // offset within the placement\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    cin >> N >> M; // N is always 20, but read anyway\n    vector<string> strs(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strs[i];\n    }\n\n    // convert strings to integer representation 0-7 for A-H, 8 for '.'\n    vector<string> raw = strs; // keep original for required char lookup\n    vector<vector<int>> a(N, vector<int>(N, 0));\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_val(0, 7); // A-H only for initial matrix\n    int dot_cnt = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            a[i][j] = dist_val(rng);\n        }\n    }\n\n    // placement data\n    vector<int> placement_sid; // placement -> string id    vector<vector<vector<CellEntry>>> cell_entries(N, vector<vector<CellEntry>>(N));\n    vector<int> placement_mismatch; // per placement\n    vector<int> match_cnt_str(M, 0); // number of matching placements per string\n    int satisfied = 0;\n\n    const int dr[2] = {0, 1};\n    const int dc[2] = {1, 0};\n\n    // Build placements and initial mismatch counts\n    for (int sid = 0; sid < M; ++sid) {\n        const string& s = raw[sid];\n        int L = (int)s.size();\n        for (int dir = 0; dir < 2; ++dir) {\n            for (int sr = 0; sr < N; ++sr) {\n                for (int sc = 0; sc < N; ++sc) {\n                    int pid = (int)placement_sid.size();\n                    placement_sid.push_back(sid);\n                    int mis = 0;\n                    for (int k = 0; k < L; ++k) {\n                        int r = (sr + dr[dir] * k) % N;\n                        int c = (sc + dc[dir] * k) % N;\n                        cell_entries[r][c].push_back({pid, (uint8_t)k});\n                        int required = raw[sid][k] - 'A';\n                        if (a[r][c] != required) ++mis;\n                    }\n                    placement_mismatch.push_back(mis);\n                    if (mis == 0) {\n                        ++match_cnt_str[sid];\n                    }\n                }\n            }\n        }\n    }\n    for (int sid = 0; sid < M; ++sid) {\n        if (match_cnt_str[sid] > 0) ++satisfied;\n    }\n\n    // Helper lambdas for evaluating and applying a cell change\n    auto evaluate_delta = [&](int r, int c, int new_val) -> int {\n        int old_val = a[r][c];\n        if (old_val == new_val) return 0;\n        static vector<int> delta_match;\n        static vector<int> touched;\n        if ((int)delta_match.size() < M) delta_match.assign(M, 0);\n        else fill(delta_match.begin(), delta_match.end(), 0);\n        touched.clear();\n\n        for (const auto& e : cell_entries[r][c]) {\n            int pid = e.pid;\n            int off = e.off;\n            int sid = placement_sid[pid];\n            int required = raw[sid][off] - 'A';\n            int old_matched = (old_val == required);\n            int new_matched = (new_val == required);\n            int delta_mismatch = old_matched - new_matched; // change in mismatch count\n            int old_mis = placement_mismatch[pid];\n            bool old_match = (old_mis == 0);\n            int new_mis = old_mis + delta_mismatch;\n            bool new_match = (new_mis == 0);\n            if (old_match != new_match) {\n                int delta = new_match ? 1 : -1;\n                if (delta_match[sid] == 0) touched.push_back(sid);\n                delta_match[sid] += delta;\n            }\n        }\n\n        int delta_sat = 0;\n        for (int sid : touched) {\n            int old_match_cnt = match_cnt_str[sid];\n            bool old_sat = (old_match_cnt > 0);\n            int new_match_cnt = old_match_cnt + delta_match[sid];\n            bool new_sat = (new_match_cnt > 0);\n            if (!old_sat && new_sat) ++delta_sat;\n            else if (old_sat && !new_sat) --delta_sat;\n            delta_match[sid] = 0; // reset for next use\n        }\n        touched.clear();\n        return delta_sat;\n    };\n\n    auto apply_change = [&](int r, int c, int new_val) {\n        int old_val = a[r][c];\n        if (old_val == new_val) return;\n        a[r][c] = new_val;\n        // update dot count\n        if (old_val == 8) --dot_cnt;\n        if (new_val == 8) ++dot_cnt;\n\n        for (const auto& e : cell_entries[r][c]) {\n            int pid = e.pid;\n            int off = e.off;\n            int sid = placement_sid[pid];\n            int required = raw[sid][off] - 'A';\n            int old_matched = (old_val == required);\n            int new_matched = (new_val == required);\n            int delta_mismatch = old_matched - new_matched;\n            int& mis = placement_mismatch[pid];\n            int old_mis = mis;\n            bool old_match = (old_mis == 0);\n            mis += delta_mismatch;\n            bool new_match = (mis == 0);\n            if (old_match != new_match) {\n                int delta = new_match ? 1 : -1;\n                int old_match_cnt = match_cnt_str[sid];\n                match_cnt_str[sid] += delta;\n                int new_match_cnt = match_cnt_str[sid];\n                bool old_sat = (old_match_cnt > 0);\n                bool new_sat = (new_match_cnt > 0);\n                if (!old_sat && new_sat) ++satisfied;\n                else if (old_sat && !new_sat) --satisfied;\n            }\n        }\n    };\n\n    // Simulated annealing to maximize number of satisfied strings\n    const int MAX_ITER = 20000;\n    double start_temp = 2.0;\n    double end_temp = 0.001;\n    uniform_int_distribution<int> dist_cell(0, N - 1);\n    uniform_int_distribution<int> dist_val_full(0, 8); // 0-7 letters, 8 for '.'\n    uniform_real_distribution<double> dist_real(0.0, 1.0);\n\n    for (int it = 0; it < MAX_ITER; ++it) {\n        double t = start_temp * pow(end_temp / start_temp, (double)it / MAX_ITER);\n        int r = dist_cell(rng);\n        int c = dist_cell(rng);\n        int cur = a[r][c];\n        int nv = dist_val_full(rng);\n        if (nv == cur) continue;\n        int delta = evaluate_delta(r, c, nv);\n        bool accept = false;\n        if (delta > 0) accept = true;\n        else if (delta == 0 && dist_real(rng) < 0.1) accept = true;\n        else if (dist_real(rng) < exp(delta / t)) accept = true;\n        if (accept) {\n            apply_change(r, c, nv);\n        }\n    }\n\n    // Greedy phase: turn non-dot cells into '.' if it does not break any satisfied string\n    bool improved;\n    do {\n        improved = false;\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (a[r][c] == 8) continue; // already dot\n                if (evaluate_delta(r, c, 8) == 0) {\n                    apply_change(r, c, 8);\n                    improved = true;\n                }\n            }\n        }\n    } while (improved);\n\n    // Output the matrix    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int v = a[i][j];\n            if (v == 8) putchar('.');\n            else putchar('A' + v);\n        }\n        putchar('\\n');\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }\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 (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\nstruct Edge {\n    int u, v;\n    long long cost;\n    bool operator<(const Edge& other) const {\n        return cost < other.cost;\n    }\n};\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    vector<vector<int>> id(N, vector<int>(N, -1));\n    vector<pair<int,int>> pos;\n    vector<int> w;\n    auto get_id = [&](int i, int j) -> int {\n        if (id[i][j] != -1) return id[i][j];\n        int cur = (int)pos.size();\n        id[i][j] = cur;\n        pos.emplace_back(i, j);\n        w.push_back(grid[i][j] - '0');\n        return cur;\n    };\n\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (grid[i][j] != '#')\n                get_id(i, j);\n\n    int V = (int)pos.size();\n    if (V == 0) { cout << '\\n'; return 0; }\n\n    vector<Edge> edges;\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == '#') continue;\n            int uid = id[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d], nj = j + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                if (grid[ni][nj] == '#') continue;\n                int vid = id[ni][nj];\n                if (uid < vid) {\n                    edges.push_back({uid, vid, (long long)w[uid] + w[vid]});\n                }\n            }\n        }\n\n    sort(edges.begin(), edges.end());\n    DSU dsu(V);\n    vector<vector<int>> tree(V);\n    for (const auto& e : edges) {\n        if (dsu.unite(e.u, e.v)) {\n            tree[e.u].push_back(e.v);\n            tree[e.v].push_back(e.u);\n        }\n    }\n\n    int start = id[si][sj];\n    string ans;\n    auto dir_char = [&](int from, int to) -> char {\n        int x1 = pos[from].first, y1 = pos[from].second;\n        int x2 = pos[to].first,   y2 = pos[to].second;\n        if (x2 == x1 - 1) return 'U';\n        if (x2 == x1 + 1) return 'D';\n        if (y2 == y1 - 1) return 'L';\n        if (y2 == y1 + 1) return 'R';\n        return '?';\n    };\n\n    function<void(int, int)> dfs = [&](int u, int p) {\n        for (int v : tree[u]) {\n            if (v == p) continue;\n            ans.push_back(dir_char(u, v));\n            dfs(v, u);\n            ans.push_back(dir_char(v, u));\n        }\n    };\n\n    dfs(start, -1);\n    cout << ans << '\\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 task difficulty vectors\n    vector<array<int, 20>> d(N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    // build dependency graph (edges u -> v, u < v)\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    // dp[i] = length of longest path (in edges) starting from i\n    vector<int> dp(N, 0);\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    // priority queue of ready tasks: higher dp first\n    using TaskInfo = pair<int, int>; // dp, task index\n    priority_queue<TaskInfo> pq;\n    vector<int> task_state(N, 0); // 0 = not started, 1 = started, 2 = completed    for (int i = 0; i < N; ++i) {\n        if (indeg[i] == 0 && task_state[i] == 0) {\n            pq.push({dp[i], i});\n        }\n    }\n\n    // worker state\n    vector<int> worker_task(M, -1);       // task assigned to worker, -1 = idle\n    vector<int> worker_start_day(M, 0);   // start day of current task (valid if not idle)\n    vector<bool> worker_idle(M, true);    // true if idle\n    vector<int> finished_today;           // workers that finished at end of previous day\n\n    int day = 1;\n    while (true) {\n        // 1) process completions from previous day        for (int w : finished_today) {\n            int task = worker_task[w];\n            // t = (day-1) - start_day + 1 = day - start_day            int t = day - worker_start_day[w];\n            // (optional) could use t to infer skill levels here\n\n            // mark task as completed\n            if (task_state[task] != 1) {\n                // defensive: should not happen\n            }\n            task_state[task] = 2;\n            for (int succ : adj[task]) {\n                if (--indeg[succ] == 0 && task_state[succ] == 0) {\n                    pq.push({dp[succ], succ});\n                }\n            }\n            worker_task[w] = -1;\n            worker_idle[w] = true;\n        }\n        finished_today.clear();\n\n        // 2) assign tasks to idle workers\n        vector<pair<int, int>> assignments; // (worker+1, task+1)\n        for (int w = 0; w < M; ++w) {\n            if (!worker_idle[w]) continue;\n            if (pq.empty()) break;\n            auto [dpval, task] = pq.top(); pq.pop();\n            worker_task[w] = task;\n            worker_start_day[w] = day;\n            worker_idle[w] = false;\n            task_state[task] = 1;\n            assignments.emplace_back(w + 1, task + 1);\n        }\n\n        // 3) output assignments for today\n        cout << assignments.size();\n        for (auto &p : assignments) {\n            cout << ' ' << p.first << ' ' << p.second;\n        }\n        cout << '\\n';\n        cout.flush();\n\n        // 4) read response (workers that finished at end of today)\n        string line;\n        if (!getline(cin, line)) break;\n        stringstream ss(line);\n        int first;\n        if (!(ss >> first)) break;\n        if (first == -1) break; // all tasks done or day limit exceeded\n        int n = first;\n        finished_today.clear();\n        for (int i = 0; i < n; ++i) {\n            int w;\n            ss >> w;\n            finished_today.push_back(w - 1);\n        }\n\n        ++day;\n        // safety stop (judge will send -1 after day 2000 anyway)\n        if (day > 2000) {\n            // we will still rely on -1 to break\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Point = pair<int, int>;\n\nconst int CENTER_X = 400;\nconst int CENTER_Y = 400;\nconst int MAX_ORDERS = 1000;\nconst int SELECT_SIZE = 50;\n\nint A[MAX_ORDERS], B[MAX_ORDERS], C[MAX_ORDERS], D[MAX_ORDERS];\n\nstruct Result {\n    ll dist;\n    vector<int> order;          // 1\u2011based indices of chosen orders in pickup order\n    vector<Point> route;        // full route (starts/ends at center)\n};\n\ninline int manh(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Build a feasible route for a given set of order indices (0\u2011based).\nResult computeRoute(const vector<int>& sel) {\n    vector<bool> visPick(MAX_ORDERS, false), visDel(MAX_ORDERS, false);\n    vector<Point> route;\n    route.emplace_back(CENTER_X, CENTER_Y);\n    int curX = CENTER_X, curY = CENTER_Y;\n    vector<int> orderVis;\n    int remaining = 2 * (int)sel.size();\n\n    while (remaining > 0) {\n        int bestId = -1;\n        bool isPick = false;\n        int bestDist = INT_MAX;\n        for (int id : sel) {\n            if (!visPick[id]) {\n                int d = manh(curX, curY, A[id], B[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = true;\n                }\n            }\n            if (visPick[id] && !visDel[id]) {\n                int d = manh(curX, curY, C[id], D[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = false;\n                }\n            }\n        }\n        if (isPick) {\n            route.emplace_back(A[bestId], B[bestId]);\n            visPick[bestId] = true;\n            orderVis.push_back(bestId + 1); // store 1\u2011based index\n            curX = A[bestId]; curY = B[bestId];\n        } else {\n            route.emplace_back(C[bestId], D[bestId]);\n            visDel[bestId] = true;\n            curX = C[bestId]; curY = D[bestId];\n        }\n        --remaining;\n    }\n    route.emplace_back(CENTER_X, CENTER_Y);\n\n    ll total = 0;\n    for (size_t i = 0; i + 1 < route.size(); ++i) {\n        total += manh(route[i].first, route[i].second,\n                      route[i+1].first, route[i+1].second);\n    }\n    return {total, orderVis, route};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    for (int i = 0; i < MAX_ORDERS; ++i) {\n        cin >> A[i] >> B[i] >> C[i] >> D[i];\n    }\n\n    // ---- initial selections -------------------------------------------------\n    vector<int> idx(MAX_ORDERS);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](int i, int j) {\n        int wi = manh(CENTER_X, CENTER_Y, A[i], B[i]) +\n                 manh(A[i], B[i], C[i], D[i]) +\n                 manh(C[i], D[i], CENTER_X, CENTER_Y);\n        int wj = manh(CENTER_X, CENTER_Y, A[j], B[j]) +\n                 manh(A[j], B[j], C[j], D[j]) +\n                 manh(C[j], D[j], CENTER_X, CENTER_Y);\n        return wi < wj;\n    });\n\n    vector<vector<int>> initialSelections;\n    {\n        vector<int> top50(idx.begin(), idx.begin() + SELECT_SIZE);\n        initialSelections.push_back(top50);\n    }\n    {\n        // random selection\n        vector<int> rnd(SELECT_SIZE);\n        mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n        uniform_int_distribution<int> dist(0, MAX_ORDERS - 1);\n        vector<bool> taken(MAX_ORDERS, false);\n        int cnt = 0;\n        while (cnt < SELECT_SIZE) {\n            int x = dist(rng);\n            if (!taken[x]) {\n                taken[x] = true;\n                rnd[cnt++] = x;\n            }\n        }\n        initialSelections.push_back(rnd);\n    }\n    {\n        // selection by nearest pickup to center only\n        vector<int> orderByPickup = idx;\n        sort(orderByPickup.begin(), orderByPickup.end(),\n             [&](int i, int j) {\n                 return manh(CENTER_X, CENTER_Y, A[i], B[i]) <                        manh(CENTER_X, CENTER_Y, A[j], B[j]);\n             });\n        vector<int> pick50(orderByPickup.begin(),\n                           orderByPickup.begin() + SELECT_SIZE);\n        initialSelections.push_back(pick50);\n    }\n\n    // ---- local search -------------------------------------------------------\n    const int MAX_ITER = 2000;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distPos(0, SELECT_SIZE - 1);\n    uniform_int_distribution<int> distId(0, MAX_ORDERS - 1);\n\n    ll bestDist = LLONG_MAX;\n    vector<int> bestOrder;\n    vector<Point> bestRoute;\n\n    auto currentTime = []() {\n        return chrono::duration<double>(\n            chrono::steady_clock::now().time_since_epoch()\n        ).count();\n    };\n    double startTime = currentTime();\n    double timeLimit = 1.9; // seconds\n\n    for (const auto& initSel : initialSelections) {\n        if (currentTime() - startTime > timeLimit) break;\n        vector<int> curSel = initSel;\n        vector<bool> inSel(MAX_ORDERS, false);\n        for (int id : curSel) inSel[id] = true;\n\n        auto [dist, order, route] = computeRoute(curSel);\n        if (dist < bestDist) {\n            bestDist = dist;\n            bestOrder = order;\n            bestRoute = route;\n        }\n\n        for (int it = 0; it < MAX_ITER; ++it) {\n            if (currentTime() - startTime > timeLimit) break;\n            int pos = distPos(rng);\n            int outId = curSel[pos];\n            int inId;\n            do {\n                inId = distId(rng);\n            } while (inSel[inId]);\n\n            // perform swap\n            curSel[pos] = inId;\n            inSel[outId] = false;\n            inSel[inId] = true;\n\n            auto [ndist, norder, nroute] = computeRoute(curSel);\n            if (ndist < bestDist) {\n                bestDist = ndist;\n                bestOrder = norder;\n                bestRoute = nroute;\n            } else {\n                // revert swap\n                curSel[pos] = outId;\n                inSel[outId] = true;\n                inSel[inId] = false;\n            }\n        }\n    }\n\n    // ---- output -------------------------------------------------------------\n    cout << SELECT_SIZE << ' ';\n    for (size_t i = 0; i < bestOrder.size(); ++i) {\n        if (i) cout << ' ';\n        cout << bestOrder[i];\n    }\n    cout << '\\n';\n    cout << bestRoute.size();\n    for (auto &p : bestRoute) {\n        cout << ' ' << p.first << ' ' << p.second;\n    }\n    cout << '\\n';\n    cout << flush;\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }\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 (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 400;\n    const int M = 1995;\n\n    // read vertex coordinates\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; ++i) cin >> x[i] >> y[i];\n\n    // read edge endpoints\n    vector<int> u(M), v(M);\n    for (int i = 0; i < M; ++i) cin >> u[i] >> v[i];\n\n    DSU dsu(N);\n    int taken = 0;                 // number of edges already accepted\n    const int needed = N - 1;      // we need exactly N\u20111 edges for a spanning tree\n\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;                  // true length (not needed for the decision)\n\n        bool useful = (dsu.find(u[i]) != dsu.find(v[i]));\n        if (useful && taken < needed) {\n            cout << 1 << '\\n';\n            cout.flush();\n            dsu.unite(u[i], v[i]);\n            ++taken;\n        } else {\n            cout << 0 << '\\n';\n            cout.flush();\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;\n    vector<int> px(N), py(N), pt(N);\n    for (int i = 0; i < N; ++i) cin >> px[i] >> py[i] >> pt[i];\n\n    int M;\n    cin >> M;\n    vector<int> hx(M), hy(M);\n    for (int i = 0; i < M; ++i) cin >> hx[i] >> hy[i];\n\n    string action(M, '.');   // all humans do nothing each turn\n\n    for (int turn = 0; turn < 300; ++turn) {\n        cout << action << '\\n';\n        cout.flush();\n\n        // read pets' movement strings for this turn\n        string mv;\n        for (int i = 0; i < N; ++i) {\n            if (!(cin >> mv)) return 0;   // input ended unexpectedly\n        }\n    }\n    return 0;\n}","ahc009":"#include<bits/stdc++.h>\nusing namespace std;\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 lines, each 19 chars)\n    for (int i = 0; i < 20; ++i) {\n        string line;\n        cin >> line;\n    }\n    // Read vertical walls (20 lines, each 20 chars)\n    for (int i = 0; i < 20; ++i) {\n        string line;\n        cin >> line;\n    }\n    \n    // Output any valid string, e.g., 200 'R's (length <= 200)\n    string ans(200, 'R');\n    cout << ans << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ----- global data -----\narray<array<int, 30>, 30> tile;\nconst int di[4] = {0, -1, 0, 1};\nconst int dj[4] = {-1, 0, 1, 0};\nconst int toBase[8][4] = {\n    {1, 0, -1, -1}, //0\n    {3, -1, -1, 0}, //1\n    {-1, -1, 3, 2}, //2\n    {-1, 2, 1, -1}, //3\n    {1, 0, 3, 2},   //4\n    {3, 2, 1, 0},   //5\n    {2, -1, 0, -1}, //6\n    {-1, 3, -1, 1}  //7\n};\nint toRot[8][4][4]; // [tile][rot][dir] -> exit dir or -1// ----- score computation -----\nlong long computeScore(const vector<vector<int>>& rot) {\n    const int N = 30 * 30 * 4; // 3600\n    vector<int> stateOut(N, -1); // -1 means dead end    // build functional graph\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            int t = tile[i][j];\n            int r = rot[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int nd = toRot[t][r][d];\n                int id = ((i * 30) + j) * 4 + d;\n                if (nd == -1) continue; // stays -1\n                int ni = i + di[nd];\n                int nj = j + dj[nd];\n                if (ni < 0 || ni >= 30 || nj < 0 || nj >= 30) continue;\n                int opp = (nd + 2) & 3;\n                int t2 = tile[ni][nj];\n                int r2 = rot[ni][nj];\n                if (toRot[t2][r2][opp] == -1) continue;\n                int nid = ((ni * 30) + nj) * 4 + opp;\n                stateOut[id] = nid;\n            }\n        }\n    }\n\n    // find cycles in functional graph\n    vector<char> color(N, 0); // 0=unvisited,1=visiting,2=done\n    vector<int> posInPath(N, -1);\n    vector<int> path;\n    path.reserve(N);\n    long long best1 = 0, best2 = 0;\n\n    for (int u = 0; u < N; ++u) {\n        if (color[u]) continue;\n        int v = u;\n        while (true) {\n            if (color[v] == 0) {\n                color[v] = 1;\n                posInPath[v] = (int)path.size();\n                path.push_back(v);\n                int nxt = stateOut[v];\n                if (nxt == -1) break;\n                v = nxt;\n                continue;\n            }\n            if (color[v] == 1) {\n                int start = posInPath[v];\n                long long len = (long long)path.size() - start;\n                if (len > best1) {\n                    best2 = best1;\n                    best1 = len;\n                } else if (len > best2) {\n                    best2 = len;\n                }\n                break;\n            }\n            if (color[v] == 2) break;\n        }\n        for (int node : path) {\n            color[node] = 2;\n            posInPath[node] = -1;\n        }\n        path.clear();\n    }\n    return best1 * best2;\n}\n\n// ----- main -----\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read tile configuration\n    for (int i = 0; i < 30; ++i) {\n        string line;\n        getline(cin, line);\n        line.erase(remove(line.begin(), line.end(), ' '), line.end());\n        for (int j = 0; j < 30; ++j)\n            tile[i][j] = line[j] - '0';\n    }\n\n    // precompute toRot\n    for (int t = 0; t < 8; ++t) {\n        for (int rot = 0; rot < 4; ++rot) {\n            for (int d = 0; d < 4; ++d) {\n                int baseDir = (d + rot) & 3;\n                int baseExit = toBase[t][baseDir];\n                if (baseExit == -1) {\n                    toRot[t][rot][d] = -1;\n                } else {\n                    int exitDir = (baseExit - rot + 4) & 3;\n                    toRot[t][rot][d] = exitDir;\n                }\n            }\n        }\n    }\n\n    // hill climbing with random restarts\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distTile(0, 29);\n    uniform_int_distribution<int> distRot(0, 3);\n\n    long long bestScore = -1;\n    vector<vector<int>> bestRot(30, vector<int>(30, 0));\n\n    for (int restart = 0; restart < 5; ++restart) {\n        vector<vector<int>> curRot(30, vector<int>(30, 0));\n        for (int i = 0; i < 30; ++i)\n            for (int j = 0; j < 30; ++j)\n                curRot[i][j] = distRot(rng);\n        long long curScore = computeScore(curRot);\n\n        for (int iter = 0; iter < 200; ++iter) {\n            int i = distTile(rng);\n            int j = distTile(rng);\n            int cur = curRot[i][j];\n            int nr = distRot(rng);\n            if (nr == cur) continue;\n            curRot[i][j] = nr;\n            long long ns = computeScore(curRot);\n            if (ns > curScore) {\n                curScore = ns;\n            } else {\n                curRot[i][j] = cur; // revert\n            }\n        }\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestRot = curRot;\n        }\n    }\n\n    // output rotation counts\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            cout << bestRot[i][j];\n        }\n    }\n    cout << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions for empty movement: U, D, L, R\nconst int dr[4] = {-1, 1, 0, 0};\nconst int dc[4] = {0, 0, -1, 1};\nconst char dirChar[4] = {'U', 'D', 'L', 'R'};\n\nint computeLargestTreeSize(const vector<vector<int>>& board) {\n    int N = (int)board.size();\n    vector<vector<int>> deg(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int v = board[i][j];\n            if (v == 0) continue;\n            // up\n            if (i > 0 && board[i-1][j] != 0) {\n                if ((v & 2) && (board[i-1][j] & 8)) ++deg[i][j];\n            }\n            // down\n            if (i+1 < N && board[i+1][j] != 0) {\n                if ((v & 8) && (board[i+1][j] & 2)) ++deg[i][j];\n            }\n            // left\n            if (j > 0 && board[i][j-1] != 0) {\n                if ((v & 1) && (board[i][j-1] & 4)) ++deg[i][j];\n            }\n            // right\n            if (j+1 < N && board[i][j+1] != 0) {\n                if ((v & 4) && (board[i][j+1] & 1)) ++deg[i][j];\n            }\n        }\n    }\n    vector<vector<char>> vis(N, vector<char>(N, 0));\n    int best = 0;\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 cnt = 0;\n            int sumdeg = 0;\n            queue<pair<int,int>> q;\n            q.push({i, j});\n            vis[i][j] = 1;\n            while (!q.empty()) {\n                auto [x, y] = q.front(); q.pop();\n                ++cnt;\n                sumdeg += deg[x][y];\n                for (int d = 0; d < 4; ++d) {\n                    int nx = x + dr[d];\n                    int ny = y + dc[d];\n                    if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                    if (board[nx][ny] == 0) continue;\n                    if (vis[nx][ny]) continue;\n                    int a = board[x][y];\n                    int b = board[nx][ny];\n                    bool edge = false;\n                    if (nx == x-1 && ny == y) { // up\n                        if ((a & 2) && (b & 8)) edge = true;\n                    } else if (nx == x+1 && ny == y) { // down\n                        if ((a & 8) && (b & 2)) edge = true;\n                    } else if (nx == x && ny == y-1) { // left\n                        if ((a & 1) && (b & 4)) edge = true;\n                    } else if (nx == x && ny == y+1) { // right\n                        if ((a & 4) && (b & 1)) edge = true;\n                    }\n                    if (edge) {\n                        vis[nx][ny] = 1;\n                        q.push({nx, ny});\n                    }\n                }\n            }\n            int edges = sumdeg / 2;\n            if (edges == cnt - 1) { // tree component\n                if (cnt > best) best = cnt;\n            }\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, T;\n    if (!(cin >> N >> T)) return 0;\n    vector<string> raw(N);\n    for (int i = 0; i < N; ++i) cin >> raw[i];\n\n    // Build board and locate empty\n    vector<vector<int>> board(N, vector<int>(N));\n    int er = -1, ec = -1;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char ch = raw[i][j];\n            int v = (ch >= '0' && ch <= '9') ? ch - '0' : ch - 'a' + 10;\n            board[i][j] = v;\n            if (v == 0) { er = i; ec = j; }\n        }\n    }\n\n    const int full = N * N - 1;\n    string ans;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    auto validMoves = [&](int r, int c, vector<int>& out) {\n        out.clear();\n        if (r > 0) out.push_back(0); // U\n        if (r + 1 < N) out.push_back(1); // D\n        if (c > 0) out.push_back(2); // L\n        if (c + 1 < N) out.push_back(3); // R\n    };\n\n    auto simulateMove = [&](int dir) -> int {\n        int nr = er + dr[dir];\n        int nc = ec + dc[dir];\n        swap(board[er][ec], board[nr][nc]);\n        int res = computeLargestTreeSize(board);\n        swap(board[er][ec], board[nr][nc]); // revert\n        return res;\n    };\n\n    while ((int)ans.size() < T && computeLargestTreeSize(board) < full) {\n        vector<int> mvds;\n        validMoves(er, ec, mvds);\n        shuffle(mvds.begin(), mvds.end(), rng);\n\n        int bestDir = -1;\n        int bestScore = computeLargestTreeSize(board);\n        for (int d : mvds) {\n            int s = simulateMove(d);\n            if (s > bestScore) {\n                bestScore = s;\n                bestDir = d;\n            }\n        }\n\n        if (bestDir != -1 && bestScore > computeLargestTreeSize(board)) {\n            int nr = er + dr[bestDir];\n            int nc = ec + dc[bestDir];\n            swap(board[er][ec], board[nr][nc]);\n            er = nr;\n            ec = nc;\n            ans.push_back(dirChar[bestDir]);\n        } else {\n            // no improving move; take a random move\n            int idx = uniform_int_distribution<int>(0, (int)mvds.size() - 1)(rng);\n            int d = mvds[idx];\n            int nr = er + dr[d];\n            int nc = ec + dc[d];\n            swap(board[er][ec], board[nr][nc]);\n            er = nr;\n            ec = nc;\n            ans.push_back(dirChar[d]);\n        }\n    }\n\n    cout << ans << '\\n';\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nstruct Line {\n    ll x1, y1, x2, y2;\n    Line() {}\n    Line(ll a, ll b, ll c, ll d) : x1(a), y1(b), x2(c), y2(d) {}\n};\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    vector<pair<ll, ll>> pts(N);\n    for (int i = 0; i < N; ++i) cin >> pts[i].first >> pts[i].second;\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<ll> coordDist(-1000000000LL, 1000000000LL);\n    uniform_int_distribution<int> jitterDist(0, 100); // gives [0,100] -> jitter [-50,50]\n\n    const int MAX_ITER = 25;\n    int bestScore = -1;\n    vector<Line> bestLines;\n\n    auto evaluate = [&](const vector<Line>& lines) -> int {\n        unordered_map<string, int> cnt;\n        cnt.reserve(N * 2);\n        for (auto &[x, y] : pts) {\n            string sig;\n            bool on = false;\n            sig.reserve(lines.size());\n            for (const auto &ln : lines) {\n                ll cross = (ln.y2 - ln.y1) * (x - ln.x1) -\n                           (ln.x2 - ln.x1) * (y - ln.y1);\n                if (cross == 0) { on = true; break; }\n                sig.push_back(cross > 0 ? '1' : '0');\n            }\n            if (on) continue;\n            cnt[sig]++;\n        }\n        vector<int> b(11, 0);\n        for (auto &[_, c] : cnt) {\n            if (c >= 1 && c <= 10) b[c]++;\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    for (int it = 0; it < MAX_ITER; ++it) {\n        vector<Line> lines;\n        lines.reserve(K);\n\n        int v = K / 2;               // vertical lines\n        int h = K - v;               // horizontal lines\n\n        ll minX = pts[0].first, maxX = pts[0].first;\n        ll minY = pts[0].second, maxY = pts[0].second;\n        for (auto &[x, y] : pts) {\n            if (x < minX) minX = x;\n            if (x > maxX) maxX = x;\n            if (y < minY) minY = y;\n            if (y > maxY) maxY = y;\n        }\n        ll rangeX = maxX - minX;\n        ll rangeY = maxY - minY;\n        if (rangeX == 0) rangeX = 1;\n        if (rangeY == 0) rangeY = 1;\n\n        // vertical lines (x = const)\n        for (int i = 0; i < v; ++i) {\n            ll t = minX + (rangeX * (i + 1LL)) / (v + 1LL);\n            ll jit = jitterDist(rng) - 50;   // [-50,50]\n            ll X = t + jit;\n            if (X < -1000000000LL) X = -1000000000LL;\n            if (X >  1000000000LL) X =  1000000000LL;\n            lines.emplace_back(X, -1000000000LL, X, 1000000000LL);\n        }\n\n        // horizontal lines (y = const)\n        for (int i = 0; i < h; ++i) {\n            ll t = minY + (rangeY * (i + 1LL)) / (h + 1LL);\n            ll jit = jitterDist(rng) - 50;\n            ll Y = t + jit;\n            if (Y < -1000000000LL) Y = -1000000000LL;\n            if (Y >  1000000000LL) Y =  1000000000LL;\n            lines.emplace_back(-1000000000LL, Y, 1000000000LL, Y);\n        }\n\n        // fill remaining (if any) with random lines\n        while ((int)lines.size() < K) {\n            ll x1 = coordDist(rng), y1 = coordDist(rng);\n            ll x2 = coordDist(rng), y2 = coordDist(rng);\n            if (x1 == x2 && y1 == y2) continue;\n            lines.emplace_back(x1, y1, x2, y2);\n        }\n\n        int score = evaluate(lines);\n        if (score > bestScore) {\n            bestScore = score;\n            bestLines = lines;\n        }\n    }\n\n    cout << (int)bestLines.size() << '\\n';\n    for (const auto &ln : bestLines) {\n        cout << ln.x1 << ' ' << ln.y1 << ' ' << ln.x2 << ' ' << ln.y2 << '\\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    int N, M;\n    cin >> N >> M;\n    // Read and discard the initial dots\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    // Output zero operations\n    cout << 0 << '\\n';\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*------------------------------------------------------------*/\n/*  board utilities                                            */\n/*------------------------------------------------------------*/\nusing Board = array<array<int,10>,10>;\n\n/* place a candy of given flavour into the p-th empty cell (1-indexed) */\nvoid place_candy(Board &bd, int flavour, int p) {\n    int cnt = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (bd[i][j] == 0) {\n                if (++cnt == p) {\n                    bd[i][j] = flavour;\n                    return;\n                }\n            }\n        }\n    }\n}\n\n/* tilt the board in the given direction:\n   0 = F (up), 1 = B (down), 2 = L (left), 3 = R (right) */\nBoard tilt(const Board &bd, int dir) {\n    Board nb{}; // all zero\n    if (dir == 0) {               // F : up\n        for (int j = 0; j < 10; ++j) {\n            int r = 0;\n            for (int i = 0; i < 10; ++i)\n                if (bd[i][j]) nb[r++][j] = bd[i][j];\n        }\n    } else if (dir == 1) {        // B : down\n        for (int i = 0; i < 10; ++i) {\n            int r = 9;\n            for (int j = 9; j >= 0; --j)\n                if (bd[i][j]) nb[i][r--] = bd[i][j];\n        }\n    } else if (dir == 2) {        // L : left\n        for (int i = 0; i < 10; ++i) {\n            int c = 0;\n            for (int j = 0; j < 10; ++j)\n                if (bd[i][j]) nb[i][c++] = bd[i][j];\n        }\n    } else {                      // dir == 3 : R : right\n        for (int i = 0; i < 10; ++i) {\n            int c = 9;\n            for (int j = 9; j >= 0; --j)\n                if (bd[i][j]) nb[i][c--] = bd[i][j];\n        }\n    }\n    return nb;\n}\n\n/* compute sum of squares of component sizes */\nint compute_score(const Board &bd) {\n    bool seen[10][10] = {};\n    int sum = 0;\n    const int dr[4] = {-1,1,0,0};\n    const int dc[4] = {0,0,-1,1};\n\n    auto bfs = [&](int sr, int sc) -> int {\n        int f = bd[sr][sc];\n        queue<pair<int,int>> q;\n        q.emplace(sr,sc);\n        seen[sr][sc] = true;\n        int sz = 0;\n        while (!q.empty()) {\n            auto [r,c] = q.front(); q.pop();\n            ++sz;\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + dr[d], nc = c + dc[d];\n                if (nr < 0 || nr >= 10 || nc < 0 || nc >= 10) continue;\n                if (seen[nr][nc] || bd[nr][nc] != f) continue;\n                seen[nr][nc] = true;\n                q.emplace(nr,nc);\n            }\n        }\n        return sz;\n    };\n\n    for (int i = 0; i < 10; ++i)\n        for (int j = 0; j < 10; ++j)\n            if (bd[i][j] != 0 && !seen[i][j]) {\n                int sz = bfs(i,j);\n                sum += sz*sz;\n            }\n    return sum;\n}\n\n/*------------------------------------------------------------*/\n/*  main                                                       */\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int flavour[100];\n    for (int i = 0; i < 100; ++i) cin >> flavour[i];\n\n    Board board{}; // all zero\n\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        if (!(cin >> p)) break;          // safety, should not happen\n        place_candy(board, flavour[t], p);\n\n        if (t == 99) break;              // last candy \u2013 no output\n\n        int best_dir = -1;\n        int best_val = -1;\n        for (int dir = 0; dir < 4; ++dir) {\n            Board tmp = tilt(board, dir);\n            int val = compute_score(tmp);\n            if (val > best_val) {\n                best_val = val;\n                best_dir = dir;\n            }\n        }\n        char out;\n        switch(best_dir) {\n            case 0: out = 'F'; break;\n            case 1: out = 'B'; break;\n            case 2: out = 'L'; break;\n            case 3: out = 'R'; break;\n        }\n        cout << out << '\\n';\n        cout.flush();\n\n        // really apply the chosen tilt\n        board = tilt(board, best_dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ------------------------------------------------------------\n// Return P[ Bin(n, p) >= start ]  (start is integer, 0 <= start <= n)\n// Uses iterative calculation of the pmf to avoid overflow.\n// ------------------------------------------------------------\nlong double binom_tail(int n, long double p, int start) {\n    if (start > n) return 0.0L;\n    if (start <= 0) return 1.0L;\n    if (p == 0.0L) {\n        return (start == 0) ? 1.0L : 0.0L;\n    }\n    if (p == 1.0L) {\n        return (start <= n) ? 1.0L : 0.0L;\n    }\n    long double prob = powl(1.0L - p, n); // P[X = 0]\n    long double sum = 0.0L;\n    for (int k = 0; k <= n; ++k) {\n        if (k >= start) sum += prob;\n        // compute P[X = k+1] from P[X = k]\n        prob = prob * p / (1.0L - p) * (n - k) / (k + 1.0L);\n    }\n    return sum;\n}\n\n// ------------------------------------------------------------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int M;\n    double eps_;\n    if (!(cin >> M >> eps_)) return 0;\n    const long double eps = static_cast<long double>(eps_);\n\n    // Use the maximum allowed number of vertices\n    const int N = 100;\n    const long long L = 1LL * N * (N - 1) / 2; // total number of possible edges\n\n    // Pre\u2011compute probabilities needed for decoding\n    const int n = N - 1;                     // number of possible edges incident to a vertex\n    const int start = n / 2 + 1;             // we need degree > n/2  (i.e. >= start)\n    const long double p_one = 1.0L - eps;    // probability an original edge stays\n    const long double p_zero = eps;          // probability a non\u2011edge appears as edge\n    const long double p_high = binom_tail(n, p_one, start);   // P[deg > n/2 | vertex in clique]\n    const long double p_low  = binom_tail(n, p_zero, start);  // P[deg > n/2 | vertex in independent set]\n    const long double denom = p_high - p_low;                // > 0 for eps < 0.5\n\n    // --------------------------------------------------------\n    // Output N and the M graphs G_0 \u2026 G_{M-1}\n    // G_s : first s vertices form a clique and are connected to    //       all other vertices; the remaining N-s vertices have\n    //       no edges among themselves.\n    // --------------------------------------------------------\n    cout << N << '\\n';\n    for (int s = 0; s < M; ++s) {\n        string g;\n        g.reserve(L);\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                // edge exists iff at least one endpoint is in the clique [0, s)\n                g.push_back((i < s) || (j < s) ? '1' : '0');\n            }\n        }\n        cout << g << '\\n';\n    }\n    cout.flush();\n\n    // --------------------------------------------------------\n    // Process the 100 queries\n    // --------------------------------------------------------\n    for (int qq = 0; qq < 100; ++qq) {\n        string H;\n        if (!(cin >> H)) break;\n        // compute degree of each vertex\n        vector<int> deg(N, 0);\n        int 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            }\n        }\n        // count vertices with degree > n/2\n        int cnt_high = 0;\n        for (int v = 0; v < N; ++v) {\n            if (deg[v] > n / 2) ++cnt_high;\n        }\n        // estimate s from the observed count\n        long double est = (static_cast<long double>(cnt_high) -\n                           static_cast<long double>(N) * p_low) /\n                          denom;\n        int s_est = static_cast<int>(floor(est + 0.5L)); // nearest integer\n        if (s_est < 0) s_est = 0;\n        if (s_est >= M) s_est = M - 1;\n        cout << s_est << '\\n';\n        cout.flush();\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing db = double;\n\nconst db INF = 1e100;\n\nstruct Edge {\n    int u, v, w, idx;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n        int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n    \n    vector<Edge> edges(M);\n    vector<vector<tuple<int,int,int>>> adj(N); // to, weight, edge index\n    vector<vector<int>> edge_idx(N, vector<int>(N, -1));\n    \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, i};\n        adj[u].emplace_back(v, w, i);\n        adj[v].emplace_back(u, w, i);\n        edge_idx[u][v] = edge_idx[v][u] = i;\n    }\n    // read and ignore coordinates\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    vector<db> betw(M, 0.0); // edge betweenness (undirected)\n    \n    for (int s = 0; s < N; ++s) {\n        vector<db> dist(N, INF);\n        vector<db> sigma(N, 0.0);\n        vector<vector<int>> pred(N);\n        using State = pair<db, int>;\n        priority_queue<State, vector<State>, greater<State>> pq;\n        \n        dist[s] = 0;\n        sigma[s] = 1.0;\n        pq.emplace(0, s);\n        \n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d > dist[v] + 1e-12) continue;\n            for (auto [to, w, _] : adj[v]) {\n                db nd = d + w;\n                if (nd < dist[to] - 1e-12) {\n                    dist[to] = nd;\n                    sigma[to] = sigma[v];\n                    pred[to].clear();\n                    pred[to].push_back(v);\n                    pq.emplace(nd, to);\n                } else if (fabs(nd - dist[to]) <= 1e-12) {\n                    sigma[to] += sigma[v];\n                    pred[to].push_back(v);\n                }\n            }\n        }\n        \n        // vertices ordered by distance decreasing\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) { return dist[a] > dist[b]; });\n        \n        vector<db> delta(N, 0.0);\n        for (int v : order) {\n            if (v == s) continue;\n            for (int p : pred[v]) {\n                db c = (sigma[p] / sigma[v]) * (1.0 + delta[v]);\n                int e = edge_idx[p][v];\n                betw[e] += c;\n                delta[p] += c;\n            }\n        }\n    }\n        // each undirected edge counted twice\n    for (int i = 0; i < M; ++i) betw[i] *= 0.5;\n    \n    // order edges by decreasing betweenness\n    vector<int> ord(M);\n    iota(ord.begin(), ord.end(), 0);\n    sort(ord.begin(), ord.end(),\n         [&](int a, int b) { return betw[a] > betw[b]; });\n    \n    vector<int> ans(M, 0);\n    for (size_t i = 0; i < ord.size(); ++i) {\n        int day = (i % D) + 1; // days 1..D\n        ans[ord[i]] = day;\n    }\n        for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << ans[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Voxel {\n    int x, y, z;\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\n    // Read silhouettes\n    vector<vector<string>> fStr(2, vector<string>(D));\n    vector<vector<string>> rStr(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> fStr[i][k];\n        }\n    }\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> rStr[i][k];\n        }\n    }\n\n    // Convert to bool arrays\n    vector<vector<vector<bool>>> f(2, vector<vector<bool>>(D, vector<bool>(D)));\n    vector<vector<vector<bool>>> r(2, vector<vector<bool>>(D, vector<bool>(D)));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int x = 0; x < D; ++x) {\n                f[i][z][x] = (fStr[i][zvoid solve() {\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int y = 0; y < D; ++y) {\n                r[i][z][y] = (rStr[i][z][y] == '1');\n            }\n        }\n    }\n}\n\n    // Collect voxels that satisfy both projections\n    vector<Voxel> vox[2];\n    for (int i = 0; i < 2; ++i) {\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[i][z][x] && r[i][z][y]) {\n                        vox[i].push_back({x, y, z});\n                    }\n                }\n            }\n        }\n    }\n\n    int v0 = (int)vox[0].size();\n    int v1 = (int)vox[1].size();\n    int n = max(v0, v1);\n\n    int size = D * D * D;\n    vector<int> b0(size, 0);\n    vector<int> b1(size, 0);\n\n    for (int i = 0; i < n; ++i) {\n        if (i < v0) {\n            const Voxel& v = vox[0][i];\n            int idx = v.x * D * D + v.y * D + v.z;\n            b0[idx] = i + 1;\n        }\n        if (i < v1) {\n            const Voxel& v = vox[1][i];\n            int idx = v.x * D * D + v.y * D + v.z;\n            b1[idx] = i + 1;\n        }\n    }\n\n    cout << n << '\\n';\n    for (int i = 0; i < size; ++i) {\n        if i > 0) cout << ' ';\n        cout << b0[i];\n    }\n    cout << '\\n';\n    for (int i = 0; i < size; ++i) {\n        if (i > 0) cout << ' ';\n        cout << b1[i];\n    }\n    cout << '\\n';\n    return 0;\n}\nint main() {\n    solve();\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n) : p(n), r(n, 0) { iota(p.begin(), p.end(), 0); }\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\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\n    vector<int> xs(N), ys(N);\n    for (int i = 0; i < N; ++i) cin >> xs[i] >> ys[i];\n\n    vector<tuple<int,int,long long>> rawEdges; // (u,v,w)\n    rawEdges.reserve(M);\n    for (int j = 0; j < M; ++j) {\n        int u, v; long long w;\n        cin >> u >> v >> w;\n        --u; --v;\n        rawEdges.emplace_back(u, v, w);\n    }\n\n    vector<pair<int,int>> residents(K);\n    for (int k = 0; k < K; ++k) {\n        cin >> residents[k].first >> residents[k].second;\n    }\n\n    /* ---------- 1. Build a Minimum Spanning Tree (Kruskal) ---------- */\n    vector<tuple<long long,int,int>> edges; // (w,u,v)\n    for (auto &[u,v,w] : rawEdges) edges.emplace_back(w, u, v);\n    sort(edges.begin(), edges.end());\n\n    DSU dsu(N);\n    vector<vector<pair<int,int>>> tree(N); // (neighbor, edgeId) in MST\n    vector<vector<int>> edgeIdLookup(N, vector<int>(N, -1)); // N \u2264 100\n    for (int j = 0; j < M; ++j) {\n        auto &[u,v,w] = rawEdges[j];\n        edgeIdLookup[u][v] = edgeIdLookup[v][u] = j;\n    }\n\n    vector<char> isTreeEdge(M, 0);\n    dsu = DSU(N);\n    for (auto &[w, u, v] : edges) {\n        if (dsu.unite(u, v)) {\n            int eid = edgeIdLookup[u][v];\n            isTreeEdge[eid] = 1;\n            tree[u].emplace_back(v, eid);\n            tree[v].emplace_back(u, eid);\n        }\n    }\n\n    /* ---------- 2. Root the MST at vertex 0 (station 1) ---------- */\n    vector<int> parentVertex(N, -1), parentEdge(N, -1);\n    function<void(int,int)> dfsRoot = [&](int v, int p) {\n        parentVertex[v] = p;\n        for (auto [to, eid] : tree[v]) {\n            if (to == p) continue;\n            parentEdge[to] = eid;\n            dfsRoot(to, v);\n        }\n    };\n    dfsRoot(0, -1);\n\n    /* ---------- 3. Helper: ceil of Euclidean distance ---------- */\n    auto distCeil = [&](int ax, int ay, int vx, int vy) -> int {\n        long long dx = vx - ax;\n        long long dy = vy - ay;\n        long long d2 = dx*dx + dy*dy;\n        double d = sqrt((double)d2);\n        int r = (int)ceil(d - 1e-9); // small epsilon to avoid floating errors        if (r < 0) r = 0;\n        if (r > 5000) r = 5000;\n        return r;\n    };\n\n    /* ---------- 4. Greedy assignment with several restarts ---------- */\n    const int GREEDY_PASSES = 20;   // passes over residents in one restart\n    const int RESTARTS      = 5;    // independent random restarts\n    vector<int> bestP(N, 0);\n    long long bestCost = LLONG_MAX; // we minimise S = \u03a3P_i\u00b2 + \u03a3edgeWeight\n\n    auto evaluate = [&](const vector<int>& Pcur) -> long long {\n        long long powerCost = 0;\n        for (int x : Pcur) powerCost += 1LL * x * x;\n        long long edgeCost = 0;\n        for (int j = 0; j < M; ++j)\n            if (isTreeEdge[j]) {\n                auto &[u,v,w] = rawEdges[j];\n                edgeCost += w;\n            }\n        return powerCost + edgeCost;\n    };\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    for (int restart = 0; restart < RESTARTS; ++restart) {\n        vector<int> P(N, 0);\n        vector<int> order(K);\n        iota(order.begin(), order.end(), 0);\n\n        for (int pass = 0; pass < GREEDY_PASSES; ++pass) {\n            shuffle(order.begin(), order.end(), rng);\n            for (int idx : order) {\n                int ax = residents[idx].first;\n                int ay = residents[idx].second;\n                long long bestInc = LLONG_MAX;\n                int bestV = -1;\n                int bestNeed = 0;\n                for (int v = 0; v < N; ++v) {\n                    int need = distCeil(ax, ay, xs[v], ys[v]);\n                    long long cur = P[v];\n                    long long inc = 0;\n                    if (need > cur) inc = 1LL * need * need - 1LL * cur * cur;\n                    if (inc < bestInc || (inc == bestInc && need < bestNeed)) {\n                        bestInc = inc;\n                        bestV = v;\n                        bestNeed = need;\n                    }\n                }\n                if (bestV != -1 && bestNeed > P[bestV])\n                    P[bestV] = bestNeed;\n            }\n        }\n\n        long long curCost = evaluate(P);\n        if (curCost < bestCost) {\n            bestCost = curCost;\n            bestP = P;\n        }\n    }\n\n    /* ---------- 5. Prune the MST: keep edge iff subtree needs power ---------- */\n    vector<char> answerB(M, 0);\n    vector<int> answerP(N);\n    for (int i = 0; i < N; ++i) answerP[i] = bestP[i];\n\n    function<bool(int,int)> dfsMark = [&](int v, int p) -> bool {\n        bool subtreeNeed = (answerP[v] > 0);\n        for (auto [to, eid] : tree[v]) {\n            if (to == p) continue;\n            bool childNeed = dfsMark(to, v);\n            if (childNeed) answerB[eid] = 1;\n            else answerB[eid] = 0;\n            subtreeNeed |= childNeed;\n        }\n        return subtreeNeed;\n    };\n    dfsMark(0, -1);\n\n    /* ---------- 6. Output ---------- */\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << answerP[i];\n    }\n    cout << '\\n';\n    for (int j = 0; j < M; ++j) {\n        if (j) cout << ' ';\n        cout << (int)answerB[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 total = N * (N + 1) / 2; // 465\n\n    // Precompute level and coordinates for each index in level\u2011order (heap) layout.\n    vector<int> level(total), cx(total), cy(total);\n    int idx = 0;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            level[idx] = x;\n            cx[idx] = x;\n            cy[idx] = y;\n            ++idx;\n        }\n    }\n\n    // Read the initial permutation.\n    vector<int> val(total);\n    idx = 0;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int v;\n            cin >> v;\n            val[idx++] = v;\n        }\n    }\n\n    struct Op { int x1, y1, x2, y2; };\n    vector<Op> ops;\n    ops.reserve(10000);\n\n    auto children = [&](int i) {\n        int lev = level[i];\n        int left = i + lev + 1;   // left child (same y)\n        int right = i + lev + 2;  // right child (y+1)\n        return make_pair(left, right);\n    };\n\n    // Helper to check if a node (not in bottom tier) violates the heap condition.\n    auto isViolation = [&](int i) {\n        if (level[i] >= N - 1) return false; // bottom tier has no children\n        auto [l, r] = children(i);\n        return (l < total && val[i] > val[l]) || (r < total && val[i] > val[r]);\n    };\n\n    // Main loop: fix violations by swapping with the smaller child.\n    while ((int)ops.size() < 10000) {\n        int violate = -1;\n        int bestDiff = -1; // we want to fix the biggest excess first\n        for (int i = 0; i < total; ++i) {\n            if (isViolation(i)) {\n                auto [l, r] = children(i);\n                int childVal = total; // large sentinel\n                int childIdx = -1;\n                if (l < total && val[l] < childVal) { childVal = val[l]; childIdx = l; }\n                if (r < total && val[r] < childVal) { childVal = val[r]; childIdx = r; }\n                int diff = val[i] - childVal; // how much parent exceeds the smaller child\n                if (diff > bestDiff) {\n                    bestDiff = diff;\n                    violate = i;\n                }\n            }\n        }\n        if (violate == -1) break; // no violations left\n\n        auto [l, r] = children(violate);\n        // choose the smaller child to swap with\n        int child = (l < total && (r >= total || val[l] < val[r])) ? l : r;\n        // perform swap\n        swap(val[violate], val[child]);\n        ops.push_back({cx[violate], cy[violate], cx[child], cy[child]});\n    }\n\n    // Output\n    cout << ops.size() << '\\n';\n    for (const auto& op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' ' << 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 ent_r = 0;\n    const int ent_c = (D - 1) / 2;\n\n    vector<vector<bool>> blocked(D, vector<bool>(D, false));\n    for (int k = 0; k < N; ++k) {\n        int r, j;\n        cin >> r >> j;\n        blocked[r][j] = true;\n    }\n    blocked[ent_r][ent_c] = false;\n\n    vector<vector<int>> dist(D, vector<int>(D, -1));\n    queue<pair<int,int>> q;\n    dist[ent_r][ent_c] = 0;\n    q.emplace(ent_r, ent_c);\n    const int dr[4] = {-1,1,0,0};\n    const int dc[4] = {0,0,-1,1};\n    while (!q.empty()) {\n        auto [r,c] = q.front(); q.pop();\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 >= D || nc < 0 || nc >= D) continue;\n            if (blocked[nr][nc]) continue;\n            if (dist[nr][nc] != -1) continue;\n            dist[nr][nc] = dist[r][c] + 1;\n            q.emplace(nr, nc);\n        }\n    }\n\n    vector<pair<int,int>> L;\n    vector<vector<int>> idx(D, vector<int>(D, -1));\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            if (blocked[i][j]) continue;\n            if (i == ent_r && j == ent_c) continue;\n            L.emplace_back(i, j);\n            idx[i][j] = (int)L.size() - 1;\n        }\n    }\n    const int M = (int)L.size();\n    sort(L.begin(), L.end(), [&](const pair<int,int>& a, const pair<int,int>& b) {\n        if (dist[a.first][a.second] != dist[b.first][b.second])\n            return dist[a.first][a.second] < dist[b.first][b.second];\n        if (a.first != b.first) return a.first < b.first;\n        return a.second < b.second;\n    });\n    for (int i = 0; i < D; ++i) for (int j = 0; j < D; ++j) idx[i][j] = -1;\n    for (int p = 0; p < M; ++p) {\n        auto [r,c] = L[p];\n        idx[r][c] = p;\n    }\n\n    vector<vector<bool>> occupied(D, vector<bool>(D, false));\n    auto bfsReachable = [&](const vector<vector<bool>>& occ) -> vector<vector<bool>> {\n        vector<vector<bool>> reach(D, vector<bool>(D, false));\n        queue<pair<int,int>> qq;\n        if (!blocked[ent_r][ent_c] && !occ[ent_r][ent_c]) {\n            reach[ent_r][ent_c] = true;\n            qq.emplace(ent_r, ent_c);\n        }\n        while (!qq.empty()) {\n            auto [r,c] = qq.front(); qq.pop();\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 >= D || nc < 0 || nc >= D) continue;\n                if (blocked[nr][nc] || occ[nr][nc]) continue;\n                if (reach[nr][nc]) continue;\n                reach[nr][nc] = true;\n                qq.emplace(nr, nc);\n            }\n        }\n        return reach;\n    };\n\n    auto getArticulation = [&](const vector<vector<bool>>& reach, const vector<vector<bool>>& occ) -> vector<vector<bool>> {\n        vector<vector<bool>> isArt(D, vector<bool>(D, false));\n        vector<int> tin(D*D, -1), low(D*D, -1);\n        vector<char> visited(D*D, false);\n        int timer = 0;\n        function<void(int,int,int)> dfs = [&](int r, int c, int pr) {\n            int id = r*D + c;\n            visited[id] = true;\n            tin[id] = low[id] = timer++;\n            int children = 0;\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 >= D || nc < 0 || nc >= D) continue;\n                if (!blocked[nr][nc] && !occ[nr][nc] && reach[nr][nc]) {\n                    int nid = nr*D + nc;\n                    if (visited[nid]) {\n                        low[id] = min(low[id], tin[nid]);\n                    } else {\n                        ++children;\n                        dfs(nr, nc, id);\n                        low[id] = min(low[id], low[nid]);\n                        if (pr != -1 && low[nid] >= tin[id]) {\n                            isArt[r][c] = true;\n                        }\n                    }\n                }\n            }\n            if (pr == -1 && children > 1) {\n                isArt[r][c] = true;\n            }\n        };\n        dfs(ent_r, ent_c, -1);\n        return isArt;\n    };\n\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;\n        vector<vector<bool>> reach = bfsReachable(occupied);\n        vector<vector<bool>> isArt = getArticulation(reach, occupied);\n\n        int best_r = -1, best_c = -1;\n        int best_cost = INT_MAX;\n        for (int i = 0; i < D; ++i) {\n            for (int j = 0; j < D; ++j) {\n                if (!reach[i][j]) continue;\n                if (i == ent_r && j == ent_c) continue;\n                if (occupied[i][j]) continue;\n                if (isArt[i][j]) continue;\n                int cost = abs(idx[i][j] - t);\n                if (cost < best_cost || (cost == best_cost && (i < best_r || (i == best_r && j < best_c)))) {\n                    best_cost = cost;\n                    best_r = i;\n                    best_c = j;\n                }\n            }\n        }\n        if (best_r == -1) {\n            for (int i = 0; i < D; ++i) {\n                for (int j = 0; j < D; ++j) {\n                    if (!reach[i][j]) continue;\n                    if (i == ent_r && j == ent_c) continue;\n                    if (occupied[i][j]) continue;\n                    best_r = i; best_c = j;\n                    break;\n                }\n                if (best_r != -1) break;\n            }\n        }\n        occupied[best_r][best_c] = true;\n        cout << best_r << ' ' << best_c << '\\n';\n        cout.flush();\n    }\n\n    for (auto [r,c] : L) {\n        cout << r << ' ' << c << '\\n';\n    }\n    cout.flush();\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*------------------------------------------------------------*/\n/*  Constants and directions                                  */\nconst int dx[4] = {1, -1, 0, 0};\nconst int dy[4] = {0, 0, 1, -1};\n\n/*------------------------------------------------------------*/\nstruct Solver {\n    int n, m;\n    vector<vector<short>> grid;          // current colours\n    vector<int> cnt;                     // number of cells of each colour (>0)\n    vector<vector<int>> adj;             // current adjacency counts\n    vector<vector<int>> adjOrig;         // original adjacency counts (constant)\n\n    Solver(int n_, int m_) : n(n_), m(m_) {\n        grid.assign(n, vector<short>(n, 0));\n        cnt.assign(m + 1, 0);\n        adj.assign(m + 1, vector<short>(m + 1, 0));\n        adjOrig.assign(m + 1, vector<short>(m + 1, 0));\n    }\n\n    /*--------------------------------------------------------*/\n    // read the input\n    void read() {\n        cin >> n >> m;\n        grid.assign(n, vector<short>(n));\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) {\n                cin >> grid[i][j];\n                if (grid[i][j] > 0) ++cnt[grid[i][j]];\n            }\n    }\n\n    /*--------------------------------------------------------*/\n    // compute adjacency matrix from a given grid\n    void computeAdj(const vector<vector<short>>& g, vector<vector<int>>& out) {\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) {\n                int c = g[i][j];\n                for (int d = 0; d < 4; ++d) {\n                    int ni = i + dx[d], nj = j + dy[d];\n                    int nb = 0;               // outside\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n)\n                        nb = g[ni][nj];\n                    if (c == nb) continue;   // same colour \u2013 we do not store c\u2011c\n                    out[c][nb]++;\n                    out[nb][c]++;\n                }\n            }\n    }\n\n    /*--------------------------------------------------------*/\n    // zero\u2011neighbour test (outside counts as zero)\n    bool hasZeroNeighbour(int i, int j) const {\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) return true;   // outside\n            if (grid[ni][nj] == 0) return true;\n        }\n        return false;\n    }\n\n    /*--------------------------------------------------------*/\n    // BFS to check connectivity of a given colour (>0)\n    bool connectedColour(int col) const {\n        // find any cell of this colour\n        int si = -1, sj = -1;\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (grid[i][j] == col) { si = i; sj = j; break; }\n            if (si != -1) break;\n        if (si == -1) return false;   // should never happen because cnt[col]>0 checked before\n        vector<vector<char>> vis(n, vector<char>(0, false));\n        queue<pair<int,int>> q;\n        q.emplace(si, sj);\n        vis[si][sj] = 1;\n        int reached = 0;\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            ++reached;\n            for (int d = 0; d < 4; ++d) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;\n                if (grid[nx][ny] != col) continue;\n                if (vis[nx][ny]) continue;\n                vis[nx][ny] = 1;\n                q.emplace(nx, ny);\n            }\n        }\n        return reached == cnt[col];\n    }\n\n    /*--------------------------------------------------------*/\n    // check that all zero cells are reachable from the outside\n    bool zeroConnected() const {\n        vector<vector<char>> vis(n, vector<char>(0, false));\n        queue<pair<int,int>> q;\n        // start from all boundary zero cells (they touch the outside)\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] == 0 && (i == 0 || i == n-1 || j == 0 || j == n-1)) {\n                    q.emplace(i, j);\n                    vis[i][j] = 1;\n                }\n            }\n        }\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;\n                if (grid[nx][ny] != 0) continue;\n                if (vis[nx][ny]) continue;\n                vis[nx][ny] = 1;\n                q.emplace(nx, ny);\n            }\n        }\n        // any zero cell not visited?\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (grid[i][j] == 0 && !vis[i][j]) return false;\n        return true;\n    }\n\n    /*--------------------------------------------------------*/\n    // try to delete cell (i,j); return true iff deletion really happened\n    bool tryDelete(int i, int j) {\n        int col = grid[i][j];\n        if (col == 0) return false;\n        if (!hasZeroNeighbour(i, j)) return false;\n\n        // backup        int backupCnt = cnt[col];\n        vector<tuple<int,int,int>> changes;   // (a,b,delta) to be added to adj[a][b]\n\n        // process the four neighbours        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d], nj = y + dy[d];\n            int nb;\n            bool outside = false;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) { nb = 0; outside = true; }\n            else nb = grid[ni][nj];\n\n            if (nb == col) continue;          // internal edge, nothing to change\n\n            // erase edge col \u2013 nb\n            changes.emplace_back(col, nb, -1);\n            changes.emplace_back(nb, col, -1);\n\n            if (nb != 0 && !outside) {\n                // create edge 0 \u2013 nb\n                changes.emplace_back(0, nb, +1);\n                changes.emplace_back(nb, 0, +1);\n            }\n            // if nb == 0 (inside zero or outside) we only removed a col\u20110 edge\n        }\n\n        // apply changes to adj\n        for (auto &ch : changes) {\n            int a = get<0>(ch), b = get<1>(ch), delta = get<2>(ch);\n            adj[a][b] += delta;\n        }\n\n        // actually delete the cell\n        grid[i][j] = 0;\n        --cnt[col];\n\n        // ----- tests -----\n        bool ok = true;\n        if (cnt[col] == 0) ok = false;                // colour must stay non\u2011empty\n\n        if (ok) {\n            // adjacency matrix must stay exactly the same (as Boolean)\n            for (int x = 0; x <= m && ok; ++x)\n                for (int y = x; y <= m && ok; ++y)\n                    bool cur = (adj[x][y] > 0);\n                    bool orig = (adjOrig[x][y] > 0);\n                    if (cur != orig) { ok = false; break; }\n        }\n        if (ok) {\n            if (!connectedColour(col)) ok = false;\n        }\n        if (ok) {\n            if (!zeroConnected()) ok = false;\n        }\n\n        if (!ok) {\n            // ----- revert -----            grid[i][j] = col;\n            cnt[col] = backupCnt;\n            for (auto &ch : changes) {\n                int a = get<0>(ch), b = get<1>(ch), delta = get<2>(ch);\n                adj[a][b] -= delta;   // undo the addition\n            }\n            return false;\n        }\n        return true;\n    }\n\n    /*--------------------------------------------------------*/\n    void solve() {\n        read();\n        computeAdj(grid, adjOrig);\n        adj = adjOrig;          // start with the original adjacency\n\n        bool progress;\n        do {\n            progress = false;\n            vector<pair<int,int>> cand;\n            for (int i = 0; i < n; ++i)\n                for (int j = 0; j < n; ++j)\n                    if (grid[i][j] > 0)\n                        cand.emplace_back(i, j);\n            std::shuffle(cand.begin(), cand.end(),\n                         std::mt19937{std::random_device{}()});\n            for (auto &p : cand)\n                if (tryDelete(p.first, p.second))\n                    progress = true;\n        } while (progress);\n\n        // output the final grid\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << grid[i][j];\n                if (j + 1 < n) cout << ' ';\n            }\n            cout << '\\n';\n        }\n    }\n};\n\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m;\n    cin >> n >> m;\n    Solver solver(n, m);\n    solver.solve();\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    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n\n    // cached comparison results: 0 = unknown, '<', '>', '='\n    vector<vector<char>> known(N, vector<char>(N, 0));\n    int query_cnt = 0;\n\n    auto ask = [&](int a, int b) -> char {\n        // precondition: query_cnt < Q (checked by caller)\n        cout << 1 << ' ' << 1 << ' ' << a << ' ' << b << '\\n';\n        cout.flush();\n        string res;\n        cin >> res;               // judge replies with one of \"<\", \">\", \"=\"\n        ++query_cnt;\n        char c = res[0];\n        known[a][b] = c;\n        known[b][a] = (c == '<' ? '>' : (c == '>' ? '<' : '='));\n        return c;\n    };\n\n    vector<bool> used(N, false);\n    vector<int> top;               // heaviest items found, in decreasing order\n\n    // ---------- 1. select as many heaviest items as query budget allows ----------\n    for (int k = 0; k < D; ++k) {\n        if (query_cnt >= Q) break;          // no queries left\n        int best = -1;\n        for (int i = 0; i < N; ++i) {\n            if (used[i]) continue;\n            if (best == -1) { best = i; continue; }\n            if (query_cnt >= Q) break;      // stop inner loop as well\n            char res = ask(i, best);\n            if (res == '>') best = i;\n        }\n        if (best == -1) break;              // no remaining items\n        top.push_back(best);\n        used[best] = true;\n    }\n\n    // ---------- 2. build the partition (round\u2011robin) ----------\n    vector<int> answer(N, -1);\n    int grp = 0;\n    // distribute the found heavy items\n    for (size_t idx = 0; idx < top.size(); ++idx) {\n        answer[top[idx]] = grp;\n        grp = (grp + 1) % D;\n    }\n    // distribute the rest\n    for (int i = 0; i < N; ++i) {\n        if (answer[i] == -1) {\n            answer[i] = grp;\n            grp = (grp + 1) % D;\n        }\n    }\n\n    // ---------- 3. consume remaining queries with dummy comparisons ----------\n    while (query_cnt < Q) {\n        // N \u2265 30, so items 0 and 1 exist and are different\n        ask(0, 1);\n    }\n\n    // ---------- 4. output the partition ----------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << answer[i];\n    }\n    cout << '\\n';\n    cout.flush();\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    int per = n / m;\n    vector<vector<int>> stacks(m);\n    for (int i = 0; i < m; ++i) {\n        stacks[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x;\n            cin >> x;\n            stacks[i].push_back(x);\n        }\n    }\n\n    using pii = pair<int, int>;\n    vector<pii> ops;\n    ops.reserve(2 * n);   // at most two operations per box\n\n    for (int v = 1; v <= n; ++v) {\n        int src = -1, pos = -1;\n        for (int i = 0; i < m; ++i) {\n            auto &st = stacks[i];\n            for (size_t j = 0; j < st.size(); ++j) {\n                if (st[j] == v) {\n                    src = i;\n                    pos = static_cast<int>(j);\n                    break;\n                }\n            }\n            if (src != -1) break;\n        }\n\n        int sz = (int)stacks[src].size();\n        if (pos == sz - 1) {                 // already on top\n            ops.emplace_back(v, 0);          // operation 2\n            stacks[src].pop_back();\n            continue;\n        }\n\n        int w = stacks[src][pos + 1];        // box directly above v\n\n        // Find destination stack != src with minimal height.\n        // If several have the same height, pick the one with the largest top value\n        // (to avoid burying small numbers that will be processed soon).\n        int best = -1;\n        int bestHeight = 1e9;\n        int bestTop = -1;                    // top value of the best stack (meaningless if empty)\n        for (int i = 0; i < m; ++i) {\n            if (i == src) continue;\n            int h = (int)stacks[i].size();\n            int top = stacks[i].empty() ? -1 : stacks[i].back();\n            if (h < bestHeight || (h == bestHeight && top > bestTop)) {\n                bestHeight = h;\n                bestTop = top;\n                best = i;\n            }\n        }\n        int dest = best;                     // guaranteed to exist (m >= 2)\n\n        // Move the suffix [w ... top] from src to dest\n        vector<int> moved;\n        moved.reserve(sz - (pos + 1));\n        for (size_t j = pos + 1; j < stacks[src].size(); ++j)\n            moved.push_back(stacks[src][j]);\n\n        stacks[src].erase(stacks[src].begin() + pos + 1, stacks[src].end());\n        stacks[dest].insert(stacks[dest].end(), moved.begin(), moved.end());\n\n        // Operation 1: move w (and everything above it)\n        ops.emplace_back(w, dest + 1);       // output uses 1\u2011based index\n        // Now v is on top of its source stack\n        ops.emplace_back(v, 0);              // operation 2: carry out v\n        stacks[src].pop_back();              // remove v\n    }\n\n    for (auto &p : ops)\n        cout << p.first << ' ' << p.second << '\\n';\n    return 0;\n}","ahc027":"#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\n    // walls\n    vector<string> h(N - 1), v(N);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    // dirt\n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) cin >> d[i][j];\n\n    // helpers to test walls\n    auto canUp = [&](int i, int j) { return i > 0 && h[i - 1][j] == '0'; };\n    auto canDown = [&](int i, int j) { return i + 1 < N && h[i][j] == '0'; };\n    auto canLeft = [&](int i, int j) { return j > 0 && v[i][j - 1] == '0'; };\n    auto canRight = [&](int i, int j) { return j + 1 < N && v[i][j] == '0'; };\n\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 oppChar[4] = {'D', 'U', 'R', 'L'};\n\n    const int MAX_LEN = 100000;\n    auto id = [&](int r, int c) { return r * N + c; };\n    const int V = N * N;\n    vector<vector<int>> adj(V);\n\n    // build adjacency list (no walls)\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            int u = id(r, c);\n            for (int dir = 0; dir < 4; ++dir) {\n                int nr = r + dx[dir];\n                int nc = c + dy[dir];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                bool ok = false;\n                if (dir == 0) ok = canUp(r, c);\n                else if (dir == 2) ok = canLeft(r, c);\n                else if (dir == 1) ok = canDown(r, c);\n                else if (dir == 3) ok = canRight(r, c);\n                if (ok) adj[u].push_back(id(nr, nc));\n            }\n        }\n    }\n\n    // ---------- BFS from (0,0) for shortest paths ----------\n    const int start_id = 0;\n    vector<int> parent(V, -1), dist(V, -1);\n    queue<int> q;\n    dist[start_id] = 0;\n    parent[start_id] = start_id;\n    q.push(start_id);\n    while (!q.empty()) {\n        int u = q.front(); q.pop();\n        int ur = u / N, uc = u % N;\n        for (int v : adj[u]) {\n            if (dist[v] == -1) {\n                dist[v] = dist[u] + 1;\n                parent[v] = u;\n                q.push(v);\n            }\n        }\n    }\n    int maxDist = *max_element(dist.begin(), dist.end());\n\n    // ---------- DFS to visit every cell (returns to start) ----------\n    vector<char> visited(V, false);\n    string baseMoves;          // safe baseline\n\n    function<void(int)> dfs = [&](int u) {\n        visited[u] = true;\n        int ur = u / N, uc = u % N;\n        for (int dir = 0; dir < 4; ++dir) {\n            int vr = ur + dx[dir];\n            int vc = uc + dy[dir];\n            if (vr < 0 || vr >= N || vc < 0 || vc >= N) continue;\n            int v = id(vr, vc);\n            bool ok = false;\n            if (dir == 0) ok = canUp(ur, uc);\n            else if (dir == 2) ok = canLeft(ur, uc);\n            else if (dir == 1) ok = canDown(ur, uc);\n            else if (dir == 3) ok = canRight(ur, uc);\n            if (!ok || visited[v]) continue;\n            baseMoves.push_back(dirChar[dir]);\n            dfs(v);\n            baseMoves.push_back(oppChar[dir]);\n        }\n    };\n    dfs(start_id);\n\n    // ---------- Try to improve with MH walk ----------\n    // precompute sqrt(d)\n    vector<double> sqrtD(V);\n    for (int i = 0; i < V; ++i) {\n        int r = i / N, c = i % N;\n        sqrtD[i] = sqrt(d[r][c]);\n    }\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_real_distribution<double> real01(0.0, 1.0);\n\n    int remaining = MAX_LEN - (int)baseMoves.size() - maxDist;\n    if (remaining < 0) remaining = 0;\n    int MH_steps = remaining;\n\n    string candMoves = baseMoves;\n    int cur = start_id;\n    for (int step = 0; step < MH_steps; ++step) {\n        const vector<int>& nb = adj[cur];\n        if (nb.empty()) continue;\n        uniform_int_distribution<int> pickNi(0, (int)nb.size() - 1);\n        int nxt = nb[pickNi(rng)];\n        double accept = min(1.0, sqrtD[nxt] / sqrtD[cur]);\n        if (real01(rng) < accept) {\n            int nr = nxt / N, nc = nxt % N;\n            int ur = cur / N, uc = cur % N;\n            int dir;\n            if (nr == ur - 1 && nc == uc) dir = 0;\n            else if (nr == ur + 1 && nc == uc) dir = 1;\n            else if (nr == ur && nc == uc - 1) dir = 2;\n            else if (nr == ur && nc == uc + 1) dir = 3;\n            else dir = 0; // safety\n            candMoves.push_back(dirChar[dir]);\n            cur = nxt;\n        }\n        // else: stay, no output\n    }\n\n    // return to start using BFS parent pointers\n    while (cur != start_id) {\n        int par = parent[cur];\n        int ur = cur / N, uc = cur % N;\n        int pr = par / N, pc = par % N;\n        int dir;\n        if (pr == ur - 1 && pc == uc) dir = 0;\n        else if (pr == ur + 1 && pc == uc) dir = 1;\n        else if (pr == ur && pc == uc - 1) dir = 2;\n        else if (pr == ur && pc == uc + 1) dir = 3;\n        else dir = 0;\n        candMoves.push_back(dirChar[dir]);\n        cur = par;\n    }\n\n    // ---------- Validate the candidate route ----------\n    auto validate = [&](const string& moves) -> bool {\n        int r = 0, c = 0; // start at (0,0)\n        for (char ch : moves) {\n            int nr = r, nc = c;\n            if (ch == 'U') nr--;\n            else if (ch == 'D') nr++;\n            else if (ch == 'L') nc--;\n            else if (ch == 'R') nc++;\n            // bounds\n            if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n            // wall check\n            if (ch == 'U') { if (!canUp(r, c)) return false; }\n            else if (ch == 'D') { if (!canDown(r, c)) return false; }\n            else if (ch == 'L') { if (!canLeft(r, c)) return false; }\n            else if (ch == 'R') { if (!canRight(r, c)) return false; }\n            r = nr; c = nc;\n        }\n        // must end at start\n        return (r == 0 && c == 0);\n    };\n\n    string answer = validate(candMoves) ? candMoves : baseMoves;\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        int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n    \n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) cin >> t[i];\n    \n    // ---------- Greedy shortest common superstring ----------\n    auto overlap = [&](const string& a, const string& b) -> int {\n        int maxk = min((int)a.size(), (int)b.size());\n        for (int k = maxk; k >= 0; --k) {\n            if (a.substr(a.size() - k, k) == b.substr(0, k)) return k;\n        }\n        return 0;\n    };\n    \n    vector<string> cur = t;\n    while (cur.size() > 1) {\n        int best_i = -1, best_j = -1, best_ov = -1;\n        string best_merge;\n        for (size_t i = 0; i < cur.size(); ++i) {\n            for (size_t j = 0; j < cur.size(); ++j) {\n                if (i == j) continue;\n                int ov = overlap(cur[i], cur[j]);\n                if (ov > best_ov) {\n                    best_ov = ov;\n                    best_i = (int)i;\n                    best_j = (int)j;\n                    best_merge = cur[i] + cur[j].substr(ov);\n                }\n            }\n        }\n        // merge best_i and best_j\n        if (best_i > best_j) swap(best_i, best_j);\n        cur.erase(cur.begin() + best_j);\n        cur.erase(cur.begin() + best_i);\n        cur.push_back(best_merge);\n    }\n    string S = cur.empty() ? \"\" : cur[0];\n    // ---------------------------------------------------------    \n    // Precompute positions of each letter\n    vector<vector<int>> pos(26);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            pos[grid[i][j] - 'A'].push_back(i * N + j);\n        }\n    }\n    \n    auto dist = [&](int a, int b) {\n        int r1 = a / N, c1 = a % N;\n        int r2 = b / N, c2 = b % N;\n        return abs(r1 - r2) + abs(c1 - c2);\n    };\n    \n    const int INF = 1e9;\n    int L = (int)S.size();\n    if (L == 0) {\n        // output nothing (zero operations) \u2013 still valid\n        return 0;\n    }\n    \n    // DP: dpPrev[cell] = min cost to have processed prefix ending at this cell\n    vector<int> dpPrev(N * N, INF);\n    // prv[i][cell] = previous cell for position i (0\u2011based) ending at cell\n    vector<vector<int>> prv(L, vector<int>(N * N, -1));\n    \n    // first character\n    char first = S[0];\n    for (int id : pos[first - 'A']) {\n        int d = dist(si * N + sj, id);\n        dpPrev[id] = d + 1; // move + press        prv[0][id] = -2;   // start marker\n    }\n        // subsequent characters\n    for (int i = 1; i < L; ++i) {\n        char curc = S[i];\n        char prec = S[i - 1];\n        vector<int> dpCurr(N * N, INF);\n        for (int id : pos[curc - 'A']) {\n            int bestCost = INF;\n            int bestPrev = -1;\n            for (int pid : pos[prec - 'A']) {\n                if (dpPrev[pid] == INF) continue;\n                int cand = dpPrev[pid] + dist(pid, id) + 1;\n                if (cand < bestCost) {\n                    bestCost = cand;\n                    bestPrev = pid;\n                }\n            }\n            dpCurr[id] = bestCost;\n            prv[i][id] = bestPrev;\n        }\n        dpPrev.swap(dpCurr);\n    }\n    \n    // find best end\n    int lastId = -1;\n    int minCost = INF;\n    char lastc = S.back();\n    for (int id : pos[lastc - 'A']) {\n        if (dpPrev[id] < minCost) {\n            minCost = dpPrev[id];\n            lastId = id;\n        }\n    }\n    \n    // reconstruct path\n    vector<int> path(L);\n    path[L - 1] = lastId;\n    for (int i = L - 1; i > 0; --i) {\n        path[i - 1] = prv[i][path[i]];\n    }\n    \n    // output operations\n    for (int id : path) {\n        int r = id / N;\n        int c = id % N;\n        cout << r << ' ' << c << '\\n';\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;\n\n    // Read and ignore the shapes of oil fields (not needed for this simple strategy)\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < 2 * d; ++i) {\n            int x;\n            cin >> x;\n        }\n    }\n\n    vector<pair<int, int>> oil;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << \"q 1 \" << i << ' ' << j << endl;\n            int v;\n            cin >> v;\n            if (v > 0) {\n                oil.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Output the answer\n    cout << \"a \" << oil.size();\n    for (auto [i, j] : oil) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << endl;\n\n    // Read verdict (1 if correct, 0 otherwise). Terminate regardless.\n    int verdict;\n    cin >> verdict;\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    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            int x; cin >> x;\n        }\n    }\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << k << \" 0 \" << k+1 << \" \" << W << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll MOD = 998244353LL;\n\nstruct Op {\n    int m, p, q;\n    Op() {}\n    Op(int _m, int _p, int _q) : m(_m), p(_p), q(_q) {}\n};\n\nll add_mod(ll x, ll v) {\n    ll res = x + v;\n    if (res >= MOD) res -= MOD;\n    return res;\n}\nll sub_mod(ll x, ll v) {\n    ll res = x - v;\n    if (res < 0) res += MOD;\n    return res;\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    vector<vector<ll>> a(N, vector<ll>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> a[i][j];\n    vector<array<array<ll, 3>, 3>> stamps(M);\n    for (int m = 0; m < M; ++m)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> stamps[m][i][j];\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_stamp(0, M-1);\n    uniform_int_distribution<int> dist_pos(0, N-3); // 0..6\n\n    ll best_score = -1;\n    vector<Op> best_ops;\n\n    auto start_time = chrono::high_resolution_clock::now();\n    const double time_limit = 1.95; // seconds\n\n    for (int restart = 0; restart < 5; ++restart) {\n        auto now = chrono::high_resolution_clock::now();\n        double elapsed = chrono::duration<double>(now - start_time).count();\n        if (elapsed >= time_limit) break;\n\n        vector<vector<ll>> cur_val = a;\n        ll score = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                score += cur_val[i][j];\n\n        vector<Op> ops;\n        // optional random initialization\n        int init_add = 5;\n        for (int t = 0; t < init_add; ++t) {\n            int m = dist_stamp(rng);\n            int p = dist_pos(rng);\n            int q = dist_pos(rng);\n            ll delta = 0;\n            for (int di = 0; di < 3; ++di)\n                for (int dj = 0; dj < 3; ++dj) {\n                    int i = p + di, j = q + dj;\n                    ll v = stamps[m][di][dj];\n                    ll nx = cur_val[i][j] + v;\n                    if (nx >= MOD) nx -= MOD;\n                    delta += nx - cur_val[i][j];\n                    cur_val[i][j] = nx;\n                }\n            score += delta;\n            ops.emplace_back(m, p, q);\n        }\n\n        // hill climbing with add/remove/swap\n        while (true) {\n            auto now2 = chrono::high_resolution_clock::now();\n            double elapsed2 = chrono::duration<double>(now2 - start_time).count();\n            if (elapsed2 >= time_limit) break;\n\n            ll best_delta = 0;\n            int best_type = 0; // 1=add, 2=remove, 3=swap\n            int best_m = -1, best_p = -1, best_q = -1;\n            int best_idx = -1; // for remove or swap (old op index)\n            int best_m2 = -1, best_p2 = -1, best_q2 = -1; // for swap (new op)\n\n            // try add\n            if ((int)ops.size() < K) {\n                for (int m = 0; m < M; ++m) {\n                    for (int p = 0; p <= N - 3; ++p) {\n                        for (int q = 0; q <= N - 3; ++q) {\n                            ll delta = 0;\n                            for (int di = 0; di < 3; ++di)\n                                for (int dj = 0; dj < 3; ++dj) {\n                                    int i = p + di, j = q + dj;\n                                    ll v = stamps[m][di][dj];\n                                    ll nx = cur_val[i][j] + v;\n                                    if (nx >= MOD) nx -= MOD;\n                                    delta += nx - cur_val[i][j];\n                                }\n                            if (delta > best_delta) {\n                                best_delta = delta;\n                                best_type = 1;\n                                best_m = m; best_p = p; best_q = q;\n                            }\n                        }\n                    }\n                }\n            }\n\n            // try remove\n            if ((int)ops.size() > 0) {\n                for (size_t idx = 0; idx < ops.size(); ++idx) {\n                    const Op& op = ops[idx];\n                    ll delta = 0;\n                    int m = op.m, p = op.p, q = op.q;\n                    for (int di = 0; di < 3; ++di)\n                        for (int dj = 0; dj < 3; ++dj) {\n                            int i = p + di, j = q + dj;\n                            ll v = stamps[m][di][dj];\n                            ll nx = cur_val[i][j] - v;\n                            if (nx < 0) nx += MOD;\n                            delta += nx - cur_val[i][j];\n                        }\n                    if (delta > best_delta) {\n                        best_delta = delta;\n                        best_type = 2;\n                        best_idx = (int)idx;\n                    }\n                }\n            }\n\n            // try swap (remove old, add new)\n            if ((int)ops.size() > 0 && (int)ops.size() < K) {\n                for (size_t idx_old = 0; idx_old < ops.size(); ++idx_old) {\n                    const Op& op_old = ops[idx_old];\n                    int m_old = op_old.m, p_old = op_old.p, q_old = op_old.q;\n                    for (int m_new = 0; m_new < M; ++m_new) {\n                        for (int p_new = 0; p_new <= N - 3; ++p_new) {\n                            for (int q_new = 0; q_new <= N - 3; ++q_new) {\n                                // optional: skip if same as old (no effect)\n                                if (m_old == m_new && p_old == p_new && q_old == q_new) continue;\n                                ll delta = 0;\n                                for (int i = 0; i < N; ++i) {\n                                    for (int j = 0; j < N; ++j) {\n                                        ll val = cur_val[i][j];\n                                        bool in_old = (i >= p_old && i < p_old + 3 && j >= q_old && j < q_old + 3);\n                                        bool in_new = (i >= p_new && i < p_new + 3 && j >= q_new && j < q_new + 3);\n                                        if (in_old) {\n                                            ll v_old = stamps[m_old][i - p_old][j - q_old];\n                                            val = val - v_old;\n                                            if (val < 0) val += MOD;\n                                        }\n                                        if (in_new) {\n                                            ll v_new = stamps[m_new][i - p_new][j - q_new];\n                                            val = val + v_new;\n                                            if (val >= MOD) val -= MOD;\n                                        }\n                                        delta += val - cur_val[i][j];\n                                    }\n                                }\n                                if (delta > best_delta) {\n                                    best_delta = delta;\n                                    best_type = 3;\n                                    best_idx = (int)idx_old;\n                                    best_m2 = m_new; best_p2 = p_new; best_q2 = q_new;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            if (best_delta <= 0) break;\n\n            // apply the best move\n            if (best_type == 1) { // add\n                ll delta_apply = 0;\n                for (int di = 0; di < 3; ++di)\n                    for (int dj = 0; dj < 3; ++dj) {\n                        int i = best_p + di, j = best_q + dj;\n                        ll v = stamps[best_m][di][dj];\n                        ll nx = cur_val[i][j] + v;\n                        if (nx >= MOD) nx -= MOD;\n                        delta_apply += nx - cur_val[i][j];\n                        cur_val[i][j] = nx;\n                    }\n                score += best_delta;\n                ops.emplace_back(best_m, best_p, best_q);\n            } else if (best_type == 2) { // remove\n                const Op& op = ops[best_idx];\n                ll delta_apply = 0;\n                int m = op.m, p = op.p, q = op.q;\n                for (int di = 0; di < 3; ++di)\n                    for (int dj = 0; dj < 3; ++dj) {\n                        int i = p + di, j = q + dj;\n                        ll v = stamps[m][di][dj];\n                        ll nx = cur_val[i][j] - v;\n                        if (nx < 0) nx += MOD;\n                        delta_apply += nx - cur_val[i][j];\n                        cur_val[i][j] = nx;\n                    }\n                score += best_delta;\n                ops.erase(ops.begin() + best_idx);\n            } else { // swap\n                const Op& op_old = ops[best_idx];\n                ll delta_apply = 0;\n                int m_old = op_old.m, p_old = op_old.p, q_old = op_old.q;\n                int m_new = best_m2, p_new = best_p2, q_new = best_q2;\n                for (int i = 0; i < N; ++i) {\n                    for (int j = 0; j < N; ++j) {\n                        ll val = cur_val[i][j];\n                        bool in_old = (i >= p_old && i < p_old + 3 && j >= q_old && j < q_old + 3);\n                        bool in_new = (i >= p_new && i < p_new + 3 && j >= q_new && j < q_new + 3);\n                        if (in_old) {\n                            ll v_old = stamps[m_old][i - p_old][j - q_old];\n                            val = val - v_old;\n                            if (val < 0) val += MOD;\n                        }\n                        if (in_new) {\n                            ll v_new = stamps[m_new][i - p_new][j - q_new];\n                            val = val + v_new;\n                            if (val >= MOD) val -= MOD;\n                        }\n                        delta_apply += val - cur_val[i][j];\n                        cur_val[i][j] = val;\n                    }\n                }\n                score += best_delta;\n                ops[best_idx] = Op(m_new, p_new, q_new);\n            }\n        }\n\n        if (score > best_score) {\n            best_score = score;\n            best_ops = ops;\n        }\n    }\n\n    cout << best_ops.size() << '\\n';\n    for (const Op& op : best_ops) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_TURNS = 10000;\nint N;\nvector<vector<int>> A;\nvector<vector<int>> grid;\nvector<int> next_needed;\nvector<int> next_arrival;\nbool crane_holding = false;\nint held_id = -1;\nint crane_r = 0, crane_c = 0;\nlong long dispatched_count = 0;\nbool done = false;\n\nenum Phase { IDLE, MOVING_TO_PICKUP, AT_PICKUP, MOVING_TO_RELEASE, AT_RELEASE };\nPhase phase = IDLE;\n\nstruct Pos {\n    int r, c;\n    bool operator==(const Pos& other) const { return r == other.r && c == other.c; }\n};\n\nPos pickup_target;\nbool pickup_from_gate;\nint pickup_row;\nint pickup_id;\nPos release_target;\n\nbool inside(int r, int c) {\n    return r >= 0 && r < N && c >= 0 && c < N;\n}\n\nchar move_step(int& cr, int& cc, int tr, int tc) {\n    if (cr < tr) { ++cr; return 'D'; }\n    else if (cr > tr) { --cr; return 'U'; }\n    else if (cc < tc) { ++cc; return 'R'; }\n    else if (cc > tc) { --cc; return 'L'; }\n    else return '.';\n}\n\nPos find_empty_storage_cell() {\n    for (int r = 0; r < N; ++r) {\n        for (int c = 1; c <= N-2; ++c) {\n            if (grid[r][c] == -1) return {r, c};\n        }\n        if (next_arrival[r] == N && grid[r][0] == -1) return {r, 0};\n    }\n    return {0, 0};\n}\n\nPos find_container(int val) {\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            if (c == N-1) continue;\n            if (grid[r][c] == val) return {r, c};\n        }\n    }\n    return {-1, -1};\n}\n\nbool choose_pickup_target() {\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] != -1) {\n            int val = grid[i][0];\n            if (val == next_needed[i]) {\n                pickup_target = {i, 0};\n                pickup_from_gate = true;\n                pickup_row = i;\n                return true;\n            }\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] != -1) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        int need = next_needed[i];\n        if (need < i * N + N) {\n            Pos p = find_container(need);\n            if (p.r != -1) {\n                pickup_target = p;\n                pickup_from_gate = false;\n                pickup_id = need;\n                return true;\n            }\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        if (next_arrival[i] < N) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid compute_release_target_after_pickup() {\n    if (pickup_from_gate) {\n        int val = grid[pickup_target.r][pickup_target.c];\n        if (val == next_needed[pickup_row]) {\n            release_target = {pickup_row, N-1};\n        } else {\n            release_target = find_empty_storage_cell();\n        }\n    } else {\n        int row = pickup_id / N;\n        release_target = {row, N-1};\n    }\n}\n\nvoid process_arrivals() {\n    for (int i = 0; i < N; ++i) {\n        if (next_arrival[i] >= N) continue;\n        if (grid[i][0] == -1 && !(crane_holding && crane_r == i && crane_c == 0)) {\n            int container = A[i][next_arrival[i]];\n            grid[i][0] = container;\n            ++next_arrival[i];\n        }\n    }\n}\n\nvoid process_dispatch() {\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][N-1] != -1) {\n            grid[i][N-1] = -1;\n        }\n    }\n}\n\nchar decide_action() {\n    if (done) return '.';\n    if (phase == IDLE) {\n        if (crane_holding) return '.';\n        if (!choose_pickup_target()) {\n            done = true;\n            return '.';\n        }\n        phase = MOVING_TO_PICKUP;\n    }\n    if (phase == MOVING_TO_PICKUP) {\n        char ch = move_step(crane_r, crane_c, pickup_target.r, pickup_target.c);\n        if (crane_r == pickup_target.r && crane_c == pickup_target.c) {\n            phase = AT_PICKUP;\n        }\n        return ch;\n    }\n    if (phase == AT_PICKUP) {\n        if (!crane_holding && grid[crane_r][crane_c] != -1) {\n            compute_release_target_after_pickup();\n            phase = MOVING_TO_RELEASE;\n            return 'P';\n        } else {\n            return '.';\n        }\n    }\n    if (phase == MOVING_TO_RELEASE) {\n        char ch = move_step(crane_r, crane_c, release_target.r, release_target.c);\n        if (crane_r == release_target.r && crane_c == release_target.c) {\n            phase = AT_RELEASE;\n        }\n        return ch;\n    }\n    if (phase == AT_RELEASE) {\n        if (crane_holding) {\n            phase = IDLE;\n            return 'Q';\n        } else {\n            return '.';\n        }\n    }\n    return '.';\n}\n\nvoid apply_action(char ch) {\n    if (ch == '.') return;\n    if (ch == 'U') { /* moved */ }\n    else if (ch == 'D') { /* moved */ }\n    else if (ch == 'L') { /* moved */ }\n    else if (ch == 'R') { /* moved */ }\n    else if (ch == 'P') {\n        assert(!crane_holding);\n        assert(grid[crane_r][crane_c] != -1);\n        held_id = grid[crane_r][crane_c];\n        crane_holding = true;\n        grid[crane_r][crane_c] = -1;\n    } else if (ch == 'Q') {\n        assert(crane_holding);\n        assert(grid[crane_r][crane_c] == -1);\n        grid[crane_r][crane_c] = held_id;\n        if (crane_c == N-1) {\n            int row = crane_r;\n            ++next_needed[row];\n            ++dispatched_count;\n        }\n        crane_holding = false;\n        held_id = -1;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> N;\n    A.assign(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    }\n    grid.assign(N, vector<int>(N, -1));\n    next_needed.assign(N, 0);\n    next_arrival.assign(N, 0);\n    for (int i = 0; i < N; ++i) {\n        next_needed[i] = i * N;\n    }\n    crane_r = 0;\n    crane_c = 0;\n    crane_holding = false;\n    held_id = -1;\n    dispatched_count = 0;\n    done = false;\n    phase = IDLE;\n\n    string actions_large;\n    int turn = 0;\n    while (turn < MAX_TURNS && !done) {\n        process_arrivals();\n        char ch = decide_action();\n        actions_large += ch;\n        apply_action(ch);\n        process_dispatch();\n        ++turn;\n        if (dispatched_count == N * N) done = true;\n    }\n    cout << actions_large << \"\\n\";\n    string small = \"B\";\n    if ((int)actions_large.size() > 1) {\n        small += string(actions_large.size() - 1, '.');\n    } else {\n        small += \".\";\n    }\n    for (int i = 1; i < N; ++i) {\n        cout << small << \"\\n\";\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int r, c;\n    int amt; // amount of soil (positive for both sources and targets)\n};\n\nstruct Transfer {\n    int sr, sc, tr, tc;\n    int amt;\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>> 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<Cell> sources, targets;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            int val = h[i][j];\n            if (val > 0)\n                sources.push_back({i, j, val});\n            else if (val < 0)\n                targets.push_back({i, j, -val});\n        }\n\n    // Greedy matching: repeatedly pick the nearest source-target pair\n    vector<Transfer> transfers;\n    while (true) {\n        int best_i = -1, best_j = -1;\n        int best_dist = INT_MAX;\n        for (size_t i = 0; i < sources.size(); ++i) {\n            if (sources[i].amt <= 0) continue;\n            for (size_t j = 0; j < targets.size(); ++j) {\n                if (targets[j].amt <= 0) continue;\n                int dist = abs(sources[i].r - targets[j].r) + abs(sources[i].c - targets[j].c);\n                if (dist < best_dist) {\n                    best_dist = dist;\n                    best_i = (int)i;\n                    best_j = (int)j;\n                }\n            }\n        }\n        if (best_i == -1) break;\n        int take = min(sources[best_i].amt, targets[best_j].amt);\n        transfers.push_back({sources[best_i].r, sources[best_i].c,\n                             targets[best_j].r, targets[best_j].c, take});\n        sources[best_i].amt -= take;\n        targets[best_j].amt -= take;\n    }\n\n    // Sequence transfers to minimize empty travel (nearest pickup heuristic)\n    vector<bool> used(transfers.size(), false);\n    vector<Transfer> order;\n    int cur_r = 0, cur_c = 0; // current position, start at depot (empty)\n\n    while (true) {\n        int best_idx = -1;\n        int best_dist = INT_MAX;\n        for (size_t i = 0; i < transfers.size(); ++i) {\n            if (used[i]) continue;\n            int dist = abs(cur_r - transfers[i].sr) + abs(cur_c - transfers[i].sc);\n            if (dist < best_dist) {\n                best_dist = dist;\n                best_idx = (int)i;\n            }\n        }\n        if (best_idx == -1) break;\n        used[best_idx] = true;\n        order.push_back(transfers[best_idx]);\n        // move empty to source\n        cur_r = transfers[best_idx].sr;\n        cur_c = transfers[best_idx].sc;\n        // loaded move to target will be done later when generating ops\n        cur_r = transfers[best_idx].tr;\n        cur_c = transfers[best_idx].tc;\n    }\n    // After all transfers, we are at the last target (empty). Return to depot will be added later.\n\n    vector<string> ops;\n    auto add_move = [&](int r, int c, int tr, int tc) -> pair<int, int> {\n        while (r < tr) { ops.push_back(\"D\"); ++r; }\n        while (r > tr) { ops.push_back(\"U\"); --r; }\n        while (c < tc) { ops.push_back(\"R\"); ++c; }\n        while (c > tc) { ops.push_back(\"L\"); --c; }\n        return {r, c};\n    };\n\n    long long load = 0;\n    int cr = 0, cc = 0; // current position for generating ops\n    // Process ordered transfers\n    for (const Transfer &t : order) {\n        // move empty from current position to source\n        tie(cr, cc) = add_move(cr, cc, t.sr, t.sc);\n        // load\n        ops.push_back(\"+\" + to_string(t.amt));\n        load += t.amt;\n        // move loaded from source to target\n        tie(cr, cc) = add_move(t.sr, t.sc, t.tr, t.tc);\n        // unload\n        ops.push_back(\"-\" + to_string(t.amt));\n        load -= t.amt;\n        // now at target, empty (cr, cc)\n    }\n    // return to depot empty\n    tie(cr, cc) = add_move(cr, cc, 0, 0);\n\n    for (const string &s : ops)\n        cout << s << '\\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    int N, M, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> X(seed_count, vector<int>(M));\n    for (int i = 0; i < seed_count; ++i) {\n        for (int j = 0; j < M; ++j) {\n            cin >> X[i][j];\n        }\n    }\n\n    // Order cells by degree (inner cells first)\n    struct Cell { int deg, i, j; };\n    vector<Cell> cells;\n    cells.reserve(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int deg = (i > 0) + (i < N - 1) + (j > 0) + (j < N - 1);\n            cells.push_back({deg, i, j});\n        }\n    }\n    sort(cells.begin(), cells.end(), [](const Cell& a, const Cell& b) {\n        return a.deg > b.deg;\n    });\n    vector<pair<int,int>> pos_order;\n    pos_order.reserve(N * N);\n    for (const auto& c : cells) {\n        pos_order.emplace_back(c.i, c.j);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        // Compute max attribute value and count of seeds achieving it\n        vector<int> max_attr(M, 0);\n        vector<int> count_max(M, 0);\n        for (int id = 0; id < seed_count; ++id) {\n            for (int l = 0; l < M; ++l) {\n                if (X[id][l] > max_attr[l]) {\n                    max_attr[l] = X[id][l];\n                    count_max[l] = 1;\n                } else if (X[id][l] == max_attr[l]) {\n                    count_max[l]++;\n                }\n            }\n        }\n        using SeedScore = pair<double, int>;\n        vector<SeedScore> scores;\n        scores.reserve(seed_count);\n        for (int id = 0; id < seed_count; ++id) {\n            double w = 0.0;\n            long long v = 0;\n            for (int l = 0; l < M; ++l) {\n                v += X[id][l];\n                if (X[id][l] == max_attr[l]) {\n                    w += 1.0 / count_max[l];\n                }\n            }\n            double score = w * 100000.0 + v;\n            scores.emplace_back(score, id);\n        }\n        // Sort by score descending\n        sort(scores.begin(), scores.end(), greater<SeedScore>());\n\n        // Assign top N^2 seeds to cells in pos_order\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        for (int idx = 0; idx < N * N; ++idx) {\n            int sid = scores[idx].second;\n            int i = pos_order[idx].first;\n            int j = pos_order[idx].second;\n            A[i][j] = sid;\n        }\n\n        // Output placement\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << A[i][j];\n                if (j + 1 < N) cout << ' ';\n                else cout << '\\n';\n            }\n        }\n        cout.flush();\n\n        // Read next generation\n        for (int id = 0; id < seed_count; ++id) {\n            for (int l = 0; l < M; ++l) {\n                if (!(cin >> X[id][l])) return 0;\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\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    // Current and target grids\n    vector<vector<int>> cur(N, vector<int>(N));\n    vector<vector<int>> target(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            cur[i][j] = s[i][j] - '0';\n            target[i][j] = t[i][j] - '0';\n        }\n    \n    // Design a simple 2-vertex arm: root (0) and leaf (1) with edge length 1.\n    const int Vp = 2;\n    cout << Vp << '\\n';\n    cout << \"0 1\" << '\\n';   // parent of vertex 1 is 0, length = 1\n    cout << \"0 0\" << '\\n';   // initial root position (top\u2011left)\n    \n    // Direction vectors: 0=right,1=down,2=left,3=up\n    const int DX[4] = {0, 1, 0, -1};\n    const int DY[4] = {1, 0, -1, 0};\n    const char DIR_CHAR[4] = {'R', 'D', 'L', 'U'};\n    \n    int rootX = 0, rootY = 0;   // root coordinates\n    int leafDir = 0;            // current direction of edge (0,1)\n    bool holding = false;       // whether the leaf holds a takoyaki\n    \n    const int MAX_TURNS = 50000;\n    vector<string> ops;\n    ops.reserve(MAX_TURNS);\n    \n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        // Check if all takoyaki are already at targets\n        int srcCnt = 0, dstCnt = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j) {\n                if (cur[i][j] == 1 && target[i][j] == 0) ++srcCnt;\n                if (cur[i][j] == 0 && target[i][j] == 1) ++dstCnt;\n            }\n        if (srcCnt == 0 && dstCnt == 0) break;\n        \n        // Determine desired root position and leaf direction\n        int desiredRX = -1, desiredRY = -1;\n        int desiredDir = -1;\n        \n        if (!holding) {\n            // Look for any source cell (needs to pick up)\n            bool found = false;\n            for (int i = 0; i < N && !found; ++i)\n                for (int j = 0; j < N && !found; ++j) {\n                    if (cur[i][j] == 1 && target[i][j] == 0) {\n                        // Try the four ways to place the leaf on (i,j)\n                        for (int d = 0; d < 4; ++d) {\n                            int rx = i - DX[d];\n                            int ry = j - DY[d];\n                            if (rx >= 0 && rx < N && ry >= 0 && ry < N) {\n                                desiredRX = rx;\n                                desiredRY = ry;\n                                desiredDir = d;\n                                found = true;\n                                break;\n                            }\n                        }\n                    }\n                }\n            if (!found) {   // should not happen because N>=15                // fallback: do nothing\n                ops.emplace_back(\"....\");\n                continue;\n            }\n        } else {\n            // Look for any target cell (needs to drop)\n            bool found = false;\n            for (int i = 0; i < N && !found; ++i)\n                for (int j = 0; j < N && !found; ++j) {\n                    if (cur[i][j] == 0 && target[i][j] == 1) {\n                        for (int d = 0; d < 4; ++d) {\n                            int rx = i - DX[d];\n                            int ry = j - DY[d];\n                            if (rx >= 0 && rx < N && ry >= 0 && ry < N) {\n                                desiredRX = rx;\n                                desiredRY = ry;\n                                desiredDir = d;\n                                found = true;\n                                break;\n                            }\n                        }\n                    }\n                }\n            if (!found) {\n                ops.emplace_back(\"....\");\n                continue;\n            }\n        }\n        \n        // ---- Operation 1: move the whole arm ----\n        char moveChar = '.';\n        if (rootX < desiredRX) { moveChar = 'D'; ++rootX; }\n        else if (rootX > desiredRX) { moveChar = 'U'; --rootX; }\n        else if (rootY < desiredRY) { moveChar = 'R'; ++rootY; }\n        else if (rootY > desiredRY) { moveChar = 'L'; --rootY; }\n        // else stay\n        \n        // ---- Operation 2: rotate subtree at vertex 1 (the leaf) ----\n        char rotChar = '.';\n        int diff = (desiredDir - leafDir + 4) & 3;\n        if (diff != 0) {\n            if (diff == 2) {          // two steps either way; choose right\n                rotChar = 'R';\n                leafDir = (leafDir + 1) & 3;\n            } else if (diff == 1) {   // need one clockwise step\n                rotChar = 'R';\n                leafDir = (leafDir + 1) & 3;\n            } else {                  // diff == 3 -> one counter\u2011clockwise step\n                rotChar = 'L';\n                leafDir = (leafDir + 3) & 3;\n            }\n        }\n                // ---- Operation 3: action at fingertips ----\n        // Vertex 0 (root) is never a leaf -> op[2] stays '.'\n        int leafX = rootX + DX[leafDir];\n        int leafY = rootY + DY[leafDir];\n        bool act = false;\n        if (leafX >= 0 && leafX < N && leafY >= 0 && leafY < N) {\n            if (!holding && cur[leafX][leafY] == 1 && target[leafX][leafY] == 0) {\n                // pick up\n                cur[leafX][leafY] = 0;\n                holding = true;\n                act = true;\n            } else if (holding && cur[leafX][leafY] == 0 && target[leafX][leafY] == 1) {\n                // drop\n                cur[leafX][leafY] = 1;\n                holding = false;\n                act = true;\n            }\n        }\n        char actChar = act ? 'P' : '.';\n        \n        // Build operation string: [move][rot][root action][leaf action]\n        string op(4, '.');\n        op[0] = moveChar;\n        op[1] = rotChar;\n        op[2] = '.';          // root is not a leaf\n        op[3] = actChar;\n        ops.push_back(op);\n    }\n    \n    // Output the operation sequence\n    for (const string& line : ops) cout << line << '\\n';\n    return 0;\n}","ahc039":"#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    const int MAXC = 100000;\n    vector<tuple<int, int, int>> pts;\n    pts.reserve(2 * N);\n    for (int i = 0; i < 2 * N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        int w = (i < N) ? 1 : -1;\n        pts.emplace_back(x, y, w);\n    }\n\n    unordered_map<int, vector<pair<int, int>>> x_to_ys;\n    unordered_map<int, vector<pair<int, int>>> y_to_xs;\n    for (auto &[x, y, w] : pts) {\n        x_to_ys[x].emplace_back(y, w);\n        y_to_xs[y].emplace_back(x, w);\n    }\n    for (auto &kv : x_to_ys) sort(kv.second.begin(), kv.second.end());\n    for (auto &kv : y_to_xs) sort(kv.second.begin(), kv.second.end());\n\n    auto sumVert = [&](int x, int y1, int y2) -> int {\n        if (y1 > y2) swap(y1, y2);\n        auto it = x_to_ys.find(x);\n        if (it == x_to_ys.end()) return 0;\n        const auto &vec = it->second;\n        int s = 0;\n        for (auto [y, w] : vec) {\n            if (y < y1) continue;\n            if (y > y2) break;\n            s += w;\n        }\n        return s;\n    };\n\n    auto sumHoriz = [&](int y, int x1, int x2) -> int {\n        if (x1 > x2) swap(x1, x2);\n        auto it = y_to_xs.find(y);\n        if (it == y_to_xs.end()) return 0;\n        const auto &vec = it->second;\n        int s = 0;\n        for (auto [x, w] : vec) {\n            if (x < x1) continue;\n            if (x > x2) break;\n            s += w;\n        }\n        return s;\n    };\n\n    long long bestScore = LLONG_MIN;\n    int bestX1 = 0, bestY1 = 0, bestX2 = 0, bestY2 = 0;\n\n    const int seedCount = min(N, 100);\n    vector<int> seeds;\n    for (int i = 0; i < seedCount; ++i) seeds.push_back(i);\n    random_shuffle(seeds.begin(), seeds.end());\n\n    for (int idx : seeds) {\n        int mx = get<0>(pts[idx]);\n        int my = get<1>(pts[idx]);\n        int x1 = mx, x2 = mx, y1 = my, y2 = my;\n        long long score = 1;\n\n        const int maxExpansions = 200;\n        int expansions = 0;\n        while (expansions < maxExpansions) {\n            int width = x2 - x1;\n            int height = y2 - y1;\n            int remaining = 200000 - (width + height);\n            if (remaining <= 0) break;\n\n            int bestGain = 0, bestDir = -1;\n            if (x1 > 0) {\n                int g = sumVert(x1 - 1, y1, y2);\n                if (g > bestGain) { bestGain = g; bestDir = 0; }\n            }\n            if (x2 < MAXC) {\n                int g = sumVert(x2 + 1, y1, y2);\n                if (g > bestGain) { bestGain = g; bestDir = 1; }\n            }\n            if (y1 > 0) {\n                int g = sumHoriz(y1 - 1, x1, x2);\n                if (g > bestGain) { bestGain = g; bestDir = 2; }\n            }\n            if (y2 < MAXC) {\n                int g = sumHoriz(y2 + 1, x1, x2);\n                if (g > bestGain) { bestGain = g; bestDir = 3; }\n            }\n            if (bestGain <= 0) break;\n\n            switch (bestDir) {\n                case 0: x1--; break;\n                case 1: x2++; break;\n                case 2: y1--; break;\n                case 3: y2++; break;\n            }\n            score += bestGain;\n            ++expansions;\n        }\n\n        while (true) {\n            int width = x2 - x1;\n            int height = y2 - y1;\n            int bestGain = 0;\n            int bestDir = -1;\n\n            if (width >= 2) {\n                int gl = sumVert(x1, y1, y2);\n                int gr = sumVert(x2, y1, y2);\n                if (gl < bestGain) { bestGain = gl; bestDir = 0; }\n                if (gr < bestGain) { bestGain = gr; bestDir = 1; }\n            }\n            if (height >= 2) {\n                int gd = sumHoriz(y1, x1, x2);\n                int gu = sumHoriz(y2, x1, x2);\n                if (gd < bestGain) { bestGain = gd; bestDir = 2; }\n                if (gu < bestGain) { bestGain = gu; bestDir = 3; }\n            }\n            if (bestGain >= 0) break;\n\n            switch (bestDir) {\n                case 0: x1++; score -= bestGain; break;\n                case 1: x2--; score -= bestGain; break;\n                case 2: y1++; score -= bestGain; break;\n                case 3: y2--; score -= bestGain; break;\n            }\n        }\n\n        if (x1 == x2) {\n            if (x2 < MAXC) ++x2;\n            else if (x1 > 0) --x1;\n        }\n        if (y1 == y2) {\n            if (y2 < MAXC) ++y2;\n            else if (y1 > 0) --y1;\n        }\n\n        if (score > bestScore) {\n            bestScore = score;\n            bestX1 = x1; bestY1 = y1; bestX2 = x2; bestY2 = y2;\n        }\n    }\n\n    cout << 4 << '\\n';\n    cout << bestX1 << ' ' << bestY1 << '\\n';\n    cout << bestX2 << ' ' << bestY1 << '\\n';\n    cout << bestX2 << ' ' << bestY2 << '\\n';\n    cout << bestX1 << ' ' << bestY2 << '\\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, sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    // Read observed dimensions (we use them as proxies for true sizes)\n    vector<int> obsW(N), obsH(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> obsW[i] >> obsH[i];\n    }\n\n    // Precompute for each rectangle:\n    //   a_i = max(obsW[i], obsH[i])  (the larger side)\n    //   b_i = min(obsW[i], obsH[i])  (the smaller side)\n    //   rotation r_i = 0 if obsW[i] >= obsH[i] (so width = a_i, height = b_i)\n    //                = 1 otherwise.\n    vector<int> a(N), b(N), rot(N);\n    for (int i = 0; i < N; ++i) {\n        if (obsW[i] >= obsH[i]) {\n            a[i] = obsW[i];\n            b[i] = obsH[i];\n            rot[i] = 0;\n        } else {\n            a[i] = obsH[i];\n            b[i] = obsW[i];\n            rot[i] = 1;\n        }\n    }\n\n    // Repeat T times: each time output the same strip placement.\n    for (int t = 0; t < T; ++t) {\n        cout << N << '\\n';\n        for (int i = 0; i < N; ++i) {\n            int p = i;\n            int r = rot[i];\n            char d = 'L';                 // place leftward, stacking vertically\n            int bIdx = (i == 0 ? -1 : i-1); // chain by bottom edge of previous rectangle\n            cout << p << ' ' << r << ' ' << d << ' ' << bIdx << '\\n';\n        }\n        cout.flush();\n\n        // Read judge's measurement for this turn (ignore the values)\n        int Wp, Hp;\n        if (!(cin >> Wp >> Hp)) break;\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    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    // read and ignore coordinates\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    const int trials = 80; // number of random orders to try\n    long long bestScore = LLONG_MIN;\n    vector<int> bestParent(N, -1);\n    \n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    for (int t = 0; t < trials; ++t) {\n        // generate random tie\u2011breaker keys\n        vector<uint64_t> key(N);\n        for (int i = 0; i < N; ++i) key[i] = uniform_int_distribution<uint64_t>(0, UINT64_MAX)(rng);\n        \n        // order by increasing beauty, then by random key\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 (A[a] != A[b]) return A[a] < A[b];\n                 return key[a] < key[b];\n             });\n        \n        vector<int> depth(N, -1);\n        vector<int> parent(N, -1);\n        long long curScore = 0;\n        \n        for (int v : order) {\n            bool assigned = false;\n            // try to attach at the largest possible depth (<= H)\n            for (int d = H; d >= 1; --d) {\n                int need = d - 1;\n                for (int u : adj[v]) {\n                    if (depth[u] == need) {\n                        parent[v] = u;\n                        depth[v] = d;\n                        assigned = true;\n                        break;\n                    }\n                }\n                if (assigned) break;\n            }\n            if (!assigned) {\n                depth[v] = 0;   // root\n                parent[v] = -1;\n            }\n            curScore += 1LL * (depth[v] + 1) * A[v];\n        }\n        \n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestParent = parent;\n        }\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << bestParent[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 Move { char d; int p; };\n    vector<Move> moves;\n    moves.reserve(4 * N * N);\n\n    auto shiftColUp = [&](int j) {\n        for (int i = 0; i + 1 < N; ++i) board[i][j] = board[i + 1][j];\n        board[N - 1][j] = '.';\n    };\n    auto shiftColDown = [&](int j) {\n        for (int i = N - 1; i > 0; --i) board[i][j] = board[i - 1][j];\n        board[0][j] = '.';\n    };\n    auto shiftRowLeft = [&](int i) {\n        for (int j = 0; j + 1 < N; ++j) board[i][j] = board[i][j + 1];\n        board[i][N - 1] = '.';\n    };\n    auto shiftRowRight = [&](int i) {\n        for (int j = N - 1; j > 0; --j) board[i][j] = board[i][j - 1];\n        board[i][0] = '.';\n    };\n\n    auto columnHasFukuUpTo = [&](int col, int row) {\n        for (int i = 0; i <= row; ++i)\n            if (board[i][col] == 'o') return true;\n        return false;\n    };\n    auto columnHasFukuDownFrom = [&](int col, int row) {\n        for (int i = row; i < N; ++i)\n            if (board[i][col] == 'o') return true;\n        return false;\n    };\n    auto rowHasFukuLeftTo = [&](int row, int col) {\n        for (int j = 0; j <= col; ++j)\n            if (board[row][j] == 'o') return true;\n        return false;\n    };\n    auto rowHasFukuRightFrom = [&](int row, int col) {\n        for (int j = col; j < N; ++j)\n            if (board[row][j] == 'o') return true;\n        return false;\n    };\n\n    while (true) {\n        bool progressed = false;\n\n        // ----- try to clear a whole column -----\n        for (int j = 0; j < N && !progressed; ++j) {\n            int max_i = -1, min_i = N;\n            for (int i = 0; i < N; ++i)\n                if (board[i][j] == 'x') {\n                    max_i = max(max_i, i);\n                    min_i = min(min_i, i);\n                }\n            if (max_i == -1) continue; // no Oni in this column\n\n            // try upward shift\n            if (!columnHasFukuUpTo(j, max_i)) {\n                int k = max_i + 1; // number of upward shifts needed\n                for (int t = 0; t < k; ++t) {\n                    moves.push_back({'U', j});\n                    shiftColUp(j);\n                }\n                progressed = true;\n                break;\n            }\n            // try downward shift\n            if (!columnHasFukuDownFrom(j, min_i)) {\n                int k = N - min_i; // downward shifts needed\n                for (int t = 0; t < k; ++t) {\n                    moves.push_back({'D', j});\n                    shiftColDown(j);\n                }\n                progressed = true;\n                break;\n            }\n        }\n        if (progressed) continue;\n\n        // ----- try to clear a whole row -----\n        for (int i = 0; i < N && !progressed; ++i) {\n            int max_j = -1, min_j = N;\n            for (int j = 0; j < N; ++j)\n                if (board[i][j] == 'x') {\n                    max_j = max(max_j, j);\n                    min_j = min(min_j, j);\n                }\n            if (max_j == -1) continue; // no Oni in this row            // try left shift\n            if (!rowHasFukuLeftTo(i, max_j)) {\n                int k = max_j + 1; // left shifts needed\n                for (int t = 0; t < k; ++t) {\n                    moves.push_back({'L', i});\n                    shiftRowLeft(i);\n                }\n                progressed = true;\n                break;\n            }\n            // try right shift\n            if (!rowHasFukuRightFrom(i, min_j)) {\n                int k = N - min_j; // right shifts needed\n                for (int t = 0; t < k; ++t) {\n                    moves.push_back({'R', i});\n                    shiftRowRight(i);\n                }\n                progressed = true;\n                break;\n            }\n        }\n        if (progressed) continue;\n\n        // ----- fallback: remove a single Oni greedily -----\n        int si = -1, sj = -1;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (board[i][j] == 'x') {\n                    si = i; sj = j;\n                    break;\n                }\n            }\n            if (si != -1) break;\n        }\n        if (si == -1) break; // no Oni left\n\n        int i = si, j = sj;\n        bool up = true, down = true, left = true, right = true;\n        for (int ii = 0; ii < i; ++ii)\n            if (board[ii][j] == 'o') { up = false; break; }\n        for (int ii = i + 1; ii < N; ++ii)\n            if (board[ii][j] == 'o') { down = false; break; }\n        for (int jj = 0; jj < j; ++jj)\n            if (board[i][jj] == 'o') { left = false; break; }\n        for (int jj = j + 1; jj < N; ++jj)\n            if (board[i][jj] == 'o') { right = false; break; }\n\n        int dir; // 0:U,1:D,2:L,3:R\n        if (up) dir = 0;\n        else if (down) dir = 1;\n        else if (left) dir = 2;\n        else dir = 3;\n\n        if (dir == 0) { // shift column j upward\n            for (int k = 0; k <= i; ++k) {\n                moves.push_back({'U', j});\n                shiftColUp(j);\n            }\n        } else if (dir == 1) { // shift column j downward\n            for (int k = 0; k < N - i; ++k) {\n                moves.push_back({'D', j});\n                shiftColDown(j);\n            }\n        } else if (dir == 2) { // shift row i left\n            for (int k = 0; k <= j; ++k) {\n                moves.push_back({'L', i});\n                shiftRowLeft(i);\n            }\n        } else { // shift row i right\n            for (int k = 0; k < N - j; ++k) {\n                moves.push_back({'R', i});\n                shiftRowRight(i);\n            }\n        }\n    }\n\n    // safety check (can be removed in final version)\n    assert((int)moves.size() <= 4 * N * N);\n\n    for (auto &mv : moves)\n        cout << mv.d << ' ' << mv.p << '\\n';\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nll simulate(const vector<int>& a, const vector<int>& b,\n            const vector<int>& target, vector<int>& cnt) {\n    int N = (int)a.size();\n    int L = (int)target.size();          // total weeks\n    cnt.assign(N, 0);\n    int cur = 0;\n    cnt[cur] = 1;                         // week 1\n    for (int week = 2; week <= L; ++week) {\n        int nx = (cnt[cur] & 1) ? a[cur] : b[cur];\n        cur = nx;\n        ++cnt[cur];\n    }\n    ll err = 0;\n    for (int i = 0; i < N; ++i) {\n        ll diff = (ll)cnt[i] - (ll)target[i];\n        if (diff < 0) diff = -diff;\n        err += diff;\n    }\n    return err;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N_input, L_input;\n    cin >> N_input >> L_input;\n    // Safeguard: use problem-fixed values if input is invalid\n    int N = (N_input <= 0) ? 100 : N_input;\n    int L = (L_input <= 0) ? 500000 : L_input;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    // initial solution: round\u2011robin\n    vector<int> a(N), b(N);\n    for (int i = 0; i < N; ++i) {\n        a[i] = b[i] = (i + 1) % N;\n    }\n\n    vector<int> cnt(N);\n    ll cur_err = simulate(a, b, T, cnt);\n    ll best_err = cur_err;\n    vector<int> best_a = a, best_b = b;\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_node(0, N - 1);\n    uniform_int_distribution<int> dist_choice(0, 1); // 0 -> a, 1 -> b\n    uniform_real_distribution<double> dist_real(0.0, 1.0);\n\n    // guided move: pick over\u2011visited node i and under\u2011visited node j\n    auto guided_move = [&](const vector<int>& cnt_cur,\n                           int& i, int& which, int& j) -> bool {\n        int n = (int)cnt_cur.size();\n        vector<int> deficit(n);\n        int total_over = 0, total_under = 0;\n        for (int k = 0; k < n; ++k) {\n            int d = T[k] - cnt_cur[k];\n            deficit[k] = d;\n            if (d > 0) total_under += d;\n            else if (d < 0) total_over -= d;\n        }\n        if (total_over == 0) return false; // fallback to random\n\n        // select i (over\u2011visited) with probability proportional to -deficit[i]\n        int r = uniform_int_distribution<int>(0, total_over - 1)(rng);\n        int acc = 0;\n        i = 0;\n        while (i < n) {\n            int d = -deficit[i];\n            if (d > 0) {\n                if (r < acc + d) break;\n                acc += d;\n            }\n            ++i;\n        }\n        // select j (under\u2011visited) with probability proportional to deficit[j]\n        int r2 = uniform_int_distribution<int>(0, total_under - 1)(rng);\n        int acc2 = 0;\n        j = 0;\n        while (j < n) {\n            int d = deficit[j];\n            if (d > 0) {\n                if (r2 < acc2 + d) break;\n                acc2 += d;\n            }\n            ++j;\n        }\n        which = dist_choice(rng); // randomly choose a_i or b_i to change\n        return true;\n    };\n\n    const int MAX_ITER = 500;\n    const double COOLING = 0.998;\n\n    for (int restart = 0; restart < 3; ++restart) {\n        // reset to round\u2011robin for each restart\n        for (int i = 0; i < N; ++i) {\n            a[i] = b[i] = (i + 1) % N;\n        }\n        cur_err = simulate(a, b, T, cnt);\n        if (cur_err < best_err) {\n            best_err = cur_err;\n            best_a = a;\n            best_b = b;\n        }\n        double Ttemp = (double)cur_err; // initial temperature\n        for (int it = 0; it < MAX_ITER; ++it) {\n            int i, which, j;\n            bool use_guided = guided_move(cnt, i, which, j);\n            if (!use_guided) {\n                i = dist_node(rng);\n                which = dist_choice(rng);\n                j = dist_node(rng);\n            }\n            // apply move\n            vector<int> a2 = a, b2 = b;\n            if (which == 0) a2[i] = j;\n            else b2[i] = j;\n            // evaluate move\n            vector<int> cnt2(N);\n            ll err2 = simulate(a2, b2, T, cnt2);\n            bool accept = false;\n            if (err2 < cur_err) accept = true;\n            else {\n                double prob = exp((cur_err - err2) / Ttemp);\n                if (dist_real(rng) < prob) accept = true;\n            }\n            if (accept) {\n                a = a2;\n                b = b2;\n                cur_err = err2;\n                cnt = cnt2;\n                if (err2 < best_err) {\n                    best_err = err2;\n                    best_a = a;\n                    best_b = b;\n                }\n            }\n            Ttemp *= COOLING;\n            if (Ttemp < 1e-5) break;\n        }\n    }\n\n    // output best solution\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    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        // centre of each rectangle (integer division)\n    vector<int> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        cx[i] = (lx[i] + rx[i]) / 2;\n        cy[i] = (ly[i] + ry[i]) / 2;\n    }\n    \n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](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 k = 0; k < M; ++k) {\n        int sz = G[k];\n        vector<int> grp;\n        grp.reserve(sz);\n        for (int i = 0; i < sz; ++i) grp.push_back(idx[pos++]);\n        groups.push_back(move(grp));\n    }\n    \n    // answer edges per group\n    vector<vector<pair<int,int>>> ansEdges(M);\n    ansEdges.reserve(M);\n    int usedQueries = 0;\n    for (int k = 0; k < M; ++k) {\n        const auto& g = groups[k];\n        int sz = (int)g.size();\n        for (int i = 0; i + 1 < sz; i += 2) {\n            if (i + 2 < sz) {\n                // query a triple\n                int a = g[i];\n                int b = g[i+1];\n                int c = g[i+2];\n                cout << \"? 3 \" << a << ' ' << b << ' ' << c << '\\n';\n                cout.flush();\n                ++usedQueries;\n                int u1, v1, u2, v2;\n                cin >> u1 >> v1;\n                cin >> u2 >> v2;\n                ansEdges[k].emplace_back(u1, v1);\n                ansEdges[k].emplace_back(u2, v2);\n            } else {\n                // only a pair left, no query needed\n                ansEdges[k].emplace_back(g[i], g[i+1]);\n            }\n        }\n    }\n    \n    // output the answer\n    cout << \"!\\n\";\n    cout.flush();\n    for (int k = 0; k < M; ++k) {\n        // cities of the group\n        for (size_t i = 0; i < groups[k].size(); ++i) {\n            if (i) cout << ' ';\n            cout << groups[k][i];\n        }\n        cout << '\\n';\n        // edges of the group\n        for (auto &e : ansEdges[k]) {\n            cout << e.first << ' ' << e.second << '\\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>> pts(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> pts[i].first >> pts[i].second;\n    }\n    \n    for (int k = 0; k + 1 < M; ++k) {\n        int ci = pts[k].first, cj = pts[k].second;\n        int ni = pts[k+1].first, nj = pts[k+1].second;\n        \n        while (ci < ni) { cout << \"M D\\n\"; ++ci; }\n        while (ci > ni) { cout << \"M U\\n\"; --ci; }\n        while (cj < nj) { cout << \"M R\\n\"; ++cj; }\n        while (cj > nj) { cout << \"M L\\n\"; --cj; }\n    }\n    \n    return 0;\n}"},"16":{"ahc001":"#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<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    const int W = 10000, H = 10000;\n    size_t totalCells = static_cast<size_t>(W) * H;\n    vector<uint8_t> occ(totalCells, 0); // 0 = free, else company id+1\n    vector<int> a(n), b(n), c(n), d(n);\n    vector<long long> area(n, 1);\n    for (int i = 0; i < n; ++i) {\n        a[i] = x[i];\n        b[i] = y[i];\n        c[i] = x[i] + 1;\n        d[i] = y[i] + 1;\n        occ[static_cast<size_t>(b[i]) * W + a[i]] = static_cast<uint8_t>(i + 1);\n    }\n\n    auto try_expand = [&](int i) -> bool {\n        if (area[i] >= r[i]) return false;\n        long long deficit = r[i] - area[i];\n        int best_dir = -1; // 0:left,1:right,2:down,3:up\n        int best_strip = 0;\n\n        int width  = c[i] - a[i];\n        int height = d[i] - b[i];\n\n        // left\n        if (a[i] > 0) {\n            int strip = height; // area added by expanding left one column\n            if (strip <= deficit) {\n                int xcol = a[i] - 1;\n                bool free = true;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    if (occ[static_cast<size_t>(yc) * W + xcol]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 0;\n                    best_strip = strip;\n                }\n            }\n        }\n        // right\n        if (c[i] < W) {\n            int strip = height;\n            if (strip <= deficit) {\n                int xcol = c[i];\n                bool free = true;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    if (occ[static_cast<size_t>(yc) * W + xcol]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 1;\n                    best_strip = strip;\n                }\n            }\n        }\n        // down\n        if (b[i] > 0) {\n            int strip = width;\n            if (strip <= deficit) {\n                int yrow = b[i] - 1;\n                bool free = true;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    if (occ[static_cast<size_t>(yrow) * W + xc]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 2;\n                    best_strip = strip;\n                }\n            }\n        }\n        // up\n        if (d[i] < H) {\n            int strip = width;\n            if (strip <= deficit) {\n                int yrow = d[i];\n                bool free = true;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    if (occ[static_cast<size_t>(yrow) * W + xc]) {\n                        free = false;\n                        break;\n                    }\n                }\n                if (free && strip > best_strip) {\n                    best_dir = 3;\n                    best_strip = strip;\n                }\n            }\n        }\n        if (best_dir == -1) return false;\n\n        // perform the expansion\n        switch (best_dir) {\n            case 0: { // left\n                int xcol = a[i] - 1;\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    occ[static_cast<size_t>(yc) * W + xcol] = static_cast<uint8_t>(i + 1);\n                }\n                a[i] -= 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 1: { // right\n                int xcol = c[i];\n                for (int yc = b[i]; yc < d[i]; ++yc) {\n                    occ[static_cast<size_t>(yc) * W + xcol] = static_cast<uint8_t>(i + 1);\n                }\n                c[i] += 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 2: { // down\n                int yrow = b[i] - 1;\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    occ[static_cast<size_t>(yrow) * W + xc] = static_cast<uint8_t>(i + 1);\n                }\n                b[i] -= 1;\n                area[i] += best_strip;\n                break;\n            }\n            case 3: { // up\n                int yrow = d[i];\n                for (int xc = a[i]; xc < c[i]; ++xc) {\n                    occ[static_cast<size_t>(yrow) * W + xc] = static_cast<uint8_t>(i + 1);\n                }\n                d[i] += 1;\n                area[i] += best_strip;\n                break;\n            }\n        }\n        return true;\n    };\n\n    vector<bool> active(n, true);\n    deque<int> q;\n    for (int i = 0; i < n; ++i) {\n        if (area[i] < r[i]) q.push_back(i);\n        else active[i] = false;\n    }\n\n    while (!q.empty()) {\n        int i = q.front();\n        q.pop_front();\n        if (!active[i]) continue;\n        if (area[i] >= r[i]) {\n            active[i] = false;\n            continue;\n        }\n        if (try_expand(i)) {\n            if (area[i] < r[i]) {\n                q.push_back(i);\n            }\n        } else {\n            active[i] = false;\n        }\n    }\n\n    for (int i = 0; i < n; ++i) {\n        cout << a[i] << ' ' << b[i] << ' ' << c[i] << ' ' << d[i] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Result {\n    string path;\n    int score;\n};\n\n/* Simulate a walk starting from (si,sj) with given already\u2011used cells/tiles.\n   The function returns the walk string and the score gained *after* the start   cell (the start cell's value is NOT added here \u2013 the caller adds it). */\nResult simulateFrom(int si, int sj,\n                    const vector<vector<int>>& t,\n                    const vector<vector<int>>& p,\n                    const vector<vector<int>>& partnerP,\n                    int M,\n                    int seed,\n                    double lambda,\n                    double exploreBase,\n                    vector<vector<bool>>& usedCell,\n                    vector<bool>& usedTile) {\n    vector<vector<bool>> locUsed = usedCell;\n    vector<bool> locUsedTile = usedTile;\n    int ci = si, cj = sj;\n    string path;\n    int score = 0;\n    int visitedTiles = 0;\n    mt19937 rng(seed);\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char dirChar[4] = {'U', 'D', 'L', 'R'};\n\n    while (true) {\n        struct Candidate {\n            int dir;      // 0..3\n            int forward;  // onward degree\n            int val;      // p of neighbour\n        };\n        vector<Candidate> cand;\n        for (int d = 0; d < 4; ++d) {\n            int ni = ci + di[d];\n            int nj = cj + dj[d];\n            if (ni < 0 || ni >= 50 || nj < 0 || nj >= 50) continue;\n            if (locUsed[ni][nj]) continue;\n            int tid = t[ni][nj];\n            if (locUsedTile[tid]) continue;\n\n            int fwd = 0;\n            for (int d2 = 0; d2 < 4; ++d2) {\n                int ni2 = ni + di[d2];\n                int nj2 = nj + dj[d2];\n                if (ni2 < 0 || ni2 >= 50 || nj2 < 0 || nj2 >= 50) continue;\n                if (locUsed[ni2][nj2]) continue;\n                int tid2 = t[ni2][nj2];\n                if (locUsedTile[tid2]) continue;\n                ++fwd;\n            }\n            cand.push_back({d, fwd, p[ni][nj]});\n        }\n        if (cand.empty()) break;\n\n        double explore = exploreBase * pow(1.0 - visitedTiles / (double)M, 1.5);\n        uniform_real_distribution<double> realDist(0.0, 1.0);\n        int chosen;\n        if (realDist(rng) < explore) {\n            uniform_int_distribution<int> intDist(0, (int)cand.size() - 1);\n            chosen = cand[intDist(rng)].dir;\n        } else {\n            double bestScore = -1e9;\n            vector<int> bestDirs;\n            for (auto &c : cand) {\n                int ni = ci + di[c.dir];\n                int nj = cj + dj[c.dir];\n                double base = p[ni][nj];\n                int partner = partnerP[ni][nj];\n                double modified = base;\n                if (partner != -1 && partner > base) {\n                    modified = base - 0.5 * (partner - base); // gamma = 0.5\n                }\n                double sc = modified - lambda * c.forward;\n                if (sc > bestScore + 1e-12) {\n                    bestScore = sc;\n                    bestDirs.clear();\n                    bestDirs.push_back(c.dir);\n                } else if (abs(sc - bestScore) <= 1e-12) {\n                    bestDirs.push_back(c.dir);\n                }\n            }\n            uniform_int_distribution<int> intDist(0, (int)bestDirs.size() - 1);\n            chosen = bestDirs[intDist(rng)];\n        }\n\n        ci += di[chosen];\n        cj += dj[chosen];\n        locUsed[ci][cj] = true;\n        int tid = t[ci][cj];\n        locUsedTile[tid] = true;\n        ++visitedTiles;\n        path.push_back(dirChar[chosen]);\n        score += p[ci][cj];\n        if (visitedTiles == M) break;\n    }\n    return {path, score};\n}\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    vector<vector<int>> t(50, vector<int>(50));\n    vector<vector<int>> p(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            cin >> t[i][j];\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            cin >> p[i][j];\n    \n    int maxTileId = 0;\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            maxTileId = max(maxTileId, t[i][j]);\n    int M = maxTileId + 1;          // tile ids are 0 .. M-1\n    \n    // partnerP[i][j] = value of the other cell in the same domino, -1 if monomer\n    vector<vector<int>> partnerP(50, vector<int>(50, -1));\n    vector<vector<pair<int,int>>> tileCells(M);\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j)\n            tileCells[t[i][j]].push_back({i, j});\n    for (int id = 0; id < M; ++id) {\n        if (tileCells[id].size() == 2) {\n            auto [i1, j1] = tileCells[id][0];\n            auto [i2, j2] = tileCells[id][1];\n            partnerP[i1][j1] = p[i2][j2];\n            partnerP[i2][j2] = p[i1][j1];\n        }\n    }\n    \n    const int GLOBAL_ITER = 800;   // number of different random restarts\n    const int LOCAL_ITER  = 20;    // local improvement attempts per restart\n    Result best;\n    best.score = -1;\n        mt19937 rngSeed(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_real_distribution<double> lambdaDist(0.4, 0.7);\n    uniform_real_distribution<double> exploreDist(0.2, 0.4);\n    \n    for (int g = 0; g < GLOBAL_ITER; ++g) {\n        unsigned seed = chrono::steady_clock::now().time_since_epoch().count() + g * 123457u;\n        double lambda = lambdaDist(rngSeed);\n        double exploreBase = exploreDist(rngSeed);\n        \n        // ---- build initial walk with the heuristic ----\n        vector<vector<bool>> usedCell(50, vector<bool>(50, false));\n        vector<bool> usedTile(M, false);\n        int ci = si, cj = sj;\n        usedCell[ci][cj] = true;\n        int startTile = t[ci][cj];\n        usedTile[startTile] = true;\n        \n        string path;\n        int score = p[ci][cj];\n        int visitedTiles = 1;\n        mt19937 rng(seed);\n        const int di[4] = {-1, 1, 0, 0};\n        const int dj[4] = {0, 0, -1, 1};\n        const char dirChar[4] = {'U', 'D', 'L', 'R'};\n        \n        while (true) {\n            struct Candidate {\n                int dir;      // 0..3\n                int forward;  // onward degree\n                int val;      // p of neighbour\n            };\n            vector<Candidate> cand;\n            for (int d = 0; d < 4; ++d) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                if (ni < 0 || ni >= 50 || nj < 0 || nj >= 50) continue;\n                if (usedCell[ni][nj]) continue;\n                int tid = t[ni][nj];\n                if (usedTile[tid]) continue;\n                int fwd = 0;\n                for (int d2 = 0; d2 < 4; ++d2) {\n                    int ni2 = ni + di[d2];\n                    int nj2 = nj + dj[d2];\n                    if (ni2 < 0 || ni2 >= 50 || nj2 < 0 || nj2 >= 50) continue;\n                    if (usedCell[ni2][nj2]) continue;\n                    int tid2 = t[ni2][nj2];\n                    if (usedTile[tid2]) continue;\n                    ++fwd;\n                }\n                cand.push_back({d, fwd, p[ni][nj]});\n            }\n            if (cand.empty()) break;\n            \n            double explore = exploreBase * pow(1.0 - visitedTiles / (double)M, 1.5);\n            uniform_real_distribution<double> realDist(0.0, 1.0);\n            int chosen;\n            if (realDist(rng) < explore) {\n                uniform_int_distribution<int> intDist(0, (int)cand.size() - 1);\n                chosen = cand[intDist(rng)].dir;\n            } else {\n                double bestScore = -1e9;\n                vector<int> bestDirs;\n                for (auto &c : cand) {\n                    int ni = ci + di[c.dir];\n                    int nj = cj + dj[c.dir];\n                    double base = p[ni][nj];\n                    int partner = partnerP[ni][nj];\n                    double modified = base;\n                    if (partner != -1 && partner > base) {\n                        modified = base - 0.5 * (partner - base);\n                    }\n                    double sc = modified - lambda * c.forward;\n                    if (sc > bestScore + 1e-12) {\n                        bestScore = sc;\n                        bestDirs.clear();\n                        bestDirs.push_back(c.dir);\n                    } else if (abs(sc - bestScore) <= 1e-12) {\n                        bestDirs.push_back(c.dir);\n                    }\n                }\n                uniform_int_distribution<int> intDist(0, (int)bestDirs.size() - 1);\n                chosen = bestDirs[intDist(rng)];\n            }\n            \n            ci += di[chosen];\n            cj += dj[chosen];\n            usedCell[ci][cj] = true;\n            int tid = t[ci][cj];\n            usedTile[tid] = true;\n            ++visitedTiles;\n            path.push_back(dirChar[chosen]);\n            score += p[ci][cj];\n            if (visitedTiles == M) break;\n        }\n        \n        // ---- local improvement: try to rewrite suffixes ----\n        for (int loc = 0; loc < LOCAL_ITER; ++loc) {\n            // pick a cut point uniformly in [0, path.length()]\n            uniform_int_distribution<int> cutDist(0, (int)path.size());\n            int cut = cutDist(rngSeed);\n            \n            // rebuild used state for the prefix [0, cut-1]\n            vector<vector<bool>> prefUsed(50, vector<bool>(50, false));\n            vector<bool> prefUsedTile(M, false);\n            int pi = si, pj = sj;\n            prefUsed[pi][pj] = true;\n            int startTile = t[pi][pj];\n            prefUsedTile[startTile] = true;\n            int prefScore = p[pi][pj];\n            for (int k = 0; k < cut; ++k) {\n                char ch = path[k];\n                int d = (ch == 'U' ? 0 : ch == 'D' ? 1 : ch == 'L' ? 2 : 3);\n                pi += di[d];\n                pj += dj[d];\n                prefUsed[pi][pj] = true;\n                int tid = t[pi][pj];\n                prefUsedTile[tid] = true;\n                prefScore += p[pi][pj];\n            }\n            \n            // simulate a suffix starting from (pi,pj) with the prefix state\n            Result suf = simulateFrom(pi, pj, t, p, partnerP, M,\n                                      rngSeed() + loc * 999983 + cut * 7,\n                                      lambda, exploreBase,\n                                      prefUsed, prefUsedTile);\n            string candPath = path.substr(0, cut) + suf.path;\n            int candScore = prefScore + suf.score;\n            if (candScore > best.score) {\n                best.path = candPath;\n                best.score = candScore;\n            }\n        }\n        \n        // also consider the whole path as candidate\n        if (score > best.score) {\n            best.path = path;\n            best.score = score;\n        }\n    }\n    \n    cout << best.path << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;                     // grid size\nconst int HN = N;                     // rows for horizontal edges\nconst int WN = N - 1;                 // columns for horizontal edges\nconst int VN = N - 1;                 // rows for vertical edges\nconst int VM = N;                     // columns for vertical edges\n\nusing EdgeWeight = double;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // ----- estimates of edge lengths -----\n    vector<vector<EdgeWeight>> h(HN, vector<EdgeWeight>(WN, 5000.0)); // horizontal edges\n    vector<vector<EdgeWeight>> v(VN, vector<EdgeWeight>(VM, 5000.0)); // vertical   edges\n\n    const double eta = 0.2;          // learning rate\n    const double MINW = 500.0, MAXW = 15000.0;\n\n    for (int query = 0; query < 1000; ++query) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) break;   // end of input\n\n        // ---------- Dijkstra on current estimates ----------\n        const int V = N * N;\n        const double INF = 1e100;\n        vector<double> dist(V, INF);\n        vector<int> prev(V, -1);\n        using State = pair<double, int>;\n        priority_queue<State, vector<State>, greater<State>> pq;\n\n        auto idx = [&](int i, int j) { return i * N + j; };\n        int s = idx(si, sj);\n        int t = idx(ti, tj);\n        dist[s] = 0.0;\n        pq.emplace(0.0, s);\n\n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u] + 1e-12) continue;\n            int ui = u / N, uj = u % N;\n            // up\n            if (ui > 0) {\n                int ni = ui - 1, nj = uj;\n                double w = static_cast<double>(v[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // down\n            if (ui < N - 1) {\n                int ni = ui + 1, nj = uj;\n                double w = static_cast<double>(v[ui][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // left\n            if (uj > 0) {\n                int ni = ui, nj = uj - 1;\n                double w = static_cast<double>(h[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n            // right\n            if (uj < N - 1) {\n                int ni = ui, nj = uj + 1;\n                double w = static_cast<double>(h[ni][nj]);\n                int vtx = idx(ni, nj);\n                if (dist[u] + w < dist[vtx] - 1e-12) {\n                    dist[vtx] = dist[u] + w;\n                    prev[vtx] = u;\n                    pq.emplace(dist[vtx], vtx);\n                }\n            }\n        }\n\n        // ---------- reconstruct path ----------\n        vector<int> rev;\n        for (int cur = t; cur != -1; cur = prev[cur]) rev.push_back(cur);\n        reverse(rev.begin(), rev.end());\n\n        string moves;\n        moves.reserve(rev.size() * 2);\n        double predicted = 0.0;\n        int path_len = 0;\n\n        for (size_t i = 1; i < rev.size(); ++i) {\n            int a = rev[i - 1], b = rev[i];\n            int ai = a / N, aj = a % N;\n            int bi = b / N, bj = b % N;\n            char ch;\n            if (ai == bi && aj == bj + 1) { ch = 'L'; predicted += h[ai][bj]; --aj; }\n            else if (ai == bi && aj == bj - 1) { ch = 'R'; predicted += h[ai][aj]; ++aj; }\n            else if (aj == bj && ai == bi + 1) { ch = 'U'; predicted += v[bi][aj]; --ai; }\n            else if (aj == bj && ai == bi - 1) { ch = 'D'; predicted += v[ai][aj]; ++ai; }\n            else { ch = '?'; } // should never happen\n            moves.push_back(ch);\n            ++path_len;\n        }\n\n        cout << moves << '\\n';\n        cout.flush();\n\n        // ---------- read judge feedback ----------\n        int y;\n        if (!(cin >> y)) break;   // defensive\n\n        // ---------- SGD update ----------\n        if (path_len > 0) {\n            double error = static_cast<double>(y) - predicted;\n            double delta = eta * error / static_cast<double>(path_len);\n\n            int ci = si, cj = sj;\n            for (char ch : moves) {\n                if (ch == 'U') {\n                    v[ci - 1][cj] += delta;\n                    if (v[ci - 1][cj] < MINW) v[ci - 1][cj] = MINW;\n                    if (v[ci - 1][cj] > MAXW) v[ci - 1][cj] = MAXW;\n                    --ci;\n                } else if (ch == 'D') {\n                    v[ci][cj] += delta;\n                    if (v[ci][cj] < MINW) v[ci][cj] = MINW;\n                    if (v[ci][cj] > MAXW) v[ci][cj] = MAXW;\n                    ++ci;\n                } else if (ch == 'L') {\n                    h[ci][cj - 1] += delta;\n                    if (h[ci][cj - 1] < MINW) h[ci][cj - 1] = MINW;\n                    if (h[ci][cj - 1] > MAXW) h[ci][cj - 1] = MAXW;\n                    --cj;\n                } else if (ch == 'R') {\n                    h[ci][cj] += delta;\n                    if (h[ci][cj] < MINW) h[ci][cj] = MINW;\n                    if (h[ci][cj] > MAXW) h[ci][cj] = MAXW;\n                    ++cj;\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int FIXED_N = 20; // N is fixed to 20 in the problem\n\nstruct CellEntry {\n    int pid;      // placement id\n    uint8_t off;  // offset within the placement\n};\n\nstruct State {\n    int N, M;\n    vector<string> raw;\n    vector<vector<int>> a; // the matrix, 0-7 for letters, 8 for dot\n    vector<int> placement_sid;\n    vector<vector<vector<CellEntry>>> cell_entries;\n    vector<int> placement_mismatch;\n    vector<int> match_cnt_str;\n    int satisfied;\n    int dot_count;\n\n    State(int N, int M, const vector<string>& strs) : \n        N(N), M(M), raw(strs),         a(N, vector<int>(N)), \n        placement_sid(), \n        cell_entries(N, vector<vector<CellEntry>>(N)), \n        placement_mismatch(), \n        match_cnt_str(M, 0), \n        satisfied(0),\n        dot_count(0) {\n        // initialize the matrix randomly\n        mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n        uniform_int_distribution<int> dist_val(0, 7);\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                a[i][j] = dist_val(rng);\n            }\n        }\n        build_placements();\n    }\n\n    void build_placements() {\n        const int dr[2] = {0, 1};\n        const int dc[2] = {1, 0};\n        for (int sid = 0; sid < M; ++sid) {\n            const string& s = raw[sid];\n            int L = (int)s.size();\n            for (int dir = 0; dir < 2; ++dir) {\n                for (int sr = 0; sr < N; ++sr) {\n                    for (int sc = 0; sc < N; ++sc) {\n                        int pid = (int)placement_sid.size();\n                        placement_sid.push_back(sid);\n                        int mis = 0;\n                        for (int k = 0; k < L; ++k) {\n                            int r = (sr + dr[dir] * k) % N;\n                            int c = (sc + dc[dir] * k) % N;\n                            cell_entries[r][c].push_back({pid, (uint8_t)k});\n                            int required = raw[sid][k] - 'A';\n                            if (a[r][c] != required) ++mis;\n                        }\n                        placement_mismatch.push_back(mis);\n                        if (mis == 0) {\n                            ++match_cnt_str[sid];\n                        }\n                    }\n                }\n            }\n        }\n        for (int sid = 0; sid < M; ++sid) {\n            if (match_cnt_str[sid] > 0) ++satisfied;\n        }\n    }\n\n    int evaluate_delta(int r, int c, int new_val) {\n        int old_val = a[r][c];\n        if (old_val == new_val) return 0;\n        vector<int> delta_match(M, 0);\n        vector<int> touched;\n        touched.reserve(100); // reserve some space to avoid reallocations\n\n        for (const auto& e : cell_entries[r][c]) {\n            int pid = e.pid;\n            int off = e.off;\n            int sid = placement_sid[pid];\n            int required = raw[sid][off] - 'A';\n            int old_matched = (old_val == required);\n            int new_matched = (new_val == required);\n            int delta_mismatch = old_matched - new_matched; // change in mismatch count\n            int old_mis = placement_mismatch[pid];\n            bool old_match = (old_mis == 0);\n            int new_mis = old_mis + delta_mismatch;\n            bool new_match = (new_mis == 0);\n            if (old_match != new_match) {\n                int delta = new_match ? 1 : -1;\n                if (delta_match[sid] == 0) touched.push_back(sid);\n                delta_match[sid] += delta;\n            }\n        }\n\n        int delta_sat = 0;\n        for (int sid : touched) {\n            int old_match_cnt = match_cnt_str[sid];\n            bool old_sat = (old_match_cnt > 0);\n            int new_match_cnt = old_match_cnt + delta_match[sid];\n            bool new_sat = (new_match_cnt > 0);\n            if (!old_sat && new_sat) ++delta_sat;\n            else if (old_sat && !new_sat) --delta_sat;\n        }\n        return delta_sat;\n    }\n\n    void apply_change(int r, int c, int new_val) {\n        int old_val = a[r][c];\n        if (old_val == new_val) return;\n        a[r][c] = new_val;\n        // update dot count\n        if (old_val == 8) --dot_count;\n        if (new_val == 8) ++dot_count;\n\n        for (const auto& e : cell_entries[r][c]) {\n            int pid = e.pid;\n            int off = e.off;\n            int sid = placement_sid[pid];\n            int required = raw[sid][off] - 'A';\n            int old_matched = (old_val == required);\n            int new_matched = (new_val == required);\n            int delta_mismatch = old_matched - new_matched;\n            int& mis = placement_mismatch[pid];\n            int old_mis = mis;\n            bool old_match = (old_mis == 0);\n            mis += delta_mismatch;\n            bool new_match = (mis == 0);\n            if (old_match != new_match) {\n                int delta = new_match ? 1 : -1;\n                int old_match_cnt = match_cnt_str[sid];\n                match_cnt_str[sid] += delta;\n                int new_match_cnt = match_cnt_str[sid];\n                bool old_sat = (old_match_cnt > 0);\n                bool new_sat = (new_match_cnt > 0);\n                if (!old_sat && new_sat) ++satisfied;\n                else if (old_sat && !new_sat) --satisfied;\n            }\n        }\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    cin >> N >> M; // N will be 20, but we read it anyway\n    vector<string> strs(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strs[i];\n    }\n\n    State state(N, M, strs);\n\n    // Simulated annealing to maximize number of satisfied strings\n    const int MAX_ITER = 20000;\n    double start_temp = 2.0;\n    double end_temp = 0.001;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_cell(0, N - 1);\n    uniform_int_distribution<int> dist_val_full(0, 8); // 0-7 letters, 8 for '.'\n    uniform_real_distribution<double> dist_real(0.0, 1.0);\n\n    for (int it = 0; it < MAX_ITER; ++it) {\n        double t = start_temp * pow(end_temp / start_temp, (double)it / MAX_ITER);\n        int r = dist_cell(rng);\n        int c = dist_cell(rng);\n        int cur = state.a[r][c];\n        int nv = dist_val_full(rng);\n        if (nv == cur) continue;\n        int delta = state.evaluate_delta(r, c, nv);\n        bool accept = false;\n        if (delta > 0) accept = true;\n        else if (delta == 0 && dist_real(rng) < 0.1) accept = true;\n        else if (dist_real(rng) < exp(delta / t)) accept = true;\n        if (accept) {\n            state.apply_change(r, c, nv);\n        }\n    }\n\n    // Greedy phase: turn non-dot cells into '.' if it does not break any satisfied string\n    bool improved;\n    do {\n        improved = false;\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (state.a[r][c] == 8) continue; // already dot\n                if (state.evaluate_delta(r, c, 8) == 0) {\n                    state.apply_change(r, c, 8);\n                    improved = true;\n                }\n            }\n        }\n    } while (improved);\n\n    // Output the matrix\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int v = state.a[i][j];\n            if (v == 8) putchar('.');\n            else putchar('A' + v);\n        }\n        putchar('\\n');\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }\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 (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\nstruct Edge {\n    int u, v;\n    long long cost;\n    bool operator<(const Edge& other) const {\n        return cost < other.cost;\n    }\n};\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    vector<vector<int>> id(N, vector<int>(N, -1));\n    vector<pair<int,int>> pos;\n    vector<int> w;\n    auto get_id = [&](int i, int j) -> int {\n        if (id[i][j] != -1) return id[i][j];\n        int cur = (int)pos.size();\n        id[i][j] = cur;\n        pos.emplace_back(i, j);\n        w.push_back(grid[i][j] - '0');\n        return cur;\n    };\n\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (grid[i][j] != '#')\n                get_id(i, j);\n\n    int V = (int)pos.size();\n    if (V == 0) { cout << '\\n'; return 0; }\n\n    vector<Edge> edges;\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == '#') continue;\n            int uid = id[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d], nj = j + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                if (grid[ni][nj] == '#') continue;\n                int vid = id[ni][nj];\n                if (uid < vid) {\n                    edges.push_back({uid, vid, (long long)w[uid] + w[vid]});\n                }\n            }\n        }\n\n    sort(edges.begin(), edges.end());\n    DSU dsu(V);\n    vector<vector<int>> tree(V);\n    for (const auto& e : edges) {\n        if (dsu.unite(e.u, e.v)) {\n            tree[e.u].push_back(e.v);\n            tree[e.v].push_back(e.u);\n        }\n    }\n\n    int start = id[si][sj];\n    string ans;\n    auto dir_char = [&](int from, int to) -> char {\n        int x1 = pos[from].first, y1 = pos[from].second;\n        int x2 = pos[to].first,   y2 = pos[to].second;\n        if (x2 == x1 - 1) return 'U';\n        if (x2 == x1 + 1) return 'D';\n        if (y2 == y1 - 1) return 'L';\n        if (y2 == y1 + 1) return 'R';\n        return '?';\n    };\n\n    function<void(int, int)> dfs = [&](int u, int p) {\n        for (int v : tree[u]) {\n            if (v == p) continue;\n            ans.push_back(dir_char(u, v));\n            dfs(v, u);\n            ans.push_back(dir_char(v, u));\n        }\n    };\n\n    dfs(start, -1);\n    cout << ans << '\\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 task difficulty vectors\n    vector<array<int, 20>> d(N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    // build dependency graph (edges u -> v, u < v)\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    // dp[i] = length of longest path (in edges) starting from i\n    vector<int> dp(N, 0);\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    // priority queue of ready tasks: higher dp first\n    using TaskInfo = pair<int, int>; // dp, task index\n    priority_queue<TaskInfo> pq;\n    vector<int> task_state(N, 0); // 0 = not started, 1 = started, 2 = completed    for (int i = 0; i < N; ++i) {\n        if (indeg[i] == 0 && task_state[i] == 0) {\n            pq.push({dp[i], i});\n        }\n    }\n\n    // worker state\n    vector<int> worker_task(M, -1);       // task assigned to worker, -1 = idle\n    vector<int> worker_start_day(M, 0);   // start day of current task (valid if not idle)\n    vector<bool> worker_idle(M, true);    // true if idle\n    vector<int> finished_today;           // workers that finished at end of previous day\n\n    int day = 1;\n    while (true) {\n        // 1) process completions from previous day        for (int w : finished_today) {\n            int task = worker_task[w];\n            // t = (day-1) - start_day + 1 = day - start_day            int t = day - worker_start_day[w];\n            // (optional) could use t to infer skill levels here\n\n            // mark task as completed\n            if (task_state[task] != 1) {\n                // defensive: should not happen\n            }\n            task_state[task] = 2;\n            for (int succ : adj[task]) {\n                if (--indeg[succ] == 0 && task_state[succ] == 0) {\n                    pq.push({dp[succ], succ});\n                }\n            }\n            worker_task[w] = -1;\n            worker_idle[w] = true;\n        }\n        finished_today.clear();\n\n        // 2) assign tasks to idle workers\n        vector<pair<int, int>> assignments; // (worker+1, task+1)\n        for (int w = 0; w < M; ++w) {\n            if (!worker_idle[w]) continue;\n            if (pq.empty()) break;\n            auto [dpval, task] = pq.top(); pq.pop();\n            worker_task[w] = task;\n            worker_start_day[w] = day;\n            worker_idle[w] = false;\n            task_state[task] = 1;\n            assignments.emplace_back(w + 1, task + 1);\n        }\n\n        // 3) output assignments for today\n        cout << assignments.size();\n        for (auto &p : assignments) {\n            cout << ' ' << p.first << ' ' << p.second;\n        }\n        cout << '\\n';\n        cout.flush();\n\n        // 4) read response (workers that finished at end of today)\n        string line;\n        if (!getline(cin, line)) break;\n        stringstream ss(line);\n        int first;\n        if (!(ss >> first)) break;\n        if (first == -1) break; // all tasks done or day limit exceeded\n        int n = first;\n        finished_today.clear();\n        for (int i = 0; i < n; ++i) {\n            int w;\n            ss >> w;\n            finished_today.push_back(w - 1);\n        }\n\n        ++day;\n        // safety stop (judge will send -1 after day 2000 anyway)\n        if (day > 2000) {\n            // we will still rely on -1 to break\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Point = pair<int, int>;\n\nconst int CENTER_X = 400;\nconst int CENTER_Y = 400;\nconst int MAX_ORDERS = 1000;\nconst int SELECT_SIZE = 50;\n\nint A[MAX_ORDERS], B[MAX_ORDERS], C[MAX_ORDERS], D[MAX_ORDERS];\n\nstruct Result {\n    ll dist;\n    vector<int> order;          // 1\u2011based indices in pickup order\n    vector<Point> route;        // full route (starts/ends at center)\n};\n\ninline int manh(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// total length of a route given as vector of points\nll routeLength(const vector<Point>& r) {\n    ll len = 0;\n    for (size_t i = 0; i + 1 < r.size(); ++i)\n        len += manh(r[i].first, r[i].second, r[i+1].first, r[i+1].second);\n    return len;\n}\n\n// Build a feasible route for a given set of order indices (0\u2011based)\n// Greedy: at each step go to the closest feasible point (pickup not yet taken,\n// or delivery whose pickup has been taken but delivery not yet).\nResult computeRoute(const vector<int>& sel) {\n    vector<bool> visPick(MAX_ORDERS, false), visDel(MAX_ORDERS, false);\n    vector<Point> route;\n    route.emplace_back(CENTER_X, CENTER_Y);\n    int curX = CENTER_X, curY = CENTER_Y;\n    vector<int> orderVis;\n    int remaining = 2 * (int)sel.size();\n\n    while (remaining > 0) {\n        int bestId = -1;\n        bool isPick = false;\n        int bestDist = INT_MAX;\n        for (int id : sel) {\n            if (!visPick[id]) {\n                int d = manh(curX, curY, A[id], B[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = true;\n                }\n            }\n            if (visPick[id] && !visDel[id]) {\n                int d = manh(curX, curY, C[id], D[id]);\n                if (d < bestDist) {\n                    bestDist = d; bestId = id; isPick = false;\n                }\n            }\n        }\n        if (isPick) {\n            route.emplace_back(A[bestId], B[bestId]);\n            visPick[bestId] = true;\n            orderVis.push_back(bestId + 1); // store 1\u2011based index\n            curX = A[bestId]; curY = B[bestId];\n        } else {\n            route.emplace_back(C[bestId], D[bestId]);\n            visDel[bestId] = true;\n            curX = C[bestId]; curY = D[bestId];\n        }\n        --remaining;\n    }\n    route.emplace_back(CENTER_X, CENTER_Y);\n\n    ll total = routeLength(route);\n    return {total, orderVis, route};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    for (int i = 0; i < MAX_ORDERS; ++i) {\n        cin >> A[i] >> B[i] >> C[i] >> D[i];\n    }\n\n    // ----- initial selections -------------------------------------------------\n    vector<int> idx(MAX_ORDERS);\n    iota(idx.begin(), idx.end(), 0);\n\n    vector<vector<int>> initialSelections;\n\n    // 1. smallest round\u2011trip via center\n    sort(idx.begin(), idx.end(), [&](int i, int j) {\n        int wi = manh(CENTER_X, CENTER_Y, A[i], B[i]) +\n                 manh(A[i], B[i], C[i], D[i]) +\n                 manh(C[i], D[i], CENTER_X, CENTER_Y);\n        int wj = manh(CENTER_X, CENTER_Y, A[j], B[j]) +\n                 manh(A[j], B[j], C[j], D[j]) +\n                 manh(C[j], D[j], CENTER_X, CENTER_Y);\n        return wi < wj;\n    });\n    initialSelections.push_back(vector<int>(idx.begin(), idx.begin() + SELECT_SIZE));\n\n    // 2. random selection\n    {\n        vector<int> rnd(SELECT_SIZE);\n        mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n        uniform_int_distribution<int> dist(0, MAX_ORDERS - 1);\n        vector<bool> taken(MAX_ORDERS, false);\n        int cnt = 0;\n        while (cnt < SELECT_SIZE) {\n            int x = dist(rng);\n            if (!taken[x]) {\n                taken[x] = true;\n                rnd[cnt++] = x;\n            }\n        }\n        initialSelections.push_back(rnd);\n    }\n\n    // 3. selection by nearest pickup to center only\n    {\n        vector<int> orderByPickup = idx;\n        sort(orderByPickup.begin(), orderByPickup.end(),\n             [&](int i, int j) {\n                 return manh(CENTER_X, CENTER_Y, A[i], B[i]) <\n                        manh(CENTER_X, CENTER_Y, A[j], B[j]);\n             });\n        vector<int> pick50(orderByPickup.begin(),\n                           orderByPickup.begin() + SELECT_SIZE);\n        initialSelections.push_back(pick50);\n    }\n\n    // ----- local search -------------------------------------------------------\n    const int MAX_ITER = 3000;\n    mt19937 rng2(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distPos(0, SELECT_SIZE - 1);\n    uniform_int_distribution<int> distId(0, MAX_ORDERS - 1);\n\n    ll bestDist = LLONG_MAX;\n    vector<int> bestOrder;\n    vector<Point> bestRoute;\n\n    auto currentTime = []() {\n        return chrono::duration<double>(\n            chrono::steady_clock::now().time_since_epoch()\n        ).count();\n    };\n    double startTime = currentTime();\n    double timeLimit = 1.8; // seconds, leave margin\n\n    for (const auto& initSel : initialSelections) {\n        if (currentTime() - startTime > timeLimit) break;\n        vector<int> curSel = initSel;\n        vector<bool> inSel(MAX_ORDERS, false);\n        for (int id : curSel) inSel[id] = true;\n\n        auto [dist, order, route] = computeRoute(curSel);\n        if (dist < bestDist) {\n            bestDist = dist;\n            bestOrder = order;\n            bestRoute = route;\n        }\n\n        for (int it = 0; it < MAX_ITER; ++it) {\n            if (currentTime() - startTime > timeLimit) break;\n            int pos = distPos(rng2);\n            int outId = curSel[pos];\n            int inId;\n            do {\n                inId = distId(rng2);\n            } while (inSel[inId]);\n\n            // perform swap\n            curSel[pos] = inId;\n            inSel[outId] = false;\n            inSel[inId] = true;\n\n            auto [ndist, norder, nroute] = computeRoute(curSel);\n            if (ndist < bestDist) {\n                bestDist = ndist;\n                bestOrder = norder;\n                bestRoute = nroute;\n            } else {\n                // revert swap\n                curSel[pos] = outId;\n                inSel[outId] = true;\n                inSel[inId] = false;\n            }\n        }\n    }\n\n    // ----- output -------------------------------------------------------------\n    cout << SELECT_SIZE << ' ';\n    for (size_t i = 0; i < bestOrder.size(); ++i) {\n        if (i) cout << ' ';\n        cout << bestOrder[i];\n    }\n    cout << '\\n';\n    cout << bestRoute.size();\n    for (auto &p : bestRoute) {\n        cout << ' ' << p.first << ' ' << p.second;\n    }\n    cout << '\\n';\n    cout << flush;\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, sz;\n    DSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }\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 (sz[a] < sz[b]) swap(a, b);\n        p[b] = a;\n        sz[a] += sz[b];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 400;\n    const int M = 1995;\n\n    // read vertex coordinates\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; ++i) cin >> x[i] >> y[i];\n\n    // read edge endpoints\n    vector<int> u(M), v(M);\n    for (int i = 0; i < M; ++i) cin >> u[i] >> v[i];\n\n    DSU dsu(N);\n    int taken = 0;                 // number of edges already accepted\n    const int needed = N - 1;      // we need exactly N\u20111 edges for a spanning tree\n\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;                  // true length (not needed for the decision)\n\n        bool useful = (dsu.find(u[i]) != dsu.find(v[i]));\n        if (useful && taken < needed) {\n            cout << 1 << '\\n';\n            cout.flush();\n            dsu.unite(u[i], v[i]);\n            ++taken;\n        } else {\n            cout << 0 << '\\n';\n            cout.flush();\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;\n    vector<int> px(N), py(N);\n    for (int i = 0; i < N; ++i) {\n        int t; cin >> px[i] >> py[i] >> t; // type is read but not used\n    }\n\n    int M;\n    cin >> M;\n    vector<int> hx(M), hy(M);\n    for (int i = 0; i < M; ++i) cin >> hx[i] >> hy[i];\n\n    // blocked[x][y] = true if the square is impassable due to a wall\n    bool blocked[31][31] = {};\n    // humanOccupied[x][y] = true if a human initially stands here (humans never move)\n    bool humanOccupied[31][31] = {};\n    for (int i = 0; i < M; ++i) {\n        humanOccupied[hx[i]][hy[i]] = true;\n    }\n\n    // direction vectors for U,D,L,R (lowercase actions)\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\n    for (int turn = 0; turn < 300; ++turn) {\n        string ans(M, '.'); // default: do nothing\n\n        // Decide actions for each human\n        for (int i = 0; i < M; ++i) {\n            int x = hx[i];\n            int y = hy[i];\n            bool placed = false;\n            for (int d = 0; d < 4 && !placed; ++d) {\n                int nx = x + dx[d];\n                int ny = y + dy[d];\n                // outside the grid is already impassable                if (nx < 1 || nx > 30 || ny < 1 || ny > 30) continue;\n                // already blocked?\n                if (blocked[nx][ny]) continue;\n                // cannot block a square occupied by a pet or a human\n                bool isOccupied = false;\n                for (int p = 0; p < N; ++p) {\n                    if (px[p] == nx && py[p] == ny) { isOccupied = true; break; }\n                }\n                if (isOccupied) continue;\n                for (int p = 0; p < M; ++p) {\n                    if (hx[p] == nx && hy[p] == ny) { isOccupied = true; break; }\n                }\n                if (isOccupied) continue;\n\n                // check that none of the four neighbours of (nx,ny) contains a pet\n                bool ok = true;\n                for (int k = 0; k < 4; ++k) {\n                    int ax = nx + dx[k];\n                    int ay = ny + dy[k];\n                    if (ax < 1 || ax > 30 || ay < 1 || ay > 30) continue;\n                    for (int p = 0; p < N; ++p) {\n                        if (px[p] == ax && py[p] == ay) { ok = false; break; }\n                    }\n                    if (!ok) break;\n                }\n                if (!ok) continue;\n\n                // this direction is viable\n                ans[i] = dirChar[d];\n                placed = true;\n            }\n            // if no direction works, ans[i] stays '.'\n        }\n\n        // output actions\n        cout << ans << '\\n';\n        cout.flush();\n\n        // read pets' movement strings\n        vector<string> petMove(N);\n        for (int i = 0; i < N; ++i) {\n            if (!(cin >> petMove[i])) return 0;\n        }\n\n        // update pet positions according to their moves\n        for (int i = 0; i < N; ++i) {\n            int x = px[i];\n            int y = py[i];\n            for (char c : petMove[i]) {\n                if (c == 'U') x--;\n                else if (c == 'D') x++;\n                else if (c == 'L') y--;\n                else if (c == 'R') y++;\n                // the move is guaranteed to be to a passable square\n            }\n            px[i] = x;\n            py[i] = y;\n        }\n\n        // apply humans' actions (only lowercase letters affect the map)\n        for (int i = 0; i < M; ++i) {\n            char c = ans[i];\n            if (c == 'u') {\n                int nx = hx[i] - 1;\n                int ny = hy[i];\n                blocked[nx][ny] = true;\n            } else if (c == 'd') {\n                int nx = hx[i] + 1;\n                int ny = hy[i];\n                blocked[nx][ny] = true;\n            } else if (c == 'l') {\n                int nx = hx[i];\n                int ny = hy[i] - 1;\n                blocked[nx][ny] = true;\n            } else if (c == 'r') {\n                int nx = hx[i];\n                int ny = hy[i] + 1;\n                blocked[nx][ny] = true;\n            }\n            // '.' does nothing; uppercase moves are not used\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\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 lines, 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 (20 lines, each 20 characters)\n    vector<string> v(20);\n    for (int i = 0; i < 20; ++i) {\n        cin >> v[i];\n    }\n    \n    // BFS to find any path from home to office\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n    const char dir_char[4] = {'U', 'D', 'L', 'R'};\n    \n    vector<vector<bool>> vis(20, vector<bool>(20, false));\n    vector<vector<pair<int,int>>> prv(20, vector<pair<int,int>>(20, {-1, -1}));\n    vector<vector<char>> prv_dir(20, vector<char>(20, 0));\n    \n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    vis[si][sj] = true;\n    \n    while (!q.empty()) {\n        auto cur = q.front(); q.pop();\n        int x = cur.first;\n        int y = cur.second;\n        if (x == ti && y == tj) break;\n        for (int d = 0; d < 4; ++d) {\n            int nx = x + dx[d];\n            int ny = y + dy[d];\n            if (nx < 0 || nx >= 20 || ny < 0 || ny >= 20) continue;\n            \n            bool blocked = false;\n            if (d == 0) { // Up\n                if (x == 0) blocked = true;\n                else blocked = (v[x-1][y] == '1');\n            } else if (d == 1) { // Down\n                if (x == 19) blocked = true;\n                else blocked = (v[x][y] == '1');\n            } else if (d == 2) { // Left\n                if (y == 0) blocked = true;\n                else blocked = (h[x][y-1] == '1');\n            } else { // Right\n                if (y == 19) blocked = true;\n                else blocked = (h[x][y] == '1');\n            }\n            if (blocked) continue;\n            if (!vis[nx][ny]) {\n                vis[nx][ny] = true;\n                prv[nx][ny] = {x, y};\n                prv_dir[nx][ny] = dir_char[d];\n                q.push({nx, ny});\n            }\n        }\n    }\n    \n    // Reconstruct path from office to home\n    vector<char> rev;\n    int x = ti, y = tj;\n    while (!(x == si && y == sj)) {\n        char d = prv_dir[x][y];\n        rev.push_back(d);\n        auto cur = prv[x][y];\n        x = cur.first;\n        y = cur.second;\n    }\n    reverse(rev.begin(), rev.end());\n    string path(rev.begin(), rev.end());\n        int L = (int)path.size();\n    if (L == 0) {\n        cout << '\\n';\n        return 0;\n    }\n    int K = 200 / L; // maximum repetitions so total length <= 200\n    if (K == 0) K = 1;\n    string ans;\n    ans.reserve(L * K);\n    for (char c : path) {\n        ans.append(K, c);\n    }\n    if ((int)ans.size() > 200) ans.resize(200);\n    cout << ans << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ----- global data -----\narray<array<int, 30>, 30> tile;\nconst int di[4] = {0, -1, 0, 1};\nconst int dj[4] = {-1, 0, 1, 0};\nconst int toBase[8][4] = {\n    {1, 0, -1, -1}, //0\n    {3, -1, -1, 0}, //1\n    {-1, -1, 3, 2}, //2\n    {-1, 2, 1, -1}, //3\n    {1, 0, 3, 2},   //4\n    {3, 2, 1, 0},   //5\n    {2, -1, 0, -1}, //6\n    {-1, 3, -1, 1}  //7\n};\nint toRot[8][4][4]; // [tile][rot][dir] -> exit dir or -1// ----- score computation -----\nlong long computeScore(const vector<vector<int>>& rot) {\n    const int N = 30 * 30 * 4; // 3600\n    vector<int> stateOut(N, -1); // -1 means dead end    // build functional graph\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            int t = tile[i][j];\n            int r = rot[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int nd = toRot[t][r][d];\n                int id = ((i * 30) + j) * 4 + d;\n                if (nd == -1) continue; // stays -1\n                int ni = i + di[nd];\n                int nj = j + dj[nd];\n                if (ni < 0 || ni >= 30 || nj < 0 || nj >= 30) continue;\n                int opp = (nd + 2) & 3;\n                int t2 = tile[ni][nj];\n                int r2 = rot[ni][nj];\n                if (toRot[t2][r2][opp] == -1) continue;\n                int nid = ((ni * 30) + nj) * 4 + opp;\n                stateOut[id] = nid;\n            }\n        }\n    }\n\n    // find cycles in functional graph\n    vector<char> color(N, 0); // 0=unvisited,1=visiting,2=done\n    vector<int> posInPath(N, -1);\n    vector<int> path;\n    path.reserve(N);\n    long long best1 = 0, best2 = 0;\n\n    for (int u = 0; u < N; ++u) {\n        if (color[u]) continue;\n        int v = u;\n        while (true) {\n            if (color[v] == 0) {\n                color[v] = 1;\n                posInPath[v] = (int)path.size();\n                path.push_back(v);\n                int nxt = stateOut[v];\n                if (nxt == -1) break;\n                v = nxt;\n                continue;\n            }\n            if (color[v] == 1) {\n                int start = posInPath[v];\n                long long len = (long long)path.size() - start;\n                if (len > best1) {\n                    best2 = best1;\n                    best1 = len;\n                } else if (len > best2) {\n                    best2 = len;\n                }\n                break;\n            }\n            if (color[v] == 2) break;\n        }\n        for (int node : path) {\n            color[node] = 2;\n            posInPath[node] = -1;\n        }\n        path.clear();\n    }\n    return best1 * best2;\n}\n\n// ----- main -----\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read tile configuration\n    for (int i = 0; i < 30; ++i) {\n        string line;\n        getline(cin, line);\n        line.erase(remove(line.begin(), line.end(), ' '), line.end());\n        for (int j = 0; j < 30; ++j)\n            tile[i][j] = line[j] - '0';\n    }\n\n    // precompute toRot\n    for (int t = 0; t < 8; ++t) {\n        for (int rot = 0; rot < 4; ++rot) {\n            for (int d = 0; d < 4; ++d) {\n                int baseDir = (d + rot) & 3;\n                int baseExit = toBase[t][baseDir];\n                if (baseExit == -1) {\n                    toRot[t][rot][d] = -1;\n                } else {\n                    int exitDir = (baseExit - rot + 4) & 3;\n                    toRot[t][rot][d] = exitDir;\n                }\n            }\n        }\n    }\n\n    // hill climbing with random restarts\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distTile(0, 29);\n    uniform_int_distribution<int> distRot(0, 3);\n\n    long long bestScore = -1;\n    vector<vector<int>> bestRot(30, vector<int>(30, 0));\n\n    for (int restart = 0; restart < 5; ++restart) {\n        vector<vector<int>> curRot(30, vector<int>(30, 0));\n        for (int i = 0; i < 30; ++i)\n            for (int j = 0; j < 30; ++j)\n                curRot[i][j] = distRot(rng);\n        long long curScore = computeScore(curRot);\n\n        for (int iter = 0; iter < 200; ++iter) {\n            int i = distTile(rng);\n            int j = distTile(rng);\n            int cur = curRot[i][j];\n            int nr = distRot(rng);\n            if (nr == cur) continue;\n            curRot[i][j] = nr;\n            long long ns = computeScore(curRot);\n            if (ns > curScore) {\n                curScore = ns;\n            } else {\n                curRot[i][j] = cur; // revert\n            }\n        }\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestRot = curRot;\n        }\n    }\n\n    // output rotation counts\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            cout << bestRot[i][j];\n        }\n    }\n    cout << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions for empty movement: U, D, L, R\nconst int dr[4] = {-1, 1, 0, 0};\nconst int dc[4] = {0, 0, -1, 1};\nconst char dirChar[4] = {'U', 'D', 'L', 'R'};\n\nint computeLargestTreeSize(const vector<vector<int>>& board) {\n    int N = (int)board.size();\n    vector<vector<int>> deg(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int v = board[i][j];\n            if (v == 0) continue;\n            // up\n            if (i > 0 && board[i-1][j] != 0) {\n                if ((v & 2) && (board[i-1][j] & 8)) ++deg[i][j];\n            }\n            // down\n            if (i+1 < N && board[i+1][j] != 0) {\n                if ((v & 8) && (board[i+1][j] & 2)) ++deg[i][j];\n            }\n            // left\n            if (j > 0 && board[i][j-1] != 0) {\n                if ((v & 1) && (board[i][j-1] & 4)) ++deg[i][j];\n            }\n            // right\n            if (j+1 < N && board[i][j+1] != 0) {\n                if ((v & 4) && (board[i][j+1] & 1)) ++deg[i][j];\n            }\n        }\n    }\n    vector<vector<char>> vis(N, vector<char>(N, 0));\n    int best = 0;\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 cnt = 0;\n            int sumdeg = 0;\n            queue<pair<int,int>> q;\n            q.push({i, j});\n            vis[i][j] = 1;\n            while (!q.empty()) {\n                auto [x, y] = q.front(); q.pop();\n                ++cnt;\n                sumdeg += deg[x][y];\n                for (int d = 0; d < 4; ++d) {\n                    int nx = x + dr[d];\n                    int ny = y + dc[d];\n                    if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                    if (board[nx][ny] == 0) continue;\n                    if (vis[nx][ny]) continue;\n                    int a = board[x][y];\n                    int b = board[nx][ny];\n                    bool edge = false;\n                    if (nx == x-1 && ny == y) { // up\n                        if ((a & 2) && (b & 8)) edge = true;\n                    } else if (nx == x+1 && ny == y) { // down\n                        if ((a & 8) && (b & 2)) edge = true;\n                    } else if (nx == x && ny == y-1) { // left\n                        if ((a & 1) && (b & 4)) edge = true;\n                    } else if (nx == x && ny == y+1) { // right\n                        if ((a & 4) && (b & 1)) edge = true;\n                    }\n                    if (edge) {\n                        vis[nx][ny] = 1;\n                        q.push({nx, ny});\n                    }\n                }\n            }\n            int edges = sumdeg / 2;\n            if (edges == cnt - 1) { // tree component\n                if (cnt > best) best = cnt;\n            }\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, T;\n    if (!(cin >> N >> T)) return 0;\n    vector<string> raw(N);\n    for (int i = 0; i < N; ++i) cin >> raw[i];\n\n    // Build board and locate empty\n    vector<vector<int>> board(N, vector<int>(N));\n    int er = -1, ec = -1;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char ch = raw[i][j];\n            int v = 0;\n            if (ch >= '0' && ch <= '9') v = ch - '0';\n            else if (ch >= 'a' && ch <= 'f') v = ch - 'a' + 10;\n            else if (ch >= 'A' && ch <= 'F') v = ch - 'A' + 10;\n            board[i][j] = v;\n            if (v == 0) { er = i; ec = j; }\n        }\n    }\n\n    const int full = N * N - 1;\n    string bestOverallSeq = \"\";\n    int bestOverallScore = -1;\n    auto startTime = chrono::high_resolution_clock::now();\n    const double timeLimit = 2.5; // seconds\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    auto validMoves = [&](int r, int c, vector<int>& out) {\n        out.clear();\n        if (r > 0) out.push_back(0); // U\n        if (r + 1 < N) out.push_back(1); // D\n        if (c > 0) out.push_back(2); // L\n        if (c + 1 < N) out.push_back(3); // R\n    };\n\n    auto simulateMove = [&](int dir, int& r, int& c, vector<vector<int>>& b) -> int {\n        int nr = r + dr[dir];\n        int nc = c + dc[dir];\n        swap(b[r][c], b[nr][nc]);\n        int res = computeLargestTreeSize(b);\n        swap(b[r][c], b[nr][nc]); // revert\n        return res;\n    };\n\n    while (true) {\n        auto now = chrono::high_resolution_clock::now();\n        double elapsed = chrono::duration<double>(now - startTime).count();\n        if (elapsed >= timeLimit) break;\n\n        // Reset board to initial state\n        vector<vector<int>> curBoard = board;\n        int curEr = er, curEc = ec;\n        string curSeq = \"\";\n        int curScore = computeLargestTreeSize(curBoard);\n        int steps = 0;\n\n        while (steps < T && curScore < full) {\n            vector<int> mvds;\n            validMoves(curEr, curEc, mvds);\n            if (mvds.empty()) break;\n            shuffle(mvds.begin(), mvds.end(), rng);\n\n            int bestDir = -1;\n            int bestScoreAfter = curScore;\n            for (int d : mvds) {\n                int s = simulateMove(d, curEr, curEc, curBoard);\n                if (s > bestScoreAfter) {\n                    bestScoreAfter = s;\n                    bestDir = d;\n                }\n            }\n\n            if (bestDir != -1 && bestScoreAfter > curScore) {\n                // Apply the best improving move\n                int nr = curEr + dr[bestDir];\n                int nc = curEc + dc[bestDir];\n                swap(curBoard[curEr][curEc], curBoard[nr][nc]);\n                curEr = nr;\n                curEc = nc;\n                curSeq.push_back(dirChar[bestDir]);\n                steps++;\n                curScore = bestScoreAfter;\n            } else {\n                // No improving move: take a random move (first in shuffled list)\n                int d = mvds[0];\n                int nr = curEr + dr[d];\n                int nc = curEc + dc[d];\n                swap(curBoard[curEr][curEc], curBoard[nr][nc]);\n                curEr = nr;\n                curEc = nc;\n                curSeq.push_back(dirChar[d]);\n                steps++;\n                curScore = computeLargestTreeSize(curBoard); // Recompute score after the move\n            }\n        }\n\n        // Update the best overall sequence\n        if (curScore > bestOverallScore || \n            (curScore == bestOverallScore && (int)curSeq.length() < (int)bestOverallSeq.length())) {\n            bestOverallScore = curScore;\n            bestOverallSeq = curSeq;\n        }\n    }\n\n    cout << bestOverallSeq << '\\n';\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nstruct Line {\n    ll x1, y1, x2, y2;\n    Line() {}\n    Line(ll a, ll b, ll c, ll d) : x1(a), y1(b), x2(c), y2(d) {}\n};\n\n/* line through two points (avoid degenerate) */\nLine lineThrough(ll x1, ll y1, ll x2, ll y2) {\n    return Line(x1, y1, x2, y2);\n}\n\n/* line perpendicular to segment (x1,y1)-(x2,y2) and passing through its midpoint */\nLine linePerpMid(ll x1, ll y1, ll x2, ll y2) {\n    ll mx = x1 + x2;          // 2 * midpoint x\n    ll my = y1 + y2;          // 2 * midpoint y\n    ll dx = x2 - x1;\n    ll dy = y2 - y1;\n    ll ax = mx - dy;\n    ll ay = my + dx;\n    ll bx = mx + dy;\n    ll by = my - dx;\n    return Line(ax, ay, bx, by);\n}\n\n/* evaluate a set of lines */\nint evaluate(const vector<Line>& lines,\n             const vector<int>& need,\n             const vector<pair<ll,ll>>& pts) {\n    unordered_map<string,int> cnt;\n    cnt.reserve(pts.size()*2);\n    for (auto &[x,y] : pts) {\n        string sig;\n        bool on = false;\n        sig.reserve(lines.size());\n        for (const auto &ln : lines) {\n            ll cross = (ln.y2 - ln.y1)*(x - ln.x1) -\n                       (ln.x2 - ln.x1)*(y - ln.y1);\n            if (cross == 0) { on = true; break; }\n            sig.push_back(cross > 0 ? '1' : '0');\n        }\n        if (on) continue;\n        cnt[sig]++;\n    }\n    vector<int> have(11,0);\n    for (auto &[_,c] : cnt) {\n        if (c>=1 && c<=10) have[c]++;\n    }\n    int score = 0;\n    for (int d=1; d<=10; ++d) score += min(need[d], have[d]);\n    return score;\n}\n\n/* add quantile lines for a projection */\nvoid addQuantileLines(const vector<ll>& vals,\n                      int num,\n                      function<Line(ll)> maker,\n                      vector<Line>& out,\n                      mt19937_64& rng,\n                      uniform_int_distribution<int>& jitter) {\n    if (num<=0 || vals.empty()) return;\n    ll mn = *min_element(vals.begin(), vals.end());\n    ll mx = *max_element(vals.begin(), vals.end());\n    ll rngv = mx - mn;\n    if (rngv==0) rngv = 1;\n    for (int i=0; i<num; ++i) {\n        ll pos = mn + (rngv * (i+1LL)) / (num+1LL);\n        ll jit = jitter(rng) - 50;          // [-50,50]\n        ll c = pos + jit;\n        if (c < -1000000000LL) c = -1000000000LL;\n        if (c >  1000000000LL) c =  1000000000LL;\n        out.push_back(maker(c));\n    }\n}\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> need(11);\n    for (int d=1; d<=10; ++d) cin >> need[d];\n    vector<pair<ll,ll>> pts(N);\n    for (int i=0; i<N; ++i) cin >> pts[i].first >> pts[i].second;\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<ll> coordDist(-1000000000LL, 1000000000LL);\n    uniform_int_distribution<int> jitterDist(0,100); // after -50 => [-50,50]\n\n    const int CANDIDATES = 25;   // different starting constructions\n    const int LOCAL_STEPS = 30;  // hill\u2011climb steps per start\n    int bestScore = -1;\n    vector<Line> bestLines;\n\n    for (int cand=0; cand<CANDIDATES; ++cand) {\n        vector<Line> lines;\n        lines.reserve(K);\n\n        int typ = cand % 5;   // 0..4 decide the flavour\n        if (typ==0) {                         // pure random\n            for (int i=0;i<K;++i) {\n                ll x1=coordDist(rng),y1=coordDist(rng);\n                ll x2=coordDist(rng),y2=coordDist(rng);\n                if (x1==x2 && y1==y2) --i;\n                else lines.emplace_back(x1,y1,x2,y2);\n            }\n        }\n        else if (typ==1) {                    // vertical/horizontal quantiles\n            int v = K/2, h = K-v;\n            vector<ll> xs, ys;\n            xs.reserve(N); ys.reserve(N);\n            for (auto &[x,y]:pts){ xs.push_back(x); ys.push_back(y); }\n            addQuantileLines(xs,v,\n                             [](ll c){ return Line(c,-1000000000LL,c,1000000000LL); },\n                             lines,rng,jitterDist);\n            addQuantileLines(ys,h,\n                             [](ll c){ return Line(-1000000000LL,c,1000000000LL,c); },\n                             lines,rng,jitterDist);\n        }\n        else if (typ==2) {                    // diagonal (x+y) and (x\u2011y) quantiles\n            int d1 = K/2, d2 = K-d1;\n            vector<ll> p1, p2;\n            p1.reserve(N); p2.reserve(N);\n            for (auto &[x,y]:pts){ p1.push_back(x+y); p2.push_back(x-y); }\n            addQuantileLines(p1,d1,\n                             [](ll c){ return Line(0,c,1,c-1); },\n                             lines,rng,jitterDist);\n            addQuantileLines(p2,d2,\n                             [](ll c){ return Line(0,-c,1,1-c); },\n                             lines,rng,jitterDist);\n        }\n        else if (typ==3) {                    // lines through two random strawberries\n            for (int i=0;i<K;++i) {\n                int a = uniform_int_distribution<int>(0,N-1)(rng);\n                int b = uniform_int_distribution<int>(0,N-1)(rng);\n                if (a==b) { --i; continue; }\n                auto [x1,y1]=pts[a];\n                auto [x2,y2]=pts[b];\n                lines.emplace_back(x1,y1,x2,y2);\n            }\n        }\n        else {                                // perpendicular bisector of two strawberries\n            for (int i=0;i<K;++i) {\n                int a = uniform_int_distribution<int>(0,N-1)(rng);\n                int b = uniform_int_distribution<int>(0,N-1)(rng);\n                if (a==b) { --i; continue; }\n                auto [x1,y1]=pts[a];\n                auto [x2,y2]=pts[b];\n                lines.push_back(linePerpMid(x1,y1,x2,y2));\n            }\n        }\n\n        /* fill missing slots with random lines (should rarely happen) */\n        while ((int)lines.size() < K) {\n            ll x1=coordDist(rng),y1=coordDist(rng);\n            ll x2=coordDist(rng),y2=coordDist(rng);\n            if (x1==x2 && y1==y2) continue;\n            lines.emplace_back(x1,y1,x2,y2);\n        }\n\n        /* ----- local improvement (hill climbing) ----- */\n        int curScore = evaluate(lines,need,pts);\n        for (int step=0; step<LOCAL_STEPS; ++step) {\n            int idx = uniform_int_distribution<int>(0,K-1)(rng);\n            Line old = lines[idx];\n            // perturb both endpoints by a small random delta\n            ll nx1 = old.x1 + uniform_int_distribution<ll>(-200,200)(rng);\n            ll ny1 = old.y1 + uniform_int_distribution<ll>(-200,200)(rng);\n            ll nx2 = old.x2 + uniform_int_distribution<ll>(-200,200)(rng);\n            ll ny2 = old.y2 + uniform_int_distribution<ll>(-200,200)(rng);\n            // keep inside allowed range\n            if (nx1<-1000000000LL) nx1=-1000000000LL;\n            if (nx1> 1000000000LL) nx1= 1000000000LL;\n            if (ny1<-1000000000LL) ny1=-1000000000LL;\n            if (ny1> 1000000000LL) ny1= 1000000000LL;\n            if (nx2<-1000000000LL) nx2=-1000000000LL;\n            if (nx2> 1000000000LL) nx2= 1000000000LL;\n            if (ny2<-1000000000LL) ny2=-1000000000LL;\n            if (ny2> 1000000000LL) ny2= 1000000000LL;\n            if (nx1==nx2 && ny1==ny2) continue;   // degenerate line\n            lines[idx] = Line(nx1,ny1,nx2,ny2);\n            int newScore = evaluate(lines,need,pts);\n            if (newScore >= curScore) {\n                curScore = newScore;   // accept improvement or equal\n            } else {\n                lines[idx] = old;      // revert\n            }\n        }\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestLines = lines;\n        }\n    }\n\n    /* ----- output ----- */\n    cout << (int)bestLines.size() << '\\n';\n    for (const auto &ln : bestLines) {\n        cout << ln.x1 << ' ' << ln.y1 << ' ' << ln.x2 << ' ' << ln.y2 << '\\n';\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    bool operator==(const Point& other) const { return x == other.x && y == other.y; }\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    const int c = (N - 1) / 2;\n    vector<vector<bool>> dot(N, vector<bool>(N, false));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        dot[x][y] = true;\n    }\n\n    // Edge usage arrays\n    vector<vector<bool>> hor(N, vector<bool>(N, false)); // hor[x][y] : (x,y)-(x+1,y)\n    vector<vector<bool>> ver(N, vector<bool>(N, false)); // ver[x][y] : (x,y)-(x,y+1)\n    vector<vector<bool>> diag1(N, vector<bool>(N, false)); // diag1[x][y] : (x+1,y)-(x,y+1)\n    vector<vector<bool>> diag2(N, vector<bool>(N, false)); // diag2[x][y] : (x-1,y)-(x,y+1)\n\n    // Point -> list of shape indices containing this point as a corner\n    vector<vector<vector<int>>> point_shapes(N, vector<vector<int>>(N));\n\n    struct Shape {\n        int type; // 0: square (x,y lower-left), 1: diamond (cx,cy center)\n        int a, b; // parameters\n    };\n    vector<Shape> shapes;\n\n    // Squares: lower-left corner (x,y)\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y < N - 1; ++y) {\n            Shape s{0, x, y};\n            int id = (int)shapes.size();\n            shapes.push_back(s);\n            // Cyclic order: (x,y) -> (x+1,y) -> (x+1,y+1) -> (x,y+1)\n            vector<Point> corners = {{x, y}, {x + 1, y}, {x + 1, y + 1}, {x, y + 1}};\n            for (auto& p : corners) point_shapes[p.x][p.y].push_back(id);\n        }\n    }\n\n    // Diamonds: center (cx,cy)\n    for (int cx = 1; cx < N - 1; ++cx) {\n        for (int cy = 1; cy < N - 1; ++cy) {\n            Shape s{1, cx, cy};\n            int id = (int)shapes.size();\n            shapes.push_back(s);\n            // Cyclic order: (cx+1,cy) -> (cx,cy+1) -> (cx-1,cy) -> (cx,cy-1)\n            vector<Point> corners = {{cx + 1, cy}, {cx, cy + 1}, {cx - 1, cy}, {cx, cy - 1}};\n            for (auto& p : corners) point_shapes[p.x][p.y].push_back(id);\n        }\n    }\n\n    int S = (int)shapes.size();\n    vector<int> dot_count(S, 0);\n    for (int id = 0; id < S; ++id) {\n        const Shape& sh = shapes[id];\n        int cnt = 0;\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            vector<Point> corners = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};\n            for (auto& p : corners) if (dot[p.x][p.y]) ++cnt;\n        } else {\n            int cx = sh.a, cy = sh.b;\n            vector<Point> corners = {{cx + 1, cy}, {cx - 1, cy}, {cx, cy + 1}, {cx, cy - 1}};\n            for (auto& p : corners) if (dot[p.x][p.y]) ++cnt;\n        }\n        dot_count[id] = cnt;\n    }\n\n    auto get_missing = [&](int id, Point& missing) -> bool {\n        const Shape& sh = shapes[id];\n        vector<Point> corners;\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            corners = {{x, y}, {x + 1, y}, {x, y + 1}, {x + 1, y + 1}};\n        } else {\n            int cx = sh.a, cy = sh.b;\n            corners = {{cx + 1, cy}, {cx - 1, cy}, {cx, cy + 1}, {cx, cy - 1}};\n        }\n        for (auto& p : corners) {\n            if (!dot[p.x][p.y]) {\n                missing = p;\n                return true;\n            }\n        }\n        return false;\n    };\n\n    auto edges_unused = [&](int id) -> bool {\n        const Shape& sh = shapes[id];\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            if (hor[x][y] || hor[x][y + 1] || ver[x][y] || ver[x + 1][y]) return false;\n        } else {\n            int cx = sh.a, cy = sh.b;\n            if (diag1[cx][cy] || diag2[cx][cy] || diag1[cx - 1][cy - 1] || diag2[cx + 1][cy - 1])\n                return false;\n        }\n        return true;\n    };\n\n    auto mark_edges_used = [&](int id) {\n        const Shape& sh = shapes[id];\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            hor[x][y] = true;\n            hor[x][y + 1] = true;\n            ver[x][y] = true;\n            ver[x + 1][y] = true;\n        } else {\n            int cx = sh.a, cy = sh.b;\n            diag1[cx][cy] = true;\n            diag2[cx][cy] = true;\n            diag1[cx - 1][cy - 1] = true;\n            diag2[cx + 1][cy - 1] = true;\n        }\n    };\n\n    priority_queue<pair<int, int>> pq; // max-heap by weight\n\n    auto push_if_eligible = [&](int id) {\n        if (dot_count[id] != 3) return;\n        Point missing;\n        if (!get_missing(id, missing)) return;\n        if (!edges_unused(id)) return;\n        int w = (missing.x - c) * (missing.x - c) + (missing.y - c) * (missing.y - c) + 1;\n        pq.push({w, id});\n    };\n\n    for (int id = 0; id < S; ++id) push_if_eligible(id);\n\n    using Op = tuple<int, int, int, int, int, int, int, int>;\n    vector<Op> ops;\n\n    auto process_shape = [&](int id) {\n        if (dot_count[id] != 3) return false;\n        Point missing;\n        if (!get_missing(id, missing)) return false;\n        if (!edges_unused(id)) return false;\n        const Shape& sh = shapes[id];\n        vector<Point> corners;\n        if (sh.type == 0) {\n            int x = sh.a, y = sh.b;\n            corners = {{x, y}, {x + 1, y}, {x + 1, y + 1}, {x, y + 1}};\n        } else {\n            int cx = sh.a, cy = sh.b;\n            corners = {{cx + 1, cy}, {cx, cy + 1}, {cx - 1, cy}, {cx, cy - 1}};\n        }\n        int missing_idx = -1;\n        for (int i = 0; i < 4; ++i) {\n            if (corners[i] == missing) { missing_idx = i; break; }\n        }\n        vector<Point> ordered;\n        for (int k = 0; k < 4; ++k) {\n            ordered.push_back(corners[(missing_idx + k) % 4]);\n        }\n        ops.emplace_back(\n            ordered[0].x, ordered[0].y,\n            ordered[1].x, ordered[1].y,\n            ordered[2].x, ordered[2].y,\n            ordered[3].x, ordered[3].y\n        );\n        dot[missing.x][missing.y] = true;\n        mark_edges_used(id);\n        for (int sid : point_shapes[missing.x][missing.y]) {\n            ++dot_count[sid];\n            if (dot_count[sid] == 3) push_if_eligible(sid);\n        }\n        return true;\n    };\n\n    while (!pq.empty()) {\n        auto [w, id] = pq.top();\n        pq.pop();\n        process_shape(id);\n    }\n\n    cout << ops.size() << '\\n';\n    for (auto& op : ops) {\n        int x1, y1, x2, y2, x3, y3, x4, y4;\n        tie(x1, y1, x2, y2, x3, y3, x4, y4) = op;\n        cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << ' '\n             << x3 << ' ' << y3 << ' ' << x4 << ' ' << y4 << '\\n';\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*------------------------------------------------------------*/\n/*  board utilities                                            */\n/*------------------------------------------------------------*/\nusing Board = array<array<int,10>,10>;\n\n/* place a candy of given flavour into the p-th empty cell (1-indexed) */\nvoid place_candy(Board &bd, int flavour, int p) {\n    int cnt = 0;\n    for (int i = 0; i < 10; ++i) {\n        for (int j = 0; j < 10; ++j) {\n            if (bd[i][j] == 0) {\n                if (++cnt == p) {\n                    bd[i][j] = flavour;\n                    return;\n                }\n            }\n        }\n    }\n}\n\n/* tilt the board in the given direction:\n   0 = F (up), 1 = B (down), 2 = L (left), 3 = R (right) */\nBoard tilt(const Board &bd, int dir) {\n    Board nb{}; // all zero\n    if (dir == 0) {               // F : up\n        for (int j = 0; j < 10; ++j) {\n            int r = 0;\n            for (int i = 0; i < 10; ++i)\n                if (bd[i][j]) nb[r++][j] = bd[i][j];\n        }\n    } else if (dir == 1) {        // B : down\n        for (int i = 0; i < 10; ++i) {\n            int r = 9;\n            for (int j = 9; j >= 0; --j)\n                if (bd[i][j]) nb[i][r--] = bd[i][j];\n        }\n    } else if (dir == 2) {        // L : left\n        for (int i = 0; i < 10; ++i) {\n            int c = 0;\n            for (int j = 0; j < 10; ++j)\n                if (bd[i][j]) nb[i][c++] = bd[i][j];\n        }\n    } else {                      // dir == 3 : R : right\n        for (int i = 0; i < 10; ++i) {\n            int c = 9;\n            for (int j = 9; j >= 0; --j)\n                if (bd[i][j]) nb[i][c--] = bd[i][j];\n        }\n    }\n    return nb;\n}\n\n/* compute sum of squares of component sizes */\nint compute_score(const Board &bd) {\n    bool seen[10][10] = {};\n    int sum = 0;\n    const int dr[4] = {-1,1,0,0};\n    const int dc[4] = {0,0,-1,1};\n\n    auto bfs = [&](int sr, int sc) -> int {\n        int f = bd[sr][sc];\n        queue<pair<int,int>> q;\n        q.emplace(sr,sc);\n        seen[sr][sc] = true;\n        int sz = 0;\n        while (!q.empty()) {\n            auto [r,c] = q.front(); q.pop();\n            ++sz;\n            for (int d = 0; d < 4; ++d) {\n                int nr = r + dr[d], nc = c + dc[d];\n                if (nr < 0 || nr >= 10 || nc < 0 || nc >= 10) continue;\n                if (seen[nr][nc] || bd[nr][nc] != f) continue;\n                seen[nr][nc] = true;\n                q.emplace(nr,nc);\n            }\n        }\n        return sz;\n    };\n\n    for (int i = 0; i < 10; ++i)\n        for (int j = 0; j < 10; ++j)\n            if (bd[i][j] != 0 && !seen[i][j]) {\n                int sz = bfs(i,j);\n                sum += sz*sz;\n            }\n    return sum;\n}\n\n/*------------------------------------------------------------*/\n/*  main                                                       */\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int flavour[100];\n    for (int i = 0; i < 100; ++i) cin >> flavour[i];\n\n    Board board{}; // all zero\n\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        if (!(cin >> p)) break;          // safety, should not happen\n        place_candy(board, flavour[t], p);\n\n        if (t == 99) break;              // last candy \u2013 no output\n\n        int best_dir = -1;\n        int best_val = -1;\n        for (int dir = 0; dir < 4; ++dir) {\n            Board tmp = tilt(board, dir);\n            int val = compute_score(tmp);\n            if (val > best_val) {\n                best_val = val;\n                best_dir = dir;\n            }\n        }\n        char out;\n        switch(best_dir) {\n            case 0: out = 'F'; break;\n            case 1: out = 'B'; break;\n            case 2: out = 'L'; break;\n            case 3: out = 'R'; break;\n        }\n        cout << out << '\\n';\n        cout.flush();\n\n        // really apply the chosen tilt\n        board = tilt(board, best_dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ------------------------------------------------------------\n// Return P[ Bin(n, p) >= start ]  (start is integer, 0 <= start <= n)\n// Uses iterative calculation of the pmf to avoid overflow.\n// ------------------------------------------------------------\nlong double binom_tail(int n, long double p, int start) {\n    if (start > n) return 0.0L;\n    if (start <= 0) return 1.0L;\n    if (p == 0.0L) {\n        return (start == 0) ? 1.0L : 0.0L;\n    }\n    if (p == 1.0L) {\n        return (start <= n) ? 1.0L : 0.0L;\n    }\n    long double prob = powl(1.0L - p, n); // P[X = 0]\n    long double sum = 0.0L;\n    for (int k = 0; k <= n; ++k) {\n        if (k >= start) sum += prob;\n        // compute P[X = k+1] from P[X = k]\n        prob = prob * p / (1.0L - p) * (n - k) / (k + 1.0L);\n    }\n    return sum;\n}\n\n// ------------------------------------------------------------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int M;\n    double eps_;\n    if (!(cin >> M >> eps_)) return 0;\n    const long double eps = static_cast<long double>(eps_);\n\n    // Use the maximum allowed number of vertices\n    const int N = 100;\n    const long long L = 1LL * N * (N - 1) / 2; // total number of possible edges\n\n    // Pre\u2011compute probabilities needed for decoding\n    const int n = N - 1;                     // number of possible edges incident to a vertex\n    const int start = n / 2 + 1;             // we need degree > n/2  (i.e. >= start)\n    const long double p_one = 1.0L - eps;    // probability an original edge stays\n    const long double p_zero = eps;          // probability a non\u2011edge appears as edge\n    const long double p_high = binom_tail(n, p_one, start);   // P[deg > n/2 | vertex in clique]\n    const long double p_low  = binom_tail(n, p_zero, start);  // P[deg > n/2 | vertex in independent set]\n    const long double denom = p_high - p_low;                // > 0 for eps < 0.5\n\n    // --------------------------------------------------------\n    // Output N and the M graphs G_0 \u2026 G_{M-1}\n    // G_s : first s vertices form a clique and are connected to    //       all other vertices; the remaining N-s vertices have\n    //       no edges among themselves.\n    // --------------------------------------------------------\n    cout << N << '\\n';\n    for (int s = 0; s < M; ++s) {\n        string g;\n        g.reserve(L);\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                // edge exists iff at least one endpoint is in the clique [0, s)\n                g.push_back((i < s) || (j < s) ? '1' : '0');\n            }\n        }\n        cout << g << '\\n';\n    }\n    cout.flush();\n\n    // --------------------------------------------------------\n    // Process the 100 queries\n    // --------------------------------------------------------\n    for (int qq = 0; qq < 100; ++qq) {\n        string H;\n        if (!(cin >> H)) break;\n        // compute degree of each vertex\n        vector<int> deg(N, 0);\n        int 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            }\n        }\n        // count vertices with degree > n/2\n        int cnt_high = 0;\n        for (int v = 0; v < N; ++v) {\n            if (deg[v] > n / 2) ++cnt_high;\n        }\n        // estimate s from the observed count\n        long double est = (static_cast<long double>(cnt_high) -\n                           static_cast<long double>(N) * p_low) /\n                          denom;\n        int s_est = static_cast<int>(floor(est + 0.5L)); // nearest integer\n        if (s_est < 0) s_est = 0;\n        if (s_est >= M) s_est = M - 1;\n        cout << s_est << '\\n';\n        cout.flush();\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing db = double;\n\nconst db INF = 1e100;\n\nstruct Edge {\n    int u, v, w, idx;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    vector<Edge> edges(M);\n    vector<vector<tuple<int, int, int>>> adj(N); // to, weight, edge index\n    vector<vector<int>> edge_idx(N, vector<int>(N, -1));\n\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, i};\n        adj[u].emplace_back(v, w, i);\n        adj[v].emplace_back(u, w, i);\n        edge_idx[u][v] = edge_idx[v][u] = i;\n    }\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // ---------- edge betweenness (Brandes) ----------\n    vector<db> betw(M, 0.0);\n    for (int s = 0; s < N; ++s) {\n        vector<db> dist(N, INF);\n        vector<db> sigma(N, 0.0);\n        vector<vector<int>> pred(N);\n        using State = pair<db, int>;\n        priority_queue<State, vector<State>, greater<State>> pq;\n\n        dist[s] = 0;\n        sigma[s] = 1.0;\n        pq.emplace(0, s);\n\n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d > dist[v] + 1e-12) continue;\n            for (auto [to, w, _] : adj[v]) {\n                db nd = d + w;\n                if (nd < dist[to] - 1e-12) {\n                    dist[to] = nd;\n                    sigma[to] = sigma[v];\n                    pred[to].clear();\n                    pred[to].push_back(v);\n                    pq.emplace(nd, to);\n                } else if (fabs(nd - dist[to]) <= 1e-12) {\n                    sigma[to] += sigma[v];\n                    pred[to].push_back(v);\n                }\n            }\n        }\n\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) { return dist[a] > dist[b]; });\n\n        vector<db> delta(N, 0.0);\n        for (int v : order) {\n            if (v == s) continue;\n            for (int p : pred[v]) {\n                int e = edge_idx[p][v];\n                if (e == -1) continue;\n                db c = (sigma[p] / sigma[v]) * (1.0 + delta[v]);\n                betw[e] += c;\n                delta[p] += c;\n            }\n        }\n    }\n    for (int i = 0; i < M; ++i) betw[i] *= 0.5;\n\n    // ---------- greedy assignment ----------\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a, int b) { return betw[a] > betw[b]; });\n\n    vector<int> ans(M, -1); // day in [0, D-1]\n    vector<int> edge_cnt(D, 0);\n    vector<db> load(D, 0.0);\n    vector<vector<int>> vertex_cnt(D, vector<int>(N, 0));\n    vector<db> conflict(D, 0.0); // sum_v C(cnt,2)\n\n    db total_betw = accumulate(betw.begin(), betw.end(), 0.0);\n    db lambda = 0.1 * (total_betw / D); // weight for conflict term\n\n    for (int idx : order) {\n        int u = edges[idx].u;\n        int v = edges[idx].v;\n        db w = betw[idx];\n        int best_day = -1;\n        db best_delta = INF;\n        for (int d = 0; d < D; ++d) {\n            if (edge_cnt[d] >= K) continue;\n            db delta_load = 2.0 * load[d] * w + w * w;\n            db delta_conf = lambda * (vertex_cnt[d][u] + vertex_cnt[d][v]);\n            db delta = delta_load + delta_conf;\n            if (delta < best_delta - 1e-12 || (fabs(delta - best_delta) <= 1e-12 && load[d] < load[best_day])) {\n                best_delta = delta;\n                best_day = d;\n            }\n        }\n        ans[idx] = best_day;\n        edge_cnt[best_day]++;\n        load[best_day] += w;\n        // update conflict and vertex counts\n        conflict[best_day] += vertex_cnt[best_day][u] + vertex_cnt[best_day][v];\n        vertex_cnt[best_day][u]++;\n        vertex_cnt[best_day][v]++;\n    }\n\n    // ---------- local search by swapping ----------\n    auto start = chrono::high_resolution_clock::now();\n    const double TIME_LIMIT = 4.5; // seconds\n    auto get_time = [&]() {\n        return chrono::duration<double>(chrono::high_resolution_clock::now() - start).count();\n    };\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_edge(0, M - 1);\n\n    auto compute_conflict_change = [&](int day, int v, int delta_cnt) -> db {\n        // delta_cnt: +1 (adding) or -1 (removing)\n        long long c = vertex_cnt[day][v];\n        db before = (db)c * (c - 1) * 0.5;\n        long long nc = c + delta_cnt;\n        db after = (db)nc * (nc - 1) * 0.5;\n        return after - before;\n    };\n\n    int max_iter = 2000000;\n    for (int it = 0; it < max_iter && get_time() < TIME_LIMIT; ++it) {\n        int i = dist_edge(rng);\n        int j = dist_edge(rng);\n        if (i == j) continue;\n        int d1 = ans[i];\n        int d2 = ans[j];\n        if (d1 == d2) continue;\n\n        // edge i\n        int ui = edges[i].u, vi = edges[i].v;\n        db wi = betw[i];\n        // edge j\n        int uj = edges[j].u, vj = edges[j].v;\n        db wj = betw[j];\n\n        // current loads and conflicts\n        db L1 = load[d1], L2 = load[d2];\n        db C1 = conflict[d1], C2 = conflict[d2];\n\n        // remove i from d1, j from d2\n        db newL1 = L1 - wi;\n        db newL2 = L2 - wj;\n        db deltaC1 = 0.0, deltaC2 = 0.0;\n        deltaC1 += compute_conflict_change(d1, ui, -1);\n        deltaC1 += compute_conflict_change(d1, vi, -1);\n        deltaC2 += compute_conflict_change(d2, uj, -1);\n        deltaC2 += compute_conflict_change(d2, vj, -1);\n\n        // add i to d2, j to d1\n        newL2 += wi;\n        newL1 += wj;\n        deltaC2 += compute_conflict_change(d2, ui, +1);\n        deltaC2 += compute_conflict_change(d2, vi, +1);\n        deltaC1 += compute_conflict_change(d1, uj, +1);\n        deltaC1 += compute_conflict_change(d1, vj, +1);\n\n        db delta_obj = (newL1 * newL1 + newL2 * newL2) -\n                       (L1 * L1 + L2 * L2) +\n                       lambda * ((deltaC1 + deltaC2) - (0.0)); // note: we already computed delta changes\n\n        if (delta_obj < 0) {\n            // perform swap\n            ans[i] = d2;\n            ans[j] = d1;\n            load[d1] = newL1;\n            load[d2] = newL2;\n            edge_cnt[d1]--; edge_cnt[d2]++; // actually counts stay same, just swapped\n            // but we need to update vertex counts and conflict\n            vertex_cnt[d1][ui]--; vertex_cnt[d1][vi]--;\n            vertex_cnt[d2][ui]++; vertex_cnt[d2][vi]++;\n            vertex_cnt[d2][uj]--; vertex_cnt[d2][vj]--;\n            vertex_cnt[d1][uj]++; vertex_cnt[d1][vj]++;\n            conflict[d1] += deltaC1;\n            conflict[d2] += deltaC2;\n        }\n    }\n\n    // ---------- output ----------\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << ans[i] + 1;\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Voxel {\n    int x, y, z;\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\n    // Read silhouettes\n    vector<vector<string>> fStr(2, vector<string>(D));\n    vector<vector<string>> rStr(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> fStr[i][k];\n        }\n    }\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> rStr[i][k];\n        }\n    }\n\n    // Convert to bool arrays\n    vector<vector<vector<bool>>> f(2, vector<vector<bool>>(D, vector<bool>(D)));\n    vector<vector<vector<bool>>> r(2, vector<vector<bool>>(D, vector<bool>(D)));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int x = 0; x < D; ++x) {\n                f[i][z][x] = (fStr[i][zvoid solve() {\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int y = 0; y < D; ++y) {\n                r[i][z][y] = (rStr[i][z][y] == '1');\n            }\n        }\n    }\n}\n\n    // Collect voxels that satisfy both projections\n    vector<Voxel> vox[2];\n    for (int i = 0; i < 2; ++i) {\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[i][z][x] && r[i][z][y]) {\n                        vox[i].push_back({x, y, z});\n                    }\n                }\n            }\n        }\n    }\n\n    int v0 = (int)vox[0].size();\n    int v1 = (int)vox[1].size();\n    int n = max(v0, v1);\n\n    int size = D * D * D;\n    vector<int> b0(size, 0);\n    vector<int> b1(size, 0);\n\n    for (int i = 0; i < n; ++i) {\n        if (i < v0) {\n            const Voxel& v = vox[0][i];\n            int idx = v.x * D * D + v.y * D + v.z;\n            b0[idx] = i + 1;\n        }\n        if (i < v1) {\n            const Voxel& v = vox[1][i];\n            int idx = v.x * D * D + v.y * D + v.z;\n            b1[idx] = i + 1;\n        }\n    }\n\n    cout << n << '\\n';\n    for (int i = 0; i < size; ++i) {\n        if i > 0) cout << ' ';\n        cout << b0[i];\n    }\n    cout << '\\n';\n    for (int i = 0; i < size; ++i) {\n        if (i > 0) cout << ' ';\n        cout << b1[i];\n    }\n    cout << '\\n';\n    return 0;\n}\nint main() {\n    solve();\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n) : p(n), r(n, 0) { iota(p.begin(), p.end(), 0); }\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\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\n    vector<int> xs(N), ys(N);\n    for (int i = 0; i < N; ++i) cin >> xs[i] >> ys[i];\n\n    vector<tuple<int,int,long long>> rawEdges; // (u,v,w)\n    rawEdges.reserve(M);\n    for (int j = 0; j < M; ++j) {\n        int u, v; long long w;\n        cin >> u >> v >> w;\n        --u; --v;\n        rawEdges.emplace_back(u, v, w);\n    }\n\n    vector<pair<int,int>> residents(K);\n    for (int k = 0; k < K; ++k) {\n        cin >> residents[k].first >> residents[k].second;\n    }\n\n    /* ---------- 1. Build a Minimum Spanning Tree (Kruskal) ---------- */\n    vector<tuple<long long,int,int>> edges; // (w,u,v)\n    for (auto &[u,v,w] : rawEdges) edges.emplace_back(w, u, v);\n    sort(edges.begin(), edges.end());\n\n    DSU dsu(N);\n    vector<vector<pair<int,int>>> tree(N); // (neighbor, edgeId) in MST\n    vector<vector<int>> edgeIdLookup(N, vector<int>(N, -1)); // N \u2264 100\n    for (int j = 0; j < M; ++j) {\n        auto &[u,v,w] = rawEdges[j];\n        edgeIdLookup[u][v] = edgeIdLookup[v][u] = j;\n    }\n\n    vector<char> isTreeEdge(M, 0);\n    dsu = DSU(N);\n    for (auto &[w, u, v] : edges) {\n        if (dsu.unite(u, v)) {\n            int eid = edgeIdLookup[u][v];\n            isTreeEdge[eid] = 1;\n            tree[u].emplace_back(v, eid);\n            tree[v].emplace_back(u, eid);\n        }\n    }\n\n    /* ---------- 2. Root the MST at vertex 0 (station 1) ---------- */\n    vector<int> parentVertex(N, -1), parentEdge(N, -1);\n    function<void(int,int)> dfsRoot = [&](int v, int p) {\n        parentVertex[v] = p;\n        for (auto [to, eid] : tree[v]) {\n            if (to == p) continue;\n            parentEdge[to] = eid;\n            dfsRoot(to, v);\n        }\n    };\n    dfsRoot(0, -1);\n\n    /* ---------- 3. Helper: ceil of Euclidean distance ---------- */\n    auto distCeil = [&](int ax, int ay, int vx, int vy) -> int {\n        long long dx = vx - ax;\n        long long dy = vy - ay;\n        long long d2 = dx*dx + dy*dy;\n        double d = sqrt((double)d2);\n        int r = (int)ceil(d - 1e-9); // small epsilon to avoid floating errors        if (r < 0) r = 0;\n        if (r > 5000) r = 5000;\n        return r;\n    };\n\n    /* ---------- 4. Greedy assignment with several restarts ---------- */\n    const int GREEDY_PASSES = 20;   // passes over residents in one restart\n    const int RESTARTS      = 5;    // independent random restarts\n    vector<int> bestP(N, 0);\n    long long bestCost = LLONG_MAX; // we minimise S = \u03a3P_i\u00b2 + \u03a3edgeWeight\n\n    auto evaluate = [&](const vector<int>& Pcur) -> long long {\n        long long powerCost = 0;\n        for (int x : Pcur) powerCost += 1LL * x * x;\n        long long edgeCost = 0;\n        for (int j = 0; j < M; ++j)\n            if (isTreeEdge[j]) {\n                auto &[u,v,w] = rawEdges[j];\n                edgeCost += w;\n            }\n        return powerCost + edgeCost;\n    };\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    for (int restart = 0; restart < RESTARTS; ++restart) {\n        vector<int> P(N, 0);\n        vector<int> order(K);\n        iota(order.begin(), order.end(), 0);\n\n        for (int pass = 0; pass < GREEDY_PASSES; ++pass) {\n            shuffle(order.begin(), order.end(), rng);\n            for (int idx : order) {\n                int ax = residents[idx].first;\n                int ay = residents[idx].second;\n                long long bestInc = LLONG_MAX;\n                int bestV = -1;\n                int bestNeed = 0;\n                for (int v = 0; v < N; ++v) {\n                    int need = distCeil(ax, ay, xs[v], ys[v]);\n                    long long cur = P[v];\n                    long long inc = 0;\n                    if (need > cur) inc = 1LL * need * need - 1LL * cur * cur;\n                    if (inc < bestInc || (inc == bestInc && need < bestNeed)) {\n                        bestInc = inc;\n                        bestV = v;\n                        bestNeed = need;\n                    }\n                }\n                if (bestV != -1 && bestNeed > P[bestV])\n                    P[bestV] = bestNeed;\n            }\n        }\n\n        long long curCost = evaluate(P);\n        if (curCost < bestCost) {\n            bestCost = curCost;\n            bestP = P;\n        }\n    }\n\n    /* ---------- 5. Prune the MST: keep edge iff subtree needs power ---------- */\n    vector<char> answerB(M, 0);\n    vector<int> answerP(N);\n    for (int i = 0; i < N; ++i) answerP[i] = bestP[i];\n\n    function<bool(int,int)> dfsMark = [&](int v, int p) -> bool {\n        bool subtreeNeed = (answerP[v] > 0);\n        for (auto [to, eid] : tree[v]) {\n            if (to == p) continue;\n            bool childNeed = dfsMark(to, v);\n            if (childNeed) answerB[eid] = 1;\n            else answerB[eid] = 0;\n            subtreeNeed |= childNeed;\n        }\n        return subtreeNeed;\n    };\n    dfsMark(0, -1);\n\n    /* ---------- 6. Output ---------- */\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << answerP[i];\n    }\n    cout << '\\n';\n    for (int j = 0; j < M; ++j) {\n        if (j) cout << ' ';\n        cout << (int)answerB[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 total = N * (N + 1) / 2; // 465\n\n    // Precompute level and coordinates for each index in level\u2011order (heap) layout.\n    vector<int> level(total), cx(total), cy(total);\n    int idx = 0;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            level[idx] = x;\n            cx[idx] = x;\n            cy[idx] = y;\n            ++idx;\n        }\n    }\n\n    // Read the initial permutation.\n    vector<int> val(total);\n    idx = 0;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int v;\n            cin >> v;\n            val[idx++] = v;\n        }\n    }\n\n    struct Op { int x1, y1, x2, y2; };\n    vector<Op> ops;\n    ops.reserve(10000);\n\n    auto children = [&](int i) {\n        int lev = level[i];\n        int left = i + lev + 1;   // left child (same y)\n        int right = i + lev + 2;  // right child (y+1)\n        return make_pair(left, right);\n    };\n\n    // Helper to check if a node (not in bottom tier) violates the heap condition.\n    auto isViolation = [&](int i) {\n        if (level[i] >= N - 1) return false; // bottom tier has no children\n        auto [l, r] = children(i);\n        return (l < total && val[i] > val[l]) || (r < total && val[i] > val[r]);\n    };\n\n    // Main loop: fix violations by swapping with the smaller child.\n    while ((int)ops.size() < 10000) {\n        int violate = -1;\n        int bestDiff = -1; // we want to fix the biggest excess first\n        for (int i = 0; i < total; ++i) {\n            if (isViolation(i)) {\n                auto [l, r] = children(i);\n                int childVal = total; // large sentinel\n                int childIdx = -1;\n                if (l < total && val[l] < childVal) { childVal = val[l]; childIdx = l; }\n                if (r < total && val[r] < childVal) { childVal = val[r]; childIdx = r; }\n                int diff = val[i] - childVal; // how much parent exceeds the smaller child\n                if (diff > bestDiff) {\n                    bestDiff = diff;\n                    violate = i;\n                }\n            }\n        }\n        if (violate == -1) break; // no violations left\n\n        auto [l, r] = children(violate);\n        // choose the smaller child to swap with\n        int child = (l < total && (r >= total || val[l] < val[r])) ? l : r;\n        // perform swap\n        swap(val[violate], val[child]);\n        ops.push_back({cx[violate], cy[violate], cx[child], cy[child]});\n    }\n\n    // Output\n    cout << ops.size() << '\\n';\n    for (const auto& op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' ' << 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 ent_r = 0;\n    const int ent_c = (D - 1) / 2;\n\n    vector<vector<bool>> blocked(D, vector<bool>(D, false));\n    for (int k = 0; k < N; ++k) {\n        int r, j;\n        cin >> r >> j;\n        blocked[r][j] = true;\n    }\n    blocked[ent_r][ent_c] = false;\n\n    // Static distances from entrance ignoring obstacles (for ordering)\n    vector<vector<int>> dist(D, vector<int>(D, -1));\n    queue<pair<int,int>> q;\n    dist[ent_r][ent_c] = 0;\n    q.emplace(ent_r, ent_c);\n    const int dr[4] = {-1,1,0,0};\n    const int dc[4] = {0,0,-1,1};\n    while (!q.empty()) {\n        auto [r,c] = q.front(); q.pop();\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 >= D || nc < 0 || nc >= D) continue;\n            if (blocked[nr][nc]) continue;\n            if (dist[nr][nc] != -1) continue;\n            dist[nr][nc] = dist[r][c] + 1;\n            q.emplace(nr, nc);\n        }\n    }\n\n    // Static articulation points (only obstacles, no containers)\n    vector<vector<bool>> staticArt(D, vector<bool>(D, false));\n    {\n        vector<int> tin(D*D, -1), low(D*D, -1);\n        vector<char> visited(D*D, false);\n        int timer = 0;\n        function<void(int,int,int)> dfs = [&](int r, int c, int pr) {\n            int id = r*D + c;\n            visited[id] = true;\n            tin[id] = low[id] = timer++;\n            int children = 0;\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 >= D || nc < 0 || nc >= D) continue;\n                if (blocked[nr][nc]) continue;\n                int nid = nr*D + nc;\n                if (visited[nid]) {\n                    low[id] = min(low[id], tin[nid]);\n                } else {\n                    ++children;\n                    dfs(nr, nc, id);\n                    low[id] = min(low[id], low[nid]);\n                    if (pr != -1 && low[nid] >= tin[id]) {\n                        staticArt[r][c] = true;\n                    }\n                }\n            }\n            if (pr == -1 && children > 1) {\n                staticArt[r][c] = true;\n            }\n        };\n        dfs(ent_r, ent_c, -1);\n    }\n\n    // List of all usable cells (non-obstacle, non-entrance)\n    vector<pair<int,int>> L;\n    vector<vector<int>> idx(D, vector<int>(D, -1));\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            if (blocked[i][j]) continue;\n            if (i == ent_r && j == ent_c) continue;\n            L.emplace_back(i, j);\n            idx[i][j] = (int)L.size() - 1;\n        }\n    }\n    const int M = (int)L.size();\n    // Sort by distance, then by staticArt (false first), then row, then column\n    sort(L.begin(), L.end(), [&](const pair<int,int>& a, const pair<int,int>& b) {\n        if (dist[a.first][a.second] != dist[b.first][b.second])\n            return dist[a.first][a.second] < dist[b.first][b.second];\n        if (staticArt[a.first][a.second] != staticArt[b.first][b.second])\n            return staticArt[a.first][a.second] < staticArt[b.first][b.second];\n        if (a.first != b.first) return a.first < b.first;\n        return a.second < b.second;\n    });\n    // Rebuild idx after sorting\n    for (int i = 0; i < D; ++i) for (int j = 0; j < D; ++j) idx[i][j] = -1;\n    for (int p = 0; p < M; ++p) {\n        auto [r,c] = L[p];\n        idx[r][c] = p;\n    }\n\n    vector<vector<bool>> occupied(D, vector<bool>(D, false));\n    vector<vector<int>> tval(D, vector<int>(D, -1)); // t value for each container\n\n    // BFS: returns reachable cells from entrance given occupation 'occ'\n    auto bfsReachable = [&](const vector<vector<bool>>& occ) -> vector<vector<bool>> {\n        vector<vector<bool>> reach(D, vector<bool>(D, false));\n        queue<pair<int,int>> qq;\n        if (!blocked[ent_r][ent_c] && !occ[ent_r][ent_c]) {\n            reach[ent_r][ent_c] = true;\n            qq.emplace(ent_r, ent_c);\n        }\n        while (!qq.empty()) {\n            auto [r,c] = qq.front(); qq.pop();\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 >= D || nc < 0 || nc >= D) continue;\n                if (blocked[nr][nc] || occ[nr][nc]) continue;\n                if (reach[nr][nc]) continue;\n                reach[nr][nc] = true;\n                qq.emplace(nr, nc);\n            }\n        }\n        return reach;\n    };\n\n    // Placement phase\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;\n        vector<vector<bool>> reach = bfsReachable(occupied);\n        vector<vector<bool>> isArt = [&](const vector<vector<bool>>& reach, const vector<vector<bool>>& occ) -> vector<vector<bool>> {\n            vector<vector<bool>> isArt(D, vector<bool>(D, false));\n            vector<int> tin(D*D, -1), low(D*D, -1);\n            vector<char> visited(D*D, false);\n            int timer = 0;\n            function<void(int,int,int)> dfs = [&](int r, int c, int pr) {\n                int id = r*D + c;\n                visited[id] = true;\n                tin[id] = low[id] = timer++;\n                int children = 0;\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 >= D || nc < 0 || nc >= D) continue;\n                    if (!blocked[nr][nc] && !occ[nr][nc] && reach[nr][nc]) {\n                        int nid = nr*D + nc;\n                        if (visited[nid]) {\n                            low[id] = min(low[id], tin[nid]);\n                        } else {\n                            ++children;\n                            dfs(nr, nc, id);\n                            low[id] = min(low[id], low[nid]);\n                            if (pr != -1 && low[nid] >= tin[id]) {\n                                isArt[r][c] = true;\n                            }\n                        }\n                    }\n                }\n                if (pr == -1 && children > 1) {\n                    isArt[r][c] = true;\n                }\n            };\n            dfs(ent_r, ent_c, -1);\n            return isArt;\n        }(reach, occupied);\n\n        int best_r = -1, best_c = -1;\n        int best_cost = INT_MAX;\n        int best_idx = -1; // for tie-breaking by index\n        for (int i = 0; i < D; ++i) {\n            for (int j = 0; j < D; ++j) {\n                if (!reach[i][j]) continue;\n                if (i == ent_r && j == ent_c) continue;\n                if (occupied[i][j]) continue;\n                if (isArt[i][j]) continue;\n                int cost = abs(idx[i][j] - t);\n                bool better = false;\n                if (cost < best_cost) {\n                    better = true;\n                } else if (cost == best_cost) {\n                    if (idx[i][j] < best_idx) {\n                        better = true;\n                    } else if (idx[i][j] == best_idx) {\n                        if (i < best_r || (i == best_r && j < best_c)) {\n                            better = true;\n                        }\n                    }\n                }\n                if (better) {\n                    best_cost = cost;\n                    best_r = i;\n                    best_c = j;\n                    best_idx = idx[i][j];\n                }\n            }\n        }\n        // Fallback: should not happen, but just in case\n        if (best_r == -1) {\n            for (int i = 0; i < D; ++i) {\n                for (int j = 0; j < D; ++j) {\n                    if (!reach[i][j]) continue;\n                    if (i == ent_r && j == ent_c) continue;\n                    if (occupied[i][j]) continue;\n                    best_r = i; best_c = j;\n                    break;\n                }\n                if (best_r != -1) break;\n            }\n        }\n        occupied[best_r][best_c] = true;\n        tval[best_r][best_c] = t;\n        cout << best_r << ' ' << best_c << '\\n';\n        cout.flush();\n    }\n\n    // Removal phase: greedy smallest t among frontier\n    vector<vector<bool>> cleared(D, vector<bool>(D, false));\n    cleared[ent_r][ent_c] = true;\n    priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<tuple<int,int,int>>> pq;\n    // initial push: neighbors of entrance that are occupied\n    for (int d = 0; d < 4; ++d) {\n        int nr = ent_r + dr[d];\n        int nc = ent_c + dc[d];\n        if (nr < 0 || nr >= D || nc < 0 || nc >= D) continue;\n        if (blocked[nr][nc]) continue;\n        if (!occupied[nr][nc]) continue;\n        pq.emplace(tval[nr][nc], nr, nc);\n    }\n    while (!pq.empty()) {\n        auto [tt, r, c] = pq.top(); pq.pop();\n        if (cleared[r][c]) continue;\n        cleared[r][c] = true;\n        cout << r << ' ' << c << '\\n';\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 >= D || nc < 0 || nc >= D) continue;\n            if (blocked[nr][nc]) continue;\n            if (!occupied[nr][nc]) continue;\n            if (cleared[nr][nc]) continue;\n            pq.emplace(tval[nr][nc], nr, nc);\n        }\n    }\n    cout.flush();\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*------------------------------------------------------------*/\n/*  Constants and directions                                  */\nconst int dx[4] = {1, -1, 0, 0};\nconst int dy[4] = {0, 0, 1, -1};\n\n/*------------------------------------------------------------*/\nstruct Solver {\n    int n, m;\n    vector<vector<short>> grid;          // current colours\n    vector<int> cnt;                     // number of cells of each colour (>0)\n    vector<vector<int>> adj;             // current adjacency counts\n    vector<vector<int>> adjOrig;         // original adjacency counts (constant)\n\n    Solver(int n_, int m_) : n(n_), m(m_) {\n        grid.assign(n, vector<short>(n, 0));\n        cnt.assign(m + 1, 0);\n        adj.assign(m + 1, vector<short>(m + 1, 0));\n        adjOrig.assign(m + 1, vector<short>(m + 1, 0));\n    }\n\n    /*--------------------------------------------------------*/\n    // read the input\n    void read() {\n        cin >> n >> m;\n        grid.assign(n, vector<short>(n));\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) {\n                cin >> grid[i][j];\n                if (grid[i][j] > 0) ++cnt[grid[i][j]];\n            }\n    }\n\n    /*--------------------------------------------------------*/\n    // compute adjacency matrix from a given grid\n    void computeAdj(const vector<vector<short>>& g, vector<vector<int>>& out) {\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) {\n                int c = g[i][j];\n                for (int d = 0; d < 4; ++d) {\n                    int ni = i + dx[d], nj = j + dy[d];\n                    int nb = 0;               // outside\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n)\n                        nb = g[ni][nj];\n                    if (c == nb) continue;   // same colour \u2013 we do not store c\u2011c\n                    out[c][nb]++;\n                    out[nb][c]++;\n                }\n            }\n    }\n\n    /*--------------------------------------------------------*/\n    // zero\u2011neighbour test (outside counts as zero)\n    bool hasZeroNeighbour(int i, int j) const {\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) return true;   // outside\n            if (grid[ni][nj] == 0) return true;\n        }\n        return false;\n    }\n\n    /*--------------------------------------------------------*/\n    // BFS to check connectivity of a given colour (>0)\n    bool connectedColour(int col) const {\n        // find any cell of this colour\n        int si = -1, sj = -1;\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (grid[i][j] == col) { si = i; sj = j; break; }\n            if (si != -1) break;\n        if (si == -1) return false;   // should never happen because cnt[col]>0 checked before\n        vector<vector<char>> vis(n, vector<char>(0, false));\n        queue<pair<int,int>> q;\n        q.emplace(si, sj);\n        vis[si][sj] = 1;\n        int reached = 0;\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            ++reached;\n            for (int d = 0; d < 4; ++d) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;\n                if (grid[nx][ny] != col) continue;\n                if (vis[nx][ny]) continue;\n                vis[nx][ny] = 1;\n                q.emplace(nx, ny);\n            }\n        }\n        return reached == cnt[col];\n    }\n\n    /*--------------------------------------------------------*/\n    // check that all zero cells are reachable from the outside\n    bool zeroConnected() const {\n        vector<vector<char>> vis(n, vector<char>(0, false));\n        queue<pair<int,int>> q;\n        // start from all boundary zero cells (they touch the outside)\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] == 0 && (i == 0 || i == n-1 || j == 0 || j == n-1)) {\n                    q.emplace(i, j);\n                    vis[i][j] = 1;\n                }\n            }\n        }\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;\n                if (grid[nx][ny] != 0) continue;\n                if (vis[nx][ny]) continue;\n                vis[nx][ny] = 1;\n                q.emplace(nx, ny);\n            }\n        }\n        // any zero cell not visited?\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (grid[i][j] == 0 && !vis[i][j]) return false;\n        return true;\n    }\n\n    /*--------------------------------------------------------*/\n    // try to delete cell (i,j); return true iff deletion really happened\n    bool tryDelete(int i, int j) {\n        int col = grid[i][j];\n        if (col == 0) return false;\n        if (!hasZeroNeighbour(i, j)) return false;\n\n        // backup        int backupCnt = cnt[col];\n        vector<tuple<int,int,int>> changes;   // (a,b,delta) to be added to adj[a][b]\n\n        // process the four neighbours        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d], nj = y + dy[d];\n            int nb;\n            bool outside = false;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) { nb = 0; outside = true; }\n            else nb = grid[ni][nj];\n\n            if (nb == col) continue;          // internal edge, nothing to change\n\n            // erase edge col \u2013 nb\n            changes.emplace_back(col, nb, -1);\n            changes.emplace_back(nb, col, -1);\n\n            if (nb != 0 && !outside) {\n                // create edge 0 \u2013 nb\n                changes.emplace_back(0, nb, +1);\n                changes.emplace_back(nb, 0, +1);\n            }\n            // if nb == 0 (inside zero or outside) we only removed a col\u20110 edge\n        }\n\n        // apply changes to adj\n        for (auto &ch : changes) {\n            int a = get<0>(ch), b = get<1>(ch), delta = get<2>(ch);\n            adj[a][b] += delta;\n        }\n\n        // actually delete the cell\n        grid[i][j] = 0;\n        --cnt[col];\n\n        // ----- tests -----\n        bool ok = true;\n        if (cnt[col] == 0) ok = false;                // colour must stay non\u2011empty\n\n        if (ok) {\n            // adjacency matrix must stay exactly the same (as Boolean)\n            for (int x = 0; x <= m && ok; ++x)\n                for (int y = x; y <= m && ok; ++y)\n                    bool cur = (adj[x][y] > 0);\n                    bool orig = (adjOrig[x][y] > 0);\n                    if (cur != orig) { ok = false; break; }\n        }\n        if (ok) {\n            if (!connectedColour(col)) ok = false;\n        }\n        if (ok) {\n            if (!zeroConnected()) ok = false;\n        }\n\n        if (!ok) {\n            // ----- revert -----            grid[i][j] = col;\n            cnt[col] = backupCnt;\n            for (auto &ch : changes) {\n                int a = get<0>(ch), b = get<1>(ch), delta = get<2>(ch);\n                adj[a][b] -= delta;   // undo the addition\n            }\n            return false;\n        }\n        return true;\n    }\n\n    /*--------------------------------------------------------*/\n    void solve() {\n        read();\n        computeAdj(grid, adjOrig);\n        adj = adjOrig;          // start with the original adjacency\n\n        bool progress;\n        do {\n            progress = false;\n            vector<pair<int,int>> cand;\n            for (int i = 0; i < n; ++i)\n                for (int j = 0; j < n; ++j)\n                    if (grid[i][j] > 0)\n                        cand.emplace_back(i, j);\n            std::shuffle(cand.begin(), cand.end(),\n                         std::mt19937{std::random_device{}()});\n            for (auto &p : cand)\n                if (tryDelete(p.first, p.second))\n                    progress = true;\n        } while (progress);\n\n        // output the final grid\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << grid[i][j];\n                if (j + 1 < n) cout << ' ';\n            }\n            cout << '\\n';\n        }\n    }\n};\n\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m;\n    cin >> n >> m;\n    Solver solver(n, m);\n    solver.solve();\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    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n\n    // cache for known comparisons: 0 = unknown, '<', '>', '='\n    vector<vector<char>> known(N, vector<char>(N, 0));\n    int query_cnt = 0;\n\n    auto ask = [&](int a, int b) -> char {\n        ++query_cnt;                     // we are guaranteed query_cnt <= Q when called\n        cout << 1 << ' ' << 1 << ' ' << a << ' ' << b << '\\n';\n        cout.flush();\n        string res;\n        cin >> res;\n        char c = res[0];\n        known[a][b] = c;\n        known[b][a] = (c == '<' ? '>' : (c == '>' ? '<' : '='));\n        return c;\n    };\n\n    vector<int> order;                   // will hold items sorted by weight (lightest -> heaviest)\n    vector<bool> in_order(N, false);\n\n    // -------- 1. insertion sort with binary search, stop when queries exhausted --------\n    for (int item = 0; item < N && query_cnt < Q; ++item) {\n        if (order.empty()) {\n            order.push_back(item);\n            in_order[item] = true;\n            continue;\n        }\n        int lo = 0, hi = (int)order.size();\n        while (lo < hi && query_cnt < Q) {\n            int mid = (lo + hi) / 2;\n            char res = ask(item, order[mid]);\n            if (res == '<') {\n                hi = mid;\n            } else if (res == '>') {\n                lo = mid + 1;\n            } else {                     // '=', treat as not less\n                lo = mid + 1;\n            }\n        }\n        if (query_cnt >= Q) break;       // no more queries, stop sorting\n        order.insert(order.begin() + lo, item);\n        in_order[item] = true;\n    }\n\n    // -------- 2. estimate weights from the obtained order --------\n    vector<int64_t> weight(N, 0);\n    int sorted_len = (int)order.size();\n    for (int i = 0; i < sorted_len; ++i) {\n        weight[order[i]] = i;            // 0 = lightest, sorted_len-1 = heaviest among known\n    }\n    // items not processed yet: treat them as heavier than all known items\n    for (int i = 0; i < N; ++i) {\n        if (!in_order[i]) weight[i] = sorted_len;\n    }\n\n    // -------- 3. LPT (greedy) partition into D groups --------\n    vector<int> answer(N);\n    vector<int64_t> group_sum(D, 0);\n    vector<int> items(N);\n    iota(items.begin(), items.end(), 0);\n    sort(items.begin(), items.end(),\n         [&](int x, int y) { return weight[x] > weight[y]; });   // descending weight\n\n    for (int v : items) {\n        int g = 0;\n        for (int j = 1; j < D; ++j) {\n            if (group_sum[j] < group_sum[g]) g = j;\n        }\n        answer[v] = g;\n        group_sum[g] += weight[v];\n    }\n\n    // -------- 4. consume remaining queries with dummy comparisons --------\n    while (query_cnt < Q) {\n        // N >= 30 guarantees items 0 and 1 exist and are different\n        ask(0, 1);\n    }\n\n    // -------- 5. output the partition --------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << answer[i];\n    }\n    cout << '\\n';\n    cout.flush();\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    int per = n / m;\n    vector<vector<int>> stacks(m);\n    for (int i = 0; i < m; ++i) {\n        stacks[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x;\n            cin >> x;\n            stacks[i].push_back(x);\n        }\n    }\n\n    using pii = pair<int, int>;\n    vector<pii> ops;\n    ops.reserve(2 * n);   // at most two operations per box\n\n    for (int v = 1; v <= n; ++v) {\n        int src = -1, pos = -1;\n        for (int i = 0; i < m; ++i) {\n            auto &st = stacks[i];\n            for (size_t j = 0; j < st.size(); ++j) {\n                if (st[j] == v) {\n                    src = i;\n                    pos = static_cast<int>(j);\n                    break;\n                }\n            }\n            if (src != -1) break;\n        }\n\n        int sz = (int)stacks[src].size();\n        if (pos == sz - 1) {                 // already on top\n            ops.emplace_back(v, 0);          // operation 2\n            stacks[src].pop_back();\n            continue;\n        }\n\n        int w = stacks[src][pos + 1];        // box directly above v\n\n        // Find destination stack != src with minimal height.\n        // If several have the same height, pick the one with the largest top value\n        // (to avoid burying small numbers that will be processed soon).\n        int best = -1;\n        int bestHeight = 1e9;\n        int bestTop = -1;                    // top value of the best stack (meaningless if empty)\n        for (int i = 0; i < m; ++i) {\n            if (i == src) continue;\n            int h = (int)stacks[i].size();\n            int top = stacks[i].empty() ? -1 : stacks[i].back();\n            if (h < bestHeight || (h == bestHeight && top > bestTop)) {\n                bestHeight = h;\n                bestTop = top;\n                best = i;\n            }\n        }\n        int dest = best;                     // guaranteed to exist (m >= 2)\n\n        // Move the suffix [w ... top] from src to dest\n        vector<int> moved;\n        moved.reserve(sz - (pos + 1));\n        for (size_t j = pos + 1; j < stacks[src].size(); ++j)\n            moved.push_back(stacks[src][j]);\n\n        stacks[src].erase(stacks[src].begin() + pos + 1, stacks[src].end());\n        stacks[dest].insert(stacks[dest].end(), moved.begin(), moved.end());\n\n        // Operation 1: move w (and everything above it)\n        ops.emplace_back(w, dest + 1);       // output uses 1\u2011based index\n        // Now v is on top of its source stack\n        ops.emplace_back(v, 0);              // operation 2: carry out v\n        stacks[src].pop_back();              // remove v\n    }\n\n    for (auto &p : ops)\n        cout << p.first << ' ' << p.second << '\\n';\n    return 0;\n}","ahc027":"#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\n    // walls\n    vector<string> h(N - 1), v(N);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    // dirt\n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) cin >> d[i][j];\n\n    // helpers to test walls\n    auto canUp = [&](int i, int j) { return i > 0 && h[i - 1][j] == '0'; };\n    auto canDown = [&](int i, int j) { return i + 1 < N && h[i][j] == '0'; };\n    auto canLeft = [&](int i, int j) { return j > 0 && v[i][j - 1] == '0'; };\n    auto canRight = [&](int i, int j) { return j + 1 < N && v[i][j] == '0'; };\n\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 oppChar[4] = {'D', 'U', 'R', 'L'};\n\n    const int MAX_LEN = 100000;\n    auto id = [&](int r, int c) { return r * N + c; };\n    const int V = N * N;\n    vector<vector<int>> adj(V);\n\n    // build adjacency list (no walls)\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            int u = id(r, c);\n            for (int dir = 0; dir < 4; ++dir) {\n                int nr = r + dx[dir];\n                int nc = c + dy[dir];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                bool ok = false;\n                if (dir == 0) ok = canUp(r, c);\n                else if (dir == 2) ok = canLeft(r, c);\n                else if (dir == 1) ok = canDown(r, c);\n                else if (dir == 3) ok = canRight(r, c);\n                if (ok) adj[u].push_back(id(nr, nc));\n            }\n        }\n    }\n\n    // ---------- BFS from (0,0) for shortest paths ----------\n    const int start_id = 0;\n    vector<int> parent(V, -1), dist(V, -1);\n    queue<int> q;\n    dist[start_id] = 0;\n    parent[start_id] = start_id;\n    q.push(start_id);\n    while (!q.empty()) {\n        int u = q.front(); q.pop();\n        int ur = u / N, uc = u % N;\n        for (int v : adj[u]) {\n            if (dist[v] == -1) {\n                dist[v] = dist[u] + 1;\n                parent[v] = u;\n                q.push(v);\n            }\n        }\n    }\n    int maxDist = *max_element(dist.begin(), dist.end());\n\n    // ---------- DFS to visit every cell (returns to start) ----------\n    vector<char> visited(V, false);\n    string baseMoves;          // safe baseline\n\n    function<void(int)> dfs = [&](int u) {\n        visited[u] = true;\n        int ur = u / N, uc = u % N;\n        for (int dir = 0; dir < 4; ++dir) {\n            int vr = ur + dx[dir];\n            int vc = uc + dy[dir];\n            if (vr < 0 || vr >= N || vc < 0 || vc >= N) continue;\n            int v = id(vr, vc);\n            bool ok = false;\n            if (dir == 0) ok = canUp(ur, uc);\n            else if (dir == 2) ok = canLeft(ur, uc);\n            else if (dir == 1) ok = canDown(ur, uc);\n            else if (dir == 3) ok = canRight(ur, uc);\n            if (!ok || visited[v]) continue;\n            baseMoves.push_back(dirChar[dir]);\n            dfs(v);\n            baseMoves.push_back(oppChar[dir]);\n        }\n    };\n    dfs(start_id);\n\n    // ---------- Try to improve with MH walk ----------\n    // precompute sqrt(d)\n    vector<double> sqrtD(V);\n    for (int i = 0; i < V; ++i) {\n        int r = i / N, c = i % N;\n        sqrtD[i] = sqrt(d[r][c]);\n    }\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_real_distribution<double> real01(0.0, 1.0);\n\n    int remaining = MAX_LEN - (int)baseMoves.size() - maxDist;\n    if (remaining < 0) remaining = 0;\n    int MH_steps = remaining;\n\n    string candMoves = baseMoves;\n    int cur = start_id;\n    for (int step = 0; step < MH_steps; ++step) {\n        const vector<int>& nb = adj[cur];\n        if (nb.empty()) continue;\n        uniform_int_distribution<int> pickNi(0, (int)nb.size() - 1);\n        int nxt = nb[pickNi(rng)];\n        double accept = min(1.0, sqrtD[nxt] / sqrtD[cur]);\n        if (real01(rng) < accept) {\n            int nr = nxt / N, nc = nxt % N;\n            int ur = cur / N, uc = cur % N;\n            int dir;\n            if (nr == ur - 1 && nc == uc) dir = 0;\n            else if (nr == ur + 1 && nc == uc) dir = 1;\n            else if (nr == ur && nc == uc - 1) dir = 2;\n            else if (nr == ur && nc == uc + 1) dir = 3;\n            else dir = 0; // safety\n            candMoves.push_back(dirChar[dir]);\n            cur = nxt;\n        }\n        // else: stay, no output\n    }\n\n    // return to start using BFS parent pointers\n    while (cur != start_id) {\n        int par = parent[cur];\n        int ur = cur / N, uc = cur % N;\n        int pr = par / N, pc = par % N;\n        int dir;\n        if (pr == ur - 1 && pc == uc) dir = 0;\n        else if (pr == ur + 1 && pc == uc) dir = 1;\n        else if (pr == ur && pc == uc - 1) dir = 2;\n        else if (pr == ur && pc == uc + 1) dir = 3;\n        else dir = 0;\n        candMoves.push_back(dirChar[dir]);\n        cur = par;\n    }\n\n    // ---------- Validate the candidate route ----------\n    auto validate = [&](const string& moves) -> bool {\n        int r = 0, c = 0; // start at (0,0)\n        for (char ch : moves) {\n            int nr = r, nc = c;\n            if (ch == 'U') nr--;\n            else if (ch == 'D') nr++;\n            else if (ch == 'L') nc--;\n            else if (ch == 'R') nc++;\n            // bounds\n            if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n            // wall check\n            if (ch == 'U') { if (!canUp(r, c)) return false; }\n            else if (ch == 'D') { if (!canDown(r, c)) return false; }\n            else if (ch == 'L') { if (!canLeft(r, c)) return false; }\n            else if (ch == 'R') { if (!canRight(r, c)) return false; }\n            r = nr; c = nc;\n        }\n        // must end at start\n        return (r == 0 && c == 0);\n    };\n\n    string answer = validate(candMoves) ? candMoves : baseMoves;\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        int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n    \n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) cin >> t[i];\n    \n    // ---------- Greedy shortest common superstring ----------\n    auto overlap = [&](const string& a, const string& b) -> int {\n        int maxk = min((int)a.size(), (int)b.size());\n        for (int k = maxk; k >= 0; --k) {\n            if (a.substr(a.size() - k, k) == b.substr(0, k)) return k;\n        }\n        return 0;\n    };\n    \n    vector<string> cur = t;\n    while (cur.size() > 1) {\n        int best_i = -1, best_j = -1, best_ov = -1;\n        string best_merge;\n        for (size_t i = 0; i < cur.size(); ++i) {\n            for (size_t j = 0; j < cur.size(); ++j) {\n                if (i == j) continue;\n                int ov = overlap(cur[i], cur[j]);\n                if (ov > best_ov) {\n                    best_ov = ov;\n                    best_i = (int)i;\n                    best_j = (int)j;\n                    best_merge = cur[i] + cur[j].substr(ov);\n                }\n            }\n        }\n        // merge best_i and best_j\n        if (best_i > best_j) swap(best_i, best_j);\n        cur.erase(cur.begin() + best_j);\n        cur.erase(cur.begin() + best_i);\n        cur.push_back(best_merge);\n    }\n    string S = cur.empty() ? \"\" : cur[0];\n    // ---------------------------------------------------------    \n    // Precompute positions of each letter\n    vector<vector<int>> pos(26);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            pos[grid[i][j] - 'A'].push_back(i * N + j);\n        }\n    }\n    \n    auto dist = [&](int a, int b) {\n        int r1 = a / N, c1 = a % N;\n        int r2 = b / N, c2 = b % N;\n        return abs(r1 - r2) + abs(c1 - c2);\n    };\n    \n    const int INF = 1e9;\n    int L = (int)S.size();\n    if (L == 0) {\n        // output nothing (zero operations) \u2013 still valid\n        return 0;\n    }\n    \n    // DP: dpPrev[cell] = min cost to have processed prefix ending at this cell\n    vector<int> dpPrev(N * N, INF);\n    // prv[i][cell] = previous cell for position i (0\u2011based) ending at cell\n    vector<vector<int>> prv(L, vector<int>(N * N, -1));\n    \n    // first character\n    char first = S[0];\n    for (int id : pos[first - 'A']) {\n        int d = dist(si * N + sj, id);\n        dpPrev[id] = d + 1; // move + press        prv[0][id] = -2;   // start marker\n    }\n        // subsequent characters\n    for (int i = 1; i < L; ++i) {\n        char curc = S[i];\n        char prec = S[i - 1];\n        vector<int> dpCurr(N * N, INF);\n        for (int id : pos[curc - 'A']) {\n            int bestCost = INF;\n            int bestPrev = -1;\n            for (int pid : pos[prec - 'A']) {\n                if (dpPrev[pid] == INF) continue;\n                int cand = dpPrev[pid] + dist(pid, id) + 1;\n                if (cand < bestCost) {\n                    bestCost = cand;\n                    bestPrev = pid;\n                }\n            }\n            dpCurr[id] = bestCost;\n            prv[i][id] = bestPrev;\n        }\n        dpPrev.swap(dpCurr);\n    }\n    \n    // find best end\n    int lastId = -1;\n    int minCost = INF;\n    char lastc = S.back();\n    for (int id : pos[lastc - 'A']) {\n        if (dpPrev[id] < minCost) {\n            minCost = dpPrev[id];\n            lastId = id;\n        }\n    }\n    \n    // reconstruct path\n    vector<int> path(L);\n    path[L - 1] = lastId;\n    for (int i = L - 1; i > 0; --i) {\n        path[i - 1] = prv[i][path[i]];\n    }\n    \n    // output operations\n    for (int id : path) {\n        int r = id / N;\n        int c = id % N;\n        cout << r << ' ' << c << '\\n';\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;\n\n    long long total_oil = 0;          // \u03a3 d_k, known from input\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        total_oil += d;\n        // skip the coordinates of this polyomino\n        for (int i = 0; i < 2 * d; ++i) {\n            int x; cin >> x;\n        }\n    }\n\n    vector<pair<int,int>> oil;\n    oil.reserve(N * N);\n    long long found = 0;               // current sum of v(i,j) discovered\n\n    for (int i = 0; i < N && found < total_oil; ++i) {\n        for (int j = 0; j < N && found < total_oil; ++j) {\n            cout << \"q 1 \" << i << ' ' << j << endl;\n            int v;\n            if (!(cin >> v)) return 0;\n            if (v > 0) oil.emplace_back(i, j);\n            found += v;\n        }\n    }\n\n    // Output the guessed set of cells with oil.\n    cout << \"a \" << oil.size();\n    for (const auto& p : oil) {\n        cout << ' ' << p.first << ' ' << p.second;\n    }\n    cout << endl;\n    cout.flush();\n\n    // Read verdict (1 if correct, 0 otherwise) and exit.\n    int verdict;\n    if (cin >> verdict) {}\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    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cin >> a[d][k];\n        }\n    }\n\n    vector<vector<array<int, 4>>> ans(D, vector<array<int, 4>>(N));\n\n    for (int d = 0; d < D; ++d) {\n        vector<pair<int, int>> vec;\n        for (int k = 0; k < N; ++k) {\n            vec.emplace_back(a[d][k], k);\n        }\n        sort(vec.rbegin(), vec.rend());\n\n        vector<int> width(N, 1);\n        int R = W - N;\n        for (int unit = 0; unit < R; ++unit) {\n            int best_i = -1;\n            long long best_reduction = -1;\n            for (int i = 0; i < N; ++i) {\n                int demand_i = vec[i].first;\n                long long w_i = width[i];\n                long long area_i = w_i * W;\n                long long cost_i = (demand_i > area_i) ? 100LL * (demand_i - area_i) : 0;\n                long long w_new = w_i + 1;\n                long long area_new = w_new * W;\n                long long cost_new = (demand_i > area_new) ? 100LL * (demand_i - area_new) : 0;\n                long long reduction = cost_i - cost_new;\n                if (reduction > best_reduction) {\n                    best_reduction = reduction;\n                    best_i = i;\n                }\n            }\n            width[best_i] += 1;\n        }\n\n        int cur = 0;\n        for (int i = 0; i < N; ++i) {\n            int idx = vec[i].second;\n            int x0 = cur;\n            int x1 = cur + width[idx];\n            ans[d][idx] = {0, x0, W, x1};\n            cur = x1;\n        }\n    }\n\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            auto &r = ans[d][k];\n            cout << r[0] << ' ' << r[1] << ' ' << r[2] << ' ' << r[3] << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst ll MOD = 998244353LL;\n\nstruct Op {\n    int m, p, q;\n    Op() {}\n    Op(int _m, int _p, int _q) : m(_m), p(_p), q(_q) {}\n};\n\nll add_mod(ll x, ll v) {\n    ll xv = x + v;\n    if (xv >= MOD) xv -= MOD;\n    return xv;\n}\nll sub_mod(ll x, ll v) {\n    ll xv = x - v;\n    if (xv < 0) xv += MOD;\n    return xv;\n}\n\n/* ---------- Global state for the current test case ---------- */\nint N, M, K;\nvector<vector<ll>> init_a; // initial board\nvector<array<array<ll, 3>, 3>> stamps; // stamp data\n\nvector<vector<ll>> cur; // current board values (mod MOD)\nll cur_score = 0; // sum of cur[i][j]\nvector<Op> ops; // current operations\n\n/* ---------- Delta computation (without modifying state) ---------- */\nll delta_add(int m, int p, int q) {\n    ll d = 0;\n    const auto& stamp = stamps[m];\n    for (int di = 0; di < 3; ++di)\n        for (int dj = 0; dj < 3; ++dj) {\n            int i = p + di, j = q + dj;\n            ll x = cur[i][j];\n            ll v = stamp[di][dj];\n            ll nx = x + v;\n            if (nx >= MOD) nx -= MOD;\n            d += nx - x;\n        }\n    return d;\n}\n\nll delta_remove(const Op& op) {\n    ll d = 0;\n    const auto& stamp = stamps[op.m];\n    for (int di = 0; di < 3; ++di)\n        for (int dj = 0; dj < 3; ++dj) {\n            int i = op.p + di, j = op.q + dj;\n            ll x = cur[i][j];\n            ll v = stamp[di][dj];\n            ll nx = x - v;\n            if (nx < 0) nx += MOD;\n            d += nx - x;\n        }\n    return d;\n}\n\nll delta_swap(const Op& op_old, int m_new, int p_new, int q_new) {\n    ll d = 0;\n    const auto& stamp_old = stamps[op_old.m];\n    const auto& stamp_new = stamps[m_new];\n    int p1 = op_old.p, q1 = op_old.q;\n    int p2 = p_new, q2 = q_new;\n    int min_p = min(p1, p2), max_p = max(p1+2, p2+2);\n    int min_q = min(q1, q2), max_q = max(q1+2, q2+2);\n    for (int i = min_p; i <= max_p; ++i)\n        for (int j = min_q; j <= max_q; ++j) {\n            bool in_old = (i >= p1 && i <= p1+2 && j >= q1 && j <= q1+2);\n            bool in_new = (i >= p2 && i <= p2+2 && j >= q2 && j <= q2+2);\n            ll x = cur[i][j];\n            ll val = x;\n            if (in_old) {\n                ll v_old = stamp_old[i - p1][j - q1];\n                val = sub_mod(val, v_old);\n            }\n            if (in_new) {\n                ll v_new = stamp_new[i - p2][j - q2];\n                val = add_mod(val, v_new);\n            }\n            d += val - x;\n        }\n    return d;\n}\n\n/* ---------- State modification (and returning delta) ---------- */\nll apply_add(int m, int p, int q) {\n    ll d = 0;\n    const auto& stamp = stamps[m];\n    for (int di = 0; di < 3; ++di)\n        for (int dj = 0; dj < 3; ++dj) {\n            int i = p + di, j = q + dj;\n            ll& x = cur[i][j];\n            ll v = stamp[di][dj];\n            ll nx = x + v;\n            if (nx >= MOD) nx -= MOD;\n            d += nx - x;\n            x = nx;\n        }\n    return d;\n}\n\nll apply_remove(const Op& op) {\n    ll d = 0;\n    const auto& stamp = stamps[op.m];\n    for (int di = 0; di < 3; ++di)\n        for (int dj = 0; dj < 3; ++dj) {\n            int i = op.p + di, j = op.q + dj;\n            ll& x = cur[i][j];\n            ll v = stamp[di][dj];\n            ll nx = x - v;\n            if (nx < 0) nx += MOD;\n            d += nx - x;\n            x = nx;\n        }\n    return d;\n}\n\nll apply_swap(const Op& op_old, int m_new, int p_new, int q_new) {\n    ll d = 0;\n    // remove old\n    const auto& stamp_old = stamps[op_old.m];\n    for (int di = 0; di < 3; ++di)\n        for (int dj = 0; dj < 3; ++dj) {\n            int i = op_old.p + di, j = op_old.q + dj;\n            ll& x = cur[i][j];\n            ll v = stamp_old[di][dj];\n            ll nx = x - v;\n            if (nx < 0) nx += MOD;\n            d += nx - x;\n            x = nx;\n        }\n    // add new\n    const auto& stamp_new = stamps[m_new];\n    for (int di = 0; di < 3; ++di)\n        for (int dj = 0; dj < 3; ++dj) {\n            int i = p_new + di, j = q_new + dj;\n            ll& x = cur[i][j];\n            ll v = stamp_new[di][dj];\n            ll nx = x + v;\n            if (nx >= MOD) nx -= MOD;\n            d += nx - x;\n            x = nx;\n        }\n    return d;\n}\n\n/* ---------- Score computation ---------- */\nll compute_score() {\n    ll s = 0;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            s += cur[i][j];\n    return s;\n}\n\n/* ---------- Main solving routine ---------- */\nvoid solve() {\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_stamp(0, M-1);\n    uniform_int_distribution<int> dist_pos(0, N-3);\n    uniform_real_distribution<double> dist01(0.0, 1.0);\n\n    auto start_time = chrono::high_resolution_clock::now();\n    auto elapsed = [&]() {\n        return chrono::duration<double>(chrono::high_resolution_clock::now() - start_time).count();\n    };\n    const double TIME_LIMIT = 1.92; // seconds\n\n    ll best_score = -1;\n    vector<Op> best_ops;\n\n    for (int restart = 0; restart < 50; ++restart) {\n        if (elapsed() >= TIME_LIMIT) break;\n\n        // reset state\n        cur = init_a;\n        cur_score = compute_score();\n        ops.clear();\n\n        // random initialization: a few random adds\n        int init_add = 6;\n        for (int t = 0; t < init_add; ++t) {\n            int m = dist_stamp(rng);\n            int p = dist_pos(rng);\n            int q = dist_pos(rng);\n            ll d = apply_add(m, p, q);\n            cur_score += d;\n            ops.emplace_back(m, p, q);\n        }\n\n        bool improved;\n        do {\n            improved = false;\n            if (elapsed() >= TIME_LIMIT) break;\n\n            ll best_delta = 0;\n            int best_type = 0; // 1=add, 2=remove, 3=swap\n            int best_m = -1, best_p = -1, best_q = -1;\n            int best_idx = -1;\n            int best_m2 = -1, best_p2 = -1, best_q2 = -1;\n\n            // try add\n            if ((int)ops.size() < K) {\n                for (int m = 0; m < M; ++m) {\n                    for (int p = 0; p <= N-3; ++p) {\n                        for (int q = 0; q <= N-3; ++q) {\n                            ll d = delta_add(m, p, q);\n                            if (d > best_delta) {\n                                best_delta = d;\n                                best_type = 1;\n                                best_m = m; best_p = p; best_q = q;\n                            }\n                        }\n                    }\n                }\n            }\n\n            // try remove\n            if (!ops.empty()) {\n                for (size_t idx = 0; idx < ops.size(); ++idx) {\n                    ll d = delta_remove(ops[idx]);\n                    if (d > best_delta) {\n                        best_delta = d;\n                        best_type = 2;\n                        best_idx = (int)idx;\n                    }\n                }\n            }\n\n            // try swap (limited sampling)\n            if (!ops.empty() && (int)ops.size() < K) {\n                for (size_t idx_old = 0; idx_old < ops.size(); ++idx_old) {\n                    for (int t = 0; t < 15; ++t) {\n                        int m = dist_stamp(rng);\n                        int p = dist_pos(rng);\n                        int q = dist_pos(rng);\n                        if (m == ops[idx_old].m && p == ops[idx_old].p && q == ops[idx_old].q) continue;\n                        ll d = delta_swap(ops[idx_old], m, p, q);\n                        if (d > best_delta) {\n                            best_delta = d;\n                            best_type = 3;\n                            best_idx = (int)idx_old;\n                            best_m2 = m; best_p2 = p; best_q2 = q;\n                        }\n                    }\n                }\n            }\n\n            if (best_delta > 0) {\n                improved = true;\n                if (best_type == 1) { // add\n                    ll d = apply_add(best_m, best_p, best_q);\n                    cur_score += d;\n                    ops.emplace_back(best_m, best_p, best_q);\n                } else if (best_type == 2) { // remove\n                    ll d = apply_remove(ops[best_idx]);\n                    cur_score += d;\n                    ops.erase(ops.begin() + best_idx);\n                } else { // swap\n                    ll d = apply_swap(ops[best_idx], best_m2, best_p2, best_q2);\n                    cur_score += d;\n                    ops[best_idx] = Op(best_m2, best_p2, best_q2);\n                }\n            }\n        } while (improved && elapsed() < TIME_LIMIT);\n\n        // perturbation to escape local optima\n        if (elapsed() < TIME_LIMIT) {\n            int perturb_steps = 5;\n            for (int t = 0; t < perturb_steps; ++t) {\n                if (rng() % 2 && !ops.empty()) {\n                    int idx = uniform_int_distribution<int>(0, (int)ops.size()-1)(rng);\n                    ll d = apply_remove(ops[idx]);\n                    cur_score += d;\n                    ops.erase(ops.begin() + idx);\n                } else if ((int)ops.size() < K) {\n                    int m = dist_stamp(rng);\n                    int p = dist_pos(rng);\n                    int q = dist_pos(rng);\n                    ll d = apply_add(m, p, q);\n                    cur_score += d;\n                    ops.emplace_back(m, p, q);\n                }\n            }\n            // short hill climbing after perturbation\n            for (int it = 0; it < 10 && elapsed() < TIME_LIMIT; ++it) {\n                ll best_delta = 0;\n                int best_type = 0;\n                int best_m = -1, best_p = -1, best_q = -1;\n                int best_idx = -1;\n                int best_m2 = -1, best_p2 = -1, best_q2 = -1;\n\n                if ((int)ops.size() < K) {\n                    for (int m = 0; m < M; ++m)\n                        for (int p = 0; p <= N-3; ++p)\n                            for (int q = 0; q <= N-3; ++q) {\n                                ll d = delta_add(m, p, q);\n                                if (d > best_delta) { best_delta = d; best_type = 1; best_m = m; best_p = p; best_q = q; }\n                            }\n                }\n                if (!ops.empty()) {\n                    for (size_t idx = 0; idx < ops.size(); ++idx) {\n                        ll d = delta_remove(ops[idx]);\n                        if (d > best_delta) { best_delta = d; best_type = 2; best_idx = (int)idx; }\n                    }\n                }\n                if (!ops.empty() && (int)ops.size() < K) {\n                    for (size_t idx_old = 0; idx_old < ops.size(); ++idx_old) {\n                        for (int t = 0; t < 8; ++t) {\n                            int m = dist_stamp(rng);\n                            int p = dist_pos(rng);\n                            int q = dist_pos(rng);\n                            if (m == ops[idx_old].m && p == ops[idx_old].p && q == ops[idx_old].q) continue;\n                            ll d = delta_swap(ops[idx_old], m, p, q);\n                            if (d > best_delta) { best_delta = d; best_type = 3; best_idx = (int)idx_old; best_m2 = m; best_p2 = p; best_q2 = q; }\n                        }\n                    }\n                }\n                if (best_delta <= 0) break;\n                if (best_type == 1) {\n                    ll d = apply_add(best_m, best_p, best_q);\n                    cur_score += d;\n                    ops.emplace_back(best_m, best_p, best_q);\n                } else if (best_type == 2) {\n                    ll d = apply_remove(ops[best_idx]);\n                    cur_score += d;\n                    ops.erase(ops.begin() + best_idx);\n                } else {\n                    ll d = apply_swap(ops[best_idx], best_m2, best_p2, best_q2);\n                    cur_score += d;\n                    ops[best_idx] = Op(best_m2, best_p2, best_q2);\n                }\n            }\n        }\n\n        if (cur_score > best_score) {\n            best_score = cur_score;\n            best_ops = ops;\n        }\n    }\n\n    // output best solution\n    cout << best_ops.size() << '\\n';\n    for (const Op& op : best_ops)\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    if (!(cin >> N >> M >> K)) return 0;\n    init_a.assign(N, vector<ll>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> init_a[i][j];\n    stamps.resize(M);\n    for (int m = 0; m < M; ++m)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> stamps[m][i][j];\n    solve();\n    return 0;\n}","ahc033":"#include<bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_TURNS = 10000;\nint N;\nvector<vector<int>> A;\nvector<vector<int>> grid;\nvector<int> next_needed;\nvector<int> next_arrival;\nbool crane_holding = false;\nint held_id = -1;\nint crane_r = 0, crane_c = 0;\nlong long dispatched_count = 0;\nbool done = false;\n\nenum Phase { IDLE, MOVING_TO_PICKUP, AT_PICKUP, MOVING_TO_RELEASE, AT_RELEASE };\nPhase phase = IDLE;\n\nstruct Pos {\n    int r, c;\n    bool operator==(const Pos& other) const { return r == other.r && c == other.c; }\n};\n\nPos pickup_target;\nbool pickup_from_gate;\nint pickup_row;\nint pickup_id;\nPos release_target;\n\nbool inside(int r, int c) {\n    return r >= 0 && r < N && c >= 0 && c < N;\n}\n\nchar move_step(int& cr, int& cc, int tr, int tc) {\n    if (cr < tr) { ++cr; return 'D'; }\n    else if (cr > tr) { --cr; return 'U'; }\n    else if (cc < tc) { ++cc; return 'R'; }\n    else if (cc > tc) { --cc; return 'L'; }\n    else return '.';\n}\n\nint dist(const Pos& a, const Pos& b) {\n    return abs(a.r - b.r) + abs(a.c - b.c);\n}\n\nPos find_container(int val) {\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            if (c == N-1) continue;\n            if (grid[r][c] == val) return {r, c};\n        }\n    }\n    return {-1, -1};\n}\n\nPos find_empty_storage_cell() {\n    for (int r = 0; r < N; ++r) {\n        for (int c = 1; c <= N-2; ++c) {\n            if (grid[r][c] == -1) return {r, c};\n        }\n        if (next_arrival[r] == N && grid[r][0] == -1) return {r, 0};\n    }\n    return {0, 0};\n}\n\nbool choose_pickup_target() {\n    // Priority 1: Gate container that is the next needed for its row\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] != -1) {\n            int val = grid[i][0];\n            if (val == next_needed[i]) {\n                pickup_target = {i, 0};\n                pickup_from_gate = true;\n                pickup_row = i;\n                return true;\n            }\n        }\n    }\n    // Priority 2: Any gate container (to be stored)\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] != -1) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    // Priority 3: Storage container that is the next needed for its row\n    for (int i = 0; i < N; ++i) {\n        int need = next_needed[i];\n        if (need < i * N + N) {\n            Pos p = find_container(need);\n            if (p.r != -1) {\n                pickup_target = p;\n                pickup_from_gate = false;\n                pickup_id = need;\n                return true;\n            }\n        }\n    }\n    // Priority 4: Any storage container\n    for (int i = 0; i < N; ++i) {\n        for (int c = 1; c <= N-2; ++c) {\n            if (grid[i][c] != -1) {\n                pickup_target = {i, c};\n                pickup_from_gate = false;\n                pickup_id = grid[i][c];\n                return true;\n            }\n        }\n        if (next_arrival[i] == N && grid[i][0] != -1) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    // Priority 5: Wait for arrivals\n    for (int i = 0; i < N; ++i) {\n        if (next_arrival[i] < N) {\n            pickup_target = {i, 0};\n            pickup_from_gate = true;\n            pickup_row = i;\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid compute_release_target_after_pickup() {\n    int val = grid[pickup_target.r][pickup_target.c];\n    int intended_row = val / N;\n    Pos intended_pos = {intended_row, N-1};\n    if (grid[intended_pos.r][intended_pos.c] == -1) {\n        release_target = intended_pos;\n    } else {\n        int best_cost = 1e9;\n        Pos best_cell = {-1, -1};\n        for (int r = 0; r < N; ++r) {\n            for (int c = 1; c <= N-2; ++c) {\n                if (grid[r][c] == -1) {\n                    int cost = dist(pickup_target, {r, c}) + dist({r, c}, intended_pos);\n                    if (cost < best_cost) {\n                        best_cost = cost;\n                        best_cell = {r, c};\n                    }\n                }\n            }\n            if (next_arrival[r] == N && grid[r][0] == -1) {\n                int cost = dist(pickup_target, {r, 0}) + dist({r, 0}, intended_pos);\n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_cell = {r, 0};\n                }\n            }\n        }\n        release_target = best_cell;\n    }\n}\n\nvoid process_arrivals() {\n    for (int i = 0; i < N; ++i) {\n        if (next_arrival[i] >= N) continue;\n        if (grid[i][0] == -1 && !(crane_holding && crane_r == i && crane_c == 0)) {\n            int container = A[i][next_arrival[i]];\n            grid[i][0] = container;\n            ++next_arrival[i];\n        }\n    }\n}\n\nvoid process_dispatch() {\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][N-1] != -1) {\n            grid[i][N-1] = -1;\n        }\n    }\n}\n\nchar decide_action() {\n    if (done) return '.';\n    if (phase == IDLE) {\n        if (crane_holding) {\n            phase = IDLE;\n            return '.';\n        }\n        if (!choose_pickup_target()) {\n            done = true;\n            return '.';\n        }\n        phase = MOVING_TO_PICKUP;\n    }\n    if (phase == MOVING_TO_PICKUP) {\n        char ch = move_step(crane_r, crane_c, pickup_target.r, pickup_target.c);\n        if (crane_r == pickup_target.r && crane_c == pickup_target.c) {\n            phase = AT_PICKUP;\n        }\n        return ch;\n    }\n    if (phase == AT_PICKUP) {\n        if (!crane_holding && grid[crane_r][crane_c] != -1) {\n            compute_release_target_after_pickup();\n            phase = MOVING_TO_RELEASE;\n            return 'P';\n        } else {\n            phase = IDLE;\n            return '.';\n        }\n    }\n    if (phase == MOVING_TO_RELEASE) {\n        char ch = move_step(crane_r, crane_c, release_target.r, release_target.c);\n        if (crane_r == release_target.r && crane_c == release_target.c) {\n            phase = AT_RELEASE;\n        }\n        return ch;\n    }\n    if (phase == AT_RELEASE) {\n        if (crane_holding) {\n            phase = IDLE;\n            return 'Q';\n        } else {\n            phase = IDLE;\n            return '.';\n        }\n    }\n    return '.';\n}\n\nvoid apply_action(char ch) {\n    if (ch == '.') return;\n    if (ch == 'U') { /* moved */ }\n    else if (ch == 'D') { /* moved */ }\n    else if (ch == 'L') { /* moved */ }\n    else if (ch == 'R') { /* moved */ }\n    else if (ch == 'P') {\n        assert(!crane_holding);\n        assert(grid[crane_r][crane_c] != -1);\n        held_id = grid[crane_r][crane_c];\n        crane_holding = true;\n        grid[crane_r][crane_c] = -1;\n    } else if (ch == 'Q') {\n        assert(crane_holding);\n        assert(grid[crane_r][crane_c] == -1);\n        grid[crane_r][crane_c] = held_id;\n        if (crane_c == N-1) {\n            int row = crane_r;\n            ++next_needed[row];\n            ++dispatched_count;\n        }\n        crane_holding = false;\n        held_id = -1;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> N;\n    A.assign(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    }\n    grid.assign(N, vector<int>(N, -1));\n    next_needed.assign(N, 0);\n    next_arrival.assign(N, 0);\n    for (int i = 0; i < N; ++i) {\n        next_needed[i] = i * N;\n    }\n    crane_r = 0;\n    crane_c = 0;\n    crane_holding = false;\n    held_id = -1;\n    dispatched_count = 0;\n    done = false;\n    phase = IDLE;\n\n    string actions_large;\n    int turn = 0;\n    while (turn < MAX_TURNS && !done) {\n        process_arrivals();\n        char ch = decide_action();\n        actions_large += ch;\n        apply_action(ch);\n        process_dispatch();\n        ++turn;\n        if (dispatched_count == N * N) done = true;\n    }\n    cout << actions_large << \"\\n\";\n    string small = \"B\";\n    if ((int)actions_large.size() > 1) {\n        small += string(actions_large.size() - 1, '.');\n    } else {\n        small += \".\";\n    }\n    for (int i = 1; i < N; ++i) {\n        cout << small << \"\\n\";\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int r, c;\n    int amt; // amount of soil (positive for both sources and targets)\n};\n\nstruct Transfer {\n    int sr, sc, tr, tc;\n    int amt;\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>> 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<Cell> sources, targets;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            int val = h[i][j];\n            if (val > 0)\n                sources.push_back({i, j, val});\n            else if (val < 0)\n                targets.push_back({i, j, -val});\n        }\n\n    // Greedy matching: repeatedly pick the nearest source-target pair\n    vector<Transfer> transfers;\n    while (true) {\n        int best_i = -1, best_j = -1;\n        int best_dist = INT_MAX;\n        for (size_t i = 0; i < sources.size(); ++i) {\n            if (sources[i].amt <= 0) continue;\n            for (size_t j = 0; j < targets.size(); ++j) {\n                if (targets[j].amt <= 0) continue;\n                int dist = abs(sources[i].r - targets[j].r) + abs(sources[i].c - targets[j].c);\n                if (dist < best_dist) {\n                    best_dist = dist;\n                    best_i = (int)i;\n                    best_j = (int)j;\n                }\n            }\n        }\n        if (best_i == -1) break;\n        int take = min(sources[best_i].amt, targets[best_j].amt);\n        transfers.push_back({sources[best_i].r, sources[best_i].c,\n                             targets[best_j].r, targets[best_j].c, take});\n        sources[best_i].amt -= take;\n        targets[best_j].amt -= take;\n    }\n\n    // Sequence transfers to minimize empty travel (nearest pickup heuristic)\n    vector<bool> used(transfers.size(), false);\n    vector<Transfer> order;\n    int cur_r = 0, cur_c = 0; // current position, start at depot (empty)\n\n    while (true) {\n        int best_idx = -1;\n        int best_dist = INT_MAX;\n        for (size_t i = 0; i < transfers.size(); ++i) {\n            if (used[i]) continue;\n            int dist = abs(cur_r - transfers[i].sr) + abs(cur_c - transfers[i].sc);\n            if (dist < best_dist) {\n                best_dist = dist;\n                best_idx = (int)i;\n            }\n        }\n        if (best_idx == -1) break;\n        used[best_idx] = true;\n        order.push_back(transfers[best_idx]);\n        // move empty to source\n        cur_r = transfers[best_idx].sr;\n        cur_c = transfers[best_idx].sc;\n        // loaded move to target will be done later when generating ops\n        cur_r = transfers[best_idx].tr;\n        cur_c = transfers[best_idx].tc;\n    }\n    // After all transfers, we are at the last target (empty). Return to depot will be added later.\n\n    vector<string> ops;\n    auto add_move = [&](int r, int c, int tr, int tc) -> pair<int, int> {\n        while (r < tr) { ops.push_back(\"D\"); ++r; }\n        while (r > tr) { ops.push_back(\"U\"); --r; }\n        while (c < tc) { ops.push_back(\"R\"); ++c; }\n        while (c > tc) { ops.push_back(\"L\"); --c; }\n        return {r, c};\n    };\n\n    long long load = 0;\n    int cr = 0, cc = 0; // current position for generating ops\n    // Process ordered transfers\n    for (const Transfer &t : order) {\n        // move empty from current position to source\n        tie(cr, cc) = add_move(cr, cc, t.sr, t.sc);\n        // load\n        ops.push_back(\"+\" + to_string(t.amt));\n        load += t.amt;\n        // move loaded from source to target\n        tie(cr, cc) = add_move(t.sr, t.sc, t.tr, t.tc);\n        // unload\n        ops.push_back(\"-\" + to_string(t.amt));\n        load -= t.amt;\n        // now at target, empty (cr, cc)\n    }\n    // return to depot empty\n    tie(cr, cc) = add_move(cr, cc, 0, 0);\n\n    for (const string &s : ops)\n        cout << s << '\\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    int N, M, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> X(seed_count, vector<int>(M));\n    for (int i = 0; i < seed_count; ++i) {\n        for (int j = 0; j < M; ++j) {\n            cin >> X[i][j];\n        }\n    }\n\n    // Order cells by degree (inner cells first)\n    struct Cell { int deg, i, j; };\n    vector<Cell> cells;\n    cells.reserve(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int deg = (i > 0) + (i < N - 1) + (j > 0) + (j < N - 1);\n            cells.push_back({deg, i, j});\n        }\n    }\n    sort(cells.begin(), cells.end(), [](const Cell& a, const Cell& b) {\n        return a.deg > b.deg;\n    });\n    vector<pair<int,int>> pos_order;\n    pos_order.reserve(N * N);\n    for (const auto& c : cells) {\n        pos_order.emplace_back(c.i, c.j);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        // Compute max attribute value and count of seeds achieving it\n        vector<int> max_attr(M, 0);\n        vector<int> count_max(M, 0);\n        for (int id = 0; id < seed_count; ++id) {\n            for (int l = 0; l < M; ++l) {\n                if (X[id][l] > max_attr[l]) {\n                    max_attr[l] = X[id][l];\n                    count_max[l] = 1;\n                } else if (X[id][l] == max_attr[l]) {\n                    count_max[l]++;\n                }\n            }\n        }\n        using SeedScore = pair<double, int>;\n        vector<SeedScore> scores;\n        scores.reserve(seed_count);\n        for (int id = 0; id < seed_count; ++id) {\n            double w = 0.0;\n            long long v = 0;\n            for (int l = 0; l < M; ++l) {\n                v += X[id][l];\n                if (X[id][l] == max_attr[l]) {\n                    w += 1.0 / count_max[l];\n                }\n            }\n            double score = w * 100000.0 + v;\n            scores.emplace_back(score, id);\n        }\n        // Sort by score descending\n        sort(scores.begin(), scores.end(), greater<SeedScore>());\n\n        // Assign top N^2 seeds to cells in pos_order\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        for (int idx = 0; idx < N * N; ++idx) {\n            int sid = scores[idx].second;\n            int i = pos_order[idx].first;\n            int j = pos_order[idx].second;\n            A[i][j] = sid;\n        }\n\n        // Output placement\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << A[i][j];\n                if (j + 1 < N) cout << ' ';\n                else cout << '\\n';\n            }\n        }\n        cout.flush();\n\n        // Read next generation\n        for (int id = 0; id < seed_count; ++id) {\n            for (int l = 0; l < M; ++l) {\n                if (!(cin >> X[id][l])) return 0;\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\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    // Current and target grids\n    vector<vector<int>> cur(N, vector<int>(N));\n    vector<vector<int>> target(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            cur[i][j] = s[i][j] - '0';\n            target[i][j] = t[i][j] - '0';\n        }\n    \n    // Design a simple 2-vertex arm: root (0) and leaf (1) with edge length 1.\n    const int Vp = 2;\n    cout << Vp << '\\n';\n    cout << \"0 1\" << '\\n';   // parent of vertex 1 is 0, length = 1\n    cout << \"0 0\" << '\\n';   // initial root position (top\u2011left)\n    \n    // Direction vectors: 0=right,1=down,2=left,3=up\n    const int DX[4] = {0, 1, 0, -1};\n    const int DY[4] = {1, 0, -1, 0};\n    const char DIR_CHAR[4] = {'R', 'D', 'L', 'U'};\n    \n    int rootX = 0, rootY = 0;   // root coordinates\n    int leafDir = 0;            // current direction of edge (0,1)\n    bool holding = false;       // whether the leaf holds a takoyaki\n    \n    const int MAX_TURNS = 50000;\n    vector<string> ops;\n    ops.reserve(MAX_TURNS);\n    \n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        // Check if all takoyaki are already at targets\n        int srcCnt = 0, dstCnt = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j) {\n                if (cur[i][j] == 1 && target[i][j] == 0) ++srcCnt;\n                if (cur[i][j] == 0 && target[i][j] == 1) ++dstCnt;\n            }\n        if (srcCnt == 0 && dstCnt == 0) break;\n        \n        // Determine desired root position and leaf direction\n        int desiredRX = -1, desiredRY = -1;\n        int desiredDir = -1;\n        \n        if (!holding) {\n            // Look for any source cell (needs to pick up)\n            bool found = false;\n            for (int i = 0; i < N && !found; ++i)\n                for (int j = 0; j < N && !found; ++j) {\n                    if (cur[i][j] == 1 && target[i][j] == 0) {\n                        // Try the four ways to place the leaf on (i,j)\n                        for (int d = 0; d < 4; ++d) {\n                            int rx = i - DX[d];\n                            int ry = j - DY[d];\n                            if (rx >= 0 && rx < N && ry >= 0 && ry < N) {\n                                desiredRX = rx;\n                                desiredRY = ry;\n                                desiredDir = d;\n                                found = true;\n                                break;\n                            }\n                        }\n                    }\n                }\n            if (!found) {   // should not happen because N>=15                // fallback: do nothing\n                ops.emplace_back(\"....\");\n                continue;\n            }\n        } else {\n            // Look for any target cell (needs to drop)\n            bool found = false;\n            for (int i = 0; i < N && !found; ++i)\n                for (int j = 0; j < N && !found; ++j) {\n                    if (cur[i][j] == 0 && target[i][j] == 1) {\n                        for (int d = 0; d < 4; ++d) {\n                            int rx = i - DX[d];\n                            int ry = j - DY[d];\n                            if (rx >= 0 && rx < N && ry >= 0 && ry < N) {\n                                desiredRX = rx;\n                                desiredRY = ry;\n                                desiredDir = d;\n                                found = true;\n                                break;\n                            }\n                        }\n                    }\n                }\n            if (!found) {\n                ops.emplace_back(\"....\");\n                continue;\n            }\n        }\n        \n        // ---- Operation 1: move the whole arm ----\n        char moveChar = '.';\n        if (rootX < desiredRX) { moveChar = 'D'; ++rootX; }\n        else if (rootX > desiredRX) { moveChar = 'U'; --rootX; }\n        else if (rootY < desiredRY) { moveChar = 'R'; ++rootY; }\n        else if (rootY > desiredRY) { moveChar = 'L'; --rootY; }\n        // else stay\n        \n        // ---- Operation 2: rotate subtree at vertex 1 (the leaf) ----\n        char rotChar = '.';\n        int diff = (desiredDir - leafDir + 4) & 3;\n        if (diff != 0) {\n            if (diff == 2) {          // two steps either way; choose right\n                rotChar = 'R';\n                leafDir = (leafDir + 1) & 3;\n            } else if (diff == 1) {   // need one clockwise step\n                rotChar = 'R';\n                leafDir = (leafDir + 1) & 3;\n            } else {                  // diff == 3 -> one counter\u2011clockwise step\n                rotChar = 'L';\n                leafDir = (leafDir + 3) & 3;\n            }\n        }\n                // ---- Operation 3: action at fingertips ----\n        // Vertex 0 (root) is never a leaf -> op[2] stays '.'\n        int leafX = rootX + DX[leafDir];\n        int leafY = rootY + DY[leafDir];\n        bool act = false;\n        if (leafX >= 0 && leafX < N && leafY >= 0 && leafY < N) {\n            if (!holding && cur[leafX][leafY] == 1 && target[leafX][leafY] == 0) {\n                // pick up\n                cur[leafX][leafY] = 0;\n                holding = true;\n                act = true;\n            } else if (holding && cur[leafX][leafY] == 0 && target[leafX][leafY] == 1) {\n                // drop\n                cur[leafX][leafY] = 1;\n                holding = false;\n                act = true;\n            }\n        }\n        char actChar = act ? 'P' : '.';\n        \n        // Build operation string: [move][rot][root action][leaf action]\n        string op(4, '.');\n        op[0] = moveChar;\n        op[1] = rotChar;\n        op[2] = '.';          // root is not a leaf\n        op[3] = actChar;\n        ops.push_back(op);\n    }\n    \n    // Output the operation sequence\n    for (const string& line : ops) cout << line << '\\n';\n    return 0;\n}","ahc039":"#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    const int MAXC = 100000;\n    vector<tuple<int, int, int>> pts_all;\n    pts_all.reserve(2 * N);\n    for (int i = 0; i < 2 * N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        int w = (i < N) ? 1 : -1;\n        pts_all.emplace_back(x, y, w);\n    }\n\n    // Coordinate compression\n    vector<int> xs, ys;\n    xs.reserve(2 * N);\n    ys.reserve(2 * N);\n    for (auto &[x, y, w] : pts_all) {\n        xs.push_back(x);\n        ys.push_back(y);\n    }\n    sort(xs.begin(), xs.end());\n    xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end());\n    ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    int nx = (int)xs.size(), ny = (int)ys.size();\n    unordered_map<int, int> xi, yi;\n    for (int i = 0; i < nx; ++i) xi[xs[i]] = i;\n    for (int i = 0; i < ny; ++i) yi[ys[i]] = i;\n\n    // Build grid (sparse, but we'll make a dense array for the compressed grid)\n    vector<int> grid(nx * ny, 0);\n    for (auto &[x, y, w] : pts_all) {\n        int ix = xi[x];\n        int iy = yi[y];\n        grid[ix * ny + iy] += w;\n    }\n\n    // Build 2D prefix sum (size (nx+1) * (ny+1))\n    vector<int> ps((nx + 1) * (ny + 1), 0);\n    for (int i = 0; i < nx; ++i) {\n        for (int j = 0; j < ny; ++j) {\n            int val = grid[i * ny + j];\n            int a = ps[i * (ny + 1) + (j + 1)];\n            int b = ps[(i + 1) * (ny + 1) + j];\n            int c = ps[i * (ny + 1) + j];\n            ps[(i + 1) * (ny + 1) + (j + 1)] = val + a + b - c;\n        }\n    }\n\n    // Function to compute sum of weights in rectangle [x1,x2]x[y1,y2] (inclusive)\n    auto rect_sum = [&](int x1, int y1, int x2, int y2) -> int {\n        if (x1 > x2) swap(x1, x2);\n        if (y1 > y2) swap(y1, y2);\n        int ix1 = lower_bound(xs.begin(), xs.end(), x1) - xs.begin();\n        int ix2 = upper_bound(xs.begin(), xs.end(), x2) - xs.begin() - 1;\n        int iy1 = lower_bound(ys.begin(), ys.end(), y1) - ys.begin();\n        int iy2 = upper_bound(ys.begin(), ys.end(), y2) - ys.begin() - 1;\n        if (ix1 > ix2 || iy1 > iy2) return 0;\n        auto get = [&](int i, int j) {\n            return ps[i * (ny + 1) + j];\n        };\n        return get(ix2 + 1, iy2 + 1) - get(ix1, iy2 + 1) - get(ix2 + 1, iy1) + get(ix1, iy1);\n    };\n\n    long long bestScore = LLONG_MIN;\n    int bestX1 = 0, bestY1 = 0, bestX2 = 0, bestY2 = 0;\n\n    auto consider = [&](int x1, int y1, int x2, int y2) {\n        // Ensure coordinates are within [0, MAXC]\n        x1 = max(0, min(x1, MAXC));\n        x2 = max(0, min(x2, MAXC));\n        y1 = max(0, min(y1, MAXC));\n        y2 = max(0, min(y2, MAXC));\n        // Ensure at least 1x1 rectangle (so we can output 4 distinct vertices)\n        if (x1 == x2) {\n            if (x2 < MAXC) ++x2;\n            else if (x1 > 0) --x1;\n        }\n        if (y1 == y2) {\n            if (y2 < MAXC) ++y2;\n            else if (y1 > 0) --y1;\n        }\n        // Check perimeter constraint: 2*(width+height) <= 400000\n        int width = x2 - x1;\n        int height = y2 - y1;\n        if (width + height > 200000) return; // 2*(width+height) > 400000\n        int s = rect_sum(x1, y1, x2, y2);\n        if (s > bestScore) {\n            bestScore = s;\n            bestX1 = x1; bestY1 = y1; bestX2 = x2; bestY2 = y2;\n        }\n    };\n\n    // 1) Rectangles centered at mackerels with various scales\n    vector<int> scales = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072};\n    vector<int> mackerel_indices;\n    for (int i = 0; i < N; ++i) mackerel_indices.push_back(i);\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    shuffle(mackerel_indices.begin(), mackerel_indices.end(), rng);\n    int sampleSize = min(N, 500);\n    for (int idx = 0; idx < sampleSize; ++idx) {\n        int i = mackerel_indices[idx];\n        int mx = get<0>(pts_all[i]);\n        int my = get<1>(pts_all[i]);\n        for (int dx : scales) {\n            for (int dy : scales) {\n                int x1 = mx - dx;\n                int x2 = mx + dx;\n                int y1 = my - dy;\n                int y2 = my + dy;\n                consider(x1, y1, x2, y2);\n            }\n        }\n    }\n\n    // 2) Random pairs of mackerels as opposite corners\n    uniform_int_distribution<int> dist_mack(0, N - 1);\n    const int pairTrials = 100000;\n    for (int t = 0; t < pairTrials; ++t) {\n        int i = dist_mack(rng);\n        int j = dist_mack(rng);\n        int x1 = get<0>(pts_all[i]);\n        int y1 = get<1>(pts_all[i]);\n        int x2 = get<0>(pts_all[j]);\n        int y2 = get<1>(pts_all[j]);\n        consider(x1, y1, x2, y2);\n    }\n\n    // 3) Whole range    consider(0, 0, MAXC, MAXC);\n\n    // 4) Bounding box of all mackerels\n    int minX = MAXC, maxX = 0, minY = MAXC, maxY = 0;\n    for (int i = 0; i < N; ++i) {\n        int x = get<0>(pts_all[i]);\n        int y = get<1>(pts_all[i]);\n        minX = min(minX, x);\n        maxX = max(maxX, x);\n        minY = min(minY, y);\n        maxY = max(maxY, y);\n    }\n    consider(minX, minY, maxX, maxY);\n\n    // Output the rectangle (counter\u2011clockwise)\n    cout << 4 << '\\n';\n    cout << bestX1 << ' ' << bestY1 << '\\n';\n    cout << bestX2 << ' ' << bestY1 << '\\n';\n    cout << bestX2 << ' ' << bestY2 << '\\n';\n    cout << bestX1 << ' ' << bestY2 << '\\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, sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    // Read observed dimensions (we use them as proxies for true sizes)\n    vector<int> obsW(N), obsH(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> obsW[i] >> obsH[i];\n    }\n\n    // Precompute for each rectangle:\n    //   a_i = max(obsW[i], obsH[i])  (the larger side)\n    //   b_i = min(obsW[i], obsH[i])  (the smaller side)\n    //   rotation r_i = 0 if obsW[i] >= obsH[i] (so width = a_i, height = b_i)\n    //                = 1 otherwise.\n    vector<int> a(N), b(N), rot(N);\n    for (int i = 0; i < N; ++i) {\n        if (obsW[i] >= obsH[i]) {\n            a[i] = obsW[i];\n            b[i] = obsH[i];\n            rot[i] = 0;\n        } else {\n            a[i] = obsH[i];\n            b[i] = obsW[i];\n            rot[i] = 1;\n        }\n    }\n\n    // Repeat T times: each time output the same strip placement.\n    for (int t = 0; t < T; ++t) {\n        cout << N << '\\n';\n        for (int i = 0; i < N; ++i) {\n            int p = i;\n            int r = rot[i];\n            char d = 'L';                 // place leftward, stacking vertically\n            int bIdx = (i == 0 ? -1 : i-1); // chain by bottom edge of previous rectangle\n            cout << p << ' ' << r << ' ' << d << ' ' << bIdx << '\\n';\n        }\n        cout.flush();\n\n        // Read judge's measurement for this turn (ignore the values)\n        int Wp, Hp;\n        if (!(cin >> Wp >> Hp)) break;\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    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    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    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    const int TRIALS = 800;\n    long long bestScore = LLONG_MIN;\n    vector<int> bestParent(N, -1);\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    auto trial = [&](const vector<int>& order) -> pair<long long, vector<int>> {\n        vector<int> depth(N, -1);\n        for (int v : order) {\n            bool assigned = false;\n            for (int d = H; d >= 1; --d) {\n                bool ok = false;\n                for (int u : adj[v]) {\n                    if (depth[u] == d-1) { ok = true; break; }\n                }\n                if (ok) {\n                    depth[v] = d;\n                    assigned = true;\n                    break;\n                }\n            }\n            if (!assigned) depth[v] = 0;\n        }\n        vector<int> parent(N, -1);\n        long long score = 0;\n        for (int v = 0; v < N; ++v) {\n            if (depth[v] > 0) {\n                for (int u : adj[v]) {\n                    if (depth[u] == depth[v]-1) {\n                        parent[v] = u;\n                        break;\n                    }\n                }\n            }\n            score += 1LL * (depth[v] + 1) * A[v];\n        }\n        return {score, parent};\n    };\n\n    for (int t = 0; t < TRIALS; ++t) {\n        vector<uint64_t> key(N);\n        for (int i = 0; i < N; ++i)\n            key[i] = uniform_int_distribution<uint64_t>(0, UINT64_MAX)(rng);\n\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        int mode = t % 8;\n        if (mode == 0) {\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     if (A[a] != A[b]) return A[a] > A[b];\n                     return key[a] < key[b];\n                 });\n        } else if (mode == 1) {\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     if (A[a] != A[b]) return A[a] < A[b];\n                     return key[a] < key[b];\n                 });\n        } else if (mode == 2) {\n            shuffle(order.begin(), order.end(), rng);\n        } else if (mode == 3) {\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     int da = (int)adj[a].size();\n                     int db = (int)adj[b].size();\n                     if (da != db) return da < db;\n                     return key[a] < key[b];\n                 });\n        } else if (mode == 4) {\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     int da = (int)adj[a].size();\n                     int db = (int)adj[b].size();\n                     if (da != db) return da > db;\n                     return key[a] < key[b];\n                 });\n        } else if (mode == 5) {\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     long long va = 1LL * A[a] * adj[a].size();\n                     long long vb = 1LL * A[b] * adj[b].size();\n                     if (va != vb) return va > vb;\n                     return key[a] < key[b];\n                 });\n        } else if (mode == 6) {\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     long long va = 1LL * A[a] * adj[a].size();\n                     long long vb = 1LL * A[b] * adj[b].size();\n                     if (va != vb) return va < vb;\n                     return key[a] < key[b];\n                 });\n        } else {\n            sort(order.begin(), order.end(),\n                 [&](int a, int b) {\n                     double va = 1.0 * A[a] / (adj[a].size() + 1);\n                     double vb = 1.0 * A[b] / (adj[b].size() + 1);\n                     if (abs(va - vb) > 1e-9) return va > vb;\n                     return key[a] < key[b];\n                 });\n        }\n\n        auto [score, parent] = trial(order);\n        if (score > bestScore) {\n            bestScore = score;\n            bestParent = parent;\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << bestParent[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 Move { char d; int p; };\n    vector<Move> moves;\n    moves.reserve(4 * N * N);\n\n    auto shiftColUp = [&](int j) {\n        for (int i = 0; i + 1 < N; ++i) board[i][j] = board[i + 1][j];\n        board[N - 1][j] = '.';\n    };\n    auto shiftColDown = [&](int j) {\n        for (int i = N - 1; i > 0; --i) board[i][j] = board[i - 1][j];\n        board[0][j] = '.';\n    };\n    auto shiftRowLeft = [&](int i) {\n        for (int j = 0; j + 1 < N; ++j) board[i][j] = board[i][j + 1];\n        board[i][N - 1] = '.';\n    };\n    auto shiftRowRight = [&](int i) {\n        for (int j = N - 1; j > 0; --j) board[i][j] = board[i][j - 1];\n        board[i][0] = '.';\n    };\n\n    auto anyOni = [&]() {\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                if (board[i][j] == 'x') return true;\n        return false;\n    };\n\n    while (anyOni()) {\n        int bestOni = 0, bestK = 0, bestDir = -1, bestIdx = -1;\n        // dir: 0=up column,1=down column,2=left row,3=right row\n\n        // ----- try columns -----\n        for (int j = 0; j < N; ++j) {\n            int upFuku = N;\n            for (int i = 0; i < N; ++i)\n                if (board[i][j] == 'o') { upFuku = i; break; }\n            int downFuku = -1;\n            for (int i = N - 1; i >= 0; --i)\n                if (board[i][j] == 'o') { downFuku = i; break; }\n\n            // upward shift: removes rows [0, upFuku-1]\n            if (upFuku > 0) {\n                int oniCnt = 0;\n                for (int i = 0; i < upFuku; ++i)\n                    if (board[i][j] == 'x') ++oniCnt;\n                if (oniCnt > bestOni || (oniCnt == bestOni && upFuku < bestK)) {\n                    bestOni = oniCnt;\n                    bestK = upFuku;\n                    bestIdx = j;\n                    bestDir = 0; // up\n                }\n            }\n            // downward shift: removes rows [downFuku+1, N-1]\n            if (downFuku < N - 1) {\n                int k = N - downFuku - 1;\n                int oniCnt = 0;\n                for (int i = downFuku + 1; i < N; ++i)\n                    if (board[i][j] == 'x') ++oniCnt;\n                if (oniCnt > bestOni || (oniCnt == bestOni && k < bestK)) {\n                    bestOni = oniCnt;\n                    bestK = k;\n                    bestIdx = j;\n                    bestDir = 1; // down\n                }\n            }\n        }\n\n        // ----- try rows -----\n        for (int i = 0; i < N; ++i) {\n            int leftFuku = N;\n            for (int j = 0; j < N; ++j)\n                if (board[i][j] == 'o') { leftFuku = j; break; }\n            int rightFuku = -1;\n            for (int j = N - 1; j >= 0; --j)\n                if (board[i][j] == 'o') { rightFuku = j; break; }\n\n            // left shift: removes columns [0, leftFuku-1]\n            if (leftFuku > 0) {\n                int oniCnt = 0;\n                for (int j = 0; j < leftFuku; ++j)\n                    if (board[i][j] == 'x') ++oniCnt;\n                if (oniCnt > bestOni || (oniCnt == bestOni && leftFuku < bestK)) {\n                    bestOni = oniCnt;\n                    bestK = leftFuku;\n                    bestIdx = i;\n                    bestDir = 2; // left\n                }\n            }\n            // right shift: removes columns [rightFuku+1, N-1]\n            if (rightFuku < N - 1) {\n                int k = N - rightFuku - 1;\n                int oniCnt = 0;\n                for (int j = rightFuku + 1; j < N; ++j)\n                    if (board[i][j] == 'x') ++oniCnt;\n                if (oniCnt > bestOni || (oniCnt == bestOni && k < bestK)) {\n                    bestOni = oniCnt;\n                    bestK = k;\n                    bestIdx = i;\n                    bestDir = 3; // right\n                }\n            }\n        }\n\n        if (bestOni > 0) {\n            // apply the chosen batch of shifts\n            for (int t = 0; t < bestK; ++t) {\n                switch (bestDir) {\n                    case 0: shiftColUp(bestIdx); moves.push_back({'U', bestIdx}); break;\n                    case 1: shiftColDown(bestIdx); moves.push_back({'D', bestIdx}); break;\n                    case 2: shiftRowLeft(bestIdx); moves.push_back({'L', bestIdx}); break;\n                    case 3: shiftRowRight(bestIdx); moves.push_back({'R', bestIdx}); break;\n                }\n            }\n            continue;\n        }\n\n        // ----- fallback: remove one Oni greedily (minimum cost) -----\n        int si = -1, sj = -1;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (board[i][j] == 'x') { si = i; sj = j; break; }\n            }\n            if (si != -1) break;\n        }\n        if (si == -1) break; // should not happen\n\n        int i = si, j = sj;\n        bool up = true, down = true, left = true, right = true;\n        for (int ii = 0; ii < i; ++ii)\n            if (board[ii][j] == 'o') { up = false; break; }\n        for (int ii = i + 1; ii < N; ++ii)\n            if (board[ii][j] == 'o') { down = false; break; }\n        for (int jj = 0; jj < j; ++jj)\n            if (board[i][jj] == 'o') { left = false; break; }\n        for (int jj = j + 1; jj < N; ++jj)\n            if (board[i][jj] == 'o') { right = false; break; }\n\n        int dir; // 0:U,1:D,2:L,3:R\n        if (up) dir = 0;\n        else if (down) dir = 1;\n        else if (left) dir = 2;\n        else dir = 3;\n\n        if (dir == 0) { // shift column j upward\n            for (int k = 0; k <= i; ++k) {\n                moves.push_back({'U', j});\n                shiftColUp(j);\n            }\n        } else if (dir == 1) { // shift column j downward\n            for (int k = 0; k < N - i; ++k) {\n                moves.push_back({'D', j});\n                shiftColDown(j);\n            }\n        } else if (dir == 2) { // shift row i left\n            for (int k = 0; k <= j; ++k) {\n                moves.push_back({'L', i});\n                shiftRowLeft(i);\n            }\n        } else { // shift row i right\n            for (int k = 0; k < N - j; ++k) {\n                moves.push_back({'R', i});\n                shiftRowRight(i);\n            }\n        }\n    }\n\n    // safety check (can be removed in final version)\n    assert((int)moves.size() <= 4 * N * N);\n\n    for (auto &mv : moves)\n        cout << mv.d << ' ' << mv.p << '\\n';\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nll simulate(const vector<int>& a, const vector<int>& b,\n            const vector<int>& target, vector<int>& cnt) {\n    int N = (int)a.size();\n    int L = (int)target.size();          // total weeks\n    cnt.assign(N, 0);\n    int cur = 0;\n    cnt[cur] = 1;                         // week 1\n    for (int week = 2; week <= L; ++week) {\n        int nx = (cnt[cur] & 1) ? a[cur] : b[cur];\n        cur = nx;\n        ++cnt[cur];\n    }\n    ll err = 0;\n    for (int i = 0; i < N; ++i) {\n        ll diff = (ll)cnt[i] - (ll)target[i];\n        if (diff < 0) diff = -diff;\n        err += diff;\n    }\n    return err;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N_input, L_input;\n    cin >> N_input >> L_input;\n    // Safeguard: use problem-fixed values if input is invalid\n    int N = (N_input <= 0) ? 100 : N_input;\n    int L = (L_input <= 0) ? 500000 : L_input;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    // initial solution: round\u2011robin\n    vector<int> a(N), b(N);\n    for (int i = 0; i < N; ++i) {\n        a[i] = b[i] = (i + 1) % N;\n    }\n\n    vector<int> cnt(N);\n    ll cur_err = simulate(a, b, T, cnt);\n    ll best_err = cur_err;\n    vector<int> best_a = a, best_b = b;\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist_node(0, N - 1);\n    uniform_int_distribution<int> dist_choice(0, 1); // 0 -> a, 1 -> b\n    uniform_real_distribution<double> dist_real(0.0, 1.0);\n\n    // guided move: pick over\u2011visited node i and under\u2011visited node j\n    auto guided_move = [&](const vector<int>& cnt_cur,\n                           int& i, int& which, int& j) -> bool {\n        int n = (int)cnt_cur.size();\n        vector<int> deficit(n);\n        int total_over = 0, total_under = 0;\n        for (int k = 0; k < n; ++k) {\n            int d = T[k] - cnt_cur[k];\n            deficit[k] = d;\n            if (d > 0) total_under += d;\n            else if (d < 0) total_over -= d;\n        }\n        if (total_over == 0) return false; // fallback to random\n\n        // select i (over\u2011visited) with probability proportional to -deficit[i]\n        int r = uniform_int_distribution<int>(0, total_over - 1)(rng);\n        int acc = 0;\n        i = 0;\n        while (i < n) {\n            int d = -deficit[i];\n            if (d > 0) {\n                if (r < acc + d) break;\n                acc += d;\n            }\n            ++i;\n        }\n        // select j (under\u2011visited) with probability proportional to deficit[j]\n        int r2 = uniform_int_distribution<int>(0, total_under - 1)(rng);\n        int acc2 = 0;\n        j = 0;\n        while (j < n) {\n            int d = deficit[j];\n            if (d > 0) {\n                if (r2 < acc2 + d) break;\n                acc2 += d;\n            }\n            ++j;\n        }\n        which = dist_choice(rng); // randomly choose a_i or b_i to change\n        return true;\n    };\n\n    const int MAX_ITER = 500;\n    const double COOLING = 0.998;\n\n    for (int restart = 0; restart < 3; ++restart) {\n        // reset to round\u2011robin for each restart\n        for (int i = 0; i < N; ++i) {\n            a[i] = b[i] = (i + 1) % N;\n        }\n        cur_err = simulate(a, b, T, cnt);\n        if (cur_err < best_err) {\n            best_err = cur_err;\n            best_a = a;\n            best_b = b;\n        }\n        double Ttemp = (double)cur_err; // initial temperature\n        for (int it = 0; it < MAX_ITER; ++it) {\n            int i, which, j;\n            bool use_guided = guided_move(cnt, i, which, j);\n            if (!use_guided) {\n                i = dist_node(rng);\n                which = dist_choice(rng);\n                j = dist_node(rng);\n            }\n            // apply move\n            vector<int> a2 = a, b2 = b;\n            if (which == 0) a2[i] = j;\n            else b2[i] = j;\n            // evaluate move\n            vector<int> cnt2(N);\n            ll err2 = simulate(a2, b2, T, cnt2);\n            bool accept = false;\n            if (err2 < cur_err) accept = true;\n            else {\n                double prob = exp((cur_err - err2) / Ttemp);\n                if (dist_real(rng) < prob) accept = true;\n            }\n            if (accept) {\n                a = a2;\n                b = b2;\n                cur_err = err2;\n                cnt = cnt2;\n                if (err2 < best_err) {\n                    best_err = err2;\n                    best_a = a;\n                    best_b = b;\n                }\n            }\n            Ttemp *= COOLING;\n            if (Ttemp < 1e-5) break;\n        }\n    }\n\n    // output best solution\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    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        // centre of each rectangle (integer division)\n    vector<int> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        cx[i] = (lx[i] + rx[i]) / 2;\n        cy[i] = (ly[i] + ry[i]) / 2;\n    }\n    \n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](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 k = 0; k < M; ++k) {\n        int sz = G[k];\n        vector<int> grp;\n        grp.reserve(sz);\n        for (int i = 0; i < sz; ++i) grp.push_back(idx[pos++]);\n        groups.push_back(move(grp));\n    }\n    \n    // answer edges per group\n    vector<vector<pair<int,int>>> ansEdges(M);\n    ansEdges.reserve(M);\n    int usedQueries = 0;\n    for (int k = 0; k < M; ++k) {\n        const auto& g = groups[k];\n        int sz = (int)g.size();\n        for (int i = 0; i + 1 < sz; i += 2) {\n            if (i + 2 < sz) {\n                // query a triple\n                int a = g[i];\n                int b = g[i+1];\n                int c = g[i+2];\n                cout << \"? 3 \" << a << ' ' << b << ' ' << c << '\\n';\n                cout.flush();\n                ++usedQueries;\n                int u1, v1, u2, v2;\n                cin >> u1 >> v1;\n                cin >> u2 >> v2;\n                ansEdges[k].emplace_back(u1, v1);\n                ansEdges[k].emplace_back(u2, v2);\n            } else {\n                // only a pair left, no query needed\n                ansEdges[k].emplace_back(g[i], g[i+1]);\n            }\n        }\n    }\n    \n    // output the answer\n    cout << \"!\\n\";\n    cout.flush();\n    for (int k = 0; k < M; ++k) {\n        // cities of the group\n        for (size_t i = 0; i < groups[k].size(); ++i) {\n            if (i) cout << ' ';\n            cout << groups[k][i];\n        }\n        cout << '\\n';\n        // edges of the group\n        for (auto &e : ansEdges[k]) {\n            cout << e.first << ' ' << e.second << '\\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>> pts(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> pts[i].first >> pts[i].second;\n    }\n    \n    for (int k = 0; k + 1 < M; ++k) {\n        int ci = pts[k].first, cj = pts[k].second;\n        int ni = pts[k+1].first, nj = pts[k+1].second;\n        \n        while (ci < ni) { cout << \"M D\\n\"; ++ci; }\n        while (ci > ni) { cout << \"M U\\n\"; --ci; }\n        while (cj < nj) { cout << \"M R\\n\"; ++cj; }\n        while (cj > nj) { cout << \"M L\\n\"; --cj; }\n    }\n    \n    return 0;\n}"}}}