{"model_name":"nova-premier-v1","codes":{"1":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int x, y, r, id;\n    bool placed = false;\n};\n\nbool cmp(const Company& a, const Company& b) {\n    return a.r > b.r;  // Larger first\n}\n\nvector<tuple<int,int,int,int>> placeAds(const vector<Company>& companies) {\n    int N = companies.size();\n    vector<tuple<int,int,int,int>> result(N);\n    set<pair<int,int>> occupied;\n    \n    vector<bool> used(N, false);\n    for (const auto& comp : companies) {\n        if (!comp.placed) {\n            int x = comp.x, y = comp.y;\n            // Try to expand rectangle while avoiding overlaps\n            int width = 1, height = comp.r;\n            bool valid = true;\n            for (int dx = 0; dx < width && valid; ++dx)\n                for (int dy = 0; dy < height; ++dy)\n                    if (occupied.count({x+dx, y+dy})) valid = false;\n            if (valid) {\n                for (int dx=0; dx<width; ++dx)\n                    for (int dy=0; dy<height; ++dy)\n                        occupied.emplace(x+dx, y+dy);\n                result[comp.id] = {x, y, x+width, y+height};\n                used[comp.id] = true;\n            } else {\n                // If vertical expansion fails, try horizontal\n                swap(width, height);\n                valid = true;\n                for (int dx = 0; dx < width; ++dx)\n                    for (int dy = 0; dy < height; ++dy)\n                        if (occupied.count({x+dx, y+dy})) valid = false;\n                if (valid) {\n                    for (int dx=0; dx<width; ++dx)\n                        for (int dy=0; dy<height; ++dy)\n                            occupied.emplace(x+dx, y+dy);\n                    result[comp.id] = {x, y, x+width, y+height};\n                    used[comp.id] = true;\n                }\n            }\n        }\n    }\n    \n    // Fill remaining gaps\n    for (int i=0; i<N; ++i) {\n        if (!used[i]) {\n            int x = companies[i].x, y = companies[i].y;\n            int side = max(1, (int)sqrt(companies[i].r));\n            bool found = false;\n            for (int a = max(0, x-side); !found && a <= x+side; ++a) {\n                for (int b = max(0, y-side); !found && b <= y+side; ++b) {\n                    bool valid = true;\n                    for (int dx=0; dx<side && a+dx <= 10000; ++dx) {\n                        for (int dy=0; dy<side && b+dy <= 10000; ++dy) {\n                            if (occupied.count({a+dx, b+dy})) {\n                                valid = false;\n                                break;\n                            }\n                        }\n                        if (!valid) break;\n                    }\n                    if (valid && (a+side <= 10000) && (b+side <= 10000)) {\n                        for (dx=0; dx<side; ++dx)\n                            for (dy=0; dy<side; ++dy)\n                                occupied.emplace(a+dx, b+dy);\n                        result[i] = {a, b, a+side, b+side};\n                        found = true;\n                    }\n                }\n            }\n            if (!found) { // Fallback\n                result[i] = {companies[i].x, companies[i].y, companies[i].x+1, companies[i].y+1};\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    int n; cin >> n;\n    vector<Company> companies(n);\n    for (int i=0; i<n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n        companies[i].id = i;\n    }\n    sort(companies.begin(), companies.end(), cmp);\n\n    auto ans = placeAds(companies);\n    for (auto& [a,b,c,d] : ans)\n        cout << a << ' ' << b << ' ' << c << ' ' << d << '\\n';\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nconst int MAXN = 50;\nvector<vector<int>> tiles(MAXN, vector<int>(MAXN));\nvector<vector<int>> points(MAXN, vector<int>(MAXN));\nvector<pair<int, int>> dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};  // U, D, L, R\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nbool inside(int x, int y) { return x >= 0 && x < MAXN && y >= 0 && y < MAXN; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n    \n    for(int i=0; i<MAXN; ++i) for(int j=0; j<MAXN; ++j) cin >> tiles[i][j];\n    for(int i=0; i<MAXN; ++j) for(int j=0; j<MAXN; ++j) cin >> points[i][j];\n\n    auto solve = [&]() {\n        int best_score = 0;\n        string best_path;\n        vector<vector<bool>> visited(MAXN, vector<bool>(MAXN, false));\n        set<int> used_tiles;\n        visited[si][sj] = true;\n        used_tiles.insert(tiles[si][sj]);\n        string current_path;\n        int current_x = si, current_y = sj;\n        int current_score = points[si][sj];\n\n        auto dfs = [&](auto &&self, int x, int y, int score) -> void {\n            if (score > best_score) {\n                best_score = score;\n                best_path = current_path;\n            }\n            \n            vector<pair<int, int>> possible_moves;\n            for (auto& [dx, dy] : dirs) {\n                int nx = x + dx, ny = y + dy;\n                if (!inside(nx, ny) || visited[nx][ny] || used_tiles.count(tiles[nx][ny])) continue;\n                int nxt_score = score + points[nx][ny];\n                possible_moves.emplace_back(nxt_score, make_pair(nx, ny));\n            }\n\n            if (possible_moves.empty()) return;\n            shuffle(possible_moves.begin(), possible_moves.end(), rng);\n\n            for (auto [_, coord] : possible_moves) {\n                auto [nx, ny] = coord;\n                visited[nx][ny] = true;\n                used_tiles.insert(tiles[nx][ny]);\n                \n                if (nx < x) current_path += 'U';\n                if (nx > x) current_path += 'D';\n                if (ny < y) current_path += 'L';\n                if (ny > y) current_path += 'R';\n                \n                int new_score = score + points[nx][ny];\n                self(self, nx, ny, new_score);\n                \n                if (nx < x) current_path.pop_back();  // Undo\n                if (nx > x) current_path.pop_back();\n                if (ny < y) current_path.pop_back();\n                if (ny > y) current_path.pop_back();\n                \n                visited[nx][ny] = false;\n                used_tiles.erase(tiles[nx][ny]);\n            }\n        };\n\n        dfs(dfs, current_x, current_y, current_score);\n\n        cout << best_path << endl;\n    };\n\n    solve();\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n\nusing namespace std;\n\nint dr[] = { -1, 1, 0, 0 };\nint dc[] = { 0, 0, -1, 1 };\nchar dir[] = { 'U', 'D', 'L', 'R' };\n\nvoid solve() {\n    srand(time(NULL));\n    for (int q = 0; q < 1000; ++q) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        string path;\n        while (si != ti || sj != tj) {\n            if (rand() % 10 < 3) { // Random chance to pick a suboptimal step\n                int d = rand() % 4;\n                int ni = si + dr[d], nj = sj + dc[d];\n                if (ni >= 0 && ni < 30 && nj >= 0 && nj < 30 && path.empty() || ni != path.back()-'U'+si || nj != path.back()-'L'+sj) {\n                    path += dir[d];\n                    si = ni; sj = nj;\n                    continue;\n                }\n            }\n            // Prioritize horizontal moves\n            if (sj < tj && (path.empty() || path.back() != 'L')) {\n                path += 'R';\n                ++sj;\n            } else if (sj > tj && (path.empty() || path.back() != 'R')) {\n                path += 'L';\n                --sj;\n            } else if (si < ti && (path.empty() || path.back() != 'U')) {\n                path += 'D';\n                ++si;\n            } else if (si > ti && (path.empty() || path.back() != 'D')) {\n                path += 'U';\n                --si;\n            } else {\n                // If stuck, move randomly\n                int index = rand() % 4;\n                path += dir[index];\n                si += dr[index];\n                sj += dc[index];\n            }\n        }\n        cout << path << endl;\n        int result;\n        cin >> result;\n    }\n}\n\nint main() {\n    solve();\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nvector<string> solve(int N, int M, vector<string> S) {\n    vector<vector<map<char, int>>> freq(N, vector<map<char, int>>(N));\n    \n    // Calculate frequency of each character at each (i, j)\n    for (auto& s : S) {\n        int len = s.size();\n        for (int p = 0; p < len; ++p) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    freq[(i + p) % N][j][s[p]]++;\n                    freq[i][(j + p) % N][s[p]]++;\n                }\n            }\n        }\n    }\n    \n    // Build initial matrix with most frequent characters\n    vector<string> matrix(N, string(N, '.'));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char best = 'A';\n            int max_freq = 0;\n            for (char c = 'A'; c <= 'H'; ++c) {\n                if (freq[i][j][c] > max_freq) {\n                    max_freq = freq[i][j][c];\n                    best = c;\n                }\n            }\n            matrix[i][j] = best;\n        }\n    }\n    \n    // Shuffle to add randomness\n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(S.begin(), S.end(), gen);\n    sort(S.rbegin(), S.rend(), [](const string& a, const string& b) { return a.size() > b.size(); });\n    \n    auto fits = [&](int x, int y, const string& s, bool vertical = false) {\n        for (size_t p = 0; p < s.size(); ++p) {\n            int i = vertical ? (x + p) % N : x;\n            int j = vertical ? y : (y + p) % N;\n            if (matrix[i][j] != '.' && matrix[i][j] != s[p]) return false;\n        }\n        return true;\n    };\n\n    auto place = [&](int x, int y, const string& s, bool vertical) {\n        for (size_t p = 0; p < s.size(); ++p) {\n            int i = vertical ? (x + p) % N : x;\n            int j = vertical ? y : (y + p) % N;\n            if (matrix[i][j] == '.') matrix[i][j] = s[p];\n        }\n    };\n\n    for (auto& s : S) {\n        bool placed = false;\n        for (int i = 0; i < N && !placed; ++i) {\n            for (int j = 0; j < N && !placed; ++j) {\n                bool vertical = gen() % 2 == 0;\n                if (fits(i, j, s, vertical)) {\n                    place(i, j, s, vertical);\n                    placed = true;\n                } else if (fits(i, j, s, !vertical)) {\n                    place(i, j, s, !vertical);\n                    placed = true;\n                }\n            }\n        }\n    }\n\n    // Fill empty with any valid char\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (matrix[i][j] == '.') {\n                set<char> cand;\n                for (char c = 'A'; c <= 'H'; ++c) {\n                    bool ok_hor = true, ok_ver = true;\n                    for (int k = 0; k < 3; ++k) {\n                        if (matrix[i][(j + k) % N] != '.' && matrix[i][(j + k) % N] != c) ok_hor = false;\n                        if (matrix[(i + k) % N][j] != '.' && matrix[(i + k) % N][j] != c) ok_ver = false;\n                    }\n                    if (ok_hor || ok_ver) cand.insert(c);\n                }\n                matrix[i][j] = (cand.empty() ? 'A' : *cand.begin());\n            }\n        }\n    }\n    \n    return matrix;\n}\n\nint main() {\n    int N = 20, M;\n    cin >> N >> M;\n    vector<string> S(M);\n    for (int i = 0; i < M; ++i) cin >> S[i];\n    \n    vector<string> ans = solve(N, M, S);\n    for (auto& row : ans) cout << row << \"\\n\";\n    return 0;\n}","ahc005":"#include <algorithm>\n#include <random>\n#include <vector>\n#include <cmath>\n#include <iostream>\n#include <tuple>\n\nusing namespace std;\nmt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());\n\nstruct State {\n    int N;\n    vector<string> grid;\n    int si, sj;\n    vector<pair<int, int>> path;\n    long long cost = 0;\n    State(int _N, vector<string> _grid, int _si, int _sj) \n        : N(_N), grid(_grid), si(_si), sj(_sj) {\n        path.push_back({si, sj});\n    }\n\n    void compute_cost() {\n        cost = 0;\n        for (size_t i = 1; i < path.size(); ++i) {\n            int x1 = path[i-1].first, y1 = path[i-1].second;\n            int x2 = path[i].first, y2 = path[i].second;\n            if (x1 == x2) cost += abs(y2 - y1) * (grid[x1][max(y1, y2)] - '0');\n            else cost += abs(x2 - x1) * (grid[max(x1, x2)][y1] - '0');\n        }\n    }\n\n    bool covers_all() {\n        vector<bool> rows(N, false), cols(N, false);\n        for (auto &[x, y] : path) {\n            rows[x] = true;\n            cols[y] = true;\n        }\n        for (int i = 0; i < N; ++i) {\n            if (rows[i] || cols[i]) continue;\n            bool has_road = false;\n            for (int j = 0; j < N; ++j) if (grid[i][j] != '#') has_road = true;\n            if (has_road) return false;\n            for (int j = 0; j < N; ++j) if (grid[j][i] != '#') has_road = true;\n            if (has_road) return false;\n        }\n        return true;\n    }\n\n    void anneal(long long T, int iterations) {\n        uniform_real_distribution<> dist(0.0, 1.0);\n        compute_cost();\n        long long current_cost = cost;\n        auto best_state = *this;\n        long long best_cost = current_cost;\n\n        for (int step = 0; step < iterations; ++step) {\n            double t = T * pow(0.999, step);\n            auto neighbor = *this;\n            int pos = uniform_int_distribution<>(1, path.size()-2)(rng);\n            swap(neighbor.path[pos], neighbor.path[pos+1]);\n            neighbor.compute_cost();\n            \n            if (neighbor.cost < current_cost || dist(rng) < exp((current_cost - neighbor.cost) / t)) {\n                swap(path, neighbor.path);\n                current_cost = neighbor.cost;\n                if (current_cost < best_cost) {\n                    best_cost = current_cost;\n                    best_state = *this;\n                }\n            }\n        }\n        *this = best_state;\n    }\n};\n\nstring solve(int N, int si, int sj, vector<string>& grid) {\n    State state(N, grid, si, sj);\n    vector<int> rows, cols;\n\n    for (int i = 0; i < N; ++i) {\n        bool has_road = false;\n        for (int j = 0; j < N; ++j) if (grid[i][j] != '#') has_road = true;\n        if (has_road) rows.push_back(i);\n    }\n    for (int j = 0; j < N; ++j) {\n        bool has_road = false;\n        for (int i = 0; i < N; ++i) if (grid[i][j] != '#') has_road = true;\n        if (has_road) cols.push_back(j);\n    }\n\n    for (int r : rows) {\n        if (state.path.back().first != r) state.path.emplace_back(r, state.path.back().second);\n        state.path.emplace_back(r, sj);\n    }\n    for (int c : cols) {\n        if (state.path.back().second != c) state.path.emplace_back(state.path.back().first, c);\n    }\n    state.path.push_back({si, sj});\n\n    if (!state.covers_all()) return \"ERROR\";\n    state.anneal(1e13, 1e4);\n\n    string route;\n    int px = si, py = sj;\n    for (auto &[x, y] : state.path) {\n        if (x < px) while (px > x) { route += 'U'; px--; }\n        if (x > px) while (px < x) { route += 'D'; px++; }\n        if (y < py) while (py > y) { route += 'L'; py--; }\n        if (y > py) while (py < y) { route += 'R'; py++; }\n    }\n    return route;\n}\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (auto &row : grid) cin >> row;\n    cout << solve(N, si, sj, grid) << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconstexpr int INF = 1e9;\n\nstruct Task {\n    vector<int> skills;\n    vector<int> children;\n    int done_day = -1;\n    int indeg = 0;\n    bool started = false;\n};\n\nint N = 1000, M = 20;\nvector<Task> tasks;\nvector<vector<int>> finished_tasks; // finished_tasks[member] = list of tasks\nvector<array<int, 1024>> skill_estimates(M, array<int, 1024>{});\n\nvoid print_flush(const vector<pair<int, int>>& assignments) {\n    if (assignments.empty()) {\n        cout << \"0\\n\";\n    } else {\n        cout << assignments.size();\n        for (auto& [a, b] : assignments) cout << ' ' << a+1 << ' ' << b+1;\n        cout << '\\n';\n    }\n    fflush(stdout);\n}\n\nint estimate_time(int member, int task_id) {\n    int sum_excess = 0;\n    for (size_t k = 0; k < tasks[task_id].skills.size(); ++k) {\n        int req = tasks[task_id].skills[k];\n        int est = skill_estimates[member][k];\n        if (req > est) sum_excess += req - est;\n    }\n    return sum_excess == 0 ? 1 : max(1, sum_excess - 3 + (rand() % 7));\n}\n\nvoid update_skills(int member, int task_id, int days) {\n    auto& skills = skill_estimates[member];\n    int excess = max(1, days - 3 + (rand() % 7)) - 1;\n    for (size_t k = 0; k < tasks[task_id].skills.size(); ++k) {\n        int req = tasks[task_id].skills[k];\n        if (req > skills[k]) skills[k] = min(req, skills[k] + excess);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int K, R;\n    cin >> N >> M >> K >> R;\n    tasks.resize(N);\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            int d;\n            cin >> d;\n            tasks[i].skills.push_back(d);\n        }\n    }\n    \n    vector<vector<int>> deps(N);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        deps[u].push_back(v);\n        tasks[v].indeg++;\n    }\n    \n    priority_queue<pair<int, int>> pq; // (completion day estimate, task_id)\n    for (int i = 0; i < N; ++i) if (tasks[i].indeg == 0) pq.emplace(0, i);\n    \n    vector<bool> member_busy(M, false);\n    \n    int day = 1;\n    while (day <= 2000) {\n        vector<pair<int, int>> assignments;\n        for (int m = 0; m < M && !pq.empty(); ++m) {\n            while (!pq.empty() && tasks[pq.top().second].started) pq.pop();\n            if (pq.empty()) break;\n            int t = pq.top().second;\n            pq.pop();\n            \n            assignments.emplace_back(m, t);\n            tasks[t].started = true;\n        }\n        \n        print_flush(assignments);\n        \n        string input;\n        getline(cin >> ws, input);\n        if (input == \"-1\") break;\n        \n        istringstream iss(input);\n        int n;\n        iss >> n;\n        for (int _ = 0; _ < n; ++_) {\n            int m;\n            iss >> m;\n            --m;\n            \n            if (!member_busy[m]) {\n                int task = finished_tasks[m].back();\n                finished_tasks[m].pop_back();\n                tasks[task].done_day = day;\n                \n                int days_taken = day - tasks[task].started_day;\n                update_skills(m, task, days_taken);\n                \n                for (int child : deps[task]) {\n                    --tasks[child].indeg;\n                    if (tasks[child].indeg == 0) {\n                        pq.emplace(-estimate_time(m, child), child);\n                    }\n                }\n            }\n        }\n        \n        for (auto& [m, t] : assignments) {\n            if (!tasks[t].started) finished_tasks[m].push_back(t);\n            member_busy[m] = !tasks[t].started;\n            tasks[t].started_day = day;\n        }\n        \n        day++;\n    }\n    \n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Order {\n    int a, b, c, d;\n};\n\nvector<pair<int,int>> best_path;\nvector<int> chosen;\n\nint dist(int x1, int y1, int x2, int y2) {\n    return abs(x1-x2) + abs(y1-y2);\n}\n\nvector<pair<int, int>> construct_route() {\n    vector<pair<int, int>> path{{400, 400}};\n    for (int i : chosen) {\n        int a = orders[i].a, b = orders[i].b;\n        int c = orders[i].c, d = orders[i].d;\n        \n        int mn_cost = INT_MAX, best_pos = 0;\n        for (int j = 0; j < (int)path.size(); ++j) {\n            vector<pair<int, int>> tmp_path = path;\n            tmp_path.insert(tmp_path.begin() + j + 1, {{a, b}, {c, d}});\n            \n            ll cost = 0;\n            for (int k = 1; k < (int)tmp_path.size(); ++k) {\n                cost += dist(tmp_path[k-1].first, tmp_path[k-1].second, tmp_path[k].first, tmp_path[k].second);\n            }\n            if (cost < mn_cost) {\n                mn_cost = cost;\n                best_pos = j + 1;\n            }\n        }\n        path.insert(path.begin() + best_pos, {{a, b}, {c, d}});\n    }\n    path.push_back({400, 400});\n    return path;\n}\n\nint main() {\n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; ++i) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n    }\n    \n    // Score heuristic: prioritize close orders\n    auto cmp = [&](int lhs, int rhs) {\n        int dist1 = dist(400, 400, orders[lhs].a, orders[lhs].b) \n                  + dist(orders[lhs].c, orders[lhs].d, 400, 400);\n        int dist2 = dist(400, 400, orders[rhs].a, orders[rhs].b)\n                  + dist(orders[rhs].c, orders[rhs].d, 400, 400);\n        return dist1 < dist2;\n    };\n    \n    // Initialize with heuristic\n    vector<int> ids(1000); iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(), cmp);\n    \n    vector<int> current_orders;\n    ll current_cost = 0;\n    priority_queue<pair<ll, int>> pq;\n    \n    for (int i = 0; i < 1000; ++i) {\n        pq.emplace(-dist(400, 400, orders[ids[i]].a, orders[ids[i]].b) \n                     - dist(orders[ids[i]].c, orders[ids[i]].d, 400, 400),\n                   ids[i]);\n    }\n    \n    while (chosen.size() < 50) {\n        auto [cost, id] = pq.top(); pq.pop();\n        chosen.push_back(id);\n        \n        best_path = construct_route();\n        ll total_cost = 0;\n        for (int i = 1; i < (int)best_path.size(); ++i) {\n            total_cost += dist(best_path[i-1].first, best_path[i-1].second,\n                               best_path[i].first, best_path[i].second);\n        }\n        current_cost = total_cost;\n    }\n    \n    cout << chosen.size();\n    for (auto id : chosen) cout << \" \" << id + 1;\n    cout << \"\\n\";\n    cout << best_path.size();\n    for (auto &[x, y] : best_path) cout << \" \" << x << \" \" << y;\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\nusing boost::disjoint_sets;\nusing boost::disjoint_sets_with_storage;\n\nstruct Edge {\n    int u, v, min_len, max_len, len;\n    double e_val;\n    bool operator<(const Edge& r) const {\n        if (max_len != r.max_len) return max_len < r.max_len;\n        return e_val < r.e_val; // Prefer lower expected value on tie\n    }\n};\n\nint main() {\n    const int N = 400, M = 1995;\n    vector<pair<int, int>> coords(N);\n    for (int i = 0; i < N; ++i) scanf(\"%d %d\", &coords[i].first, &coords[i].second);\n    \n    vector<Edge> edges(M);\n    auto calc_dist = [&](int u, int v) -> int {\n        int dx = coords[u].first - coords[v].first;\n        int dy = coords[u].second - coords[v].second;\n        return round(sqrt(dx*dx + dy*dy));\n    };\n    \n    for (int i = 0; i < M; ++i) {\n        scanf(\"%d %d\", &edges[i].u, &edges[i].v);\n        int d = calc_dist(edges[i].u, edges[i].v);\n        edges[i].min_len = d;\n        edges[i].max_len = 3 * d;\n        edges[i].e_val = (edges[i].min_len + edges[i].max_len) / 2.0;\n    }\n    \n    // Sort edges by (max_len ascending, then expected value ascending)\n    sort(edges.begin(), edges.end());\n    \n    vector<int> sorted_indices(M);\n    iota(sorted_indices.begin(), sorted_indices.end(), 0);\n    stable_sort(sorted_indices.begin(), sorted_indices.end(), [&](int i, int j) {\n        if (edges[i].max_len != edges[j].max_len) return edges[i].max_len < edges[j].max_len;\n        return edges[i].e_val < edges[j].e_val;\n    });\n\n    unordered_set<int> known_edges;\n    disjoint_sets<> uf(N);\n    int connected = N;\n    int idx = 0;\n    \n    auto in_order = [&]() mutable -> int {\n        while (idx < M && known_edges.contains(sorted_indices[idx])) ++idx;\n        return idx == M ? -1 : sorted_indices[idx];\n    };\n\n    for (int i = 0; i < M; ++i) {\n        int len;\n        scanf(\"%d\", &len);\n        edges[i].len = len;\n        \n        known_edges.insert(i);\n        int next_potential = in_order();\n        \n        if (next_potential == -1 || (uf.find_set(edges[i].u) != uf.find_set(edges[i].v) && len <= 2.5 * edges[next_potential].min_len)) {\n            // Accept if connects disconnected or within threshold of next candidate\n            if (uf.link(edges[i].u, edges[i].v)) --connected;\n            printf(\"1\\n\");\n            fflush(stdout);\n        } else {\n            printf(\"0\\n\");\n            fflush(stdout);\n        }\n        if (connected == 1) break; // Already connected\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing Point = pair<int, int>;\nconst int MAX_T = 300;\nconst int SIZE = 31;\nint cx[5] = { 0, -1, 1, 0, 0 }, cy[5] = { 0, 0, 0, -1, 1 };\nchar dir[] = \"UDLR\";\n\nstruct State {\n    Point pos;\n    int id;\n};\n\nvector<State> humans;\nvector<Point> pets;\nvector<vector<bool>> grid(SIZE, vector<bool>(SIZE, true));\nint n, m, turn = 0;\n\ninline bool valid(int x, int y) {\n    return x >= 1 && x <= 30 && y >= 1 && y <= 30;\n}\n\nvoid update_barriers(const string& actions) {\n    set<Point> new_blocks;\n    for (int i = 0; i < (int)actions.size(); ++i) {\n        if (actions[i] >= 'u' && actions[i] <= 'r') {\n            int dx = cx[actions[i] - 'u' + 1];\n            int dy = cy[actions[i] - 'u' + 1];\n            int nx = humans[i].pos.first + dx, ny = humans[i].pos.second + dy;\n            if (valid(nx, ny)) && !grid[nx][ny]) {\n                new_blocks.insert({nx, ny});\n            }\n        }\n    }\n    for (auto [x, y] : new_blocks) grid[x][y] = true;\n}\n\nbool has_adjacent_pet(int x, int y) {\n    for (int d = 1; d <= 4; ++d) {\n        int nx = x + cx[d], ny = y + cy[d];\n        if (valid(nx, ny)) && find(pets.begin(), pets.end(), Point(nx, ny)) != pets.end()) {\n            return true;\n        }\n    }\n    return false;\n}\n\nstring decide_actions() {\n    string result(m, '.');\n    map<Point, int> target_counts;\n\n    // Assign targets for fencing\n    for (int i = 0; i < m; ++i) {\n        int best_val = -1, choice = -1;\n        auto [x, y] = humans[i].pos;\n\n        for (int d = 1; d <= 4; ++d) {\n            int nx = x + cx[d], ny = y + cy[d];\n            if (valid(nx, ny) && !grid[nx][ny] && !has_adjacent_pet(nx, ny)) {\n                int adj_cnt = 0;\n                for (int k = 1; k <= 4; ++k) {\n                    if (valid(nx + cx[k], ny + cy[k]) && grid[nx + cx[k]][ny + cy[k]]) {\n                        adj_cnt++;\n                    }\n                }\n                if (adj_cnt > best_val) {\n                    best_val = adj_cnt;\n                    choice = d;\n                }\n            }\n        }\n        if (choice == -1) continue;\n        \n        int dx = cx[choice], dy = cy[choice];\n        result[i] = dir[choice - 1] + 'a' - 'A';\n        grid[x + dx][y + dy] = true;\n        target_counts[{x+dx, y+dy}]++;\n    }\n\n    // If early turns, fill in remaining with moves\n    if (turn < 12) {\n        int row = 1 + (turn / 10) * 5;\n        for (int i = 0; i < m; ++i) {\n            if (result[i] == '.') {\n                int col = 1 + (turn % 10) * 3;\n                while (!valid(row, col) || grid[row][col]) col++;\n                result[i] = (col < humans[i].pos.second ? 'L' : 'R');\n            }\n        }\n    }\n    \n    // Reset after updating (ensures correctness)\n    for (int i = 0; i <= 30; ++i) for (int j = 0; j <= 30; ++j) grid[i][j] = false;\n    return result;\n}\n\nvoid move_humans(const string& actions) {\n    for (int i = 0; i < m; ++i) {\n        if (actions[i] == '.') continue;\n        char move = tolower(actions[i]);\n        int dir_idx = find(begin(dir), end(dir), move) - begin(dir);\n        int x = humans[i].pos.first + cx[dir_idx + 1];\n        int y = humans[i].pos.second + cy[dir_idx + 1];\n        if (valid(x, y) && !grid[x][y]) {\n            humans[i].pos = {x, y};\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    \n    // Read initial pets\n    cin >> n;\n    pets.resize(n);\n    for (auto& p : pets) {\n        int t; cin >> p.first >> p.second >> t;\n    }\n    // Read humans\n    cin >> m;\n    humans.resize(m);\n    for (int i = 0; i < m; ++i) {\n        cin >> humans[i].pos.first >> humans[i].pos.second;\n        humans[i].id = i + 1;\n    }\n\n    while (turn < MAX_T) {\n        string actions = decide_actions();\n        cout << actions << endl;\n        \n        string dummy;\n        for (int i = 0; i < n; ++i) cin >> dummy;\n\n        move_humans(actions);\n        update_barriers(actions);\n        turn++;\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n    \n    vector<string> h(20), v(19);\n    for (int i = 0; i < 20; ++i) cin >> h[i];\n    for (int i = 0; i < 19; ++i) cin >> v[i];\n    \n    auto in_map = [&](int x, int y) {\n        return 0 <= x && x < 20 && 0 <= y && y < 20;\n    };\n    \n    vector movedir = {{-1, 0, 'U'}, {1, 0, 'D'}, {0, -1, 'L'}, {0, 1, 'R'}};\n    auto bfs = [&]() -> string {\n        queue<Pos> q;\n        vector<vector<bool>> used(20, vector<bool>(20, false));\n        vector<vector<char>> prev(20, vector<char>(20));\n        \n        q.push({si, sj});\n        used[si][sj] = true;\n        \n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            if (x == ti && y == tj) break;\n            \n            for (auto& m : movedir) {\n                int nx = x + m[0], ny = y + m[1];\n                if (!in_map(nx, ny)) continue;\n                if (used[nx][ny]) continue;\n                bool blocked = false;\n                if (m[2] == 'R' && h[x][y] == '1') blocked = true;\n                if (m[2] == 'D' && v[x][y] == '1') blocked = true;\n                if (m[2] == 'L' && (y == 0 || h[x][y-1] == '1')) blocked = true;\n                if (m[2] == 'U' && (x == 0 || v[x-1][y] == '1')) blocked = true;\n                if (blocked) continue;\n                \n                used[nx][ny] = true;\n                prev[nx][ny] = m[2];\n                q.push({nx, ny});\n            }\n        }\n        \n        string path;\n        int x = ti, y = tj;\n        while (x != si || y != sj) {\n            char move = prev[x][y];\n            if (move == 'R') { y--; path += 'L'; }\n            if (move == 'D') { x--; path += 'U'; }\n            if (move == 'L') { y++; path += 'R'; }\n            if (move == 'U') { x++; path += 'D'; }\n        }\n        reverse(path.begin(), path.end());\n        return path;\n    };\n    \n    string basic = bfs();\n    if (basic.size() == 0) {\n        cout << string(200, 'D') << endl;\n        return 0;\n    }\n    \n    string result;\n    for (int i = 0; i < 5; ++i) {\n        result += basic;\n    }\n    if (result.size() <= 200) {\n        cout << result << endl;\n    } else {\n        cout << result.substr(0, 200) << endl;\n    }\n}","ahc010":"#include <bits/stdc++.h>\n#include <random>\nusing namespace std;\n\nconst int N = 30;\nint T[N][N], R[N][N], bestR[N][N];\nint dirs[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1},\n};\nint di[4] = {0, -1, 0, 1}, dj[4] = {-1, 0, 1, 0};\n\nmt19937 mt(time(nullptr));\n\nlong long eval(int rotate[N][N]) {\n    int tcopy[N][N];\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        tcopy[i][j] = rotate[i][j];\n        while (tcopy[i][j] < 0) tcopy[i][j] += 8;\n        tcopy[i][j] %= 8;\n    }\n\n    vector<int> lengths;\n    bool vis[N][N][4] = {};\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        for (int d=0; d<4; ++d) {\n            if (vis[i][j][d]) continue;\n            vector<tuple<int, int, int>> path;\n            int ci=i, cj=j, cd=d, len=0;\n            while (true) {\n                path.emplace_back(ci, cj, cd);\n                vis[ci][cj][cd] = true;\n                int nd = dirs[tcopy[ci][cj]][cd];\n                if (nd == -1) break;\n                ci += di[nd];\n                cj += dj[nd];\n                if (ci < 0 || ci >= N || cj < 0 || cj >= N) break;\n                cd = (nd + 2) % 4;\n                if (vis[ci][cj][cd]) {\n                    for (auto [pi, pj, pd] : path) {\n                        if (pi == ci && pj == cj && pd == cd) {\n                            len = path.size() - (path.end() - find(path.begin(), path.end(), make_tuple(pi, pj, pd)));\n                            break;\n                        }\n                    }\n                    break;\n                }\n            }\n            if (len > 0) {\n                lengths.push_back(len);\n                for (auto& [pi, pj, pd] : path) vis[pi][pj][pd] = true;\n            }\n        }\n    }\n    sort(lengths.rbegin(), lengths.rend());\n    long long l1 = (lengths.size() > 0) ? lengths[0] : 0;\n    long long l2 = (lengths.size() > 1) ? lengths[1] : 0;\n    return l1 * l2;\n}\n\nlong long calc() {\n    static int rotate[N][N];\n    memcpy(rotate, R, sizeof(rotate));\n    long long ans = 0;\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        long long best = 0;\n        for (int k=0; k<4; ++k) {\n            rotate[i][j] = (rotate[i][j] + 1) % 8;\n            long long score = eval(rotate);\n            if (score > best) best = score;\n        }\n        rotate[i][j] = (rotate[i][j] - best + 8) % 8;\n        ans += best;\n    }\n    return ans;\n}\n\nint main() {\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        char c; cin >> c;\n        T[i][j] = c - '0';\n    }\n    memcpy(R, T, sizeof(R));\n\n    auto update_ans = [&]() {\n        long long cur_score = eval(bestR);\n        long long score = eval(R);\n        if (score > cur_score) memcpy(bestR, R, sizeof(bestR));\n    };\n\n    const double START_TEMP = 1e6, END_TEMP = 1e-3, RATE = 0.9999;\n    double temp = START_TEMP;\n    long long cur_score = eval(R), best_score = cur_score;\n    while (temp > END_TEMP) {\n        for (int _=0; _<max(1, N*N * temp / START_TEMP); ++_) {\n            int i = mt() % N, j = mt() % N;\n            int prev = R[i][j];\n\n            long long best_rotate = -1;\n            long long best_gain = -1e18;\n            vector<long long> scores(4);\n            for (int delta=0; delta<4; ++delta) {\n                R[i][j] = (prev + delta) % 8;\n                scores[delta] = eval(R);\n                if (scores[delta] - cur_score > best_gain) {\n                    best_gain = scores[delta] - cur_score;\n                    best_rotate = delta;\n                }\n            }\n\n            if (best_rotate == -1 || exp((scores[best_rotate] - cur_score) / temp) < (mt() % 10000)/10000.) {\n                int rnd = mt() % 4;\n                if (scores[rnd] <= cur_score && exp((scores[rnd] - cur_score) / temp) < (mt() % 10000)/10000.) {\n                    R[i][j] = prev;\n                    continue;\n                }\n                best_rotate = rnd;\n            }\n\n            R[i][j] = (prev + best_rotate) % 8;\n            cur_score = scores[best_rotate];\n            update_ans();\n        }\n        best_score = max(best_score, cur_score);\n        temp *= RATE;\n    }\n\n    memcpy(R, bestR, sizeof(R));\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        int diff = 0;\n        while ((bestR[i][j] - T[i][j] - diff) % 8 != 0 && (bestR[i][j] - T[i][j] - diff) % 8 != 4) ++diff;\n        while (diff < 0) diff += 8;\n        cout << diff % 4;\n    }\n    cout << endl;\n}","ahc011":"#include <algorithm>\n#include <deque>\n#include <iostream>\n#include <numeric>\n#include <queue>\n#include <vector>\nusing namespace std;\nusing ll = long long;\n\n#define rep(i, n) for (int i = 0; i < n; i++)\n\nint n, e_x, e_y;\nvector<vector<int>> a;\n\nbool in_grid(int x, int y) { return 0 <= x && x < n && 0 <= y && y < n; }\n\nbool valid(int x, int y) { return in_grid(x, y) && a[x][y] != 0; }\n\nint cnt_connect(int x, int y) {\n  int c = (x == e_x && y == e_y);\n  if (valid(x + 1, y)) c++;\n  if (valid(x, y - 1)) c++;\n  if (valid(x, y + 1)) c++;\n  if (valid(x - 1, y)) c++;\n  return c - 1;\n}\n\npair<int, int> find_target() {\n  rep(i, n) rep(j, n) if (a[i][j] == 0) return {i, j};\n  return {-1, -1};\n}\n\npair<int, pair<int, int>> find_tile() {\n  int mx = -1;\n  pair<int, pair<int, int>> res;\n  rep(x, n) rep(y, n) {\n    if (!valid(x, y)) continue;\n    int nc = __builtin_popcount(a[x][y]);\n    int cc = cnt_connect(x, y);\n    if (nc - 1 <= cc) continue;\n    int score = nc - cc;\n    if (score > mx || (score == mx && rand() % 2 == 0)) {\n      mx = score;\n      res = {a[x][y], {x, y}};\n    }\n  }\n  return res;\n}\n\nstring generate_path(int sx, int sy, int tx, int ty) {\n  deque<pair<int, int>> qb, qe;\n  vector<vector<int>> db(n, vector<int>(n, -1)), de(n, vector<int>(n, -1));\n  qb.push_back({sx, sy});\n  qe.push_back({tx, ty});\n  db[sx][sy] = 0;\n  de[tx][ty] = 0;\n  while (!qb.empty() || !qe.empty()) {\n    auto bfs = [&](deque<pair<int, int>> &q, vector<vector<int>> &d, deque<pair<int, int>> &oq, vector<vector<int>> &od) {\n      pair<int, int> cur = q.front();\n      q.pop_front();\n      int x = cur.first, y = cur.second;\n      if (od[x][y] != -1) {\n        string pathb, pathe;\n        while (cur.first != sx || cur.second != sy) {\n          pathb += (cur.first == x + 1 && cur.second == y) ? 'U'\n                   : (cur.first == x - 1 && cur.second == y) ? 'D'\n                   : (cur.first == x && cur.second == y + 1) ? 'L'\n                                                               : 'R';\n          cur = {db[cur.first][cur.second] / n, db[cur.first][cur.second] % n};\n        }\n        while (cur.first != tx || cur.second != ty) {\n          pathe += (od[cur.first][cur.second] == x + 1 && od[cur.first][cur.second] / n == y) ? 'D'\n               : (od[cur.first][cur.second] == x - 1 && od[cur.first][cur.second] / n == y) ? 'U'\n               : (od[cur.first][cur.second] == x && od[cur.first][cur.second] / n == y + 1) ? 'R'\n                                                                                              : 'L';\n          cur = {od[cur.first][cur.second], od[cur.first][cur.second] / n};\n        }\n        reverse(pathb.begin(), pathb.end());\n        string ans = pathb + pathe;\n        while (ans.size() > 1 && (ans.back() == 'U' && ans[ans.size() - 2] == 'D' || ans.back() == 'D' && ans[ans.size() - 2] == 'U' ||\n                                   ans.back() == 'L' && ans[ans.size() - 2] == 'R' || ans.back() == 'R' && ans[ans.size() - 2] == 'L')) {\n          ans.pop_back();\n          ans.pop_back();\n        }\n        return ans;\n      }\n      static const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};\n      rep(i, 4) {\n        int nx = x + dx[i], ny = y + dy[i];\n        if (in_grid(nx, ny) && d[nx][ny] == -1 && a[nx][ny] != 0) {\n          d[nx][ny] = d[x][y] * n + ny;\n          q.push_back({nx, ny});\n        }\n      }\n      return \"\";\n    };\n    if (!qb.empty()) {\n      auto res = bfs(qb, db, qe, de);\n      if (!res.empty()) return res;\n    }\n    if (!qe.empty()) {\n      auto res = bfs(qe, de, qb, db);\n      if (!res.empty()) return res;\n    }\n  }\n  return \"\";\n}\n\nint main() {\n  cin >> n;\n  int T;\n  cin >> T;\n  a.resize(n, vector<int>(n));\n  rep(i, n) rep(j, n) {\n    char c;\n    cin >> c;\n    if (c >= 'a') a[i][j] = c - 'a' + 10;\n    else a[i][j] = c - '0';\n  }\n  string ans;\n  auto [ex, ey] = find_target();\n  while (true) {\n    auto [val, pos] = find_tile();\n    if (val == -1) break;\n    auto [x, y] = pos;\n    if (cnt_connect(x, y) == __builtin_popcount(val) - 1) continue;\n    int tx = ex, ty = ey;\n    ex = x;\n    ey = y;\n    a[tx][ty] = val;\n    a[x][y] = 0;\n    ans += generate_path(tx, ty, x, y);\n  }\n  cout << ans << endl;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    // Predefined set of lines combining vertical, horizontal & some diagonals\n    vector<array<int, 4>> lines = {\n        {-20000, 20000, -20000, -20000},   // Horizontal lines\n        {-20000, 15000, -20000, 15000},\n        {-20000, 10000, -20000, 10000},\n        {-20000, 5000, -20000, 5000},\n        {-20000, 0, -20000, 0},\n        {-20000, -5000, -20000, -5000},\n        {-20000, -10000, -20000, -10000},\n        {-20000, -15000, -20000, -15000},\n        {20000, -20000, 20000, 20000},     // Vertical lines\n        {15000, -20000, 15000, 20000},\n        {10000, -20000, 10000, 20000},\n        {5000, -20000, 5000, 20000},\n        {0, -20000, 0, 20000},\n        {-5000, -20000, -5000, 20000},\n        {-10000, -20000, -10000, 20000},\n        {-15000, -20000, -15000, 20000},\n        {-5000, -20000, 15000, 20000},     // Diagonal 1\n        {-10000, -10000, 10000, 10000},    // Diagonal 2\n        {-15000, 0, 15000, 0},             // Diagonal 3\n        {-5000, 20000, 15000, -20000}      // Another diagonal for better splitting\n    };\n\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line[0] << \" \" << line[1] << \" \" << line[2] << \" \" << line[3] << endl;\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nvector<vector<bool>> visited;\nvector<tuple<int, int, int, int, int, int>> ans;\nint N, M;\n\nbool validate(int x1, int y1, int x2, int y2, int x3, int y3) {\n    if (!(0 <= min({x1, x2, x3}) && max({x1, x2, x3}) < N)) return false;\n    if (!(0 <= min({y1, y2, y3}) && max({y1, y2, y3}) < N)) return false;\n    if (x1 == x2 || x2 == x3 || x3 == x1 || y1 == y2 || y2 == y3 || y3 == y1)\n        return false;\n    return true;\n}\n\nint main() {\n    cin >> N >> M;\n    visited.assign(N, vector<bool>(N, false));\n    queue<pair<int, int>> q;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        visited[x][y] = true;\n        q.emplace(x, y);\n    }\n\n    int total_dots = M;\n    while (!q.empty() && (double)total_dots / N / N < 0.08) { // Adjust target fill\n        auto [x, y] = q.front(); q.pop();\n        // Search in a limited radius to balance coverage and time\n        for (int dx = -5; dx <= 5; ++dx) for (int dy = -5; dy <= 5; ++dy) {\n            if (abs(dx) + abs(dy) > 9) continue; // Stay within bounded steps\n            int nx = x + dx, ny = y + dy;\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N || visited[nx][ny]) continue;\n            for (int d = 1; d <= 5; ++d) {\n                if (validate(nx, ny, x, y, x, y+d, x+d, y)) {\n                    if (!visited[x][y+d] || !visited[x+d][y]) break;\n                    visited[nx][ny] = true;\n                    ans.emplace(nx, ny, x, y, x, y+d, x+d, y);\n                    q.emplace(nx, ny);\n                    total_dots++;\n                    goto next_point;\n                }\n                if (validate(nx, ny, x, y, x, y-d, x-d, y)) {\n                    if (!visited[x][y-d] || !visited[x-d][y]) break;\n                    visited[nx][ny] = true;\n                    ans.emplace(nx, ny, x, y, x, y-d, x-d, y);\n                    q.emplace(nx, ny);\n                    total_dots++;\n                    goto next_point;\n                }\n            }\n        }\n    next_point:;\n    }\n\n    cout << ans.size() << endl;\n    for (auto &[x1, y1, x2, y2, x3, y3] : ans)\n        cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << ' '\n             << x3 << ' ' << y3 << ' ' << (x3+y2-x2) << ' ' << (x2+y3-x3) << endl;\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Position {\n    int x, y;\n    Position(int _x, int _y) : x(_x), y(_y) {}\n};\n\nconst int SIZE = 10;\nvector<vector<int>> grid(SIZE, vector<int>(SIZE, 0));\nvector<Position> emptyPositions;\nvector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nstring dirChars = \"FBLR\";\nunordered_map<int, char> dirMap = {{0, 'F'}, {1, 'B'}, {2, 'L'}, {3, 'R'}};\n\nvoid applyTilt(char dir) {\n    vector<vector<int>> temp = grid;\n    if (dir == 'F') { // Down\n        for (int j = 0; j < SIZE; ++j) {\n            int lastrow = SIZE - 1;\n            for (int i = SIZE - 1; i >= 0; --i) {\n                if (grid[i][j]) {\n                    temp[lastrow][j] = grid[i][j];\n                    if (i != lastrow) temp[i][j] = 0;\n                    --lastrow;\n                }\n            }\n        }\n    } else if (dir == 'B') { // Up\n        for (int j = 0; j < SIZE; ++j) {\n            int lastrow = 0;\n            for (int i = 0; i < SIZE; ++i) {\n                if (grid[i][j]) {\n                    temp[lastrow][j] = grid[i][j];\n                    if (i != lastrow) temp[i][j] = 0;\n                    ++lastrow;\n                }\n            }\n        }\n    } else if (dir == 'L') { // Left\n        for (int i = 0; i < SIZE; ++i) {\n            int lastcol = 0;\n            for (int j = 0; j < SIZE; ++j) {\n                if (grid[i][j]) {\n                    temp[i][lastcol] = grid[i][j];\n                    if (j != lastcol) temp[i][j] = 0;\n                    ++lastcol;\n                }\n            }\n        }\n    } else if (dir == 'R') { // Right\n        for (int i = 0; i < SIZE; ++i) {\n            int lastcol = SIZE - 1;\n            for (int j = SIZE - 1; j >= 0; --j) {\n                if (grid[i][j]) {\n                    temp[i][lastcol] = grid[i][j];\n                    if (j != lastcol) temp[i][j] = 0;\n                    --lastcol;\n                }\n            }\n        }\n    }\n    grid = temp;\n}\n\nvoid updateEmptyPos() {\n    emptyPositions.clear();\n    for (int i = 0; i < SIZE; ++i)\n        for (int j = 0; j < SIZE; ++j)\n            if (!grid[i][j]) emptyPositions.emplace_back(i, j);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<int> flavors(100);\n    for (auto& f : flavors) cin >> f;\n\n    int step = 1;\n    for (int t = 1; t <= 100; ++t) {\n        int pt;\n        cin >> pt;\n        --pt;\n        Position pos = emptyPositions[pt];\n        grid[pos.x][pos.y] = flavors[t-1];\n        updateEmptyPos();\n\n        if (t == 100) break;\n\n        // Simple heuristic: alternate directions based on steps and grid state\n        char dir = (t % 2 == 0) ? 'L' : 'R';\n        if (t >= 60) dir = (step++ % 2 == 0) ? 'F' : 'B';\n        cout << dir << endl;\n        cout.flush();\n        applyTilt(dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\n\n// Generate a graph string with specific connections forming small cycles\nstring generate_graph(int N, int edges) {\n    vector<bool> used(N, false);\n    vector<int> perm(N); iota(perm.begin(), perm.end(), 0);\n    shuffle(perm.begin(), perm.end(), mt19937{random_device{}()});\n    \n    string graph(N*(N-1)/2, '0');\n    atcoder::dsu dsu(N);\n    \n    for (int i = 1; i < edges; ++i) {\n        int u = (perm[i] - 1 + N) % N;\n        int v = (perm[i-1] + 1) % N;\n        if (u < v) swap(u, v);\n        int idx = u*(u-1)/2 + v;\n        if (graph[idx] == '0') {\n            graph[idx] = '1';\n            dsu.merge(u, v);\n        }\n    }\n    \n    // Complete cycles by connecting edges between groups\n    vector<vector<int>> groups = dsu.groups();\n    int extra = edges - (groups.size() - 1);\n    \n    for (int g = 1; g < groups.size() && extra > 0; ++g) {\n        for (int u : groups[g]) {\n            for (int v : groups[g-1]) {\n                if (extra == 0) break;\n                int a = min(u, v), b = max(u, v);\n                int idx = a*(a-1)/2 + b;\n                if (graph[idx] == '0') {\n                    graph[idx] = '1';\n                    --extra;\n                }\n            }\n        }\n    }\n    \n    return graph;\n}\n\nint main() {\n    int M;\n    double eps;\n    cin >> M >> eps;\n    \n    const int N = 20; // Use 20 vertices for manageable complexity\n    cout << N << endl;\n    \n    vector<string> graphs(M);\n    for (int k = 0; k < M; ++k) {\n        graphs[k] = generate_graph(N, k + 5); // Varying edges starting from 5\n        cout << graphs[k] << endl;\n    }\n    cout << flush;\n    \n    vector<int> edge_count(M);\n    for (int k = 0; k < M; ++k) {\n        edge_count[k] = count(graphs[k].begin(), graphs[k].end(), '1');\n    }\n    \n    for (int q = 0; q < 100; ++q) {\n        string H; cin >> H;\n        int edges = count(H.begin(), H.end(), '1');\n        \n        // Find closest match using edge count and edge flip allowance\n        int min_diff = INT_MAX;\n        int best = 0;\n        for (int k = 0; k < M; ++k) {\n            int diff = abs(edges - edge_count[k]);\n            if (diff < min_diff || (diff == min_diff && k < best)) {\n                min_diff = diff;\n                best = k;\n            }\n        }\n        cout << best << endl;\n        cout << flush;\n    }\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing i32 = int;\nusing i64 = long long;\nusing vi = vector<i32>;\nusing pii = pair<i32, i32>;\nusing Graph = vector<vector<pii>>;\nconstexpr i64 INF = 1e18;\n\nvector<vector<i64>> dijkstra(int start, const Graph& adj, int N) {\n    priority_queue<pii, vector<pii>, greater<pii>> pq;\n    vector<i64> dist(N, INF);\n    vector<i64> cnt(N, 0);\n    dist[start] = 0;\n    pq.emplace(0, start);\n    cnt[start] = 1;\n\n    while (!pq.empty()) {\n        auto [current_dist, u] = pq.top();\n        pq.pop();\n        if (current_dist != dist[u]) continue;\n\n        for (const auto& [v, w] : adj[u]) {\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                cnt[v] = cnt[u];\n                pq.emplace(dist[v], v);\n            } else if (dist[u] + w == dist[v]) {\n                cnt[v] += cnt[u];\n            }\n        }\n    }\n    return {dist, cnt};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    i32 N, M, D, K;\n    cin >> N >> M >> D >> K;\n    \n    Graph adj(N);\n    vector<tuple<i32, i32, i32>> edges;\n    \n    for (i32 i = 0; i < M; ++i) {\n        i32 u, v, w;\n        cin >> u >> v >> w;\n        --u, --v;\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n        edges.emplace_back(u, v, w);\n    }\n    \n    for (i32 i = 0; i < N; ++i) {\n        i32 x, y;\n        cin >> x >> y;\n    }\n\n    vector<pair<i64, i32>> edge_importance(M, {0, 0});\n    for (i32 i = 0; i < N; ++i) {\n        auto [dist, cnt] = dijkstra(i, adj, N);\n        for (i32 j = 0; j < M; ++j) {\n            auto& [u, v, w] = edges[j];\n            if (dist[u] + w == dist[v]) {\n                i64 imp = (i64)cnt[u] * (N - cnt[v]);\n                edge_importance[j] = {edge_importance[j].first + imp, j};\n            }\n            if (dist[v] + w == dist[u]) {\n                i64 imp = (i64)cnt[v] * (N - cnt[u]);\n                edge_importance[j] = {edge_importance[j].first + imp, j};\n            }\n        }\n    }\n    \n    sort(edge_importance.begin(), edge_importance.end(), greater<>());\n\n    vector<i32> schedule(M);\n    unordered_set<i32> day_edges[D];\n    i32 current_day = 0;\n    for (const auto& [imp, idx] : edge_importance) {\n        while (current_day < D && (i32)day_edges[current_day].size() >= K) ++current_day;\n        if (current_day >= D) current_day = 0;\n        schedule[idx] = current_day + 1;\n        day_edges[current_day].insert(idx);\n    }\n    \n    for (i32 sched : schedule) {\n        cout << sched << \" \";\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n    bool operator<(const Point& o) const {\n        return tie(x, y, z) < tie(o.x, o.y, o.z);\n    }\n};\n\nvector<vector<string>> input;  // Store each 2D silhouette\nvector<vector<vector<int>>> dp; // Precompute front and right silhouettes\nvector<vector<vector<int>>> blocks;\n\nvector<vector<vector<int>>> construct(int idx) {\n    auto& sil = input[idx*2];\n    auto& sir = input[idx*2 + 1];\n    int n = sil.size();\n    vector<vector<vector<int>>> cube(n, vector<vector<int>>(n, vector<int>(n)));\n    vector<vector<int>> vis(n, vector<int>(n, 0));\n    int cnt = 1;\n    \n    auto addBlock = [&](int x, int y, int z) {\n        cube[x][y][z] = cnt;\n    };\n    \n    // Process intersections to use same blocks for both configurations\n    for (int z = 0; z < n; z++) {\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (dp[idx][x][z] && dp[idx + 2][y][z] && !vis[x][y] && !blocks[x][y][z]) {\n                    blocks[x][y][z] = cnt;\n                    addBlock(x, y, z);\n                    vis[x][y]++;\n                }\n            }\n        }\n    }\n    \n    // Fill remaining regions needed by the first silhouette\n    for (int z = 0; z < n; z++) {\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (dp[idx][x][z] && !blocks[x][y][z]) {\n                    addBlock(x, y, z);\n                    blocks[x][y][z] = cnt++;\n                }\n            }\n        }\n    }\n    return cube;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D;\n    cin >> D;\n    input.resize(4);\n    \n    for (int t = 0; t < 4; t++) {\n        for (int i = 0; i < D; i++) {\n            string s;\n            cin >> s;\n            input[t].push_back(s);\n        }\n    }\n    \n    // Precompute front and right silhouettes\n    dp.assign(4, vector<vector<int>>(D, vector<int>(D)));\n    for (int t = 0; t < 4; t += 2) {\n        for (int z = 0; z < D; z++) {\n            for (int x = 0; x < D; x++) {\n                for (int y = 0; y < D; y++) {\n                    if (input[t][z][x] == '1') dp[t][x][z]++;\n                    if (input[t+1][z][y] == '1') dp[t+2][y][z]++;\n                }\n            }\n        }\n    }\n    \n    blocks.resize(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    auto cube1 = construct(0);\n    blocks.assign(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    auto cube2 = construct(1);\n    \n    // Count blocks used\n    int max_block = 0;\n    for (const auto& c1 : cube1) for (const auto& row : c1) \n        for (int block : row) max_block = max(max_block, block);\n    for (const auto& c2 : cube2) for (const auto& row : c2) \n        for (int block : row) max_block = max(max_block, block);\n    \n    cout << max_block << '\\n';\n    \n    // Output cubes\n    for (auto& c : cube1) {\n        for (auto& r : c) \n            for (int val : r) cout << val << \" \";\n        cout << \"\\n\";\n    }\n    for (auto& c : cube2) {\n        for (auto& r : c) \n            for (int val : r) cout << val << \" \";\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\n#include <boost/geometry.hpp>\nusing namespace std;\nusing namespace boost::geometry;\ntypedef model::d2::point_xy<int> Point;\n\nauto rng = mt19937(chrono::steady_clock::now().time_since_epoch().count());\n\nlong long distSquared(const Point &a, const Point &b) {\n    return (long long)(a.x() - b.x()) * (a.x() - b.x()) +\n           (long long)(a.y() - b.y()) * (a.y() - b.y());\n}\n\nstruct Edge {\n    int u, v, w;\n    bool operator<(const Edge &o) const { return w < o.w; }\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<Point> stations(N);\n    stations[0] = Point(0, 0);\n    for (int i = 1; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        stations[i] = Point(x, y);\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v >> edges[i].w;\n        edges[i].u--, edges[i].v--;\n    }\n\n    vector<Point> residents(K);\n    for (int i = 0; i < K; ++i) {\n        int a, b;\n        cin >> a >> b;\n        residents[i] = Point(a, b);\n    }\n\n    // Prim's MST\n    vector<bool> inMST(N, false);\n    inMST[0] = true;\n    priority_queue<Edge> pq;\n    for (Edge e : edges) {\n        if (e.u == 0 || e.v == 0) pq.push(e);\n    }\n\n    vector<bool> edgeUsed(M, false);\n    while (!pq.empty()) {\n        auto [u, v, w] = pq.top();\n        pq.pop();\n        if (inMST[u] && inMST[v]) continue;\n\n        int nxt = inMST[u] ? v : u;\n        inMST[nxt] = true;\n\n        if (u < v) edgeUsed[v - 1] = true;\n        else edgeUsed[u - 1] = true;\n\n        for (Edge e : edges) {\n            if ((e.u == nxt || e.v == nxt) && !inMST[e.u] && !inMST[e.v]) {\n                pq.push(e);\n            }\n        }\n    }\n\n    vector<int> radius(N, 0);\n    for (auto res : residents) {\n        int min_idx = 0;\n        long long min_dist = distSquared(res, stations[0]);\n        for (int i = 1; i < N; ++i) {\n            if (!inMST[i]) continue;\n            long long cur = distSquared(res, stations[i]);\n            if (cur < min_dist) {\n                min_dist = cur;\n                min_idx = i;\n            }\n        }\n        radius[min_idx] = max(radius[min_idx], \n            static_cast<int>(ceil(sqrt(min_dist))));\n    }\n\n    // Output results\n    for (int r : radius) cout << r << \" \";\n    cout << endl;\n    for (bool e : edgeUsed) cout << e << \" \";\n    cout << endl;\n\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Ball {\n    int x, y, v;\n    bool operator<(const Ball& o) const {\n        return v < o.v;\n    }\n};\n\nint N = 30;\nvector<vector<int>> v(N, vector<int>(N));\nvector<tuple<int, int, int, int>> operations;\nint eval() {\n    int cnt = 0;\n    for (int x = 0; x < N - 1; x++) {\n        for (int y = 0; y <= x; y++) {\n            if (v[x][y] > v[x+1][y]) cnt++;\n            if (v[x][y] > v[x+1][y+1]) cnt++;\n        }\n    }\n    return cnt;\n}\n\nvoid do_swap(int x1, int y1, int x2, int y2) {\n    swap(v[x1][y1], v[x2][y2]);\n    operations.emplace_back(x1, y1, x2, y2);\n}\n\nvector<pair<int, int>> dirs = {{-1,-1}, {-1,0}, {0,-1}, {0,1}, {1,0}, {1,1}};\nbool valid(int x, int y) {\n    return x >= 0 && y >= 0 && x < N && y <= x;\n}\n\nvoid solve() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j <= i; j++) {\n            cin >> v[i][j];\n        }\n    }\n    int iters = 3000;\n    \n    while (iters-- > 0) {\n        bool updated = false;\n        vector<vector<int>> original = v;\n        // Try to place v[x][y] in the right place by swapping\n        for (int x = 0; x < N - 1; x++) {\n            for (int y = 0; y <= x; y++) {\n                int best_gain = 0;\n                int dx = 1, dy = (rand() % 2 == 0) ? 0 : 1; // choose left or right child\n                if (!valid(x + dx, y + dy)) continue;\n                int current_eval = eval();\n                if (v[x][y] > v[x+dx][y+dy]) {\n                    do_swap(x, y, x+dx, y+dy);\n                    int new_eval = eval();\n                    if (new_eval < current_eval) {\n                        updated = true;\n                    } else {\n                        v = original;\n                        operations.pop_back();\n                    }\n                }\n            }\n        }\n        if (!updated) break; // Stop if no more improvements\n    }\n    cout << operations.size() << endl;\n    for (auto& [x1, y1, x2, y2] : operations) {\n        cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << endl;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int D = 9;\nint N;\nvector<vector<bool>> is_obstacle(D, vector<bool>(D, false));\n\n// Spiral path initialization\nvector<pair<int, int>> spiral_order;\n\nvoid initialize_spiral() {\n    int top = 0, bottom = D-1, left = 0, right = D-1;\n    int dir = 0; // 0: right, 1: down, 2: left, 3: up\n    while (top <= bottom && left <= right) {\n        if (dir == 0) {\n            for (int j = left; j <= right; ++j) spiral_order.emplace_back(top, j);\n            top++;\n        } else if (dir == 1) {\n            for (int i = top; i <= bottom; ++i) spiral_order.emplace_back(i, right);\n            right--;\n        } else if (dir == 2) {\n            for (int j = right; j >= left; --j) spiral_order.emplace_back(bottom, j);\n            bottom--;\n        } else if (dir == 3) {\n            for (int i = bottom; i >= top; --i) spiral_order.emplace_back(i, left);\n            left++;\n        }\n        dir = (dir + 1) % 4;\n    }\n    // Filter out entrance and invalid positions\n    spiral_order.erase(remove_if(spiral_order.begin(), spiral_order.end(), \n        [](auto& pos) {\n            return (pos.first == 0 && pos.second == (D-1)/2) || is_obstacle[pos.first][pos.second];\n        }), \n        spiral_order.end());\n    reverse(spiral_order.begin(), spiral_order.end());\n}\n\nbool in_bounds(int x, int y) {\n    return x >= 0 && x < D && y >= 0 && y < D;\n}\n\nstruct StorageEntry {\n    int val;\n    int x, y;\n};\n\nvector<vector<int>> grid(D, vector<int>(D, -1));\nvector<StorageEntry> stored;\n\npair<int, int> bfs_nearest(int target) {\n    queue<pair<int, int>> q;\n    q.emplace((0, (D-1)/2));\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    visited[0][(D-1)/2] = true;\n    \n    while (!q.empty()) {\n        auto [cx, cy] = q.front(); q.pop();\n        for (auto [dx, dy] : vector<pair<int, int>>{{-1,0},{1,0},{0,-1},{0,1}}) {\n            int nx = cx + dx, ny = cy + dy;\n            if (in_bounds(nx, ny) && !visited[nx][ny] && !is_obstacle[nx][ny] && grid[nx][ny] != -1) {\n                if (grid[nx][ny] == target) {\n                    grid[nx][ny] = -1; // mark as used\n                    return {nx, ny};\n                }\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return {-1, -1};\n}\n\nint main() {\n    cin >> N;\n    int n = D*D - 1 - N;\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        is_obstacle[x][y] = true;\n    }\n\n    initialize_spiral();\n    int cur_pos = 0;\n    unordered_map<int, pair<int, int>> container_map;\n\n    for (int d = 0; d < n; ++d) {\n        int t;\n        cin >> t;\n        stored.push_back({t, spiral_order[cur_pos].first, spiral_order[cur_pos].second});\n        container_map[t] = spiral_order[cur_pos];\n        grid[spiral_order[cur_pos].first][spiral_order[cur_pos].second] = t;\n        cur_pos++;\n        cout << spiral_order[cur_pos - 1].first << \" \" << spiral_order[cur_pos - 1].second << endl;\n    }\n\n    sort(stored.begin(), stored.end(), [](const auto& a, const auto& b) { return a.val < b.val; });\n\n    for (const auto& entry : stored) {\n        auto [x, y] = bfs_nearest(entry.val);\n        cout << x << \" \" << y << endl;\n    }\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 51;\nint grid[N][N];\nint ans[N][N];\nint n, m;\n\nint dx[4] = {-1, 0, 1, 0};\nint dy[4] = {0, 1, 0, -1};\n\nvoid bfs_zero() {\n    deque<pair<int, int>> q;\n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    for (int i=0; i<n; ++i) {\n        if (ans[i][0] == 0 && !vis[i][0]) {\n            q.push_back({i, 0});\n            vis[i][0] = true;\n        }\n        if (ans[i][n-1] == 0 && !vis[i][n-1]) {\n            q.push_back({i, n-1});\n            vis[i][n-1] = true;\n        }\n    }\n    for (int j=0; j<n; ++j) {\n        if (ans[0][j] == 0 && !vis[0][j]) {\n            q.push_back({0, j});\n            vis[0][j] = true;\n        }\n        if (ans[n-1][j] == 0 && !vis[n-1][j]) {\n            q.push_back({n-1, j});\n            vis[n-1][j] = true;\n        }\n    }\n\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop_front();\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 || vis[nx][ny] || ans[nx][ny] != 0) continue;\n            ans[nx][ny] = 0;\n            vis[nx][ny] = true;\n            q.push_back({nx, ny});\n        }\n    }\n}\n\nint main() {\n    cin >> n >> m;\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            cin >> grid[i][j];\n            ans[i][j] = grid[i][j];\n        }\n    }\n    \n    vector<pair<int, int>> reps(m+1);\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            int c = grid[i][j];\n            if (reps[c] == pair<int, int>{}) {\n                reps[c] = {i, j};\n            }\n        }\n    }\n\n    memset(ans, -1, sizeof(ans));\n    for (int i=1; i<=m; ++i) {\n        if (reps[i] != pair<int, int>{}) {\n            auto [x, y] = reps[i];\n            ans[x][y] = i;\n            // Connect to border if it's adjacent originally\n            if (x == 0 || x == n-1 || y == 0 || y == n-1) {\n                ans[x][y] = 0; // Treat edge as zero\n            }\n        }\n    }\n\n    // Handle adjacencies for initial fill\n    for (int i=1; i<=m; ++i) {\n        if (reps[i].first != -1) {\n            auto [x, y] = reps[i];\n            bool adj_zero = false;\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) {\n                    adj_zero = true;\n                    break;\n                }\n                if (grid[nx][ny] == 0) adj_zero = true;\n            }\n            if (adj_zero) ans[x][y] = 0;\n        }\n    }\n\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (ans[i][j] == -1) ans[i][j] = 0;\n        }\n    }\n    \n    bfs_zero(); // Expand zeros properly\n    \n    // Connect remaining color cells to components\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (ans[i][j] > 0) continue;\n            for (int d=0; d<4; ++d) {\n                int nx = i + dx[d], ny = j + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n || ans[nx][ny] <= 0) continue;\n                ans[i][j] = ans[nx][ny];\n                break;\n            }\n        }\n    }\n\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (j > 0) cout << ' ';\n            cout << ans[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Vec = vector<int>;\nusing Mat = vector<Vec>;\nusing Graph = vector<Vec>;\nconstexpr ll INF = 1LL<<60;\nmt19937 mt(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct Partition {\n    int N, D, Q;\n    Vec A; // Answer partitions\n    Mat W; // Constraints: W[u][v] > 0 means u > v\n    vector<double> weight; // Virtual item weights\n\n    void init(int n, int d, int q) {\n        N = n; D = d; Q = q;\n        A = Vec(N, -1);\n        W.assign(N, Vec(N));\n        weight.resize(N, 1.0);\n    }\n\n    // Assign a random group with the smallest current sum\n    int assign(const Vec& cnt) {\n        priority_queue<pair<double, int>, vector<pair<double, int>>, greater<>> pq;\n        for (int i=0; i<D; ++i) pq.emplace(cnt[i] * weight[i], i);\n        \n        // Prefer groups with space but allow overfill near the end\n        int best = -1, minOver = N+1;\n        for (auto [w, idx] : pq) {\n            int total = cnt[idx] + 1;\n            if (total > N/D && minOver <= N/D) continue;\n            if (best == -1 || (total <= N/D && cnt[idx] < cnt[best])) {\n                best = idx;\n                if (total > N/D) minOver = total;\n            }\n        }\n        return best;\n    }\n\n    Vec solve() {\n        // Initial comparison phase\n        int q = 0;\n        for (int i=0; i<N-1 && q < Q; ++i) {\n            cout << 1 << ' ' << 1 << ' ' << i << ' ' << (i+1) << endl;\n            char res; cin >> res;\n            if (res == '>') W[i][i+1] = 1;\n            else if (res == '<') W[i+1][i] = 1;\n            ++q;\n        }\n\n        // Update virtual weights based on constraints\n        for (int k=0; k<N; ++k)\n            for (int i=0; i<N; ++i)\n                for (int j=0; j<N; ++j)\n                    if (W[i][k] && W[k][j]) W[i][j] = 1;\n\n        Vec cnt(D, 0);\n        for (int i=0; i<N; ++i) {\n            if (q >= Q) break;\n            int group = assign(cnt);\n            if (group == -1) {\n                group = mt() % D; // Random if stuck\n                if (cnt[group] >= N/D) continue; // Avoid overfill\n            }\n            A[i] = group;\n            cnt[group]++;\n        }\n\n        // Fill remaining unassigned items (if any)\n        int group = 0;\n        for (int i=0; i<N; ++i) {\n            if (A[i] == -1) {\n                while (cnt[group] >= N/D) group++;\n                A[i] = group;\n                cnt[group]++;\n            }\n        }\n\n        // Output final partition\n        for (int x: A) cout << x << ' ';\n        cout << endl;\n        return A;\n    }\n};\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n    Partition solver;\n    solver.init(N, D, Q);\n    solver.solve();\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nvoid find_box(const multi_array<int, 2>& stacks, int target, int& sidx, int& pos) {\n    for (int i=0; i<stacks.shape()[0]; ++i) {\n        for (int j=stacks.shape()[1]-1; j>=0; --j) {\n            if (stacks[i][j] == target) {\n                sidx = i; pos = j;\n                return;\n            }\n        }\n    }\n}\n\nint main() {\n    int n = 200, m = 10;\n    multi_array<int, 2> stacks(extents[m][n/m]);\n    for (int i=0; i<m; ++i)\n        for (int j=0; j<n/m; ++j)\n            cin >> stacks[i][j];\n\n    vector<pair<int, int>> moves;\n    int target = 1;\n\n    while (target <= n) {\n        int current_s = -1, pos = -1;\n        find_box(stacks, target, current_s, pos);\n        \n        bool at_top = false;\n        for (int s=0; s<m; ++s) {\n            if (!stacks[s].empty() && stacks[s].back() == target) {\n                at_top = true;\n                current_s = s;\n                break;\n            }\n        }\n        if (at_top) {\n            moves.emplace_back(target, 0);\n            stacks[current_s].pop_back();\n            target++;\n            continue;\n        }\n        \n        if (pos != stacks[current_s].size()-1) {\n            int max_dest = -1, dest_idx = -1;\n            for (int s=0; s<m; ++s) {\n                if (!stacks[s].empty() && s != current_s) {\n                    if (stacks[s].back() > max_dest || dest_idx == -1) {\n                        max_dest = stacks[s].back();\n                        dest_idx = s;\n                    }\n                }\n            }\n            if (dest_idx == -1) dest_idx = (current_s + 1) % m; // Pick next available\n            moves.emplace_back(stacks[current_s][pos], dest_idx + 1);\n            auto seq = stacks[current_s].subarray(pos, stacks[current_s].size());\n            stacks[dest_idx].insert(stacks[dest_idx].end(), seq.begin(), seq.end());\n            stacks[current_s].resize(pos);\n        }\n    }\n\n    for (auto& [v, i] : moves)\n        cout << v << \" \" << i << \"\\n\";\n}","ahc027":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\nusing namespace boost;\n\n// Direction vectors: down, right, up, left\nint dx[] = {1, 0, -1, 0};\nint dy[] = {0, 1, 0, -1};\nchar dir_char[] = {'D', 'R', 'U', 'L'};\n\nconst int INF = 1e9;\ntypedef vector<vector<int>> Matrix;\ntypedef vector<vector<vector<int>>> Dist; // precomputed distances\n\nbool valid(int x, int y, int n) {\n    return x >= 0 && x < n && y >= 0 && y < n;\n}\n\npair<Matrix, Matrix> parseInput(int n) {\n    vector<string> h(n-1), v(n);\n    for (auto& s : h) cin >> s;\n    for (auto& s : v) cin >> s;\n    \n    Matrix hor(n, vector<int>(n, 0));\n    for (int i = 0; i < n-1; ++i)\n        for (int j = 0; j < n; ++j)\n            hor[i][j] = h[i][j] - '0';\n            \n    Matrix ver(n, vector<int>(n, 0));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n-1; ++j)\n            ver[i][j] = v[i][j] - '0';\n            \n    return {hor, ver};\n}\n\nMatrix readDirt(int n) {\n    Matrix d(n, vector<int>(n, 0));\n    for (auto& row : d)\n        for (int& v : row) cin >> v;\n    return d;\n}\n\nvoid bfs(int x, int y, int n, const Matrix& hor, const Matrix& ver, vector<vector<bool>>& vis) {\n    queue<pair<int,int>> q;\n    q.emplace(x, y);\n    vis[x][y] = true;\n    while (!q.empty()) {\n        auto [cx, cy] = q.front(); q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int nx = cx + dx[k], ny = cy + dy[k];\n            if (valid(nx, ny, n) && !vis[nx][ny]) {\n                if ((k == 0 && !hor[cx][cy]) || \n                    (k == 1 && !ver[cx][cy]) ||\n                    (k == 2 && !hor[nx][ny]) ||\n                    (k == 3 && !ver[nx][ny])) {\n                    vis[nx][ny] = true;\n                    q.emplace(nx, ny);\n                }\n            }\n        }\n    }\n}\n\nDist precompute_distances(int n, const Matrix& hor, const Matrix& ver) {\n    Dist dist(n, vector<vector<int>>(n, vector<int>(n*n, INF)));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            priority_queue<pair<int, pair<int,int>>, \n                           vector<pair<int, pair<int,int>>>, \n                           greater<>> pq;\n            pq.emplace(0, make_pair(i, j));\n            dist[i][j][i*n + j] = 0;\n            while (!pq.empty()) {\n                auto [d, p] = pq.top(); pq.pop();\n                auto [x, y] = p;\n                if (d > dist[i][j][x*n + y]) continue;\n                for (int k = 0; k < 4; ++k) {\n                    int nx = x + dx[k], ny = y + dy[k];\n                    if (valid(nx, ny, n)) {\n                        bool blocked = (k == 0 && hor[x][y]) ||\n                                       (k == 1 && ver[x][y]) ||\n                                       (k == 2 && hor[nx][ny]) ||\n                                       (k == 3 && ver[nx][ny]);\n                        if (!blocked && d + 1 < dist[i][j][nx*n + ny]) {\n                            dist[i][j][nx*n + ny] = d + 1;\n                            pq.emplace(d + 1, make_pair(nx, ny));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return dist;\n}\n\nvoid add_route(int x, int y, int nx, int ny, const Dist& dist, vector<char>& answer, int n) {\n    if (x == nx && y == ny) return;\n    auto& d = dist[x][y];\n    int best_k = -1;\n    for (int k = 0; k < 4; ++k) {\n        int ax = x + dx[k], ay = y + dy[k];\n        if (valid(ax, ay, n) && dist[x][y][ax*n + ay] == d[nx*n + ny] - 1 && \n            (best_k == -1 || dist[ax][ay][nx*n + ny] < dist[x + dx[best_k]][y + dy[best_k]][nx*n + ny])) {\n            best_k = k;\n        }\n    }\n    if (best_k != -1) {\n        answer.push_back(dir_char[best_k]);\n        add_route(x + dx[best_k], y + dy[best_k], nx, ny, dist, answer, n);\n    }\n}\n\nvector<pair<int, int>> get_critical_points(const Matrix& d, int region_size) {\n    vector<pair<int, pair<int,int>>> points;\n    for (int i = 0; i < d.size(); ++i)\n        for (int j = 0; j < d.size(); ++j)\n            points.emplace_back(-d[i][j], make_pair(i,j));\n    sort(points.begin(), points.end());\n    \n    vector<pair<int,int>> result;\n    for (int i = 0; i < min<int>(region_size, (int)points.size()); ++i)\n        result.emplace_back(points[i].second);\n    return result;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    auto [hor, ver] = parseInput(n);\n    Matrix d = readDirt(n);\n    \n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    bfs(0, 0, n, hor, ver, vis);\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            assert(vis[i][j]);\n    \n    Dist dist = precompute_distances(n, hor, ver);\n    \n    vector<pair<int, int>> critical = get_critical_points(d, n); // Top critical points\n    \n    vector<char> answer;\n    int len = 0, limit = 1e5;\n    int x = 0, y = 0;\n    \n    vector<int> shuffled(critical.size());\n    iota(shuffled.begin(), shuffled.end(), 0);\n    \n    while (true) {\n        random_shuffle(shuffled.begin(), shuffled.end());\n        for (int idx : shuffled) {\n            auto [nx, ny] = critical[idx];\n            if (len + dist[x][y][nx*n + ny] > limit) break;\n            add_route(x, y, nx, ny, dist, answer, n);\n            len += dist[x][y][nx*n + ny];\n            x = nx; y = ny;\n        }\n        if (len + dist[x][y][0] > limit)\n            break;\n        add_route(x, y, 0, 0, dist, answer, n);\n        break;\n    }\n    \n    cout << string(answer.begin(), answer.end()) << endl;\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\n#include <boost/algorithm/string/find_tail.hpp>\nusing namespace std;\n\nstring concat(const vector<string>& t) {\n    int m = t.size();\n    string result = t[0];\n    unordered_map<string, vector<int>> suffix;\n    for (int i=0; i<m; ++i) {\n        for (int len=1; len<=4; ++len) {\n            suffix[t[i].substr(t[i].size() - len)].push_back(i);\n        }\n    }\n    vector<bool> used(m, false);\n    used[0] = true;\n    \n    auto get_cost = [&](int idx, const string& prev_str) {\n        string target = t[idx];\n        int n = prev_str.size();\n        int max_overlap = 0;\n        for (int i=1; i<=4 && i<=n; ++i) {\n            if (boost::algorithm::ends_with(prev_str, target.substr(0,i))) \n                max_overlap = i;\n        }\n        return target.size() - max_overlap;\n    };\n    \n    for (int count=1; count<m; ++count) {\n        int best_idx = -1, min_cost = INT_MAX;\n        for (int i=0; i<m; ++i) {\n            if (!used[i]) {\n                int cost = get_cost(i, result);\n                if (cost < min_cost) {\n                    min_cost = cost;\n                    best_idx = i;\n                }\n            }\n        }\n        if (best_idx == -1) break;\n        used[best_idx] = true;\n        string current = t[best_idx];\n        int n = result.size();\n        int overlap = 0;\n        for (int k=1; k<=min(4,n); ++k) {\n            if (boost::algorithm::ends_with(result, current.substr(0,k)))\n                overlap = k;\n        }\n        result += current.substr(overlap);\n    }\n    return result.substr(0, 5000);\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> A(N);\n    for (int i=0; i<N; ++i) cin >> A[i];\n    \n    vector<string> words(M);\n    unordered_map<char, pair<int,int>> pos;\n    \n    for (int i=0; i<M; ++i) cin >> words[i];\n    \n    for (int i=0; i<N; ++i) \n        for (int j=0; j<N; ++j) \n            pos[A[i][j]] = {i, j};\n    \n    string lucky = concat(words);\n    pair<int, int> current = {si, sj};\n    vector<pair<int,int>> steps;\n    \n    for (char c : lucky) {\n        steps.emplace_back(pos[c]);\n    }\n    \n    cout << steps.size() << endl;\n    for (auto& [x, y] : steps) {\n        cout << x << \" \" << y << endl;\n    }\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nusing namespace std;\nusing namespace boost::accumulators;\n\nstruct Grid {\n    int n;\n    boost::multi_array<int, 2> grid;  // 0: unknown, -1: empty, >=1: count\n    vector<pair<int,int>> unknown;\n    mt19937 mt{random_device{}()};\n    \n    Grid(int _n) : n(_n), grid(boost::extents[_n][_n]) {\n        for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) {\n            grid[i][j] = 0;\n            unknown.emplace_back(i, j);\n        }\n    }\n    \n    bool is_unknown(int i, int j) const {\n        return 0 <= i && i < n && 0 <= j && j <n && grid[i][j] == 0;\n    }\n    \n    void query_group(int size, const vector<pair<int,int>>& indexes) {\n        cout << \"q \" << size;\n        for (auto [x,y] : indexes) cout << ' ' << x << ' ' << y;\n        cout << endl;\n        int result;\n        cin >> result;\n        double mean = result + size * (1e-5); // Prevent division by zero\n        double stddev = sqrt(size * 0.2); // Conservative estimate\n        \n        double z_score = (result - size * 0.1) / (stddev + 1e-5);\n        for (auto [x,y] : indexes) {\n            if (grid[x][y] == 0) {\n                if (z_score > 2.0) grid[x][y] = 2;\n                else if (z_score < -1.5) grid[x][y] = -1;\n            }\n        }\n    }\n    \n    void drill(int i, int j) {\n        cout << \"q 1 \" << i << ' ' << j << endl;\n        cin >> grid[i][j];\n    }\n    \n    void report() {\n        vector<pair<int,int>> positives;\n        for (int i=0; i<n; ++i)\n            for (int j=0; j<n; ++j)\n                if (grid[i][j] > 0) positives.emplace_back(i,j);\n        \n        cout << \"a \" << positives.size();\n        for (auto [x,y] : positives) cout << ' ' << x << ' ' << y;\n        cout << endl;\n        exit(0);\n    }\n};\n\nbool is_border(int i, int j, int n) {\n    return i == 0 || j == 0 || i == n-1 || j == n-1;\n}\n\nint main() {\n    srand(time(0));\n    int N, M;\n    double epsilon;\n    cin >> N >> M >> epsilon;\n    vector<vector<pair<int,int>>> oil(M);\n    \n    for (int m=0; m<M; ++m) {\n        int d; cin >> d;\n        oil[m].resize(d);\n        for (int k=0; k<d; ++k) {\n            cin >> oil[m][k].first >> oil[m][k].second;\n        }\n    }\n    \n    Grid g(N);\n    int total = N * N;\n    int budget = total / 3;\n    \n    // Initial divination phase: 5x5 blocks\n    for (int i=0; i+5<=N; i+=5) {\n        for (int j=0; j+5<=N; j+=5) {\n            if (budget-- <= 0) break;\n            vector<pair<int,int>> block;\n            for (int x=i; x < i+5; ++x)\n                for (int y=j; y < j+5; ++y) \n                    if (g.is_unknown(x,y)) block.emplace_back(x,y);\n            if (block.size() >= 2) g.query_group(block.size(), block);\n        }\n        if (budget <= 0) break;\n    }\n    \n    // Remaining cells: smaller divination\n    while (budget >= 5 && g.unknown.size() >= 5) {\n        shuffle(g.unknown.begin(), g.unknown.end(), g.mt);\n        vector<pair<int,int>> batch;\n        while (budget >= 0 && batch.size() < 20 && !g.unknown.empty()) {\n            auto [x,y] = g.unknown.back();\n            g.unknown.pop_back();\n            if (g.is_unknown(x,y)) {\n                batch.emplace_back(x,y);\n            }\n        }\n        if (batch.size() >= 2) {\n            g.query_group(batch.size(), batch);\n            budget--;\n        }\n    }\n    \n    // Drill borders\n    for (auto &cell : g.unknown) {\n        if (g.is_unknown(cell.first, cell.second) && is_border(cell.first, cell.second, N)) {\n            g.drill(cell.first, cell.second);\n        }\n    }\n    \n    // Drill remaining\n    for (auto &cell : g.unknown) {\n        if (g.is_unknown(cell.first, cell.second)) {\n            g.drill(cell.first, cell.second);\n        }\n    }\n    \n    g.report();\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<tuple<int,int,int,int>> rectangles[55];\n\nvoid solve(int n, const vector<int>& areas) {\n    int w = 1000;\n    int sum = accumulate(areas.begin(), areas.end(), 0);\n    int remaining = w * w - sum;\n    vector<int> needed = areas;\n    int max_y = w;\n\n    rectangles[n].resize(areas.size());\n    \n    for (int i=0; i<(int)areas.size(); ++i) {\n        int rows = (remaining + (int)areas.size() - i - 1) / ((int)areas.size() - i);\n        rows = max(rows, (needed[i] + w - 1) / w); // at least enough area\n        \n        int y_start = max_y - rows;\n        get<0>(rectangles[n][i]) = y_start;\n        get<2>(rectangles[n][i]) = max_y;\n        get<1>(rectangles[n][i]) = 0;\n        int cols = needed[i] / rows;\n        if (cols * rows < needed[i]) ++cols;\n        cols = min(cols, w); // max columns can't exceed grid width\n        get<3>(rectangles[n][i]) = cols;\n        \n        remaining -= (rows * cols - needed[i]);\n        max_y = y_start;\n    }\n    \n    int last_x = 0;\n    for (int k=0; k < (int)rectangles[n].size(); ++k) {\n        get<1>(rectangles[n][k]) = last_x;\n        last_x += get<3>(rectangles[n][k]);\n        get<3>(rectangles[n][k]) = last_x;\n    }\n}\n\nint main() {\n    int W = 1000, D, N;\n    cin >> W >> D >> N;\n    \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    for (int d=0; d<D; ++d) \n        solve(d, a[d]);\n    \n    for (int d=0; d<D; ++d)\n        for (auto [x1,y1,x2,y2] : rectangles[d])\n            printf(\"%d %d %d %d\\n\", x1, y1, x2, y2);\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\nconst int MOD = 998244353;\nint a[N][N], stamps[M][3][3];\nvector<tuple<int, int, int>> operations;\n\nbool isValid(int p, int q) {\n    return p <= N-3 && q <= N-3;\n}\n\nint applyStamp(int m, int p, int q) {\n    int total = 0;\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            total += (a[p+i][q+j] + stamps[m][i][j]) % MOD - a[p+i][q+j] % MOD;\n        }\n    }\n    return total >= 0 ? total : total + MOD;\n}\n\nint main() {\n    int n, m, k;\n    cin >> n >> m >> k;\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n    \n    for (int l = 0; l < m; ++l)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> stamps[l][i][j];\n    \n    // Store available positions\n    vector<pair<int, int>> positions;\n    for (int i = 0; i <= N-3; ++i)\n        for (int j = 0; j <= N-3; ++j)\n            positions.emplace_back(i, j);\n\n    while (operations.size() < K) {\n        int best_score = 0;\n        int best_stamp = -1, best_p = -1, best_q = -1;\n        \n        shuffle(positions.begin(), positions.end(), mt19937(random_device()()));\n        \n        for (auto &[p, q] : positions) {\n            for (int st = 0; st < m; ++st) {\n                int score = applyStamp(st, p, q);\n                if (score > best_score) {\n                    best_score = score;\n                    best_stamp = st;\n                    best_p = p;\n                    best_q = q;\n                }\n            }\n        }\n        \n        if (best_stamp == -1) break;\n\n        operations.emplace_back(best_stamp, best_p, best_q);\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                a[best_p+i][best_q+j] = (a[best_p+i][best_q+j] + stamps[best_stamp][i][j]) % MOD;\n            }\n        }\n    }\n\n    cout << operations.size() << endl;\n    for (auto &[m, p, q] : operations)\n        cout << m << \" \" << p << \" \" << q << endl;\n    \n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nvector<string> solve(const vector<vector<int>>& containers) {\n    int N = containers.size();\n    vector<int> targetRow(N * N);\n    for (int i = 0; i < N; ++i)\n        for (int k = 0; k < N; ++k)\n            targetRow[containers[i][k]] = i;\n\n    vector<vector<int>> targetPos(N * N);\n    for (int b = 0; b < N * N; ++b) {\n        int r = targetRow[b];\n        targetPos[b] = {r, N-1};\n    }\n\n    vector<string> res(N);\n    int T = 30 + N * N * 5;\n    for (int t = 0; t < T; ++t) {\n        for (int i = 0; i < N; ++i)\n            res[i] += '.';\n        bool moved = false;\n        // Large crane (index 0)\n        if (res[0].back() != 'B') {\n            vector<int> cranePos = {0 + t % N, 0};\n            if (cranePos[1] < N-1) {\n                int mx = -1;\n                for (int x = 0; x < N; ++x) {\n                    if (cranePos[0] == x && containers[x].size() > t) {\n                        int b = containers[x][t];\n                        if (mx == -1 || targetRow[mx] < targetRow[b]) {\n                            mx = b;\n                        }\n                    }\n                }\n                if (mx != -1 && t + abs(cranePos[0] - targetPos[mx][0]) + abs(cranePos[1] - targetPos[mx][1]) <= T) {\n                    if (cranePos[1] == 0) res[0].back() = 'P';\n                    else {\n                        if (targetPos[mx][1] == cranePos[1] + 1) res[0].back() = 'R';\n                        else if (targetPos[mx][0] > cranePos[0] && cranePos[0] < N-1) res[0].back() = 'D';\n                        else if (targetPos[mx][0] < cranePos[0] && cranePos[0] > 0) res[0].back() = 'U';\n                    }\n                    moved = true;\n                }\n            }\n        }\n\n        // Small cranes\n        for (int i = 1; i < N; ++i) {\n            if (res[i].back() != 'B') {\n                vector<int> cranePos = {i, 0};\n                auto update = [&](int dx, int dy, char dir) {\n                    if (cranePos[0] + dx >= 0 && cranePos[0] + dx < N && cranePos[1] + dy >= 0 && cranePos[1] + dy < N) {\n                        res[i].back() = dir;\n                        moved = true;\n                    }\n                };\n                bool carrying = (res[i].size() > 0 && res[i].back() == 'P');\n                // Drop container if at Dispatch Gate\n                if (cranePos[1] == N-1 && carrying) res[i].back() = 'Q';\n                // Else move towards Dispatch Gates or pick up containers\n                else if (cranePos[1] > 0 && !carrying) update(0, -1, 'L');\n                else if (cranePos[1] < N-1) update(0, 1, 'R');\n            }\n        }\n        if (!moved) break;\n    }\n    return res;\n}\n\nint main() {\n    int N = 5;\n    vector<vector<int>> containers(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> containers[i][j];\n    auto commands = solve(containers);\n    int maxLen = 0;\n    for (auto& s : commands) maxLen = max(maxLen, (int)s.size());\n    for (auto& s : commands) s.resize(maxLen, '.');\n    for (auto& s : commands) cout << s << endl;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint H[20][20], dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}, vis[20][20];\nvector<string> ans;\nint n = 20, x = 0, y = 0, load = 0;\n\nvoid move(int nx, int ny) {\n    while (x != nx || y != ny) {\n        if (x > nx) ans.push_back(\"U\"), x--;\n        else if (x < nx) ans.push_back(\"D\"), x++;\n        else if (y > ny) ans.push_back(\"L\"), y--;\n        else ans.push_back(\"R\"), y++;\n    }\n}\n\nvoid load_soil(int val) {\n    ans.push_back(\"+\" + to_string(val));\n    load += val;\n    H[x][y] -= val;\n}\n\nvoid unload_soil(int val) {\n    ans.push_back(\"-\" + to_string(val));\n    load -= val;\n    H[x][y] += val;\n}\n\nvoid process() {\n    memset(vis, 0, sizeof(vis));\n    vector<pair<int, int>> positives, negatives;\n    \n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            (H[i][j] > 0) ? positives.emplace_back(H[i][j], i*n+j) :\n            (H[i][j] < 0) ? negatives.emplace_back(-H[i][j], i*n+j) : void();\n        }\n    }\n\n    sort(positives.rbegin(), positives.rend());\n    sort(negatives.rbegin(), negatives.rend());\n\n    auto get = [&](int val) { return pair{val/n, val%n}; };\n\n    while (!positives.empty() && !negatives.empty()) {\n        auto [pval, pos] = positives.back(); positives.pop_back();\n        auto [nval, neg] = negatives.back(); negatives.pop_back();\n        auto [posx, posy] = get(pos);\n        auto [negx, negy] = get(neg);\n\n        if (pval == 0 || nval == 0) break;\n        int transfer = min(pval, nval);\n\n        move(posx, posy);\n        load_soil(transfer);\n        move(negx, negy);\n        unload_soil(transfer);\n\n        if (pval > transfer) positives.emplace_back(pval - transfer, pos);\n        if (nval > transfer) negatives.emplace_back(nval - transfer, neg);\n    }\n\n    while (!positives.empty()) {\n        auto [pval, pos] = positives.back(); positives.pop_back();\n        auto [posx, posy] = get(pos);\n        if (posx == x && posy == y) continue;\n        move(posx, posy);\n        load_soil(pval);\n    }\n\n    while (!negatives.empty()) {\n        auto [nval, neg] = negatives.back(); negatives.pop_back();\n        auto [negx, negy] = get(neg);\n        move(negx, negy);\n        unload_soil(nval);\n    }\n}\n\nint main() {\n    cin >> n;\n    for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) cin >> H[i][j];\n    \n    process();\n    for (auto& op : ans) cout << op << endl;\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\nusing namespace std;\n\nconstexpr int N = 6;\nconstexpr int SEED_COUNT = 2 * N * (N - 1);\nconstexpr int FIELD_SIZE = N * N;\n\nnamespace atcoder {\n    void internal_error() {\n        cerr << \"Error!\" << endl;\n        exit(0);\n    }\n\n    mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());\n\n    int rand(int a, int b) {\n        return uniform_int_distribution<int>(a, b)(mt);\n    }\n\n    double rand(double a, double b) {\n        return uniform_real_distribution<double>(a, b)(mt);\n    }\n}\nusing namespace atcoder;\n\nstruct Seed {\n    vector<int> eval;\n    int total;\n\n    Seed(const vector<int> &eval) : eval(eval) {\n        total = accumulate(eval.begin(), eval.end(), 0);\n    }\n\n    bool operator<(const Seed &other) const {\n        return this->total < other.total;\n    }\n};\n\nvector<int> next_gen(int round, const vector<Seed> &seeds) {\n    // Prioritize top seeds\n    vector<int> sorted_id(SEED_COUNT);\n    iota(sorted_id.begin(), sorted_id.end(), 0);\n    sort(sorted_id.begin(), sorted_id.end(), [&](int a, int b) {\n        return seeds[a].total > seeds[b].total;\n    });\n\n    vector<int> layout(FIELD_SIZE);\n    fill(layout.begin(), layout.end(), -1);\n    \n    // Place the N*N best seeds on the board\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            layout[i * N + j] = sorted_id[i * N + j];\n        }\n    }\n\n    return layout;\n}\n\nint main() {\n    int M, T;\n    cin >> N >> M >> T;\n\n    vector<Seed> seeds;\n    for (int i = 0; i < SEED_COUNT; ++i) {\n        vector<int> eval(M);\n        for (int &val : eval) cin >> val;\n        seeds.emplace_back(eval);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        auto layout = next_gen(t, seeds);\n        \n        for (int i = 0; i < FIELD_SIZE; ++i) {\n            cout << layout[i] << (i % N == N - 1 ? '\\n' : ' ');\n        }\n        cout << flush;\n\n        // Read the newly generated seeds\n        seeds.resize(SEED_COUNT);\n        for (int i = 0; i < SEED_COUNT; ++i) {\n            vector<int> eval(M);\n            for (int &val : eval) cin >> val;\n            seeds[i] = Seed(eval);\n        }\n    }\n}","ahc038":"#include <bits/stdc++.h>\n#include <queue>\n#include <optional>\nusing namespace std;\n\nconstexpr int INF = 1e9;\n\nstruct Pos {\n    int x, y;\n    bool operator==(const Pos& o) const { return x == o.x && y == o.y; }\n    Pos rotate(char c) const {\n        if (c == 'L') return {-y, x};\n        if (c == 'R') return {y, -x};\n        return {x, y};\n    }\n};\n\nstruct State {\n    int turns;\n    Pos pos;\n    vector<Pos> fingers; // relative positions\n    State(int t, Pos p, const vector<Pos>& f) : turns(t), pos(p), fingers(f) {}\n};\n\nvector<string> grid;\nvector<vector<char>> rotations;\nint dist(Pos a, Pos b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvector<string> find_path(Pos start, Pos goal, int V, const string& initial_rot = \"\") {\n    priority_queue<pair<int, State>, vector<pair<int, State>>, greater<>> pq;\n    unordered_map<Pos, int> dirs = {{'R', 0}, {'D', 1}, {'L', 2}, {'U', 3}};\n    vector<Pos> dir_offs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n    vector<string> dir_strs = {\"R\", \"D\", \"L\", \"U\"};\n    unordered_map<State, int, hash<State>> visited;\n    \n    vector<Pos> init_fingers(V - 1);\n    for (int i = 0; i < V - 1; ++i) {\n        init_fingers[i] = {i + 1, 0};\n    }\n    for (char c : initial_rot) {\n        if (c == '.') break;\n        for (auto& f : init_fingers) f = f.rotate(c);\n    }\n    \n    auto start_state = State(0, start, init_fingers);\n    pq.emplace(dist(start, goal), start_state);\n    visited[start_state] = 0;\n    \n    while (!pq.empty()) {\n        auto [current_cost, current] = pq.top();\n        pq.pop();\n        if (current.pos == goal) {\n            vector<string> path;\n            string rot = initial_rot.substr(0, V - 1);\n            while (current.turns > 0) {\n                path.emplace_back(dir_strs[current.pos.x] + rot + string(V, '.'));\n                for (char& c : rot) {\n                    if (c == 'R') c = 'L';\n                    else if (c == 'L') c = 'R';\n                }\n                reverse(rot.begin(), rot.end());\n                current.pos = goal;\n                --current.turns;\n            }\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        \n        for (int i = 0; i < 4; ++i) {\n            Pos next_pos = {current.pos.x + dir_offs[i].x, current.pos.y + dir_offs[i].y};\n            if (next_pos.x < 0 || next_pos.x >= grid.size() || next_pos.y < 0 || next_pos.y >= grid.size())\n                continue;\n            auto new_state = State(current.turns + 1, next_pos, current.fingers);\n            if (visited.count(new_state) && visited[new_state] <= new_state.turns)\n                continue;\n            visited[new_state] = new_state.turns;\n            pq.emplace(new_state.turns + dist(next_pos, goal), new_state);\n        }\n        \n        // Rotate subtrees\n        for (int v = 1; v < V; ++v) {\n            for (char rot : {'L', 'R'}) {\n                vector<Pos> new_fingers = current.fingers;\n                for (auto& f : new_fingers) f = f.rotate(rot);\n                auto rotated = State(current.turns + 1, current.pos, new_fingers);\n                if (visited.count(rotated) && visited[rotated] <= rotated.turns)\n                    continue;\n                visited[rotated] = rotated.turns;\n                pq.emplace(rotated.turns + dist(current.pos, goal), rotated);\n            }\n        }\n    }\n    return {};\n}\n\nint main() {\n    // Example input parsing; actual input handling depends on contest environment\n    int N = 20, M = 7, V = 8; \n    vector<pair<Pos, Pos>> tasks = {\n        {{0,0}, {15,5}}, {{3,2}, {17,7}}, {{5,5}, {18,18}}, \n        {{12,8}, {2,2}}, {{15,19}, {3,3}}, {{7,11}, {10,10}}, {{9,14}, {11,2}}\n    };\n    \n    cout << V << \"\\n\";\n    for (int i = 1; i < V; ++i) {\n        cout << \"0 \" << 1 << '\\n'; // star structure with length 1\n    }\n    cout << \"0 0\\n\"; // initial root position\n    \n    vector<bool> done(M, false);\n    Pos current = {0, 0};\n    int completed = 0;\n    \n    for (int steps = 0; completed < M; ++steps) {\n        pair<int, int> best = {INF, -1};\n        for (int i = 0; i < M; ++i) {\n            if (!done[i]) {\n                int cost = dist(current, tasks[i].first) + dist(tasks[i].first, tasks[i].second);\n                best = min(best, {cost, i});\n            }\n        }\n        int idx = best.second;\n        if (idx < 0) break;\n        \n        // Move to source\n        auto path1 = find_path(current, tasks[idx].first, V);\n        for (auto& s : path1) {\n            cout << s << '\\n';\n        }\n        current = tasks[idx].first;\n        \n        // Operation to grab\n        cout << \".\" + string(V - 1, '.') + string(V - 1, '.') << \"P\\n\";\n        \n        // Move to target\n        auto path2 = find_path(current, tasks[idx].second, V);\n        for (auto& s : path2) {\n            cout << s << '\\n';\n        }\n        \n        // Operation to release\n        cout << \".\" + string(V - 1, '.') + string(V - 1, '.') << \"P\\n\";\n        \n        done[idx] = true;\n        completed++;\n        current = tasks[idx].second;\n    }\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\nusing namespace std;\nusing namespace boost::geometry;\nusing namespace boost::geometry::index;\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint main() {\n    int N = 5000;\n    vector<pair<int, int>> mackerel(N), sardine(N);\n    for (int i = 0; i < 2*N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        if (i < N) mackerel[i] = {x, y};\n        else sardine[i-N] = {x, y};\n    }\n    \n    // K-means clustering for mackerels\n    int K = 15;\n    vector<vector<pair<int, int>>> clusters(K);\n    vector<pair<int, int>> centroids(K);\n    for (auto& [x, y] : mackerel) {\n        int idx = uniform_int_distribution<>(0, K-1)(rng);\n        centroids[idx].first += x;\n        centroids[idx].second += y;\n        clusters[idx].emplace_back(x, y);\n    }\n    for (int i = 0; i < 10; ++i) {\n        for (auto& cl : clusters) cl.clear();\n        for (auto& [x, y] : mackerel) {\n            int best = 0, min_dist = INT_MAX;\n            for (int j = 0; j < K; ++j) {\n                auto& [cx, cy] = centroids[j];\n                int dist = (x - cx)*(x - cx) + (y - cy)*(y - cy);\n                if (dist < min_dist) {\n                    min_dist = dist;\n                    best = j;\n                }\n            }\n            clusters[best].emplace_back(x, y);\n        }\n        for (int j = 0; j < K; ++j) {\n            if (!clusters[j].empty()) {\n                centroids[j] = {0, 0};\n                for (auto& [x, y] : clusters[j]) {\n                    centroids[j].first += x;\n                    centroids[j].second += y;\n                }\n                centroids[j].first /= clusters[j].size();\n                centroids[j].second /= clusters[j].size();\n            }\n        }\n    }\n\n    // Build sardine R-Tree\n    rtree<pair<int, int>, rstar<16>> sardine_tree;\n    for (auto& [x, y] : sardine) sardine_tree.insert({x, y});\n\n    vector<tuple<int, int, int, int>> candidates;\n    for (auto& cls : clusters) {\n        if (cls.empty()) continue;\n        int min_x = INT_MAX, max_x = -1, min_y = INT_MAX, max_y = -1;\n        for (auto& [x, y] : cls) {\n            min_x = min(min_x, x); max_x = max(max_x, x);\n            min_y = min(min_y, y); max_y = max(max_y, y);\n        }\n        if (max_x - min_x + max_y - min_y <= 4e5 / 4 && max_x - min_x > 0 && max_y - min_y > 0) {\n            candidates.emplace_back(min_x, min_y, max_x, max_y);\n        }\n    }\n    \n    if (candidates.empty()) {\n        cout << \"4\\n0 0\\n0 100000\\n100000 100000\\n100000 0\\n\";\n        return 0;\n    }\n    \n    auto best_rect = *max_element(candidates.begin(), candidates.end(), \n        [&](const auto& a, const auto& b) {\n            int a_count = 0, b_count = 0;\n            for (auto& s : sardine) {\n                if (a <= get<0>(s) && get<0>(s) <= get<2>(a) &&\n                    a <= get<1>(s) && get<1>(s) <= get<3>(a)) a_count++;\n                if (b <= get<0>(s) && get<0>(s) <= get<2>(b) &&\n                    b <= get<1>(s) && get<1>(s) <= get<3>(b)) b_count++;\n            }\n            return (get<2>(a)-get<0>(a)+get<3>(a)-get<1>(a))-a_count < \n                   (get<2>(b)-get<0>(b)+get<3>(b)-get<1>(b))-b_count;\n        });\n    \n    auto [x1, y1, x2, y2] = best_rect;\n    // Build polygon\n    vector<pair<int, int>> poly = {{x1,y1}, {x1,y2}, {x2,y2}, {x2,y1}};\n    cout << poly.size() << '\\n';\n    for (auto& [x, y] : poly) cout << x << ' ' << y << '\\n';\n    \n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\nusing namespace std;\nusing namespace boost::geometry;\n\nstruct Rect {\n    int x, y, w, h;\n    bool rotated;\n};\n\nvector<pair<int, int>> sizes;\nvector<int> order;\nint N, T;\ndouble start_temp = 1e3, end_temp = 1e-5;\nmt19937 mt(chrono::steady_clock::now().time_since_epoch().count());\n\npair<int, int> place_rects(const vector<int>& perm, bool left_first = false, int mode = 0) {\n    map<pair<int, int>, int> points;\n    points[{0, 0}] = -1;\n    vector<Rect> rects;\n    int max_x = 0, max_y = 0;\n    \n    auto update_max = [&](int x, int y) {\n        max_x = max(max_x, x);\n        max_y = max(max_y, y);\n    };\n    \n    auto can_place = [&](int x, int y, int w, int h) {\n        model::box<point<int>> box(point(x, y), point(x + w, y + h));\n        for (auto& r : rects) {\n            if (overlaps(box, model::box<point<int>>(\n                point(r.x, r.y), point(r.x + r.w, r.y + r.h))\n            )) return false;\n        }\n        return true;\n    };\n    \n    int idx = 0;\n    for (int op : perm) {\n        int rw = max(sizes[op].first, sizes[op].second);\n        int rh = min(sizes[op].first, sizes[op].second);\n        bool rot = (sizes[op].first < sizes[op].second);\n        bool placed = false;\n        \n        for (int step = 0; step < 2; ++step) { // 2 orientations\n            if (step == 1) swap(rw, rh), rot = !rot;\n            // Try U (up) first\n            if (!left_first || idx++ % 2 == mode) {\n                for (auto [pt, prev] : points) {\n                    int x = pt.first, y_try = pt.second;\n                    if (can_place(x, y_try, rw, rh)) {\n                        rects.push_back({x, y_try, rw, rh, rot});\n                        points[{x + rw, y_try + rh}] = prev;\n                        update_max(x + rw, y_try + rh);\n                        placed = true;\n                        break;\n                    }\n                }\n                if (placed) break;\n            }\n            // Then try L (left)\n            if (left_first || idx % 2 != mode) {\n                for (auto [pt, prev] : points) {\n                    int y = pt.second, x_try = pt.first;\n                    if (can_place(x_try, y, rw, rh)) {\n                        rects.push_back({x_try, y, rw, rh, rot});\n                        points[{x_try + rw, y + rh}] = prev;\n                        update_max(x_try + rw, y + rh);\n                        placed = true;\n                        break;\n                    }\n                }\n                if (placed) break;\n            }\n        }\n        if (!placed) { max_x += rw; max_y += rh; } // penalty for unused\n    }\n    return {max_x, max_y};\n}\n\nvoid solve() {\n    cin >> N >> T;\n    double sigma; cin >> sigma;\n    sizes.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> sizes[i].first >> sizes[i].second;\n        sizes[i].first += 3 * sigma;  // Upper approx\n        sizes[i].second += 3 * sigma;\n        if (sizes[i].first > 1e9) sizes[i].first = 1e9;\n        if (sizes[i].second > 1e9) sizes[i].second = 1e9;\n        order.push_back(i);\n    }\n    \n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return max(sizes[a].first, sizes[a].second) > max(sizes[b].first, sizes[b].second);\n    });\n    \n    auto best = place_rects(order);\n    auto best_order = order;\n    \n    // Simulated Annealing\n    for (int iteration = 0; iteration < 30; ++iteration) {\n        auto current = order;\n        for (double temp = start_temp; temp > end_temp; temp *= 0.99) {\n            int i = uniform_int_distribution<>(0, N-1)(mt);\n            int j = uniform_int_distribution<>(0, N-1)(mt);\n            swap(current[i], current[j]);\n            \n            auto candidate = place_rects(current, iteration % 2 == 0, iteration / 10);\n            int current_score = best.first + best.second;\n            int candidate_score = candidate.first + candidate.second;\n            \n            if (candidate_score < current_score || \n                exp((current_score - candidate_score) / temp) > (double)mt()/mt.max()) {\n                best = candidate;\n            } else {\n                swap(current[i], current[j]); // revert\n            }\n        }\n    }\n    \n    for (int t = 0; t < T; ++t) {\n        cout << N << '\\n';\n        for (size_t i = 0; i < best_order.size(); ++i) {\n            int id = best_order[i];\n            cout << id << ' ' << \"0\" << ' ' << (i % 2 ? 'L' : 'U') << ' ' << (i > 0 ? best_order[i-1] : -1) << '\\n';\n        }\n        cout.flush();\n        \n        int W, H;\n        cin >> W >> H;\n        if (t == T-1) break;\n        \n        // Optional: Adjust based on feedback if needed\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing i64 = long long;\nconstexpr int INF = (int)1e9 + 5;\nconstexpr i64 LINF = (i64)1e18 + 5;\n\nstruct Edge {\n    int to;\n};\n\nint main() {\n    int N, M, H;\n    cin >> N >> M >> H;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> A[i];\n    }\n\n    vector<vector<Edge>> G(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        G[u].push_back({v});\n        G[v].push_back({u});\n    }\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    vector<int> parent(N, -1);\n    vector<bool> used(N, false);\n    vector<pair<int, int>> order;\n    for (int i = 0; i < N; ++i) {\n        order.emplace_back(A[i], i);\n    }\n\n    auto cmp = [&](pair<int, int> a, pair<int, int> b) {\n        return a.first > b.first || (a.first == b.first && a.second < b.second);\n    };\n    sort(order.begin(), order.end(), cmp);\n\n    for (auto [a, v] : order) {\n        if (used[v]) continue;\n        queue<int> que, next_que;\n        que.push(v);\n        used[v] = true;\n        int height = 0;\n        vector<int> current_level;\n\n        while (!que.empty() && height <= H) {\n            while (!que.empty()) {\n                int u = que.front();\n                que.pop();\n                current_level.push_back(u);\n\n                for (Edge& e : G[u]) {\n                    if (!used[e.to]) {\n                        used[e.to] = true;\n                        next_que.push(e.to);\n                        if (height + 1 < H) {\n                            parent[e.to] = u;\n                        }\n                    }\n                }\n            }\n            que = next_que;\n            queue<int> empty;\n            swap(next_que, empty);\n            ++height;\n        }\n\n        if (height == H + 1) {\n            for (int u : current_level) {\n                parent[u] = -1;\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << parent[i] << (i == N - 1 ? '\\n' : ' ');\n    }\n\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nvoid remove_oni(int i, int j, const vector<string>& board, vector<pair<char, int>>& operations) {\n    if (j > 0 && (board[i][j - 1] == 'x' || board[i][j - 1] == '.')) {\n        // Push right\n        for (int k = 0; k < j; ++k) operations.emplace_back('R', i);\n        for (int k = 0; k <= j; ++k) operations.emplace_back('L', i);\n    } else if (j < 19 && (board[i][j + 1] == 'x' || board[i][j + 1] == '.')) {\n        // Push left\n        for (int k = 0; k <= (19 - j); ++k) operations.emplace_back('L', i);\n        for (int k = 0; k <= (19 - j); ++k) operations.emplace_back('R', i);\n    } else if (i > 0 && (board[i - 1][j] == 'x' || board[i - 1][j] == '.')) {\n        // Push down\n        for (int k = 0; k < i; ++k) operations.emplace_back('D', j);\n        for (int k = 0; k <= i; ++k) operations.emplace_back('U', j);\n    } else if (i < 19 && (board[i + 1][j] == 'x' || board[i + 1][j] == '.')) {\n        // Push up\n        for (int k = 0; k <= (19 - i); ++k) operations.emplace_back('U', j);\n        for (int k = 0; k <= (19 - i); ++k) operations.emplace_back('D', j);\n    }\n}\n\nint main() {\n    int N = 20;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    vector<pair<char, int>> operations;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                remove_oni(i, j, board, operations);\n            }\n        }\n    }\n\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing namespace boost::multiprecision;\n\nusing lint = long long;\nusing P = pair<lint, int>; \nconstexpr lint INF = 1LL<<60;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N = 100;\n    lint L = 500000;\n    cin >> N >> L;\n    vector<lint> T(N);\n    for (auto& t : T) cin >> t;\n    \n    vector<int> a(N), b(N), cnt(N);\n    priority_queue<P> pq;\n    for (int i=0; i<N; ++i) pq.emplace(T[i], i);\n    \n    vector<bool> used(N, false);\n    auto pick_next = [&](int cur) {\n        for (int j=0; j<N; ++j) {\n            if (!used[j] && j != cur) {\n                used[j] = true;\n                return j;\n            }\n        }\n        return (cur + 1) % N;\n    };\n    \n    int prev = -1;\n    bool even = true;\n    \n    while (!pq.empty()) {\n        auto [need, idx] = pq.top(); pq.pop();\n        if (cnt[idx] >= need) continue;\n        \n        if (prev != -1) {\n            if (even) a[prev] = idx;\n            else b[prev] = idx;\n        }\n        ++cnt[idx];\n        pq.emplace(need - cnt[idx], idx);\n        prev = idx;\n        even ^= true;\n    }\n    \n    for (int i=0; i<N; ++i) {\n        if (cnt[i] < T[i]) a[i] = i;\n    }\n    \n    for (int i=0; i<N; ++i) {\n        cout << a[i] << \" \" << b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\nusing ll = long long;\nusing P = pair<int, int>;\n\nconst int INF = 1e9;\nrandom_device rd;\nmt19937 RNG(rd());\n\nstruct City {\n    int idx;\n    int cx, cy; // center\n    City(int i, int lx, int rx, int ly, int ry) \n        : idx(i), cx((lx+rx)/2), cy((ly+ry)/2) {}\n    bool operator<(const City& o) const {\n        return make_pair(cx, cy) < make_pair(o.cx, o.cy);\n    }\n};\n\nvector<int> query_group(const vector<City>& group) {\n    if (group.size() < 2) return {};\n    cout << \"? \" << group.size();\n    for (auto& c : group) cout << \" \" << c.idx;\n    cout << endl;\n    \n    vector<int> res;\n    int edges = group.size() - 1;\n    for (int i=0; i < edges; ++i) {\n        int u, v; cin >> u >> v;\n        if (u > v) swap(u, v);\n        res.emplace_back(u);\n        res.emplace_back(v);\n    }\n    return res;\n}\n\nvoid solve() {\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (auto& g : G) cin >> g;\n    \n    vector<City> cities;\n    for (int i=0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cities.emplace_back(i, lx, rx, ly, ry);\n    }\n    sort(cities.begin(), cities.end());\n    \n    // Assign cities to groups\n    vector<vector<int>> groups(M);\n    int pos = 0;\n    for (int i=0; i < M; ++i) {\n        for (int j=0; j < G[i]; ++j, ++pos) {\n            groups[i].push_back(cities[pos].idx);\n        }\n    }\n\n    // Query MST and build connections\n    vector<tuple<int, int, int>> all_edges;\n    for (auto& group : groups) {\n        vector<City> current_group;\n        for (auto idx : group) {\n            for (auto& c : cities) {\n                if (c.idx == idx) {\n                    current_group.push_back(c);\n                    break;\n                }\n            }\n        }\n        vector<int> raw = query_group(current_group);\n        for (size_t i=0; i < raw.size(); i += 2) {\n            int u = raw[i], v = raw[i+1];\n            all_edges.emplace_back(u, v, hypot(\n                cities[u].cx - cities[v].cx,\n                cities[u].cy - cities[v].cy\n            ));\n        }\n    }\n    \n    // Collect all cities and ensure they are connected\n    vector<int> remaining_cities;\n    for (auto& e : all_edges) remaining_cities.push_back(get<0>(e));\n    sort(remaining_cities.begin(), remaining_cities.end());\n    remaining_cities.erase(unique(remaining_cities.begin(), remaining_cities.end()), remaining_cities.end());\n    \n    // Assign leftovers\n    set<int> used(remaining_cities.begin(), remaining_cities.end());\n    for (auto& c : cities) if (!used.count(c.idx)) remaining_cities.push_back(c.idx);\n    \n    // Form final groups respecting exact group sizes\n    vector<vector<int>> ans_groups;\n    for (int i=0; i < M; ++i) {\n        if (i < groups.size()) {\n            ans_groups.push_back(groups[i]);\n        } else {\n            ans_groups.emplace_back();\n        }\n    }\n\n    int start = 0;\n    for (int sz : G) {\n        ans_groups.emplace_back(vector<int>(remaining_cities.begin() + start, remaining_cities.begin() + start + sz));\n        start += sz;\n    }\n\n    cout << \"!\" << endl;\n    for (auto& group : ans_groups) {\n        for (auto idx : group) cout << idx << \" \";\n        cout << endl;\n        sort(group.begin(), group.end());\n        for (size_t i=1; i < group.size(); ++i) {\n            cout << group[i-1] << \" \" << group[i] << endl;\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    solve();\n    \n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define INF (1LL << 60)\ntypedef long long ll;\ntypedef tree<pair<pair<int, int>, vector<pair<int, int>>>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> oset;\n\nstruct VecHash {\n    size_t operator()(const vector<pair<int, int>>& v) const {\n        size_t seed = 0;\n        for (auto x : v) {\n            seed ^= x.first + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            seed ^= x.second + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n        }\n        return seed;\n    }\n};\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dir[] = {'U', 'D', 'L', 'R'};\n\nvoid astar(vector<pair<int, int>>& goals) {\n    int startX = goals.front().first;\n    int startY = goals.front().second;\n    goals.erase(goals.begin());\n    \n    oset pq;\n    map<pair<pair<int, int>, vector<pair<int, int>>>, int, VecHash> dist;\n    pq.insert({{0, {startX, startY, goals}}, {}});\n    dist[{{startX, startY}, goals}] = 0;\n\n    auto get_priority = [&](int x, int y, const auto& path_rem) {\n        int h = 0;\n        if (!path_rem.empty()) {\n            int nx = path_rem[0].first, ny = path_rem[0].second;\n            h = max(abs(nx - x), abs(ny - y));\n        }\n        for (size_t i = 1; i < path_rem.size(); ++i) {\n            int px = path_rem[i-1].first, py = path_rem[i-1].second;\n            int cx = path_rem[i].first, cy = path_rem[i].second;\n            h += max(abs(cx - px), abs(cy - py));\n        }\n        return h + (int)path_rem.size();\n    };\n\n    while (!pq.empty()) {\n        auto current = pq.begin()->second;\n        pq.erase(pq.begin());\n        int x = current.first;\n        int y = current.second.first;\n        auto remaining = current.second.second;\n        \n        if (remaining.empty()) {\n            for (auto& move : dist[current.first]) {\n                cout << move.first << ' ' << move.second << '\\n';\n            }\n            exit(0);\n        }\n\n        int curr_dist = dist[current.first];\n        for (int d = 0; d < 4; ++d) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx < 0 || nx >= 20 || ny < 0 || ny >= 20) continue;\n\n            bool blocked = false;\n            vector<pair<int, int>> new_rem = remaining;\n            if (new_rem.size() > 0 && new_rem[0] == make_pair(nx, ny)) {\n                new_rem.erase(new_rem.begin());\n            }\n\n            string actions = \"MS\";\n            for (char action : actions) {\n                int tx = x, ty = y, steps = 1;\n                if (action == 'S') {\n                    while (tx + dx[d] >= 0 && tx + dx[d] < 20 && ty + dy[d] >= 0 && ty + dy[d] < 20 && \n                           (new_rem.empty() || make_pair(tx+dx[d], ty+dy[d]) != new_rem[0])) {\n                        tx += dx[d]; ty += dy[d]; ++steps;\n                    }\n                    if (new_rem.size() > 0 && make_pair(tx, ty) != new_rem[0]) continue;\n                    if (!new_rem.empty() && make_pair(tx, ty) == new_rem[0]) {\n                        vector<pair<int, int>> next_rem = new_rem;\n                        next_rem.erase(next_rem.begin());\n                        new_rem = next_rem;\n                    }\n                } else {\n                    tx = nx; ty = ny;\n                }\n                \n                if (dist.count({{tx, ty}, new_rem}) && dist[{{tx, ty}, new_rem}] <= curr_dist + 1) continue;\n\n                dist[{{tx, ty}, new_rem}] = curr_dist + 1;\n                int priority = curr_dist + get_priority(tx, ty, new_rem) + 1;\n                pq.insert({{priority, {tx, ty, new_rem}}, {action, dir[d]}});\n                \n                if (action == 'S') dist[{{tx, ty}, new_rem}].push_back({action, dir[d]});\n            }\n        }\n    }\n}\n\nint main() {\n    int N, M; cin >> N >> M;\n    vector<pair<int, int>> goals(M);\n    for (int i = 0; i < M; ++i) {\n        int x, y; cin >> x >> y;\n        goals[i] = {x, y};\n    }\n    astar(goals);\n    return 0;\n}"},"2":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int x, y, r, id;\n    bool placed = false;\n};\n\nbool cmp(const Company& a, const Company& b) {\n    return a.r > b.r;  // Larger first\n}\n\nvector<tuple<int,int,int,int>> placeAds(const vector<Company>& companies) {\n    int N = companies.size();\n    vector<tuple<int,int,int,int>> result(N);\n    set<pair<int,int>> occupied;\n    \n    vector<bool> used(N, false);\n    for (const auto& comp : companies) {\n        if (!comp.placed) {\n            int x = comp.x, y = comp.y;\n            // Try to expand rectangle while avoiding overlaps\n            int width = 1, height = comp.r;\n            bool valid = true;\n            for (int dx = 0; dx < width && valid; ++dx)\n                for (int dy = 0; dy < height; ++dy)\n                    if (occupied.count({x+dx, y+dy})) valid = false;\n            if (valid) {\n                for (int dx=0; dx<width; ++dx)\n                    for (int dy=0; dy<height; ++dy)\n                        occupied.emplace(x+dx, y+dy);\n                result[comp.id] = {x, y, x+width, y+height};\n                used[comp.id] = true;\n            } else {\n                // If vertical expansion fails, try horizontal\n                swap(width, height);\n                valid = true;\n                for (int dx = 0; dx < width; ++dx)\n                    for (int dy = 0; dy < height; ++dy)\n                        if (occupied.count({x+dx, y+dy})) valid = false;\n                if (valid) {\n                    for (int dx=0; dx<width; ++dx)\n                        for (int dy=0; dy<height; ++dy)\n                            occupied.emplace(x+dx, y+dy);\n                    result[comp.id] = {x, y, x+width, y+height};\n                    used[comp.id] = true;\n                }\n            }\n        }\n    }\n    \n    // Fill remaining gaps\n    for (int i=0; i<N; ++i) {\n        if (!used[i]) {\n            int x = companies[i].x, y = companies[i].y;\n            int side = max(1, (int)sqrt(companies[i].r));\n            bool found = false;\n            for (int a = max(0, x-side); !found && a <= x+side; ++a) {\n                for (int b = max(0, y-side); !found && b <= y+side; ++b) {\n                    bool valid = true;\n                    for (int dx=0; dx<side && a+dx <= 10000; ++dx) {\n                        for (int dy=0; dy<side && b+dy <= 10000; ++dy) {\n                            if (occupied.count({a+dx, b+dy})) {\n                                valid = false;\n                                break;\n                            }\n                        }\n                        if (!valid) break;\n                    }\n                    if (valid && (a+side <= 10000) && (b+side <= 10000)) {\n                        for (dx=0; dx<side; ++dx)\n                            for (dy=0; dy<side; ++dy)\n                                occupied.emplace(a+dx, b+dy);\n                        result[i] = {a, b, a+side, b+side};\n                        found = true;\n                    }\n                }\n            }\n            if (!found) { // Fallback\n                result[i] = {companies[i].x, companies[i].y, companies[i].x+1, companies[i].y+1};\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    int n; cin >> n;\n    vector<Company> companies(n);\n    for (int i=0; i<n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n        companies[i].id = i;\n    }\n    sort(companies.begin(), companies.end(), cmp);\n\n    auto ans = placeAds(companies);\n    for (auto& [a,b,c,d] : ans)\n        cout << a << ' ' << b << ' ' << c << ' ' << d << '\\n';\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nconst int MAXN = 50;\nvector<vector<int>> tiles(MAXN, vector<int>(MAXN));\nvector<vector<int>> points(MAXN, vector<int>(MAXN));\nvector<pair<int, int>> dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};  // U, D, L, R\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nbool inside(int x, int y) { return x >= 0 && x < MAXN && y >= 0 && y < MAXN; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n    \n    for(int i=0; i<MAXN; ++i) for(int j=0; j<MAXN; ++j) cin >> tiles[i][j];\n    for(int i=0; i<MAXN; ++j) for(int j=0; j<MAXN; ++j) cin >> points[i][j];\n\n    auto solve = [&]() {\n        int best_score = 0;\n        string best_path;\n        vector<vector<bool>> visited(MAXN, vector<bool>(MAXN, false));\n        set<int> used_tiles;\n        visited[si][sj] = true;\n        used_tiles.insert(tiles[si][sj]);\n        string current_path;\n        int current_x = si, current_y = sj;\n        int current_score = points[si][sj];\n\n        auto dfs = [&](auto &&self, int x, int y, int score) -> void {\n            if (score > best_score) {\n                best_score = score;\n                best_path = current_path;\n            }\n            \n            vector<pair<int, int>> possible_moves;\n            for (auto& [dx, dy] : dirs) {\n                int nx = x + dx, ny = y + dy;\n                if (!inside(nx, ny) || visited[nx][ny] || used_tiles.count(tiles[nx][ny])) continue;\n                int nxt_score = score + points[nx][ny];\n                possible_moves.emplace_back(nxt_score, make_pair(nx, ny));\n            }\n\n            if (possible_moves.empty()) return;\n            shuffle(possible_moves.begin(), possible_moves.end(), rng);\n\n            for (auto [_, coord] : possible_moves) {\n                auto [nx, ny] = coord;\n                visited[nx][ny] = true;\n                used_tiles.insert(tiles[nx][ny]);\n                \n                if (nx < x) current_path += 'U';\n                if (nx > x) current_path += 'D';\n                if (ny < y) current_path += 'L';\n                if (ny > y) current_path += 'R';\n                \n                int new_score = score + points[nx][ny];\n                self(self, nx, ny, new_score);\n                \n                if (nx < x) current_path.pop_back();  // Undo\n                if (nx > x) current_path.pop_back();\n                if (ny < y) current_path.pop_back();\n                if (ny > y) current_path.pop_back();\n                \n                visited[nx][ny] = false;\n                used_tiles.erase(tiles[nx][ny]);\n            }\n        };\n\n        dfs(dfs, current_x, current_y, current_score);\n\n        cout << best_path << endl;\n    };\n\n    solve();\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n\nusing namespace std;\n\nint dr[] = { -1, 1, 0, 0 };\nint dc[] = { 0, 0, -1, 1 };\nchar dir[] = { 'U', 'D', 'L', 'R' };\n\nvoid solve() {\n    srand(time(NULL));\n    for (int q = 0; q < 1000; ++q) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        string path;\n        while (si != ti || sj != tj) {\n            if (rand() % 10 < 3) { // Random chance to pick a suboptimal step\n                int d = rand() % 4;\n                int ni = si + dr[d], nj = sj + dc[d];\n                if (ni >= 0 && ni < 30 && nj >= 0 && nj < 30 && path.empty() || ni != path.back()-'U'+si || nj != path.back()-'L'+sj) {\n                    path += dir[d];\n                    si = ni; sj = nj;\n                    continue;\n                }\n            }\n            // Prioritize horizontal moves\n            if (sj < tj && (path.empty() || path.back() != 'L')) {\n                path += 'R';\n                ++sj;\n            } else if (sj > tj && (path.empty() || path.back() != 'R')) {\n                path += 'L';\n                --sj;\n            } else if (si < ti && (path.empty() || path.back() != 'U')) {\n                path += 'D';\n                ++si;\n            } else if (si > ti && (path.empty() || path.back() != 'D')) {\n                path += 'U';\n                --si;\n            } else {\n                // If stuck, move randomly\n                int index = rand() % 4;\n                path += dir[index];\n                si += dr[index];\n                sj += dc[index];\n            }\n        }\n        cout << path << endl;\n        int result;\n        cin >> result;\n    }\n}\n\nint main() {\n    solve();\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Entry {\n    char ch;\n    int freq;\n    bool operator<(const Entry& other) const {\n        return freq > other.freq || (freq == other.freq && ch < other.ch);\n    }\n};\n\nvector<string> solve(int N, vector<string>& S) {\n    vector<vector<map<char, int>>> freq(N, vector<map<char, int>>(N));\n\n    // Compute frequency of each char in possible subsequences\n    for (auto& s : S) {\n        int len = s.size();\n        for (int start = 0; start < N; ++start) {\n            for (int p = 0; p < len; ++p) {\n                // Horizontal (rows)\n                freq[start][(p % N)][s[p]]++;\n                // Vertical (cols)\n                freq[(p % N)][start][s[p]]++;\n            }\n        }\n    }\n\n    // Build initial matrix based on frequency\n    vector<string> mat(N, string(N, '.'));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            vector<Entry> entries;\n            for (char c = 'A'; c <= 'H'; ++c) {\n                entries.push_back({c, freq[i][j][c]});\n            }\n            sort(entries.begin(), entries.end());\n            mat[i][j] = entries[0].ch;\n        }\n    }\n\n    auto can_place = [&](int x, int y, const string& s, bool vert) {\n        for (size_t idx = 0; idx < s.size(); ++idx) {\n            int i = vert ? (x + idx) % N : x;\n            int j = vert ? y : (y + idx) % N;\n            if (mat[i][j] != '.' && mat[i][j] != s[idx]) return false;\n        }\n        return true;\n    };\n\n    auto place = [&](int x, int y, const string& s, bool vert) {\n        for (size_t idx = 0; idx < s.size(); ++idx) {\n            int i = vert ? (x + idx) % N : x;\n            int j = vert ? y : (y + idx) % N;\n            if (mat[i][j] == '.') mat[i][j] = s[idx];\n        }\n    };\n\n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(S.begin(), S.end(), gen);\n    sort(S.rbegin(), S.rend(), [](const string& a, const string& b) {\n        return a.size() > b.size();\n    });\n\n    for (auto& s : S) {\n        for (int t = 0; t < 1; ++t) {\n            bool placed = false;\n            for (int i = 0; i < N && !placed; ++i) {\n                for (int j = 0; j < N && !placed; ++j) {\n                    bool pick_vert = (t == 0 && gen() % 2) || (t == 1 && (gen() % 4 == 0));\n                    if (can_place(i, j, s, pick_vert)) {\n                        place(i, j, s, pick_vert);\n                        placed = true;\n                    } else if (can_place(i, j, s, !pick_vert)) {\n                        place(i, j, s, !pick_vert);\n                        placed = true;\n                    }\n                }\n            }\n        }\n    }\n\n    // Post-processing to fill empty spots intelligently\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (mat[i][j] != '.') continue;\n            set<char> valid;\n            for (char c = 'A'; c <= 'H'; ++c) {\n                bool valid_horiz = true, valid_vert = true;\n                for (int k = 0; k < 1; ++k) {\n                    int ni = (i + k) % N;\n                    int nj = (j + k) % N;\n                    if (nj < N-1 && mat[ni][nj+1] != '.' && mat[ni][nj+1] != c) valid_horiz = false;\n                    if (ni < N-1 && mat[ni+1][nj] != '.' && mat[ni+1][nj] != c) valid_vert = false;\n                }\n                if (valid_horiz || valid_vert) valid.insert(c);\n            }\n            mat[i][j] = valid.empty() ? 'A' : *valid.begin();\n        }\n    }\n    \n    return mat;\n}\n\nint main() {\n    int N = 20, M;\n    cin >> N >> M;\n    vector<string> S(M);\n    for (auto& s : S) cin >> s;\n    vector<string> ans = solve(N, S);\n    \n    for (auto& row : ans) cout << row << endl;\n    return 0;\n}","ahc005":"#include <algorithm>\n#include <random>\n#include <vector>\n#include <cmath>\n#include <iostream>\n#include <tuple>\n\nusing namespace std;\nmt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());\n\nstruct State {\n    int N;\n    vector<string> grid;\n    int si, sj;\n    vector<pair<int, int>> path;\n    long long cost = 0;\n    State(int _N, vector<string> _grid, int _si, int _sj) \n        : N(_N), grid(_grid), si(_si), sj(_sj) {\n        path.push_back({si, sj});\n    }\n\n    void compute_cost() {\n        cost = 0;\n        for (size_t i = 1; i < path.size(); ++i) {\n            int x1 = path[i-1].first, y1 = path[i-1].second;\n            int x2 = path[i].first, y2 = path[i].second;\n            if (x1 == x2) cost += abs(y2 - y1) * (grid[x1][max(y1, y2)] - '0');\n            else cost += abs(x2 - x1) * (grid[max(x1, x2)][y1] - '0');\n        }\n    }\n\n    bool covers_all() {\n        vector<bool> rows(N, false), cols(N, false);\n        for (auto &[x, y] : path) {\n            rows[x] = true;\n            cols[y] = true;\n        }\n        for (int i = 0; i < N; ++i) {\n            if (rows[i] || cols[i]) continue;\n            bool has_road = false;\n            for (int j = 0; j < N; ++j) if (grid[i][j] != '#') has_road = true;\n            if (has_road) return false;\n            for (int j = 0; j < N; ++j) if (grid[j][i] != '#') has_road = true;\n            if (has_road) return false;\n        }\n        return true;\n    }\n\n    void anneal(long long T, int iterations) {\n        uniform_real_distribution<> dist(0.0, 1.0);\n        compute_cost();\n        long long current_cost = cost;\n        auto best_state = *this;\n        long long best_cost = current_cost;\n\n        for (int step = 0; step < iterations; ++step) {\n            double t = T * pow(0.999, step);\n            auto neighbor = *this;\n            int pos = uniform_int_distribution<>(1, path.size()-2)(rng);\n            swap(neighbor.path[pos], neighbor.path[pos+1]);\n            neighbor.compute_cost();\n            \n            if (neighbor.cost < current_cost || dist(rng) < exp((current_cost - neighbor.cost) / t)) {\n                swap(path, neighbor.path);\n                current_cost = neighbor.cost;\n                if (current_cost < best_cost) {\n                    best_cost = current_cost;\n                    best_state = *this;\n                }\n            }\n        }\n        *this = best_state;\n    }\n};\n\nstring solve(int N, int si, int sj, vector<string>& grid) {\n    State state(N, grid, si, sj);\n    vector<int> rows, cols;\n\n    for (int i = 0; i < N; ++i) {\n        bool has_road = false;\n        for (int j = 0; j < N; ++j) if (grid[i][j] != '#') has_road = true;\n        if (has_road) rows.push_back(i);\n    }\n    for (int j = 0; j < N; ++j) {\n        bool has_road = false;\n        for (int i = 0; i < N; ++i) if (grid[i][j] != '#') has_road = true;\n        if (has_road) cols.push_back(j);\n    }\n\n    for (int r : rows) {\n        if (state.path.back().first != r) state.path.emplace_back(r, state.path.back().second);\n        state.path.emplace_back(r, sj);\n    }\n    for (int c : cols) {\n        if (state.path.back().second != c) state.path.emplace_back(state.path.back().first, c);\n    }\n    state.path.push_back({si, sj});\n\n    if (!state.covers_all()) return \"ERROR\";\n    state.anneal(1e13, 1e4);\n\n    string route;\n    int px = si, py = sj;\n    for (auto &[x, y] : state.path) {\n        if (x < px) while (px > x) { route += 'U'; px--; }\n        if (x > px) while (px < x) { route += 'D'; px++; }\n        if (y < py) while (py > y) { route += 'L'; py--; }\n        if (y > py) while (py < y) { route += 'R'; py++; }\n    }\n    return route;\n}\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (auto &row : grid) cin >> row;\n    cout << solve(N, si, sj, grid) << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconstexpr int INF = 1e9;\n\nstruct Task {\n    vector<int> skills;\n    vector<int> children;\n    int done_day = -1;\n    int indeg = 0;\n    bool started = false;\n};\n\nint N = 1000, M = 20;\nvector<Task> tasks;\nvector<vector<int>> finished_tasks; // finished_tasks[member] = list of tasks\nvector<array<int, 1024>> skill_estimates(M, array<int, 1024>{});\n\nvoid print_flush(const vector<pair<int, int>>& assignments) {\n    if (assignments.empty()) {\n        cout << \"0\\n\";\n    } else {\n        cout << assignments.size();\n        for (auto& [a, b] : assignments) cout << ' ' << a+1 << ' ' << b+1;\n        cout << '\\n';\n    }\n    fflush(stdout);\n}\n\nint estimate_time(int member, int task_id) {\n    int sum_excess = 0;\n    for (size_t k = 0; k < tasks[task_id].skills.size(); ++k) {\n        int req = tasks[task_id].skills[k];\n        int est = skill_estimates[member][k];\n        if (req > est) sum_excess += req - est;\n    }\n    return sum_excess == 0 ? 1 : max(1, sum_excess - 3 + (rand() % 7));\n}\n\nvoid update_skills(int member, int task_id, int days) {\n    auto& skills = skill_estimates[member];\n    int excess = max(1, days - 3 + (rand() % 7)) - 1;\n    for (size_t k = 0; k < tasks[task_id].skills.size(); ++k) {\n        int req = tasks[task_id].skills[k];\n        if (req > skills[k]) skills[k] = min(req, skills[k] + excess);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int K, R;\n    cin >> N >> M >> K >> R;\n    tasks.resize(N);\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            int d;\n            cin >> d;\n            tasks[i].skills.push_back(d);\n        }\n    }\n    \n    vector<vector<int>> deps(N);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        deps[u].push_back(v);\n        tasks[v].indeg++;\n    }\n    \n    priority_queue<pair<int, int>> pq; // (completion day estimate, task_id)\n    for (int i = 0; i < N; ++i) if (tasks[i].indeg == 0) pq.emplace(0, i);\n    \n    vector<bool> member_busy(M, false);\n    \n    int day = 1;\n    while (day <= 2000) {\n        vector<pair<int, int>> assignments;\n        for (int m = 0; m < M && !pq.empty(); ++m) {\n            while (!pq.empty() && tasks[pq.top().second].started) pq.pop();\n            if (pq.empty()) break;\n            int t = pq.top().second;\n            pq.pop();\n            \n            assignments.emplace_back(m, t);\n            tasks[t].started = true;\n        }\n        \n        print_flush(assignments);\n        \n        string input;\n        getline(cin >> ws, input);\n        if (input == \"-1\") break;\n        \n        istringstream iss(input);\n        int n;\n        iss >> n;\n        for (int _ = 0; _ < n; ++_) {\n            int m;\n            iss >> m;\n            --m;\n            \n            if (!member_busy[m]) {\n                int task = finished_tasks[m].back();\n                finished_tasks[m].pop_back();\n                tasks[task].done_day = day;\n                \n                int days_taken = day - tasks[task].started_day;\n                update_skills(m, task, days_taken);\n                \n                for (int child : deps[task]) {\n                    --tasks[child].indeg;\n                    if (tasks[child].indeg == 0) {\n                        pq.emplace(-estimate_time(m, child), child);\n                    }\n                }\n            }\n        }\n        \n        for (auto& [m, t] : assignments) {\n            if (!tasks[t].started) finished_tasks[m].push_back(t);\n            member_busy[m] = !tasks[t].started;\n            tasks[t].started_day = day;\n        }\n        \n        day++;\n    }\n    \n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Order {\n    int a, b, c, d;\n};\n\nvector<pair<int,int>> best_path;\nvector<int> chosen;\n\nint dist(int x1, int y1, int x2, int y2) {\n    return abs(x1-x2) + abs(y1-y2);\n}\n\nvector<pair<int, int>> construct_route() {\n    vector<pair<int, int>> path{{400, 400}};\n    for (int i : chosen) {\n        int a = orders[i].a, b = orders[i].b;\n        int c = orders[i].c, d = orders[i].d;\n        \n        int mn_cost = INT_MAX, best_pos = 0;\n        for (int j = 0; j < (int)path.size(); ++j) {\n            vector<pair<int, int>> tmp_path = path;\n            tmp_path.insert(tmp_path.begin() + j + 1, {{a, b}, {c, d}});\n            \n            ll cost = 0;\n            for (int k = 1; k < (int)tmp_path.size(); ++k) {\n                cost += dist(tmp_path[k-1].first, tmp_path[k-1].second, tmp_path[k].first, tmp_path[k].second);\n            }\n            if (cost < mn_cost) {\n                mn_cost = cost;\n                best_pos = j + 1;\n            }\n        }\n        path.insert(path.begin() + best_pos, {{a, b}, {c, d}});\n    }\n    path.push_back({400, 400});\n    return path;\n}\n\nint main() {\n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; ++i) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n    }\n    \n    // Score heuristic: prioritize close orders\n    auto cmp = [&](int lhs, int rhs) {\n        int dist1 = dist(400, 400, orders[lhs].a, orders[lhs].b) \n                  + dist(orders[lhs].c, orders[lhs].d, 400, 400);\n        int dist2 = dist(400, 400, orders[rhs].a, orders[rhs].b)\n                  + dist(orders[rhs].c, orders[rhs].d, 400, 400);\n        return dist1 < dist2;\n    };\n    \n    // Initialize with heuristic\n    vector<int> ids(1000); iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(), cmp);\n    \n    vector<int> current_orders;\n    ll current_cost = 0;\n    priority_queue<pair<ll, int>> pq;\n    \n    for (int i = 0; i < 1000; ++i) {\n        pq.emplace(-dist(400, 400, orders[ids[i]].a, orders[ids[i]].b) \n                     - dist(orders[ids[i]].c, orders[ids[i]].d, 400, 400),\n                   ids[i]);\n    }\n    \n    while (chosen.size() < 50) {\n        auto [cost, id] = pq.top(); pq.pop();\n        chosen.push_back(id);\n        \n        best_path = construct_route();\n        ll total_cost = 0;\n        for (int i = 1; i < (int)best_path.size(); ++i) {\n            total_cost += dist(best_path[i-1].first, best_path[i-1].second,\n                               best_path[i].first, best_path[i].second);\n        }\n        current_cost = total_cost;\n    }\n    \n    cout << chosen.size();\n    for (auto id : chosen) cout << \" \" << id + 1;\n    cout << \"\\n\";\n    cout << best_path.size();\n    for (auto &[x, y] : best_path) cout << \" \" << x << \" \" << y;\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\nusing boost::disjoint_sets;\nusing boost::disjoint_sets_with_storage;\n\nstruct Edge {\n    int u, v, min_len, max_len, len;\n    double e_val;\n    bool operator<(const Edge& r) const {\n        if (max_len != r.max_len) return max_len < r.max_len;\n        return e_val < r.e_val; // Prefer lower expected value on tie\n    }\n};\n\nint main() {\n    const int N = 400, M = 1995;\n    vector<pair<int, int>> coords(N);\n    for (int i = 0; i < N; ++i) scanf(\"%d %d\", &coords[i].first, &coords[i].second);\n    \n    vector<Edge> edges(M);\n    auto calc_dist = [&](int u, int v) -> int {\n        int dx = coords[u].first - coords[v].first;\n        int dy = coords[u].second - coords[v].second;\n        return round(sqrt(dx*dx + dy*dy));\n    };\n    \n    for (int i = 0; i < M; ++i) {\n        scanf(\"%d %d\", &edges[i].u, &edges[i].v);\n        int d = calc_dist(edges[i].u, edges[i].v);\n        edges[i].min_len = d;\n        edges[i].max_len = 3 * d;\n        edges[i].e_val = (edges[i].min_len + edges[i].max_len) / 2.0;\n    }\n    \n    // Sort edges by (max_len ascending, then expected value ascending)\n    sort(edges.begin(), edges.end());\n    \n    vector<int> sorted_indices(M);\n    iota(sorted_indices.begin(), sorted_indices.end(), 0);\n    stable_sort(sorted_indices.begin(), sorted_indices.end(), [&](int i, int j) {\n        if (edges[i].max_len != edges[j].max_len) return edges[i].max_len < edges[j].max_len;\n        return edges[i].e_val < edges[j].e_val;\n    });\n\n    unordered_set<int> known_edges;\n    disjoint_sets<> uf(N);\n    int connected = N;\n    int idx = 0;\n    \n    auto in_order = [&]() mutable -> int {\n        while (idx < M && known_edges.contains(sorted_indices[idx])) ++idx;\n        return idx == M ? -1 : sorted_indices[idx];\n    };\n\n    for (int i = 0; i < M; ++i) {\n        int len;\n        scanf(\"%d\", &len);\n        edges[i].len = len;\n        \n        known_edges.insert(i);\n        int next_potential = in_order();\n        \n        if (next_potential == -1 || (uf.find_set(edges[i].u) != uf.find_set(edges[i].v) && len <= 2.5 * edges[next_potential].min_len)) {\n            // Accept if connects disconnected or within threshold of next candidate\n            if (uf.link(edges[i].u, edges[i].v)) --connected;\n            printf(\"1\\n\");\n            fflush(stdout);\n        } else {\n            printf(\"0\\n\");\n            fflush(stdout);\n        }\n        if (connected == 1) break; // Already connected\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing Point = pair<int, int>;\nconst int MAX_T = 300;\nconst int SIZE = 31;\nint cx[5] = { 0, -1, 1, 0, 0 }, cy[5] = { 0, 0, 0, -1, 1 };\nchar dir[] = \"UDLR\";\n\nstruct State {\n    Point pos;\n    int id;\n};\n\nvector<State> humans;\nvector<Point> pets;\nvector<vector<bool>> grid(SIZE, vector<bool>(SIZE, true));\nint n, m, turn = 0;\n\ninline bool valid(int x, int y) {\n    return x >= 1 && x <= 30 && y >= 1 && y <= 30;\n}\n\nvoid update_barriers(const string& actions) {\n    set<Point> new_blocks;\n    for (int i = 0; i < (int)actions.size(); ++i) {\n        if (actions[i] >= 'u' && actions[i] <= 'r') {\n            int dx = cx[actions[i] - 'u' + 1];\n            int dy = cy[actions[i] - 'u' + 1];\n            int nx = humans[i].pos.first + dx, ny = humans[i].pos.second + dy;\n            if (valid(nx, ny)) && !grid[nx][ny]) {\n                new_blocks.insert({nx, ny});\n            }\n        }\n    }\n    for (auto [x, y] : new_blocks) grid[x][y] = true;\n}\n\nbool has_adjacent_pet(int x, int y) {\n    for (int d = 1; d <= 4; ++d) {\n        int nx = x + cx[d], ny = y + cy[d];\n        if (valid(nx, ny)) && find(pets.begin(), pets.end(), Point(nx, ny)) != pets.end()) {\n            return true;\n        }\n    }\n    return false;\n}\n\nstring decide_actions() {\n    string result(m, '.');\n    map<Point, int> target_counts;\n\n    // Assign targets for fencing\n    for (int i = 0; i < m; ++i) {\n        int best_val = -1, choice = -1;\n        auto [x, y] = humans[i].pos;\n\n        for (int d = 1; d <= 4; ++d) {\n            int nx = x + cx[d], ny = y + cy[d];\n            if (valid(nx, ny) && !grid[nx][ny] && !has_adjacent_pet(nx, ny)) {\n                int adj_cnt = 0;\n                for (int k = 1; k <= 4; ++k) {\n                    if (valid(nx + cx[k], ny + cy[k]) && grid[nx + cx[k]][ny + cy[k]]) {\n                        adj_cnt++;\n                    }\n                }\n                if (adj_cnt > best_val) {\n                    best_val = adj_cnt;\n                    choice = d;\n                }\n            }\n        }\n        if (choice == -1) continue;\n        \n        int dx = cx[choice], dy = cy[choice];\n        result[i] = dir[choice - 1] + 'a' - 'A';\n        grid[x + dx][y + dy] = true;\n        target_counts[{x+dx, y+dy}]++;\n    }\n\n    // If early turns, fill in remaining with moves\n    if (turn < 12) {\n        int row = 1 + (turn / 10) * 5;\n        for (int i = 0; i < m; ++i) {\n            if (result[i] == '.') {\n                int col = 1 + (turn % 10) * 3;\n                while (!valid(row, col) || grid[row][col]) col++;\n                result[i] = (col < humans[i].pos.second ? 'L' : 'R');\n            }\n        }\n    }\n    \n    // Reset after updating (ensures correctness)\n    for (int i = 0; i <= 30; ++i) for (int j = 0; j <= 30; ++j) grid[i][j] = false;\n    return result;\n}\n\nvoid move_humans(const string& actions) {\n    for (int i = 0; i < m; ++i) {\n        if (actions[i] == '.') continue;\n        char move = tolower(actions[i]);\n        int dir_idx = find(begin(dir), end(dir), move) - begin(dir);\n        int x = humans[i].pos.first + cx[dir_idx + 1];\n        int y = humans[i].pos.second + cy[dir_idx + 1];\n        if (valid(x, y) && !grid[x][y]) {\n            humans[i].pos = {x, y};\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    \n    // Read initial pets\n    cin >> n;\n    pets.resize(n);\n    for (auto& p : pets) {\n        int t; cin >> p.first >> p.second >> t;\n    }\n    // Read humans\n    cin >> m;\n    humans.resize(m);\n    for (int i = 0; i < m; ++i) {\n        cin >> humans[i].pos.first >> humans[i].pos.second;\n        humans[i].id = i + 1;\n    }\n\n    while (turn < MAX_T) {\n        string actions = decide_actions();\n        cout << actions << endl;\n        \n        string dummy;\n        for (int i = 0; i < n; ++i) cin >> dummy;\n\n        move_humans(actions);\n        update_barriers(actions);\n        turn++;\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n    \n    vector<string> h(20), v(19);\n    for (auto& s : h) cin >> s;\n    for (auto& s : v) cin >> s;\n    \n    auto inside = [](int x, int y) {\n        return 0 <= x && x < 20 && 0 <= y && y < 20;\n    };\n    \n    vector<array<int, 3>> dirs = {{{-1, 0, 'U'}, {1, 0, 'D'}, {0, -1, 'L'}, {0, 1, 'R'}}};\n    \n    auto bfs = [&]() -> string {\n        queue<Pos> q;\n        vector<vector<bool>> vis(20, vector<bool>(20, false));\n        vector<vector<char>> parent(20, vector<char>(20, 0));\n        q.push({si, sj});\n        vis[si][sj] = true;\n        \n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            if (x == ti && y == tj) {\n                string path;\n                while (x != si || y != sj) {\n                    char c = parent[x][y];\n                    if (c == 'U') { x++; path.push_back('D'); }\n                    else if (c == 'D') { x--; path.push_back('U'); }\n                    else if (c == 'L') { y++; path.push_back('R'); }\n                    else if (c == 'R') { y--; path.push_back('L'); }\n                }\n                reverse(path.begin(), path.end());\n                return path;\n            }\n            for (const auto& d : dirs) {\n                int nx = x + d[0], ny = y + d[1];\n                if (!inside(nx, ny) || vis[nx][ny]) continue;\n                bool blocked = false;\n                if (d[2] == 'R' && h[x][y] == '1') blocked = true;\n                if (d[2] == 'D' && v[x][y] == '1') blocked = true;\n                if (d[2] == 'L' && (y == 0 || h[x][y-1] == '1')) blocked = true;\n                if (d[2] == 'U' && (x == 0 || v[x-1][y] == '1')) blocked = true;\n                if (!blocked) {\n                    parent[nx][ny] = d[2];\n                    vis[nx][ny] = true;\n                    q.push({nx, ny});\n                }\n            }\n        }\n        return \"\";\n    };\n    \n    string base = bfs();\n    string result;\n    for (int i=0; i<5 && result.size() + base.size() <= 200; ++i) {\n        result += base;\n    }\n    cout << (result.empty() ? string(200, 'D') : result.substr(0,200)) << '\\n';\n}","ahc010":"#include <bits/stdc++.h>\n#include <random>\nusing namespace std;\n\nconst int N = 30;\nint T[N][N], R[N][N], bestR[N][N];\nint dirs[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1},\n};\nint di[4] = {0, -1, 0, 1}, dj[4] = {-1, 0, 1, 0};\n\nmt19937 mt(time(nullptr));\n\nlong long eval(int rotate[N][N]) {\n    int tcopy[N][N];\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        tcopy[i][j] = rotate[i][j];\n        while (tcopy[i][j] < 0) tcopy[i][j] += 8;\n        tcopy[i][j] %= 8;\n    }\n\n    vector<int> lengths;\n    bool vis[N][N][4] = {};\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        for (int d=0; d<4; ++d) {\n            if (vis[i][j][d]) continue;\n            vector<tuple<int, int, int>> path;\n            int ci=i, cj=j, cd=d, len=0;\n            while (true) {\n                path.emplace_back(ci, cj, cd);\n                vis[ci][cj][cd] = true;\n                int nd = dirs[tcopy[ci][cj]][cd];\n                if (nd == -1) break;\n                ci += di[nd];\n                cj += dj[nd];\n                if (ci < 0 || ci >= N || cj < 0 || cj >= N) break;\n                cd = (nd + 2) % 4;\n                if (vis[ci][cj][cd]) {\n                    for (auto [pi, pj, pd] : path) {\n                        if (pi == ci && pj == cj && pd == cd) {\n                            len = path.size() - (path.end() - find(path.begin(), path.end(), make_tuple(pi, pj, pd)));\n                            break;\n                        }\n                    }\n                    break;\n                }\n            }\n            if (len > 0) {\n                lengths.push_back(len);\n                for (auto& [pi, pj, pd] : path) vis[pi][pj][pd] = true;\n            }\n        }\n    }\n    sort(lengths.rbegin(), lengths.rend());\n    long long l1 = (lengths.size() > 0) ? lengths[0] : 0;\n    long long l2 = (lengths.size() > 1) ? lengths[1] : 0;\n    return l1 * l2;\n}\n\nlong long calc() {\n    static int rotate[N][N];\n    memcpy(rotate, R, sizeof(rotate));\n    long long ans = 0;\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        long long best = 0;\n        for (int k=0; k<4; ++k) {\n            rotate[i][j] = (rotate[i][j] + 1) % 8;\n            long long score = eval(rotate);\n            if (score > best) best = score;\n        }\n        rotate[i][j] = (rotate[i][j] - best + 8) % 8;\n        ans += best;\n    }\n    return ans;\n}\n\nint main() {\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        char c; cin >> c;\n        T[i][j] = c - '0';\n    }\n    memcpy(R, T, sizeof(R));\n\n    auto update_ans = [&]() {\n        long long cur_score = eval(bestR);\n        long long score = eval(R);\n        if (score > cur_score) memcpy(bestR, R, sizeof(bestR));\n    };\n\n    const double START_TEMP = 1e6, END_TEMP = 1e-3, RATE = 0.9999;\n    double temp = START_TEMP;\n    long long cur_score = eval(R), best_score = cur_score;\n    while (temp > END_TEMP) {\n        for (int _=0; _<max(1, N*N * temp / START_TEMP); ++_) {\n            int i = mt() % N, j = mt() % N;\n            int prev = R[i][j];\n\n            long long best_rotate = -1;\n            long long best_gain = -1e18;\n            vector<long long> scores(4);\n            for (int delta=0; delta<4; ++delta) {\n                R[i][j] = (prev + delta) % 8;\n                scores[delta] = eval(R);\n                if (scores[delta] - cur_score > best_gain) {\n                    best_gain = scores[delta] - cur_score;\n                    best_rotate = delta;\n                }\n            }\n\n            if (best_rotate == -1 || exp((scores[best_rotate] - cur_score) / temp) < (mt() % 10000)/10000.) {\n                int rnd = mt() % 4;\n                if (scores[rnd] <= cur_score && exp((scores[rnd] - cur_score) / temp) < (mt() % 10000)/10000.) {\n                    R[i][j] = prev;\n                    continue;\n                }\n                best_rotate = rnd;\n            }\n\n            R[i][j] = (prev + best_rotate) % 8;\n            cur_score = scores[best_rotate];\n            update_ans();\n        }\n        best_score = max(best_score, cur_score);\n        temp *= RATE;\n    }\n\n    memcpy(R, bestR, sizeof(R));\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        int diff = 0;\n        while ((bestR[i][j] - T[i][j] - diff) % 8 != 0 && (bestR[i][j] - T[i][j] - diff) % 8 != 4) ++diff;\n        while (diff < 0) diff += 8;\n        cout << diff % 4;\n    }\n    cout << endl;\n}","ahc011":"#include <algorithm>\n#include <deque>\n#include <iostream>\n#include <numeric>\n#include <queue>\n#include <vector>\nusing namespace std;\nusing ll = long long;\n\n#define rep(i, n) for (int i = 0; i < n; i++)\n\nint n, e_x, e_y;\nvector<vector<int>> a;\n\nbool in_grid(int x, int y) { return 0 <= x && x < n && 0 <= y && y < n; }\n\nbool valid(int x, int y) { return in_grid(x, y) && a[x][y] != 0; }\n\nint cnt_connect(int x, int y) {\n  int c = (x == e_x && y == e_y);\n  if (valid(x + 1, y)) c++;\n  if (valid(x, y - 1)) c++;\n  if (valid(x, y + 1)) c++;\n  if (valid(x - 1, y)) c++;\n  return c - 1;\n}\n\npair<int, int> find_target() {\n  rep(i, n) rep(j, n) if (a[i][j] == 0) return {i, j};\n  return {-1, -1};\n}\n\npair<int, pair<int, int>> find_tile() {\n  int mx = -1;\n  pair<int, pair<int, int>> res;\n  rep(x, n) rep(y, n) {\n    if (!valid(x, y)) continue;\n    int nc = __builtin_popcount(a[x][y]);\n    int cc = cnt_connect(x, y);\n    if (nc - 1 <= cc) continue;\n    int score = nc - cc;\n    if (score > mx || (score == mx && rand() % 2 == 0)) {\n      mx = score;\n      res = {a[x][y], {x, y}};\n    }\n  }\n  return res;\n}\n\nstring generate_path(int sx, int sy, int tx, int ty) {\n  deque<pair<int, int>> qb, qe;\n  vector<vector<int>> db(n, vector<int>(n, -1)), de(n, vector<int>(n, -1));\n  qb.push_back({sx, sy});\n  qe.push_back({tx, ty});\n  db[sx][sy] = 0;\n  de[tx][ty] = 0;\n  while (!qb.empty() || !qe.empty()) {\n    auto bfs = [&](deque<pair<int, int>> &q, vector<vector<int>> &d, deque<pair<int, int>> &oq, vector<vector<int>> &od) {\n      pair<int, int> cur = q.front();\n      q.pop_front();\n      int x = cur.first, y = cur.second;\n      if (od[x][y] != -1) {\n        string pathb, pathe;\n        while (cur.first != sx || cur.second != sy) {\n          pathb += (cur.first == x + 1 && cur.second == y) ? 'U'\n                   : (cur.first == x - 1 && cur.second == y) ? 'D'\n                   : (cur.first == x && cur.second == y + 1) ? 'L'\n                                                               : 'R';\n          cur = {db[cur.first][cur.second] / n, db[cur.first][cur.second] % n};\n        }\n        while (cur.first != tx || cur.second != ty) {\n          pathe += (od[cur.first][cur.second] == x + 1 && od[cur.first][cur.second] / n == y) ? 'D'\n               : (od[cur.first][cur.second] == x - 1 && od[cur.first][cur.second] / n == y) ? 'U'\n               : (od[cur.first][cur.second] == x && od[cur.first][cur.second] / n == y + 1) ? 'R'\n                                                                                              : 'L';\n          cur = {od[cur.first][cur.second], od[cur.first][cur.second] / n};\n        }\n        reverse(pathb.begin(), pathb.end());\n        string ans = pathb + pathe;\n        while (ans.size() > 1 && (ans.back() == 'U' && ans[ans.size() - 2] == 'D' || ans.back() == 'D' && ans[ans.size() - 2] == 'U' ||\n                                   ans.back() == 'L' && ans[ans.size() - 2] == 'R' || ans.back() == 'R' && ans[ans.size() - 2] == 'L')) {\n          ans.pop_back();\n          ans.pop_back();\n        }\n        return ans;\n      }\n      static const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};\n      rep(i, 4) {\n        int nx = x + dx[i], ny = y + dy[i];\n        if (in_grid(nx, ny) && d[nx][ny] == -1 && a[nx][ny] != 0) {\n          d[nx][ny] = d[x][y] * n + ny;\n          q.push_back({nx, ny});\n        }\n      }\n      return \"\";\n    };\n    if (!qb.empty()) {\n      auto res = bfs(qb, db, qe, de);\n      if (!res.empty()) return res;\n    }\n    if (!qe.empty()) {\n      auto res = bfs(qe, de, qb, db);\n      if (!res.empty()) return res;\n    }\n  }\n  return \"\";\n}\n\nint main() {\n  cin >> n;\n  int T;\n  cin >> T;\n  a.resize(n, vector<int>(n));\n  rep(i, n) rep(j, n) {\n    char c;\n    cin >> c;\n    if (c >= 'a') a[i][j] = c - 'a' + 10;\n    else a[i][j] = c - '0';\n  }\n  string ans;\n  auto [ex, ey] = find_target();\n  while (true) {\n    auto [val, pos] = find_tile();\n    if (val == -1) break;\n    auto [x, y] = pos;\n    if (cnt_connect(x, y) == __builtin_popcount(val) - 1) continue;\n    int tx = ex, ty = ey;\n    ex = x;\n    ey = y;\n    a[tx][ty] = val;\n    a[x][y] = 0;\n    ans += generate_path(tx, ty, x, y);\n  }\n  cout << ans << endl;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    vector<array<int, 4>> lines;\n    int offset = 20000; // sufficiently large to cover all possibilities\n    \n    // Generate vertical lines: vary x, fix y\n    for (int x = -15000; x <= 15000; x += 5000) {\n        if (x != 0) { // skip previously redundant x=0\n            lines.push_back({x, -offset, x, offset});\n        }\n    }\n    \n    // Generate horizontal lines: vary y, fix x\n    for (int y = -15000; y <= 15000; y += 5000) {\n        if (y != 0) { // skip redundant y=0\n            lines.push_back({-offset, y, offset, y});\n        }\n    }\n    \n    // Add diagonal lines\n    lines.push_back({-offset, 0, offset, 0});\n    lines.push_back({0, -offset, 0, offset});\n    lines.push_back({-offset, -offset, offset, offset});\n    lines.push_back({-offset, offset, offset, -offset});\n    \n    cout << lines.size() << \"\\n\";\n    for (const auto& line : lines) {\n        cout << line[0] << \" \" << line[1] << \" \" << line[2] << \" \" << line[3] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nvector<vector<bool>> visited;\nvector<tuple<int, int, int, int, int, int>> ans;\nint N, M;\n\nbool validate(int x1, int y1, int x2, int y2, int x3, int y3) {\n    if (!(0 <= min({x1, x2, x3}) && max({x1, x2, x3}) < N)) return false;\n    if (!(0 <= min({y1, y2, y3}) && max({y1, y2, y3}) < N)) return false;\n    if (x1 == x2 || x2 == x3 || x3 == x1 || y1 == y2 || y2 == y3 || y3 == y1)\n        return false;\n    return true;\n}\n\nint main() {\n    cin >> N >> M;\n    visited.assign(N, vector<bool>(N, false));\n    queue<pair<int, int>> q;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        visited[x][y] = true;\n        q.emplace(x, y);\n    }\n\n    int total_dots = M;\n    while (!q.empty() && (double)total_dots / N / N < 0.08) { // Adjust target fill\n        auto [x, y] = q.front(); q.pop();\n        // Search in a limited radius to balance coverage and time\n        for (int dx = -5; dx <= 5; ++dx) for (int dy = -5; dy <= 5; ++dy) {\n            if (abs(dx) + abs(dy) > 9) continue; // Stay within bounded steps\n            int nx = x + dx, ny = y + dy;\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N || visited[nx][ny]) continue;\n            for (int d = 1; d <= 5; ++d) {\n                if (validate(nx, ny, x, y, x, y+d, x+d, y)) {\n                    if (!visited[x][y+d] || !visited[x+d][y]) break;\n                    visited[nx][ny] = true;\n                    ans.emplace(nx, ny, x, y, x, y+d, x+d, y);\n                    q.emplace(nx, ny);\n                    total_dots++;\n                    goto next_point;\n                }\n                if (validate(nx, ny, x, y, x, y-d, x-d, y)) {\n                    if (!visited[x][y-d] || !visited[x-d][y]) break;\n                    visited[nx][ny] = true;\n                    ans.emplace(nx, ny, x, y, x, y-d, x-d, y);\n                    q.emplace(nx, ny);\n                    total_dots++;\n                    goto next_point;\n                }\n            }\n        }\n    next_point:;\n    }\n\n    cout << ans.size() << endl;\n    for (auto &[x1, y1, x2, y2, x3, y3] : ans)\n        cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << ' '\n             << x3 << ' ' << y3 << ' ' << (x3+y2-x2) << ' ' << (x2+y3-x3) << endl;\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int SIZE = 10;\nvector<vector<int>> grid(SIZE, vector<int>(SIZE, 0));\nvector<pair<int, int>> emptyCells;\nunordered_map<int, int> flavorCount = {{1,0}, {2,0}, {3,0}};\nunordered_map<int, pair<int, int>> centroids; // flavor -> centroid (sum_x, sum_y)\n\nvoid updateCenterMass(int flavor, int x, int y) {\n    flavorCount[flavor]++;\n    centroids[flavor].first += x;\n    centroids[flavor].second += y;\n}\n\nvoid applyGravity(char dir) {\n    if (dir == 'F') {\n        for (int col = 0; col < SIZE; ++col) {\n            for (int row = SIZE-2; row >= 0; --row) {\n                if (grid[row][col] && !grid[row+1][col]) {\n                    int r = row+1;\n                    while (r < SIZE && !grid[r][col]) r++;\n                    --r;\n                    swap(grid[r][col], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'B') {\n        // B direction logic\n        for (int col = 0; col < SIZE; ++col) {\n            for (int row = 1; row < SIZE; ++row) {\n                if (grid[row][col] && !grid[row-1][col]) {\n                    int r = row-1;\n                    while (r >= 0 && !grid[r][col]) r--;\n                    ++r;\n                    swap(grid[r][col], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'L') {\n        // L direction logic\n        for (int row = 0; row < SIZE; ++row) {\n            for (int col = 1; col < SIZE; ++col) {\n                if (grid[row][col] && !grid[row][col-1]) {\n                    int c = col-1;\n                    while (c >= 0 && !grid[row][c]) c--;\n                    ++c;\n                    swap(grid[row][c], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'R') {\n        // R direction logic\n        for (int row = 0; row < SIZE; ++row) {\n            for (int col = SIZE-2; col >= 0; --col) {\n                if (grid[row][col] && !grid[row][col+1]) {\n                    int c = col+1;\n                    while (c < SIZE && !grid[row][c]) c++;\n                    --c;\n                    swap(grid[row][c], grid[row][col]);\n                }\n            }\n        }\n    }\n}\n\nchar chooseDirection(int flavor, int x, int y) {\n    pair<int, int> bestDir = {0, 0};\n    int currentScore = 1e9;\n    for (auto& [dx, dy] : {pair{-1,0}, {1,0}, {0,-1}, {0,1}}) {\n        int nx = x + dx*(SIZE-1), ny = y + dy*(SIZE-1);\n        if (flavorCount[flavor] == 0) {\n            if (abs(nx) + abs(ny) < currentScore) {\n                currentScore = abs(nx) + abs(ny);\n                bestDir = {dx, dy};\n            }\n        } else {\n            auto cm = centroids[flavor];\n            int cx = cm.first / flavorCount[flavor];\n            int cy = cm.second / flavorCount[flavor];\n            int newScore = abs(nx - cx) + abs(ny - cy);\n            if (newScore < currentScore) {\n                currentScore = newScore;\n                bestDir = {dx, dy};\n            }\n        }\n    }\n    return bestDir == make_pair(-1, 0) ? 'F' : \n           bestDir == make_pair(1, 0) ? 'B' : \n           bestDir == make_pair(0, -1) ? 'L' : 'R';\n}\n\nint main() {\n    vector<int> flavors(100);\n    for (int& f : flavors) cin >> f;\n    \n    for (int t = 0; t < 100; ++t) {\n        emptyCells.clear();\n        for (int i = 0; i < SIZE; ++i)\n            for (int j = 0; j < SIZE; ++j)\n                if (!grid[i][j])\n                    emptyCells.emplace_back(i, j);\n        \n        int p; cin >> p;\n        --p;\n        auto [x, y] = emptyCells[p];\n        int f = flavors[t];\n        grid[x][y] = f;\n        updateCenterMass(f, x, y);\n\n        if (t == 99) break;\n        \n        char dir = chooseDirection(f, x, y);\n        cout << dir << '\\n';\n        cout.flush();\n        applyGravity(dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nstring generate_graph(int vertices, int edges) {\n    vector<bool> visited(vertices * (vertices-1) / 2, false);\n    string result(vertices * (vertices-1) / 2, '0');\n    \n    int current = 0;\n    for (int j=1; j<=edges; ++j) {\n        if (current >= visited.size()) current = 0; // Fallback to start if out\n        while (result[current] == '1' || visited[current]) {\n            ++current;\n            if (current >= visited.size()) current = 0;\n        }\n        result[current] = '1';\n        visited[current] = true;\n    }\n    return result;\n}\n\nint main() {\n    int M;\n    double eps;\n    cin >> M >> eps;\n    \n    const int N = 20;\n    cout << N << endl;\n    \n    vector<string> precomputed(M);\n    for (int i=0; i < M; ++i) {\n        precomputed[i] = generate_graph(N, i);\n        cout << precomputed[i] << endl;\n    }\n    cout << flush;\n    \n    // Precompute edge counts for faster lookup\n    vector<int> edges_counts(M);\n    for (int i=0; i < M; ++i) {\n        edges_counts[i] = count(precomputed[i].begin(), precomputed[i].end(), '1');\n    }\n    \n    for (int k=0; k < 100; ++k) {\n        string H;\n        cin >> H;\n        int current_edges = count(H.begin(), H.end(), '1');\n        \n        // Match using edge count distance\n        int best_match = 0;\n        int min_diff = INT_MAX;\n        for (int m=0; m < M; ++m) {\n            int diff = abs(current_edges - edges_counts[m]);\n            if (diff < min_diff) {\n                min_diff = diff;\n                best_match = m;\n            }\n        }\n        cout << best_match << endl << flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing i32 = int;\nusing i64 = long long;\nusing vi = vector<i32>;\nusing pii = pair<i32, i32>;\nusing Graph = vector<vector<pii>>;\nconstexpr i64 INF = 1e18;\n\npair<vector<i64>, vector<i64>> dijkstra(int start, const Graph& adj, int N) {\n    priority_queue<pii, vector<pii>, greater<pii>> pq;\n    vector<i64> dist(N, INF), cnt(N, 0);\n    dist[start] = 0;\n    cnt[start] = 1;\n    pq.emplace(0, start);\n\n    while (!pq.empty()) {\n        auto [current_dist, u] = pq.top();\n        pq.pop();\n        if (current_dist != dist[u]) continue;\n        for (auto [v, w] : adj[u]) {\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                cnt[v] = cnt[u];\n                pq.emplace(dist[v], v);\n            } else if (dist[u] + w == dist[v]) {\n                cnt[v] += cnt[u];\n            }\n        }\n    }\n    return {dist, cnt};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    i32 N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    Graph adj(N);\n    vector<tuple<i32, i32, i32>> edges(M);\n    for (i32 i = 0; i < M; ++i) {\n        i32 u, v, w;\n        cin >> u >> v >> w;\n        --u, --v;\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n        edges[i] = {u, v, w};\n    }\n\n    for (i32 i = 0; i < N; ++i) {\n        i32 x, y;\n        cin >> x >> y;\n    }\n\n    vector<pair<i64, i32>> edge_importance(M, {0, 0});\n    for (i32 i = 0; i < N; ++i) {\n        auto [dist, cnt] = dijkstra(i, adj, N);\n        for (i32 j = 0; j < M; ++j) {\n            auto& [u, v, w] = edges[j];\n            if (dist[u] + w == dist[v]) {\n                edge_importance[j].first += cnt[u] * (N - cnt[v]);\n            }\n            if (dist[v] + w == dist[u]) {\n                edge_importance[j].first += cnt[v] * (N - cnt[u]);\n            }\n            edge_importance[j].second = j;\n        }\n    }\n\n    sort(edge_importance.rbegin(), edge_importance.rend());\n\n    vector<i32> days(M, -1);\n    vector<int> current_size(D, 0);\n    for (auto [imp, idx] : edge_importance) {\n        int current_day = 0;\n        for (int d = 0; d < D; ++d) {\n            if (current_size[d] < K) {\n                current_day = d;\n                break;\n            }\n        }\n        days[idx] = current_day + 1;\n        current_size[current_day]++;\n    }\n\n    for (i32 d : days) cout << d << \" \";\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n    bool operator<(const Point& o) const {\n        return tie(x, y, z) < tie(o.x, o.y, o.z);\n    }\n};\n\nvector<vector<string>> input;  // Store each 2D silhouette\nvector<vector<vector<int>>> dp; // Precompute front and right silhouettes\nvector<vector<vector<int>>> blocks;\n\nvector<vector<vector<int>>> construct(int idx) {\n    auto& sil = input[idx*2];\n    auto& sir = input[idx*2 + 1];\n    int n = sil.size();\n    vector<vector<vector<int>>> cube(n, vector<vector<int>>(n, vector<int>(n)));\n    vector<vector<int>> vis(n, vector<int>(n, 0));\n    int cnt = 1;\n    \n    auto addBlock = [&](int x, int y, int z) {\n        cube[x][y][z] = cnt;\n    };\n    \n    // Process intersections to use same blocks for both configurations\n    for (int z = 0; z < n; z++) {\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (dp[idx][x][z] && dp[idx + 2][y][z] && !vis[x][y] && !blocks[x][y][z]) {\n                    blocks[x][y][z] = cnt;\n                    addBlock(x, y, z);\n                    vis[x][y]++;\n                }\n            }\n        }\n    }\n    \n    // Fill remaining regions needed by the first silhouette\n    for (int z = 0; z < n; z++) {\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (dp[idx][x][z] && !blocks[x][y][z]) {\n                    addBlock(x, y, z);\n                    blocks[x][y][z] = cnt++;\n                }\n            }\n        }\n    }\n    return cube;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D;\n    cin >> D;\n    input.resize(4);\n    \n    for (int t = 0; t < 4; t++) {\n        for (int i = 0; i < D; i++) {\n            string s;\n            cin >> s;\n            input[t].push_back(s);\n        }\n    }\n    \n    // Precompute front and right silhouettes\n    dp.assign(4, vector<vector<int>>(D, vector<int>(D)));\n    for (int t = 0; t < 4; t += 2) {\n        for (int z = 0; z < D; z++) {\n            for (int x = 0; x < D; x++) {\n                for (int y = 0; y < D; y++) {\n                    if (input[t][z][x] == '1') dp[t][x][z]++;\n                    if (input[t+1][z][y] == '1') dp[t+2][y][z]++;\n                }\n            }\n        }\n    }\n    \n    blocks.resize(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    auto cube1 = construct(0);\n    blocks.assign(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    auto cube2 = construct(1);\n    \n    // Count blocks used\n    int max_block = 0;\n    for (const auto& c1 : cube1) for (const auto& row : c1) \n        for (int block : row) max_block = max(max_block, block);\n    for (const auto& c2 : cube2) for (const auto& row : c2) \n        for (int block : row) max_block = max(max_block, block);\n    \n    cout << max_block << '\\n';\n    \n    // Output cubes\n    for (auto& c : cube1) {\n        for (auto& r : c) \n            for (int val : r) cout << val << \" \";\n        cout << \"\\n\";\n    }\n    for (auto& c : cube2) {\n        for (auto& r : c) \n            for (int val : r) cout << val << \" \";\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\n#include <boost/geometry.hpp>\nusing namespace std;\nusing namespace boost::geometry;\ntypedef model::d2::point_xy<int> Point;\n\nauto rng = mt19937(chrono::steady_clock::now().time_since_epoch().count());\n\nlong long distSquared(const Point &a, const Point &b) {\n    return (long long)(a.x() - b.x()) * (a.x() - b.x()) +\n           (long long)(a.y() - b.y()) * (a.y() - b.y());\n}\n\nstruct Edge {\n    int u, v, w;\n    bool operator<(const Edge &o) const { return w < o.w; }\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<Point> stations(N);\n    stations[0] = Point(0, 0);\n    for (int i = 1; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        stations[i] = Point(x, y);\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v >> edges[i].w;\n        edges[i].u--, edges[i].v--;\n    }\n\n    vector<Point> residents(K);\n    for (int i = 0; i < K; ++i) {\n        int a, b;\n        cin >> a >> b;\n        residents[i] = Point(a, b);\n    }\n\n    // Prim's MST\n    vector<bool> inMST(N, false);\n    inMST[0] = true;\n    priority_queue<Edge> pq;\n    for (Edge e : edges) {\n        if (e.u == 0 || e.v == 0) pq.push(e);\n    }\n\n    vector<bool> edgeUsed(M, false);\n    while (!pq.empty()) {\n        auto [u, v, w] = pq.top();\n        pq.pop();\n        if (inMST[u] && inMST[v]) continue;\n\n        int nxt = inMST[u] ? v : u;\n        inMST[nxt] = true;\n\n        if (u < v) edgeUsed[v - 1] = true;\n        else edgeUsed[u - 1] = true;\n\n        for (Edge e : edges) {\n            if ((e.u == nxt || e.v == nxt) && !inMST[e.u] && !inMST[e.v]) {\n                pq.push(e);\n            }\n        }\n    }\n\n    vector<int> radius(N, 0);\n    for (auto res : residents) {\n        int min_idx = 0;\n        long long min_dist = distSquared(res, stations[0]);\n        for (int i = 1; i < N; ++i) {\n            if (!inMST[i]) continue;\n            long long cur = distSquared(res, stations[i]);\n            if (cur < min_dist) {\n                min_dist = cur;\n                min_idx = i;\n            }\n        }\n        radius[min_idx] = max(radius[min_idx], \n            static_cast<int>(ceil(sqrt(min_dist))));\n    }\n\n    // Output results\n    for (int r : radius) cout << r << \" \";\n    cout << endl;\n    for (bool e : edgeUsed) cout << e << \" \";\n    cout << endl;\n\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nvector<vector<int>> grid(N, vector<int>(N));\nvector<tuple<int, int, int, int>> ans;\n\nbool isValid(int x, int y) {\n    return x >= 0 && y >= 0 && x < N && y <= x;\n}\n\nint evaluate() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            if (isValid(x + 1, y) && grid[x][y] > grid[x+1][y]) ++violations;\n            if (isValid(x + 1, y + 1) && grid[x][y] > grid[x+1][y+1]) ++violations;\n        }\n    }\n    return violations;\n}\n\nvoid runSwaps() {\n    int current_violations = evaluate();\n    bool improved = true;\n\n    while (ans.size() < 10000 && improved) {\n        improved = false;\n        vector<vector<int>> backup = grid;\n        \n        for (int x = 0; x < N - 1; ++x) {\n            for (int y = 0; y <= x; ++y) {\n                // Check child on the left\n                if (isValid(x + 1, y) && grid[x][y] > grid[x + 1][y]) {\n                    swap(grid[x][y], grid[x + 1][y]);\n                    ans.emplace_back(x, y, x + 1, y);\n                    int new_violations = evaluate();\n                    if (new_violations >= current_violations) {\n                        swap(grid[x][y], grid[x + 1][y]);\n                        ans.pop_back();\n                    } else {\n                        current_violations = new_violations;\n                        improved = true;\n                    }\n                }\n                // Check child on the right\n                if (isValid(x + 1, y + 1) && grid[x][y] > grid[x + 1][y + 1]) {\n                    swap(grid[x][y], grid[x + 1][y + 1]);\n                    ans.emplace_back(x, y, x + 1, y + 1);\n                    int new_violations = evaluate();\n                    if (new_violations >= current_violations) {\n                        swap(grid[x][y], grid[x + 1][y + 1]);\n                        ans.pop_back();\n                    } else {\n                        current_violations = new_violations;\n                        improved = true;\n                    }\n                }\n                if (ans.size() >= 10000) return;\n            }\n        }\n\n        if (!improved) grid = backup;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Input\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            cin >> grid[i][j];\n        }\n    }\n\n    runSwaps();\n    \n    cout << ans.size() << '\\n';\n    for (auto& [x1, y1, x2, y2] : ans) {\n        cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << '\\n';\n    }\n    \n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int D = 9;\nint N;\nvector<vector<bool>> is_obstacle(D, vector<bool>(D, false));\n\n// Spiral path initialization\nvector<pair<int, int>> spiral_order;\n\nvoid initialize_spiral() {\n    int top = 0, bottom = D-1, left = 0, right = D-1;\n    int dir = 0; // 0: right, 1: down, 2: left, 3: up\n    while (top <= bottom && left <= right) {\n        if (dir == 0) {\n            for (int j = left; j <= right; ++j) spiral_order.emplace_back(top, j);\n            top++;\n        } else if (dir == 1) {\n            for (int i = top; i <= bottom; ++i) spiral_order.emplace_back(i, right);\n            right--;\n        } else if (dir == 2) {\n            for (int j = right; j >= left; --j) spiral_order.emplace_back(bottom, j);\n            bottom--;\n        } else if (dir == 3) {\n            for (int i = bottom; i >= top; --i) spiral_order.emplace_back(i, left);\n            left++;\n        }\n        dir = (dir + 1) % 4;\n    }\n    // Filter out entrance and invalid positions\n    spiral_order.erase(remove_if(spiral_order.begin(), spiral_order.end(), \n        [](auto& pos) {\n            return (pos.first == 0 && pos.second == (D-1)/2) || is_obstacle[pos.first][pos.second];\n        }), \n        spiral_order.end());\n    reverse(spiral_order.begin(), spiral_order.end());\n}\n\nbool in_bounds(int x, int y) {\n    return x >= 0 && x < D && y >= 0 && y < D;\n}\n\nstruct StorageEntry {\n    int val;\n    int x, y;\n};\n\nvector<vector<int>> grid(D, vector<int>(D, -1));\nvector<StorageEntry> stored;\n\npair<int, int> bfs_nearest(int target) {\n    queue<pair<int, int>> q;\n    q.emplace((0, (D-1)/2));\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    visited[0][(D-1)/2] = true;\n    \n    while (!q.empty()) {\n        auto [cx, cy] = q.front(); q.pop();\n        for (auto [dx, dy] : vector<pair<int, int>>{{-1,0},{1,0},{0,-1},{0,1}}) {\n            int nx = cx + dx, ny = cy + dy;\n            if (in_bounds(nx, ny) && !visited[nx][ny] && !is_obstacle[nx][ny] && grid[nx][ny] != -1) {\n                if (grid[nx][ny] == target) {\n                    grid[nx][ny] = -1; // mark as used\n                    return {nx, ny};\n                }\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return {-1, -1};\n}\n\nint main() {\n    cin >> N;\n    int n = D*D - 1 - N;\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        is_obstacle[x][y] = true;\n    }\n\n    initialize_spiral();\n    int cur_pos = 0;\n    unordered_map<int, pair<int, int>> container_map;\n\n    for (int d = 0; d < n; ++d) {\n        int t;\n        cin >> t;\n        stored.push_back({t, spiral_order[cur_pos].first, spiral_order[cur_pos].second});\n        container_map[t] = spiral_order[cur_pos];\n        grid[spiral_order[cur_pos].first][spiral_order[cur_pos].second] = t;\n        cur_pos++;\n        cout << spiral_order[cur_pos - 1].first << \" \" << spiral_order[cur_pos - 1].second << endl;\n    }\n\n    sort(stored.begin(), stored.end(), [](const auto& a, const auto& b) { return a.val < b.val; });\n\n    for (const auto& entry : stored) {\n        auto [x, y] = bfs_nearest(entry.val);\n        cout << x << \" \" << y << endl;\n    }\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 51;\nint grid[N][N];\nint ans[N][N];\nint n, m;\n\nint dx[4] = {-1, 0, 1, 0};\nint dy[4] = {0, 1, 0, -1};\n\nvoid bfs_zero() {\n    deque<pair<int, int>> q;\n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    for (int i=0; i<n; ++i) {\n        if (ans[i][0] == 0 && !vis[i][0]) {\n            q.push_back({i, 0});\n            vis[i][0] = true;\n        }\n        if (ans[i][n-1] == 0 && !vis[i][n-1]) {\n            q.push_back({i, n-1});\n            vis[i][n-1] = true;\n        }\n    }\n    for (int j=0; j<n; ++j) {\n        if (ans[0][j] == 0 && !vis[0][j]) {\n            q.push_back({0, j});\n            vis[0][j] = true;\n        }\n        if (ans[n-1][j] == 0 && !vis[n-1][j]) {\n            q.push_back({n-1, j});\n            vis[n-1][j] = true;\n        }\n    }\n\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop_front();\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 || vis[nx][ny] || ans[nx][ny] != 0) continue;\n            ans[nx][ny] = 0;\n            vis[nx][ny] = true;\n            q.push_back({nx, ny});\n        }\n    }\n}\n\nint main() {\n    cin >> n >> m;\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            cin >> grid[i][j];\n            ans[i][j] = grid[i][j];\n        }\n    }\n    \n    vector<pair<int, int>> reps(m+1);\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            int c = grid[i][j];\n            if (reps[c] == pair<int, int>{}) {\n                reps[c] = {i, j};\n            }\n        }\n    }\n\n    memset(ans, -1, sizeof(ans));\n    for (int i=1; i<=m; ++i) {\n        if (reps[i] != pair<int, int>{}) {\n            auto [x, y] = reps[i];\n            ans[x][y] = i;\n            // Connect to border if it's adjacent originally\n            if (x == 0 || x == n-1 || y == 0 || y == n-1) {\n                ans[x][y] = 0; // Treat edge as zero\n            }\n        }\n    }\n\n    // Handle adjacencies for initial fill\n    for (int i=1; i<=m; ++i) {\n        if (reps[i].first != -1) {\n            auto [x, y] = reps[i];\n            bool adj_zero = false;\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) {\n                    adj_zero = true;\n                    break;\n                }\n                if (grid[nx][ny] == 0) adj_zero = true;\n            }\n            if (adj_zero) ans[x][y] = 0;\n        }\n    }\n\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (ans[i][j] == -1) ans[i][j] = 0;\n        }\n    }\n    \n    bfs_zero(); // Expand zeros properly\n    \n    // Connect remaining color cells to components\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (ans[i][j] > 0) continue;\n            for (int d=0; d<4; ++d) {\n                int nx = i + dx[d], ny = j + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n || ans[nx][ny] <= 0) continue;\n                ans[i][j] = ans[nx][ny];\n                break;\n            }\n        }\n    }\n\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (j > 0) cout << ' ';\n            cout << ans[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Vec = vector<int>;\nusing Mat = vector<Vec>;\nusing Graph = vector<Vec>;\nconstexpr ll INF = 1LL<<60;\nmt19937 mt(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct Partition {\n    int N, D, Q;\n    Vec A; // Answer partitions\n    Mat W; // Constraints: W[u][v] > 0 means u > v\n    vector<double> weight; // Virtual item weights\n\n    void init(int n, int d, int q) {\n        N = n; D = d; Q = q;\n        A = Vec(N, -1);\n        W.assign(N, Vec(N));\n        weight.resize(N, 1.0);\n    }\n\n    // Assign a random group with the smallest current sum\n    int assign(const Vec& cnt) {\n        priority_queue<pair<double, int>, vector<pair<double, int>>, greater<>> pq;\n        for (int i=0; i<D; ++i) pq.emplace(cnt[i] * weight[i], i);\n        \n        // Prefer groups with space but allow overfill near the end\n        int best = -1, minOver = N+1;\n        for (auto [w, idx] : pq) {\n            int total = cnt[idx] + 1;\n            if (total > N/D && minOver <= N/D) continue;\n            if (best == -1 || (total <= N/D && cnt[idx] < cnt[best])) {\n                best = idx;\n                if (total > N/D) minOver = total;\n            }\n        }\n        return best;\n    }\n\n    Vec solve() {\n        // Initial comparison phase\n        int q = 0;\n        for (int i=0; i<N-1 && q < Q; ++i) {\n            cout << 1 << ' ' << 1 << ' ' << i << ' ' << (i+1) << endl;\n            char res; cin >> res;\n            if (res == '>') W[i][i+1] = 1;\n            else if (res == '<') W[i+1][i] = 1;\n            ++q;\n        }\n\n        // Update virtual weights based on constraints\n        for (int k=0; k<N; ++k)\n            for (int i=0; i<N; ++i)\n                for (int j=0; j<N; ++j)\n                    if (W[i][k] && W[k][j]) W[i][j] = 1;\n\n        Vec cnt(D, 0);\n        for (int i=0; i<N; ++i) {\n            if (q >= Q) break;\n            int group = assign(cnt);\n            if (group == -1) {\n                group = mt() % D; // Random if stuck\n                if (cnt[group] >= N/D) continue; // Avoid overfill\n            }\n            A[i] = group;\n            cnt[group]++;\n        }\n\n        // Fill remaining unassigned items (if any)\n        int group = 0;\n        for (int i=0; i<N; ++i) {\n            if (A[i] == -1) {\n                while (cnt[group] >= N/D) group++;\n                A[i] = group;\n                cnt[group]++;\n            }\n        }\n\n        // Output final partition\n        for (int x: A) cout << x << ' ';\n        cout << endl;\n        return A;\n    }\n};\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n    Partition solver;\n    solver.init(N, D, Q);\n    solver.solve();\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nvoid find_box(const multi_array<int, 2>& stacks, int target, int& sidx, int& pos) {\n    for (int i=0; i<stacks.shape()[0]; ++i) {\n        for (int j=stacks.shape()[1]-1; j>=0; --j) {\n            if (stacks[i][j] == target) {\n                sidx = i; pos = j;\n                return;\n            }\n        }\n    }\n}\n\nint main() {\n    int n = 200, m = 10;\n    multi_array<int, 2> stacks(extents[m][n/m]);\n    for (int i=0; i<m; ++i)\n        for (int j=0; j<n/m; ++j)\n            cin >> stacks[i][j];\n\n    vector<pair<int, int>> moves;\n    int target = 1;\n\n    while (target <= n) {\n        int current_s = -1, pos = -1;\n        find_box(stacks, target, current_s, pos);\n        \n        bool at_top = false;\n        for (int s=0; s<m; ++s) {\n            if (!stacks[s].empty() && stacks[s].back() == target) {\n                at_top = true;\n                current_s = s;\n                break;\n            }\n        }\n        if (at_top) {\n            moves.emplace_back(target, 0);\n            stacks[current_s].pop_back();\n            target++;\n            continue;\n        }\n        \n        if (pos != stacks[current_s].size()-1) {\n            int max_dest = -1, dest_idx = -1;\n            for (int s=0; s<m; ++s) {\n                if (!stacks[s].empty() && s != current_s) {\n                    if (stacks[s].back() > max_dest || dest_idx == -1) {\n                        max_dest = stacks[s].back();\n                        dest_idx = s;\n                    }\n                }\n            }\n            if (dest_idx == -1) dest_idx = (current_s + 1) % m; // Pick next available\n            moves.emplace_back(stacks[current_s][pos], dest_idx + 1);\n            auto seq = stacks[current_s].subarray(pos, stacks[current_s].size());\n            stacks[dest_idx].insert(stacks[dest_idx].end(), seq.begin(), seq.end());\n            stacks[current_s].resize(pos);\n        }\n    }\n\n    for (auto& [v, i] : moves)\n        cout << v << \" \" << i << \"\\n\";\n}","ahc027":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\nusing namespace boost;\n\n// Direction vectors: down, right, up, left\nint dx[] = {1, 0, -1, 0};\nint dy[] = {0, 1, 0, -1};\nchar dir_char[] = {'D', 'R', 'U', 'L'};\n\nconst int INF = 1e9;\ntypedef vector<vector<int>> Matrix;\ntypedef vector<vector<vector<int>>> Dist; // precomputed distances\n\nbool valid(int x, int y, int n) {\n    return x >= 0 && x < n && y >= 0 && y < n;\n}\n\npair<Matrix, Matrix> parseInput(int n) {\n    vector<string> h(n-1), v(n);\n    for (auto& s : h) cin >> s;\n    for (auto& s : v) cin >> s;\n    \n    Matrix hor(n, vector<int>(n, 0));\n    for (int i = 0; i < n-1; ++i)\n        for (int j = 0; j < n; ++j)\n            hor[i][j] = h[i][j] - '0';\n            \n    Matrix ver(n, vector<int>(n, 0));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n-1; ++j)\n            ver[i][j] = v[i][j] - '0';\n            \n    return {hor, ver};\n}\n\nMatrix readDirt(int n) {\n    Matrix d(n, vector<int>(n, 0));\n    for (auto& row : d)\n        for (int& v : row) cin >> v;\n    return d;\n}\n\nvoid bfs(int x, int y, int n, const Matrix& hor, const Matrix& ver, vector<vector<bool>>& vis) {\n    queue<pair<int,int>> q;\n    q.emplace(x, y);\n    vis[x][y] = true;\n    while (!q.empty()) {\n        auto [cx, cy] = q.front(); q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int nx = cx + dx[k], ny = cy + dy[k];\n            if (valid(nx, ny, n) && !vis[nx][ny]) {\n                if ((k == 0 && !hor[cx][cy]) || \n                    (k == 1 && !ver[cx][cy]) ||\n                    (k == 2 && !hor[nx][ny]) ||\n                    (k == 3 && !ver[nx][ny])) {\n                    vis[nx][ny] = true;\n                    q.emplace(nx, ny);\n                }\n            }\n        }\n    }\n}\n\nDist precompute_distances(int n, const Matrix& hor, const Matrix& ver) {\n    Dist dist(n, vector<vector<int>>(n, vector<int>(n*n, INF)));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            priority_queue<pair<int, pair<int,int>>, \n                           vector<pair<int, pair<int,int>>>, \n                           greater<>> pq;\n            pq.emplace(0, make_pair(i, j));\n            dist[i][j][i*n + j] = 0;\n            while (!pq.empty()) {\n                auto [d, p] = pq.top(); pq.pop();\n                auto [x, y] = p;\n                if (d > dist[i][j][x*n + y]) continue;\n                for (int k = 0; k < 4; ++k) {\n                    int nx = x + dx[k], ny = y + dy[k];\n                    if (valid(nx, ny, n)) {\n                        bool blocked = (k == 0 && hor[x][y]) ||\n                                       (k == 1 && ver[x][y]) ||\n                                       (k == 2 && hor[nx][ny]) ||\n                                       (k == 3 && ver[nx][ny]);\n                        if (!blocked && d + 1 < dist[i][j][nx*n + ny]) {\n                            dist[i][j][nx*n + ny] = d + 1;\n                            pq.emplace(d + 1, make_pair(nx, ny));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return dist;\n}\n\nvoid add_route(int x, int y, int nx, int ny, const Dist& dist, vector<char>& answer, int n) {\n    if (x == nx && y == ny) return;\n    auto& d = dist[x][y];\n    int best_k = -1;\n    for (int k = 0; k < 4; ++k) {\n        int ax = x + dx[k], ay = y + dy[k];\n        if (valid(ax, ay, n) && dist[x][y][ax*n + ay] == d[nx*n + ny] - 1 && \n            (best_k == -1 || dist[ax][ay][nx*n + ny] < dist[x + dx[best_k]][y + dy[best_k]][nx*n + ny])) {\n            best_k = k;\n        }\n    }\n    if (best_k != -1) {\n        answer.push_back(dir_char[best_k]);\n        add_route(x + dx[best_k], y + dy[best_k], nx, ny, dist, answer, n);\n    }\n}\n\nvector<pair<int, int>> get_critical_points(const Matrix& d, int region_size) {\n    vector<pair<int, pair<int,int>>> points;\n    for (int i = 0; i < d.size(); ++i)\n        for (int j = 0; j < d.size(); ++j)\n            points.emplace_back(-d[i][j], make_pair(i,j));\n    sort(points.begin(), points.end());\n    \n    vector<pair<int,int>> result;\n    for (int i = 0; i < min<int>(region_size, (int)points.size()); ++i)\n        result.emplace_back(points[i].second);\n    return result;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    auto [hor, ver] = parseInput(n);\n    Matrix d = readDirt(n);\n    \n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    bfs(0, 0, n, hor, ver, vis);\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            assert(vis[i][j]);\n    \n    Dist dist = precompute_distances(n, hor, ver);\n    \n    vector<pair<int, int>> critical = get_critical_points(d, n); // Top critical points\n    \n    vector<char> answer;\n    int len = 0, limit = 1e5;\n    int x = 0, y = 0;\n    \n    vector<int> shuffled(critical.size());\n    iota(shuffled.begin(), shuffled.end(), 0);\n    \n    while (true) {\n        random_shuffle(shuffled.begin(), shuffled.end());\n        for (int idx : shuffled) {\n            auto [nx, ny] = critical[idx];\n            if (len + dist[x][y][nx*n + ny] > limit) break;\n            add_route(x, y, nx, ny, dist, answer, n);\n            len += dist[x][y][nx*n + ny];\n            x = nx; y = ny;\n        }\n        if (len + dist[x][y][0] > limit)\n            break;\n        add_route(x, y, 0, 0, dist, answer, n);\n        break;\n    }\n    \n    cout << string(answer.begin(), answer.end()) << endl;\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\n#include <boost/algorithm/string/find_tail.hpp>\nusing namespace std;\n\nstring concat(const vector<string>& t) {\n    int m = t.size();\n    string result = t[0];\n    unordered_map<string, vector<int>> suffix;\n    for (int i=0; i<m; ++i) {\n        for (int len=1; len<=4; ++len) {\n            suffix[t[i].substr(t[i].size() - len)].push_back(i);\n        }\n    }\n    vector<bool> used(m, false);\n    used[0] = true;\n    \n    auto get_cost = [&](int idx, const string& prev_str) {\n        string target = t[idx];\n        int n = prev_str.size();\n        int max_overlap = 0;\n        for (int i=1; i<=4 && i<=n; ++i) {\n            if (boost::algorithm::ends_with(prev_str, target.substr(0,i))) \n                max_overlap = i;\n        }\n        return target.size() - max_overlap;\n    };\n    \n    for (int count=1; count<m; ++count) {\n        int best_idx = -1, min_cost = INT_MAX;\n        for (int i=0; i<m; ++i) {\n            if (!used[i]) {\n                int cost = get_cost(i, result);\n                if (cost < min_cost) {\n                    min_cost = cost;\n                    best_idx = i;\n                }\n            }\n        }\n        if (best_idx == -1) break;\n        used[best_idx] = true;\n        string current = t[best_idx];\n        int n = result.size();\n        int overlap = 0;\n        for (int k=1; k<=min(4,n); ++k) {\n            if (boost::algorithm::ends_with(result, current.substr(0,k)))\n                overlap = k;\n        }\n        result += current.substr(overlap);\n    }\n    return result.substr(0, 5000);\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> A(N);\n    for (int i=0; i<N; ++i) cin >> A[i];\n    \n    vector<string> words(M);\n    unordered_map<char, pair<int,int>> pos;\n    \n    for (int i=0; i<M; ++i) cin >> words[i];\n    \n    for (int i=0; i<N; ++i) \n        for (int j=0; j<N; ++j) \n            pos[A[i][j]] = {i, j};\n    \n    string lucky = concat(words);\n    pair<int, int> current = {si, sj};\n    vector<pair<int,int>> steps;\n    \n    for (char c : lucky) {\n        steps.emplace_back(pos[c]);\n    }\n    \n    cout << steps.size() << endl;\n    for (auto& [x, y] : steps) {\n        cout << x << \" \" << y << endl;\n    }\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nusing namespace std;\nusing namespace boost::accumulators;\n\nstruct Grid {\n    int n;\n    boost::multi_array<int, 2> grid;  // 0: unknown, -1: empty, >=1: count\n    vector<pair<int,int>> unknown;\n    mt19937 mt{random_device{}()};\n    \n    Grid(int _n) : n(_n), grid(boost::extents[_n][_n]) {\n        for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) {\n            grid[i][j] = 0;\n            unknown.emplace_back(i, j);\n        }\n    }\n    \n    bool is_unknown(int i, int j) const {\n        return 0 <= i && i < n && 0 <= j && j <n && grid[i][j] == 0;\n    }\n    \n    void query_group(int size, const vector<pair<int,int>>& indexes) {\n        cout << \"q \" << size;\n        for (auto [x,y] : indexes) cout << ' ' << x << ' ' << y;\n        cout << endl;\n        int result;\n        cin >> result;\n        double mean = result + size * (1e-5); // Prevent division by zero\n        double stddev = sqrt(size * 0.2); // Conservative estimate\n        \n        double z_score = (result - size * 0.1) / (stddev + 1e-5);\n        for (auto [x,y] : indexes) {\n            if (grid[x][y] == 0) {\n                if (z_score > 2.0) grid[x][y] = 2;\n                else if (z_score < -1.5) grid[x][y] = -1;\n            }\n        }\n    }\n    \n    void drill(int i, int j) {\n        cout << \"q 1 \" << i << ' ' << j << endl;\n        cin >> grid[i][j];\n    }\n    \n    void report() {\n        vector<pair<int,int>> positives;\n        for (int i=0; i<n; ++i)\n            for (int j=0; j<n; ++j)\n                if (grid[i][j] > 0) positives.emplace_back(i,j);\n        \n        cout << \"a \" << positives.size();\n        for (auto [x,y] : positives) cout << ' ' << x << ' ' << y;\n        cout << endl;\n        exit(0);\n    }\n};\n\nbool is_border(int i, int j, int n) {\n    return i == 0 || j == 0 || i == n-1 || j == n-1;\n}\n\nint main() {\n    srand(time(0));\n    int N, M;\n    double epsilon;\n    cin >> N >> M >> epsilon;\n    vector<vector<pair<int,int>>> oil(M);\n    \n    for (int m=0; m<M; ++m) {\n        int d; cin >> d;\n        oil[m].resize(d);\n        for (int k=0; k<d; ++k) {\n            cin >> oil[m][k].first >> oil[m][k].second;\n        }\n    }\n    \n    Grid g(N);\n    int total = N * N;\n    int budget = total / 3;\n    \n    // Initial divination phase: 5x5 blocks\n    for (int i=0; i+5<=N; i+=5) {\n        for (int j=0; j+5<=N; j+=5) {\n            if (budget-- <= 0) break;\n            vector<pair<int,int>> block;\n            for (int x=i; x < i+5; ++x)\n                for (int y=j; y < j+5; ++y) \n                    if (g.is_unknown(x,y)) block.emplace_back(x,y);\n            if (block.size() >= 2) g.query_group(block.size(), block);\n        }\n        if (budget <= 0) break;\n    }\n    \n    // Remaining cells: smaller divination\n    while (budget >= 5 && g.unknown.size() >= 5) {\n        shuffle(g.unknown.begin(), g.unknown.end(), g.mt);\n        vector<pair<int,int>> batch;\n        while (budget >= 0 && batch.size() < 20 && !g.unknown.empty()) {\n            auto [x,y] = g.unknown.back();\n            g.unknown.pop_back();\n            if (g.is_unknown(x,y)) {\n                batch.emplace_back(x,y);\n            }\n        }\n        if (batch.size() >= 2) {\n            g.query_group(batch.size(), batch);\n            budget--;\n        }\n    }\n    \n    // Drill borders\n    for (auto &cell : g.unknown) {\n        if (g.is_unknown(cell.first, cell.second) && is_border(cell.first, cell.second, N)) {\n            g.drill(cell.first, cell.second);\n        }\n    }\n    \n    // Drill remaining\n    for (auto &cell : g.unknown) {\n        if (g.is_unknown(cell.first, cell.second)) {\n            g.drill(cell.first, cell.second);\n        }\n    }\n    \n    g.report();\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<tuple<int,int,int,int>> rectangles[55];\n\nvoid solve(int n, const vector<int>& areas) {\n    int w = 1000;\n    int sum = accumulate(areas.begin(), areas.end(), 0);\n    int remaining = w * w - sum;\n    vector<int> needed = areas;\n    int max_y = w;\n\n    rectangles[n].resize(areas.size());\n    \n    for (int i=0; i<(int)areas.size(); ++i) {\n        int rows = (remaining + (int)areas.size() - i - 1) / ((int)areas.size() - i);\n        rows = max(rows, (needed[i] + w - 1) / w); // at least enough area\n        \n        int y_start = max_y - rows;\n        get<0>(rectangles[n][i]) = y_start;\n        get<2>(rectangles[n][i]) = max_y;\n        get<1>(rectangles[n][i]) = 0;\n        int cols = needed[i] / rows;\n        if (cols * rows < needed[i]) ++cols;\n        cols = min(cols, w); // max columns can't exceed grid width\n        get<3>(rectangles[n][i]) = cols;\n        \n        remaining -= (rows * cols - needed[i]);\n        max_y = y_start;\n    }\n    \n    int last_x = 0;\n    for (int k=0; k < (int)rectangles[n].size(); ++k) {\n        get<1>(rectangles[n][k]) = last_x;\n        last_x += get<3>(rectangles[n][k]);\n        get<3>(rectangles[n][k]) = last_x;\n    }\n}\n\nint main() {\n    int W = 1000, D, N;\n    cin >> W >> D >> N;\n    \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    for (int d=0; d<D; ++d) \n        solve(d, a[d]);\n    \n    for (int d=0; d<D; ++d)\n        for (auto [x1,y1,x2,y2] : rectangles[d])\n            printf(\"%d %d %d %d\\n\", x1, y1, x2, y2);\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\nconst int MOD = 998244353;\nint a[N][N], stamps[M][3][3];\nvector<tuple<int, int, int>> operations;\n\nbool isValid(int p, int q) {\n    return p <= N-3 && q <= N-3;\n}\n\nint applyStamp(int m, int p, int q) {\n    int total = 0;\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            total += (a[p+i][q+j] + stamps[m][i][j]) % MOD - a[p+i][q+j] % MOD;\n        }\n    }\n    return total >= 0 ? total : total + MOD;\n}\n\nint main() {\n    int n, m, k;\n    cin >> n >> m >> k;\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n    \n    for (int l = 0; l < m; ++l)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> stamps[l][i][j];\n    \n    // Store available positions\n    vector<pair<int, int>> positions;\n    for (int i = 0; i <= N-3; ++i)\n        for (int j = 0; j <= N-3; ++j)\n            positions.emplace_back(i, j);\n\n    while (operations.size() < K) {\n        int best_score = 0;\n        int best_stamp = -1, best_p = -1, best_q = -1;\n        \n        shuffle(positions.begin(), positions.end(), mt19937(random_device()()));\n        \n        for (auto &[p, q] : positions) {\n            for (int st = 0; st < m; ++st) {\n                int score = applyStamp(st, p, q);\n                if (score > best_score) {\n                    best_score = score;\n                    best_stamp = st;\n                    best_p = p;\n                    best_q = q;\n                }\n            }\n        }\n        \n        if (best_stamp == -1) break;\n\n        operations.emplace_back(best_stamp, best_p, best_q);\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                a[best_p+i][best_q+j] = (a[best_p+i][best_q+j] + stamps[best_stamp][i][j]) % MOD;\n            }\n        }\n    }\n\n    cout << operations.size() << endl;\n    for (auto &[m, p, q] : operations)\n        cout << m << \" \" << p << \" \" << q << endl;\n    \n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nvector<string> solve(const vector<vector<int>>& containers) {\n    int N = containers.size();\n    vector<int> targetRow(N * N);\n    for (int i = 0; i < N; ++i)\n        for (int k = 0; k < N; ++k)\n            targetRow[containers[i][k]] = i;\n\n    vector<vector<int>> targetPos(N * N);\n    for (int b = 0; b < N * N; ++b) {\n        int r = targetRow[b];\n        targetPos[b] = {r, N-1};\n    }\n\n    vector<string> res(N);\n    int T = 30 + N * N * 5;\n    for (int t = 0; t < T; ++t) {\n        for (int i = 0; i < N; ++i)\n            res[i] += '.';\n        bool moved = false;\n        // Large crane (index 0)\n        if (res[0].back() != 'B') {\n            vector<int> cranePos = {0 + t % N, 0};\n            if (cranePos[1] < N-1) {\n                int mx = -1;\n                for (int x = 0; x < N; ++x) {\n                    if (cranePos[0] == x && containers[x].size() > t) {\n                        int b = containers[x][t];\n                        if (mx == -1 || targetRow[mx] < targetRow[b]) {\n                            mx = b;\n                        }\n                    }\n                }\n                if (mx != -1 && t + abs(cranePos[0] - targetPos[mx][0]) + abs(cranePos[1] - targetPos[mx][1]) <= T) {\n                    if (cranePos[1] == 0) res[0].back() = 'P';\n                    else {\n                        if (targetPos[mx][1] == cranePos[1] + 1) res[0].back() = 'R';\n                        else if (targetPos[mx][0] > cranePos[0] && cranePos[0] < N-1) res[0].back() = 'D';\n                        else if (targetPos[mx][0] < cranePos[0] && cranePos[0] > 0) res[0].back() = 'U';\n                    }\n                    moved = true;\n                }\n            }\n        }\n\n        // Small cranes\n        for (int i = 1; i < N; ++i) {\n            if (res[i].back() != 'B') {\n                vector<int> cranePos = {i, 0};\n                auto update = [&](int dx, int dy, char dir) {\n                    if (cranePos[0] + dx >= 0 && cranePos[0] + dx < N && cranePos[1] + dy >= 0 && cranePos[1] + dy < N) {\n                        res[i].back() = dir;\n                        moved = true;\n                    }\n                };\n                bool carrying = (res[i].size() > 0 && res[i].back() == 'P');\n                // Drop container if at Dispatch Gate\n                if (cranePos[1] == N-1 && carrying) res[i].back() = 'Q';\n                // Else move towards Dispatch Gates or pick up containers\n                else if (cranePos[1] > 0 && !carrying) update(0, -1, 'L');\n                else if (cranePos[1] < N-1) update(0, 1, 'R');\n            }\n        }\n        if (!moved) break;\n    }\n    return res;\n}\n\nint main() {\n    int N = 5;\n    vector<vector<int>> containers(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> containers[i][j];\n    auto commands = solve(containers);\n    int maxLen = 0;\n    for (auto& s : commands) maxLen = max(maxLen, (int)s.size());\n    for (auto& s : commands) s.resize(maxLen, '.');\n    for (auto& s : commands) cout << s << endl;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint H[20][20], dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}, vis[20][20];\nvector<string> ans;\nint n = 20, x = 0, y = 0, load = 0;\n\nvoid move(int nx, int ny) {\n    while (x != nx || y != ny) {\n        if (x > nx) ans.push_back(\"U\"), x--;\n        else if (x < nx) ans.push_back(\"D\"), x++;\n        else if (y > ny) ans.push_back(\"L\"), y--;\n        else ans.push_back(\"R\"), y++;\n    }\n}\n\nvoid load_soil(int val) {\n    ans.push_back(\"+\" + to_string(val));\n    load += val;\n    H[x][y] -= val;\n}\n\nvoid unload_soil(int val) {\n    ans.push_back(\"-\" + to_string(val));\n    load -= val;\n    H[x][y] += val;\n}\n\nvoid process() {\n    memset(vis, 0, sizeof(vis));\n    vector<pair<int, int>> positives, negatives;\n    \n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            (H[i][j] > 0) ? positives.emplace_back(H[i][j], i*n+j) :\n            (H[i][j] < 0) ? negatives.emplace_back(-H[i][j], i*n+j) : void();\n        }\n    }\n\n    sort(positives.rbegin(), positives.rend());\n    sort(negatives.rbegin(), negatives.rend());\n\n    auto get = [&](int val) { return pair{val/n, val%n}; };\n\n    while (!positives.empty() && !negatives.empty()) {\n        auto [pval, pos] = positives.back(); positives.pop_back();\n        auto [nval, neg] = negatives.back(); negatives.pop_back();\n        auto [posx, posy] = get(pos);\n        auto [negx, negy] = get(neg);\n\n        if (pval == 0 || nval == 0) break;\n        int transfer = min(pval, nval);\n\n        move(posx, posy);\n        load_soil(transfer);\n        move(negx, negy);\n        unload_soil(transfer);\n\n        if (pval > transfer) positives.emplace_back(pval - transfer, pos);\n        if (nval > transfer) negatives.emplace_back(nval - transfer, neg);\n    }\n\n    while (!positives.empty()) {\n        auto [pval, pos] = positives.back(); positives.pop_back();\n        auto [posx, posy] = get(pos);\n        if (posx == x && posy == y) continue;\n        move(posx, posy);\n        load_soil(pval);\n    }\n\n    while (!negatives.empty()) {\n        auto [nval, neg] = negatives.back(); negatives.pop_back();\n        auto [negx, negy] = get(neg);\n        move(negx, negy);\n        unload_soil(nval);\n    }\n}\n\nint main() {\n    cin >> n;\n    for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) cin >> H[i][j];\n    \n    process();\n    for (auto& op : ans) cout << op << endl;\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\nusing namespace std;\n\nconstexpr int N = 6;\nconstexpr int SEED_COUNT = 2 * N * (N - 1);\nconstexpr int FIELD_SIZE = N * N;\n\nnamespace atcoder {\n    void internal_error() {\n        cerr << \"Error!\" << endl;\n        exit(0);\n    }\n\n    mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());\n\n    int rand(int a, int b) {\n        return uniform_int_distribution<int>(a, b)(mt);\n    }\n\n    double rand(double a, double b) {\n        return uniform_real_distribution<double>(a, b)(mt);\n    }\n}\nusing namespace atcoder;\n\nstruct Seed {\n    vector<int> eval;\n    int total;\n\n    Seed(const vector<int> &eval) : eval(eval) {\n        total = accumulate(eval.begin(), eval.end(), 0);\n    }\n\n    bool operator<(const Seed &other) const {\n        return this->total < other.total;\n    }\n};\n\nvector<int> next_gen(int round, const vector<Seed> &seeds) {\n    // Prioritize top seeds\n    vector<int> sorted_id(SEED_COUNT);\n    iota(sorted_id.begin(), sorted_id.end(), 0);\n    sort(sorted_id.begin(), sorted_id.end(), [&](int a, int b) {\n        return seeds[a].total > seeds[b].total;\n    });\n\n    vector<int> layout(FIELD_SIZE);\n    fill(layout.begin(), layout.end(), -1);\n    \n    // Place the N*N best seeds on the board\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            layout[i * N + j] = sorted_id[i * N + j];\n        }\n    }\n\n    return layout;\n}\n\nint main() {\n    int M, T;\n    cin >> N >> M >> T;\n\n    vector<Seed> seeds;\n    for (int i = 0; i < SEED_COUNT; ++i) {\n        vector<int> eval(M);\n        for (int &val : eval) cin >> val;\n        seeds.emplace_back(eval);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        auto layout = next_gen(t, seeds);\n        \n        for (int i = 0; i < FIELD_SIZE; ++i) {\n            cout << layout[i] << (i % N == N - 1 ? '\\n' : ' ');\n        }\n        cout << flush;\n\n        // Read the newly generated seeds\n        seeds.resize(SEED_COUNT);\n        for (int i = 0; i < SEED_COUNT; ++i) {\n            vector<int> eval(M);\n            for (int &val : eval) cin >> val;\n            seeds[i] = Seed(eval);\n        }\n    }\n}","ahc038":"#include <bits/stdc++.h>\n#include <queue>\n#include <optional>\nusing namespace std;\n\nconstexpr int INF = 1e9;\n\nstruct Pos {\n    int x, y;\n    bool operator==(const Pos& o) const { return x == o.x && y == o.y; }\n    Pos rotate(char c) const {\n        if (c == 'L') return {-y, x};\n        if (c == 'R') return {y, -x};\n        return {x, y};\n    }\n};\n\nstruct State {\n    int turns;\n    Pos pos;\n    vector<Pos> fingers; // relative positions\n    State(int t, Pos p, const vector<Pos>& f) : turns(t), pos(p), fingers(f) {}\n};\n\nvector<string> grid;\nvector<vector<char>> rotations;\nint dist(Pos a, Pos b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvector<string> find_path(Pos start, Pos goal, int V, const string& initial_rot = \"\") {\n    priority_queue<pair<int, State>, vector<pair<int, State>>, greater<>> pq;\n    unordered_map<Pos, int> dirs = {{'R', 0}, {'D', 1}, {'L', 2}, {'U', 3}};\n    vector<Pos> dir_offs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n    vector<string> dir_strs = {\"R\", \"D\", \"L\", \"U\"};\n    unordered_map<State, int, hash<State>> visited;\n    \n    vector<Pos> init_fingers(V - 1);\n    for (int i = 0; i < V - 1; ++i) {\n        init_fingers[i] = {i + 1, 0};\n    }\n    for (char c : initial_rot) {\n        if (c == '.') break;\n        for (auto& f : init_fingers) f = f.rotate(c);\n    }\n    \n    auto start_state = State(0, start, init_fingers);\n    pq.emplace(dist(start, goal), start_state);\n    visited[start_state] = 0;\n    \n    while (!pq.empty()) {\n        auto [current_cost, current] = pq.top();\n        pq.pop();\n        if (current.pos == goal) {\n            vector<string> path;\n            string rot = initial_rot.substr(0, V - 1);\n            while (current.turns > 0) {\n                path.emplace_back(dir_strs[current.pos.x] + rot + string(V, '.'));\n                for (char& c : rot) {\n                    if (c == 'R') c = 'L';\n                    else if (c == 'L') c = 'R';\n                }\n                reverse(rot.begin(), rot.end());\n                current.pos = goal;\n                --current.turns;\n            }\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        \n        for (int i = 0; i < 4; ++i) {\n            Pos next_pos = {current.pos.x + dir_offs[i].x, current.pos.y + dir_offs[i].y};\n            if (next_pos.x < 0 || next_pos.x >= grid.size() || next_pos.y < 0 || next_pos.y >= grid.size())\n                continue;\n            auto new_state = State(current.turns + 1, next_pos, current.fingers);\n            if (visited.count(new_state) && visited[new_state] <= new_state.turns)\n                continue;\n            visited[new_state] = new_state.turns;\n            pq.emplace(new_state.turns + dist(next_pos, goal), new_state);\n        }\n        \n        // Rotate subtrees\n        for (int v = 1; v < V; ++v) {\n            for (char rot : {'L', 'R'}) {\n                vector<Pos> new_fingers = current.fingers;\n                for (auto& f : new_fingers) f = f.rotate(rot);\n                auto rotated = State(current.turns + 1, current.pos, new_fingers);\n                if (visited.count(rotated) && visited[rotated] <= rotated.turns)\n                    continue;\n                visited[rotated] = rotated.turns;\n                pq.emplace(rotated.turns + dist(current.pos, goal), rotated);\n            }\n        }\n    }\n    return {};\n}\n\nint main() {\n    // Example input parsing; actual input handling depends on contest environment\n    int N = 20, M = 7, V = 8; \n    vector<pair<Pos, Pos>> tasks = {\n        {{0,0}, {15,5}}, {{3,2}, {17,7}}, {{5,5}, {18,18}}, \n        {{12,8}, {2,2}}, {{15,19}, {3,3}}, {{7,11}, {10,10}}, {{9,14}, {11,2}}\n    };\n    \n    cout << V << \"\\n\";\n    for (int i = 1; i < V; ++i) {\n        cout << \"0 \" << 1 << '\\n'; // star structure with length 1\n    }\n    cout << \"0 0\\n\"; // initial root position\n    \n    vector<bool> done(M, false);\n    Pos current = {0, 0};\n    int completed = 0;\n    \n    for (int steps = 0; completed < M; ++steps) {\n        pair<int, int> best = {INF, -1};\n        for (int i = 0; i < M; ++i) {\n            if (!done[i]) {\n                int cost = dist(current, tasks[i].first) + dist(tasks[i].first, tasks[i].second);\n                best = min(best, {cost, i});\n            }\n        }\n        int idx = best.second;\n        if (idx < 0) break;\n        \n        // Move to source\n        auto path1 = find_path(current, tasks[idx].first, V);\n        for (auto& s : path1) {\n            cout << s << '\\n';\n        }\n        current = tasks[idx].first;\n        \n        // Operation to grab\n        cout << \".\" + string(V - 1, '.') + string(V - 1, '.') << \"P\\n\";\n        \n        // Move to target\n        auto path2 = find_path(current, tasks[idx].second, V);\n        for (auto& s : path2) {\n            cout << s << '\\n';\n        }\n        \n        // Operation to release\n        cout << \".\" + string(V - 1, '.') + string(V - 1, '.') << \"P\\n\";\n        \n        done[idx] = true;\n        completed++;\n        current = tasks[idx].second;\n    }\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\nusing namespace std;\nusing namespace boost::geometry;\nusing namespace boost::geometry::index;\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint main() {\n    int N = 5000;\n    vector<pair<int, int>> mackerel(N), sardine(N);\n    for (int i = 0; i < 2*N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        if (i < N) mackerel[i] = {x, y};\n        else sardine[i-N] = {x, y};\n    }\n    \n    // K-means clustering for mackerels\n    int K = 15;\n    vector<vector<pair<int, int>>> clusters(K);\n    vector<pair<int, int>> centroids(K);\n    for (auto& [x, y] : mackerel) {\n        int idx = uniform_int_distribution<>(0, K-1)(rng);\n        centroids[idx].first += x;\n        centroids[idx].second += y;\n        clusters[idx].emplace_back(x, y);\n    }\n    for (int i = 0; i < 10; ++i) {\n        for (auto& cl : clusters) cl.clear();\n        for (auto& [x, y] : mackerel) {\n            int best = 0, min_dist = INT_MAX;\n            for (int j = 0; j < K; ++j) {\n                auto& [cx, cy] = centroids[j];\n                int dist = (x - cx)*(x - cx) + (y - cy)*(y - cy);\n                if (dist < min_dist) {\n                    min_dist = dist;\n                    best = j;\n                }\n            }\n            clusters[best].emplace_back(x, y);\n        }\n        for (int j = 0; j < K; ++j) {\n            if (!clusters[j].empty()) {\n                centroids[j] = {0, 0};\n                for (auto& [x, y] : clusters[j]) {\n                    centroids[j].first += x;\n                    centroids[j].second += y;\n                }\n                centroids[j].first /= clusters[j].size();\n                centroids[j].second /= clusters[j].size();\n            }\n        }\n    }\n\n    // Build sardine R-Tree\n    rtree<pair<int, int>, rstar<16>> sardine_tree;\n    for (auto& [x, y] : sardine) sardine_tree.insert({x, y});\n\n    vector<tuple<int, int, int, int>> candidates;\n    for (auto& cls : clusters) {\n        if (cls.empty()) continue;\n        int min_x = INT_MAX, max_x = -1, min_y = INT_MAX, max_y = -1;\n        for (auto& [x, y] : cls) {\n            min_x = min(min_x, x); max_x = max(max_x, x);\n            min_y = min(min_y, y); max_y = max(max_y, y);\n        }\n        if (max_x - min_x + max_y - min_y <= 4e5 / 4 && max_x - min_x > 0 && max_y - min_y > 0) {\n            candidates.emplace_back(min_x, min_y, max_x, max_y);\n        }\n    }\n    \n    if (candidates.empty()) {\n        cout << \"4\\n0 0\\n0 100000\\n100000 100000\\n100000 0\\n\";\n        return 0;\n    }\n    \n    auto best_rect = *max_element(candidates.begin(), candidates.end(), \n        [&](const auto& a, const auto& b) {\n            int a_count = 0, b_count = 0;\n            for (auto& s : sardine) {\n                if (a <= get<0>(s) && get<0>(s) <= get<2>(a) &&\n                    a <= get<1>(s) && get<1>(s) <= get<3>(a)) a_count++;\n                if (b <= get<0>(s) && get<0>(s) <= get<2>(b) &&\n                    b <= get<1>(s) && get<1>(s) <= get<3>(b)) b_count++;\n            }\n            return (get<2>(a)-get<0>(a)+get<3>(a)-get<1>(a))-a_count < \n                   (get<2>(b)-get<0>(b)+get<3>(b)-get<1>(b))-b_count;\n        });\n    \n    auto [x1, y1, x2, y2] = best_rect;\n    // Build polygon\n    vector<pair<int, int>> poly = {{x1,y1}, {x1,y2}, {x2,y2}, {x2,y1}};\n    cout << poly.size() << '\\n';\n    for (auto& [x, y] : poly) cout << x << ' ' << y << '\\n';\n    \n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\nusing namespace std;\nusing namespace boost::geometry;\n\nstruct Rect {\n    int x, y, w, h;\n    bool rotated;\n};\n\nvector<pair<int, int>> sizes;\nvector<int> order;\nint N, T;\ndouble start_temp = 1e3, end_temp = 1e-5;\nmt19937 mt(chrono::steady_clock::now().time_since_epoch().count());\n\npair<int, int> place_rects(const vector<int>& perm, bool left_first = false, int mode = 0) {\n    map<pair<int, int>, int> points;\n    points[{0, 0}] = -1;\n    vector<Rect> rects;\n    int max_x = 0, max_y = 0;\n    \n    auto update_max = [&](int x, int y) {\n        max_x = max(max_x, x);\n        max_y = max(max_y, y);\n    };\n    \n    auto can_place = [&](int x, int y, int w, int h) {\n        model::box<point<int>> box(point(x, y), point(x + w, y + h));\n        for (auto& r : rects) {\n            if (overlaps(box, model::box<point<int>>(\n                point(r.x, r.y), point(r.x + r.w, r.y + r.h))\n            )) return false;\n        }\n        return true;\n    };\n    \n    int idx = 0;\n    for (int op : perm) {\n        int rw = max(sizes[op].first, sizes[op].second);\n        int rh = min(sizes[op].first, sizes[op].second);\n        bool rot = (sizes[op].first < sizes[op].second);\n        bool placed = false;\n        \n        for (int step = 0; step < 2; ++step) { // 2 orientations\n            if (step == 1) swap(rw, rh), rot = !rot;\n            // Try U (up) first\n            if (!left_first || idx++ % 2 == mode) {\n                for (auto [pt, prev] : points) {\n                    int x = pt.first, y_try = pt.second;\n                    if (can_place(x, y_try, rw, rh)) {\n                        rects.push_back({x, y_try, rw, rh, rot});\n                        points[{x + rw, y_try + rh}] = prev;\n                        update_max(x + rw, y_try + rh);\n                        placed = true;\n                        break;\n                    }\n                }\n                if (placed) break;\n            }\n            // Then try L (left)\n            if (left_first || idx % 2 != mode) {\n                for (auto [pt, prev] : points) {\n                    int y = pt.second, x_try = pt.first;\n                    if (can_place(x_try, y, rw, rh)) {\n                        rects.push_back({x_try, y, rw, rh, rot});\n                        points[{x_try + rw, y + rh}] = prev;\n                        update_max(x_try + rw, y + rh);\n                        placed = true;\n                        break;\n                    }\n                }\n                if (placed) break;\n            }\n        }\n        if (!placed) { max_x += rw; max_y += rh; } // penalty for unused\n    }\n    return {max_x, max_y};\n}\n\nvoid solve() {\n    cin >> N >> T;\n    double sigma; cin >> sigma;\n    sizes.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> sizes[i].first >> sizes[i].second;\n        sizes[i].first += 3 * sigma;  // Upper approx\n        sizes[i].second += 3 * sigma;\n        if (sizes[i].first > 1e9) sizes[i].first = 1e9;\n        if (sizes[i].second > 1e9) sizes[i].second = 1e9;\n        order.push_back(i);\n    }\n    \n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return max(sizes[a].first, sizes[a].second) > max(sizes[b].first, sizes[b].second);\n    });\n    \n    auto best = place_rects(order);\n    auto best_order = order;\n    \n    // Simulated Annealing\n    for (int iteration = 0; iteration < 30; ++iteration) {\n        auto current = order;\n        for (double temp = start_temp; temp > end_temp; temp *= 0.99) {\n            int i = uniform_int_distribution<>(0, N-1)(mt);\n            int j = uniform_int_distribution<>(0, N-1)(mt);\n            swap(current[i], current[j]);\n            \n            auto candidate = place_rects(current, iteration % 2 == 0, iteration / 10);\n            int current_score = best.first + best.second;\n            int candidate_score = candidate.first + candidate.second;\n            \n            if (candidate_score < current_score || \n                exp((current_score - candidate_score) / temp) > (double)mt()/mt.max()) {\n                best = candidate;\n            } else {\n                swap(current[i], current[j]); // revert\n            }\n        }\n    }\n    \n    for (int t = 0; t < T; ++t) {\n        cout << N << '\\n';\n        for (size_t i = 0; i < best_order.size(); ++i) {\n            int id = best_order[i];\n            cout << id << ' ' << \"0\" << ' ' << (i % 2 ? 'L' : 'U') << ' ' << (i > 0 ? best_order[i-1] : -1) << '\\n';\n        }\n        cout.flush();\n        \n        int W, H;\n        cin >> W >> H;\n        if (t == T-1) break;\n        \n        // Optional: Adjust based on feedback if needed\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing i64 = long long;\nconstexpr int INF = (int)1e9 + 5;\nconstexpr i64 LINF = (i64)1e18 + 5;\n\nstruct Edge {\n    int to;\n};\n\nint main() {\n    int N, M, H;\n    cin >> N >> M >> H;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> A[i];\n    }\n\n    vector<vector<Edge>> G(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        G[u].push_back({v});\n        G[v].push_back({u});\n    }\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    vector<int> parent(N, -1);\n    vector<bool> used(N, false);\n    vector<pair<int, int>> order;\n    for (int i = 0; i < N; ++i) {\n        order.emplace_back(A[i], i);\n    }\n\n    auto cmp = [&](pair<int, int> a, pair<int, int> b) {\n        return a.first > b.first || (a.first == b.first && a.second < b.second);\n    };\n    sort(order.begin(), order.end(), cmp);\n\n    for (auto [a, v] : order) {\n        if (used[v]) continue;\n        queue<int> que, next_que;\n        que.push(v);\n        used[v] = true;\n        int height = 0;\n        vector<int> current_level;\n\n        while (!que.empty() && height <= H) {\n            while (!que.empty()) {\n                int u = que.front();\n                que.pop();\n                current_level.push_back(u);\n\n                for (Edge& e : G[u]) {\n                    if (!used[e.to]) {\n                        used[e.to] = true;\n                        next_que.push(e.to);\n                        if (height + 1 < H) {\n                            parent[e.to] = u;\n                        }\n                    }\n                }\n            }\n            que = next_que;\n            queue<int> empty;\n            swap(next_que, empty);\n            ++height;\n        }\n\n        if (height == H + 1) {\n            for (int u : current_level) {\n                parent[u] = -1;\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << parent[i] << (i == N - 1 ? '\\n' : ' ');\n    }\n\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<pair<char, int>> remove_row_oni(int row, int start, int end, const vector<string>& board) {\n    vector<pair<char, int>> operations;\n    if (start < end) {\n        for (int k = 0; k <= start; ++k) operations.emplace_back('L', row);\n        for (int k = 0; k <= end; ++k) operations.emplace_back('R', row);\n    } else {\n        for (int k = 0; k <= (19 - start); ++k) operations.emplace_back('R', row);\n        for (int k = 0; k <= (19 - end); ++k) operations.emplace_back('L', row);\n    }\n    return operations;\n}\n\nvector<pair<char, int>> remove_column_oni(int col, int start, int end, const vector<string>& board) {\n    vector<pair<char, int>> operations;\n    if (start < end) {\n        for (int k = 0; k <= start; ++k) operations.emplace_back('U', col);\n        for (int k = 0; k <= end; ++k) operations.emplace_back('D', col);\n    } else {\n        for (int k = 0; k <= (19 - start); ++k) operations.emplace_back('D', col);\n        for (int k = 0; k <= (19 - end); ++k) operations.emplace_back('U', col);\n    }\n    return operations;\n}\n\nint main() {\n    int N = 20;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    vector<pair<char, int>> operations;\n    \n    // Process each row\n    for (int i = 0; i < N; ++i) {\n        int first_oni = -1, last_oni = -1;\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                if (first_oni == -1) first_oni = j;\n                last_oni = j;\n            }\n        }\n        if (first_oni != -1) {\n            auto row_ops = remove_row_oni(i, first_oni, last_oni, board);\n            operations.insert(operations.end(), row_ops.begin(), row_ops.end());\n        }\n    }\n\n    // Process each column\n    for (int j = 0; j < N; ++j) {\n        int first_oni = -1, last_oni = -1;\n        for (int i = 0; i < N; ++i) {\n            if (board[i][j] == 'x') {\n                if (first_oni == -1) first_oni = i;\n                last_oni = i;\n            }\n        }\n        if (first_oni != -1) {\n            auto col_ops = remove_column_oni(j, first_oni, last_oni, board);\n            operations.insert(operations.end(), col_ops.begin(), col_ops.end());\n        }\n    }\n\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing namespace boost::multiprecision;\n\nusing lint = long long;\nusing P = pair<lint, int>; \nconstexpr lint INF = 1LL<<60;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N = 100;\n    lint L = 500000;\n    cin >> N >> L;\n    vector<lint> T(N);\n    for (auto& t : T) cin >> t;\n    \n    vector<int> a(N), b(N), cnt(N);\n    priority_queue<P> pq;\n    for (int i=0; i<N; ++i) pq.emplace(T[i], i);\n    \n    vector<bool> used(N, false);\n    auto pick_next = [&](int cur) {\n        for (int j=0; j<N; ++j) {\n            if (!used[j] && j != cur) {\n                used[j] = true;\n                return j;\n            }\n        }\n        return (cur + 1) % N;\n    };\n    \n    int prev = -1;\n    bool even = true;\n    \n    while (!pq.empty()) {\n        auto [need, idx] = pq.top(); pq.pop();\n        if (cnt[idx] >= need) continue;\n        \n        if (prev != -1) {\n            if (even) a[prev] = idx;\n            else b[prev] = idx;\n        }\n        ++cnt[idx];\n        pq.emplace(need - cnt[idx], idx);\n        prev = idx;\n        even ^= true;\n    }\n    \n    for (int i=0; i<N; ++i) {\n        if (cnt[i] < T[i]) a[i] = i;\n    }\n    \n    for (int i=0; i<N; ++i) {\n        cout << a[i] << \" \" << b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\nusing ll = long long;\nusing P = pair<int, int>;\n\nconst int INF = 1e9;\nrandom_device rd;\nmt19937 RNG(rd());\n\nstruct City {\n    int idx;\n    int cx, cy; // center\n    City(int i, int lx, int rx, int ly, int ry) \n        : idx(i), cx((lx+rx)/2), cy((ly+ry)/2) {}\n    bool operator<(const City& o) const {\n        return make_pair(cx, cy) < make_pair(o.cx, o.cy);\n    }\n};\n\nvector<int> query_group(const vector<City>& group) {\n    if (group.size() < 2) return {};\n    cout << \"? \" << group.size();\n    for (auto& c : group) cout << \" \" << c.idx;\n    cout << endl;\n    \n    vector<int> res;\n    int edges = group.size() - 1;\n    for (int i=0; i < edges; ++i) {\n        int u, v; cin >> u >> v;\n        if (u > v) swap(u, v);\n        res.emplace_back(u);\n        res.emplace_back(v);\n    }\n    return res;\n}\n\nvoid solve() {\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (auto& g : G) cin >> g;\n    \n    vector<City> cities;\n    for (int i=0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cities.emplace_back(i, lx, rx, ly, ry);\n    }\n    sort(cities.begin(), cities.end());\n    \n    // Assign cities to groups\n    vector<vector<int>> groups(M);\n    int pos = 0;\n    for (int i=0; i < M; ++i) {\n        for (int j=0; j < G[i]; ++j, ++pos) {\n            groups[i].push_back(cities[pos].idx);\n        }\n    }\n\n    // Query MST and build connections\n    vector<tuple<int, int, int>> all_edges;\n    for (auto& group : groups) {\n        vector<City> current_group;\n        for (auto idx : group) {\n            for (auto& c : cities) {\n                if (c.idx == idx) {\n                    current_group.push_back(c);\n                    break;\n                }\n            }\n        }\n        vector<int> raw = query_group(current_group);\n        for (size_t i=0; i < raw.size(); i += 2) {\n            int u = raw[i], v = raw[i+1];\n            all_edges.emplace_back(u, v, hypot(\n                cities[u].cx - cities[v].cx,\n                cities[u].cy - cities[v].cy\n            ));\n        }\n    }\n    \n    // Collect all cities and ensure they are connected\n    vector<int> remaining_cities;\n    for (auto& e : all_edges) remaining_cities.push_back(get<0>(e));\n    sort(remaining_cities.begin(), remaining_cities.end());\n    remaining_cities.erase(unique(remaining_cities.begin(), remaining_cities.end()), remaining_cities.end());\n    \n    // Assign leftovers\n    set<int> used(remaining_cities.begin(), remaining_cities.end());\n    for (auto& c : cities) if (!used.count(c.idx)) remaining_cities.push_back(c.idx);\n    \n    // Form final groups respecting exact group sizes\n    vector<vector<int>> ans_groups;\n    for (int i=0; i < M; ++i) {\n        if (i < groups.size()) {\n            ans_groups.push_back(groups[i]);\n        } else {\n            ans_groups.emplace_back();\n        }\n    }\n\n    int start = 0;\n    for (int sz : G) {\n        ans_groups.emplace_back(vector<int>(remaining_cities.begin() + start, remaining_cities.begin() + start + sz));\n        start += sz;\n    }\n\n    cout << \"!\" << endl;\n    for (auto& group : ans_groups) {\n        for (auto idx : group) cout << idx << \" \";\n        cout << endl;\n        sort(group.begin(), group.end());\n        for (size_t i=1; i < group.size(); ++i) {\n            cout << group[i-1] << \" \" << group[i] << endl;\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    solve();\n    \n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define INF (1LL << 60)\ntypedef long long ll;\ntypedef tree<pair<pair<int, int>, vector<pair<int, int>>>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> oset;\n\nstruct VecHash {\n    size_t operator()(const vector<pair<int, int>>& v) const {\n        size_t seed = 0;\n        for (auto x : v) {\n            seed ^= x.first + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            seed ^= x.second + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n        }\n        return seed;\n    }\n};\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dir[] = {'U', 'D', 'L', 'R'};\n\nvoid astar(vector<pair<int, int>>& goals) {\n    int startX = goals.front().first;\n    int startY = goals.front().second;\n    goals.erase(goals.begin());\n    \n    oset pq;\n    map<pair<pair<int, int>, vector<pair<int, int>>>, int, VecHash> dist;\n    pq.insert({{0, {startX, startY, goals}}, {}});\n    dist[{{startX, startY}, goals}] = 0;\n\n    auto get_priority = [&](int x, int y, const auto& path_rem) {\n        int h = 0;\n        if (!path_rem.empty()) {\n            int nx = path_rem[0].first, ny = path_rem[0].second;\n            h = max(abs(nx - x), abs(ny - y));\n        }\n        for (size_t i = 1; i < path_rem.size(); ++i) {\n            int px = path_rem[i-1].first, py = path_rem[i-1].second;\n            int cx = path_rem[i].first, cy = path_rem[i].second;\n            h += max(abs(cx - px), abs(cy - py));\n        }\n        return h + (int)path_rem.size();\n    };\n\n    while (!pq.empty()) {\n        auto current = pq.begin()->second;\n        pq.erase(pq.begin());\n        int x = current.first;\n        int y = current.second.first;\n        auto remaining = current.second.second;\n        \n        if (remaining.empty()) {\n            for (auto& move : dist[current.first]) {\n                cout << move.first << ' ' << move.second << '\\n';\n            }\n            exit(0);\n        }\n\n        int curr_dist = dist[current.first];\n        for (int d = 0; d < 4; ++d) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx < 0 || nx >= 20 || ny < 0 || ny >= 20) continue;\n\n            bool blocked = false;\n            vector<pair<int, int>> new_rem = remaining;\n            if (new_rem.size() > 0 && new_rem[0] == make_pair(nx, ny)) {\n                new_rem.erase(new_rem.begin());\n            }\n\n            string actions = \"MS\";\n            for (char action : actions) {\n                int tx = x, ty = y, steps = 1;\n                if (action == 'S') {\n                    while (tx + dx[d] >= 0 && tx + dx[d] < 20 && ty + dy[d] >= 0 && ty + dy[d] < 20 && \n                           (new_rem.empty() || make_pair(tx+dx[d], ty+dy[d]) != new_rem[0])) {\n                        tx += dx[d]; ty += dy[d]; ++steps;\n                    }\n                    if (new_rem.size() > 0 && make_pair(tx, ty) != new_rem[0]) continue;\n                    if (!new_rem.empty() && make_pair(tx, ty) == new_rem[0]) {\n                        vector<pair<int, int>> next_rem = new_rem;\n                        next_rem.erase(next_rem.begin());\n                        new_rem = next_rem;\n                    }\n                } else {\n                    tx = nx; ty = ny;\n                }\n                \n                if (dist.count({{tx, ty}, new_rem}) && dist[{{tx, ty}, new_rem}] <= curr_dist + 1) continue;\n\n                dist[{{tx, ty}, new_rem}] = curr_dist + 1;\n                int priority = curr_dist + get_priority(tx, ty, new_rem) + 1;\n                pq.insert({{priority, {tx, ty, new_rem}}, {action, dir[d]}});\n                \n                if (action == 'S') dist[{{tx, ty}, new_rem}].push_back({action, dir[d]});\n            }\n        }\n    }\n}\n\nint main() {\n    int N, M; cin >> N >> M;\n    vector<pair<int, int>> goals(M);\n    for (int i = 0; i < M; ++i) {\n        int x, y; cin >> x >> y;\n        goals[i] = {x, y};\n    }\n    astar(goals);\n    return 0;\n}"},"4":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int x, y, r, id;\n    bool placed = false;\n};\n\nbool cmp(const Company& a, const Company& b) {\n    return a.r > b.r;  // Larger first\n}\n\nvector<tuple<int,int,int,int>> placeAds(const vector<Company>& companies) {\n    int N = companies.size();\n    vector<tuple<int,int,int,int>> result(N);\n    set<pair<int,int>> occupied;\n    \n    vector<bool> used(N, false);\n    for (const auto& comp : companies) {\n        if (!comp.placed) {\n            int x = comp.x, y = comp.y;\n            // Try to expand rectangle while avoiding overlaps\n            int width = 1, height = comp.r;\n            bool valid = true;\n            for (int dx = 0; dx < width && valid; ++dx)\n                for (int dy = 0; dy < height; ++dy)\n                    if (occupied.count({x+dx, y+dy})) valid = false;\n            if (valid) {\n                for (int dx=0; dx<width; ++dx)\n                    for (int dy=0; dy<height; ++dy)\n                        occupied.emplace(x+dx, y+dy);\n                result[comp.id] = {x, y, x+width, y+height};\n                used[comp.id] = true;\n            } else {\n                // If vertical expansion fails, try horizontal\n                swap(width, height);\n                valid = true;\n                for (int dx = 0; dx < width; ++dx)\n                    for (int dy = 0; dy < height; ++dy)\n                        if (occupied.count({x+dx, y+dy})) valid = false;\n                if (valid) {\n                    for (int dx=0; dx<width; ++dx)\n                        for (int dy=0; dy<height; ++dy)\n                            occupied.emplace(x+dx, y+dy);\n                    result[comp.id] = {x, y, x+width, y+height};\n                    used[comp.id] = true;\n                }\n            }\n        }\n    }\n    \n    // Fill remaining gaps\n    for (int i=0; i<N; ++i) {\n        if (!used[i]) {\n            int x = companies[i].x, y = companies[i].y;\n            int side = max(1, (int)sqrt(companies[i].r));\n            bool found = false;\n            for (int a = max(0, x-side); !found && a <= x+side; ++a) {\n                for (int b = max(0, y-side); !found && b <= y+side; ++b) {\n                    bool valid = true;\n                    for (int dx=0; dx<side && a+dx <= 10000; ++dx) {\n                        for (int dy=0; dy<side && b+dy <= 10000; ++dy) {\n                            if (occupied.count({a+dx, b+dy})) {\n                                valid = false;\n                                break;\n                            }\n                        }\n                        if (!valid) break;\n                    }\n                    if (valid && (a+side <= 10000) && (b+side <= 10000)) {\n                        for (dx=0; dx<side; ++dx)\n                            for (dy=0; dy<side; ++dy)\n                                occupied.emplace(a+dx, b+dy);\n                        result[i] = {a, b, a+side, b+side};\n                        found = true;\n                    }\n                }\n            }\n            if (!found) { // Fallback\n                result[i] = {companies[i].x, companies[i].y, companies[i].x+1, companies[i].y+1};\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    int n; cin >> n;\n    vector<Company> companies(n);\n    for (int i=0; i<n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n        companies[i].id = i;\n    }\n    sort(companies.begin(), companies.end(), cmp);\n\n    auto ans = placeAds(companies);\n    for (auto& [a,b,c,d] : ans)\n        cout << a << ' ' << b << ' ' << c << ' ' << d << '\\n';\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nconst int MAXN = 50;\nvector<vector<int>> tiles(MAXN, vector<int>(MAXN));\nvector<vector<int>> points(MAXN, vector<int>(MAXN));\nvector<pair<int, int>> dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};  // U, D, L, R\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nbool inside(int x, int y) { return x >= 0 && x < MAXN && y >= 0 && y < MAXN; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n    \n    for(int i=0; i<MAXN; ++i) for(int j=0; j<MAXN; ++j) cin >> tiles[i][j];\n    for(int i=0; i<MAXN; ++j) for(int j=0; j<MAXN; ++j) cin >> points[i][j];\n\n    auto solve = [&]() {\n        int best_score = 0;\n        string best_path;\n        vector<vector<bool>> visited(MAXN, vector<bool>(MAXN, false));\n        set<int> used_tiles;\n        visited[si][sj] = true;\n        used_tiles.insert(tiles[si][sj]);\n        string current_path;\n        int current_x = si, current_y = sj;\n        int current_score = points[si][sj];\n\n        auto dfs = [&](auto &&self, int x, int y, int score) -> void {\n            if (score > best_score) {\n                best_score = score;\n                best_path = current_path;\n            }\n            \n            vector<pair<int, int>> possible_moves;\n            for (auto& [dx, dy] : dirs) {\n                int nx = x + dx, ny = y + dy;\n                if (!inside(nx, ny) || visited[nx][ny] || used_tiles.count(tiles[nx][ny])) continue;\n                int nxt_score = score + points[nx][ny];\n                possible_moves.emplace_back(nxt_score, make_pair(nx, ny));\n            }\n\n            if (possible_moves.empty()) return;\n            shuffle(possible_moves.begin(), possible_moves.end(), rng);\n\n            for (auto [_, coord] : possible_moves) {\n                auto [nx, ny] = coord;\n                visited[nx][ny] = true;\n                used_tiles.insert(tiles[nx][ny]);\n                \n                if (nx < x) current_path += 'U';\n                if (nx > x) current_path += 'D';\n                if (ny < y) current_path += 'L';\n                if (ny > y) current_path += 'R';\n                \n                int new_score = score + points[nx][ny];\n                self(self, nx, ny, new_score);\n                \n                if (nx < x) current_path.pop_back();  // Undo\n                if (nx > x) current_path.pop_back();\n                if (ny < y) current_path.pop_back();\n                if (ny > y) current_path.pop_back();\n                \n                visited[nx][ny] = false;\n                used_tiles.erase(tiles[nx][ny]);\n            }\n        };\n\n        dfs(dfs, current_x, current_y, current_score);\n\n        cout << best_path << endl;\n    };\n\n    solve();\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n\nusing namespace std;\n\nvoid solve() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr); // Fast IO\n    \n    for (int q = 0; q < 1000; ++q) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        string path;\n        \n        // Move horizontally first (align columns)\n        int sgn = (sj < tj) ? 1 : -1;\n        while (sj != tj) {\n            path += (sgn == 1 ? 'R' : 'L');\n            sj += sgn;\n        }\n        // Move vertically (align rows)\n        sgn = (si < ti) ? 1 : -1;\n        while (si != ti) {\n            path += (sgn == 1 ? 'D' : 'U');\n            si += sgn;\n        }\n        \n        cout << path << endl;\n        int result;\n        cin >> result;\n    }\n}\n\nint main() {\n    solve();\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Entry {\n    char ch;\n    int freq;\n    bool operator<(const Entry& other) const {\n        return freq > other.freq || (freq == other.freq && ch < other.ch);\n    }\n};\n\nvector<string> solve(int N, vector<string>& S) {\n    vector<vector<map<char, int>>> freq(N, vector<map<char, int>>(N));\n\n    // Compute frequency of each char in possible subsequences\n    for (auto& s : S) {\n        int len = s.size();\n        for (int start = 0; start < N; ++start) {\n            for (int p = 0; p < len; ++p) {\n                // Horizontal (rows)\n                freq[start][(p % N)][s[p]]++;\n                // Vertical (cols)\n                freq[(p % N)][start][s[p]]++;\n            }\n        }\n    }\n\n    // Build initial matrix based on frequency\n    vector<string> mat(N, string(N, '.'));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            vector<Entry> entries;\n            for (char c = 'A'; c <= 'H'; ++c) {\n                entries.push_back({c, freq[i][j][c]});\n            }\n            sort(entries.begin(), entries.end());\n            mat[i][j] = entries[0].ch;\n        }\n    }\n\n    auto can_place = [&](int x, int y, const string& s, bool vert) {\n        for (size_t idx = 0; idx < s.size(); ++idx) {\n            int i = vert ? (x + idx) % N : x;\n            int j = vert ? y : (y + idx) % N;\n            if (mat[i][j] != '.' && mat[i][j] != s[idx]) return false;\n        }\n        return true;\n    };\n\n    auto place = [&](int x, int y, const string& s, bool vert) {\n        for (size_t idx = 0; idx < s.size(); ++idx) {\n            int i = vert ? (x + idx) % N : x;\n            int j = vert ? y : (y + idx) % N;\n            if (mat[i][j] == '.') mat[i][j] = s[idx];\n        }\n    };\n\n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(S.begin(), S.end(), gen);\n    sort(S.rbegin(), S.rend(), [](const string& a, const string& b) {\n        return a.size() > b.size();\n    });\n\n    for (auto& s : S) {\n        for (int t = 0; t < 1; ++t) {\n            bool placed = false;\n            for (int i = 0; i < N && !placed; ++i) {\n                for (int j = 0; j < N && !placed; ++j) {\n                    bool pick_vert = (t == 0 && gen() % 2) || (t == 1 && (gen() % 4 == 0));\n                    if (can_place(i, j, s, pick_vert)) {\n                        place(i, j, s, pick_vert);\n                        placed = true;\n                    } else if (can_place(i, j, s, !pick_vert)) {\n                        place(i, j, s, !pick_vert);\n                        placed = true;\n                    }\n                }\n            }\n        }\n    }\n\n    // Post-processing to fill empty spots intelligently\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (mat[i][j] != '.') continue;\n            set<char> valid;\n            for (char c = 'A'; c <= 'H'; ++c) {\n                bool valid_horiz = true, valid_vert = true;\n                for (int k = 0; k < 1; ++k) {\n                    int ni = (i + k) % N;\n                    int nj = (j + k) % N;\n                    if (nj < N-1 && mat[ni][nj+1] != '.' && mat[ni][nj+1] != c) valid_horiz = false;\n                    if (ni < N-1 && mat[ni+1][nj] != '.' && mat[ni+1][nj] != c) valid_vert = false;\n                }\n                if (valid_horiz || valid_vert) valid.insert(c);\n            }\n            mat[i][j] = valid.empty() ? 'A' : *valid.begin();\n        }\n    }\n    \n    return mat;\n}\n\nint main() {\n    int N = 20, M;\n    cin >> N >> M;\n    vector<string> S(M);\n    for (auto& s : S) cin >> s;\n    vector<string> ans = solve(N, S);\n    \n    for (auto& row : ans) cout << row << endl;\n    return 0;\n}","ahc005":"#include <algorithm>\n#include <random>\n#include <vector>\n#include <cmath>\n#include <iostream>\n#include <tuple>\n\nusing namespace std;\nmt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());\n\nstruct State {\n    int N;\n    vector<string> grid;\n    int si, sj;\n    vector<pair<int, int>> path;\n    long long cost = 0;\n    State(int _N, vector<string> _grid, int _si, int _sj) \n        : N(_N), grid(_grid), si(_si), sj(_sj) {\n        path.push_back({si, sj});\n    }\n\n    void compute_cost() {\n        cost = 0;\n        for (size_t i = 1; i < path.size(); ++i) {\n            int x1 = path[i-1].first, y1 = path[i-1].second;\n            int x2 = path[i].first, y2 = path[i].second;\n            if (x1 == x2) cost += abs(y2 - y1) * (grid[x1][max(y1, y2)] - '0');\n            else cost += abs(x2 - x1) * (grid[max(x1, x2)][y1] - '0');\n        }\n    }\n\n    bool covers_all() {\n        vector<bool> rows(N, false), cols(N, false);\n        for (auto &[x, y] : path) {\n            rows[x] = true;\n            cols[y] = true;\n        }\n        for (int i = 0; i < N; ++i) {\n            if (rows[i] || cols[i]) continue;\n            bool has_road = false;\n            for (int j = 0; j < N; ++j) if (grid[i][j] != '#') has_road = true;\n            if (has_road) return false;\n            for (int j = 0; j < N; ++j) if (grid[j][i] != '#') has_road = true;\n            if (has_road) return false;\n        }\n        return true;\n    }\n\n    void anneal(long long T, int iterations) {\n        uniform_real_distribution<> dist(0.0, 1.0);\n        compute_cost();\n        long long current_cost = cost;\n        auto best_state = *this;\n        long long best_cost = current_cost;\n\n        for (int step = 0; step < iterations; ++step) {\n            double t = T * pow(0.999, step);\n            auto neighbor = *this;\n            int pos = uniform_int_distribution<>(1, path.size()-2)(rng);\n            swap(neighbor.path[pos], neighbor.path[pos+1]);\n            neighbor.compute_cost();\n            \n            if (neighbor.cost < current_cost || dist(rng) < exp((current_cost - neighbor.cost) / t)) {\n                swap(path, neighbor.path);\n                current_cost = neighbor.cost;\n                if (current_cost < best_cost) {\n                    best_cost = current_cost;\n                    best_state = *this;\n                }\n            }\n        }\n        *this = best_state;\n    }\n};\n\nstring solve(int N, int si, int sj, vector<string>& grid) {\n    State state(N, grid, si, sj);\n    vector<int> rows, cols;\n\n    for (int i = 0; i < N; ++i) {\n        bool has_road = false;\n        for (int j = 0; j < N; ++j) if (grid[i][j] != '#') has_road = true;\n        if (has_road) rows.push_back(i);\n    }\n    for (int j = 0; j < N; ++j) {\n        bool has_road = false;\n        for (int i = 0; i < N; ++i) if (grid[i][j] != '#') has_road = true;\n        if (has_road) cols.push_back(j);\n    }\n\n    for (int r : rows) {\n        if (state.path.back().first != r) state.path.emplace_back(r, state.path.back().second);\n        state.path.emplace_back(r, sj);\n    }\n    for (int c : cols) {\n        if (state.path.back().second != c) state.path.emplace_back(state.path.back().first, c);\n    }\n    state.path.push_back({si, sj});\n\n    if (!state.covers_all()) return \"ERROR\";\n    state.anneal(1e13, 1e4);\n\n    string route;\n    int px = si, py = sj;\n    for (auto &[x, y] : state.path) {\n        if (x < px) while (px > x) { route += 'U'; px--; }\n        if (x > px) while (px < x) { route += 'D'; px++; }\n        if (y < py) while (py > y) { route += 'L'; py--; }\n        if (y > py) while (py < y) { route += 'R'; py++; }\n    }\n    return route;\n}\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (auto &row : grid) cin >> row;\n    cout << solve(N, si, sj, grid) << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconstexpr int INF = 1e9;\n\nstruct Task {\n    vector<int> skills;\n    vector<int> children;\n    int done_day = -1;\n    int indeg = 0;\n    bool started = false;\n};\n\nint N = 1000, M = 20;\nvector<Task> tasks;\nvector<vector<int>> finished_tasks; // finished_tasks[member] = list of tasks\nvector<array<int, 1024>> skill_estimates(M, array<int, 1024>{});\n\nvoid print_flush(const vector<pair<int, int>>& assignments) {\n    if (assignments.empty()) {\n        cout << \"0\\n\";\n    } else {\n        cout << assignments.size();\n        for (auto& [a, b] : assignments) cout << ' ' << a+1 << ' ' << b+1;\n        cout << '\\n';\n    }\n    fflush(stdout);\n}\n\nint estimate_time(int member, int task_id) {\n    int sum_excess = 0;\n    for (size_t k = 0; k < tasks[task_id].skills.size(); ++k) {\n        int req = tasks[task_id].skills[k];\n        int est = skill_estimates[member][k];\n        if (req > est) sum_excess += req - est;\n    }\n    return sum_excess == 0 ? 1 : max(1, sum_excess - 3 + (rand() % 7));\n}\n\nvoid update_skills(int member, int task_id, int days) {\n    auto& skills = skill_estimates[member];\n    int excess = max(1, days - 3 + (rand() % 7)) - 1;\n    for (size_t k = 0; k < tasks[task_id].skills.size(); ++k) {\n        int req = tasks[task_id].skills[k];\n        if (req > skills[k]) skills[k] = min(req, skills[k] + excess);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int K, R;\n    cin >> N >> M >> K >> R;\n    tasks.resize(N);\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            int d;\n            cin >> d;\n            tasks[i].skills.push_back(d);\n        }\n    }\n    \n    vector<vector<int>> deps(N);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        deps[u].push_back(v);\n        tasks[v].indeg++;\n    }\n    \n    priority_queue<pair<int, int>> pq; // (completion day estimate, task_id)\n    for (int i = 0; i < N; ++i) if (tasks[i].indeg == 0) pq.emplace(0, i);\n    \n    vector<bool> member_busy(M, false);\n    \n    int day = 1;\n    while (day <= 2000) {\n        vector<pair<int, int>> assignments;\n        for (int m = 0; m < M && !pq.empty(); ++m) {\n            while (!pq.empty() && tasks[pq.top().second].started) pq.pop();\n            if (pq.empty()) break;\n            int t = pq.top().second;\n            pq.pop();\n            \n            assignments.emplace_back(m, t);\n            tasks[t].started = true;\n        }\n        \n        print_flush(assignments);\n        \n        string input;\n        getline(cin >> ws, input);\n        if (input == \"-1\") break;\n        \n        istringstream iss(input);\n        int n;\n        iss >> n;\n        for (int _ = 0; _ < n; ++_) {\n            int m;\n            iss >> m;\n            --m;\n            \n            if (!member_busy[m]) {\n                int task = finished_tasks[m].back();\n                finished_tasks[m].pop_back();\n                tasks[task].done_day = day;\n                \n                int days_taken = day - tasks[task].started_day;\n                update_skills(m, task, days_taken);\n                \n                for (int child : deps[task]) {\n                    --tasks[child].indeg;\n                    if (tasks[child].indeg == 0) {\n                        pq.emplace(-estimate_time(m, child), child);\n                    }\n                }\n            }\n        }\n        \n        for (auto& [m, t] : assignments) {\n            if (!tasks[t].started) finished_tasks[m].push_back(t);\n            member_busy[m] = !tasks[t].started;\n            tasks[t].started_day = day;\n        }\n        \n        day++;\n    }\n    \n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Order {\n    int a, b, c, d;\n};\n\nvector<pair<int,int>> best_path;\nvector<int> chosen;\n\nint dist(int x1, int y1, int x2, int y2) {\n    return abs(x1-x2) + abs(y1-y2);\n}\n\nvector<pair<int, int>> construct_route() {\n    vector<pair<int, int>> path{{400, 400}};\n    for (int i : chosen) {\n        int a = orders[i].a, b = orders[i].b;\n        int c = orders[i].c, d = orders[i].d;\n        \n        int mn_cost = INT_MAX, best_pos = 0;\n        for (int j = 0; j < (int)path.size(); ++j) {\n            vector<pair<int, int>> tmp_path = path;\n            tmp_path.insert(tmp_path.begin() + j + 1, {{a, b}, {c, d}});\n            \n            ll cost = 0;\n            for (int k = 1; k < (int)tmp_path.size(); ++k) {\n                cost += dist(tmp_path[k-1].first, tmp_path[k-1].second, tmp_path[k].first, tmp_path[k].second);\n            }\n            if (cost < mn_cost) {\n                mn_cost = cost;\n                best_pos = j + 1;\n            }\n        }\n        path.insert(path.begin() + best_pos, {{a, b}, {c, d}});\n    }\n    path.push_back({400, 400});\n    return path;\n}\n\nint main() {\n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; ++i) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n    }\n    \n    // Score heuristic: prioritize close orders\n    auto cmp = [&](int lhs, int rhs) {\n        int dist1 = dist(400, 400, orders[lhs].a, orders[lhs].b) \n                  + dist(orders[lhs].c, orders[lhs].d, 400, 400);\n        int dist2 = dist(400, 400, orders[rhs].a, orders[rhs].b)\n                  + dist(orders[rhs].c, orders[rhs].d, 400, 400);\n        return dist1 < dist2;\n    };\n    \n    // Initialize with heuristic\n    vector<int> ids(1000); iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(), cmp);\n    \n    vector<int> current_orders;\n    ll current_cost = 0;\n    priority_queue<pair<ll, int>> pq;\n    \n    for (int i = 0; i < 1000; ++i) {\n        pq.emplace(-dist(400, 400, orders[ids[i]].a, orders[ids[i]].b) \n                     - dist(orders[ids[i]].c, orders[ids[i]].d, 400, 400),\n                   ids[i]);\n    }\n    \n    while (chosen.size() < 50) {\n        auto [cost, id] = pq.top(); pq.pop();\n        chosen.push_back(id);\n        \n        best_path = construct_route();\n        ll total_cost = 0;\n        for (int i = 1; i < (int)best_path.size(); ++i) {\n            total_cost += dist(best_path[i-1].first, best_path[i-1].second,\n                               best_path[i].first, best_path[i].second);\n        }\n        current_cost = total_cost;\n    }\n    \n    cout << chosen.size();\n    for (auto id : chosen) cout << \" \" << id + 1;\n    cout << \"\\n\";\n    cout << best_path.size();\n    for (auto &[x, y] : best_path) cout << \" \" << x << \" \" << y;\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\nusing boost::disjoint_sets;\nusing boost::disjoint_sets_with_storage;\n\nstruct Edge {\n    int u, v, min_len, max_len, len;\n    double e_val;\n    bool operator<(const Edge& r) const {\n        if (max_len != r.max_len) return max_len < r.max_len;\n        return e_val < r.e_val; // Prefer lower expected value on tie\n    }\n};\n\nint main() {\n    const int N = 400, M = 1995;\n    vector<pair<int, int>> coords(N);\n    for (int i = 0; i < N; ++i) scanf(\"%d %d\", &coords[i].first, &coords[i].second);\n    \n    vector<Edge> edges(M);\n    auto calc_dist = [&](int u, int v) -> int {\n        int dx = coords[u].first - coords[v].first;\n        int dy = coords[u].second - coords[v].second;\n        return round(sqrt(dx*dx + dy*dy));\n    };\n    \n    for (int i = 0; i < M; ++i) {\n        scanf(\"%d %d\", &edges[i].u, &edges[i].v);\n        int d = calc_dist(edges[i].u, edges[i].v);\n        edges[i].min_len = d;\n        edges[i].max_len = 3 * d;\n        edges[i].e_val = (edges[i].min_len + edges[i].max_len) / 2.0;\n    }\n    \n    // Sort edges by (max_len ascending, then expected value ascending)\n    sort(edges.begin(), edges.end());\n    \n    vector<int> sorted_indices(M);\n    iota(sorted_indices.begin(), sorted_indices.end(), 0);\n    stable_sort(sorted_indices.begin(), sorted_indices.end(), [&](int i, int j) {\n        if (edges[i].max_len != edges[j].max_len) return edges[i].max_len < edges[j].max_len;\n        return edges[i].e_val < edges[j].e_val;\n    });\n\n    unordered_set<int> known_edges;\n    disjoint_sets<> uf(N);\n    int connected = N;\n    int idx = 0;\n    \n    auto in_order = [&]() mutable -> int {\n        while (idx < M && known_edges.contains(sorted_indices[idx])) ++idx;\n        return idx == M ? -1 : sorted_indices[idx];\n    };\n\n    for (int i = 0; i < M; ++i) {\n        int len;\n        scanf(\"%d\", &len);\n        edges[i].len = len;\n        \n        known_edges.insert(i);\n        int next_potential = in_order();\n        \n        if (next_potential == -1 || (uf.find_set(edges[i].u) != uf.find_set(edges[i].v) && len <= 2.5 * edges[next_potential].min_len)) {\n            // Accept if connects disconnected or within threshold of next candidate\n            if (uf.link(edges[i].u, edges[i].v)) --connected;\n            printf(\"1\\n\");\n            fflush(stdout);\n        } else {\n            printf(\"0\\n\");\n            fflush(stdout);\n        }\n        if (connected == 1) break; // Already connected\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\nusing Point = pair<int, int>;\nconst int MAX_TURNS = 300;\nconst int GRID_SIZE = 30;\n\nchar dirs[] = {'u','d','l','r','U','D','L','R'};\nint dx[] = {-1,1,0,0,-1,1,0,0};\nint dy[] = {0,0,-1,1,0,0,-1,1};\n\nvector<Point> humans;\nvector<pair<Point, int>> pets;\nvector<string> grid(GRID_SIZE+1, string(GRID_SIZE+1, '.'));\n\nbool isValid(int x, int y) {\n    return x >= 1 && x <= GRID_SIZE && y >= 1 && y <= GRID_SIZE;\n}\n\nbool hasAdjacentPet(int x, int y) {\n    for (int d = 0; d < 4; ++d) {\n        int nx = x + dx[d], ny = y + dy[d];\n        if (isValid(nx, ny) && grid[nx][ny] == '#') {\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid updateBarriers(string actions) {\n    set<Point> blocks;\n    for (int i = 0; i < (int)actions.size(); ++i) {\n        char c = actions[i];\n        if (c == '.' || isupper(c)) continue;\n        int d = find(dirs, dirs+8, c) - dirs;\n        int x = humans[i].first + dx[d], y = humans[i].second + dy[d];\n        if (isValid(x, y) && grid[x][y] == '.') {\n            grid[x][y] = '#';\n        }\n    }\n}\n\nstring decideActions() {\n    string result(humans.size(), '.');\n    \n    // Attempt to move to outer corners first\n    for (int i = 0; i < (int)humans.size(); ++i) {\n        int x = humans[i].first, y = humans[i].second;\n        for (char c : {'U','D','L','R'}) {\n            int d = find(dirs, dirs+8, c) - dirs;\n            int nx = x + dx[d], ny = y + dy[d];\n            if (isValid(nx, ny) && grid[nx][ny] == '.') {\n                result[i] = c;\n                break;\n            }\n        }\n        if (result[i] != '.') continue;\n        // Next try to block\n        for (char c : {'u','d','l','r'}) {\n            int d = find(dirs, dirs+4, c) - dirs;\n            int nx = x + dx[d], ny = y + dy[d];\n            if (isValid(nx, ny) && grid[nx][ny] == '.' && !hasAdjacentPet(nx,ny)) {\n                result[i] = c;\n                break;\n            }\n        }\n    }\n    return result;\n}\n\n// Update human positions\nvoid executeActions(const string& actions) {\n    for (int i = 0; i < (int)actions.size(); ++i) {\n        char act = actions[i];\n        if (islower(act)) continue; // Only move if uppercase\n        int d = find(dirs+4, dirs+8, act) - (dirs+4);\n        int x = humans[i].first + dx[d+4], y = humans[i].second + dy[d+4];\n        if (isValid(x,y) && grid[x][y] == '.') {\n            humans[i] = {x, y};\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read pets\n    int N; cin >> N;\n    for (int i = 0; i < N; ++i) {\n        int x, y, t; \n        cin >> x >> y >> t;\n        pets.push_back({{x,y}, t});\n        grid[x][y] = 'O'; // Mark with a temp char for pets\n    }\n    \n    // Read humans\n    int M; cin >> M;\n    humans.resize(M);\n    for (auto& [x, y] : humans) {\n        cin >> x >> y;\n    }\n    \n    // Clear pet markings for actual use\n    for (auto& [p, t] : pets) {\n        grid[p.first][p.second] = '.';\n    }\n    \n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        string actions = decideActions();\n        cout << actions << endl;\n        \n        // Read dummy pet movements; actual movements not tracked here\n        for (int i = 0; i < N; ++i) {\n            string _;\n            cin >> _;\n        }\n        \n        executeActions(actions);\n        updateBarriers(actions);\n    }\n    \n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    string path;\n    int remain_downs = ti - si;\n    int remain_rights = tj - sj;\n\n    // Generate necessary moves first\n    auto add_moves = [&](int count, char move) {\n        for (int i = 0; i < count; ++i) {\n            path += move;\n            // Add redundancy in the same direction to maximize chances\n            path += move;\n            if (path.size() >= 200) break;\n        }\n    };\n\n    // Ensure each step in the right direction is added at least twice\n    while (remain_downs > 0 || remain_rights > 0) {\n        if (remain_downs > 0) {\n            path += \"DD\";\n            remain_downs--;\n        }\n        if (remain_rights > 0) {\n            path += \"RR\";\n            remain_rights--;\n        }\n    }\n\n    // If needed, pad with more down and right moves\n    while (path.size() < 200) {\n        path += \"D\";\n        if (path.size() < 200) path += \"R\";\n    }\n\n    cout << path.substr(0, 200) << endl;\n}","ahc010":"#include <bits/stdc++.h>\n#include <random>\nusing namespace std;\n\nconst int N = 30;\nint T[N][N], R[N][N], bestR[N][N];\nint dirs[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1},\n};\nint di[4] = {0, -1, 0, 1}, dj[4] = {-1, 0, 1, 0};\n\nmt19937 mt(time(nullptr));\n\nlong long eval(int rotate[N][N]) {\n    int tcopy[N][N];\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        tcopy[i][j] = rotate[i][j];\n        while (tcopy[i][j] < 0) tcopy[i][j] += 8;\n        tcopy[i][j] %= 8;\n    }\n\n    vector<int> lengths;\n    bool vis[N][N][4] = {};\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        for (int d=0; d<4; ++d) {\n            if (vis[i][j][d]) continue;\n            vector<tuple<int, int, int>> path;\n            int ci=i, cj=j, cd=d, len=0;\n            while (true) {\n                path.emplace_back(ci, cj, cd);\n                vis[ci][cj][cd] = true;\n                int nd = dirs[tcopy[ci][cj]][cd];\n                if (nd == -1) break;\n                ci += di[nd];\n                cj += dj[nd];\n                if (ci < 0 || ci >= N || cj < 0 || cj >= N) break;\n                cd = (nd + 2) % 4;\n                if (vis[ci][cj][cd]) {\n                    for (auto [pi, pj, pd] : path) {\n                        if (pi == ci && pj == cj && pd == cd) {\n                            len = path.size() - (path.end() - find(path.begin(), path.end(), make_tuple(pi, pj, pd)));\n                            break;\n                        }\n                    }\n                    break;\n                }\n            }\n            if (len > 0) {\n                lengths.push_back(len);\n                for (auto& [pi, pj, pd] : path) vis[pi][pj][pd] = true;\n            }\n        }\n    }\n    sort(lengths.rbegin(), lengths.rend());\n    long long l1 = (lengths.size() > 0) ? lengths[0] : 0;\n    long long l2 = (lengths.size() > 1) ? lengths[1] : 0;\n    return l1 * l2;\n}\n\nlong long calc() {\n    static int rotate[N][N];\n    memcpy(rotate, R, sizeof(rotate));\n    long long ans = 0;\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        long long best = 0;\n        for (int k=0; k<4; ++k) {\n            rotate[i][j] = (rotate[i][j] + 1) % 8;\n            long long score = eval(rotate);\n            if (score > best) best = score;\n        }\n        rotate[i][j] = (rotate[i][j] - best + 8) % 8;\n        ans += best;\n    }\n    return ans;\n}\n\nint main() {\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        char c; cin >> c;\n        T[i][j] = c - '0';\n    }\n    memcpy(R, T, sizeof(R));\n\n    auto update_ans = [&]() {\n        long long cur_score = eval(bestR);\n        long long score = eval(R);\n        if (score > cur_score) memcpy(bestR, R, sizeof(bestR));\n    };\n\n    const double START_TEMP = 1e6, END_TEMP = 1e-3, RATE = 0.9999;\n    double temp = START_TEMP;\n    long long cur_score = eval(R), best_score = cur_score;\n    while (temp > END_TEMP) {\n        for (int _=0; _<max(1, N*N * temp / START_TEMP); ++_) {\n            int i = mt() % N, j = mt() % N;\n            int prev = R[i][j];\n\n            long long best_rotate = -1;\n            long long best_gain = -1e18;\n            vector<long long> scores(4);\n            for (int delta=0; delta<4; ++delta) {\n                R[i][j] = (prev + delta) % 8;\n                scores[delta] = eval(R);\n                if (scores[delta] - cur_score > best_gain) {\n                    best_gain = scores[delta] - cur_score;\n                    best_rotate = delta;\n                }\n            }\n\n            if (best_rotate == -1 || exp((scores[best_rotate] - cur_score) / temp) < (mt() % 10000)/10000.) {\n                int rnd = mt() % 4;\n                if (scores[rnd] <= cur_score && exp((scores[rnd] - cur_score) / temp) < (mt() % 10000)/10000.) {\n                    R[i][j] = prev;\n                    continue;\n                }\n                best_rotate = rnd;\n            }\n\n            R[i][j] = (prev + best_rotate) % 8;\n            cur_score = scores[best_rotate];\n            update_ans();\n        }\n        best_score = max(best_score, cur_score);\n        temp *= RATE;\n    }\n\n    memcpy(R, bestR, sizeof(R));\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        int diff = 0;\n        while ((bestR[i][j] - T[i][j] - diff) % 8 != 0 && (bestR[i][j] - T[i][j] - diff) % 8 != 4) ++diff;\n        while (diff < 0) diff += 8;\n        cout << diff % 4;\n    }\n    cout << endl;\n}","ahc011":"#include <algorithm>\n#include <deque>\n#include <iostream>\n#include <numeric>\n#include <queue>\n#include <vector>\nusing namespace std;\nusing ll = long long;\n\n#define rep(i, n) for (int i = 0; i < n; i++)\n\nint n, e_x, e_y;\nvector<vector<int>> a;\n\nbool in_grid(int x, int y) { return 0 <= x && x < n && 0 <= y && y < n; }\n\nbool valid(int x, int y) { return in_grid(x, y) && a[x][y] != 0; }\n\nint cnt_connect(int x, int y) {\n  int c = (x == e_x && y == e_y);\n  if (valid(x + 1, y)) c++;\n  if (valid(x, y - 1)) c++;\n  if (valid(x, y + 1)) c++;\n  if (valid(x - 1, y)) c++;\n  return c - 1;\n}\n\npair<int, int> find_target() {\n  rep(i, n) rep(j, n) if (a[i][j] == 0) return {i, j};\n  return {-1, -1};\n}\n\npair<int, pair<int, int>> find_tile() {\n  int mx = -1;\n  pair<int, pair<int, int>> res;\n  rep(x, n) rep(y, n) {\n    if (!valid(x, y)) continue;\n    int nc = __builtin_popcount(a[x][y]);\n    int cc = cnt_connect(x, y);\n    if (nc - 1 <= cc) continue;\n    int score = nc - cc;\n    if (score > mx || (score == mx && rand() % 2 == 0)) {\n      mx = score;\n      res = {a[x][y], {x, y}};\n    }\n  }\n  return res;\n}\n\nstring generate_path(int sx, int sy, int tx, int ty) {\n  deque<pair<int, int>> qb, qe;\n  vector<vector<int>> db(n, vector<int>(n, -1)), de(n, vector<int>(n, -1));\n  qb.push_back({sx, sy});\n  qe.push_back({tx, ty});\n  db[sx][sy] = 0;\n  de[tx][ty] = 0;\n  while (!qb.empty() || !qe.empty()) {\n    auto bfs = [&](deque<pair<int, int>> &q, vector<vector<int>> &d, deque<pair<int, int>> &oq, vector<vector<int>> &od) {\n      pair<int, int> cur = q.front();\n      q.pop_front();\n      int x = cur.first, y = cur.second;\n      if (od[x][y] != -1) {\n        string pathb, pathe;\n        while (cur.first != sx || cur.second != sy) {\n          pathb += (cur.first == x + 1 && cur.second == y) ? 'U'\n                   : (cur.first == x - 1 && cur.second == y) ? 'D'\n                   : (cur.first == x && cur.second == y + 1) ? 'L'\n                                                               : 'R';\n          cur = {db[cur.first][cur.second] / n, db[cur.first][cur.second] % n};\n        }\n        while (cur.first != tx || cur.second != ty) {\n          pathe += (od[cur.first][cur.second] == x + 1 && od[cur.first][cur.second] / n == y) ? 'D'\n               : (od[cur.first][cur.second] == x - 1 && od[cur.first][cur.second] / n == y) ? 'U'\n               : (od[cur.first][cur.second] == x && od[cur.first][cur.second] / n == y + 1) ? 'R'\n                                                                                              : 'L';\n          cur = {od[cur.first][cur.second], od[cur.first][cur.second] / n};\n        }\n        reverse(pathb.begin(), pathb.end());\n        string ans = pathb + pathe;\n        while (ans.size() > 1 && (ans.back() == 'U' && ans[ans.size() - 2] == 'D' || ans.back() == 'D' && ans[ans.size() - 2] == 'U' ||\n                                   ans.back() == 'L' && ans[ans.size() - 2] == 'R' || ans.back() == 'R' && ans[ans.size() - 2] == 'L')) {\n          ans.pop_back();\n          ans.pop_back();\n        }\n        return ans;\n      }\n      static const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};\n      rep(i, 4) {\n        int nx = x + dx[i], ny = y + dy[i];\n        if (in_grid(nx, ny) && d[nx][ny] == -1 && a[nx][ny] != 0) {\n          d[nx][ny] = d[x][y] * n + ny;\n          q.push_back({nx, ny});\n        }\n      }\n      return \"\";\n    };\n    if (!qb.empty()) {\n      auto res = bfs(qb, db, qe, de);\n      if (!res.empty()) return res;\n    }\n    if (!qe.empty()) {\n      auto res = bfs(qe, de, qb, db);\n      if (!res.empty()) return res;\n    }\n  }\n  return \"\";\n}\n\nint main() {\n  cin >> n;\n  int T;\n  cin >> T;\n  a.resize(n, vector<int>(n));\n  rep(i, n) rep(j, n) {\n    char c;\n    cin >> c;\n    if (c >= 'a') a[i][j] = c - 'a' + 10;\n    else a[i][j] = c - '0';\n  }\n  string ans;\n  auto [ex, ey] = find_target();\n  while (true) {\n    auto [val, pos] = find_tile();\n    if (val == -1) break;\n    auto [x, y] = pos;\n    if (cnt_connect(x, y) == __builtin_popcount(val) - 1) continue;\n    int tx = ex, ty = ey;\n    ex = x;\n    ey = y;\n    a[tx][ty] = val;\n    a[x][y] = 0;\n    ans += generate_path(tx, ty, x, y);\n  }\n  cout << ans << endl;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    vector<array<int,4>> lines;\n    const int range = 15000;\n    const int step = 3000; // Smaller step to create smaller regions\n    \n    // Dense vertical lines near the center to facilitate smaller groups\n    for (int x = -range + step; x <= range - step; x += step) {\n        if (x != 0) lines.emplace_back(array{x, -range, x, range});\n    }\n    // Dense horizontal lines near the center for the same reason\n    for (int y = -range + step; y <= range - step; y += step) {\n        if (y != 0) lines.emplace_back(array{-range, y, range, y});\n    }\n    \n    // Key diagonal lines\n    lines.emplace_back(array{-range, -range, range, range});\n    lines.emplace_back(array{-range, range, range, -range});\n    lines.emplace_back(array{-range*2, 0, range*2, 0});\n    lines.emplace_back(array{0, -range*2, 0, range*2});\n\n    cout << lines.size() << '\\n';\n    for (const auto& line : lines) {\n        cout << line[0] << ' ' << line[1] << ' ' << line[2] << ' ' << line[3] << '\\n';\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nvector<vector<bool>> visited;\nvector<tuple<int, int, int, int, int, int>> ans;\nint N, M;\n\nbool validate(int x1, int y1, int x2, int y2, int x3, int y3) {\n    if (!(0 <= min({x1, x2, x3}) && max({x1, x2, x3}) < N)) return false;\n    if (!(0 <= min({y1, y2, y3}) && max({y1, y2, y3}) < N)) return false;\n    if (x1 == x2 || x2 == x3 || x3 == x1 || y1 == y2 || y2 == y3 || y3 == y1)\n        return false;\n    return true;\n}\n\nint main() {\n    cin >> N >> M;\n    visited.assign(N, vector<bool>(N, false));\n    queue<pair<int, int>> q;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        visited[x][y] = true;\n        q.emplace(x, y);\n    }\n\n    int total_dots = M;\n    while (!q.empty() && (double)total_dots / N / N < 0.08) { // Adjust target fill\n        auto [x, y] = q.front(); q.pop();\n        // Search in a limited radius to balance coverage and time\n        for (int dx = -5; dx <= 5; ++dx) for (int dy = -5; dy <= 5; ++dy) {\n            if (abs(dx) + abs(dy) > 9) continue; // Stay within bounded steps\n            int nx = x + dx, ny = y + dy;\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N || visited[nx][ny]) continue;\n            for (int d = 1; d <= 5; ++d) {\n                if (validate(nx, ny, x, y, x, y+d, x+d, y)) {\n                    if (!visited[x][y+d] || !visited[x+d][y]) break;\n                    visited[nx][ny] = true;\n                    ans.emplace(nx, ny, x, y, x, y+d, x+d, y);\n                    q.emplace(nx, ny);\n                    total_dots++;\n                    goto next_point;\n                }\n                if (validate(nx, ny, x, y, x, y-d, x-d, y)) {\n                    if (!visited[x][y-d] || !visited[x-d][y]) break;\n                    visited[nx][ny] = true;\n                    ans.emplace(nx, ny, x, y, x, y-d, x-d, y);\n                    q.emplace(nx, ny);\n                    total_dots++;\n                    goto next_point;\n                }\n            }\n        }\n    next_point:;\n    }\n\n    cout << ans.size() << endl;\n    for (auto &[x1, y1, x2, y2, x3, y3] : ans)\n        cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << ' '\n             << x3 << ' ' << y3 << ' ' << (x3+y2-x2) << ' ' << (x2+y3-x3) << endl;\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int SIZE = 10;\nvector<vector<int>> grid(SIZE, vector<int>(SIZE, 0));\nvector<pair<int, int>> emptyCells;\nunordered_map<int, int> flavorCount = {{1,0}, {2,0}, {3,0}};\nunordered_map<int, pair<int, int>> centroids; // flavor -> centroid (sum_x, sum_y)\n\nvoid updateCenterMass(int flavor, int x, int y) {\n    flavorCount[flavor]++;\n    centroids[flavor].first += x;\n    centroids[flavor].second += y;\n}\n\nvoid applyGravity(char dir) {\n    if (dir == 'F') {\n        for (int col = 0; col < SIZE; ++col) {\n            for (int row = SIZE-2; row >= 0; --row) {\n                if (grid[row][col] && !grid[row+1][col]) {\n                    int r = row+1;\n                    while (r < SIZE && !grid[r][col]) r++;\n                    --r;\n                    swap(grid[r][col], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'B') {\n        // B direction logic\n        for (int col = 0; col < SIZE; ++col) {\n            for (int row = 1; row < SIZE; ++row) {\n                if (grid[row][col] && !grid[row-1][col]) {\n                    int r = row-1;\n                    while (r >= 0 && !grid[r][col]) r--;\n                    ++r;\n                    swap(grid[r][col], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'L') {\n        // L direction logic\n        for (int row = 0; row < SIZE; ++row) {\n            for (int col = 1; col < SIZE; ++col) {\n                if (grid[row][col] && !grid[row][col-1]) {\n                    int c = col-1;\n                    while (c >= 0 && !grid[row][c]) c--;\n                    ++c;\n                    swap(grid[row][c], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'R') {\n        // R direction logic\n        for (int row = 0; row < SIZE; ++row) {\n            for (int col = SIZE-2; col >= 0; --col) {\n                if (grid[row][col] && !grid[row][col+1]) {\n                    int c = col+1;\n                    while (c < SIZE && !grid[row][c]) c++;\n                    --c;\n                    swap(grid[row][c], grid[row][col]);\n                }\n            }\n        }\n    }\n}\n\nchar chooseDirection(int flavor, int x, int y) {\n    pair<int, int> bestDir = {0, 0};\n    int currentScore = 1e9;\n    for (auto& [dx, dy] : {pair{-1,0}, {1,0}, {0,-1}, {0,1}}) {\n        int nx = x + dx*(SIZE-1), ny = y + dy*(SIZE-1);\n        if (flavorCount[flavor] == 0) {\n            if (abs(nx) + abs(ny) < currentScore) {\n                currentScore = abs(nx) + abs(ny);\n                bestDir = {dx, dy};\n            }\n        } else {\n            auto cm = centroids[flavor];\n            int cx = cm.first / flavorCount[flavor];\n            int cy = cm.second / flavorCount[flavor];\n            int newScore = abs(nx - cx) + abs(ny - cy);\n            if (newScore < currentScore) {\n                currentScore = newScore;\n                bestDir = {dx, dy};\n            }\n        }\n    }\n    return bestDir == make_pair(-1, 0) ? 'F' : \n           bestDir == make_pair(1, 0) ? 'B' : \n           bestDir == make_pair(0, -1) ? 'L' : 'R';\n}\n\nint main() {\n    vector<int> flavors(100);\n    for (int& f : flavors) cin >> f;\n    \n    for (int t = 0; t < 100; ++t) {\n        emptyCells.clear();\n        for (int i = 0; i < SIZE; ++i)\n            for (int j = 0; j < SIZE; ++j)\n                if (!grid[i][j])\n                    emptyCells.emplace_back(i, j);\n        \n        int p; cin >> p;\n        --p;\n        auto [x, y] = emptyCells[p];\n        int f = flavors[t];\n        grid[x][y] = f;\n        updateCenterMass(f, x, y);\n\n        if (t == 99) break;\n        \n        char dir = chooseDirection(f, x, y);\n        cout << dir << '\\n';\n        cout.flush();\n        applyGravity(dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nstring generate_graph(int vertices, int edges) {\n    vector<bool> visited(vertices * (vertices-1) / 2, false);\n    string result(vertices * (vertices-1) / 2, '0');\n    \n    int current = 0;\n    for (int j=1; j<=edges; ++j) {\n        if (current >= visited.size()) current = 0; // Fallback to start if out\n        while (result[current] == '1' || visited[current]) {\n            ++current;\n            if (current >= visited.size()) current = 0;\n        }\n        result[current] = '1';\n        visited[current] = true;\n    }\n    return result;\n}\n\nint main() {\n    int M;\n    double eps;\n    cin >> M >> eps;\n    \n    const int N = 20;\n    cout << N << endl;\n    \n    vector<string> precomputed(M);\n    for (int i=0; i < M; ++i) {\n        precomputed[i] = generate_graph(N, i);\n        cout << precomputed[i] << endl;\n    }\n    cout << flush;\n    \n    // Precompute edge counts for faster lookup\n    vector<int> edges_counts(M);\n    for (int i=0; i < M; ++i) {\n        edges_counts[i] = count(precomputed[i].begin(), precomputed[i].end(), '1');\n    }\n    \n    for (int k=0; k < 100; ++k) {\n        string H;\n        cin >> H;\n        int current_edges = count(H.begin(), H.end(), '1');\n        \n        // Match using edge count distance\n        int best_match = 0;\n        int min_diff = INT_MAX;\n        for (int m=0; m < M; ++m) {\n            int diff = abs(current_edges - edges_counts[m]);\n            if (diff < min_diff) {\n                min_diff = diff;\n                best_match = m;\n            }\n        }\n        cout << best_match << endl << flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing i32 = int;\nusing i64 = long long;\nusing vi = vector<i32>;\nusing pii = pair<i32, i32>;\nusing Graph = vector<vector<pii>>;\nconst i64 INF = 1e18;\n\npair<vector<i64>, vector<i64>> dijkstra(int start, const Graph& adj, int N) {\n    using Node = pair<i64, i32>;\n    priority_queue<Node, vector<Node>, greater<>> pq;\n    vector<i64> dist(N, INF), cnt(N, 0);\n    dist[start] = 0;\n    cnt[start] = 1;\n    pq.emplace(0, start);\n\n    while (!pq.empty()) {\n        auto [current_dist, u] = pq.top();\n        pq.pop();\n        if (current_dist != dist[u]) continue;\n\n        for (auto& [v, w] : adj[u]) {\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                cnt[v] = cnt[u];\n                pq.emplace(dist[v], v);\n            } else if (dist[u] + w == dist[v]) {\n                cnt[v] += cnt[u];\n            }\n        }\n    }\n    return {dist, cnt};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    i32 N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    Graph adj(N);\n    vector<tuple<i32, i32, i32>> edges(M);\n    for (i32 i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u, --v;\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n        edges[i] = {u, v, w};\n    }\n\n    vector<i64> edge_importance(M, 0);\n    for (i32 i = 0; i < N; ++i) {\n        auto [dist, cnt] = dijkstra(i, adj, N);\n        for (i32 j = 0; j < M; ++j) {\n            auto& [u, v, w] = edges[j];\n            if (dist[u] + w == dist[v]) \n                edge_importance[j] += cnt[u] * (N - cnt[v]);\n            if (dist[v] + w == dist[u])\n                edge_importance[j] += cnt[v] * (N - cnt[u]);\n        }\n    }\n\n    vector<pair<i64, i32>> order;\n    for (i32 i = 0; i < M; ++i) order.emplace_back(edge_importance[i], i);\n    sort(order.rbegin(), order.rend());\n\n    vi days(M, -1);\n    vector<i64> current_imp(D, 0);\n    priority_queue<pii, vector<pii>, greater<>> day_pq;\n    for (i32 i = 0; i < D; ++i) day_pq.push({0, i});\n\n    for (auto& [imp, idx] : order) {\n        auto [min_imp, day] = day_pq.top();\n        day_pq.pop();\n        days[idx] = day + 1;\n        day_pq.push({min_imp + imp, day});\n        current_imp[day] += imp;\n    }\n\n    for (auto d : days) cout << d << ' ';\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n    bool operator<(const Point& o) const {\n        return tie(x, y, z) < tie(o.x, o.y, o.z);\n    }\n};\n\nvector<vector<string>> input;  // Store each 2D silhouette\nvector<vector<vector<int>>> dp; // Precompute front and right silhouettes\nvector<vector<vector<int>>> blocks;\n\nvector<vector<vector<int>>> construct(int idx) {\n    auto& sil = input[idx*2];\n    auto& sir = input[idx*2 + 1];\n    int n = sil.size();\n    vector<vector<vector<int>>> cube(n, vector<vector<int>>(n, vector<int>(n)));\n    vector<vector<int>> vis(n, vector<int>(n, 0));\n    int cnt = 1;\n    \n    auto addBlock = [&](int x, int y, int z) {\n        cube[x][y][z] = cnt;\n    };\n    \n    // Process intersections to use same blocks for both configurations\n    for (int z = 0; z < n; z++) {\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (dp[idx][x][z] && dp[idx + 2][y][z] && !vis[x][y] && !blocks[x][y][z]) {\n                    blocks[x][y][z] = cnt;\n                    addBlock(x, y, z);\n                    vis[x][y]++;\n                }\n            }\n        }\n    }\n    \n    // Fill remaining regions needed by the first silhouette\n    for (int z = 0; z < n; z++) {\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (dp[idx][x][z] && !blocks[x][y][z]) {\n                    addBlock(x, y, z);\n                    blocks[x][y][z] = cnt++;\n                }\n            }\n        }\n    }\n    return cube;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D;\n    cin >> D;\n    input.resize(4);\n    \n    for (int t = 0; t < 4; t++) {\n        for (int i = 0; i < D; i++) {\n            string s;\n            cin >> s;\n            input[t].push_back(s);\n        }\n    }\n    \n    // Precompute front and right silhouettes\n    dp.assign(4, vector<vector<int>>(D, vector<int>(D)));\n    for (int t = 0; t < 4; t += 2) {\n        for (int z = 0; z < D; z++) {\n            for (int x = 0; x < D; x++) {\n                for (int y = 0; y < D; y++) {\n                    if (input[t][z][x] == '1') dp[t][x][z]++;\n                    if (input[t+1][z][y] == '1') dp[t+2][y][z]++;\n                }\n            }\n        }\n    }\n    \n    blocks.resize(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    auto cube1 = construct(0);\n    blocks.assign(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    auto cube2 = construct(1);\n    \n    // Count blocks used\n    int max_block = 0;\n    for (const auto& c1 : cube1) for (const auto& row : c1) \n        for (int block : row) max_block = max(max_block, block);\n    for (const auto& c2 : cube2) for (const auto& row : c2) \n        for (int block : row) max_block = max(max_block, block);\n    \n    cout << max_block << '\\n';\n    \n    // Output cubes\n    for (auto& c : cube1) {\n        for (auto& r : c) \n            for (int val : r) cout << val << \" \";\n        cout << \"\\n\";\n    }\n    for (auto& c : cube2) {\n        for (auto& r : c) \n            for (int val : r) cout << val << \" \";\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\n#include <boost/geometry.hpp>\nusing namespace std;\nusing namespace boost::geometry;\ntypedef model::d2::point_xy<int> Point;\n\nauto rng = mt19937(chrono::steady_clock::now().time_since_epoch().count());\n\nlong long distSquared(const Point &a, const Point &b) {\n    return (long long)(a.x() - b.x()) * (a.x() - b.x()) +\n           (long long)(a.y() - b.y()) * (a.y() - b.y());\n}\n\nstruct Edge {\n    int u, v, w;\n    bool operator<(const Edge &o) const { return w < o.w; }\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<Point> stations(N);\n    stations[0] = Point(0, 0);\n    for (int i = 1; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        stations[i] = Point(x, y);\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v >> edges[i].w;\n        edges[i].u--, edges[i].v--;\n    }\n\n    vector<Point> residents(K);\n    for (int i = 0; i < K; ++i) {\n        int a, b;\n        cin >> a >> b;\n        residents[i] = Point(a, b);\n    }\n\n    // Prim's MST\n    vector<bool> inMST(N, false);\n    inMST[0] = true;\n    priority_queue<Edge> pq;\n    for (Edge e : edges) {\n        if (e.u == 0 || e.v == 0) pq.push(e);\n    }\n\n    vector<bool> edgeUsed(M, false);\n    while (!pq.empty()) {\n        auto [u, v, w] = pq.top();\n        pq.pop();\n        if (inMST[u] && inMST[v]) continue;\n\n        int nxt = inMST[u] ? v : u;\n        inMST[nxt] = true;\n\n        if (u < v) edgeUsed[v - 1] = true;\n        else edgeUsed[u - 1] = true;\n\n        for (Edge e : edges) {\n            if ((e.u == nxt || e.v == nxt) && !inMST[e.u] && !inMST[e.v]) {\n                pq.push(e);\n            }\n        }\n    }\n\n    vector<int> radius(N, 0);\n    for (auto res : residents) {\n        int min_idx = 0;\n        long long min_dist = distSquared(res, stations[0]);\n        for (int i = 1; i < N; ++i) {\n            if (!inMST[i]) continue;\n            long long cur = distSquared(res, stations[i]);\n            if (cur < min_dist) {\n                min_dist = cur;\n                min_idx = i;\n            }\n        }\n        radius[min_idx] = max(radius[min_idx], \n            static_cast<int>(ceil(sqrt(min_dist))));\n    }\n\n    // Output results\n    for (int r : radius) cout << r << \" \";\n    cout << endl;\n    for (bool e : edgeUsed) cout << e << \" \";\n    cout << endl;\n\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;\nvector<vector<int>> grid(N, vector<int>(N));\nvector<tuple<int, int, int, int>> operations;\n\nbool valid(int x, int y) {\n    return x >= 0 && y >= 0 && x < N && y <= x;\n}\n\nint eval() {\n    int cnt = 0;\n    for (int i = 0; i < N-1; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            if (valid(i + 1, j) && grid[i][j] > grid[i + 1][j]) ++cnt;\n            if (valid(i + 1, j + 1) && grid[i][j] > grid[i + 1][j + 1]) ++cnt;\n        }\n    }\n    return cnt;\n}\n\nvoid swap_and_push(int x1, int y1, int x2, int y2) {\n    swap(grid[x1][y1], grid[x2][y2]);\n    operations.emplace_back(x1, y1, x2, y2);\n}\n\nvoid solve() {\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j <= i; ++j)\n            cin >> grid[i][j];\n\n    for (int iter = 0; iter < 500 && operations.size() < 10000; ++iter) {\n        bool improved = false;\n        // Iterate each position from top to bottom\n        for (int i = 0; i < N-1; ++i) {\n            for (int j = 0; j <= i; ++j) {\n                if (valid(i+1, j) && grid[i][j] > grid[i+1][j]) {\n                    swap_and_push(i, j, i+1, j);\n                    improved = true;\n                } else if (valid(i+1, j+1) && grid[i][j] > grid[i+1][j+1]) {\n                    swap_and_push(i, j, i+1, j+1);\n                    improved = true;\n                }\n                if (operations.size() >= 10000) break;\n            }\n            if (operations.size() >= 10000) break;\n        }\n        if (!improved) break;\n    }\n\n    cout << operations.size() << '\\n';\n    for (auto& [x1, y1, x2, y2] : operations)\n        cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int D = 9;\nint N;\nvector<vector<bool>> is_obstacle(D, vector<bool>(D, false));\n\n// Spiral path initialization\nvector<pair<int, int>> spiral_order;\n\nvoid initialize_spiral() {\n    int top = 0, bottom = D-1, left = 0, right = D-1;\n    int dir = 0; // 0: right, 1: down, 2: left, 3: up\n    while (top <= bottom && left <= right) {\n        if (dir == 0) {\n            for (int j = left; j <= right; ++j) spiral_order.emplace_back(top, j);\n            top++;\n        } else if (dir == 1) {\n            for (int i = top; i <= bottom; ++i) spiral_order.emplace_back(i, right);\n            right--;\n        } else if (dir == 2) {\n            for (int j = right; j >= left; --j) spiral_order.emplace_back(bottom, j);\n            bottom--;\n        } else if (dir == 3) {\n            for (int i = bottom; i >= top; --i) spiral_order.emplace_back(i, left);\n            left++;\n        }\n        dir = (dir + 1) % 4;\n    }\n    // Filter out entrance and invalid positions\n    spiral_order.erase(remove_if(spiral_order.begin(), spiral_order.end(), \n        [](auto& pos) {\n            return (pos.first == 0 && pos.second == (D-1)/2) || is_obstacle[pos.first][pos.second];\n        }), \n        spiral_order.end());\n    reverse(spiral_order.begin(), spiral_order.end());\n}\n\nbool in_bounds(int x, int y) {\n    return x >= 0 && x < D && y >= 0 && y < D;\n}\n\nstruct StorageEntry {\n    int val;\n    int x, y;\n};\n\nvector<vector<int>> grid(D, vector<int>(D, -1));\nvector<StorageEntry> stored;\n\npair<int, int> bfs_nearest(int target) {\n    queue<pair<int, int>> q;\n    q.emplace((0, (D-1)/2));\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    visited[0][(D-1)/2] = true;\n    \n    while (!q.empty()) {\n        auto [cx, cy] = q.front(); q.pop();\n        for (auto [dx, dy] : vector<pair<int, int>>{{-1,0},{1,0},{0,-1},{0,1}}) {\n            int nx = cx + dx, ny = cy + dy;\n            if (in_bounds(nx, ny) && !visited[nx][ny] && !is_obstacle[nx][ny] && grid[nx][ny] != -1) {\n                if (grid[nx][ny] == target) {\n                    grid[nx][ny] = -1; // mark as used\n                    return {nx, ny};\n                }\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return {-1, -1};\n}\n\nint main() {\n    cin >> N;\n    int n = D*D - 1 - N;\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        is_obstacle[x][y] = true;\n    }\n\n    initialize_spiral();\n    int cur_pos = 0;\n    unordered_map<int, pair<int, int>> container_map;\n\n    for (int d = 0; d < n; ++d) {\n        int t;\n        cin >> t;\n        stored.push_back({t, spiral_order[cur_pos].first, spiral_order[cur_pos].second});\n        container_map[t] = spiral_order[cur_pos];\n        grid[spiral_order[cur_pos].first][spiral_order[cur_pos].second] = t;\n        cur_pos++;\n        cout << spiral_order[cur_pos - 1].first << \" \" << spiral_order[cur_pos - 1].second << endl;\n    }\n\n    sort(stored.begin(), stored.end(), [](const auto& a, const auto& b) { return a.val < b.val; });\n\n    for (const auto& entry : stored) {\n        auto [x, y] = bfs_nearest(entry.val);\n        cout << x << \" \" << y << endl;\n    }\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 51;\nint grid[N][N];\nint ans[N][N];\nint n, m;\n\nint dx[4] = {-1, 0, 1, 0};\nint dy[4] = {0, 1, 0, -1};\n\nvoid bfs_zero() {\n    deque<pair<int, int>> q;\n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    for (int i=0; i<n; ++i) {\n        if (ans[i][0] == 0 && !vis[i][0]) {\n            q.push_back({i, 0});\n            vis[i][0] = true;\n        }\n        if (ans[i][n-1] == 0 && !vis[i][n-1]) {\n            q.push_back({i, n-1});\n            vis[i][n-1] = true;\n        }\n    }\n    for (int j=0; j<n; ++j) {\n        if (ans[0][j] == 0 && !vis[0][j]) {\n            q.push_back({0, j});\n            vis[0][j] = true;\n        }\n        if (ans[n-1][j] == 0 && !vis[n-1][j]) {\n            q.push_back({n-1, j});\n            vis[n-1][j] = true;\n        }\n    }\n\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop_front();\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 || vis[nx][ny] || ans[nx][ny] != 0) continue;\n            ans[nx][ny] = 0;\n            vis[nx][ny] = true;\n            q.push_back({nx, ny});\n        }\n    }\n}\n\nint main() {\n    cin >> n >> m;\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            cin >> grid[i][j];\n            ans[i][j] = grid[i][j];\n        }\n    }\n    \n    vector<pair<int, int>> reps(m+1);\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            int c = grid[i][j];\n            if (reps[c] == pair<int, int>{}) {\n                reps[c] = {i, j};\n            }\n        }\n    }\n\n    memset(ans, -1, sizeof(ans));\n    for (int i=1; i<=m; ++i) {\n        if (reps[i] != pair<int, int>{}) {\n            auto [x, y] = reps[i];\n            ans[x][y] = i;\n            // Connect to border if it's adjacent originally\n            if (x == 0 || x == n-1 || y == 0 || y == n-1) {\n                ans[x][y] = 0; // Treat edge as zero\n            }\n        }\n    }\n\n    // Handle adjacencies for initial fill\n    for (int i=1; i<=m; ++i) {\n        if (reps[i].first != -1) {\n            auto [x, y] = reps[i];\n            bool adj_zero = false;\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) {\n                    adj_zero = true;\n                    break;\n                }\n                if (grid[nx][ny] == 0) adj_zero = true;\n            }\n            if (adj_zero) ans[x][y] = 0;\n        }\n    }\n\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (ans[i][j] == -1) ans[i][j] = 0;\n        }\n    }\n    \n    bfs_zero(); // Expand zeros properly\n    \n    // Connect remaining color cells to components\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (ans[i][j] > 0) continue;\n            for (int d=0; d<4; ++d) {\n                int nx = i + dx[d], ny = j + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n || ans[nx][ny] <= 0) continue;\n                ans[i][j] = ans[nx][ny];\n                break;\n            }\n        }\n    }\n\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (j > 0) cout << ' ';\n            cout << ans[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Vec = vector<int>;\nusing Mat = vector<Vec>;\nusing Graph = vector<Vec>;\nconstexpr ll INF = 1LL<<60;\nmt19937 mt(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct Partition {\n    int N, D, Q;\n    Vec A; // Answer partitions\n    Mat W; // Constraints: W[u][v] > 0 means u > v\n    vector<double> weight; // Virtual item weights\n\n    void init(int n, int d, int q) {\n        N = n; D = d; Q = q;\n        A = Vec(N, -1);\n        W.assign(N, Vec(N));\n        weight.resize(N, 1.0);\n    }\n\n    // Assign a random group with the smallest current sum\n    int assign(const Vec& cnt) {\n        priority_queue<pair<double, int>, vector<pair<double, int>>, greater<>> pq;\n        for (int i=0; i<D; ++i) pq.emplace(cnt[i] * weight[i], i);\n        \n        // Prefer groups with space but allow overfill near the end\n        int best = -1, minOver = N+1;\n        for (auto [w, idx] : pq) {\n            int total = cnt[idx] + 1;\n            if (total > N/D && minOver <= N/D) continue;\n            if (best == -1 || (total <= N/D && cnt[idx] < cnt[best])) {\n                best = idx;\n                if (total > N/D) minOver = total;\n            }\n        }\n        return best;\n    }\n\n    Vec solve() {\n        // Initial comparison phase\n        int q = 0;\n        for (int i=0; i<N-1 && q < Q; ++i) {\n            cout << 1 << ' ' << 1 << ' ' << i << ' ' << (i+1) << endl;\n            char res; cin >> res;\n            if (res == '>') W[i][i+1] = 1;\n            else if (res == '<') W[i+1][i] = 1;\n            ++q;\n        }\n\n        // Update virtual weights based on constraints\n        for (int k=0; k<N; ++k)\n            for (int i=0; i<N; ++i)\n                for (int j=0; j<N; ++j)\n                    if (W[i][k] && W[k][j]) W[i][j] = 1;\n\n        Vec cnt(D, 0);\n        for (int i=0; i<N; ++i) {\n            if (q >= Q) break;\n            int group = assign(cnt);\n            if (group == -1) {\n                group = mt() % D; // Random if stuck\n                if (cnt[group] >= N/D) continue; // Avoid overfill\n            }\n            A[i] = group;\n            cnt[group]++;\n        }\n\n        // Fill remaining unassigned items (if any)\n        int group = 0;\n        for (int i=0; i<N; ++i) {\n            if (A[i] == -1) {\n                while (cnt[group] >= N/D) group++;\n                A[i] = group;\n                cnt[group]++;\n            }\n        }\n\n        // Output final partition\n        for (int x: A) cout << x << ' ';\n        cout << endl;\n        return A;\n    }\n};\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n    Partition solver;\n    solver.init(N, D, Q);\n    solver.solve();\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nvoid find_box(const multi_array<int, 2>& stacks, int target, int& sidx, int& pos) {\n    for (int i=0; i<stacks.shape()[0]; ++i) {\n        for (int j=stacks.shape()[1]-1; j>=0; --j) {\n            if (stacks[i][j] == target) {\n                sidx = i; pos = j;\n                return;\n            }\n        }\n    }\n}\n\nint main() {\n    int n = 200, m = 10;\n    multi_array<int, 2> stacks(extents[m][n/m]);\n    for (int i=0; i<m; ++i)\n        for (int j=0; j<n/m; ++j)\n            cin >> stacks[i][j];\n\n    vector<pair<int, int>> moves;\n    int target = 1;\n\n    while (target <= n) {\n        int current_s = -1, pos = -1;\n        find_box(stacks, target, current_s, pos);\n        \n        bool at_top = false;\n        for (int s=0; s<m; ++s) {\n            if (!stacks[s].empty() && stacks[s].back() == target) {\n                at_top = true;\n                current_s = s;\n                break;\n            }\n        }\n        if (at_top) {\n            moves.emplace_back(target, 0);\n            stacks[current_s].pop_back();\n            target++;\n            continue;\n        }\n        \n        if (pos != stacks[current_s].size()-1) {\n            int max_dest = -1, dest_idx = -1;\n            for (int s=0; s<m; ++s) {\n                if (!stacks[s].empty() && s != current_s) {\n                    if (stacks[s].back() > max_dest || dest_idx == -1) {\n                        max_dest = stacks[s].back();\n                        dest_idx = s;\n                    }\n                }\n            }\n            if (dest_idx == -1) dest_idx = (current_s + 1) % m; // Pick next available\n            moves.emplace_back(stacks[current_s][pos], dest_idx + 1);\n            auto seq = stacks[current_s].subarray(pos, stacks[current_s].size());\n            stacks[dest_idx].insert(stacks[dest_idx].end(), seq.begin(), seq.end());\n            stacks[current_s].resize(pos);\n        }\n    }\n\n    for (auto& [v, i] : moves)\n        cout << v << \" \" << i << \"\\n\";\n}","ahc027":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\nusing namespace boost;\n\n// Direction vectors: down, right, up, left\nint dx[] = {1, 0, -1, 0};\nint dy[] = {0, 1, 0, -1};\nchar dir_char[] = {'D', 'R', 'U', 'L'};\n\nconst int INF = 1e9;\ntypedef vector<vector<int>> Matrix;\ntypedef vector<vector<vector<int>>> Dist; // precomputed distances\n\nbool valid(int x, int y, int n) {\n    return x >= 0 && x < n && y >= 0 && y < n;\n}\n\npair<Matrix, Matrix> parseInput(int n) {\n    vector<string> h(n-1), v(n);\n    for (auto& s : h) cin >> s;\n    for (auto& s : v) cin >> s;\n    \n    Matrix hor(n, vector<int>(n, 0));\n    for (int i = 0; i < n-1; ++i)\n        for (int j = 0; j < n; ++j)\n            hor[i][j] = h[i][j] - '0';\n            \n    Matrix ver(n, vector<int>(n, 0));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n-1; ++j)\n            ver[i][j] = v[i][j] - '0';\n            \n    return {hor, ver};\n}\n\nMatrix readDirt(int n) {\n    Matrix d(n, vector<int>(n, 0));\n    for (auto& row : d)\n        for (int& v : row) cin >> v;\n    return d;\n}\n\nvoid bfs(int x, int y, int n, const Matrix& hor, const Matrix& ver, vector<vector<bool>>& vis) {\n    queue<pair<int,int>> q;\n    q.emplace(x, y);\n    vis[x][y] = true;\n    while (!q.empty()) {\n        auto [cx, cy] = q.front(); q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int nx = cx + dx[k], ny = cy + dy[k];\n            if (valid(nx, ny, n) && !vis[nx][ny]) {\n                if ((k == 0 && !hor[cx][cy]) || \n                    (k == 1 && !ver[cx][cy]) ||\n                    (k == 2 && !hor[nx][ny]) ||\n                    (k == 3 && !ver[nx][ny])) {\n                    vis[nx][ny] = true;\n                    q.emplace(nx, ny);\n                }\n            }\n        }\n    }\n}\n\nDist precompute_distances(int n, const Matrix& hor, const Matrix& ver) {\n    Dist dist(n, vector<vector<int>>(n, vector<int>(n*n, INF)));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            priority_queue<pair<int, pair<int,int>>, \n                           vector<pair<int, pair<int,int>>>, \n                           greater<>> pq;\n            pq.emplace(0, make_pair(i, j));\n            dist[i][j][i*n + j] = 0;\n            while (!pq.empty()) {\n                auto [d, p] = pq.top(); pq.pop();\n                auto [x, y] = p;\n                if (d > dist[i][j][x*n + y]) continue;\n                for (int k = 0; k < 4; ++k) {\n                    int nx = x + dx[k], ny = y + dy[k];\n                    if (valid(nx, ny, n)) {\n                        bool blocked = (k == 0 && hor[x][y]) ||\n                                       (k == 1 && ver[x][y]) ||\n                                       (k == 2 && hor[nx][ny]) ||\n                                       (k == 3 && ver[nx][ny]);\n                        if (!blocked && d + 1 < dist[i][j][nx*n + ny]) {\n                            dist[i][j][nx*n + ny] = d + 1;\n                            pq.emplace(d + 1, make_pair(nx, ny));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return dist;\n}\n\nvoid add_route(int x, int y, int nx, int ny, const Dist& dist, vector<char>& answer, int n) {\n    if (x == nx && y == ny) return;\n    auto& d = dist[x][y];\n    int best_k = -1;\n    for (int k = 0; k < 4; ++k) {\n        int ax = x + dx[k], ay = y + dy[k];\n        if (valid(ax, ay, n) && dist[x][y][ax*n + ay] == d[nx*n + ny] - 1 && \n            (best_k == -1 || dist[ax][ay][nx*n + ny] < dist[x + dx[best_k]][y + dy[best_k]][nx*n + ny])) {\n            best_k = k;\n        }\n    }\n    if (best_k != -1) {\n        answer.push_back(dir_char[best_k]);\n        add_route(x + dx[best_k], y + dy[best_k], nx, ny, dist, answer, n);\n    }\n}\n\nvector<pair<int, int>> get_critical_points(const Matrix& d, int region_size) {\n    vector<pair<int, pair<int,int>>> points;\n    for (int i = 0; i < d.size(); ++i)\n        for (int j = 0; j < d.size(); ++j)\n            points.emplace_back(-d[i][j], make_pair(i,j));\n    sort(points.begin(), points.end());\n    \n    vector<pair<int,int>> result;\n    for (int i = 0; i < min<int>(region_size, (int)points.size()); ++i)\n        result.emplace_back(points[i].second);\n    return result;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    auto [hor, ver] = parseInput(n);\n    Matrix d = readDirt(n);\n    \n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    bfs(0, 0, n, hor, ver, vis);\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            assert(vis[i][j]);\n    \n    Dist dist = precompute_distances(n, hor, ver);\n    \n    vector<pair<int, int>> critical = get_critical_points(d, n); // Top critical points\n    \n    vector<char> answer;\n    int len = 0, limit = 1e5;\n    int x = 0, y = 0;\n    \n    vector<int> shuffled(critical.size());\n    iota(shuffled.begin(), shuffled.end(), 0);\n    \n    while (true) {\n        random_shuffle(shuffled.begin(), shuffled.end());\n        for (int idx : shuffled) {\n            auto [nx, ny] = critical[idx];\n            if (len + dist[x][y][nx*n + ny] > limit) break;\n            add_route(x, y, nx, ny, dist, answer, n);\n            len += dist[x][y][nx*n + ny];\n            x = nx; y = ny;\n        }\n        if (len + dist[x][y][0] > limit)\n            break;\n        add_route(x, y, 0, 0, dist, answer, n);\n        break;\n    }\n    \n    cout << string(answer.begin(), answer.end()) << endl;\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\n#include <boost/algorithm/string/find_tail.hpp>\nusing namespace std;\n\nstring concat(const vector<string>& t) {\n    int m = t.size();\n    string result = t[0];\n    unordered_map<string, vector<int>> suffix;\n    for (int i=0; i<m; ++i) {\n        for (int len=1; len<=4; ++len) {\n            suffix[t[i].substr(t[i].size() - len)].push_back(i);\n        }\n    }\n    vector<bool> used(m, false);\n    used[0] = true;\n    \n    auto get_cost = [&](int idx, const string& prev_str) {\n        string target = t[idx];\n        int n = prev_str.size();\n        int max_overlap = 0;\n        for (int i=1; i<=4 && i<=n; ++i) {\n            if (boost::algorithm::ends_with(prev_str, target.substr(0,i))) \n                max_overlap = i;\n        }\n        return target.size() - max_overlap;\n    };\n    \n    for (int count=1; count<m; ++count) {\n        int best_idx = -1, min_cost = INT_MAX;\n        for (int i=0; i<m; ++i) {\n            if (!used[i]) {\n                int cost = get_cost(i, result);\n                if (cost < min_cost) {\n                    min_cost = cost;\n                    best_idx = i;\n                }\n            }\n        }\n        if (best_idx == -1) break;\n        used[best_idx] = true;\n        string current = t[best_idx];\n        int n = result.size();\n        int overlap = 0;\n        for (int k=1; k<=min(4,n); ++k) {\n            if (boost::algorithm::ends_with(result, current.substr(0,k)))\n                overlap = k;\n        }\n        result += current.substr(overlap);\n    }\n    return result.substr(0, 5000);\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> A(N);\n    for (int i=0; i<N; ++i) cin >> A[i];\n    \n    vector<string> words(M);\n    unordered_map<char, pair<int,int>> pos;\n    \n    for (int i=0; i<M; ++i) cin >> words[i];\n    \n    for (int i=0; i<N; ++i) \n        for (int j=0; j<N; ++j) \n            pos[A[i][j]] = {i, j};\n    \n    string lucky = concat(words);\n    pair<int, int> current = {si, sj};\n    vector<pair<int,int>> steps;\n    \n    for (char c : lucky) {\n        steps.emplace_back(pos[c]);\n    }\n    \n    cout << steps.size() << endl;\n    for (auto& [x, y] : steps) {\n        cout << x << \" \" << y << endl;\n    }\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nusing namespace std;\nusing namespace boost::accumulators;\n\nstruct Grid {\n    int n;\n    boost::multi_array<int, 2> grid;  // 0: unknown, -1: empty, >=1: count\n    vector<pair<int,int>> unknown;\n    mt19937 mt{random_device{}()};\n    \n    Grid(int _n) : n(_n), grid(boost::extents[_n][_n]) {\n        for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) {\n            grid[i][j] = 0;\n            unknown.emplace_back(i, j);\n        }\n    }\n    \n    bool is_unknown(int i, int j) const {\n        return 0 <= i && i < n && 0 <= j && j <n && grid[i][j] == 0;\n    }\n    \n    void query_group(int size, const vector<pair<int,int>>& indexes) {\n        cout << \"q \" << size;\n        for (auto [x,y] : indexes) cout << ' ' << x << ' ' << y;\n        cout << endl;\n        int result;\n        cin >> result;\n        double mean = result + size * (1e-5); // Prevent division by zero\n        double stddev = sqrt(size * 0.2); // Conservative estimate\n        \n        double z_score = (result - size * 0.1) / (stddev + 1e-5);\n        for (auto [x,y] : indexes) {\n            if (grid[x][y] == 0) {\n                if (z_score > 2.0) grid[x][y] = 2;\n                else if (z_score < -1.5) grid[x][y] = -1;\n            }\n        }\n    }\n    \n    void drill(int i, int j) {\n        cout << \"q 1 \" << i << ' ' << j << endl;\n        cin >> grid[i][j];\n    }\n    \n    void report() {\n        vector<pair<int,int>> positives;\n        for (int i=0; i<n; ++i)\n            for (int j=0; j<n; ++j)\n                if (grid[i][j] > 0) positives.emplace_back(i,j);\n        \n        cout << \"a \" << positives.size();\n        for (auto [x,y] : positives) cout << ' ' << x << ' ' << y;\n        cout << endl;\n        exit(0);\n    }\n};\n\nbool is_border(int i, int j, int n) {\n    return i == 0 || j == 0 || i == n-1 || j == n-1;\n}\n\nint main() {\n    srand(time(0));\n    int N, M;\n    double epsilon;\n    cin >> N >> M >> epsilon;\n    vector<vector<pair<int,int>>> oil(M);\n    \n    for (int m=0; m<M; ++m) {\n        int d; cin >> d;\n        oil[m].resize(d);\n        for (int k=0; k<d; ++k) {\n            cin >> oil[m][k].first >> oil[m][k].second;\n        }\n    }\n    \n    Grid g(N);\n    int total = N * N;\n    int budget = total / 3;\n    \n    // Initial divination phase: 5x5 blocks\n    for (int i=0; i+5<=N; i+=5) {\n        for (int j=0; j+5<=N; j+=5) {\n            if (budget-- <= 0) break;\n            vector<pair<int,int>> block;\n            for (int x=i; x < i+5; ++x)\n                for (int y=j; y < j+5; ++y) \n                    if (g.is_unknown(x,y)) block.emplace_back(x,y);\n            if (block.size() >= 2) g.query_group(block.size(), block);\n        }\n        if (budget <= 0) break;\n    }\n    \n    // Remaining cells: smaller divination\n    while (budget >= 5 && g.unknown.size() >= 5) {\n        shuffle(g.unknown.begin(), g.unknown.end(), g.mt);\n        vector<pair<int,int>> batch;\n        while (budget >= 0 && batch.size() < 20 && !g.unknown.empty()) {\n            auto [x,y] = g.unknown.back();\n            g.unknown.pop_back();\n            if (g.is_unknown(x,y)) {\n                batch.emplace_back(x,y);\n            }\n        }\n        if (batch.size() >= 2) {\n            g.query_group(batch.size(), batch);\n            budget--;\n        }\n    }\n    \n    // Drill borders\n    for (auto &cell : g.unknown) {\n        if (g.is_unknown(cell.first, cell.second) && is_border(cell.first, cell.second, N)) {\n            g.drill(cell.first, cell.second);\n        }\n    }\n    \n    // Drill remaining\n    for (auto &cell : g.unknown) {\n        if (g.is_unknown(cell.first, cell.second)) {\n            g.drill(cell.first, cell.second);\n        }\n    }\n    \n    g.report();\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<tuple<int,int,int,int>> rectangles[55];\n\nvoid solve(int n, const vector<int>& areas) {\n    int w = 1000;\n    int sum = accumulate(areas.begin(), areas.end(), 0);\n    int remaining = w * w - sum;\n    vector<int> needed = areas;\n    int max_y = w;\n\n    rectangles[n].resize(areas.size());\n    \n    for (int i=0; i<(int)areas.size(); ++i) {\n        int rows = (remaining + (int)areas.size() - i - 1) / ((int)areas.size() - i);\n        rows = max(rows, (needed[i] + w - 1) / w); // at least enough area\n        \n        int y_start = max_y - rows;\n        get<0>(rectangles[n][i]) = y_start;\n        get<2>(rectangles[n][i]) = max_y;\n        get<1>(rectangles[n][i]) = 0;\n        int cols = needed[i] / rows;\n        if (cols * rows < needed[i]) ++cols;\n        cols = min(cols, w); // max columns can't exceed grid width\n        get<3>(rectangles[n][i]) = cols;\n        \n        remaining -= (rows * cols - needed[i]);\n        max_y = y_start;\n    }\n    \n    int last_x = 0;\n    for (int k=0; k < (int)rectangles[n].size(); ++k) {\n        get<1>(rectangles[n][k]) = last_x;\n        last_x += get<3>(rectangles[n][k]);\n        get<3>(rectangles[n][k]) = last_x;\n    }\n}\n\nint main() {\n    int W = 1000, D, N;\n    cin >> W >> D >> N;\n    \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    for (int d=0; d<D; ++d) \n        solve(d, a[d]);\n    \n    for (int d=0; d<D; ++d)\n        for (auto [x1,y1,x2,y2] : rectangles[d])\n            printf(\"%d %d %d %d\\n\", x1, y1, x2, y2);\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nconst int MOD = 998244353;\nconst int N = 9;\nint a[N][N], s[20][3][3];\n\nint get_gain(int m, int p, int q) {\n    int total = 0;\n    for (int i = 0; i < 3; ++i)\n        for (int j = 0; j < 3; ++j) {\n            int new_val = (a[p+i][q+j] + s[m][i][j]) % MOD;\n            total += (new_val - a[p+i][q+j] + MOD) % MOD;\n        }\n    return total;\n}\n\nvoid apply_stamp(int m, int p, int q) {\n    for (int i = 0; i < 3; ++i)\n        for (int j = 0; j < 3; ++j)\n            a[p+i][q+j] = (a[p+i][q+j] + s[m][i][j]) % MOD;\n}\n\nint main() {\n    mt19937 rng(random_device{}());\n    int n, m, k;\n    cin >> n >> m >> k;\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n    \n    for (int t = 0; t < m; ++t)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> s[t][i][j];\n\n    vector<tuple<int, int, int>> ops;\n    int used = 0;\n\n    // Prioritize deterministic best moves first\n    while (used < k) {\n        int best_gain = -1, bst_m = -1, bst_p = -1, bst_q = -1;\n        for (int m_idx = 0; m_idx < m; ++m_idx) {\n            for (int p = 0; p <= 6; ++p) {\n                for (int q = 0; q <= 6; ++q) {\n                    int gain = get_gain(m_idx, p, q);\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        bst_m = m_idx;\n                        bst_p = p;\n                        bst_q = q;\n                    }\n                }\n            }\n        }\n        if (best_gain <= 0 || ops.size() == k) break;\n        ops.emplace_back(bst_m, bst_p, bst_q);\n        apply_stamp(bst_m, bst_p, bst_q);\n        ++used;\n    }\n\n    // Fill remaining with semi-random choices\n    vector<pair<int, int>> pos;\n    for (int x = 0; x <= 6; ++x) for (int y = 0; y <= 6; ++y) pos.emplace_back(x, y);\n    while (used < k) {\n        shuffle(pos.begin(), pos.end(), rng);\n        for (auto [x, y] : pos) {\n            if (used == k) break;\n            for (int m_idx = rng() % m; m_idx < m; ++m_idx) {\n                if (used == k) break;\n                ops.emplace_back(m_idx, x, y);\n                apply_stamp(m_idx, x, y);\n                ++used;\n            }\n        }\n    }\n\n    cout << ops.size() << \"\\n\";\n    for (auto [m, p, q] : ops)\n        cout << m << \" \" << p << \" \" << q << \"\\n\";\n}","ahc033":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nvector<string> solve(const vector<vector<int>>& containers) {\n    int N = containers.size();\n    vector<int> targetRow(N * N);\n    for (int i = 0; i < N; ++i)\n        for (int k = 0; k < N; ++k)\n            targetRow[containers[i][k]] = i;\n\n    vector<vector<int>> targetPos(N * N);\n    for (int b = 0; b < N * N; ++b) {\n        int r = targetRow[b];\n        targetPos[b] = {r, N-1};\n    }\n\n    vector<string> res(N);\n    int T = 30 + N * N * 5;\n    for (int t = 0; t < T; ++t) {\n        for (int i = 0; i < N; ++i)\n            res[i] += '.';\n        bool moved = false;\n        // Large crane (index 0)\n        if (res[0].back() != 'B') {\n            vector<int> cranePos = {0 + t % N, 0};\n            if (cranePos[1] < N-1) {\n                int mx = -1;\n                for (int x = 0; x < N; ++x) {\n                    if (cranePos[0] == x && containers[x].size() > t) {\n                        int b = containers[x][t];\n                        if (mx == -1 || targetRow[mx] < targetRow[b]) {\n                            mx = b;\n                        }\n                    }\n                }\n                if (mx != -1 && t + abs(cranePos[0] - targetPos[mx][0]) + abs(cranePos[1] - targetPos[mx][1]) <= T) {\n                    if (cranePos[1] == 0) res[0].back() = 'P';\n                    else {\n                        if (targetPos[mx][1] == cranePos[1] + 1) res[0].back() = 'R';\n                        else if (targetPos[mx][0] > cranePos[0] && cranePos[0] < N-1) res[0].back() = 'D';\n                        else if (targetPos[mx][0] < cranePos[0] && cranePos[0] > 0) res[0].back() = 'U';\n                    }\n                    moved = true;\n                }\n            }\n        }\n\n        // Small cranes\n        for (int i = 1; i < N; ++i) {\n            if (res[i].back() != 'B') {\n                vector<int> cranePos = {i, 0};\n                auto update = [&](int dx, int dy, char dir) {\n                    if (cranePos[0] + dx >= 0 && cranePos[0] + dx < N && cranePos[1] + dy >= 0 && cranePos[1] + dy < N) {\n                        res[i].back() = dir;\n                        moved = true;\n                    }\n                };\n                bool carrying = (res[i].size() > 0 && res[i].back() == 'P');\n                // Drop container if at Dispatch Gate\n                if (cranePos[1] == N-1 && carrying) res[i].back() = 'Q';\n                // Else move towards Dispatch Gates or pick up containers\n                else if (cranePos[1] > 0 && !carrying) update(0, -1, 'L');\n                else if (cranePos[1] < N-1) update(0, 1, 'R');\n            }\n        }\n        if (!moved) break;\n    }\n    return res;\n}\n\nint main() {\n    int N = 5;\n    vector<vector<int>> containers(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> containers[i][j];\n    auto commands = solve(containers);\n    int maxLen = 0;\n    for (auto& s : commands) maxLen = max(maxLen, (int)s.size());\n    for (auto& s : commands) s.resize(maxLen, '.');\n    for (auto& s : commands) cout << s << endl;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint H[20][20], dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}, vis[20][20];\nvector<string> ans;\nint n = 20, x = 0, y = 0, load = 0;\n\nvoid move(int nx, int ny) {\n    while (x != nx || y != ny) {\n        if (x > nx) ans.push_back(\"U\"), x--;\n        else if (x < nx) ans.push_back(\"D\"), x++;\n        else if (y > ny) ans.push_back(\"L\"), y--;\n        else ans.push_back(\"R\"), y++;\n    }\n}\n\nvoid load_soil(int val) {\n    ans.push_back(\"+\" + to_string(val));\n    load += val;\n    H[x][y] -= val;\n}\n\nvoid unload_soil(int val) {\n    ans.push_back(\"-\" + to_string(val));\n    load -= val;\n    H[x][y] += val;\n}\n\nvoid process() {\n    memset(vis, 0, sizeof(vis));\n    vector<pair<int, int>> positives, negatives;\n    \n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            (H[i][j] > 0) ? positives.emplace_back(H[i][j], i*n+j) :\n            (H[i][j] < 0) ? negatives.emplace_back(-H[i][j], i*n+j) : void();\n        }\n    }\n\n    sort(positives.rbegin(), positives.rend());\n    sort(negatives.rbegin(), negatives.rend());\n\n    auto get = [&](int val) { return pair{val/n, val%n}; };\n\n    while (!positives.empty() && !negatives.empty()) {\n        auto [pval, pos] = positives.back(); positives.pop_back();\n        auto [nval, neg] = negatives.back(); negatives.pop_back();\n        auto [posx, posy] = get(pos);\n        auto [negx, negy] = get(neg);\n\n        if (pval == 0 || nval == 0) break;\n        int transfer = min(pval, nval);\n\n        move(posx, posy);\n        load_soil(transfer);\n        move(negx, negy);\n        unload_soil(transfer);\n\n        if (pval > transfer) positives.emplace_back(pval - transfer, pos);\n        if (nval > transfer) negatives.emplace_back(nval - transfer, neg);\n    }\n\n    while (!positives.empty()) {\n        auto [pval, pos] = positives.back(); positives.pop_back();\n        auto [posx, posy] = get(pos);\n        if (posx == x && posy == y) continue;\n        move(posx, posy);\n        load_soil(pval);\n    }\n\n    while (!negatives.empty()) {\n        auto [nval, neg] = negatives.back(); negatives.pop_back();\n        auto [negx, negy] = get(neg);\n        move(negx, negy);\n        unload_soil(nval);\n    }\n}\n\nint main() {\n    cin >> n;\n    for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) cin >> H[i][j];\n    \n    process();\n    for (auto& op : ans) cout << op << endl;\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\nusing namespace std;\n\nconstexpr int N = 6;\nconstexpr int SEED_COUNT = 2 * N * (N - 1);\nconstexpr int FIELD_SIZE = N * N;\n\nnamespace atcoder {\n    void internal_error() {\n        cerr << \"Error!\" << endl;\n        exit(0);\n    }\n\n    mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());\n\n    int rand(int a, int b) {\n        return uniform_int_distribution<int>(a, b)(mt);\n    }\n\n    double rand(double a, double b) {\n        return uniform_real_distribution<double>(a, b)(mt);\n    }\n}\nusing namespace atcoder;\n\nstruct Seed {\n    vector<int> eval;\n    int total;\n\n    Seed(const vector<int> &eval) : eval(eval) {\n        total = accumulate(eval.begin(), eval.end(), 0);\n    }\n\n    bool operator<(const Seed &other) const {\n        return this->total < other.total;\n    }\n};\n\nvector<int> next_gen(int round, const vector<Seed> &seeds) {\n    // Prioritize top seeds\n    vector<int> sorted_id(SEED_COUNT);\n    iota(sorted_id.begin(), sorted_id.end(), 0);\n    sort(sorted_id.begin(), sorted_id.end(), [&](int a, int b) {\n        return seeds[a].total > seeds[b].total;\n    });\n\n    vector<int> layout(FIELD_SIZE);\n    fill(layout.begin(), layout.end(), -1);\n    \n    // Place the N*N best seeds on the board\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            layout[i * N + j] = sorted_id[i * N + j];\n        }\n    }\n\n    return layout;\n}\n\nint main() {\n    int M, T;\n    cin >> N >> M >> T;\n\n    vector<Seed> seeds;\n    for (int i = 0; i < SEED_COUNT; ++i) {\n        vector<int> eval(M);\n        for (int &val : eval) cin >> val;\n        seeds.emplace_back(eval);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        auto layout = next_gen(t, seeds);\n        \n        for (int i = 0; i < FIELD_SIZE; ++i) {\n            cout << layout[i] << (i % N == N - 1 ? '\\n' : ' ');\n        }\n        cout << flush;\n\n        // Read the newly generated seeds\n        seeds.resize(SEED_COUNT);\n        for (int i = 0; i < SEED_COUNT; ++i) {\n            vector<int> eval(M);\n            for (int &val : eval) cin >> val;\n            seeds[i] = Seed(eval);\n        }\n    }\n}","ahc038":"#include <bits/stdc++.h>\n#include <queue>\n#include <optional>\nusing namespace std;\n\nconstexpr int INF = 1e9;\n\nstruct Pos {\n    int x, y;\n    bool operator==(const Pos& o) const { return x == o.x && y == o.y; }\n    Pos rotate(char c) const {\n        if (c == 'L') return {-y, x};\n        if (c == 'R') return {y, -x};\n        return {x, y};\n    }\n};\n\nstruct State {\n    int turns;\n    Pos pos;\n    vector<Pos> fingers; // relative positions\n    State(int t, Pos p, const vector<Pos>& f) : turns(t), pos(p), fingers(f) {}\n};\n\nvector<string> grid;\nvector<vector<char>> rotations;\nint dist(Pos a, Pos b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvector<string> find_path(Pos start, Pos goal, int V, const string& initial_rot = \"\") {\n    priority_queue<pair<int, State>, vector<pair<int, State>>, greater<>> pq;\n    unordered_map<Pos, int> dirs = {{'R', 0}, {'D', 1}, {'L', 2}, {'U', 3}};\n    vector<Pos> dir_offs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n    vector<string> dir_strs = {\"R\", \"D\", \"L\", \"U\"};\n    unordered_map<State, int, hash<State>> visited;\n    \n    vector<Pos> init_fingers(V - 1);\n    for (int i = 0; i < V - 1; ++i) {\n        init_fingers[i] = {i + 1, 0};\n    }\n    for (char c : initial_rot) {\n        if (c == '.') break;\n        for (auto& f : init_fingers) f = f.rotate(c);\n    }\n    \n    auto start_state = State(0, start, init_fingers);\n    pq.emplace(dist(start, goal), start_state);\n    visited[start_state] = 0;\n    \n    while (!pq.empty()) {\n        auto [current_cost, current] = pq.top();\n        pq.pop();\n        if (current.pos == goal) {\n            vector<string> path;\n            string rot = initial_rot.substr(0, V - 1);\n            while (current.turns > 0) {\n                path.emplace_back(dir_strs[current.pos.x] + rot + string(V, '.'));\n                for (char& c : rot) {\n                    if (c == 'R') c = 'L';\n                    else if (c == 'L') c = 'R';\n                }\n                reverse(rot.begin(), rot.end());\n                current.pos = goal;\n                --current.turns;\n            }\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        \n        for (int i = 0; i < 4; ++i) {\n            Pos next_pos = {current.pos.x + dir_offs[i].x, current.pos.y + dir_offs[i].y};\n            if (next_pos.x < 0 || next_pos.x >= grid.size() || next_pos.y < 0 || next_pos.y >= grid.size())\n                continue;\n            auto new_state = State(current.turns + 1, next_pos, current.fingers);\n            if (visited.count(new_state) && visited[new_state] <= new_state.turns)\n                continue;\n            visited[new_state] = new_state.turns;\n            pq.emplace(new_state.turns + dist(next_pos, goal), new_state);\n        }\n        \n        // Rotate subtrees\n        for (int v = 1; v < V; ++v) {\n            for (char rot : {'L', 'R'}) {\n                vector<Pos> new_fingers = current.fingers;\n                for (auto& f : new_fingers) f = f.rotate(rot);\n                auto rotated = State(current.turns + 1, current.pos, new_fingers);\n                if (visited.count(rotated) && visited[rotated] <= rotated.turns)\n                    continue;\n                visited[rotated] = rotated.turns;\n                pq.emplace(rotated.turns + dist(current.pos, goal), rotated);\n            }\n        }\n    }\n    return {};\n}\n\nint main() {\n    // Example input parsing; actual input handling depends on contest environment\n    int N = 20, M = 7, V = 8; \n    vector<pair<Pos, Pos>> tasks = {\n        {{0,0}, {15,5}}, {{3,2}, {17,7}}, {{5,5}, {18,18}}, \n        {{12,8}, {2,2}}, {{15,19}, {3,3}}, {{7,11}, {10,10}}, {{9,14}, {11,2}}\n    };\n    \n    cout << V << \"\\n\";\n    for (int i = 1; i < V; ++i) {\n        cout << \"0 \" << 1 << '\\n'; // star structure with length 1\n    }\n    cout << \"0 0\\n\"; // initial root position\n    \n    vector<bool> done(M, false);\n    Pos current = {0, 0};\n    int completed = 0;\n    \n    for (int steps = 0; completed < M; ++steps) {\n        pair<int, int> best = {INF, -1};\n        for (int i = 0; i < M; ++i) {\n            if (!done[i]) {\n                int cost = dist(current, tasks[i].first) + dist(tasks[i].first, tasks[i].second);\n                best = min(best, {cost, i});\n            }\n        }\n        int idx = best.second;\n        if (idx < 0) break;\n        \n        // Move to source\n        auto path1 = find_path(current, tasks[idx].first, V);\n        for (auto& s : path1) {\n            cout << s << '\\n';\n        }\n        current = tasks[idx].first;\n        \n        // Operation to grab\n        cout << \".\" + string(V - 1, '.') + string(V - 1, '.') << \"P\\n\";\n        \n        // Move to target\n        auto path2 = find_path(current, tasks[idx].second, V);\n        for (auto& s : path2) {\n            cout << s << '\\n';\n        }\n        \n        // Operation to release\n        cout << \".\" + string(V - 1, '.') + string(V - 1, '.') << \"P\\n\";\n        \n        done[idx] = true;\n        completed++;\n        current = tasks[idx].second;\n    }\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Box {\n    int x1, y1, x2, y2;\n    bool contains(int x, int y) const {\n        return x1 <= x && x <= x2 && y1 <= y && y <= y2;\n    }\n    int perimeter() const {\n        return 2 * ((x2 - x1) + (y2 - y1));\n    }\n    bool valid() const {\n        return x1 <= x2 && y1 <= y2;\n    }\n};\n\nint main() {\n    int N = 5000;\n    vector<pair<int, int>> mackerel(N), sardine(N);\n    for (int i = 0; i < 2*N; ++i) {\n        int x, y; cin >> x >> y;\n        if (i < N) mackerel[i] = {x, y};\n        else sardine[i-N] = {x, y};\n    }\n\n    constexpr int kGridSize = 1e5 / 10;\n    int best_cell = -1, max_mackerel = -1;\n    vector<int> count(100, 0);\n    \n    for (auto& [x, y] : mackerel) {\n        int cx = x / kGridSize;\n        int cy = y / kGridSize;\n        if (++count[cx*10 + cy] > max_mackerel) {\n            max_mackerel = count[cx*10 + cy];\n            best_cell = cx*10 + cy;\n        }\n    }\n\n    if (best_cell == -1) { // Handle case with no mackerels found (unlikely but safe)\n        cout << \"4\\n0 0\\n0 100000\\n100000 100000\\n100000 0\\n\";\n        return 0;\n    }\n    \n    int start_x = (best_cell / 10) * kGridSize;\n    int start_y = (best_cell % 10) * kGridSize;\n    int end_x = start_x + kGridSize - 1;\n    int end_y = start_y + kGridSize - 1;\n    constexpr int max_edge = 4e5;\n\n    Box best_box{start_x, start_y, end_x, end_y};\n    int best_score = max_mackerel - count_if(sardine.begin(), sardine.end(), \n              [&](auto& p){ return best_box.contains(p.first, p.second); });\n\n    // Check expansions\n    int offsets[] = {0, kGridSize, 2*kGridSize, 3*kGridSize};\n    for (int dx = 0; dx <= 3*kGridSize; dx += kGridSize) {\n        for (int dy = 0; dy <= 3*kGridSize; dy += kGridSize) {\n            Box current{\n                max(0, start_x - dx),\n                max(0, start_y - dy),\n                min((int)1e5, end_x + dx),\n                min((int)1e5, end_y + dy)\n            };\n            if (current.perimeter() > max_edge || !current.valid()) continue;\n\n            int current_mack = 0, current_sard = 0;\n            for (auto& [x, y] : mackerel) if (current.contains(x, y)) ++current_mack;\n            for (auto& [x, y] : sardine) if (current.contains(x, y)) ++current_sard;\n\n            if (current_mack - current_sard > best_score) {\n                best_box = current;\n                best_score = current_mack - current_sard;\n            }\n        }\n    }\n\n    vector<pair<int, int>> ans = {\n        {best_box.x1, best_box.y1},\n        {best_box.x1, best_box.y2},\n        {best_box.x2, best_box.y2},\n        {best_box.x2, best_box.y1}\n    };\n\n    cout << ans.size() << '\\n';\n    for (auto& [x, y] : ans) cout << x << ' ' << y << '\\n';\n}","ahc040":"#include <bits/stdc++.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\nusing namespace std;\nusing namespace boost::geometry;\n\nstruct Rect {\n    int x, y, w, h;\n    bool rotated;\n};\n\nvector<pair<int, int>> sizes;\nvector<int> order;\nint N, T;\ndouble start_temp = 1e3, end_temp = 1e-5;\nmt19937 mt(chrono::steady_clock::now().time_since_epoch().count());\n\npair<int, int> place_rects(const vector<int>& perm, bool left_first = false, int mode = 0) {\n    map<pair<int, int>, int> points;\n    points[{0, 0}] = -1;\n    vector<Rect> rects;\n    int max_x = 0, max_y = 0;\n    \n    auto update_max = [&](int x, int y) {\n        max_x = max(max_x, x);\n        max_y = max(max_y, y);\n    };\n    \n    auto can_place = [&](int x, int y, int w, int h) {\n        model::box<point<int>> box(point(x, y), point(x + w, y + h));\n        for (auto& r : rects) {\n            if (overlaps(box, model::box<point<int>>(\n                point(r.x, r.y), point(r.x + r.w, r.y + r.h))\n            )) return false;\n        }\n        return true;\n    };\n    \n    int idx = 0;\n    for (int op : perm) {\n        int rw = max(sizes[op].first, sizes[op].second);\n        int rh = min(sizes[op].first, sizes[op].second);\n        bool rot = (sizes[op].first < sizes[op].second);\n        bool placed = false;\n        \n        for (int step = 0; step < 2; ++step) { // 2 orientations\n            if (step == 1) swap(rw, rh), rot = !rot;\n            // Try U (up) first\n            if (!left_first || idx++ % 2 == mode) {\n                for (auto [pt, prev] : points) {\n                    int x = pt.first, y_try = pt.second;\n                    if (can_place(x, y_try, rw, rh)) {\n                        rects.push_back({x, y_try, rw, rh, rot});\n                        points[{x + rw, y_try + rh}] = prev;\n                        update_max(x + rw, y_try + rh);\n                        placed = true;\n                        break;\n                    }\n                }\n                if (placed) break;\n            }\n            // Then try L (left)\n            if (left_first || idx % 2 != mode) {\n                for (auto [pt, prev] : points) {\n                    int y = pt.second, x_try = pt.first;\n                    if (can_place(x_try, y, rw, rh)) {\n                        rects.push_back({x_try, y, rw, rh, rot});\n                        points[{x_try + rw, y + rh}] = prev;\n                        update_max(x_try + rw, y + rh);\n                        placed = true;\n                        break;\n                    }\n                }\n                if (placed) break;\n            }\n        }\n        if (!placed) { max_x += rw; max_y += rh; } // penalty for unused\n    }\n    return {max_x, max_y};\n}\n\nvoid solve() {\n    cin >> N >> T;\n    double sigma; cin >> sigma;\n    sizes.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> sizes[i].first >> sizes[i].second;\n        sizes[i].first += 3 * sigma;  // Upper approx\n        sizes[i].second += 3 * sigma;\n        if (sizes[i].first > 1e9) sizes[i].first = 1e9;\n        if (sizes[i].second > 1e9) sizes[i].second = 1e9;\n        order.push_back(i);\n    }\n    \n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return max(sizes[a].first, sizes[a].second) > max(sizes[b].first, sizes[b].second);\n    });\n    \n    auto best = place_rects(order);\n    auto best_order = order;\n    \n    // Simulated Annealing\n    for (int iteration = 0; iteration < 30; ++iteration) {\n        auto current = order;\n        for (double temp = start_temp; temp > end_temp; temp *= 0.99) {\n            int i = uniform_int_distribution<>(0, N-1)(mt);\n            int j = uniform_int_distribution<>(0, N-1)(mt);\n            swap(current[i], current[j]);\n            \n            auto candidate = place_rects(current, iteration % 2 == 0, iteration / 10);\n            int current_score = best.first + best.second;\n            int candidate_score = candidate.first + candidate.second;\n            \n            if (candidate_score < current_score || \n                exp((current_score - candidate_score) / temp) > (double)mt()/mt.max()) {\n                best = candidate;\n            } else {\n                swap(current[i], current[j]); // revert\n            }\n        }\n    }\n    \n    for (int t = 0; t < T; ++t) {\n        cout << N << '\\n';\n        for (size_t i = 0; i < best_order.size(); ++i) {\n            int id = best_order[i];\n            cout << id << ' ' << \"0\" << ' ' << (i % 2 ? 'L' : 'U') << ' ' << (i > 0 ? best_order[i-1] : -1) << '\\n';\n        }\n        cout.flush();\n        \n        int W, H;\n        cin >> W >> H;\n        if (t == T-1) break;\n        \n        // Optional: Adjust based on feedback if needed\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\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    cin >> N >> M >> H;\n    vector<int> A(N);\n    for (int& a : A) cin >> a;\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // Prepare order by highest beauty first\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return A[a] > A[b];\n    });\n\n    constexpr int UNVISITED = -2;\n    vector<int> parent(N, UNVISITED);\n    vector<bool> visited(N, false);\n\n    auto bfs = [&](int start) {\n        deque<int> q;\n        q.push_back(start);\n        visited[start] = true;\n        parent[start] = -1;\n        int current_height = 0;\n        \n        while (!q.empty() && current_height < H) {\n            int level_size = q.size();\n            current_height++;\n            \n            for (int i = 0; i < level_size; ++i) {\n                int u = q.front();\n                q.pop_front();\n                \n                for (int v : adj[u]) {\n                    if (!visited[v]) {\n                        visited[v] = true;\n                        if (current_height < H) {\n                            parent[v] = u;\n                        } else {\n                            parent[v] = -1;\n                        }\n                        q.push_back(v);\n                    }\n                }\n            }\n        }\n    };\n    \n    for (int u : order) {\n        if (!visited[u]) {\n            bfs(u);\n        }\n    }\n\n    // Ensure all nodes are assigned\n    for (int i = 0; i < N; ++i) {\n        if (parent[i] == UNVISITED) parent[i] = -1;\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        if (parent[i] == -1) continue;\n        int count = 0;\n        int temp = i;\n        while (parent[temp] != -1) {\n            temp = parent[temp];\n            count++;\n            if (count >= H) {\n                parent[i] = -1; // reset to root if exceeds height H\n                break;\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << parent[i] << (i == N-1 ? '\\n' : ' ');\n    }\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nvoid perform_shift(int type, int idx, int direction, vector<pair<char, int>>& operations) {\n    char dir_char;\n    if (type == 0) { // row\n        dir_char = (direction == 0) ? 'L' : 'R';\n        for (int i = 0; i < 20; ++i) operations.emplace_back(dir_char, idx);\n    } else { // column\n        dir_char = (direction == 0) ? 'U' : 'D';\n        for (int i = 0; i < 20; ++i) operations.emplace_back(dir_char, idx);\n    }\n}\n\nint main() {\n    int n = 20;\n    vector<string> board(n);\n    for (auto& row : board) cin >> row;\n\n    vector<pair<char, int>> operations;\n    vector<vector<bool>> processed(n, vector<bool>(n, false));\n\n    // Prioritize rows and columns by the number of Oni and least Fukunokami\n    for (int iter = 0; iter < 40; ++iter) {\n        vector<pair<int, pair<int, int>>> candidates;\n        for (int i = 0; i < n; ++i) {\n            int oni_count = 0, fuku_count = 0;\n            for (int j = 0; j < n; ++j) {\n                if (board[i][j] == 'x') ++oni_count;\n                if (board[i][j] == 'o') ++fuku_count;\n            }\n            if (oni_count > 0 && fuku_count == 0)\n                candidates.emplace_back(oni_count, make_pair(0, i)); // row i\n        }\n        for (int j = 0; j < n; ++j) {\n            int oni_count = 0, fuku_count = 0;\n            for (int i = 0; i < n; ++i) {\n                if (board[i][j] == 'x') ++oni_count;\n                if (board[i][j] == 'o') ++fuku_count;\n            }\n            if (oni_count > 0 && fuku_count == 0)\n                candidates.emplace_back(oni_count, make_pair(1, j)); // column j\n        }\n\n        if (candidates.empty()) break;\n\n        sort(candidates.rbegin(), candidates.rend());\n        auto best = candidates[0].second;\n        if (best.first == 0) { // row\n            perform_shift(0, best.second, 0, operations);\n            perform_shift(0, best.second, 1, operations);\n        } else { // column\n            perform_shift(1, best.second, 0, operations);\n            perform_shift(1, best.second, 1, operations);\n        }\n\n        // Update Board\n        if (best.first == 0) {\n            for (int j = 0; j < n; ++j) {\n                if (board[best.second][j] == 'x') board[best.second][j] = '.';\n            }\n        } else {\n            for (int i = 0; i < n; ++i) {\n                if (board[i][best.second] == 'x') board[i][best.second] = '.';\n            }\n        }\n    }\n\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing namespace boost::multiprecision;\n\nusing lint = long long;\nusing P = pair<lint, int>; \nconstexpr lint INF = 1LL<<60;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N = 100;\n    lint L = 500000;\n    cin >> N >> L;\n    vector<lint> T(N);\n    for (auto& t : T) cin >> t;\n    \n    vector<int> a(N), b(N), cnt(N);\n    priority_queue<P> pq;\n    for (int i=0; i<N; ++i) pq.emplace(T[i], i);\n    \n    vector<bool> used(N, false);\n    auto pick_next = [&](int cur) {\n        for (int j=0; j<N; ++j) {\n            if (!used[j] && j != cur) {\n                used[j] = true;\n                return j;\n            }\n        }\n        return (cur + 1) % N;\n    };\n    \n    int prev = -1;\n    bool even = true;\n    \n    while (!pq.empty()) {\n        auto [need, idx] = pq.top(); pq.pop();\n        if (cnt[idx] >= need) continue;\n        \n        if (prev != -1) {\n            if (even) a[prev] = idx;\n            else b[prev] = idx;\n        }\n        ++cnt[idx];\n        pq.emplace(need - cnt[idx], idx);\n        prev = idx;\n        even ^= true;\n    }\n    \n    for (int i=0; i<N; ++i) {\n        if (cnt[i] < T[i]) a[i] = i;\n    }\n    \n    for (int i=0; i<N; ++i) {\n        cout << a[i] << \" \" << b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\nusing ll = long long;\nusing P = pair<int, int>;\n\nconst int INF = 1e9;\nrandom_device rd;\nmt19937 RNG(rd());\n\nstruct City {\n    int idx;\n    int cx, cy; // center\n    City(int i, int lx, int rx, int ly, int ry) \n        : idx(i), cx((lx+rx)/2), cy((ly+ry)/2) {}\n    bool operator<(const City& o) const {\n        return make_pair(cx, cy) < make_pair(o.cx, o.cy);\n    }\n};\n\nvector<int> query_group(const vector<City>& group) {\n    if (group.size() < 2) return {};\n    cout << \"? \" << group.size();\n    for (auto& c : group) cout << \" \" << c.idx;\n    cout << endl;\n    \n    vector<int> res;\n    int edges = group.size() - 1;\n    for (int i=0; i < edges; ++i) {\n        int u, v; cin >> u >> v;\n        if (u > v) swap(u, v);\n        res.emplace_back(u);\n        res.emplace_back(v);\n    }\n    return res;\n}\n\nvoid solve() {\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (auto& g : G) cin >> g;\n    \n    vector<City> cities;\n    for (int i=0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cities.emplace_back(i, lx, rx, ly, ry);\n    }\n    sort(cities.begin(), cities.end());\n    \n    // Assign cities to groups\n    vector<vector<int>> groups(M);\n    int pos = 0;\n    for (int i=0; i < M; ++i) {\n        for (int j=0; j < G[i]; ++j, ++pos) {\n            groups[i].push_back(cities[pos].idx);\n        }\n    }\n\n    // Query MST and build connections\n    vector<tuple<int, int, int>> all_edges;\n    for (auto& group : groups) {\n        vector<City> current_group;\n        for (auto idx : group) {\n            for (auto& c : cities) {\n                if (c.idx == idx) {\n                    current_group.push_back(c);\n                    break;\n                }\n            }\n        }\n        vector<int> raw = query_group(current_group);\n        for (size_t i=0; i < raw.size(); i += 2) {\n            int u = raw[i], v = raw[i+1];\n            all_edges.emplace_back(u, v, hypot(\n                cities[u].cx - cities[v].cx,\n                cities[u].cy - cities[v].cy\n            ));\n        }\n    }\n    \n    // Collect all cities and ensure they are connected\n    vector<int> remaining_cities;\n    for (auto& e : all_edges) remaining_cities.push_back(get<0>(e));\n    sort(remaining_cities.begin(), remaining_cities.end());\n    remaining_cities.erase(unique(remaining_cities.begin(), remaining_cities.end()), remaining_cities.end());\n    \n    // Assign leftovers\n    set<int> used(remaining_cities.begin(), remaining_cities.end());\n    for (auto& c : cities) if (!used.count(c.idx)) remaining_cities.push_back(c.idx);\n    \n    // Form final groups respecting exact group sizes\n    vector<vector<int>> ans_groups;\n    for (int i=0; i < M; ++i) {\n        if (i < groups.size()) {\n            ans_groups.push_back(groups[i]);\n        } else {\n            ans_groups.emplace_back();\n        }\n    }\n\n    int start = 0;\n    for (int sz : G) {\n        ans_groups.emplace_back(vector<int>(remaining_cities.begin() + start, remaining_cities.begin() + start + sz));\n        start += sz;\n    }\n\n    cout << \"!\" << endl;\n    for (auto& group : ans_groups) {\n        for (auto idx : group) cout << idx << \" \";\n        cout << endl;\n        sort(group.begin(), group.end());\n        for (size_t i=1; i < group.size(); ++i) {\n            cout << group[i-1] << \" \" << group[i] << endl;\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    solve();\n    \n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define INF (1LL << 60)\ntypedef long long ll;\ntypedef tree<pair<pair<int, int>, vector<pair<int, int>>>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> oset;\n\nstruct VecHash {\n    size_t operator()(const vector<pair<int, int>>& v) const {\n        size_t seed = 0;\n        for (auto x : v) {\n            seed ^= x.first + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            seed ^= x.second + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n        }\n        return seed;\n    }\n};\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dir[] = {'U', 'D', 'L', 'R'};\n\nvoid astar(vector<pair<int, int>>& goals) {\n    int startX = goals.front().first;\n    int startY = goals.front().second;\n    goals.erase(goals.begin());\n    \n    oset pq;\n    map<pair<pair<int, int>, vector<pair<int, int>>>, int, VecHash> dist;\n    pq.insert({{0, {startX, startY, goals}}, {}});\n    dist[{{startX, startY}, goals}] = 0;\n\n    auto get_priority = [&](int x, int y, const auto& path_rem) {\n        int h = 0;\n        if (!path_rem.empty()) {\n            int nx = path_rem[0].first, ny = path_rem[0].second;\n            h = max(abs(nx - x), abs(ny - y));\n        }\n        for (size_t i = 1; i < path_rem.size(); ++i) {\n            int px = path_rem[i-1].first, py = path_rem[i-1].second;\n            int cx = path_rem[i].first, cy = path_rem[i].second;\n            h += max(abs(cx - px), abs(cy - py));\n        }\n        return h + (int)path_rem.size();\n    };\n\n    while (!pq.empty()) {\n        auto current = pq.begin()->second;\n        pq.erase(pq.begin());\n        int x = current.first;\n        int y = current.second.first;\n        auto remaining = current.second.second;\n        \n        if (remaining.empty()) {\n            for (auto& move : dist[current.first]) {\n                cout << move.first << ' ' << move.second << '\\n';\n            }\n            exit(0);\n        }\n\n        int curr_dist = dist[current.first];\n        for (int d = 0; d < 4; ++d) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx < 0 || nx >= 20 || ny < 0 || ny >= 20) continue;\n\n            bool blocked = false;\n            vector<pair<int, int>> new_rem = remaining;\n            if (new_rem.size() > 0 && new_rem[0] == make_pair(nx, ny)) {\n                new_rem.erase(new_rem.begin());\n            }\n\n            string actions = \"MS\";\n            for (char action : actions) {\n                int tx = x, ty = y, steps = 1;\n                if (action == 'S') {\n                    while (tx + dx[d] >= 0 && tx + dx[d] < 20 && ty + dy[d] >= 0 && ty + dy[d] < 20 && \n                           (new_rem.empty() || make_pair(tx+dx[d], ty+dy[d]) != new_rem[0])) {\n                        tx += dx[d]; ty += dy[d]; ++steps;\n                    }\n                    if (new_rem.size() > 0 && make_pair(tx, ty) != new_rem[0]) continue;\n                    if (!new_rem.empty() && make_pair(tx, ty) == new_rem[0]) {\n                        vector<pair<int, int>> next_rem = new_rem;\n                        next_rem.erase(next_rem.begin());\n                        new_rem = next_rem;\n                    }\n                } else {\n                    tx = nx; ty = ny;\n                }\n                \n                if (dist.count({{tx, ty}, new_rem}) && dist[{{tx, ty}, new_rem}] <= curr_dist + 1) continue;\n\n                dist[{{tx, ty}, new_rem}] = curr_dist + 1;\n                int priority = curr_dist + get_priority(tx, ty, new_rem) + 1;\n                pq.insert({{priority, {tx, ty, new_rem}}, {action, dir[d]}});\n                \n                if (action == 'S') dist[{{tx, ty}, new_rem}].push_back({action, dir[d]});\n            }\n        }\n    }\n}\n\nint main() {\n    int N, M; cin >> N >> M;\n    vector<pair<int, int>> goals(M);\n    for (int i = 0; i < M; ++i) {\n        int x, y; cin >> x >> y;\n        goals[i] = {x, y};\n    }\n    astar(goals);\n    return 0;\n}"},"8":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int MAX = 10000;\n\nstruct Ad {\n    int x, y, area;\n};\n\nvector<vector<bool>> occupied(MAX, vector<bool>(MAX, false));\n\n// Check if (x,y,w,h) is valid and unoccupied\nbool can_place(int x, int y, int w, int h) {\n    if (x < 0 || y < 0 || x + w > MAX || y + h > MAX) return false;\n    for (int i = x; i < x + w; ++i)\n        for (int j = y; j < y + h; ++j)\n            if (occupied[i][j]) return false;\n    return true;\n}\n\n// Mark cells from (x,y) to (x+w-1, y+h-1) as occupied\nvoid mark(int x, int y, int w, int h) {\n    for (int i = x; i < x + w; ++i)\n        for (int j = y; j < y + h; ++j)\n            occupied[i][j] = true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n;\n    cin >> n;\n    vector<Ad> ads(n);\n    for (auto& ad : ads)\n        cin >> ad.x >> ad.y >> ad.area;\n\n    // Sort largest areas first\n    sort(ads.begin(), ads.end(), [](const Ad& a, const Ad& b){\n        return a.area > b.area;\n    });\n\n    // Precompute minimal dimensions for each ad\n    for (auto& ad : ads) {\n        int base_dim = static_cast<int>(sqrt(ad.area));\n        int width = 1, height = ad.area;\n        // Try to keep aspect ratio close to 1\n        while (width <= base_dim) {\n            if (width * height >= ad.area) break;\n            width++;\n            height = (ad.area + width - 1) / width;\n        }\n        \n        // Attempt to place near (x,y), checking all directions\n        bool placed = false;\n        for (int dx = -5; dx <= 5; ++dx) {\n            for (int dy = -5; dy <=5; ++dy) {\n                int nx = max(0, ad.x + dx);\n                int ny = max(0, ad.y + dy);\n                if (nx + width <= MAX && ny + height <= MAX && can_place(nx, ny, width, height)) {\n                    mark(nx, ny, width, height);\n                    cout << nx << ' ' << ny << ' ' << nx+width << ' ' << ny+height << '\\n';\n                    placed = true;\n                    break;\n                }\n                // Try swapping dimensions\n                if (nx + height <= MAX && ny + width <= MAX && can_place(nx, ny, height, width)) {\n                    mark(nx, ny, height, width);\n                    cout << nx << ' ' << ny << ' ' << nx+height << ' ' << ny+width << '\\n';\n                    placed = true;\n                    break;\n                }\n            }\n            if (placed) break;\n        }\n\n        // Fallback: if no valid position found, place minimal ad at desired point\n        if (!placed) {\n            int nx = ad.x, ny = ad.y;\n            // Try to move down/right until empty\n            while (!can_place(nx, ny, 1, 1)) {\n                nx++;\n                if (nx == MAX) {\n                    nx = 0;\n                    ny++;\n                    if (ny == MAX) ny = 0; // cycle if needed\n                }\n            }\n            mark(nx, ny, 1, 1);\n            cout << nx << ' ' << ny << ' ' << nx+1 << ' ' << ny+1 << '\\n';\n        }\n    }\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 50;\nint si, sj;\nint tiles[MAXN][MAXN];\nint points[MAXN][MAXN];\nvector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nstring best_path;\nint best_score = 0;\nchrono::steady_clock::time_point start_time;\n\nbool inside(int x, int y) {\n    return x >= 0 && x < MAXN && y >= 0 && y < MAXN;\n}\n\nvoid dfs(int x, int y, string path, int current_score, set<int> used_tiles, int depth_left) {\n    if (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() > 1900) \n        return;\n\n    if (depth_left == 0) {\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_path = path;\n        }\n        return;\n    }\n\n    vector<pair<int, int>> shuffled_dirs = dirs;\n    shuffle(shuffled_dirs.begin(), shuffled_dirs.end(), rng);\n\n    for (const auto& [dx, dy] : shuffled_dirs) {\n        int nx = x + dx, ny = y + dy;\n        if (!inside(nx, ny) || used_tiles.count(tiles[nx][ny]))\n            continue;\n\n        set<int> new_used = used_tiles;\n        new_used.insert(tiles[nx][ny]);\n        char dir = \"UDLR\"[find(dirs.begin(), dirs.end(), make_pair(dx, dy)) - dirs.begin()];\n        \n        dfs(nx, ny, path + string(1, dir), current_score + points[nx][ny], new_used, depth_left - 1);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> si >> sj;\n    start_time = chrono::steady_clock::now();\n\n    for (int i = 0; i < MAXN; ++i) \n        for (int j = 0; j < MAXN; ++j) \n            cin >> tiles[i][j];\n    for (int i = 0; i < MAXN; ++i) \n        for (int j = 0; j < MAXN; ++j) \n            cin >> points[i][j];\n\n    set<int> initial_used = {tiles[si][sj]};\n    int initial_depth = 4; // Start with a smaller depth and increment\n    while (true) {\n        dfs(si, sj, \"\", points[si][sj], initial_used, initial_depth);\n        if (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() > 1700) // leave buffer time\n            break;\n        initial_depth++;\n    }\n\n    cout << best_path << endl;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\nusing namespace std;\n\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dirs[] = {'U','D','L','R'};\n\nvoid solve() {\n    srand(time(nullptr));\n    for (int q = 0; q < 1000; ++q) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        string path;\n        vector<vector<bool>> visited(30, vector<bool>(30, false));\n        visited[si][sj] = true;\n\n        while (si != ti || sj != tj) {\n            vector<int> possible_moves;\n            for (int d = 0; d < 4; ++d) {\n                int ni = si + dr[d], nj = sj + dc[d];\n                if (ni >= 0 && ni < 30 && nj >= 0 && nj < 30 && !visited[ni][nj]) {\n                    possible_moves.push_back(d);\n                }\n            }\n            if (possible_moves.empty()) break;\n\n            // Always prefer deterministic progress if available\n            bool has_target_move = false;\n            int target_dir = -1;\n            for (int m : possible_moves) {\n                if ((m == 0 && si > ti) || (m == 1 && si < ti) || \n                    (m == 2 && sj > tj) || (m == 3 && sj < tj)) {\n                    target_dir = m;\n                    has_target_move = true;\n                    break;\n                }\n            }\n            \n            int move_dir;\n            if (has_target_move) {\n                move_dir = target_dir;\n            } else {\n                // Random valid move\n                move_dir = possible_moves[rand() % possible_moves.size()];\n            }\n\n            si += dr[move_dir];\n            sj += dc[move_dir];\n            visited[si][sj] = true;\n            path += dirs[move_dir];\n        }\n\n        cout << path << endl;\n        long long feedback;\n        cin >> feedback;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Entry {\n    char ch;\n    int freq;\n    bool operator<(const Entry& other) const {\n        return freq > other.freq || (freq == other.freq && ch < other.ch);\n    }\n};\n\nvector<string> solve(int N, vector<string>& S) {\n    vector<vector<map<char, int>>> freq(N, vector<map<char, int>>(N));\n\n    // Compute frequency of each char in possible subsequences\n    for (auto& s : S) {\n        int len = s.size();\n        for (int start = 0; start < N; ++start) {\n            for (int p = 0; p < len; ++p) {\n                // Horizontal (rows)\n                freq[start][(p % N)][s[p]]++;\n                // Vertical (cols)\n                freq[(p % N)][start][s[p]]++;\n            }\n        }\n    }\n\n    // Build initial matrix based on frequency\n    vector<string> mat(N, string(N, '.'));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            vector<Entry> entries;\n            for (char c = 'A'; c <= 'H'; ++c) {\n                entries.push_back({c, freq[i][j][c]});\n            }\n            sort(entries.begin(), entries.end());\n            mat[i][j] = entries[0].ch;\n        }\n    }\n\n    auto can_place = [&](int x, int y, const string& s, bool vert) {\n        for (size_t idx = 0; idx < s.size(); ++idx) {\n            int i = vert ? (x + idx) % N : x;\n            int j = vert ? y : (y + idx) % N;\n            if (mat[i][j] != '.' && mat[i][j] != s[idx]) return false;\n        }\n        return true;\n    };\n\n    auto place = [&](int x, int y, const string& s, bool vert) {\n        for (size_t idx = 0; idx < s.size(); ++idx) {\n            int i = vert ? (x + idx) % N : x;\n            int j = vert ? y : (y + idx) % N;\n            if (mat[i][j] == '.') mat[i][j] = s[idx];\n        }\n    };\n\n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(S.begin(), S.end(), gen);\n    sort(S.rbegin(), S.rend(), [](const string& a, const string& b) {\n        return a.size() > b.size();\n    });\n\n    for (auto& s : S) {\n        for (int t = 0; t < 1; ++t) {\n            bool placed = false;\n            for (int i = 0; i < N && !placed; ++i) {\n                for (int j = 0; j < N && !placed; ++j) {\n                    bool pick_vert = (t == 0 && gen() % 2) || (t == 1 && (gen() % 4 == 0));\n                    if (can_place(i, j, s, pick_vert)) {\n                        place(i, j, s, pick_vert);\n                        placed = true;\n                    } else if (can_place(i, j, s, !pick_vert)) {\n                        place(i, j, s, !pick_vert);\n                        placed = true;\n                    }\n                }\n            }\n        }\n    }\n\n    // Post-processing to fill empty spots intelligently\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (mat[i][j] != '.') continue;\n            set<char> valid;\n            for (char c = 'A'; c <= 'H'; ++c) {\n                bool valid_horiz = true, valid_vert = true;\n                for (int k = 0; k < 1; ++k) {\n                    int ni = (i + k) % N;\n                    int nj = (j + k) % N;\n                    if (nj < N-1 && mat[ni][nj+1] != '.' && mat[ni][nj+1] != c) valid_horiz = false;\n                    if (ni < N-1 && mat[ni+1][nj] != '.' && mat[ni+1][nj] != c) valid_vert = false;\n                }\n                if (valid_horiz || valid_vert) valid.insert(c);\n            }\n            mat[i][j] = valid.empty() ? 'A' : *valid.begin();\n        }\n    }\n    \n    return mat;\n}\n\nint main() {\n    int N = 20, M;\n    cin >> N >> M;\n    vector<string> S(M);\n    for (auto& s : S) cin >> s;\n    vector<string> ans = solve(N, S);\n    \n    for (auto& row : ans) cout << row << endl;\n    return 0;\n}","ahc005":"#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <queue>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nvector<pair<char, int>> find_segment(int sx, int sy, int tx, int ty, const vector<string>& grid) {\n    int N = grid.size();\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    char dir[] = {'D', 'U', 'L', 'R'};\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> parent(N * N, {-1, -1});\n    q.emplace(sx, sy);\n    visited[sx][sy] = true;\n\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n        if (x == tx && y == ty) break;\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 && !visited[nx][ny] && grid[nx][ny] != '#') {\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n                parent[nx * N + ny] = {x, y};\n            }\n        }\n    }\n\n    vector<pair<char, int>> steps;\n    if (!visited[tx][ty]) return {};\n    int x = tx, y = ty;\n    while (x != sx || y != sy) {\n        auto [px, py] = parent[x * N + y];\n        char move;\n        if (px == x-1) move = 'D';\n        else if (px == x+1) move = 'U';\n        else if (py == y-1) move = 'R';\n        else move = 'L';\n        steps.emplace_back(move, 1);\n        x = px; y = py;\n    }\n    reverse(steps.begin(), steps.end());\n    return steps;\n}\n\nstring compute_optimal_route(int N, int si, int sj, const vector<string>& grid) {\n    vector<bool> covered_row(N, false), covered_col(N, false);\n    vector<pair<int, int>> path = {{si, sj}};\n    vector<pair<char, int>> moves;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                covered_row[i] = true;\n                covered_col[j] = true;\n            }\n        }\n    }\n\n    auto add_segment = [&](int x, int y) {\n        if (path.empty()) return;\n        auto segment = find_segment(path.back().first, path.back().second, x, y, grid);\n        if (segment.empty()) return;\n        moves.insert(moves.end(), segment.begin(), segment.end());\n        path.emplace_back(x, y);\n    };\n\n    int x = si, y = sj;\n    for (int row : {si-1, si+1}) {\n        if (row >= 0 && row < N && covered_row[row] && !covered_col[sj])\n            add_segment(row, sj);\n    }\n    for (int col : {sj-1, sj+1}) {\n        if (col >= 0 && col < N && covered_col[col] && !covered_row[si])\n            add_segment(si, col);\n    }\n\n    if (!moves.empty()) {\n        x = path.back().first;\n        y = path.back().second;\n    }\n    for (int i = 0; i < N; ++i) {\n        if (covered_row[i])\n            add_segment(i, y);\n    }\n    for (int j = 0; j < N; ++j) {\n        if (covered_col[j])\n            add_segment(x, j);\n    }\n    add_segment(si, sj);\n\n    string result;\n    for (auto [m, cnt] : moves) {\n        result += string(cnt, m);\n    }\n    return result;\n}\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (auto& s : grid) cin >> s;\n\n    cout << compute_optimal_route(N, si, sj, grid) << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconstexpr int INF = 1e9;\n\nstruct Task {\n    vector<int> skills;\n    vector<int> children;\n    int done_day = -1;\n    int indeg = 0;\n    bool started = false;\n};\n\nint N = 1000, M = 20;\nvector<Task> tasks;\nvector<vector<int>> finished_tasks; // finished_tasks[member] = list of tasks\nvector<array<int, 1024>> skill_estimates(M, array<int, 1024>{});\n\nvoid print_flush(const vector<pair<int, int>>& assignments) {\n    if (assignments.empty()) {\n        cout << \"0\\n\";\n    } else {\n        cout << assignments.size();\n        for (auto& [a, b] : assignments) cout << ' ' << a+1 << ' ' << b+1;\n        cout << '\\n';\n    }\n    fflush(stdout);\n}\n\nint estimate_time(int member, int task_id) {\n    int sum_excess = 0;\n    for (size_t k = 0; k < tasks[task_id].skills.size(); ++k) {\n        int req = tasks[task_id].skills[k];\n        int est = skill_estimates[member][k];\n        if (req > est) sum_excess += req - est;\n    }\n    return sum_excess == 0 ? 1 : max(1, sum_excess - 3 + (rand() % 7));\n}\n\nvoid update_skills(int member, int task_id, int days) {\n    auto& skills = skill_estimates[member];\n    int excess = max(1, days - 3 + (rand() % 7)) - 1;\n    for (size_t k = 0; k < tasks[task_id].skills.size(); ++k) {\n        int req = tasks[task_id].skills[k];\n        if (req > skills[k]) skills[k] = min(req, skills[k] + excess);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int K, R;\n    cin >> N >> M >> K >> R;\n    tasks.resize(N);\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            int d;\n            cin >> d;\n            tasks[i].skills.push_back(d);\n        }\n    }\n    \n    vector<vector<int>> deps(N);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        deps[u].push_back(v);\n        tasks[v].indeg++;\n    }\n    \n    priority_queue<pair<int, int>> pq; // (completion day estimate, task_id)\n    for (int i = 0; i < N; ++i) if (tasks[i].indeg == 0) pq.emplace(0, i);\n    \n    vector<bool> member_busy(M, false);\n    \n    int day = 1;\n    while (day <= 2000) {\n        vector<pair<int, int>> assignments;\n        for (int m = 0; m < M && !pq.empty(); ++m) {\n            while (!pq.empty() && tasks[pq.top().second].started) pq.pop();\n            if (pq.empty()) break;\n            int t = pq.top().second;\n            pq.pop();\n            \n            assignments.emplace_back(m, t);\n            tasks[t].started = true;\n        }\n        \n        print_flush(assignments);\n        \n        string input;\n        getline(cin >> ws, input);\n        if (input == \"-1\") break;\n        \n        istringstream iss(input);\n        int n;\n        iss >> n;\n        for (int _ = 0; _ < n; ++_) {\n            int m;\n            iss >> m;\n            --m;\n            \n            if (!member_busy[m]) {\n                int task = finished_tasks[m].back();\n                finished_tasks[m].pop_back();\n                tasks[task].done_day = day;\n                \n                int days_taken = day - tasks[task].started_day;\n                update_skills(m, task, days_taken);\n                \n                for (int child : deps[task]) {\n                    --tasks[child].indeg;\n                    if (tasks[child].indeg == 0) {\n                        pq.emplace(-estimate_time(m, child), child);\n                    }\n                }\n            }\n        }\n        \n        for (auto& [m, t] : assignments) {\n            if (!tasks[t].started) finished_tasks[m].push_back(t);\n            member_busy[m] = !tasks[t].started;\n            tasks[t].started_day = day;\n        }\n        \n        day++;\n    }\n    \n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Order {\n    int a, b, c, d;\n};\n\nvector<pair<int,int>> best_path;\nvector<int> chosen;\n\nint dist(int x1, int y1, int x2, int y2) {\n    return abs(x1-x2) + abs(y1-y2);\n}\n\nvector<pair<int, int>> construct_route() {\n    vector<pair<int, int>> path{{400, 400}};\n    for (int i : chosen) {\n        int a = orders[i].a, b = orders[i].b;\n        int c = orders[i].c, d = orders[i].d;\n        \n        int mn_cost = INT_MAX, best_pos = 0;\n        for (int j = 0; j < (int)path.size(); ++j) {\n            vector<pair<int, int>> tmp_path = path;\n            tmp_path.insert(tmp_path.begin() + j + 1, {{a, b}, {c, d}});\n            \n            ll cost = 0;\n            for (int k = 1; k < (int)tmp_path.size(); ++k) {\n                cost += dist(tmp_path[k-1].first, tmp_path[k-1].second, tmp_path[k].first, tmp_path[k].second);\n            }\n            if (cost < mn_cost) {\n                mn_cost = cost;\n                best_pos = j + 1;\n            }\n        }\n        path.insert(path.begin() + best_pos, {{a, b}, {c, d}});\n    }\n    path.push_back({400, 400});\n    return path;\n}\n\nint main() {\n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; ++i) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n    }\n    \n    // Score heuristic: prioritize close orders\n    auto cmp = [&](int lhs, int rhs) {\n        int dist1 = dist(400, 400, orders[lhs].a, orders[lhs].b) \n                  + dist(orders[lhs].c, orders[lhs].d, 400, 400);\n        int dist2 = dist(400, 400, orders[rhs].a, orders[rhs].b)\n                  + dist(orders[rhs].c, orders[rhs].d, 400, 400);\n        return dist1 < dist2;\n    };\n    \n    // Initialize with heuristic\n    vector<int> ids(1000); iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(), cmp);\n    \n    vector<int> current_orders;\n    ll current_cost = 0;\n    priority_queue<pair<ll, int>> pq;\n    \n    for (int i = 0; i < 1000; ++i) {\n        pq.emplace(-dist(400, 400, orders[ids[i]].a, orders[ids[i]].b) \n                     - dist(orders[ids[i]].c, orders[ids[i]].d, 400, 400),\n                   ids[i]);\n    }\n    \n    while (chosen.size() < 50) {\n        auto [cost, id] = pq.top(); pq.pop();\n        chosen.push_back(id);\n        \n        best_path = construct_route();\n        ll total_cost = 0;\n        for (int i = 1; i < (int)best_path.size(); ++i) {\n            total_cost += dist(best_path[i-1].first, best_path[i-1].second,\n                               best_path[i].first, best_path[i].second);\n        }\n        current_cost = total_cost;\n    }\n    \n    cout << chosen.size();\n    for (auto id : chosen) cout << \" \" << id + 1;\n    cout << \"\\n\";\n    cout << best_path.size();\n    for (auto &[x, y] : best_path) cout << \" \" << x << \" \" << y;\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge {\n    int u, v, d, cost, idx;\n    bool operator<(const Edge& o) const { return idx < o.idx; }\n};\n\nstruct DSU {\n    vector<int> p;\n    DSU(int n) : p(n, -1) {}\n    int find(int u) { return p[u] < 0 ? u : p[u] = find(p[u]); }\n    bool unite(int u, int v) {\n        u = find(u), v = find(v);\n        if (u == v) return false;\n        if (p[u] > p[v]) swap(u, v);\n        p[u] += p[v];\n        p[v] = u;\n        return true;\n    }\n    int components() const {\n        int c = 0;\n        for (int x : p) if (x < 0) ++c;\n        return c;\n    }\n};\n\nint dist(pair<int,int> a, pair<int,int> b) {\n    int dx = a.first - b.first, dy = a.second - b.second;\n    return ::round(sqrt(dx*dx + dy*dy));\n}\n\nint main() {\n    const int N = 400, M = 1995;\n    vector<pair<int,int>> coords(N);\n    for (int i = 0; i < N; ++i) scanf(\"%d %d\", &coords[i].first, &coords[i].second);\n    \n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        scanf(\"%d %d\", &edges[i].u, &edges[i].v);\n        edges[i].d = dist(coords[edges[i].u], coords[edges[i].v]);\n        edges[i].idx = i;\n    }\n\n    DSU dsu(N);\n    vector<int> seen(M, false);\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int i, int j) {\n        return max(edges[i].d, 3*edges[i].d) < max(edges[j].d, 3*edges[j].d);\n    });\n\n    for (int i = 0; i < M; ++i) {\n        scanf(\"%d\", &edges[i].cost);\n        auto& e = edges[i];\n\n        bool accept = (dsu.find(e.u) != dsu.find(e.v));\n        seen[e.idx] = true;\n\n        if (!accept) {\n            int remain = M - 1 - i; // Edges left\n            int current = dsu.components();\n            double factor = 1.5 + 0.7 * (double)(current - 1) / (N - 1); // Tighten as we connect more components\n            if (remain > current - 1) {\n                // Look at next candidate edge (minimum possible cost)\n                int next_best = N * 10; // Default high if nothing is found\n                for (int j = 0; j < M; ++j) {\n                    if (!seen[j] && dsu.find(edges[j].u) != dsu.find(edges[j].v)) {\n                        next_best = min(next_best, edges[j].d);\n                    }\n                }\n                if (e.cost <= factor * next_best) accept = true;\n            }\n        }\n\n        printf(\"%d\\n\", accept ? 1 : 0);\n        fflush(stdout);\n\n        if (accept) dsu.unite(e.u, e.v);\n\n        if (dsu.components() == 1) {\n            // If already connected, reject all remaining edges to save time\n            for (++i; i < M; ++i) {\n                scanf(\"%d\", &edges[i].cost);\n                printf(\"0\\n\");\n                fflush(stdout);\n            }\n            break;\n        }\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\nusing Point = pair<int, int>;\nconst int MAX_TURNS = 300;\nconst int GRID_SIZE = 30;\n\nchar dirs[] = {'u','d','l','r','U','D','L','R'};\nint dx[] = {-1,1,0,0,-1,1,0,0};\nint dy[] = {0,0,-1,1,0,0,-1,1};\n\nvector<Point> humans;\nvector<pair<Point, int>> pets;\nvector<string> grid(GRID_SIZE+1, string(GRID_SIZE+1, '.'));\n\nbool isValid(int x, int y) {\n    return x >= 1 && x <= GRID_SIZE && y >= 1 && y <= GRID_SIZE;\n}\n\nbool hasAdjacentPet(int x, int y) {\n    for (int d = 0; d < 4; ++d) {\n        int nx = x + dx[d], ny = y + dy[d];\n        if (isValid(nx, ny) && grid[nx][ny] == '#') {\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid updateBarriers(string actions) {\n    set<Point> blocks;\n    for (int i = 0; i < (int)actions.size(); ++i) {\n        char c = actions[i];\n        if (c == '.' || isupper(c)) continue;\n        int d = find(dirs, dirs+8, c) - dirs;\n        int x = humans[i].first + dx[d], y = humans[i].second + dy[d];\n        if (isValid(x, y) && grid[x][y] == '.') {\n            grid[x][y] = '#';\n        }\n    }\n}\n\nstring decideActions() {\n    string result(humans.size(), '.');\n    \n    // Attempt to move to outer corners first\n    for (int i = 0; i < (int)humans.size(); ++i) {\n        int x = humans[i].first, y = humans[i].second;\n        for (char c : {'U','D','L','R'}) {\n            int d = find(dirs, dirs+8, c) - dirs;\n            int nx = x + dx[d], ny = y + dy[d];\n            if (isValid(nx, ny) && grid[nx][ny] == '.') {\n                result[i] = c;\n                break;\n            }\n        }\n        if (result[i] != '.') continue;\n        // Next try to block\n        for (char c : {'u','d','l','r'}) {\n            int d = find(dirs, dirs+4, c) - dirs;\n            int nx = x + dx[d], ny = y + dy[d];\n            if (isValid(nx, ny) && grid[nx][ny] == '.' && !hasAdjacentPet(nx,ny)) {\n                result[i] = c;\n                break;\n            }\n        }\n    }\n    return result;\n}\n\n// Update human positions\nvoid executeActions(const string& actions) {\n    for (int i = 0; i < (int)actions.size(); ++i) {\n        char act = actions[i];\n        if (islower(act)) continue; // Only move if uppercase\n        int d = find(dirs+4, dirs+8, act) - (dirs+4);\n        int x = humans[i].first + dx[d+4], y = humans[i].second + dy[d+4];\n        if (isValid(x,y) && grid[x][y] == '.') {\n            humans[i] = {x, y};\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read pets\n    int N; cin >> N;\n    for (int i = 0; i < N; ++i) {\n        int x, y, t; \n        cin >> x >> y >> t;\n        pets.push_back({{x,y}, t});\n        grid[x][y] = 'O'; // Mark with a temp char for pets\n    }\n    \n    // Read humans\n    int M; cin >> M;\n    humans.resize(M);\n    for (auto& [x, y] : humans) {\n        cin >> x >> y;\n    }\n    \n    // Clear pet markings for actual use\n    for (auto& [p, t] : pets) {\n        grid[p.first][p.second] = '.';\n    }\n    \n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        string actions = decideActions();\n        cout << actions << endl;\n        \n        // Read dummy pet movements; actual movements not tracked here\n        for (int i = 0; i < N; ++i) {\n            string _;\n            cin >> _;\n        }\n        \n        executeActions(actions);\n        updateBarriers(actions);\n    }\n    \n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    string path;\n    int remain_downs = ti - si;\n    int remain_rights = tj - sj;\n\n    // Generate necessary moves first\n    auto add_moves = [&](int count, char move) {\n        for (int i = 0; i < count; ++i) {\n            path += move;\n            // Add redundancy in the same direction to maximize chances\n            path += move;\n            if (path.size() >= 200) break;\n        }\n    };\n\n    // Ensure each step in the right direction is added at least twice\n    while (remain_downs > 0 || remain_rights > 0) {\n        if (remain_downs > 0) {\n            path += \"DD\";\n            remain_downs--;\n        }\n        if (remain_rights > 0) {\n            path += \"RR\";\n            remain_rights--;\n        }\n    }\n\n    // If needed, pad with more down and right moves\n    while (path.size() < 200) {\n        path += \"D\";\n        if (path.size() < 200) path += \"R\";\n    }\n\n    cout << path.substr(0, 200) << endl;\n}","ahc010":"#include <bits/stdc++.h>\n#include <random>\nusing namespace std;\n\nconst int N = 30;\nint T[N][N], R[N][N], bestR[N][N];\nint dirs[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1},\n};\nint di[4] = {0, -1, 0, 1}, dj[4] = {-1, 0, 1, 0};\n\nmt19937 mt(time(nullptr));\n\nlong long eval(int rotate[N][N]) {\n    int tcopy[N][N];\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        tcopy[i][j] = rotate[i][j];\n        while (tcopy[i][j] < 0) tcopy[i][j] += 8;\n        tcopy[i][j] %= 8;\n    }\n\n    vector<int> lengths;\n    bool vis[N][N][4] = {};\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        for (int d=0; d<4; ++d) {\n            if (vis[i][j][d]) continue;\n            vector<tuple<int, int, int>> path;\n            int ci=i, cj=j, cd=d, len=0;\n            while (true) {\n                path.emplace_back(ci, cj, cd);\n                vis[ci][cj][cd] = true;\n                int nd = dirs[tcopy[ci][cj]][cd];\n                if (nd == -1) break;\n                ci += di[nd];\n                cj += dj[nd];\n                if (ci < 0 || ci >= N || cj < 0 || cj >= N) break;\n                cd = (nd + 2) % 4;\n                if (vis[ci][cj][cd]) {\n                    for (auto [pi, pj, pd] : path) {\n                        if (pi == ci && pj == cj && pd == cd) {\n                            len = path.size() - (path.end() - find(path.begin(), path.end(), make_tuple(pi, pj, pd)));\n                            break;\n                        }\n                    }\n                    break;\n                }\n            }\n            if (len > 0) {\n                lengths.push_back(len);\n                for (auto& [pi, pj, pd] : path) vis[pi][pj][pd] = true;\n            }\n        }\n    }\n    sort(lengths.rbegin(), lengths.rend());\n    long long l1 = (lengths.size() > 0) ? lengths[0] : 0;\n    long long l2 = (lengths.size() > 1) ? lengths[1] : 0;\n    return l1 * l2;\n}\n\nlong long calc() {\n    static int rotate[N][N];\n    memcpy(rotate, R, sizeof(rotate));\n    long long ans = 0;\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        long long best = 0;\n        for (int k=0; k<4; ++k) {\n            rotate[i][j] = (rotate[i][j] + 1) % 8;\n            long long score = eval(rotate);\n            if (score > best) best = score;\n        }\n        rotate[i][j] = (rotate[i][j] - best + 8) % 8;\n        ans += best;\n    }\n    return ans;\n}\n\nint main() {\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        char c; cin >> c;\n        T[i][j] = c - '0';\n    }\n    memcpy(R, T, sizeof(R));\n\n    auto update_ans = [&]() {\n        long long cur_score = eval(bestR);\n        long long score = eval(R);\n        if (score > cur_score) memcpy(bestR, R, sizeof(bestR));\n    };\n\n    const double START_TEMP = 1e6, END_TEMP = 1e-3, RATE = 0.9999;\n    double temp = START_TEMP;\n    long long cur_score = eval(R), best_score = cur_score;\n    while (temp > END_TEMP) {\n        for (int _=0; _<max(1, N*N * temp / START_TEMP); ++_) {\n            int i = mt() % N, j = mt() % N;\n            int prev = R[i][j];\n\n            long long best_rotate = -1;\n            long long best_gain = -1e18;\n            vector<long long> scores(4);\n            for (int delta=0; delta<4; ++delta) {\n                R[i][j] = (prev + delta) % 8;\n                scores[delta] = eval(R);\n                if (scores[delta] - cur_score > best_gain) {\n                    best_gain = scores[delta] - cur_score;\n                    best_rotate = delta;\n                }\n            }\n\n            if (best_rotate == -1 || exp((scores[best_rotate] - cur_score) / temp) < (mt() % 10000)/10000.) {\n                int rnd = mt() % 4;\n                if (scores[rnd] <= cur_score && exp((scores[rnd] - cur_score) / temp) < (mt() % 10000)/10000.) {\n                    R[i][j] = prev;\n                    continue;\n                }\n                best_rotate = rnd;\n            }\n\n            R[i][j] = (prev + best_rotate) % 8;\n            cur_score = scores[best_rotate];\n            update_ans();\n        }\n        best_score = max(best_score, cur_score);\n        temp *= RATE;\n    }\n\n    memcpy(R, bestR, sizeof(R));\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        int diff = 0;\n        while ((bestR[i][j] - T[i][j] - diff) % 8 != 0 && (bestR[i][j] - T[i][j] - diff) % 8 != 4) ++diff;\n        while (diff < 0) diff += 8;\n        cout << diff % 4;\n    }\n    cout << endl;\n}","ahc011":"#include <algorithm>\n#include <cstdio>\n#include <queue>\n#include <string>\n#include <vector>\nusing namespace std;\n\nint n, t_limit;\nvector<vector<int>> board;\npair<int, int> empty_cell;\nconst int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};\n\nbool in_bounds(int x, int y) { return 0 <= x && x < n && 0 <= y && y < n; }\n\nint count_connections(int x, int y) {\n    int mask = board[x][y];\n    int count = 0;\n    int dirs[] = {8, 1, 2, 4}; // Down, left, up, right connection checks\n    for (int i=0; i<4; ++i) {\n        int nx = x + dx[i], ny = y + dy[i];\n        if (in_bounds(nx, ny) && board[nx][ny] && (board[nx][ny] & (1 << 3-i))) {\n            ++count;\n        }\n    }\n    return count;\n}\n\nbool can_fit(int x, int y) {\n    int mask = board[x][y];\n    int required = __builtin_popcount(mask);\n    int current = count_connections(x, y);\n    return required - 1 == current;\n}\n\npair<int, int> find_valid_move() {\n    int best = -1e9, best_x = -1, best_y = -1;\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (board[i][j] == 0) continue;\n            int edges = __builtin_popcount(board[i][j]);\n            int current = edges ? count_connections(i, j) : -1;\n            int gain = edges - 1 - current;\n            if (gain > best) {\n                best = gain;\n                best_x = i; best_y = j;\n            }\n        }\n    }\n    return {best_x, best_y};\n}\n\npair<string, bool> shortest_path_to_empty(int sx, int sy) {\n    queue<pair<pair<int, int>, string>> q;\n    vector<vector<bool>> visited(n, vector<bool>(n, false));\n    q.push({{sx, sy}, \"\"});\n    visited[sx][sy] = true;\n    \n    while (!q.empty()) {\n        auto [pos, path] = q.front();\n        q.pop();\n        int x = pos.first, y = pos.second;\n        \n        if (board[x][y] == 0) // Found empty cell\n            return {path, true};\n        \n        for (int i=0; i<4; ++i) {\n            int nx = x + dx[i], ny = y + dy[i];\n            if (in_bounds(nx, ny) && !visited[nx][ny] && board[nx][ny] != 0) {\n                visited[nx][ny] = true;\n                char move = \"D\"[i]; // D=down, L, U, R = left, up, right\n                if (move == 'L') move = 'R';\n                else if (move == 'R') move = 'L';\n                q.push({{nx, ny}, path + move});\n            }\n        }\n    }\n    return {\"\", false};\n}\n\nvoid execute_moves(string path, int& ex, int& ey) {\n    for (char c : path) {\n        switch (c) {\n            case 'U': swap(board[ex][ey], board[ex-1][ey]); --ex; break;\n            case 'D': swap(board[ex][ey], board[ex+1][ey]); ++ex; break;\n            case 'L': swap(board[ex][ey], board[ex][ey-1]); --ey; break;\n            case 'R': swap(board[ex][ey], board[ex][ey+1]); ++ey; break;\n        }\n    }\n}\n\nint main() {\n    scanf(\"%d %d\", &n, &t_limit);\n    board.resize(n, vector<int>(n));\n    for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) {\n        char c;\n        scanf(\" %c\", &c);\n        board[i][j] = isdigit(c) ? c - '0' : c - 'a' + 10;\n        if (!board[i][j]) empty_cell = {i, j};\n    }\n    \n    string operations;\n    int steps = 0;\n    while (steps < t_limit) {\n        auto [x, y] = find_valid_move();\n        if (x == -1 || can_fit(x, y)) break;\n        \n        auto [dir, found] = shortest_path_to_empty(x, y);\n        if (!found) break;\n        reverse(dir.begin(), dir.end());\n        execute_moves(dir, empty_cell.first, empty_cell.second);\n        operations += dir;\n        steps += dir.size();\n    }\n    \n    printf(\"%s\\n\", operations.c_str());\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int offset = 20000;\n    int step = 2000; // Smaller step for finer partitioning\n    vector<array<int, 4>> lines;\n\n    // More frequent vertical lines within a contained range\n    for (int x = -offset; x <= offset; x += step) {\n        if (x != 0) lines.emplace_back(array{x, -offset, x, offset});\n    }\n    // More frequent horizontal lines\n    for (int y = -offset; y <= offset; y += step) {\n        if (y != 0) lines.emplace_back(array{-offset, y, offset, y});\n    }\n\n    // Essential diagonals\n    lines.emplace_back(array{-offset, -offset, offset, offset});\n    lines.emplace_back(array{-offset,  offset, offset, -offset});\n    lines.emplace_back(array{-offset, 0, offset, 0});\n    lines.emplace_back(array{0, -offset, 0, offset});\n    \n    // Additional diagonals for better coverage\n    for (int k = 1; k <= 8; ++k) {\n        lines.emplace_back(array{-offset + 200*k, -offset, offset - 200*k, offset});\n        lines.emplace_back(array{-offset + 200*k, offset, offset - 200*k, -offset});\n    }\n\n    cout << lines.size() << '\\n';\n    for (auto& line : lines) {\n        cout << line[0] << ' ' << line[1] << ' ' << line[2] << ' ' << line[3] << '\\n';\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nusing ll = long long;\nvector<vector<bool>> visited;\nvector<tuple<int, int, int, int, int, int, int, int>> ops;\n\nbool valid(int x, int y) {\n    return 0 <= x && x < N && 0 <= y && y < N && !visited[x][y];\n}\n\n// Directions: right, down, diagonal (both 45 degrees)\nint dx[] = {1, 0, 1, -1};\nint dy[] = {0, 1, 1, 1};\n\nint main() {\n    cin >> N >> M;\n    visited.assign(N, vector<bool>(N, false));\n    vector<pair<int, int>> initials;\n\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        initials.emplace_back(x, y);\n        visited[x][y] = true;\n    }\n\n    for (auto &[x, y] : initials) {\n        // For each initial dot, check possible rectangles\n        for (int d = 0; d < 4; ++d) {\n            for (int len = 1; len <= min(N, 3); ++len) {\n                int nx = x + dx[d] * len;\n                int ny = y + dy[d] * len;\n                if (!valid(nx, ny)) continue;\n\n                int nx2 = x + (d < 2 ? dx[d^1] : dx[(d+2)%4]) * len;\n                int ny2 = y + (d < 2 ? dy[d^1] : dy[(d+2)%4]) * len;\n                int ox = x + (d < 2 ? dx[d] : dx[(d+1)%4]);\n                int oy = y + (d < 2 ? dy[d] : dy[(d+1)%4]);\n\n                if (!valid(nx2, ny2) || !visited[ox][oy] || (!visited[nx][ny] && !visited[nx2][ny2]))\n                    continue;\n\n                // Check edges for no existing points except at vertices\n                bool ok = true;\n                // Check edge between (x,y) and (ox, oy):\n                for (int i=1; i < len; ++i) {\n                    int mx = x + dx[d]*i, my = y + dy[d]*i;\n                    if (visited[mx][my]) { ok = false; break; }\n                }\n                if (!ok) continue;\n\n                // Check between (nx, ny) to (nx2, ny2), but not needed if !visited[nx][ny], ok\n                if (!visited[nx2][ny2]) ok = false; // Must be existing for third point if nx,ny is new\n\n                if (ok) {\n                    visited[nx][ny] = true;\n                    ops.emplace_back(nx, ny, x, y, ox, oy, nx2, ny2);\n                    // Only once for each new point added\n                    break;\n                }\n            }\n        }\n    }\n\n    cout << ops.size() << endl;\n    for (auto &[x, y, x2, y2, x3, y3, x4, y4] : ops) {\n        // Output order is (new point, other three forming the rectangle)\n        cout << x << ' ' << y << ' ' \n             << x2 << ' ' << y2 << ' ' \n             << x3 << ' ' << y3 << ' ' \n             << x4 << ' ' << y4 << endl;\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int SIZE = 10;\nvector<vector<int>> grid(SIZE, vector<int>(SIZE, 0));\nvector<pair<int, int>> emptyCells;\nunordered_map<int, int> flavorCount = {{1,0}, {2,0}, {3,0}};\nunordered_map<int, pair<int, int>> centroids; // flavor -> centroid (sum_x, sum_y)\n\nvoid updateCenterMass(int flavor, int x, int y) {\n    flavorCount[flavor]++;\n    centroids[flavor].first += x;\n    centroids[flavor].second += y;\n}\n\nvoid applyGravity(char dir) {\n    if (dir == 'F') {\n        for (int col = 0; col < SIZE; ++col) {\n            for (int row = SIZE-2; row >= 0; --row) {\n                if (grid[row][col] && !grid[row+1][col]) {\n                    int r = row+1;\n                    while (r < SIZE && !grid[r][col]) r++;\n                    --r;\n                    swap(grid[r][col], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'B') {\n        // B direction logic\n        for (int col = 0; col < SIZE; ++col) {\n            for (int row = 1; row < SIZE; ++row) {\n                if (grid[row][col] && !grid[row-1][col]) {\n                    int r = row-1;\n                    while (r >= 0 && !grid[r][col]) r--;\n                    ++r;\n                    swap(grid[r][col], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'L') {\n        // L direction logic\n        for (int row = 0; row < SIZE; ++row) {\n            for (int col = 1; col < SIZE; ++col) {\n                if (grid[row][col] && !grid[row][col-1]) {\n                    int c = col-1;\n                    while (c >= 0 && !grid[row][c]) c--;\n                    ++c;\n                    swap(grid[row][c], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'R') {\n        // R direction logic\n        for (int row = 0; row < SIZE; ++row) {\n            for (int col = SIZE-2; col >= 0; --col) {\n                if (grid[row][col] && !grid[row][col+1]) {\n                    int c = col+1;\n                    while (c < SIZE && !grid[row][c]) c++;\n                    --c;\n                    swap(grid[row][c], grid[row][col]);\n                }\n            }\n        }\n    }\n}\n\nchar chooseDirection(int flavor, int x, int y) {\n    pair<int, int> bestDir = {0, 0};\n    int currentScore = 1e9;\n    for (auto& [dx, dy] : {pair{-1,0}, {1,0}, {0,-1}, {0,1}}) {\n        int nx = x + dx*(SIZE-1), ny = y + dy*(SIZE-1);\n        if (flavorCount[flavor] == 0) {\n            if (abs(nx) + abs(ny) < currentScore) {\n                currentScore = abs(nx) + abs(ny);\n                bestDir = {dx, dy};\n            }\n        } else {\n            auto cm = centroids[flavor];\n            int cx = cm.first / flavorCount[flavor];\n            int cy = cm.second / flavorCount[flavor];\n            int newScore = abs(nx - cx) + abs(ny - cy);\n            if (newScore < currentScore) {\n                currentScore = newScore;\n                bestDir = {dx, dy};\n            }\n        }\n    }\n    return bestDir == make_pair(-1, 0) ? 'F' : \n           bestDir == make_pair(1, 0) ? 'B' : \n           bestDir == make_pair(0, -1) ? 'L' : 'R';\n}\n\nint main() {\n    vector<int> flavors(100);\n    for (int& f : flavors) cin >> f;\n    \n    for (int t = 0; t < 100; ++t) {\n        emptyCells.clear();\n        for (int i = 0; i < SIZE; ++i)\n            for (int j = 0; j < SIZE; ++j)\n                if (!grid[i][j])\n                    emptyCells.emplace_back(i, j);\n        \n        int p; cin >> p;\n        --p;\n        auto [x, y] = emptyCells[p];\n        int f = flavors[t];\n        grid[x][y] = f;\n        updateCenterMass(f, x, y);\n\n        if (t == 99) break;\n        \n        char dir = chooseDirection(f, x, y);\n        cout << dir << '\\n';\n        cout.flush();\n        applyGravity(dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nstring generate_graph(int vertices, int edges) {\n    vector<bool> visited(vertices * (vertices-1) / 2, false);\n    string result(vertices * (vertices-1) / 2, '0');\n    \n    int current = 0;\n    for (int j=1; j<=edges; ++j) {\n        if (current >= visited.size()) current = 0; // Fallback to start if out\n        while (result[current] == '1' || visited[current]) {\n            ++current;\n            if (current >= visited.size()) current = 0;\n        }\n        result[current] = '1';\n        visited[current] = true;\n    }\n    return result;\n}\n\nint main() {\n    int M;\n    double eps;\n    cin >> M >> eps;\n    \n    const int N = 20;\n    cout << N << endl;\n    \n    vector<string> precomputed(M);\n    for (int i=0; i < M; ++i) {\n        precomputed[i] = generate_graph(N, i);\n        cout << precomputed[i] << endl;\n    }\n    cout << flush;\n    \n    // Precompute edge counts for faster lookup\n    vector<int> edges_counts(M);\n    for (int i=0; i < M; ++i) {\n        edges_counts[i] = count(precomputed[i].begin(), precomputed[i].end(), '1');\n    }\n    \n    for (int k=0; k < 100; ++k) {\n        string H;\n        cin >> H;\n        int current_edges = count(H.begin(), H.end(), '1');\n        \n        // Match using edge count distance\n        int best_match = 0;\n        int min_diff = INT_MAX;\n        for (int m=0; m < M; ++m) {\n            int diff = abs(current_edges - edges_counts[m]);\n            if (diff < min_diff) {\n                min_diff = diff;\n                best_match = m;\n            }\n        }\n        cout << best_match << endl << flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing i32 = int;\nusing i64 = long long;\nusing vi = vector<i32>;\nusing pii = pair<i32, i32>;\nusing Graph = vector<vector<pii>>;\nconst i64 INF = 1e18;\n\npair<vector<i64>, vector<i64>> dijkstra(int start, const Graph& adj, int N) {\n    using Node = pair<i64, i32>;\n    priority_queue<Node, vector<Node>, greater<>> pq;\n    vector<i64> dist(N, INF), cnt(N, 0);\n    dist[start] = 0;\n    cnt[start] = 1;\n    pq.emplace(0, start);\n\n    while (!pq.empty()) {\n        auto [current_dist, u] = pq.top();\n        pq.pop();\n        if (current_dist != dist[u]) continue;\n\n        for (auto& [v, w] : adj[u]) {\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                cnt[v] = cnt[u];\n                pq.emplace(dist[v], v);\n            } else if (dist[u] + w == dist[v]) {\n                cnt[v] += cnt[u];\n            }\n        }\n    }\n    return {dist, cnt};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    i32 N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    Graph adj(N);\n    vector<tuple<i32, i32, i32>> edges(M);\n    for (i32 i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u, --v;\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n        edges[i] = {u, v, w};\n    }\n\n    vector<i64> edge_importance(M, 0);\n    for (i32 i = 0; i < N; ++i) {\n        auto [dist, cnt] = dijkstra(i, adj, N);\n        for (i32 j = 0; j < M; ++j) {\n            auto& [u, v, w] = edges[j];\n            if (dist[u] + w == dist[v]) \n                edge_importance[j] += cnt[u] * (N - cnt[v]);\n            if (dist[v] + w == dist[u])\n                edge_importance[j] += cnt[v] * (N - cnt[u]);\n        }\n    }\n\n    vector<pair<i64, i32>> order;\n    for (i32 i = 0; i < M; ++i) order.emplace_back(edge_importance[i], i);\n    sort(order.rbegin(), order.rend());\n\n    vi days(M, -1);\n    vector<i64> current_imp(D, 0);\n    priority_queue<pii, vector<pii>, greater<>> day_pq;\n    for (i32 i = 0; i < D; ++i) day_pq.push({0, i});\n\n    for (auto& [imp, idx] : order) {\n        auto [min_imp, day] = day_pq.top();\n        day_pq.pop();\n        days[idx] = day + 1;\n        day_pq.push({min_imp + imp, day});\n        current_imp[day] += imp;\n    }\n\n    for (auto d : days) cout << d << ' ';\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n    bool operator<(const Point& o) const {\n        return tie(x, y, z) < tie(o.x, o.y, o.z);\n    }\n};\n\nvector<vector<string>> input;  // Store each 2D silhouette\nvector<vector<vector<int>>> dp; // Precompute front and right silhouettes\nvector<vector<vector<int>>> blocks;\n\nvector<vector<vector<int>>> construct(int idx) {\n    auto& sil = input[idx*2];\n    auto& sir = input[idx*2 + 1];\n    int n = sil.size();\n    vector<vector<vector<int>>> cube(n, vector<vector<int>>(n, vector<int>(n)));\n    vector<vector<int>> vis(n, vector<int>(n, 0));\n    int cnt = 1;\n    \n    auto addBlock = [&](int x, int y, int z) {\n        cube[x][y][z] = cnt;\n    };\n    \n    // Process intersections to use same blocks for both configurations\n    for (int z = 0; z < n; z++) {\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (dp[idx][x][z] && dp[idx + 2][y][z] && !vis[x][y] && !blocks[x][y][z]) {\n                    blocks[x][y][z] = cnt;\n                    addBlock(x, y, z);\n                    vis[x][y]++;\n                }\n            }\n        }\n    }\n    \n    // Fill remaining regions needed by the first silhouette\n    for (int z = 0; z < n; z++) {\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (dp[idx][x][z] && !blocks[x][y][z]) {\n                    addBlock(x, y, z);\n                    blocks[x][y][z] = cnt++;\n                }\n            }\n        }\n    }\n    return cube;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D;\n    cin >> D;\n    input.resize(4);\n    \n    for (int t = 0; t < 4; t++) {\n        for (int i = 0; i < D; i++) {\n            string s;\n            cin >> s;\n            input[t].push_back(s);\n        }\n    }\n    \n    // Precompute front and right silhouettes\n    dp.assign(4, vector<vector<int>>(D, vector<int>(D)));\n    for (int t = 0; t < 4; t += 2) {\n        for (int z = 0; z < D; z++) {\n            for (int x = 0; x < D; x++) {\n                for (int y = 0; y < D; y++) {\n                    if (input[t][z][x] == '1') dp[t][x][z]++;\n                    if (input[t+1][z][y] == '1') dp[t+2][y][z]++;\n                }\n            }\n        }\n    }\n    \n    blocks.resize(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    auto cube1 = construct(0);\n    blocks.assign(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    auto cube2 = construct(1);\n    \n    // Count blocks used\n    int max_block = 0;\n    for (const auto& c1 : cube1) for (const auto& row : c1) \n        for (int block : row) max_block = max(max_block, block);\n    for (const auto& c2 : cube2) for (const auto& row : c2) \n        for (int block : row) max_block = max(max_block, block);\n    \n    cout << max_block << '\\n';\n    \n    // Output cubes\n    for (auto& c : cube1) {\n        for (auto& r : c) \n            for (int val : r) cout << val << \" \";\n        cout << \"\\n\";\n    }\n    for (auto& c : cube2) {\n        for (auto& r : c) \n            for (int val : r) cout << val << \" \";\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\n#include <boost/geometry.hpp>\nusing namespace std;\nusing namespace boost::geometry;\ntypedef model::d2::point_xy<int> Point;\n\nauto rng = mt19937(chrono::steady_clock::now().time_since_epoch().count());\n\nlong long distSquared(const Point &a, const Point &b) {\n    return (long long)(a.x() - b.x()) * (a.x() - b.x()) +\n           (long long)(a.y() - b.y()) * (a.y() - b.y());\n}\n\nstruct Edge {\n    int u, v, w;\n    bool operator<(const Edge &o) const { return w < o.w; }\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<Point> stations(N);\n    stations[0] = Point(0, 0);\n    for (int i = 1; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        stations[i] = Point(x, y);\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v >> edges[i].w;\n        edges[i].u--, edges[i].v--;\n    }\n\n    vector<Point> residents(K);\n    for (int i = 0; i < K; ++i) {\n        int a, b;\n        cin >> a >> b;\n        residents[i] = Point(a, b);\n    }\n\n    // Prim's MST\n    vector<bool> inMST(N, false);\n    inMST[0] = true;\n    priority_queue<Edge> pq;\n    for (Edge e : edges) {\n        if (e.u == 0 || e.v == 0) pq.push(e);\n    }\n\n    vector<bool> edgeUsed(M, false);\n    while (!pq.empty()) {\n        auto [u, v, w] = pq.top();\n        pq.pop();\n        if (inMST[u] && inMST[v]) continue;\n\n        int nxt = inMST[u] ? v : u;\n        inMST[nxt] = true;\n\n        if (u < v) edgeUsed[v - 1] = true;\n        else edgeUsed[u - 1] = true;\n\n        for (Edge e : edges) {\n            if ((e.u == nxt || e.v == nxt) && !inMST[e.u] && !inMST[e.v]) {\n                pq.push(e);\n            }\n        }\n    }\n\n    vector<int> radius(N, 0);\n    for (auto res : residents) {\n        int min_idx = 0;\n        long long min_dist = distSquared(res, stations[0]);\n        for (int i = 1; i < N; ++i) {\n            if (!inMST[i]) continue;\n            long long cur = distSquared(res, stations[i]);\n            if (cur < min_dist) {\n                min_dist = cur;\n                min_idx = i;\n            }\n        }\n        radius[min_idx] = max(radius[min_idx], \n            static_cast<int>(ceil(sqrt(min_dist))));\n    }\n\n    // Output results\n    for (int r : radius) cout << r << \" \";\n    cout << endl;\n    for (bool e : edgeUsed) cout << e << \" \";\n    cout << endl;\n\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;\nvector<vector<int>> grid(N, vector<int>(N));\nvector<tuple<int, int, int, int>> operations;\n\nbool valid(int x, int y) {\n    return x >= 0 && y >= 0 && x < N && y <= x;\n}\n\nint eval() {\n    int cnt = 0;\n    for (int i = 0; i < N-1; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            if (valid(i + 1, j) && grid[i][j] > grid[i + 1][j]) ++cnt;\n            if (valid(i + 1, j + 1) && grid[i][j] > grid[i + 1][j + 1]) ++cnt;\n        }\n    }\n    return cnt;\n}\n\nvoid swap_and_push(int x1, int y1, int x2, int y2) {\n    swap(grid[x1][y1], grid[x2][y2]);\n    operations.emplace_back(x1, y1, x2, y2);\n}\n\nvoid solve() {\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j <= i; ++j)\n            cin >> grid[i][j];\n\n    for (int iter = 0; iter < 500 && operations.size() < 10000; ++iter) {\n        bool improved = false;\n        // Iterate each position from top to bottom\n        for (int i = 0; i < N-1; ++i) {\n            for (int j = 0; j <= i; ++j) {\n                if (valid(i+1, j) && grid[i][j] > grid[i+1][j]) {\n                    swap_and_push(i, j, i+1, j);\n                    improved = true;\n                } else if (valid(i+1, j+1) && grid[i][j] > grid[i+1][j+1]) {\n                    swap_and_push(i, j, i+1, j+1);\n                    improved = true;\n                }\n                if (operations.size() >= 10000) break;\n            }\n            if (operations.size() >= 10000) break;\n        }\n        if (!improved) break;\n    }\n\n    cout << operations.size() << '\\n';\n    for (auto& [x1, y1, x2, y2] : operations)\n        cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int D = 9;\nint N;\nvector<vector<bool>> is_obstacle(D, vector<bool>(D, false));\n\n// Spiral path initialization\nvector<pair<int, int>> spiral_order;\n\nvoid initialize_spiral() {\n    int top = 0, bottom = D-1, left = 0, right = D-1;\n    int dir = 0; // 0: right, 1: down, 2: left, 3: up\n    while (top <= bottom && left <= right) {\n        if (dir == 0) {\n            for (int j = left; j <= right; ++j) spiral_order.emplace_back(top, j);\n            top++;\n        } else if (dir == 1) {\n            for (int i = top; i <= bottom; ++i) spiral_order.emplace_back(i, right);\n            right--;\n        } else if (dir == 2) {\n            for (int j = right; j >= left; --j) spiral_order.emplace_back(bottom, j);\n            bottom--;\n        } else if (dir == 3) {\n            for (int i = bottom; i >= top; --i) spiral_order.emplace_back(i, left);\n            left++;\n        }\n        dir = (dir + 1) % 4;\n    }\n    // Filter out entrance and invalid positions\n    spiral_order.erase(remove_if(spiral_order.begin(), spiral_order.end(), \n        [](auto& pos) {\n            return (pos.first == 0 && pos.second == (D-1)/2) || is_obstacle[pos.first][pos.second];\n        }), \n        spiral_order.end());\n    reverse(spiral_order.begin(), spiral_order.end());\n}\n\nbool in_bounds(int x, int y) {\n    return x >= 0 && x < D && y >= 0 && y < D;\n}\n\nstruct StorageEntry {\n    int val;\n    int x, y;\n};\n\nvector<vector<int>> grid(D, vector<int>(D, -1));\nvector<StorageEntry> stored;\n\npair<int, int> bfs_nearest(int target) {\n    queue<pair<int, int>> q;\n    q.emplace((0, (D-1)/2));\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    visited[0][(D-1)/2] = true;\n    \n    while (!q.empty()) {\n        auto [cx, cy] = q.front(); q.pop();\n        for (auto [dx, dy] : vector<pair<int, int>>{{-1,0},{1,0},{0,-1},{0,1}}) {\n            int nx = cx + dx, ny = cy + dy;\n            if (in_bounds(nx, ny) && !visited[nx][ny] && !is_obstacle[nx][ny] && grid[nx][ny] != -1) {\n                if (grid[nx][ny] == target) {\n                    grid[nx][ny] = -1; // mark as used\n                    return {nx, ny};\n                }\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return {-1, -1};\n}\n\nint main() {\n    cin >> N;\n    int n = D*D - 1 - N;\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        is_obstacle[x][y] = true;\n    }\n\n    initialize_spiral();\n    int cur_pos = 0;\n    unordered_map<int, pair<int, int>> container_map;\n\n    for (int d = 0; d < n; ++d) {\n        int t;\n        cin >> t;\n        stored.push_back({t, spiral_order[cur_pos].first, spiral_order[cur_pos].second});\n        container_map[t] = spiral_order[cur_pos];\n        grid[spiral_order[cur_pos].first][spiral_order[cur_pos].second] = t;\n        cur_pos++;\n        cout << spiral_order[cur_pos - 1].first << \" \" << spiral_order[cur_pos - 1].second << endl;\n    }\n\n    sort(stored.begin(), stored.end(), [](const auto& a, const auto& b) { return a.val < b.val; });\n\n    for (const auto& entry : stored) {\n        auto [x, y] = bfs_nearest(entry.val);\n        cout << x << \" \" << y << endl;\n    }\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 51;\nint grid[N][N];\nint ans[N][N];\nint n, m;\n\nint dx[4] = {-1, 0, 1, 0};\nint dy[4] = {0, 1, 0, -1};\n\nvoid bfs_zero() {\n    deque<pair<int, int>> q;\n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    for (int i=0; i<n; ++i) {\n        if (ans[i][0] == 0 && !vis[i][0]) {\n            q.push_back({i, 0});\n            vis[i][0] = true;\n        }\n        if (ans[i][n-1] == 0 && !vis[i][n-1]) {\n            q.push_back({i, n-1});\n            vis[i][n-1] = true;\n        }\n    }\n    for (int j=0; j<n; ++j) {\n        if (ans[0][j] == 0 && !vis[0][j]) {\n            q.push_back({0, j});\n            vis[0][j] = true;\n        }\n        if (ans[n-1][j] == 0 && !vis[n-1][j]) {\n            q.push_back({n-1, j});\n            vis[n-1][j] = true;\n        }\n    }\n\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop_front();\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 || vis[nx][ny] || ans[nx][ny] != 0) continue;\n            ans[nx][ny] = 0;\n            vis[nx][ny] = true;\n            q.push_back({nx, ny});\n        }\n    }\n}\n\nint main() {\n    cin >> n >> m;\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            cin >> grid[i][j];\n            ans[i][j] = grid[i][j];\n        }\n    }\n    \n    vector<pair<int, int>> reps(m+1);\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            int c = grid[i][j];\n            if (reps[c] == pair<int, int>{}) {\n                reps[c] = {i, j};\n            }\n        }\n    }\n\n    memset(ans, -1, sizeof(ans));\n    for (int i=1; i<=m; ++i) {\n        if (reps[i] != pair<int, int>{}) {\n            auto [x, y] = reps[i];\n            ans[x][y] = i;\n            // Connect to border if it's adjacent originally\n            if (x == 0 || x == n-1 || y == 0 || y == n-1) {\n                ans[x][y] = 0; // Treat edge as zero\n            }\n        }\n    }\n\n    // Handle adjacencies for initial fill\n    for (int i=1; i<=m; ++i) {\n        if (reps[i].first != -1) {\n            auto [x, y] = reps[i];\n            bool adj_zero = false;\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) {\n                    adj_zero = true;\n                    break;\n                }\n                if (grid[nx][ny] == 0) adj_zero = true;\n            }\n            if (adj_zero) ans[x][y] = 0;\n        }\n    }\n\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (ans[i][j] == -1) ans[i][j] = 0;\n        }\n    }\n    \n    bfs_zero(); // Expand zeros properly\n    \n    // Connect remaining color cells to components\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (ans[i][j] > 0) continue;\n            for (int d=0; d<4; ++d) {\n                int nx = i + dx[d], ny = j + dy[d];\n                if (nx < 0 || nx >= n || ny < 0 || ny >= n || ans[nx][ny] <= 0) continue;\n                ans[i][j] = ans[nx][ny];\n                break;\n            }\n        }\n    }\n\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (j > 0) cout << ' ';\n            cout << ans[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Vec = vector<int>;\nusing Mat = vector<Vec>;\nusing Graph = vector<Vec>;\nconstexpr ll INF = 1LL<<60;\nmt19937 mt(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct Partition {\n    int N, D, Q;\n    Vec A; // Answer partitions\n    Mat W; // Constraints: W[u][v] > 0 means u > v\n    vector<double> weight; // Virtual item weights\n\n    void init(int n, int d, int q) {\n        N = n; D = d; Q = q;\n        A = Vec(N, -1);\n        W.assign(N, Vec(N));\n        weight.resize(N, 1.0);\n    }\n\n    // Assign a random group with the smallest current sum\n    int assign(const Vec& cnt) {\n        priority_queue<pair<double, int>, vector<pair<double, int>>, greater<>> pq;\n        for (int i=0; i<D; ++i) pq.emplace(cnt[i] * weight[i], i);\n        \n        // Prefer groups with space but allow overfill near the end\n        int best = -1, minOver = N+1;\n        for (auto [w, idx] : pq) {\n            int total = cnt[idx] + 1;\n            if (total > N/D && minOver <= N/D) continue;\n            if (best == -1 || (total <= N/D && cnt[idx] < cnt[best])) {\n                best = idx;\n                if (total > N/D) minOver = total;\n            }\n        }\n        return best;\n    }\n\n    Vec solve() {\n        // Initial comparison phase\n        int q = 0;\n        for (int i=0; i<N-1 && q < Q; ++i) {\n            cout << 1 << ' ' << 1 << ' ' << i << ' ' << (i+1) << endl;\n            char res; cin >> res;\n            if (res == '>') W[i][i+1] = 1;\n            else if (res == '<') W[i+1][i] = 1;\n            ++q;\n        }\n\n        // Update virtual weights based on constraints\n        for (int k=0; k<N; ++k)\n            for (int i=0; i<N; ++i)\n                for (int j=0; j<N; ++j)\n                    if (W[i][k] && W[k][j]) W[i][j] = 1;\n\n        Vec cnt(D, 0);\n        for (int i=0; i<N; ++i) {\n            if (q >= Q) break;\n            int group = assign(cnt);\n            if (group == -1) {\n                group = mt() % D; // Random if stuck\n                if (cnt[group] >= N/D) continue; // Avoid overfill\n            }\n            A[i] = group;\n            cnt[group]++;\n        }\n\n        // Fill remaining unassigned items (if any)\n        int group = 0;\n        for (int i=0; i<N; ++i) {\n            if (A[i] == -1) {\n                while (cnt[group] >= N/D) group++;\n                A[i] = group;\n                cnt[group]++;\n            }\n        }\n\n        // Output final partition\n        for (int x: A) cout << x << ' ';\n        cout << endl;\n        return A;\n    }\n};\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n    Partition solver;\n    solver.init(N, D, Q);\n    solver.solve();\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nvoid find_box(const multi_array<int, 2>& stacks, int target, int& sidx, int& pos) {\n    for (int i=0; i<stacks.shape()[0]; ++i) {\n        for (int j=stacks.shape()[1]-1; j>=0; --j) {\n            if (stacks[i][j] == target) {\n                sidx = i; pos = j;\n                return;\n            }\n        }\n    }\n}\n\nint main() {\n    int n = 200, m = 10;\n    multi_array<int, 2> stacks(extents[m][n/m]);\n    for (int i=0; i<m; ++i)\n        for (int j=0; j<n/m; ++j)\n            cin >> stacks[i][j];\n\n    vector<pair<int, int>> moves;\n    int target = 1;\n\n    while (target <= n) {\n        int current_s = -1, pos = -1;\n        find_box(stacks, target, current_s, pos);\n        \n        bool at_top = false;\n        for (int s=0; s<m; ++s) {\n            if (!stacks[s].empty() && stacks[s].back() == target) {\n                at_top = true;\n                current_s = s;\n                break;\n            }\n        }\n        if (at_top) {\n            moves.emplace_back(target, 0);\n            stacks[current_s].pop_back();\n            target++;\n            continue;\n        }\n        \n        if (pos != stacks[current_s].size()-1) {\n            int max_dest = -1, dest_idx = -1;\n            for (int s=0; s<m; ++s) {\n                if (!stacks[s].empty() && s != current_s) {\n                    if (stacks[s].back() > max_dest || dest_idx == -1) {\n                        max_dest = stacks[s].back();\n                        dest_idx = s;\n                    }\n                }\n            }\n            if (dest_idx == -1) dest_idx = (current_s + 1) % m; // Pick next available\n            moves.emplace_back(stacks[current_s][pos], dest_idx + 1);\n            auto seq = stacks[current_s].subarray(pos, stacks[current_s].size());\n            stacks[dest_idx].insert(stacks[dest_idx].end(), seq.begin(), seq.end());\n            stacks[current_s].resize(pos);\n        }\n    }\n\n    for (auto& [v, i] : moves)\n        cout << v << \" \" << i << \"\\n\";\n}","ahc027":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\nusing namespace boost;\n\n// Direction vectors: down, right, up, left\nint dx[] = {1, 0, -1, 0};\nint dy[] = {0, 1, 0, -1};\nchar dir_char[] = {'D', 'R', 'U', 'L'};\n\nconst int INF = 1e9;\ntypedef vector<vector<int>> Matrix;\ntypedef vector<vector<vector<int>>> Dist; // precomputed distances\n\nbool valid(int x, int y, int n) {\n    return x >= 0 && x < n && y >= 0 && y < n;\n}\n\npair<Matrix, Matrix> parseInput(int n) {\n    vector<string> h(n-1), v(n);\n    for (auto& s : h) cin >> s;\n    for (auto& s : v) cin >> s;\n    \n    Matrix hor(n, vector<int>(n, 0));\n    for (int i = 0; i < n-1; ++i)\n        for (int j = 0; j < n; ++j)\n            hor[i][j] = h[i][j] - '0';\n            \n    Matrix ver(n, vector<int>(n, 0));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n-1; ++j)\n            ver[i][j] = v[i][j] - '0';\n            \n    return {hor, ver};\n}\n\nMatrix readDirt(int n) {\n    Matrix d(n, vector<int>(n, 0));\n    for (auto& row : d)\n        for (int& v : row) cin >> v;\n    return d;\n}\n\nvoid bfs(int x, int y, int n, const Matrix& hor, const Matrix& ver, vector<vector<bool>>& vis) {\n    queue<pair<int,int>> q;\n    q.emplace(x, y);\n    vis[x][y] = true;\n    while (!q.empty()) {\n        auto [cx, cy] = q.front(); q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int nx = cx + dx[k], ny = cy + dy[k];\n            if (valid(nx, ny, n) && !vis[nx][ny]) {\n                if ((k == 0 && !hor[cx][cy]) || \n                    (k == 1 && !ver[cx][cy]) ||\n                    (k == 2 && !hor[nx][ny]) ||\n                    (k == 3 && !ver[nx][ny])) {\n                    vis[nx][ny] = true;\n                    q.emplace(nx, ny);\n                }\n            }\n        }\n    }\n}\n\nDist precompute_distances(int n, const Matrix& hor, const Matrix& ver) {\n    Dist dist(n, vector<vector<int>>(n, vector<int>(n*n, INF)));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            priority_queue<pair<int, pair<int,int>>, \n                           vector<pair<int, pair<int,int>>>, \n                           greater<>> pq;\n            pq.emplace(0, make_pair(i, j));\n            dist[i][j][i*n + j] = 0;\n            while (!pq.empty()) {\n                auto [d, p] = pq.top(); pq.pop();\n                auto [x, y] = p;\n                if (d > dist[i][j][x*n + y]) continue;\n                for (int k = 0; k < 4; ++k) {\n                    int nx = x + dx[k], ny = y + dy[k];\n                    if (valid(nx, ny, n)) {\n                        bool blocked = (k == 0 && hor[x][y]) ||\n                                       (k == 1 && ver[x][y]) ||\n                                       (k == 2 && hor[nx][ny]) ||\n                                       (k == 3 && ver[nx][ny]);\n                        if (!blocked && d + 1 < dist[i][j][nx*n + ny]) {\n                            dist[i][j][nx*n + ny] = d + 1;\n                            pq.emplace(d + 1, make_pair(nx, ny));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return dist;\n}\n\nvoid add_route(int x, int y, int nx, int ny, const Dist& dist, vector<char>& answer, int n) {\n    if (x == nx && y == ny) return;\n    auto& d = dist[x][y];\n    int best_k = -1;\n    for (int k = 0; k < 4; ++k) {\n        int ax = x + dx[k], ay = y + dy[k];\n        if (valid(ax, ay, n) && dist[x][y][ax*n + ay] == d[nx*n + ny] - 1 && \n            (best_k == -1 || dist[ax][ay][nx*n + ny] < dist[x + dx[best_k]][y + dy[best_k]][nx*n + ny])) {\n            best_k = k;\n        }\n    }\n    if (best_k != -1) {\n        answer.push_back(dir_char[best_k]);\n        add_route(x + dx[best_k], y + dy[best_k], nx, ny, dist, answer, n);\n    }\n}\n\nvector<pair<int, int>> get_critical_points(const Matrix& d, int region_size) {\n    vector<pair<int, pair<int,int>>> points;\n    for (int i = 0; i < d.size(); ++i)\n        for (int j = 0; j < d.size(); ++j)\n            points.emplace_back(-d[i][j], make_pair(i,j));\n    sort(points.begin(), points.end());\n    \n    vector<pair<int,int>> result;\n    for (int i = 0; i < min<int>(region_size, (int)points.size()); ++i)\n        result.emplace_back(points[i].second);\n    return result;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    auto [hor, ver] = parseInput(n);\n    Matrix d = readDirt(n);\n    \n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    bfs(0, 0, n, hor, ver, vis);\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            assert(vis[i][j]);\n    \n    Dist dist = precompute_distances(n, hor, ver);\n    \n    vector<pair<int, int>> critical = get_critical_points(d, n); // Top critical points\n    \n    vector<char> answer;\n    int len = 0, limit = 1e5;\n    int x = 0, y = 0;\n    \n    vector<int> shuffled(critical.size());\n    iota(shuffled.begin(), shuffled.end(), 0);\n    \n    while (true) {\n        random_shuffle(shuffled.begin(), shuffled.end());\n        for (int idx : shuffled) {\n            auto [nx, ny] = critical[idx];\n            if (len + dist[x][y][nx*n + ny] > limit) break;\n            add_route(x, y, nx, ny, dist, answer, n);\n            len += dist[x][y][nx*n + ny];\n            x = nx; y = ny;\n        }\n        if (len + dist[x][y][0] > limit)\n            break;\n        add_route(x, y, 0, 0, dist, answer, n);\n        break;\n    }\n    \n    cout << string(answer.begin(), answer.end()) << endl;\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\n#include <boost/algorithm/string/find_tail.hpp>\nusing namespace std;\n\nstring concat(const vector<string>& t) {\n    int m = t.size();\n    string result = t[0];\n    unordered_map<string, vector<int>> suffix;\n    for (int i=0; i<m; ++i) {\n        for (int len=1; len<=4; ++len) {\n            suffix[t[i].substr(t[i].size() - len)].push_back(i);\n        }\n    }\n    vector<bool> used(m, false);\n    used[0] = true;\n    \n    auto get_cost = [&](int idx, const string& prev_str) {\n        string target = t[idx];\n        int n = prev_str.size();\n        int max_overlap = 0;\n        for (int i=1; i<=4 && i<=n; ++i) {\n            if (boost::algorithm::ends_with(prev_str, target.substr(0,i))) \n                max_overlap = i;\n        }\n        return target.size() - max_overlap;\n    };\n    \n    for (int count=1; count<m; ++count) {\n        int best_idx = -1, min_cost = INT_MAX;\n        for (int i=0; i<m; ++i) {\n            if (!used[i]) {\n                int cost = get_cost(i, result);\n                if (cost < min_cost) {\n                    min_cost = cost;\n                    best_idx = i;\n                }\n            }\n        }\n        if (best_idx == -1) break;\n        used[best_idx] = true;\n        string current = t[best_idx];\n        int n = result.size();\n        int overlap = 0;\n        for (int k=1; k<=min(4,n); ++k) {\n            if (boost::algorithm::ends_with(result, current.substr(0,k)))\n                overlap = k;\n        }\n        result += current.substr(overlap);\n    }\n    return result.substr(0, 5000);\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> A(N);\n    for (int i=0; i<N; ++i) cin >> A[i];\n    \n    vector<string> words(M);\n    unordered_map<char, pair<int,int>> pos;\n    \n    for (int i=0; i<M; ++i) cin >> words[i];\n    \n    for (int i=0; i<N; ++i) \n        for (int j=0; j<N; ++j) \n            pos[A[i][j]] = {i, j};\n    \n    string lucky = concat(words);\n    pair<int, int> current = {si, sj};\n    vector<pair<int,int>> steps;\n    \n    for (char c : lucky) {\n        steps.emplace_back(pos[c]);\n    }\n    \n    cout << steps.size() << endl;\n    for (auto& [x, y] : steps) {\n        cout << x << \" \" << y << endl;\n    }\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nusing namespace std;\nusing namespace boost::accumulators;\n\nstruct Grid {\n    int n;\n    boost::multi_array<int, 2> grid;  // 0: unknown, -1: empty, >=1: count\n    vector<pair<int,int>> unknown;\n    mt19937 mt{random_device{}()};\n    \n    Grid(int _n) : n(_n), grid(boost::extents[_n][_n]) {\n        for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) {\n            grid[i][j] = 0;\n            unknown.emplace_back(i, j);\n        }\n    }\n    \n    bool is_unknown(int i, int j) const {\n        return 0 <= i && i < n && 0 <= j && j <n && grid[i][j] == 0;\n    }\n    \n    void query_group(int size, const vector<pair<int,int>>& indexes) {\n        cout << \"q \" << size;\n        for (auto [x,y] : indexes) cout << ' ' << x << ' ' << y;\n        cout << endl;\n        int result;\n        cin >> result;\n        double mean = result + size * (1e-5); // Prevent division by zero\n        double stddev = sqrt(size * 0.2); // Conservative estimate\n        \n        double z_score = (result - size * 0.1) / (stddev + 1e-5);\n        for (auto [x,y] : indexes) {\n            if (grid[x][y] == 0) {\n                if (z_score > 2.0) grid[x][y] = 2;\n                else if (z_score < -1.5) grid[x][y] = -1;\n            }\n        }\n    }\n    \n    void drill(int i, int j) {\n        cout << \"q 1 \" << i << ' ' << j << endl;\n        cin >> grid[i][j];\n    }\n    \n    void report() {\n        vector<pair<int,int>> positives;\n        for (int i=0; i<n; ++i)\n            for (int j=0; j<n; ++j)\n                if (grid[i][j] > 0) positives.emplace_back(i,j);\n        \n        cout << \"a \" << positives.size();\n        for (auto [x,y] : positives) cout << ' ' << x << ' ' << y;\n        cout << endl;\n        exit(0);\n    }\n};\n\nbool is_border(int i, int j, int n) {\n    return i == 0 || j == 0 || i == n-1 || j == n-1;\n}\n\nint main() {\n    srand(time(0));\n    int N, M;\n    double epsilon;\n    cin >> N >> M >> epsilon;\n    vector<vector<pair<int,int>>> oil(M);\n    \n    for (int m=0; m<M; ++m) {\n        int d; cin >> d;\n        oil[m].resize(d);\n        for (int k=0; k<d; ++k) {\n            cin >> oil[m][k].first >> oil[m][k].second;\n        }\n    }\n    \n    Grid g(N);\n    int total = N * N;\n    int budget = total / 3;\n    \n    // Initial divination phase: 5x5 blocks\n    for (int i=0; i+5<=N; i+=5) {\n        for (int j=0; j+5<=N; j+=5) {\n            if (budget-- <= 0) break;\n            vector<pair<int,int>> block;\n            for (int x=i; x < i+5; ++x)\n                for (int y=j; y < j+5; ++y) \n                    if (g.is_unknown(x,y)) block.emplace_back(x,y);\n            if (block.size() >= 2) g.query_group(block.size(), block);\n        }\n        if (budget <= 0) break;\n    }\n    \n    // Remaining cells: smaller divination\n    while (budget >= 5 && g.unknown.size() >= 5) {\n        shuffle(g.unknown.begin(), g.unknown.end(), g.mt);\n        vector<pair<int,int>> batch;\n        while (budget >= 0 && batch.size() < 20 && !g.unknown.empty()) {\n            auto [x,y] = g.unknown.back();\n            g.unknown.pop_back();\n            if (g.is_unknown(x,y)) {\n                batch.emplace_back(x,y);\n            }\n        }\n        if (batch.size() >= 2) {\n            g.query_group(batch.size(), batch);\n            budget--;\n        }\n    }\n    \n    // Drill borders\n    for (auto &cell : g.unknown) {\n        if (g.is_unknown(cell.first, cell.second) && is_border(cell.first, cell.second, N)) {\n            g.drill(cell.first, cell.second);\n        }\n    }\n    \n    // Drill remaining\n    for (auto &cell : g.unknown) {\n        if (g.is_unknown(cell.first, cell.second)) {\n            g.drill(cell.first, cell.second);\n        }\n    }\n    \n    g.report();\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<tuple<int,int,int,int>> rectangles[55];\n\nvoid solve(int n, const vector<int>& areas) {\n    int w = 1000;\n    int sum = accumulate(areas.begin(), areas.end(), 0);\n    int remaining = w * w - sum;\n    vector<int> needed = areas;\n    int max_y = w;\n\n    rectangles[n].resize(areas.size());\n    \n    for (int i=0; i<(int)areas.size(); ++i) {\n        int rows = (remaining + (int)areas.size() - i - 1) / ((int)areas.size() - i);\n        rows = max(rows, (needed[i] + w - 1) / w); // at least enough area\n        \n        int y_start = max_y - rows;\n        get<0>(rectangles[n][i]) = y_start;\n        get<2>(rectangles[n][i]) = max_y;\n        get<1>(rectangles[n][i]) = 0;\n        int cols = needed[i] / rows;\n        if (cols * rows < needed[i]) ++cols;\n        cols = min(cols, w); // max columns can't exceed grid width\n        get<3>(rectangles[n][i]) = cols;\n        \n        remaining -= (rows * cols - needed[i]);\n        max_y = y_start;\n    }\n    \n    int last_x = 0;\n    for (int k=0; k < (int)rectangles[n].size(); ++k) {\n        get<1>(rectangles[n][k]) = last_x;\n        last_x += get<3>(rectangles[n][k]);\n        get<3>(rectangles[n][k]) = last_x;\n    }\n}\n\nint main() {\n    int W = 1000, D, N;\n    cin >> W >> D >> N;\n    \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    for (int d=0; d<D; ++d) \n        solve(d, a[d]);\n    \n    for (int d=0; d<D; ++d)\n        for (auto [x1,y1,x2,y2] : rectangles[d])\n            printf(\"%d %d %d %d\\n\", x1, y1, x2, y2);\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nconst int MOD = 998244353;\nconst int N = 9;\nint a[N][N], s[20][3][3];\n\nint get_gain(int m, int p, int q) {\n    int total = 0;\n    for (int i = 0; i < 3; ++i)\n        for (int j = 0; j < 3; ++j) {\n            int new_val = (a[p+i][q+j] + s[m][i][j]) % MOD;\n            total += (new_val - a[p+i][q+j] + MOD) % MOD;\n        }\n    return total;\n}\n\nvoid apply_stamp(int m, int p, int q) {\n    for (int i = 0; i < 3; ++i)\n        for (int j = 0; j < 3; ++j)\n            a[p+i][q+j] = (a[p+i][q+j] + s[m][i][j]) % MOD;\n}\n\nint main() {\n    mt19937 rng(random_device{}());\n    int n, m, k;\n    cin >> n >> m >> k;\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n    \n    for (int t = 0; t < m; ++t)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> s[t][i][j];\n\n    vector<tuple<int, int, int>> ops;\n    int used = 0;\n\n    // Prioritize deterministic best moves first\n    while (used < k) {\n        int best_gain = -1, bst_m = -1, bst_p = -1, bst_q = -1;\n        for (int m_idx = 0; m_idx < m; ++m_idx) {\n            for (int p = 0; p <= 6; ++p) {\n                for (int q = 0; q <= 6; ++q) {\n                    int gain = get_gain(m_idx, p, q);\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        bst_m = m_idx;\n                        bst_p = p;\n                        bst_q = q;\n                    }\n                }\n            }\n        }\n        if (best_gain <= 0 || ops.size() == k) break;\n        ops.emplace_back(bst_m, bst_p, bst_q);\n        apply_stamp(bst_m, bst_p, bst_q);\n        ++used;\n    }\n\n    // Fill remaining with semi-random choices\n    vector<pair<int, int>> pos;\n    for (int x = 0; x <= 6; ++x) for (int y = 0; y <= 6; ++y) pos.emplace_back(x, y);\n    while (used < k) {\n        shuffle(pos.begin(), pos.end(), rng);\n        for (auto [x, y] : pos) {\n            if (used == k) break;\n            for (int m_idx = rng() % m; m_idx < m; ++m_idx) {\n                if (used == k) break;\n                ops.emplace_back(m_idx, x, y);\n                apply_stamp(m_idx, x, y);\n                ++used;\n            }\n        }\n    }\n\n    cout << ops.size() << \"\\n\";\n    for (auto [m, p, q] : ops)\n        cout << m << \" \" << p << \" \" << q << \"\\n\";\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nvector<string> solve(const vector<vector<int>>& containers) {\n    int N = 5;\n    vector<pair<int, int>> targets(N*N);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            targets[containers[i][j]] = {i, N-1};\n\n    vector<pair<int, int>> crane(N);\n    vector<bool> holding(N, false);\n    for (int i=0; i < N; ++i) crane[i] = {i, 0};\n\n    vector<string> ans(N);\n    for (int turn = 0; turn < 100; ++turn) {\n        bool moved = false;\n        vector<bool> grid(N*N, false);\n        for (auto [x, y] : crane) grid[x*N + y] = true;\n\n        for (int i = 0; i < N; ++i) {\n            auto [x, y] = crane[i];\n            char move = '.';\n\n            if (!holding[i] && y == 0) {\n                bool found = false;\n                for (int r = 0; r < N && !found; ++r) {\n                    if (x == r && turn < (int)containers[r].size() && !grid[r*N + 0]) {\n                        move = 'P';\n                        found = true;\n                    }\n                }\n            } else if (holding[i]) {\n                auto [tx, ty] = targets[containers[x][turn]];\n                if (x == tx && y == ty) move = 'Q';\n                else {\n                    if (y < ty) move = 'R';\n                    else if (x < tx) move = 'D';\n                    else move = 'U';\n                }\n            } else {\n                // Move towards a container\n                if (x > 0) move = 'U';\n                else if (x < N-1) move = 'D';\n            }\n\n            pair<int, int> next = crane[i];\n            if (move == 'P') next.second++;\n            if (move == 'Q') next.second--;\n            if (move == 'U') next.first--;\n            if (move == 'D') next.first++;\n            if (move == 'R') next.second++;\n            if (move == 'L') next.second--;\n\n            bool valid = (next.first >= 0 && next.first < N && next.second >= 0 && next.second < N);\n            for (int j = 0; j < N && valid; ++j) {\n                if (i != j && crane[j] == next) valid = false;\n            }\n\n            if (valid && move != '.') {\n                ans[i] += move;\n                crane[i] = next;\n                moved = true;\n                if (move == 'P') grid[next.first*N + next.second] = true;\n                if (move == 'Q') {\n                    holding[i] = false;\n                    grid[next.first*N + next.second] = false;\n                }\n            } else {\n                ans[i] += '.';\n            }\n        }\n        if (!moved) break;\n    }\n\n    int max_len = 0;\n    for (auto& cmd : ans) max_len = max(max_len, (int)cmd.size());\n    for (auto& cmd : ans) cmd.resize(max_len, '.');\n    \n    return ans;\n}\n\nint main() {\n    int N = 5;\n    vector<vector<int>> containers(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> containers[i][j];\n    \n    auto result = solve(containers);\n    for (auto& s : result)\n        cout << s << '\\n';\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint H[20][20], dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}, vis[20][20];\nvector<string> ans;\nint n = 20, x = 0, y = 0, load = 0;\n\nvoid move(int nx, int ny) {\n    while (x != nx || y != ny) {\n        if (x > nx) ans.push_back(\"U\"), x--;\n        else if (x < nx) ans.push_back(\"D\"), x++;\n        else if (y > ny) ans.push_back(\"L\"), y--;\n        else ans.push_back(\"R\"), y++;\n    }\n}\n\nvoid load_soil(int val) {\n    ans.push_back(\"+\" + to_string(val));\n    load += val;\n    H[x][y] -= val;\n}\n\nvoid unload_soil(int val) {\n    ans.push_back(\"-\" + to_string(val));\n    load -= val;\n    H[x][y] += val;\n}\n\nvoid process() {\n    memset(vis, 0, sizeof(vis));\n    vector<pair<int, int>> positives, negatives;\n    \n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            (H[i][j] > 0) ? positives.emplace_back(H[i][j], i*n+j) :\n            (H[i][j] < 0) ? negatives.emplace_back(-H[i][j], i*n+j) : void();\n        }\n    }\n\n    sort(positives.rbegin(), positives.rend());\n    sort(negatives.rbegin(), negatives.rend());\n\n    auto get = [&](int val) { return pair{val/n, val%n}; };\n\n    while (!positives.empty() && !negatives.empty()) {\n        auto [pval, pos] = positives.back(); positives.pop_back();\n        auto [nval, neg] = negatives.back(); negatives.pop_back();\n        auto [posx, posy] = get(pos);\n        auto [negx, negy] = get(neg);\n\n        if (pval == 0 || nval == 0) break;\n        int transfer = min(pval, nval);\n\n        move(posx, posy);\n        load_soil(transfer);\n        move(negx, negy);\n        unload_soil(transfer);\n\n        if (pval > transfer) positives.emplace_back(pval - transfer, pos);\n        if (nval > transfer) negatives.emplace_back(nval - transfer, neg);\n    }\n\n    while (!positives.empty()) {\n        auto [pval, pos] = positives.back(); positives.pop_back();\n        auto [posx, posy] = get(pos);\n        if (posx == x && posy == y) continue;\n        move(posx, posy);\n        load_soil(pval);\n    }\n\n    while (!negatives.empty()) {\n        auto [nval, neg] = negatives.back(); negatives.pop_back();\n        auto [negx, negy] = get(neg);\n        move(negx, negy);\n        unload_soil(nval);\n    }\n}\n\nint main() {\n    cin >> n;\n    for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) cin >> H[i][j];\n    \n    process();\n    for (auto& op : ans) cout << op << endl;\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\nusing namespace std;\n\nconstexpr int N = 6;\nconstexpr int SEED_COUNT = 2 * N * (N - 1);\nconstexpr int FIELD_SIZE = N * N;\n\nnamespace atcoder {\n    void internal_error() {\n        cerr << \"Error!\" << endl;\n        exit(0);\n    }\n\n    mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());\n\n    int rand(int a, int b) {\n        return uniform_int_distribution<int>(a, b)(mt);\n    }\n\n    double rand(double a, double b) {\n        return uniform_real_distribution<double>(a, b)(mt);\n    }\n}\nusing namespace atcoder;\n\nstruct Seed {\n    vector<int> eval;\n    int total;\n\n    Seed(const vector<int> &eval) : eval(eval) {\n        total = accumulate(eval.begin(), eval.end(), 0);\n    }\n\n    bool operator<(const Seed &other) const {\n        return this->total < other.total;\n    }\n};\n\nvector<int> next_gen(int round, const vector<Seed> &seeds) {\n    // Prioritize top seeds\n    vector<int> sorted_id(SEED_COUNT);\n    iota(sorted_id.begin(), sorted_id.end(), 0);\n    sort(sorted_id.begin(), sorted_id.end(), [&](int a, int b) {\n        return seeds[a].total > seeds[b].total;\n    });\n\n    vector<int> layout(FIELD_SIZE);\n    fill(layout.begin(), layout.end(), -1);\n    \n    // Place the N*N best seeds on the board\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            layout[i * N + j] = sorted_id[i * N + j];\n        }\n    }\n\n    return layout;\n}\n\nint main() {\n    int M, T;\n    cin >> N >> M >> T;\n\n    vector<Seed> seeds;\n    for (int i = 0; i < SEED_COUNT; ++i) {\n        vector<int> eval(M);\n        for (int &val : eval) cin >> val;\n        seeds.emplace_back(eval);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        auto layout = next_gen(t, seeds);\n        \n        for (int i = 0; i < FIELD_SIZE; ++i) {\n            cout << layout[i] << (i % N == N - 1 ? '\\n' : ' ');\n        }\n        cout << flush;\n\n        // Read the newly generated seeds\n        seeds.resize(SEED_COUNT);\n        for (int i = 0; i < SEED_COUNT; ++i) {\n            vector<int> eval(M);\n            for (int &val : eval) cin >> val;\n            seeds[i] = Seed(eval);\n        }\n    }\n}","ahc038":"#include <bits/stdc++.h>\n#include <queue>\n#include <optional>\nusing namespace std;\n\nconstexpr int INF = 1e9;\n\nstruct Pos {\n    int x, y;\n    bool operator==(const Pos& o) const { return x == o.x && y == o.y; }\n    Pos rotate(char c) const {\n        if (c == 'L') return {-y, x};\n        if (c == 'R') return {y, -x};\n        return {x, y};\n    }\n};\n\nstruct State {\n    int turns;\n    Pos pos;\n    vector<Pos> fingers; // relative positions\n    State(int t, Pos p, const vector<Pos>& f) : turns(t), pos(p), fingers(f) {}\n};\n\nvector<string> grid;\nvector<vector<char>> rotations;\nint dist(Pos a, Pos b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvector<string> find_path(Pos start, Pos goal, int V, const string& initial_rot = \"\") {\n    priority_queue<pair<int, State>, vector<pair<int, State>>, greater<>> pq;\n    unordered_map<Pos, int> dirs = {{'R', 0}, {'D', 1}, {'L', 2}, {'U', 3}};\n    vector<Pos> dir_offs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n    vector<string> dir_strs = {\"R\", \"D\", \"L\", \"U\"};\n    unordered_map<State, int, hash<State>> visited;\n    \n    vector<Pos> init_fingers(V - 1);\n    for (int i = 0; i < V - 1; ++i) {\n        init_fingers[i] = {i + 1, 0};\n    }\n    for (char c : initial_rot) {\n        if (c == '.') break;\n        for (auto& f : init_fingers) f = f.rotate(c);\n    }\n    \n    auto start_state = State(0, start, init_fingers);\n    pq.emplace(dist(start, goal), start_state);\n    visited[start_state] = 0;\n    \n    while (!pq.empty()) {\n        auto [current_cost, current] = pq.top();\n        pq.pop();\n        if (current.pos == goal) {\n            vector<string> path;\n            string rot = initial_rot.substr(0, V - 1);\n            while (current.turns > 0) {\n                path.emplace_back(dir_strs[current.pos.x] + rot + string(V, '.'));\n                for (char& c : rot) {\n                    if (c == 'R') c = 'L';\n                    else if (c == 'L') c = 'R';\n                }\n                reverse(rot.begin(), rot.end());\n                current.pos = goal;\n                --current.turns;\n            }\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        \n        for (int i = 0; i < 4; ++i) {\n            Pos next_pos = {current.pos.x + dir_offs[i].x, current.pos.y + dir_offs[i].y};\n            if (next_pos.x < 0 || next_pos.x >= grid.size() || next_pos.y < 0 || next_pos.y >= grid.size())\n                continue;\n            auto new_state = State(current.turns + 1, next_pos, current.fingers);\n            if (visited.count(new_state) && visited[new_state] <= new_state.turns)\n                continue;\n            visited[new_state] = new_state.turns;\n            pq.emplace(new_state.turns + dist(next_pos, goal), new_state);\n        }\n        \n        // Rotate subtrees\n        for (int v = 1; v < V; ++v) {\n            for (char rot : {'L', 'R'}) {\n                vector<Pos> new_fingers = current.fingers;\n                for (auto& f : new_fingers) f = f.rotate(rot);\n                auto rotated = State(current.turns + 1, current.pos, new_fingers);\n                if (visited.count(rotated) && visited[rotated] <= rotated.turns)\n                    continue;\n                visited[rotated] = rotated.turns;\n                pq.emplace(rotated.turns + dist(current.pos, goal), rotated);\n            }\n        }\n    }\n    return {};\n}\n\nint main() {\n    // Example input parsing; actual input handling depends on contest environment\n    int N = 20, M = 7, V = 8; \n    vector<pair<Pos, Pos>> tasks = {\n        {{0,0}, {15,5}}, {{3,2}, {17,7}}, {{5,5}, {18,18}}, \n        {{12,8}, {2,2}}, {{15,19}, {3,3}}, {{7,11}, {10,10}}, {{9,14}, {11,2}}\n    };\n    \n    cout << V << \"\\n\";\n    for (int i = 1; i < V; ++i) {\n        cout << \"0 \" << 1 << '\\n'; // star structure with length 1\n    }\n    cout << \"0 0\\n\"; // initial root position\n    \n    vector<bool> done(M, false);\n    Pos current = {0, 0};\n    int completed = 0;\n    \n    for (int steps = 0; completed < M; ++steps) {\n        pair<int, int> best = {INF, -1};\n        for (int i = 0; i < M; ++i) {\n            if (!done[i]) {\n                int cost = dist(current, tasks[i].first) + dist(tasks[i].first, tasks[i].second);\n                best = min(best, {cost, i});\n            }\n        }\n        int idx = best.second;\n        if (idx < 0) break;\n        \n        // Move to source\n        auto path1 = find_path(current, tasks[idx].first, V);\n        for (auto& s : path1) {\n            cout << s << '\\n';\n        }\n        current = tasks[idx].first;\n        \n        // Operation to grab\n        cout << \".\" + string(V - 1, '.') + string(V - 1, '.') << \"P\\n\";\n        \n        // Move to target\n        auto path2 = find_path(current, tasks[idx].second, V);\n        for (auto& s : path2) {\n            cout << s << '\\n';\n        }\n        \n        // Operation to release\n        cout << \".\" + string(V - 1, '.') + string(V - 1, '.') << \"P\\n\";\n        \n        done[idx] = true;\n        completed++;\n        current = tasks[idx].second;\n    }\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Box {\n    int x1, y1, x2, y2;\n    bool contains(int x, int y) const {\n        return x1 <= x && x <= x2 && y1 <= y && y <= y2;\n    }\n    int perimeter() const {\n        return 2 * (x2 - x1 + y2 - y1);\n    }\n    bool valid() const {\n        return x1 <= x2 && y1 <= y2;\n    }\n};\n\nint main() {\n    const int MAX_FISH = 5000;\n    vector<pair<int, int>> mackerel(MAX_FISH), sardine(MAX_FISH);\n    for (int i = 0; i < 2*MAX_FISH; ++i) {\n        int x, y; cin >> x >> y;\n        if (i < MAX_FISH) mackerel[i] = {x, y};\n        else sardine[i-MAX_FISH] = {x, y};\n    }\n    \n    const int kGridSize = 1e5 / 5; // 5x5 grid for finer clusters\n    vector<int> mack_grid(25);\n    int best_x = 0, best_y = 0;\n    for (auto& [x, y] : mackerel) {\n        int cx = x / kGridSize;\n        int cy = y / kGridSize;\n        if (++mack_grid[cx*5 + cy] > mack_grid[best_x*5 + best_y])\n            best_x = cx, best_y = cy;\n    }\n    \n    int x_min = best_x * kGridSize, x_max = x_min + kGridSize - 1;\n    int y_min = best_y * kGridSize, y_max = y_min + kGridSize - 1;\n    \n    // Find exact mackerel bounds\n    for (auto& [x, y] : mackerel) {\n        if (best_x*kGridSize <= x && x < (best_x+1)*kGridSize &&\n            best_y*kGridSize <= y && y < (best_y+1)*kGridSize) \n        {\n            x_min = min(x_min, x);\n            y_min = min(y_min, y);\n            x_max = max(x_max, x);\n            y_max = max(y_max, y);\n        }\n    }\n    \n    // Greedily expand boundaries\n    const int max_edge = 4e5;\n    Box best = {x_min, y_min, x_max, y_max};\n    int best_score = count_if(mackerel.begin(), mackerel.end(), \n        [&](auto& p) { return best.contains(p.first, p.second); })\n        - count_if(sardine.begin(), sardine.end(),\n        [&](auto& p) { return best.contains(p.first, p.second); });\n    \n    auto compute_score = [&](int l, int r, int b, int t) -> int {\n        if (l > r || b > t) return -1e9;\n        int p = 2*(r-l + t-b);\n        if (p > max_edge) return -1e9;\n        int macks = 0, sards = 0;\n        for (auto& [x, y] : mackerel)\n            if (l <= x && x <= r && b <= y && y <= t) macks++;\n        for (auto& [x, y] : sardine)\n            if (l <= x && x <= r && b <= y && y <= t) sards++;\n        return macks - sards;\n    };\n    \n    Box current = best;\n    while (true) {\n        int prev_score = best_score;\n        // Expand left, right, bottom, top one by one and track best\n        for (int dir = 0; dir < 4; ++dir) {\n            Box next = current;\n            if (dir == 0) next.x1 = max(0, next.x1 - 5000); // Larger step left\n            if (dir == 1) next.x2 = min((int)1e5, next.x2 + 5000); // Larger step right\n            if (dir == 2) next.y1 = max(0, next.y1 - 5000);\n            if (dir == 3) next.y2 = min((int)1e5, next.y2 + 5000);\n            \n            int score = compute_score(next.x1, next.x2, next.y1, next.y2);\n            if (score > best_score) {\n                best_score = score;\n                current = next;\n            }\n        }\n        if (prev_score == best_score) break; // No improvement\n        best = current;\n    }\n    \n    vector<pair<int, int>> poly = {\n        {current.x1, current.y1}, \n        {current.x1, current.y2}, \n        {current.x2, current.y2}, \n        {current.x2, current.y1}\n    };\n    cout << poly.size() << '\\n';\n    for (auto& [x, y] : poly) cout << x << ' ' << y << '\\n';\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, T;\n    double sigma;\n    cin >> N >> T >> sigma;\n    vector<pair<int,int>> rects(N);\n    \n    for (int i=0; i<N; ++i) {\n        int a, b;\n        cin >> a >> b;\n        rects[i] = {a + ceil(3*sigma), b + ceil(3*sigma)};\n        if (rects[i].first > 1e9) rects[i].first = 1'000'000'000;\n        if (rects[i].second > 1e9) rects[i].second = 1'000'000'000;\n    }\n    \n    // Simple strategy: Sort by max dimension, build vertical stack\n    for (int t=0; t<T; ++t) {\n        cout << N << '\\n';\n        int last_ref = -1;\n        for (int i=0; i<N; ++i) {\n            cout << i << \" 0 U \" << last_ref << '\\n';\n            last_ref = i;\n        }\n        cout.flush();\n        \n        if (t < T-1) {\n            int W, H;\n            cin >> W >> H;\n        }\n    }\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    cin >> N >> M >> H;\n    vector<int> A(N);\n    for (int& a : A) cin >> a;\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // Prepare order by highest beauty first\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return A[a] > A[b];\n    });\n\n    constexpr int UNVISITED = -2;\n    vector<int> parent(N, UNVISITED);\n    vector<bool> visited(N, false);\n\n    auto bfs = [&](int start) {\n        deque<int> q;\n        q.push_back(start);\n        visited[start] = true;\n        parent[start] = -1;\n        int current_height = 0;\n        \n        while (!q.empty() && current_height < H) {\n            int level_size = q.size();\n            current_height++;\n            \n            for (int i = 0; i < level_size; ++i) {\n                int u = q.front();\n                q.pop_front();\n                \n                for (int v : adj[u]) {\n                    if (!visited[v]) {\n                        visited[v] = true;\n                        if (current_height < H) {\n                            parent[v] = u;\n                        } else {\n                            parent[v] = -1;\n                        }\n                        q.push_back(v);\n                    }\n                }\n            }\n        }\n    };\n    \n    for (int u : order) {\n        if (!visited[u]) {\n            bfs(u);\n        }\n    }\n\n    // Ensure all nodes are assigned\n    for (int i = 0; i < N; ++i) {\n        if (parent[i] == UNVISITED) parent[i] = -1;\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        if (parent[i] == -1) continue;\n        int count = 0;\n        int temp = i;\n        while (parent[temp] != -1) {\n            temp = parent[temp];\n            count++;\n            if (count >= H) {\n                parent[i] = -1; // reset to root if exceeds height H\n                break;\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << parent[i] << (i == N-1 ? '\\n' : ' ');\n    }\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nvoid perform_shift(int type, int idx, int direction, vector<pair<char, int>>& operations) {\n    char dir_char;\n    if (type == 0) { // row\n        dir_char = (direction == 0) ? 'L' : 'R';\n        for (int i = 0; i < 20; ++i) operations.emplace_back(dir_char, idx);\n    } else { // column\n        dir_char = (direction == 0) ? 'U' : 'D';\n        for (int i = 0; i < 20; ++i) operations.emplace_back(dir_char, idx);\n    }\n}\n\nint main() {\n    int n = 20;\n    vector<string> board(n);\n    for (auto& row : board) cin >> row;\n\n    vector<pair<char, int>> operations;\n    vector<vector<bool>> processed(n, vector<bool>(n, false));\n\n    // Prioritize rows and columns by the number of Oni and least Fukunokami\n    for (int iter = 0; iter < 40; ++iter) {\n        vector<pair<int, pair<int, int>>> candidates;\n        for (int i = 0; i < n; ++i) {\n            int oni_count = 0, fuku_count = 0;\n            for (int j = 0; j < n; ++j) {\n                if (board[i][j] == 'x') ++oni_count;\n                if (board[i][j] == 'o') ++fuku_count;\n            }\n            if (oni_count > 0 && fuku_count == 0)\n                candidates.emplace_back(oni_count, make_pair(0, i)); // row i\n        }\n        for (int j = 0; j < n; ++j) {\n            int oni_count = 0, fuku_count = 0;\n            for (int i = 0; i < n; ++i) {\n                if (board[i][j] == 'x') ++oni_count;\n                if (board[i][j] == 'o') ++fuku_count;\n            }\n            if (oni_count > 0 && fuku_count == 0)\n                candidates.emplace_back(oni_count, make_pair(1, j)); // column j\n        }\n\n        if (candidates.empty()) break;\n\n        sort(candidates.rbegin(), candidates.rend());\n        auto best = candidates[0].second;\n        if (best.first == 0) { // row\n            perform_shift(0, best.second, 0, operations);\n            perform_shift(0, best.second, 1, operations);\n        } else { // column\n            perform_shift(1, best.second, 0, operations);\n            perform_shift(1, best.second, 1, operations);\n        }\n\n        // Update Board\n        if (best.first == 0) {\n            for (int j = 0; j < n; ++j) {\n                if (board[best.second][j] == 'x') board[best.second][j] = '.';\n            }\n        } else {\n            for (int i = 0; i < n; ++i) {\n                if (board[i][best.second] == 'x') board[i][best.second] = '.';\n            }\n        }\n    }\n\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    const int N = 100;\n    long long L = 500000;\n    \n    vector<long long> T(N);\n    for (auto& t : T) cin >> t;\n    \n    vector<int> a(N, -1), b(N, -1);\n    vector<long long> cnt(N, 0);\n    cnt[0] = 1; // Week 1: Employee 0\n    \n    int current = 0;\n    bool even = false;\n    \n    for (int i = 0; i < L - 1; ++i) {\n        // Assign to closest under-target employee\n        int next_best = -1;\n        long long max_deficit = 0;\n        for (int j = 0; j < N; ++j) {\n            if (cnt[j] < T[j] && (max_deficit == 0 || T[j] - cnt[j] > T[next_best] - cnt[next_best])) {\n                next_best = j;\n                max_deficit = T[j] - cnt[j];\n            }\n        }\n        \n        if (next_best == -1) {\n            // If all met, cycle safely\n            next_best = (current + 1) % N;\n        }\n        \n        if (even) {\n            a[current] = next_best;\n        } else {\n            b[current] = next_best;\n        }\n        cnt[next_best]++;\n        current = next_best;\n        even = !even;\n    }\n    \n    // Fill unset a/b with valid transitions\n    for (int i = 0; i < N; ++i) {\n        if (a[i] == -1) {\n            a[i] = (i + 1) % N;\n        }\n        if (b[i] == -1) {\n            b[i] = (i + 2) % N;\n        }\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        cout << a[i] << \" \" << b[i] << \"\\n\";\n    }\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct City {\n    int idx;\n    int cx, cy;\n    City(int id, int lx, int rx, int ly, int ry) \n        : idx(id), cx((lx + rx)/2), cy((ly + ry)/2) {}\n    bool operator<(const City& other) const {\n        return make_pair(cx, cy) < make_pair(other.cx, other.cy);\n    }\n};\n\nvector<vector<int>> form_groups(int N, const vector<int>& sizes, const vector<City>& cities) {\n    vector<vector<int>> groups;\n    int pos = 0;\n    for (int size : sizes) {\n        vector<int> group;\n        while (pos < N && group.size() < size) {\n            group.push_back(cities[pos++].idx);\n        }\n        groups.push_back(group);\n    }\n    // Adjust for leftover cities (unlikely due to valid input)\n    return groups;\n}\n\nvoid run_queries_and_connect(const vector<vector<int>>& groups, int L) {\n    for (const auto& group : groups) {\n        if (group.size() < 3) continue; // Only MST for size >=3\n        \n        for (int i = 0; i < group.size(); i += L-1) {\n            int end = min(i + L, int(group.size()));\n            if (end - i < 2) break;\n            \n            cout << \"? \" << (end - i) << \" \";\n            for (int j = i; j < end; ++j) {\n                cout << group[j] << \" \";\n            }\n            cout << endl;\n            \n            int edges_expected = end - i - 1;\n            for (int j = 0; j < edges_expected; ++j) {\n                int u, v; cin >> u >> v;\n                // Edges are only used for feedback, connection handled below\n            }\n        }\n    }\n}\n\nvoid output_result(const vector<vector<int>>& groups) {\n    cout << \"!\" << endl;\n    for (const auto& group : groups) {\n        for (int id : group) cout << id << \" \";\n        cout << endl;\n        \n        if (group.size() > 1) {\n            for (size_t i = 1; i < group.size(); ++i) {\n                cout << group[i-1] << \" \" << group[i] << endl;\n            }\n        }\n    }\n}\n\nvoid solve() {\n    int N, M, Q, L, W; \n    cin >> N >> M >> Q >> L >> W;\n    vector<int> sizes(M);\n    for (auto& s : sizes) cin >> s;\n    \n    vector<City> cities;\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry; \n        cin >> lx >> rx >> ly >> ry;\n        cities.emplace_back(i, lx, rx, ly, ry);\n    }\n    sort(cities.begin(), cities.end()); // Cluster by centers\n    \n    auto groups = form_groups(N, sizes, cities);\n    run_queries_and_connect(groups, L);\n    output_result(groups);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n}","ahc046":"#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define INF (1LL << 60)\ntypedef long long ll;\ntypedef tree<pair<pair<int, int>, vector<pair<int, int>>>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> oset;\n\nstruct VecHash {\n    size_t operator()(const vector<pair<int, int>>& v) const {\n        size_t seed = 0;\n        for (auto x : v) {\n            seed ^= x.first + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            seed ^= x.second + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n        }\n        return seed;\n    }\n};\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dir[] = {'U', 'D', 'L', 'R'};\n\nvoid astar(vector<pair<int, int>>& goals) {\n    int startX = goals.front().first;\n    int startY = goals.front().second;\n    goals.erase(goals.begin());\n    \n    oset pq;\n    map<pair<pair<int, int>, vector<pair<int, int>>>, int, VecHash> dist;\n    pq.insert({{0, {startX, startY, goals}}, {}});\n    dist[{{startX, startY}, goals}] = 0;\n\n    auto get_priority = [&](int x, int y, const auto& path_rem) {\n        int h = 0;\n        if (!path_rem.empty()) {\n            int nx = path_rem[0].first, ny = path_rem[0].second;\n            h = max(abs(nx - x), abs(ny - y));\n        }\n        for (size_t i = 1; i < path_rem.size(); ++i) {\n            int px = path_rem[i-1].first, py = path_rem[i-1].second;\n            int cx = path_rem[i].first, cy = path_rem[i].second;\n            h += max(abs(cx - px), abs(cy - py));\n        }\n        return h + (int)path_rem.size();\n    };\n\n    while (!pq.empty()) {\n        auto current = pq.begin()->second;\n        pq.erase(pq.begin());\n        int x = current.first;\n        int y = current.second.first;\n        auto remaining = current.second.second;\n        \n        if (remaining.empty()) {\n            for (auto& move : dist[current.first]) {\n                cout << move.first << ' ' << move.second << '\\n';\n            }\n            exit(0);\n        }\n\n        int curr_dist = dist[current.first];\n        for (int d = 0; d < 4; ++d) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx < 0 || nx >= 20 || ny < 0 || ny >= 20) continue;\n\n            bool blocked = false;\n            vector<pair<int, int>> new_rem = remaining;\n            if (new_rem.size() > 0 && new_rem[0] == make_pair(nx, ny)) {\n                new_rem.erase(new_rem.begin());\n            }\n\n            string actions = \"MS\";\n            for (char action : actions) {\n                int tx = x, ty = y, steps = 1;\n                if (action == 'S') {\n                    while (tx + dx[d] >= 0 && tx + dx[d] < 20 && ty + dy[d] >= 0 && ty + dy[d] < 20 && \n                           (new_rem.empty() || make_pair(tx+dx[d], ty+dy[d]) != new_rem[0])) {\n                        tx += dx[d]; ty += dy[d]; ++steps;\n                    }\n                    if (new_rem.size() > 0 && make_pair(tx, ty) != new_rem[0]) continue;\n                    if (!new_rem.empty() && make_pair(tx, ty) == new_rem[0]) {\n                        vector<pair<int, int>> next_rem = new_rem;\n                        next_rem.erase(next_rem.begin());\n                        new_rem = next_rem;\n                    }\n                } else {\n                    tx = nx; ty = ny;\n                }\n                \n                if (dist.count({{tx, ty}, new_rem}) && dist[{{tx, ty}, new_rem}] <= curr_dist + 1) continue;\n\n                dist[{{tx, ty}, new_rem}] = curr_dist + 1;\n                int priority = curr_dist + get_priority(tx, ty, new_rem) + 1;\n                pq.insert({{priority, {tx, ty, new_rem}}, {action, dir[d]}});\n                \n                if (action == 'S') dist[{{tx, ty}, new_rem}].push_back({action, dir[d]});\n            }\n        }\n    }\n}\n\nint main() {\n    int N, M; cin >> N >> M;\n    vector<pair<int, int>> goals(M);\n    for (int i = 0; i < M; ++i) {\n        int x, y; cin >> x >> y;\n        goals[i] = {x, y};\n    }\n    astar(goals);\n    return 0;\n}"},"16":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Ad {\n    int x, y;\n    int area;\n};\n\nconstexpr int GRID = 10'000;\nvector<vector<bool>> used(GRID, vector<bool>(GRID, false));\n\nbool is_valid(int x, int y, int w, int h) {\n    if (x < 0 || x >= GRID || y < 0 || y >= GRID || x + w > GRID || y + h > GRID)\n        return false;\n    for (int i = 0; i < w; ++i)\n        for (int j = 0; j < h; ++j)\n            if (used[x+i][y+j]) return false;\n    return true;\n}\n\nvoid mark_used(int x, int y, int w, int h) {\n    for (int i = 0; i < w; ++i)\n        for (int j = 0; j < h; ++j)\n            used[x+i][y+j] = true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    vector<Ad> ads(N);\n    for (auto& ad : ads) {\n        cin >> ad.x >> ad.y >> ad.area;\n    }\n    \n    // Sort to prioritize larger areas\n    sort(ads.begin(), ads.end(), [](const Ad& a, const Ad& b) {\n        return a.area > b.area;\n    });\n    \n    for (auto& ad : ads) {\n        int x = ad.x, y = ad.y;\n        bool placed = false;\n        \n        // Try to keep aspect ratio close to square\n        int w = 1, h = ad.area;\n        while (w * h < ad.area || w < h) {\n            w++;\n            h = (ad.area + w - 1) / w;\n        }\n        \n        // Check up to 5 units in all directions around desired point\n        for (int dx = -5; dx <= 5 && !placed; ++dx) {\n            for (int dy = -5; dy <= 5 && !placed; ++dy) {\n                int nx = x + dx, ny = y + dy;\n                \n                // Ensure rectangle contains (x,y)\n                if (nx <= x && nx + w > x + 1 && ny <= y && ny + h > y + 1) {\n                    if (is_valid(nx, ny, w, h)) {\n                        mark_used(nx, ny, w, h);\n                        cout << nx << ' ' << ny << ' ' << nx + w << ' ' << ny + h << '\\n';\n                        placed = true;\n                        break;\n                    }\n                }\n                // Swap dimensions and retry\n                if (is_valid(nx, ny, h, w)) {\n                    mark_used(nx, ny, h, w);\n                    cout << nx << ' ' << ny << ' ' << nx + h << ' ' << ny + w << '\\n';\n                    placed = true;\n                    break;\n                }\n            }\n        }\n        \n        // Fallback: place minimal valid rectangle at (x,y)\n        if (!placed) {\n            int nx = x, ny = y;\n            while (!is_valid(nx, ny, 1, 1)) {\n                nx++; if (nx >= GRID) { nx=0; ny++; }\n            }\n            mark_used(nx, ny, 1, 1);\n            cout << nx << ' ' << ny << ' ' << nx+1 << ' ' << ny+1 << '\\n';\n        }\n    }\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 50;\nint si, sj;\nint tiles[MAXN][MAXN];\nint points[MAXN][MAXN];\nvector<tuple<int, int, char>> dirs = {{-1, 0, 'U'}, {1, 0, 'D'}, {0, -1, 'L'}, {0, 1, 'R'}};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nstring best_path;\nint best_score = -1e9;\nchrono::steady_clock::time_point start_time;\n\nbool inside(int x, int y) {\n    return x >= 0 && x < MAXN && y >= 0 && y < MAXN;\n}\n\nvoid dfs(int x, int y, string path, int score, set<int> used_tiles, int steps_left) {\n    if (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() > 1900) \n        return;\n    \n    if (score > best_score) {\n        best_score = score;\n        best_path = path;\n    }\n    \n    if (steps_left == 0) return;\n\n    vector<tuple<int, int, char>> valid;\n    for (const auto &[dx, dy, dir] : dirs) {\n        int nx = x + dx, ny = y + dy;\n        if (!inside(nx, ny) || used_tiles.count(tiles[nx][ny])) continue;\n        valid.emplace_back(points[nx][ny], rng(), dir);\n    }\n    sort(valid.rbegin(), valid.rend());\n\n    for (const auto &[p, _, dir] : valid) {\n        for (const auto &[dx, dy, __] : dirs) {\n            if (dir == 'U' && dx == -1 && dy == 0 ||\n                dir == 'D' && dx == 1 && dy == 0 ||\n                dir == 'L' && dx == 0 && dy == -1 ||\n                dir == 'R' && dx == 0 && dy == 1) {\n                int nx = x + dx, ny = y + dy;\n                set<int> next_used = used_tiles;\n                next_used.insert(tiles[nx][ny]);\n\n                dfs(nx, ny, path + dir, score + points[nx][ny], next_used, steps_left - 1);\n                break; // Only execute once for selected direction\n            }\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> si >> sj;\n    start_time = chrono::steady_clock::now();\n\n    for (int i = 0; i < MAXN; ++i)\n        for (int j = 0; j < MAXN; ++j)\n            cin >> tiles[i][j];\n    for (int i = 0; i < MAXN; ++i)\n        for (int j = 0; j < MAXN; ++j)\n            cin >> points[i][j];\n\n    set<int> used = {tiles[si][sj]};\n\n    // Initial search with limited steps to prevent TLE\n    dfs(si, sj, \"\", points[si][sj], used, 5);\n    // Attempt a deeper search\n    if (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 1850)\n        dfs(si, sj, \"\", points[si][sj], used, 25);\n\n    cout << best_path << endl;\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n\nusing namespace std;\n\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dirs[] = {'U','D','L','R'};\n\nvoid solve() {\n    srand(time(nullptr));\n    for (int q = 0; q < 1000; ++q) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        string path;\n        vector<vector<bool>> visited(30, vector<bool>(30, false));\n        visited[si][sj] = true;\n\n        while (si != ti || sj != tj) {\n            vector<int> possible_moves;\n            for (int d = 0; d < 4; ++d) {\n                int ni = si + dr[d], nj = sj + dc[d];\n                if (ni >= 0 && ni < 30 && nj >= 0 && nj < 30 && !visited[ni][nj]) {\n                    possible_moves.push_back(d);\n                }\n            }\n            if (possible_moves.empty()) break;\n\n            // Always prefer deterministic progress if available\n            bool has_target_move = false;\n            int target_dir = -1;\n            for (int m : possible_moves) {\n                if ((m == 0 && si > ti) || (m == 1 && si < ti) || \n                    (m == 2 && sj > tj) || (m == 3 && sj < tj)) {\n                    target_dir = m;\n                    has_target_move = true;\n                    break;\n                }\n            }\n            \n            int move_dir;\n            if (has_target_move) {\n                move_dir = target_dir;\n            } else {\n                // Random valid move\n                move_dir = possible_moves[rand() % possible_moves.size()];\n            }\n\n            si += dr[move_dir];\n            sj += dc[move_dir];\n            visited[si][sj] = true;\n            path += dirs[move_dir];\n        }\n\n        cout << path << endl;\n        long long feedback;\n        cin >> feedback;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int SZ = 20;\nconst string VALID = \"ABCDEFGH\";\n\nstruct Matrix {\n    vector<string> data;\n    \n    Matrix() : data(SZ, string(SZ, 'A')) {\n        for (int i=0; i<SZ; ++i)\n            for (int j=0; j<SZ; ++j)\n                data[i][j] = VALID[rand() % VALID.size()];\n    }\n    \n    bool fits(int i, int j, const string& s, bool horiz) const {\n        int len = s.size();\n        for (int k=0; k < len; ++k) {\n            int x = horiz ? i : (i + k) % SZ;\n            int y = horiz ? (j + k) % SZ : j;\n            if (data[x][y] != '.' && data[x][y] != s[k]) \n                return false;\n        }\n        return true;\n    }\n    \n    int score(const vector<string>& S) const {\n        int total = 0;\n        for (const auto& s : S) {\n            for (int i=0; i<SZ; ++i) {\n                for (int j=0; j<SZ; ++j) {\n                    if (fits(i, j, s, true) || fits(i, j, s, false)) {\n                        ++total;\n                        break;\n                    }\n                }\n            }\n        }\n        return total;\n    }\n    \n    void fill_subseqs(const vector<string>& S) {\n        for (const auto& s : S) {\n            int len = s.size();\n            for (int try_=0; try_ < 10; ++try_) {\n                int i = rand() % SZ, j = rand() % SZ;\n                bool horiz = rand() % 2 == 0;\n                if (fits(i, j, s, horiz)) {\n                    for (int k=0; k < len; ++k) {\n                        int x = horiz ? i : (i + k) % SZ;\n                        int y = horiz ? (j + k) % SZ : j;\n                        if (data[x][y] == '.')\n                            data[x][y] = s[k];\n                    }\n                    break;\n                }\n            }\n        }\n    }\n    \n    void mutate() {\n        // Only fill empty spots with valid characters\n        for (int i=0; i < SZ; ++i)\n            for (int j=0; j < SZ; ++j)\n                if (data[i][j] == '.')\n                    data[i][j] = VALID[rand() % VALID.size()];\n    }\n    \n    void optimize(const vector<string>& S) {\n        int best = score(S);\n        auto best_mat = data;\n        int total_tries = 200;\n        \n        while (total_tries--) {\n            int i = rand() % SZ, j = rand() % SZ;\n            char original = data[i][j];\n            // Only change non-dot entries to avoid invalid chars\n            if (rand() % 3 == 0 && original != '.') {\n                char new_c = VALID[rand() % VALID.size()];\n                data[i][j] = new_c;\n                int temp = score(S);\n                if (temp > best) {\n                    best = temp;\n                    best_mat = data;\n                } else {\n                    data[i][j] = original;\n                }\n            }\n        }\n        data = best_mat;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    srand(time(nullptr));\n    \n    int M; cin >> M;\n    vector<string> seqs(M);\n    for (auto& s : seqs) cin >> s;\n    \n    Matrix mat;\n    mat.fill_subseqs(seqs);\n    mat.mutate();\n    mat.optimize(seqs);\n    \n    // Safety final check (though should be redundant)\n    for (auto& row : mat.data) {\n        for (char& c : row)\n            if (!('A' <= c && c <= 'H')) c = 'A';\n        cout << row << endl;\n    }\n}","ahc005":"#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <queue>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nvector<pair<char, int>> find_segment(int sx, int sy, int tx, int ty, const vector<string>& grid) {\n    int N = grid.size();\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    char dir[] = {'D', 'U', 'L', 'R'};\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> parent(N * N, {-1, -1});\n    q.emplace(sx, sy);\n    visited[sx][sy] = true;\n\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n        if (x == tx && y == ty) break;\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 && !visited[nx][ny] && grid[nx][ny] != '#') {\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n                parent[nx * N + ny] = {x, y};\n            }\n        }\n    }\n\n    vector<pair<char, int>> steps;\n    if (!visited[tx][ty]) return {};\n    int x = tx, y = ty;\n    while (x != sx || y != sy) {\n        auto [px, py] = parent[x * N + y];\n        char move;\n        if (px == x-1) move = 'D';\n        else if (px == x+1) move = 'U';\n        else if (py == y-1) move = 'R';\n        else move = 'L';\n        steps.emplace_back(move, 1);\n        x = px; y = py;\n    }\n    reverse(steps.begin(), steps.end());\n    return steps;\n}\n\nstring compute_optimal_route(int N, int si, int sj, const vector<string>& grid) {\n    vector<bool> covered_row(N, false), covered_col(N, false);\n    vector<pair<int, int>> path = {{si, sj}};\n    vector<pair<char, int>> moves;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                covered_row[i] = true;\n                covered_col[j] = true;\n            }\n        }\n    }\n\n    auto add_segment = [&](int x, int y) {\n        if (path.empty()) return;\n        auto segment = find_segment(path.back().first, path.back().second, x, y, grid);\n        if (segment.empty()) return;\n        moves.insert(moves.end(), segment.begin(), segment.end());\n        path.emplace_back(x, y);\n    };\n\n    int x = si, y = sj;\n    for (int row : {si-1, si+1}) {\n        if (row >= 0 && row < N && covered_row[row] && !covered_col[sj])\n            add_segment(row, sj);\n    }\n    for (int col : {sj-1, sj+1}) {\n        if (col >= 0 && col < N && covered_col[col] && !covered_row[si])\n            add_segment(si, col);\n    }\n\n    if (!moves.empty()) {\n        x = path.back().first;\n        y = path.back().second;\n    }\n    for (int i = 0; i < N; ++i) {\n        if (covered_row[i])\n            add_segment(i, y);\n    }\n    for (int j = 0; j < N; ++j) {\n        if (covered_col[j])\n            add_segment(x, j);\n    }\n    add_segment(si, sj);\n\n    string result;\n    for (auto [m, cnt] : moves) {\n        result += string(cnt, m);\n    }\n    return result;\n}\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (auto& s : grid) cin >> s;\n\n    cout << compute_optimal_route(N, si, sj, grid) << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconstexpr int INF = 1e9;\n\nstruct Task {\n    vector<int> skills;\n    vector<int> children;\n    int done_day = -1;\n    int indeg = 0;\n    bool started = false;\n};\n\nint N = 1000, M = 20;\nvector<Task> tasks;\nvector<vector<int>> finished_tasks; // finished_tasks[member] = list of tasks\nvector<array<int, 1024>> skill_estimates(M, array<int, 1024>{});\n\nvoid print_flush(const vector<pair<int, int>>& assignments) {\n    if (assignments.empty()) {\n        cout << \"0\\n\";\n    } else {\n        cout << assignments.size();\n        for (auto& [a, b] : assignments) cout << ' ' << a+1 << ' ' << b+1;\n        cout << '\\n';\n    }\n    fflush(stdout);\n}\n\nint estimate_time(int member, int task_id) {\n    int sum_excess = 0;\n    for (size_t k = 0; k < tasks[task_id].skills.size(); ++k) {\n        int req = tasks[task_id].skills[k];\n        int est = skill_estimates[member][k];\n        if (req > est) sum_excess += req - est;\n    }\n    return sum_excess == 0 ? 1 : max(1, sum_excess - 3 + (rand() % 7));\n}\n\nvoid update_skills(int member, int task_id, int days) {\n    auto& skills = skill_estimates[member];\n    int excess = max(1, days - 3 + (rand() % 7)) - 1;\n    for (size_t k = 0; k < tasks[task_id].skills.size(); ++k) {\n        int req = tasks[task_id].skills[k];\n        if (req > skills[k]) skills[k] = min(req, skills[k] + excess);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int K, R;\n    cin >> N >> M >> K >> R;\n    tasks.resize(N);\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            int d;\n            cin >> d;\n            tasks[i].skills.push_back(d);\n        }\n    }\n    \n    vector<vector<int>> deps(N);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        deps[u].push_back(v);\n        tasks[v].indeg++;\n    }\n    \n    priority_queue<pair<int, int>> pq; // (completion day estimate, task_id)\n    for (int i = 0; i < N; ++i) if (tasks[i].indeg == 0) pq.emplace(0, i);\n    \n    vector<bool> member_busy(M, false);\n    \n    int day = 1;\n    while (day <= 2000) {\n        vector<pair<int, int>> assignments;\n        for (int m = 0; m < M && !pq.empty(); ++m) {\n            while (!pq.empty() && tasks[pq.top().second].started) pq.pop();\n            if (pq.empty()) break;\n            int t = pq.top().second;\n            pq.pop();\n            \n            assignments.emplace_back(m, t);\n            tasks[t].started = true;\n        }\n        \n        print_flush(assignments);\n        \n        string input;\n        getline(cin >> ws, input);\n        if (input == \"-1\") break;\n        \n        istringstream iss(input);\n        int n;\n        iss >> n;\n        for (int _ = 0; _ < n; ++_) {\n            int m;\n            iss >> m;\n            --m;\n            \n            if (!member_busy[m]) {\n                int task = finished_tasks[m].back();\n                finished_tasks[m].pop_back();\n                tasks[task].done_day = day;\n                \n                int days_taken = day - tasks[task].started_day;\n                update_skills(m, task, days_taken);\n                \n                for (int child : deps[task]) {\n                    --tasks[child].indeg;\n                    if (tasks[child].indeg == 0) {\n                        pq.emplace(-estimate_time(m, child), child);\n                    }\n                }\n            }\n        }\n        \n        for (auto& [m, t] : assignments) {\n            if (!tasks[t].started) finished_tasks[m].push_back(t);\n            member_busy[m] = !tasks[t].started;\n            tasks[t].started_day = day;\n        }\n        \n        day++;\n    }\n    \n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1000;\nconst int K = 50;\nvector<tuple<int,int,int,int>> orders(N);\n\nint dist(int x1, int y1, int x2, int y2) {\n    return abs(x1-x2) + abs(y1-y2);\n}\n\nvector<int> select_orders() {\n    vector<int> best;\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n    sort(indices.begin(), indices.end(), [&](int i, int j){\n        auto [a1,b1,c1,d1] = orders[i];\n        auto [a2,b2,c2,d2] = orders[j];\n        return (dist(a1,b1,400,400) + dist(c1,d1,a1,b1)) <\n               (dist(a2,b2,400,400) + dist(c2,d2,a2,b2));\n    });\n    for (int i=0; i<K && i<N; ++i) best.push_back(indices[i]);\n    return best;\n}\n\nvector<pair<int,int>> build_route(const vector<int>& selected) {\n    // Track visited nodes efficiently\n    vector<bool> picked(N, false);\n    for (int idx : selected) picked[idx] = true;\n    \n    vector<pair<int,int>> route = {{400,400}};\n    vector<bool> delivered(selected.size(), false);\n    vector<tuple<int,int,int,int>> chosen;\n    for (int id : selected) chosen.emplace_back(orders[id]);\n    \n    for (int phase=0; phase < 2*K; ++phase) {\n        int best = -1;\n        auto& last = route.back();\n        int mn = INT_MAX;\n        \n        // Find next best node (pickup or delivery)\n        for (int i=0; i<K; ++i) {\n            int idx = selected[i];\n            auto [a,b,c,d] = orders[idx];\n            bool add_pickup = !count(route.begin(), route.end(), make_pair(a,b));\n            bool add_delivery = count(route.begin(), route.end(), make_pair(a,b)) && !delivered[i];\n            \n            if (add_pickup) {\n                int cur = dist(last.first, last.second, a, b);\n                if (cur < mn) {\n                    mn = cur;\n                    best = i * 2;  // Mark as pickup\n                }\n            } \n            if (add_delivery) {\n                int cur = dist(last.first, last.second, c, d);\n                if (cur < mn) {\n                    mn = cur;\n                    best = i * 2 + 1;  // Mark as delivery\n                }\n            }\n        }\n        if (best == -1) break;\n        \n        bool is_delivery = best % 2 == 1;\n        int order_idx = best / 2;\n        auto [a,b,c,d] = chosen[order_idx];\n        \n        if (is_delivery) {\n            route.emplace_back(c, d);\n            delivered[order_idx] = true;\n        } else {\n            route.emplace_back(a, b);\n        }\n    }\n    route.emplace_back(400, 400);\n    return route;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (auto& o : orders) \n        cin >> get<0>(o) >> get<1>(o) >> get<2>(o) >> get<3>(o);\n    \n    auto selected = select_orders();\n    auto path = build_route(selected);\n    \n    cout << K << \" \";\n    for (int id : selected) cout << id+1 << \" \";\n    cout << endl;\n    \n    cout << path.size() << \" \";\n    for (auto& [x,y] : path) cout << x << \" \" << y << \" \";\n    cout << endl;\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge {\n    int u, v, d, cost, idx;\n    bool operator<(const Edge& o) const { return idx < o.idx; }\n};\n\nstruct DSU {\n    vector<int> p;\n    DSU(int n) : p(n, -1) {}\n    int find(int u) { return p[u] < 0 ? u : p[u] = find(p[u]); }\n    bool unite(int u, int v) {\n        u = find(u), v = find(v);\n        if (u == v) return false;\n        if (p[u] > p[v]) swap(u, v);\n        p[u] += p[v];\n        p[v] = u;\n        return true;\n    }\n    int components() const {\n        int c = 0;\n        for (int x : p) if (x < 0) ++c;\n        return c;\n    }\n};\n\nint dist(pair<int,int> a, pair<int,int> b) {\n    int dx = a.first - b.first, dy = a.second - b.second;\n    return ::round(sqrt(dx*dx + dy*dy));\n}\n\nint main() {\n    const int N = 400, M = 1995;\n    vector<pair<int,int>> coords(N);\n    for (int i = 0; i < N; ++i) scanf(\"%d %d\", &coords[i].first, &coords[i].second);\n    \n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        scanf(\"%d %d\", &edges[i].u, &edges[i].v);\n        edges[i].d = dist(coords[edges[i].u], coords[edges[i].v]);\n        edges[i].idx = i;\n    }\n\n    DSU dsu(N);\n    vector<int> seen(M, false);\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int i, int j) {\n        return max(edges[i].d, 3*edges[i].d) < max(edges[j].d, 3*edges[j].d);\n    });\n\n    for (int i = 0; i < M; ++i) {\n        scanf(\"%d\", &edges[i].cost);\n        auto& e = edges[i];\n\n        bool accept = (dsu.find(e.u) != dsu.find(e.v));\n        seen[e.idx] = true;\n\n        if (!accept) {\n            int remain = M - 1 - i; // Edges left\n            int current = dsu.components();\n            double factor = 1.5 + 0.7 * (double)(current - 1) / (N - 1); // Tighten as we connect more components\n            if (remain > current - 1) {\n                // Look at next candidate edge (minimum possible cost)\n                int next_best = N * 10; // Default high if nothing is found\n                for (int j = 0; j < M; ++j) {\n                    if (!seen[j] && dsu.find(edges[j].u) != dsu.find(edges[j].v)) {\n                        next_best = min(next_best, edges[j].d);\n                    }\n                }\n                if (e.cost <= factor * next_best) accept = true;\n            }\n        }\n\n        printf(\"%d\\n\", accept ? 1 : 0);\n        fflush(stdout);\n\n        if (accept) dsu.unite(e.u, e.v);\n\n        if (dsu.components() == 1) {\n            // If already connected, reject all remaining edges to save time\n            for (++i; i < M; ++i) {\n                scanf(\"%d\", &edges[i].cost);\n                printf(\"0\\n\");\n                fflush(stdout);\n            }\n            break;\n        }\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\nusing Point = pair<int, int>;\nconst int MAX_TURNS = 300;\nconst int GRID_SIZE = 30;\n\nchar dirs[] = {'u','d','l','r','U','D','L','R'};\nint dx[] = {-1,1,0,0,-1,1,0,0};\nint dy[] = {0,0,-1,1,0,0,-1,1};\n\nvector<Point> humans;\nvector<pair<Point, int>> pets;\nvector<string> grid(GRID_SIZE+1, string(GRID_SIZE+1, '.'));\n\nbool isValid(int x, int y) {\n    return x >= 1 && x <= GRID_SIZE && y >= 1 && y <= GRID_SIZE;\n}\n\nbool hasAdjacentPet(int x, int y) {\n    for (int d = 0; d < 4; ++d) {\n        int nx = x + dx[d], ny = y + dy[d];\n        if (isValid(nx, ny) && grid[nx][ny] == '#') {\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid updateBarriers(string actions) {\n    set<Point> blocks;\n    for (int i = 0; i < (int)actions.size(); ++i) {\n        char c = actions[i];\n        if (c == '.' || isupper(c)) continue;\n        int d = find(dirs, dirs+8, c) - dirs;\n        int x = humans[i].first + dx[d], y = humans[i].second + dy[d];\n        if (isValid(x, y) && grid[x][y] == '.') {\n            grid[x][y] = '#';\n        }\n    }\n}\n\nstring decideActions() {\n    string result(humans.size(), '.');\n    \n    // Attempt to move to outer corners first\n    for (int i = 0; i < (int)humans.size(); ++i) {\n        int x = humans[i].first, y = humans[i].second;\n        for (char c : {'U','D','L','R'}) {\n            int d = find(dirs, dirs+8, c) - dirs;\n            int nx = x + dx[d], ny = y + dy[d];\n            if (isValid(nx, ny) && grid[nx][ny] == '.') {\n                result[i] = c;\n                break;\n            }\n        }\n        if (result[i] != '.') continue;\n        // Next try to block\n        for (char c : {'u','d','l','r'}) {\n            int d = find(dirs, dirs+4, c) - dirs;\n            int nx = x + dx[d], ny = y + dy[d];\n            if (isValid(nx, ny) && grid[nx][ny] == '.' && !hasAdjacentPet(nx,ny)) {\n                result[i] = c;\n                break;\n            }\n        }\n    }\n    return result;\n}\n\n// Update human positions\nvoid executeActions(const string& actions) {\n    for (int i = 0; i < (int)actions.size(); ++i) {\n        char act = actions[i];\n        if (islower(act)) continue; // Only move if uppercase\n        int d = find(dirs+4, dirs+8, act) - (dirs+4);\n        int x = humans[i].first + dx[d+4], y = humans[i].second + dy[d+4];\n        if (isValid(x,y) && grid[x][y] == '.') {\n            humans[i] = {x, y};\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read pets\n    int N; cin >> N;\n    for (int i = 0; i < N; ++i) {\n        int x, y, t; \n        cin >> x >> y >> t;\n        pets.push_back({{x,y}, t});\n        grid[x][y] = 'O'; // Mark with a temp char for pets\n    }\n    \n    // Read humans\n    int M; cin >> M;\n    humans.resize(M);\n    for (auto& [x, y] : humans) {\n        cin >> x >> y;\n    }\n    \n    // Clear pet markings for actual use\n    for (auto& [p, t] : pets) {\n        grid[p.first][p.second] = '.';\n    }\n    \n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        string actions = decideActions();\n        cout << actions << endl;\n        \n        // Read dummy pet movements; actual movements not tracked here\n        for (int i = 0; i < N; ++i) {\n            string _;\n            cin >> _;\n        }\n        \n        executeActions(actions);\n        updateBarriers(actions);\n    }\n    \n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    string path;\n    int remain_downs = ti - si;\n    int remain_rights = tj - sj;\n\n    // Generate necessary moves first\n    auto add_moves = [&](int count, char move) {\n        for (int i = 0; i < count; ++i) {\n            path += move;\n            // Add redundancy in the same direction to maximize chances\n            path += move;\n            if (path.size() >= 200) break;\n        }\n    };\n\n    // Ensure each step in the right direction is added at least twice\n    while (remain_downs > 0 || remain_rights > 0) {\n        if (remain_downs > 0) {\n            path += \"DD\";\n            remain_downs--;\n        }\n        if (remain_rights > 0) {\n            path += \"RR\";\n            remain_rights--;\n        }\n    }\n\n    // If needed, pad with more down and right moves\n    while (path.size() < 200) {\n        path += \"D\";\n        if (path.size() < 200) path += \"R\";\n    }\n\n    cout << path.substr(0, 200) << endl;\n}","ahc010":"#include <bits/stdc++.h>\n#include <random>\nusing namespace std;\n\nconst int N = 30;\nint T[N][N], R[N][N], bestR[N][N];\nint dirs[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1},\n};\nint di[4] = {0, -1, 0, 1}, dj[4] = {-1, 0, 1, 0};\n\nmt19937 mt(time(nullptr));\n\nlong long eval(int rotate[N][N]) {\n    int tcopy[N][N];\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        tcopy[i][j] = rotate[i][j];\n        while (tcopy[i][j] < 0) tcopy[i][j] += 8;\n        tcopy[i][j] %= 8;\n    }\n\n    vector<int> lengths;\n    bool vis[N][N][4] = {};\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        for (int d=0; d<4; ++d) {\n            if (vis[i][j][d]) continue;\n            vector<tuple<int, int, int>> path;\n            int ci=i, cj=j, cd=d, len=0;\n            while (true) {\n                path.emplace_back(ci, cj, cd);\n                vis[ci][cj][cd] = true;\n                int nd = dirs[tcopy[ci][cj]][cd];\n                if (nd == -1) break;\n                ci += di[nd];\n                cj += dj[nd];\n                if (ci < 0 || ci >= N || cj < 0 || cj >= N) break;\n                cd = (nd + 2) % 4;\n                if (vis[ci][cj][cd]) {\n                    for (auto [pi, pj, pd] : path) {\n                        if (pi == ci && pj == cj && pd == cd) {\n                            len = path.size() - (path.end() - find(path.begin(), path.end(), make_tuple(pi, pj, pd)));\n                            break;\n                        }\n                    }\n                    break;\n                }\n            }\n            if (len > 0) {\n                lengths.push_back(len);\n                for (auto& [pi, pj, pd] : path) vis[pi][pj][pd] = true;\n            }\n        }\n    }\n    sort(lengths.rbegin(), lengths.rend());\n    long long l1 = (lengths.size() > 0) ? lengths[0] : 0;\n    long long l2 = (lengths.size() > 1) ? lengths[1] : 0;\n    return l1 * l2;\n}\n\nlong long calc() {\n    static int rotate[N][N];\n    memcpy(rotate, R, sizeof(rotate));\n    long long ans = 0;\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        long long best = 0;\n        for (int k=0; k<4; ++k) {\n            rotate[i][j] = (rotate[i][j] + 1) % 8;\n            long long score = eval(rotate);\n            if (score > best) best = score;\n        }\n        rotate[i][j] = (rotate[i][j] - best + 8) % 8;\n        ans += best;\n    }\n    return ans;\n}\n\nint main() {\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        char c; cin >> c;\n        T[i][j] = c - '0';\n    }\n    memcpy(R, T, sizeof(R));\n\n    auto update_ans = [&]() {\n        long long cur_score = eval(bestR);\n        long long score = eval(R);\n        if (score > cur_score) memcpy(bestR, R, sizeof(bestR));\n    };\n\n    const double START_TEMP = 1e6, END_TEMP = 1e-3, RATE = 0.9999;\n    double temp = START_TEMP;\n    long long cur_score = eval(R), best_score = cur_score;\n    while (temp > END_TEMP) {\n        for (int _=0; _<max(1, N*N * temp / START_TEMP); ++_) {\n            int i = mt() % N, j = mt() % N;\n            int prev = R[i][j];\n\n            long long best_rotate = -1;\n            long long best_gain = -1e18;\n            vector<long long> scores(4);\n            for (int delta=0; delta<4; ++delta) {\n                R[i][j] = (prev + delta) % 8;\n                scores[delta] = eval(R);\n                if (scores[delta] - cur_score > best_gain) {\n                    best_gain = scores[delta] - cur_score;\n                    best_rotate = delta;\n                }\n            }\n\n            if (best_rotate == -1 || exp((scores[best_rotate] - cur_score) / temp) < (mt() % 10000)/10000.) {\n                int rnd = mt() % 4;\n                if (scores[rnd] <= cur_score && exp((scores[rnd] - cur_score) / temp) < (mt() % 10000)/10000.) {\n                    R[i][j] = prev;\n                    continue;\n                }\n                best_rotate = rnd;\n            }\n\n            R[i][j] = (prev + best_rotate) % 8;\n            cur_score = scores[best_rotate];\n            update_ans();\n        }\n        best_score = max(best_score, cur_score);\n        temp *= RATE;\n    }\n\n    memcpy(R, bestR, sizeof(R));\n    for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) {\n        int diff = 0;\n        while ((bestR[i][j] - T[i][j] - diff) % 8 != 0 && (bestR[i][j] - T[i][j] - diff) % 8 != 4) ++diff;\n        while (diff < 0) diff += 8;\n        cout << diff % 4;\n    }\n    cout << endl;\n}","ahc011":"#include <algorithm>\n#include <cstdio>\n#include <queue>\n#include <string>\n#include <vector>\nusing namespace std;\n\nint n, t_limit;\nvector<vector<int>> board;\npair<int, int> empty_cell;\nconst int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};\n\nbool in_bounds(int x, int y) { return 0 <= x && x < n && 0 <= y && y < n; }\n\nint count_connections(int x, int y) {\n    int mask = board[x][y];\n    int count = 0;\n    int dirs[] = {8, 1, 2, 4}; // Down, left, up, right connection checks\n    for (int i=0; i<4; ++i) {\n        int nx = x + dx[i], ny = y + dy[i];\n        if (in_bounds(nx, ny) && board[nx][ny] && (board[nx][ny] & (1 << 3-i))) {\n            ++count;\n        }\n    }\n    return count;\n}\n\nbool can_fit(int x, int y) {\n    int mask = board[x][y];\n    int required = __builtin_popcount(mask);\n    int current = count_connections(x, y);\n    return required - 1 == current;\n}\n\npair<int, int> find_valid_move() {\n    int best = -1e9, best_x = -1, best_y = -1;\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (board[i][j] == 0) continue;\n            int edges = __builtin_popcount(board[i][j]);\n            int current = edges ? count_connections(i, j) : -1;\n            int gain = edges - 1 - current;\n            if (gain > best) {\n                best = gain;\n                best_x = i; best_y = j;\n            }\n        }\n    }\n    return {best_x, best_y};\n}\n\npair<string, bool> shortest_path_to_empty(int sx, int sy) {\n    queue<pair<pair<int, int>, string>> q;\n    vector<vector<bool>> visited(n, vector<bool>(n, false));\n    q.push({{sx, sy}, \"\"});\n    visited[sx][sy] = true;\n    \n    while (!q.empty()) {\n        auto [pos, path] = q.front();\n        q.pop();\n        int x = pos.first, y = pos.second;\n        \n        if (board[x][y] == 0) // Found empty cell\n            return {path, true};\n        \n        for (int i=0; i<4; ++i) {\n            int nx = x + dx[i], ny = y + dy[i];\n            if (in_bounds(nx, ny) && !visited[nx][ny] && board[nx][ny] != 0) {\n                visited[nx][ny] = true;\n                char move = \"D\"[i]; // D=down, L, U, R = left, up, right\n                if (move == 'L') move = 'R';\n                else if (move == 'R') move = 'L';\n                q.push({{nx, ny}, path + move});\n            }\n        }\n    }\n    return {\"\", false};\n}\n\nvoid execute_moves(string path, int& ex, int& ey) {\n    for (char c : path) {\n        switch (c) {\n            case 'U': swap(board[ex][ey], board[ex-1][ey]); --ex; break;\n            case 'D': swap(board[ex][ey], board[ex+1][ey]); ++ex; break;\n            case 'L': swap(board[ex][ey], board[ex][ey-1]); --ey; break;\n            case 'R': swap(board[ex][ey], board[ex][ey+1]); ++ey; break;\n        }\n    }\n}\n\nint main() {\n    scanf(\"%d %d\", &n, &t_limit);\n    board.resize(n, vector<int>(n));\n    for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) {\n        char c;\n        scanf(\" %c\", &c);\n        board[i][j] = isdigit(c) ? c - '0' : c - 'a' + 10;\n        if (!board[i][j]) empty_cell = {i, j};\n    }\n    \n    string operations;\n    int steps = 0;\n    while (steps < t_limit) {\n        auto [x, y] = find_valid_move();\n        if (x == -1 || can_fit(x, y)) break;\n        \n        auto [dir, found] = shortest_path_to_empty(x, y);\n        if (!found) break;\n        reverse(dir.begin(), dir.end());\n        execute_moves(dir, empty_cell.first, empty_cell.second);\n        operations += dir;\n        steps += dir.size();\n    }\n    \n    printf(\"%s\\n\", operations.c_str());\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <array>\n\nusing namespace std;\n\nint main() {\n    vector<array<int, 4>> lines;\n    const int boundary = 20000;\n    // Finer steps in the inner region, coarser outside.\n    for (int x = -boundary; x <= boundary; x += 2500) {\n        if (x == 0) continue; // skip the redundant x=0 line\n        lines.emplace_back(array<int, 4>{{x, -boundary, x, boundary}});\n    }\n    \n    for (int y = -boundary; y <= boundary; y += 2500) {\n        if (y == 0) continue; // skip y=0\n        lines.emplace_back(array<int, 4>{{-boundary, y, boundary, y}});\n    }\n    \n    // Diagonal lines with slight offsets for finer partitioning\n    for (int i = 0; i <= 6; ++i) {\n        int shift = 1000 * i;\n        lines.emplace_back(array<int, 4>{{-boundary + shift, -boundary, boundary - shift, boundary}});\n        lines.emplace_back(array<int, 4>{{-boundary + shift, boundary, boundary - shift, -boundary}});\n    }\n    \n    // Ensuring the number of lines is under the limit\n    while (lines.size() > 100) {\n        lines.pop_back();\n    }\n    \n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line[0] << ' ' << line[1] << ' ' << line[2] << ' ' << line[3] << endl;\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nusing ll = long long;\nvector<vector<bool>> visited;\nvector<tuple<int, int, int, int, int, int, int, int>> ops;\n\nbool valid(int x, int y) {\n    return 0 <= x && x < N && 0 <= y && y < N && !visited[x][y];\n}\n\n// Directions: right, down, diagonal (both 45 degrees)\nint dx[] = {1, 0, 1, -1};\nint dy[] = {0, 1, 1, 1};\n\nint main() {\n    cin >> N >> M;\n    visited.assign(N, vector<bool>(N, false));\n    vector<pair<int, int>> initials;\n\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        initials.emplace_back(x, y);\n        visited[x][y] = true;\n    }\n\n    for (auto &[x, y] : initials) {\n        // For each initial dot, check possible rectangles\n        for (int d = 0; d < 4; ++d) {\n            for (int len = 1; len <= min(N, 3); ++len) {\n                int nx = x + dx[d] * len;\n                int ny = y + dy[d] * len;\n                if (!valid(nx, ny)) continue;\n\n                int nx2 = x + (d < 2 ? dx[d^1] : dx[(d+2)%4]) * len;\n                int ny2 = y + (d < 2 ? dy[d^1] : dy[(d+2)%4]) * len;\n                int ox = x + (d < 2 ? dx[d] : dx[(d+1)%4]);\n                int oy = y + (d < 2 ? dy[d] : dy[(d+1)%4]);\n\n                if (!valid(nx2, ny2) || !visited[ox][oy] || (!visited[nx][ny] && !visited[nx2][ny2]))\n                    continue;\n\n                // Check edges for no existing points except at vertices\n                bool ok = true;\n                // Check edge between (x,y) and (ox, oy):\n                for (int i=1; i < len; ++i) {\n                    int mx = x + dx[d]*i, my = y + dy[d]*i;\n                    if (visited[mx][my]) { ok = false; break; }\n                }\n                if (!ok) continue;\n\n                // Check between (nx, ny) to (nx2, ny2), but not needed if !visited[nx][ny], ok\n                if (!visited[nx2][ny2]) ok = false; // Must be existing for third point if nx,ny is new\n\n                if (ok) {\n                    visited[nx][ny] = true;\n                    ops.emplace_back(nx, ny, x, y, ox, oy, nx2, ny2);\n                    // Only once for each new point added\n                    break;\n                }\n            }\n        }\n    }\n\n    cout << ops.size() << endl;\n    for (auto &[x, y, x2, y2, x3, y3, x4, y4] : ops) {\n        // Output order is (new point, other three forming the rectangle)\n        cout << x << ' ' << y << ' ' \n             << x2 << ' ' << y2 << ' ' \n             << x3 << ' ' << y3 << ' ' \n             << x4 << ' ' << y4 << endl;\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int SIZE = 10;\nvector<vector<int>> grid(SIZE, vector<int>(SIZE, 0));\nvector<pair<int, int>> emptyCells;\nunordered_map<int, int> flavorCount = {{1,0}, {2,0}, {3,0}};\nunordered_map<int, pair<int, int>> centroids; // flavor -> centroid (sum_x, sum_y)\n\nvoid updateCenterMass(int flavor, int x, int y) {\n    flavorCount[flavor]++;\n    centroids[flavor].first += x;\n    centroids[flavor].second += y;\n}\n\nvoid applyGravity(char dir) {\n    if (dir == 'F') {\n        for (int col = 0; col < SIZE; ++col) {\n            for (int row = SIZE-2; row >= 0; --row) {\n                if (grid[row][col] && !grid[row+1][col]) {\n                    int r = row+1;\n                    while (r < SIZE && !grid[r][col]) r++;\n                    --r;\n                    swap(grid[r][col], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'B') {\n        // B direction logic\n        for (int col = 0; col < SIZE; ++col) {\n            for (int row = 1; row < SIZE; ++row) {\n                if (grid[row][col] && !grid[row-1][col]) {\n                    int r = row-1;\n                    while (r >= 0 && !grid[r][col]) r--;\n                    ++r;\n                    swap(grid[r][col], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'L') {\n        // L direction logic\n        for (int row = 0; row < SIZE; ++row) {\n            for (int col = 1; col < SIZE; ++col) {\n                if (grid[row][col] && !grid[row][col-1]) {\n                    int c = col-1;\n                    while (c >= 0 && !grid[row][c]) c--;\n                    ++c;\n                    swap(grid[row][c], grid[row][col]);\n                }\n            }\n        }\n    } else if (dir == 'R') {\n        // R direction logic\n        for (int row = 0; row < SIZE; ++row) {\n            for (int col = SIZE-2; col >= 0; --col) {\n                if (grid[row][col] && !grid[row][col+1]) {\n                    int c = col+1;\n                    while (c < SIZE && !grid[row][c]) c++;\n                    --c;\n                    swap(grid[row][c], grid[row][col]);\n                }\n            }\n        }\n    }\n}\n\nchar chooseDirection(int flavor, int x, int y) {\n    pair<int, int> bestDir = {0, 0};\n    int currentScore = 1e9;\n    for (auto& [dx, dy] : {pair{-1,0}, {1,0}, {0,-1}, {0,1}}) {\n        int nx = x + dx*(SIZE-1), ny = y + dy*(SIZE-1);\n        if (flavorCount[flavor] == 0) {\n            if (abs(nx) + abs(ny) < currentScore) {\n                currentScore = abs(nx) + abs(ny);\n                bestDir = {dx, dy};\n            }\n        } else {\n            auto cm = centroids[flavor];\n            int cx = cm.first / flavorCount[flavor];\n            int cy = cm.second / flavorCount[flavor];\n            int newScore = abs(nx - cx) + abs(ny - cy);\n            if (newScore < currentScore) {\n                currentScore = newScore;\n                bestDir = {dx, dy};\n            }\n        }\n    }\n    return bestDir == make_pair(-1, 0) ? 'F' : \n           bestDir == make_pair(1, 0) ? 'B' : \n           bestDir == make_pair(0, -1) ? 'L' : 'R';\n}\n\nint main() {\n    vector<int> flavors(100);\n    for (int& f : flavors) cin >> f;\n    \n    for (int t = 0; t < 100; ++t) {\n        emptyCells.clear();\n        for (int i = 0; i < SIZE; ++i)\n            for (int j = 0; j < SIZE; ++j)\n                if (!grid[i][j])\n                    emptyCells.emplace_back(i, j);\n        \n        int p; cin >> p;\n        --p;\n        auto [x, y] = emptyCells[p];\n        int f = flavors[t];\n        grid[x][y] = f;\n        updateCenterMass(f, x, y);\n\n        if (t == 99) break;\n        \n        char dir = chooseDirection(f, x, y);\n        cout << dir << '\\n';\n        cout.flush();\n        applyGravity(dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nstring generate_graph(int vertices, int edges) {\n    vector<bool> visited(vertices * (vertices-1) / 2, false);\n    string result(vertices * (vertices-1) / 2, '0');\n    \n    int current = 0;\n    for (int j=1; j<=edges; ++j) {\n        if (current >= visited.size()) current = 0; // Fallback to start if out\n        while (result[current] == '1' || visited[current]) {\n            ++current;\n            if (current >= visited.size()) current = 0;\n        }\n        result[current] = '1';\n        visited[current] = true;\n    }\n    return result;\n}\n\nint main() {\n    int M;\n    double eps;\n    cin >> M >> eps;\n    \n    const int N = 20;\n    cout << N << endl;\n    \n    vector<string> precomputed(M);\n    for (int i=0; i < M; ++i) {\n        precomputed[i] = generate_graph(N, i);\n        cout << precomputed[i] << endl;\n    }\n    cout << flush;\n    \n    // Precompute edge counts for faster lookup\n    vector<int> edges_counts(M);\n    for (int i=0; i < M; ++i) {\n        edges_counts[i] = count(precomputed[i].begin(), precomputed[i].end(), '1');\n    }\n    \n    for (int k=0; k < 100; ++k) {\n        string H;\n        cin >> H;\n        int current_edges = count(H.begin(), H.end(), '1');\n        \n        // Match using edge count distance\n        int best_match = 0;\n        int min_diff = INT_MAX;\n        for (int m=0; m < M; ++m) {\n            int diff = abs(current_edges - edges_counts[m]);\n            if (diff < min_diff) {\n                min_diff = diff;\n                best_match = m;\n            }\n        }\n        cout << best_match << endl << flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing i32 = int;\nusing i64 = long long;\nusing vi = vector<i32>;\nusing pii = pair<i32, i32>;\nusing Graph = vector<vector<pii>>;\nconst i64 INF = 1e18;\n\npair<vector<i64>, vector<i64>> dijkstra(int start, const Graph& adj, int N) {\n    using Node = pair<i64, i32>;\n    priority_queue<Node, vector<Node>, greater<>> pq;\n    vector<i64> dist(N, INF), cnt(N, 0);\n    dist[start] = 0;\n    cnt[start] = 1;\n    pq.emplace(0, start);\n\n    while (!pq.empty()) {\n        auto [current_dist, u] = pq.top();\n        pq.pop();\n        if (current_dist != dist[u]) continue;\n\n        for (auto& [v, w] : adj[u]) {\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                cnt[v] = cnt[u];\n                pq.emplace(dist[v], v);\n            } else if (dist[u] + w == dist[v]) {\n                cnt[v] += cnt[u];\n            }\n        }\n    }\n    return {dist, cnt};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    i32 N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    Graph adj(N);\n    vector<tuple<i32, i32, i32>> edges(M);\n    for (i32 i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u, --v;\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n        edges[i] = {u, v, w};\n    }\n\n    vector<i64> edge_importance(M, 0);\n    for (i32 i = 0; i < N; ++i) {\n        auto [dist, cnt] = dijkstra(i, adj, N);\n        for (i32 j = 0; j < M; ++j) {\n            auto& [u, v, w] = edges[j];\n            if (dist[u] + w == dist[v]) \n                edge_importance[j] += cnt[u] * (N - cnt[v]);\n            if (dist[v] + w == dist[u])\n                edge_importance[j] += cnt[v] * (N - cnt[u]);\n        }\n    }\n\n    vector<pair<i64, i32>> order;\n    for (i32 i = 0; i < M; ++i) order.emplace_back(edge_importance[i], i);\n    sort(order.rbegin(), order.rend());\n\n    vi days(M, -1);\n    vector<i64> current_imp(D, 0);\n    priority_queue<pii, vector<pii>, greater<>> day_pq;\n    for (i32 i = 0; i < D; ++i) day_pq.push({0, i});\n\n    for (auto& [imp, idx] : order) {\n        auto [min_imp, day] = day_pq.top();\n        day_pq.pop();\n        days[idx] = day + 1;\n        day_pq.push({min_imp + imp, day});\n        current_imp[day] += imp;\n    }\n\n    for (auto d : days) cout << d << ' ';\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n    bool operator<(const Point& o) const {\n        return tie(x, y, z) < tie(o.x, o.y, o.z);\n    }\n};\n\nvector<vector<string>> input;  // Store each 2D silhouette\nvector<vector<vector<int>>> dp; // Precompute front and right silhouettes\nvector<vector<vector<int>>> blocks;\n\nvector<vector<vector<int>>> construct(int idx) {\n    auto& sil = input[idx*2];\n    auto& sir = input[idx*2 + 1];\n    int n = sil.size();\n    vector<vector<vector<int>>> cube(n, vector<vector<int>>(n, vector<int>(n)));\n    vector<vector<int>> vis(n, vector<int>(n, 0));\n    int cnt = 1;\n    \n    auto addBlock = [&](int x, int y, int z) {\n        cube[x][y][z] = cnt;\n    };\n    \n    // Process intersections to use same blocks for both configurations\n    for (int z = 0; z < n; z++) {\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (dp[idx][x][z] && dp[idx + 2][y][z] && !vis[x][y] && !blocks[x][y][z]) {\n                    blocks[x][y][z] = cnt;\n                    addBlock(x, y, z);\n                    vis[x][y]++;\n                }\n            }\n        }\n    }\n    \n    // Fill remaining regions needed by the first silhouette\n    for (int z = 0; z < n; z++) {\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (dp[idx][x][z] && !blocks[x][y][z]) {\n                    addBlock(x, y, z);\n                    blocks[x][y][z] = cnt++;\n                }\n            }\n        }\n    }\n    return cube;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D;\n    cin >> D;\n    input.resize(4);\n    \n    for (int t = 0; t < 4; t++) {\n        for (int i = 0; i < D; i++) {\n            string s;\n            cin >> s;\n            input[t].push_back(s);\n        }\n    }\n    \n    // Precompute front and right silhouettes\n    dp.assign(4, vector<vector<int>>(D, vector<int>(D)));\n    for (int t = 0; t < 4; t += 2) {\n        for (int z = 0; z < D; z++) {\n            for (int x = 0; x < D; x++) {\n                for (int y = 0; y < D; y++) {\n                    if (input[t][z][x] == '1') dp[t][x][z]++;\n                    if (input[t+1][z][y] == '1') dp[t+2][y][z]++;\n                }\n            }\n        }\n    }\n    \n    blocks.resize(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    auto cube1 = construct(0);\n    blocks.assign(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    auto cube2 = construct(1);\n    \n    // Count blocks used\n    int max_block = 0;\n    for (const auto& c1 : cube1) for (const auto& row : c1) \n        for (int block : row) max_block = max(max_block, block);\n    for (const auto& c2 : cube2) for (const auto& row : c2) \n        for (int block : row) max_block = max(max_block, block);\n    \n    cout << max_block << '\\n';\n    \n    // Output cubes\n    for (auto& c : cube1) {\n        for (auto& r : c) \n            for (int val : r) cout << val << \" \";\n        cout << \"\\n\";\n    }\n    for (auto& c : cube2) {\n        for (auto& r : c) \n            for (int val : r) cout << val << \" \";\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int, int> Point;\n\nll dist(const Point& a, const Point& b) {\n    return (a.first - b.first) * (ll)(a.first - b.first) +\n           (a.second - b.second) * (ll)(a.second - b.second);\n}\n\nstruct Edge {\n    int u, v, w, id;\n};\n\nstruct UnionFind {\n    vector<int> parent, rank;\n    UnionFind(int n) : parent(n), rank(n, 1) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int x) {\n        return parent[x] == x ? x : parent[x] = find(parent[x]);\n    }\n    bool unite(int x, int y) {\n        x = find(x); y = find(y);\n        if (x == y) return false;\n        if (rank[x] > rank[y]) swap(x, y);\n        parent[x] = y;\n        if (rank[x] == rank[y]) ++rank[y];\n        return true;\n    }\n};\n\nvoid solve() {\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<Point> stations(N);\n    for (auto& st : stations) cin >> st.first >> st.second;\n\n    vector<Edge> edges(M);\n    for (auto& e : edges) {\n        cin >> e.u >> e.v >> e.w;\n        --e.u; --e.v;\n        e.id = e.u < e.v ? e.u : e.v;\n    }\n\n    vector<Point> residents(K);\n    for (auto& res : residents) cin >> res.first >> res.second;\n\n    vector<bool> used(M);\n    UnionFind uf(N);\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.w < b.w;\n    });\n\n    // MST using Kruskal's algorithm\n    for (auto& e : edges) {\n        if (uf.unite(e.u, e.v)) used[e.id] = true;\n    }\n\n    // Assign powers\n    vector<int> power(N, 0);\n    for (auto& [x, y] : residents) {\n        ll min_d = LLONG_MAX;\n        int best = 0;\n        for (int i=0; i < N; ++i) {\n            ll d = dist(stations[i], {x, y});\n            if (uf.find(i) == uf.find(0) && d < min_d) {\n                min_d = d;\n                best = i;\n            }\n        }\n        if (best != -1) power[best] = max(power[best], (int)ceil(sqrt(min_d)));\n    }\n\n    // Output results\n    for (int p : power) cout << p << ' ';\n    cout << '\\n';\n    for (bool u : used) cout << u << ' ';\n    cout << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 30;\nvector<vector<int>> grid(N, vector<int>(N));\nvector<tuple<int, int, int, int>> operations;\n\nbool valid(int x, int y) {\n    return x >= 0 && y >= 0 && x < N && y <= x;\n}\n\nint eval() {\n    int cnt = 0;\n    for (int i = 0; i < N-1; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            if (valid(i + 1, j) && grid[i][j] > grid[i + 1][j]) ++cnt;\n            if (valid(i + 1, j + 1) && grid[i][j] > grid[i + 1][j + 1]) ++cnt;\n        }\n    }\n    return cnt;\n}\n\nvoid swap_and_push(int x1, int y1, int x2, int y2) {\n    swap(grid[x1][y1], grid[x2][y2]);\n    operations.emplace_back(x1, y1, x2, y2);\n}\n\nvoid solve() {\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j <= i; ++j)\n            cin >> grid[i][j];\n\n    for (int iter = 0; iter < 500 && operations.size() < 10000; ++iter) {\n        bool improved = false;\n        // Iterate each position from top to bottom\n        for (int i = 0; i < N-1; ++i) {\n            for (int j = 0; j <= i; ++j) {\n                if (valid(i+1, j) && grid[i][j] > grid[i+1][j]) {\n                    swap_and_push(i, j, i+1, j);\n                    improved = true;\n                } else if (valid(i+1, j+1) && grid[i][j] > grid[i+1][j+1]) {\n                    swap_and_push(i, j, i+1, j+1);\n                    improved = true;\n                }\n                if (operations.size() >= 10000) break;\n            }\n            if (operations.size() >= 10000) break;\n        }\n        if (!improved) break;\n    }\n\n    cout << operations.size() << '\\n';\n    for (auto& [x1, y1, x2, y2] : operations)\n        cout << x1 << ' ' << y1 << ' ' << x2 << ' ' << y2 << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int D = 9;\nint N;\nvector<vector<bool>> is_obstacle(D, vector<bool>(D, false));\n\n// Spiral path initialization\nvector<pair<int, int>> spiral_order;\n\nvoid initialize_spiral() {\n    int top = 0, bottom = D-1, left = 0, right = D-1;\n    int dir = 0; // 0: right, 1: down, 2: left, 3: up\n    while (top <= bottom && left <= right) {\n        if (dir == 0) {\n            for (int j = left; j <= right; ++j) spiral_order.emplace_back(top, j);\n            top++;\n        } else if (dir == 1) {\n            for (int i = top; i <= bottom; ++i) spiral_order.emplace_back(i, right);\n            right--;\n        } else if (dir == 2) {\n            for (int j = right; j >= left; --j) spiral_order.emplace_back(bottom, j);\n            bottom--;\n        } else if (dir == 3) {\n            for (int i = bottom; i >= top; --i) spiral_order.emplace_back(i, left);\n            left++;\n        }\n        dir = (dir + 1) % 4;\n    }\n    // Filter out entrance and invalid positions\n    spiral_order.erase(remove_if(spiral_order.begin(), spiral_order.end(), \n        [](auto& pos) {\n            return (pos.first == 0 && pos.second == (D-1)/2) || is_obstacle[pos.first][pos.second];\n        }), \n        spiral_order.end());\n    reverse(spiral_order.begin(), spiral_order.end());\n}\n\nbool in_bounds(int x, int y) {\n    return x >= 0 && x < D && y >= 0 && y < D;\n}\n\nstruct StorageEntry {\n    int val;\n    int x, y;\n};\n\nvector<vector<int>> grid(D, vector<int>(D, -1));\nvector<StorageEntry> stored;\n\npair<int, int> bfs_nearest(int target) {\n    queue<pair<int, int>> q;\n    q.emplace((0, (D-1)/2));\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    visited[0][(D-1)/2] = true;\n    \n    while (!q.empty()) {\n        auto [cx, cy] = q.front(); q.pop();\n        for (auto [dx, dy] : vector<pair<int, int>>{{-1,0},{1,0},{0,-1},{0,1}}) {\n            int nx = cx + dx, ny = cy + dy;\n            if (in_bounds(nx, ny) && !visited[nx][ny] && !is_obstacle[nx][ny] && grid[nx][ny] != -1) {\n                if (grid[nx][ny] == target) {\n                    grid[nx][ny] = -1; // mark as used\n                    return {nx, ny};\n                }\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return {-1, -1};\n}\n\nint main() {\n    cin >> N;\n    int n = D*D - 1 - N;\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        is_obstacle[x][y] = true;\n    }\n\n    initialize_spiral();\n    int cur_pos = 0;\n    unordered_map<int, pair<int, int>> container_map;\n\n    for (int d = 0; d < n; ++d) {\n        int t;\n        cin >> t;\n        stored.push_back({t, spiral_order[cur_pos].first, spiral_order[cur_pos].second});\n        container_map[t] = spiral_order[cur_pos];\n        grid[spiral_order[cur_pos].first][spiral_order[cur_pos].second] = t;\n        cur_pos++;\n        cout << spiral_order[cur_pos - 1].first << \" \" << spiral_order[cur_pos - 1].second << endl;\n    }\n\n    sort(stored.begin(), stored.end(), [](const auto& a, const auto& b) { return a.val < b.val; });\n\n    for (const auto& entry : stored) {\n        auto [x, y] = bfs_nearest(entry.val);\n        cout << x << \" \" << y << endl;\n    }\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 52;\nint grid[N][N];\nint ans[N][N];\nbool required_adj[101][101] = {};\nbool border_colors[101] = {};\n\nvoid mark_adjacencies(int n) {\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            int c = grid[i][j];\n            border_colors[c] |= (i == 0 || j == 0 || i == n-1 || j == n-1);\n            for (int dx = -1; dx <= 1; ++dx) {\n                for (int dy = -1; dy <= 1; ++dy) {\n                    if (dx == 0 && dy == 0 || abs(dx) + abs(dy) != 1) continue;\n                    int x = i + dx, y = j + dy;\n                    if (x >= 0 && x < n && y >= 0 && y <n) {\n                        required_adj[c][grid[x][y]] = true;\n                    }\n                }\n            }\n        }\n    }\n}\n\nbool can_place_zero(int x, int y, int n) {\n    vector<int> neighbors;\n    for (int dx = -1; dx <= 1; ++dx) {\n        for (int dy = -1; dy <= 1; ++dy) {\n            if (abs(dx) + abs(dy) != 1) continue;\n            int nx = x + dx, ny = y + dy;\n            if (nx < 0 || nx >= n || ny < 0 || ny >= n) {\n                if (!border_colors[grid[x][y]]) return false;\n            } else if (ans[nx][ny] > 0) {\n                neighbors.push_back(ans[nx][ny]);\n            }\n        }\n    }\n    \n    for (int a : neighbors) {\n        for (int b : neighbors) {\n            if (a != b && !required_adj[a][b]) return false;\n        }\n    }\n    return true;\n}\n\nvoid bfs_expand_zeros(int n) {\n    deque<pair<int,int>> q;\n    for (int i=0; i<n; ++i) {\n        if (ans[i][0] == 0) q.emplace_back(i,0);\n        if (ans[i][n-1] == 0) q.emplace_back(i,n-1);\n    }\n    for (int j=0; j<n; ++j) {\n        if (ans[0][j] == 0) q.emplace_back(0,j);\n        if (ans[n-1][j] == 0) q.emplace_back(n-1,j);\n    }\n    \n    while (!q.empty()) {\n        auto [x, y] = q.front(); q.pop_front();\n        for (int d=0; d<4; ++d) {\n            int nx = x + \"-1+0+1-0\"[d] - '0';\n            int ny = y + \"-0-1+1+0\"[d] - '0';\n            if (nx < 0 || ny < 0 || nx >=n || ny >=n || ans[nx][ny] != -1) continue;\n            if (!can_place_zero(nx, ny, n)) continue;\n            ans[nx][ny] = 0;\n            q.emplace_back(nx, ny);\n        }\n    }\n}\n\nint main() {\n    const int n = 50;\n    int m;\n    scanf(\"%d%d\", &n, &m);\n    for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) scanf(\"%d\", &grid[i][j]);\n    \n    memset(ans, -1, sizeof(ans));\n    mark_adjacencies(n);\n    \n    // Place initial representatives (prioritize borders)\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            int c = grid[i][j];\n            if (ans[i][j] == -1 && ((border_colors[c] && (i==0 || i==n-1 || j==0 || j==n-1)) || !border_colors[c])) {\n                ans[i][j] = c;\n            }\n        }\n    }\n    \n    bfs_expand_zeros(n);\n    \n    // Fill remaining cells with original color\n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            if (ans[i][j] == -1) ans[i][j] = grid[i][j];\n        }\n    }\n    \n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) printf(\"%d \", ans[i][j]);\n        puts(\"\");\n    }\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing Vec = vector<int>;\nusing Mat = vector<Vec>;\nusing Graph = vector<Vec>;\nconstexpr ll INF = 1LL<<60;\nmt19937 mt(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct Partition {\n    int N, D, Q;\n    Vec A; // Answer partitions\n    Mat W; // Constraints: W[u][v] > 0 means u > v\n    vector<double> weight; // Virtual item weights\n\n    void init(int n, int d, int q) {\n        N = n; D = d; Q = q;\n        A = Vec(N, -1);\n        W.assign(N, Vec(N));\n        weight.resize(N, 1.0);\n    }\n\n    // Assign a random group with the smallest current sum\n    int assign(const Vec& cnt) {\n        priority_queue<pair<double, int>, vector<pair<double, int>>, greater<>> pq;\n        for (int i=0; i<D; ++i) pq.emplace(cnt[i] * weight[i], i);\n        \n        // Prefer groups with space but allow overfill near the end\n        int best = -1, minOver = N+1;\n        for (auto [w, idx] : pq) {\n            int total = cnt[idx] + 1;\n            if (total > N/D && minOver <= N/D) continue;\n            if (best == -1 || (total <= N/D && cnt[idx] < cnt[best])) {\n                best = idx;\n                if (total > N/D) minOver = total;\n            }\n        }\n        return best;\n    }\n\n    Vec solve() {\n        // Initial comparison phase\n        int q = 0;\n        for (int i=0; i<N-1 && q < Q; ++i) {\n            cout << 1 << ' ' << 1 << ' ' << i << ' ' << (i+1) << endl;\n            char res; cin >> res;\n            if (res == '>') W[i][i+1] = 1;\n            else if (res == '<') W[i+1][i] = 1;\n            ++q;\n        }\n\n        // Update virtual weights based on constraints\n        for (int k=0; k<N; ++k)\n            for (int i=0; i<N; ++i)\n                for (int j=0; j<N; ++j)\n                    if (W[i][k] && W[k][j]) W[i][j] = 1;\n\n        Vec cnt(D, 0);\n        for (int i=0; i<N; ++i) {\n            if (q >= Q) break;\n            int group = assign(cnt);\n            if (group == -1) {\n                group = mt() % D; // Random if stuck\n                if (cnt[group] >= N/D) continue; // Avoid overfill\n            }\n            A[i] = group;\n            cnt[group]++;\n        }\n\n        // Fill remaining unassigned items (if any)\n        int group = 0;\n        for (int i=0; i<N; ++i) {\n            if (A[i] == -1) {\n                while (cnt[group] >= N/D) group++;\n                A[i] = group;\n                cnt[group]++;\n            }\n        }\n\n        // Output final partition\n        for (int x: A) cout << x << ' ';\n        cout << endl;\n        return A;\n    }\n};\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n    Partition solver;\n    solver.init(N, D, Q);\n    solver.solve();\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nvoid find_box(const multi_array<int, 2>& stacks, int target, int& sidx, int& pos) {\n    for (int i=0; i<stacks.shape()[0]; ++i) {\n        for (int j=stacks.shape()[1]-1; j>=0; --j) {\n            if (stacks[i][j] == target) {\n                sidx = i; pos = j;\n                return;\n            }\n        }\n    }\n}\n\nint main() {\n    int n = 200, m = 10;\n    multi_array<int, 2> stacks(extents[m][n/m]);\n    for (int i=0; i<m; ++i)\n        for (int j=0; j<n/m; ++j)\n            cin >> stacks[i][j];\n\n    vector<pair<int, int>> moves;\n    int target = 1;\n\n    while (target <= n) {\n        int current_s = -1, pos = -1;\n        find_box(stacks, target, current_s, pos);\n        \n        bool at_top = false;\n        for (int s=0; s<m; ++s) {\n            if (!stacks[s].empty() && stacks[s].back() == target) {\n                at_top = true;\n                current_s = s;\n                break;\n            }\n        }\n        if (at_top) {\n            moves.emplace_back(target, 0);\n            stacks[current_s].pop_back();\n            target++;\n            continue;\n        }\n        \n        if (pos != stacks[current_s].size()-1) {\n            int max_dest = -1, dest_idx = -1;\n            for (int s=0; s<m; ++s) {\n                if (!stacks[s].empty() && s != current_s) {\n                    if (stacks[s].back() > max_dest || dest_idx == -1) {\n                        max_dest = stacks[s].back();\n                        dest_idx = s;\n                    }\n                }\n            }\n            if (dest_idx == -1) dest_idx = (current_s + 1) % m; // Pick next available\n            moves.emplace_back(stacks[current_s][pos], dest_idx + 1);\n            auto seq = stacks[current_s].subarray(pos, stacks[current_s].size());\n            stacks[dest_idx].insert(stacks[dest_idx].end(), seq.begin(), seq.end());\n            stacks[current_s].resize(pos);\n        }\n    }\n\n    for (auto& [v, i] : moves)\n        cout << v << \" \" << i << \"\\n\";\n}","ahc027":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n#include <boost/pending/disjoint_sets.hpp>\nusing namespace std;\nusing namespace boost;\n\n// Direction vectors: down, right, up, left\nint dx[] = {1, 0, -1, 0};\nint dy[] = {0, 1, 0, -1};\nchar dir_char[] = {'D', 'R', 'U', 'L'};\n\nconst int INF = 1e9;\ntypedef vector<vector<int>> Matrix;\ntypedef vector<vector<vector<int>>> Dist; // precomputed distances\n\nbool valid(int x, int y, int n) {\n    return x >= 0 && x < n && y >= 0 && y < n;\n}\n\npair<Matrix, Matrix> parseInput(int n) {\n    vector<string> h(n-1), v(n);\n    for (auto& s : h) cin >> s;\n    for (auto& s : v) cin >> s;\n    \n    Matrix hor(n, vector<int>(n, 0));\n    for (int i = 0; i < n-1; ++i)\n        for (int j = 0; j < n; ++j)\n            hor[i][j] = h[i][j] - '0';\n            \n    Matrix ver(n, vector<int>(n, 0));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n-1; ++j)\n            ver[i][j] = v[i][j] - '0';\n            \n    return {hor, ver};\n}\n\nMatrix readDirt(int n) {\n    Matrix d(n, vector<int>(n, 0));\n    for (auto& row : d)\n        for (int& v : row) cin >> v;\n    return d;\n}\n\nvoid bfs(int x, int y, int n, const Matrix& hor, const Matrix& ver, vector<vector<bool>>& vis) {\n    queue<pair<int,int>> q;\n    q.emplace(x, y);\n    vis[x][y] = true;\n    while (!q.empty()) {\n        auto [cx, cy] = q.front(); q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int nx = cx + dx[k], ny = cy + dy[k];\n            if (valid(nx, ny, n) && !vis[nx][ny]) {\n                if ((k == 0 && !hor[cx][cy]) || \n                    (k == 1 && !ver[cx][cy]) ||\n                    (k == 2 && !hor[nx][ny]) ||\n                    (k == 3 && !ver[nx][ny])) {\n                    vis[nx][ny] = true;\n                    q.emplace(nx, ny);\n                }\n            }\n        }\n    }\n}\n\nDist precompute_distances(int n, const Matrix& hor, const Matrix& ver) {\n    Dist dist(n, vector<vector<int>>(n, vector<int>(n*n, INF)));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            priority_queue<pair<int, pair<int,int>>, \n                           vector<pair<int, pair<int,int>>>, \n                           greater<>> pq;\n            pq.emplace(0, make_pair(i, j));\n            dist[i][j][i*n + j] = 0;\n            while (!pq.empty()) {\n                auto [d, p] = pq.top(); pq.pop();\n                auto [x, y] = p;\n                if (d > dist[i][j][x*n + y]) continue;\n                for (int k = 0; k < 4; ++k) {\n                    int nx = x + dx[k], ny = y + dy[k];\n                    if (valid(nx, ny, n)) {\n                        bool blocked = (k == 0 && hor[x][y]) ||\n                                       (k == 1 && ver[x][y]) ||\n                                       (k == 2 && hor[nx][ny]) ||\n                                       (k == 3 && ver[nx][ny]);\n                        if (!blocked && d + 1 < dist[i][j][nx*n + ny]) {\n                            dist[i][j][nx*n + ny] = d + 1;\n                            pq.emplace(d + 1, make_pair(nx, ny));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return dist;\n}\n\nvoid add_route(int x, int y, int nx, int ny, const Dist& dist, vector<char>& answer, int n) {\n    if (x == nx && y == ny) return;\n    auto& d = dist[x][y];\n    int best_k = -1;\n    for (int k = 0; k < 4; ++k) {\n        int ax = x + dx[k], ay = y + dy[k];\n        if (valid(ax, ay, n) && dist[x][y][ax*n + ay] == d[nx*n + ny] - 1 && \n            (best_k == -1 || dist[ax][ay][nx*n + ny] < dist[x + dx[best_k]][y + dy[best_k]][nx*n + ny])) {\n            best_k = k;\n        }\n    }\n    if (best_k != -1) {\n        answer.push_back(dir_char[best_k]);\n        add_route(x + dx[best_k], y + dy[best_k], nx, ny, dist, answer, n);\n    }\n}\n\nvector<pair<int, int>> get_critical_points(const Matrix& d, int region_size) {\n    vector<pair<int, pair<int,int>>> points;\n    for (int i = 0; i < d.size(); ++i)\n        for (int j = 0; j < d.size(); ++j)\n            points.emplace_back(-d[i][j], make_pair(i,j));\n    sort(points.begin(), points.end());\n    \n    vector<pair<int,int>> result;\n    for (int i = 0; i < min<int>(region_size, (int)points.size()); ++i)\n        result.emplace_back(points[i].second);\n    return result;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    auto [hor, ver] = parseInput(n);\n    Matrix d = readDirt(n);\n    \n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    bfs(0, 0, n, hor, ver, vis);\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            assert(vis[i][j]);\n    \n    Dist dist = precompute_distances(n, hor, ver);\n    \n    vector<pair<int, int>> critical = get_critical_points(d, n); // Top critical points\n    \n    vector<char> answer;\n    int len = 0, limit = 1e5;\n    int x = 0, y = 0;\n    \n    vector<int> shuffled(critical.size());\n    iota(shuffled.begin(), shuffled.end(), 0);\n    \n    while (true) {\n        random_shuffle(shuffled.begin(), shuffled.end());\n        for (int idx : shuffled) {\n            auto [nx, ny] = critical[idx];\n            if (len + dist[x][y][nx*n + ny] > limit) break;\n            add_route(x, y, nx, ny, dist, answer, n);\n            len += dist[x][y][nx*n + ny];\n            x = nx; y = ny;\n        }\n        if (len + dist[x][y][0] > limit)\n            break;\n        add_route(x, y, 0, 0, dist, answer, n);\n        break;\n    }\n    \n    cout << string(answer.begin(), answer.end()) << endl;\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\n#include <boost/algorithm/string/find_tail.hpp>\nusing namespace std;\n\nstring concat(const vector<string>& t) {\n    int m = t.size();\n    string result = t[0];\n    unordered_map<string, vector<int>> suffix;\n    for (int i=0; i<m; ++i) {\n        for (int len=1; len<=4; ++len) {\n            suffix[t[i].substr(t[i].size() - len)].push_back(i);\n        }\n    }\n    vector<bool> used(m, false);\n    used[0] = true;\n    \n    auto get_cost = [&](int idx, const string& prev_str) {\n        string target = t[idx];\n        int n = prev_str.size();\n        int max_overlap = 0;\n        for (int i=1; i<=4 && i<=n; ++i) {\n            if (boost::algorithm::ends_with(prev_str, target.substr(0,i))) \n                max_overlap = i;\n        }\n        return target.size() - max_overlap;\n    };\n    \n    for (int count=1; count<m; ++count) {\n        int best_idx = -1, min_cost = INT_MAX;\n        for (int i=0; i<m; ++i) {\n            if (!used[i]) {\n                int cost = get_cost(i, result);\n                if (cost < min_cost) {\n                    min_cost = cost;\n                    best_idx = i;\n                }\n            }\n        }\n        if (best_idx == -1) break;\n        used[best_idx] = true;\n        string current = t[best_idx];\n        int n = result.size();\n        int overlap = 0;\n        for (int k=1; k<=min(4,n); ++k) {\n            if (boost::algorithm::ends_with(result, current.substr(0,k)))\n                overlap = k;\n        }\n        result += current.substr(overlap);\n    }\n    return result.substr(0, 5000);\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> A(N);\n    for (int i=0; i<N; ++i) cin >> A[i];\n    \n    vector<string> words(M);\n    unordered_map<char, pair<int,int>> pos;\n    \n    for (int i=0; i<M; ++i) cin >> words[i];\n    \n    for (int i=0; i<N; ++i) \n        for (int j=0; j<N; ++j) \n            pos[A[i][j]] = {i, j};\n    \n    string lucky = concat(words);\n    pair<int, int> current = {si, sj};\n    vector<pair<int,int>> steps;\n    \n    for (char c : lucky) {\n        steps.emplace_back(pos[c]);\n    }\n    \n    cout << steps.size() << endl;\n    for (auto& [x, y] : steps) {\n        cout << x << \" \" << y << endl;\n    }\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\n#include <boost/multi_array.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nusing namespace std;\nusing namespace boost::accumulators;\n\nstruct Grid {\n    int n;\n    boost::multi_array<int, 2> grid;  // 0: unknown, -1: empty, >=1: count\n    vector<pair<int,int>> unknown;\n    mt19937 mt{random_device{}()};\n    \n    Grid(int _n) : n(_n), grid(boost::extents[_n][_n]) {\n        for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) {\n            grid[i][j] = 0;\n            unknown.emplace_back(i, j);\n        }\n    }\n    \n    bool is_unknown(int i, int j) const {\n        return 0 <= i && i < n && 0 <= j && j <n && grid[i][j] == 0;\n    }\n    \n    void query_group(int size, const vector<pair<int,int>>& indexes) {\n        cout << \"q \" << size;\n        for (auto [x,y] : indexes) cout << ' ' << x << ' ' << y;\n        cout << endl;\n        int result;\n        cin >> result;\n        double mean = result + size * (1e-5); // Prevent division by zero\n        double stddev = sqrt(size * 0.2); // Conservative estimate\n        \n        double z_score = (result - size * 0.1) / (stddev + 1e-5);\n        for (auto [x,y] : indexes) {\n            if (grid[x][y] == 0) {\n                if (z_score > 2.0) grid[x][y] = 2;\n                else if (z_score < -1.5) grid[x][y] = -1;\n            }\n        }\n    }\n    \n    void drill(int i, int j) {\n        cout << \"q 1 \" << i << ' ' << j << endl;\n        cin >> grid[i][j];\n    }\n    \n    void report() {\n        vector<pair<int,int>> positives;\n        for (int i=0; i<n; ++i)\n            for (int j=0; j<n; ++j)\n                if (grid[i][j] > 0) positives.emplace_back(i,j);\n        \n        cout << \"a \" << positives.size();\n        for (auto [x,y] : positives) cout << ' ' << x << ' ' << y;\n        cout << endl;\n        exit(0);\n    }\n};\n\nbool is_border(int i, int j, int n) {\n    return i == 0 || j == 0 || i == n-1 || j == n-1;\n}\n\nint main() {\n    srand(time(0));\n    int N, M;\n    double epsilon;\n    cin >> N >> M >> epsilon;\n    vector<vector<pair<int,int>>> oil(M);\n    \n    for (int m=0; m<M; ++m) {\n        int d; cin >> d;\n        oil[m].resize(d);\n        for (int k=0; k<d; ++k) {\n            cin >> oil[m][k].first >> oil[m][k].second;\n        }\n    }\n    \n    Grid g(N);\n    int total = N * N;\n    int budget = total / 3;\n    \n    // Initial divination phase: 5x5 blocks\n    for (int i=0; i+5<=N; i+=5) {\n        for (int j=0; j+5<=N; j+=5) {\n            if (budget-- <= 0) break;\n            vector<pair<int,int>> block;\n            for (int x=i; x < i+5; ++x)\n                for (int y=j; y < j+5; ++y) \n                    if (g.is_unknown(x,y)) block.emplace_back(x,y);\n            if (block.size() >= 2) g.query_group(block.size(), block);\n        }\n        if (budget <= 0) break;\n    }\n    \n    // Remaining cells: smaller divination\n    while (budget >= 5 && g.unknown.size() >= 5) {\n        shuffle(g.unknown.begin(), g.unknown.end(), g.mt);\n        vector<pair<int,int>> batch;\n        while (budget >= 0 && batch.size() < 20 && !g.unknown.empty()) {\n            auto [x,y] = g.unknown.back();\n            g.unknown.pop_back();\n            if (g.is_unknown(x,y)) {\n                batch.emplace_back(x,y);\n            }\n        }\n        if (batch.size() >= 2) {\n            g.query_group(batch.size(), batch);\n            budget--;\n        }\n    }\n    \n    // Drill borders\n    for (auto &cell : g.unknown) {\n        if (g.is_unknown(cell.first, cell.second) && is_border(cell.first, cell.second, N)) {\n            g.drill(cell.first, cell.second);\n        }\n    }\n    \n    // Drill remaining\n    for (auto &cell : g.unknown) {\n        if (g.is_unknown(cell.first, cell.second)) {\n            g.drill(cell.first, cell.second);\n        }\n    }\n    \n    g.report();\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<tuple<int,int,int,int>> rectangles[55];\n\nvoid solve(int n, const vector<int>& areas) {\n    int w = 1000;\n    int sum = accumulate(areas.begin(), areas.end(), 0);\n    int remaining = w * w - sum;\n    vector<int> needed = areas;\n    int max_y = w;\n\n    rectangles[n].resize(areas.size());\n    \n    for (int i=0; i<(int)areas.size(); ++i) {\n        int rows = (remaining + (int)areas.size() - i - 1) / ((int)areas.size() - i);\n        rows = max(rows, (needed[i] + w - 1) / w); // at least enough area\n        \n        int y_start = max_y - rows;\n        get<0>(rectangles[n][i]) = y_start;\n        get<2>(rectangles[n][i]) = max_y;\n        get<1>(rectangles[n][i]) = 0;\n        int cols = needed[i] / rows;\n        if (cols * rows < needed[i]) ++cols;\n        cols = min(cols, w); // max columns can't exceed grid width\n        get<3>(rectangles[n][i]) = cols;\n        \n        remaining -= (rows * cols - needed[i]);\n        max_y = y_start;\n    }\n    \n    int last_x = 0;\n    for (int k=0; k < (int)rectangles[n].size(); ++k) {\n        get<1>(rectangles[n][k]) = last_x;\n        last_x += get<3>(rectangles[n][k]);\n        get<3>(rectangles[n][k]) = last_x;\n    }\n}\n\nint main() {\n    int W = 1000, D, N;\n    cin >> W >> D >> N;\n    \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    for (int d=0; d<D; ++d) \n        solve(d, a[d]);\n    \n    for (int d=0; d<D; ++d)\n        for (auto [x1,y1,x2,y2] : rectangles[d])\n            printf(\"%d %d %d %d\\n\", x1, y1, x2, y2);\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nconst int MOD = 998244353;\nconst int N = 9;\nint a[N][N], s[20][3][3];\n\nint get_gain(int m, int p, int q) {\n    int total = 0;\n    for (int i = 0; i < 3; ++i)\n        for (int j = 0; j < 3; ++j) {\n            int new_val = (a[p+i][q+j] + s[m][i][j]) % MOD;\n            total += (new_val - a[p+i][q+j] + MOD) % MOD;\n        }\n    return total;\n}\n\nvoid apply_stamp(int m, int p, int q) {\n    for (int i = 0; i < 3; ++i)\n        for (int j = 0; j < 3; ++j)\n            a[p+i][q+j] = (a[p+i][q+j] + s[m][i][j]) % MOD;\n}\n\nint main() {\n    mt19937 rng(random_device{}());\n    int n, m, k;\n    cin >> n >> m >> k;\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n    \n    for (int t = 0; t < m; ++t)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> s[t][i][j];\n\n    vector<tuple<int, int, int>> ops;\n    int used = 0;\n\n    // Prioritize deterministic best moves first\n    while (used < k) {\n        int best_gain = -1, bst_m = -1, bst_p = -1, bst_q = -1;\n        for (int m_idx = 0; m_idx < m; ++m_idx) {\n            for (int p = 0; p <= 6; ++p) {\n                for (int q = 0; q <= 6; ++q) {\n                    int gain = get_gain(m_idx, p, q);\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        bst_m = m_idx;\n                        bst_p = p;\n                        bst_q = q;\n                    }\n                }\n            }\n        }\n        if (best_gain <= 0 || ops.size() == k) break;\n        ops.emplace_back(bst_m, bst_p, bst_q);\n        apply_stamp(bst_m, bst_p, bst_q);\n        ++used;\n    }\n\n    // Fill remaining with semi-random choices\n    vector<pair<int, int>> pos;\n    for (int x = 0; x <= 6; ++x) for (int y = 0; y <= 6; ++y) pos.emplace_back(x, y);\n    while (used < k) {\n        shuffle(pos.begin(), pos.end(), rng);\n        for (auto [x, y] : pos) {\n            if (used == k) break;\n            for (int m_idx = rng() % m; m_idx < m; ++m_idx) {\n                if (used == k) break;\n                ops.emplace_back(m_idx, x, y);\n                apply_stamp(m_idx, x, y);\n                ++used;\n            }\n        }\n    }\n\n    cout << ops.size() << \"\\n\";\n    for (auto [m, p, q] : ops)\n        cout << m << \" \" << p << \" \" << q << \"\\n\";\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nvector<string> solve(const vector<vector<int>>& containers) {\n    int N = 5;\n    vector<pair<int, int>> targets(N*N);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            targets[containers[i][j]] = {i, N-1};\n\n    vector<pair<int, int>> crane(N);\n    vector<bool> holding(N, false);\n    for (int i=0; i < N; ++i) crane[i] = {i, 0};\n\n    vector<string> ans(N);\n    for (int turn = 0; turn < 100; ++turn) {\n        bool moved = false;\n        vector<bool> grid(N*N, false);\n        for (auto [x, y] : crane) grid[x*N + y] = true;\n\n        for (int i = 0; i < N; ++i) {\n            auto [x, y] = crane[i];\n            char move = '.';\n\n            if (!holding[i] && y == 0) {\n                bool found = false;\n                for (int r = 0; r < N && !found; ++r) {\n                    if (x == r && turn < (int)containers[r].size() && !grid[r*N + 0]) {\n                        move = 'P';\n                        found = true;\n                    }\n                }\n            } else if (holding[i]) {\n                auto [tx, ty] = targets[containers[x][turn]];\n                if (x == tx && y == ty) move = 'Q';\n                else {\n                    if (y < ty) move = 'R';\n                    else if (x < tx) move = 'D';\n                    else move = 'U';\n                }\n            } else {\n                // Move towards a container\n                if (x > 0) move = 'U';\n                else if (x < N-1) move = 'D';\n            }\n\n            pair<int, int> next = crane[i];\n            if (move == 'P') next.second++;\n            if (move == 'Q') next.second--;\n            if (move == 'U') next.first--;\n            if (move == 'D') next.first++;\n            if (move == 'R') next.second++;\n            if (move == 'L') next.second--;\n\n            bool valid = (next.first >= 0 && next.first < N && next.second >= 0 && next.second < N);\n            for (int j = 0; j < N && valid; ++j) {\n                if (i != j && crane[j] == next) valid = false;\n            }\n\n            if (valid && move != '.') {\n                ans[i] += move;\n                crane[i] = next;\n                moved = true;\n                if (move == 'P') grid[next.first*N + next.second] = true;\n                if (move == 'Q') {\n                    holding[i] = false;\n                    grid[next.first*N + next.second] = false;\n                }\n            } else {\n                ans[i] += '.';\n            }\n        }\n        if (!moved) break;\n    }\n\n    int max_len = 0;\n    for (auto& cmd : ans) max_len = max(max_len, (int)cmd.size());\n    for (auto& cmd : ans) cmd.resize(max_len, '.');\n    \n    return ans;\n}\n\nint main() {\n    int N = 5;\n    vector<vector<int>> containers(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> containers[i][j];\n    \n    auto result = solve(containers);\n    for (auto& s : result)\n        cout << s << '\\n';\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint H[20][20], dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}, vis[20][20];\nvector<string> ans;\nint n = 20, x = 0, y = 0, load = 0;\n\nvoid move(int nx, int ny) {\n    while (x != nx || y != ny) {\n        if (x > nx) ans.push_back(\"U\"), x--;\n        else if (x < nx) ans.push_back(\"D\"), x++;\n        else if (y > ny) ans.push_back(\"L\"), y--;\n        else ans.push_back(\"R\"), y++;\n    }\n}\n\nvoid load_soil(int val) {\n    ans.push_back(\"+\" + to_string(val));\n    load += val;\n    H[x][y] -= val;\n}\n\nvoid unload_soil(int val) {\n    ans.push_back(\"-\" + to_string(val));\n    load -= val;\n    H[x][y] += val;\n}\n\nvoid process() {\n    memset(vis, 0, sizeof(vis));\n    vector<pair<int, int>> positives, negatives;\n    \n    for (int i=0; i<n; ++i) {\n        for (int j=0; j<n; ++j) {\n            (H[i][j] > 0) ? positives.emplace_back(H[i][j], i*n+j) :\n            (H[i][j] < 0) ? negatives.emplace_back(-H[i][j], i*n+j) : void();\n        }\n    }\n\n    sort(positives.rbegin(), positives.rend());\n    sort(negatives.rbegin(), negatives.rend());\n\n    auto get = [&](int val) { return pair{val/n, val%n}; };\n\n    while (!positives.empty() && !negatives.empty()) {\n        auto [pval, pos] = positives.back(); positives.pop_back();\n        auto [nval, neg] = negatives.back(); negatives.pop_back();\n        auto [posx, posy] = get(pos);\n        auto [negx, negy] = get(neg);\n\n        if (pval == 0 || nval == 0) break;\n        int transfer = min(pval, nval);\n\n        move(posx, posy);\n        load_soil(transfer);\n        move(negx, negy);\n        unload_soil(transfer);\n\n        if (pval > transfer) positives.emplace_back(pval - transfer, pos);\n        if (nval > transfer) negatives.emplace_back(nval - transfer, neg);\n    }\n\n    while (!positives.empty()) {\n        auto [pval, pos] = positives.back(); positives.pop_back();\n        auto [posx, posy] = get(pos);\n        if (posx == x && posy == y) continue;\n        move(posx, posy);\n        load_soil(pval);\n    }\n\n    while (!negatives.empty()) {\n        auto [nval, neg] = negatives.back(); negatives.pop_back();\n        auto [negx, negy] = get(neg);\n        move(negx, negy);\n        unload_soil(nval);\n    }\n}\n\nint main() {\n    cin >> n;\n    for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) cin >> H[i][j];\n    \n    process();\n    for (auto& op : ans) cout << op << endl;\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nconstexpr int N = 6;\nconstexpr int M = 15;\nconstexpr int T = 10;\nconstexpr int TOTAL = 2 * N * (N - 1);\nconstexpr int GRID = N * N;\n\nstruct Seed {\n    vector<int> eval;\n    int total = 0;\n    \n    void update() {\n        total = accumulate(eval.begin(), eval.end(), 0);\n    }\n};\n\nbool operator<(const Seed& a, const Seed& b) {\n    return a.total < b.total;\n}\n\nvoid read_all_seeds(vector<Seed>& seeds) {\n    for (auto& seed : seeds) {\n        seed.eval.assign(M, 0);\n        for (auto& x : seed.eval) cin >> x;\n        seed.update();\n    }\n}\n\nint main() {\n    vector<Seed> seeds(TOTAL);\n    read_all_seeds(seeds);\n    \n    // Initial planting of the top seeds based on sorted indices\n    vector<int> initial_indices(TOTAL);\n    iota(initial_indices.begin(), initial_indices.end(), 0);\n    sort(initial_indices.begin(), initial_indices.end(), [&](int i, int j) {\n        return seeds[i].total > seeds[j].total;\n    });\n    \n    for (int t = 0; t < T; ++t) {\n        // Always output the first GRID indices after resorting\n        for (int i = 0; i < GRID; ++i) {\n            cout << initial_indices[i];\n            if (i % N == N - 1) cout << '\\n';\n            else cout << ' ';\n        }\n        cout.flush();\n        \n        if (t == T - 1) break;\n        \n        // Update seeds based on judge input after each turn\n        read_all_seeds(seeds);\n        vector<int> sorted_indices(TOTAL);\n        iota(sorted_indices.begin(), sorted_indices.end(), 0);\n        sort(sorted_indices.begin(), sorted_indices.end(), [&](int i, int j){\n            return seeds[i].total > seeds[j].total;\n        });\n        \n        // Reset initial_indices to current sorted for next turn\n        initial_indices = vector<int>(sorted_indices.begin(), sorted_indices.begin() + GRID);\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\n#include <queue>\n#include <optional>\nusing namespace std;\n\nconstexpr int INF = 1e9;\n\nstruct Pos {\n    int x, y;\n    bool operator==(const Pos& o) const { return x == o.x && y == o.y; }\n    Pos rotate(char c) const {\n        if (c == 'L') return {-y, x};\n        if (c == 'R') return {y, -x};\n        return {x, y};\n    }\n};\n\nstruct State {\n    int turns;\n    Pos pos;\n    vector<Pos> fingers; // relative positions\n    State(int t, Pos p, const vector<Pos>& f) : turns(t), pos(p), fingers(f) {}\n};\n\nvector<string> grid;\nvector<vector<char>> rotations;\nint dist(Pos a, Pos b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvector<string> find_path(Pos start, Pos goal, int V, const string& initial_rot = \"\") {\n    priority_queue<pair<int, State>, vector<pair<int, State>>, greater<>> pq;\n    unordered_map<Pos, int> dirs = {{'R', 0}, {'D', 1}, {'L', 2}, {'U', 3}};\n    vector<Pos> dir_offs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n    vector<string> dir_strs = {\"R\", \"D\", \"L\", \"U\"};\n    unordered_map<State, int, hash<State>> visited;\n    \n    vector<Pos> init_fingers(V - 1);\n    for (int i = 0; i < V - 1; ++i) {\n        init_fingers[i] = {i + 1, 0};\n    }\n    for (char c : initial_rot) {\n        if (c == '.') break;\n        for (auto& f : init_fingers) f = f.rotate(c);\n    }\n    \n    auto start_state = State(0, start, init_fingers);\n    pq.emplace(dist(start, goal), start_state);\n    visited[start_state] = 0;\n    \n    while (!pq.empty()) {\n        auto [current_cost, current] = pq.top();\n        pq.pop();\n        if (current.pos == goal) {\n            vector<string> path;\n            string rot = initial_rot.substr(0, V - 1);\n            while (current.turns > 0) {\n                path.emplace_back(dir_strs[current.pos.x] + rot + string(V, '.'));\n                for (char& c : rot) {\n                    if (c == 'R') c = 'L';\n                    else if (c == 'L') c = 'R';\n                }\n                reverse(rot.begin(), rot.end());\n                current.pos = goal;\n                --current.turns;\n            }\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        \n        for (int i = 0; i < 4; ++i) {\n            Pos next_pos = {current.pos.x + dir_offs[i].x, current.pos.y + dir_offs[i].y};\n            if (next_pos.x < 0 || next_pos.x >= grid.size() || next_pos.y < 0 || next_pos.y >= grid.size())\n                continue;\n            auto new_state = State(current.turns + 1, next_pos, current.fingers);\n            if (visited.count(new_state) && visited[new_state] <= new_state.turns)\n                continue;\n            visited[new_state] = new_state.turns;\n            pq.emplace(new_state.turns + dist(next_pos, goal), new_state);\n        }\n        \n        // Rotate subtrees\n        for (int v = 1; v < V; ++v) {\n            for (char rot : {'L', 'R'}) {\n                vector<Pos> new_fingers = current.fingers;\n                for (auto& f : new_fingers) f = f.rotate(rot);\n                auto rotated = State(current.turns + 1, current.pos, new_fingers);\n                if (visited.count(rotated) && visited[rotated] <= rotated.turns)\n                    continue;\n                visited[rotated] = rotated.turns;\n                pq.emplace(rotated.turns + dist(current.pos, goal), rotated);\n            }\n        }\n    }\n    return {};\n}\n\nint main() {\n    // Example input parsing; actual input handling depends on contest environment\n    int N = 20, M = 7, V = 8; \n    vector<pair<Pos, Pos>> tasks = {\n        {{0,0}, {15,5}}, {{3,2}, {17,7}}, {{5,5}, {18,18}}, \n        {{12,8}, {2,2}}, {{15,19}, {3,3}}, {{7,11}, {10,10}}, {{9,14}, {11,2}}\n    };\n    \n    cout << V << \"\\n\";\n    for (int i = 1; i < V; ++i) {\n        cout << \"0 \" << 1 << '\\n'; // star structure with length 1\n    }\n    cout << \"0 0\\n\"; // initial root position\n    \n    vector<bool> done(M, false);\n    Pos current = {0, 0};\n    int completed = 0;\n    \n    for (int steps = 0; completed < M; ++steps) {\n        pair<int, int> best = {INF, -1};\n        for (int i = 0; i < M; ++i) {\n            if (!done[i]) {\n                int cost = dist(current, tasks[i].first) + dist(tasks[i].first, tasks[i].second);\n                best = min(best, {cost, i});\n            }\n        }\n        int idx = best.second;\n        if (idx < 0) break;\n        \n        // Move to source\n        auto path1 = find_path(current, tasks[idx].first, V);\n        for (auto& s : path1) {\n            cout << s << '\\n';\n        }\n        current = tasks[idx].first;\n        \n        // Operation to grab\n        cout << \".\" + string(V - 1, '.') + string(V - 1, '.') << \"P\\n\";\n        \n        // Move to target\n        auto path2 = find_path(current, tasks[idx].second, V);\n        for (auto& s : path2) {\n            cout << s << '\\n';\n        }\n        \n        // Operation to release\n        cout << \".\" + string(V - 1, '.') + string(V - 1, '.') << \"P\\n\";\n        \n        done[idx] = true;\n        completed++;\n        current = tasks[idx].second;\n    }\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Box {\n    int x1, y1, x2, y2;\n    bool contains(int x, int y) const {\n        return x1 <= x && x <= x2 && y1 <= y && y <= y2;\n    }\n    int perimeter() const {\n        return 2 * (x2 - x1 + y2 - y1);\n    }\n    bool valid() const {\n        return x1 <= x2 && y1 <= y2;\n    }\n};\n\nint main() {\n    const int MAX_FISH = 5000;\n    vector<pair<int, int>> mackerel(MAX_FISH), sardine(MAX_FISH);\n    for (int i = 0; i < 2*MAX_FISH; ++i) {\n        int x, y; cin >> x >> y;\n        if (i < MAX_FISH) mackerel[i] = {x, y};\n        else sardine[i-MAX_FISH] = {x, y};\n    }\n    \n    const int kGridSize = 1e5 / 5; // 5x5 grid for finer clusters\n    vector<int> mack_grid(25);\n    int best_x = 0, best_y = 0;\n    for (auto& [x, y] : mackerel) {\n        int cx = x / kGridSize;\n        int cy = y / kGridSize;\n        if (++mack_grid[cx*5 + cy] > mack_grid[best_x*5 + best_y])\n            best_x = cx, best_y = cy;\n    }\n    \n    int x_min = best_x * kGridSize, x_max = x_min + kGridSize - 1;\n    int y_min = best_y * kGridSize, y_max = y_min + kGridSize - 1;\n    \n    // Find exact mackerel bounds\n    for (auto& [x, y] : mackerel) {\n        if (best_x*kGridSize <= x && x < (best_x+1)*kGridSize &&\n            best_y*kGridSize <= y && y < (best_y+1)*kGridSize) \n        {\n            x_min = min(x_min, x);\n            y_min = min(y_min, y);\n            x_max = max(x_max, x);\n            y_max = max(y_max, y);\n        }\n    }\n    \n    // Greedily expand boundaries\n    const int max_edge = 4e5;\n    Box best = {x_min, y_min, x_max, y_max};\n    int best_score = count_if(mackerel.begin(), mackerel.end(), \n        [&](auto& p) { return best.contains(p.first, p.second); })\n        - count_if(sardine.begin(), sardine.end(),\n        [&](auto& p) { return best.contains(p.first, p.second); });\n    \n    auto compute_score = [&](int l, int r, int b, int t) -> int {\n        if (l > r || b > t) return -1e9;\n        int p = 2*(r-l + t-b);\n        if (p > max_edge) return -1e9;\n        int macks = 0, sards = 0;\n        for (auto& [x, y] : mackerel)\n            if (l <= x && x <= r && b <= y && y <= t) macks++;\n        for (auto& [x, y] : sardine)\n            if (l <= x && x <= r && b <= y && y <= t) sards++;\n        return macks - sards;\n    };\n    \n    Box current = best;\n    while (true) {\n        int prev_score = best_score;\n        // Expand left, right, bottom, top one by one and track best\n        for (int dir = 0; dir < 4; ++dir) {\n            Box next = current;\n            if (dir == 0) next.x1 = max(0, next.x1 - 5000); // Larger step left\n            if (dir == 1) next.x2 = min((int)1e5, next.x2 + 5000); // Larger step right\n            if (dir == 2) next.y1 = max(0, next.y1 - 5000);\n            if (dir == 3) next.y2 = min((int)1e5, next.y2 + 5000);\n            \n            int score = compute_score(next.x1, next.x2, next.y1, next.y2);\n            if (score > best_score) {\n                best_score = score;\n                current = next;\n            }\n        }\n        if (prev_score == best_score) break; // No improvement\n        best = current;\n    }\n    \n    vector<pair<int, int>> poly = {\n        {current.x1, current.y1}, \n        {current.x1, current.y2}, \n        {current.x2, current.y2}, \n        {current.x2, current.y1}\n    };\n    cout << poly.size() << '\\n';\n    for (auto& [x, y] : poly) cout << x << ' ' << y << '\\n';\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, T;\n    double sigma;\n    cin >> N >> T >> sigma;\n    vector<pair<int,int>> rects(N);\n    \n    for (auto& [w,h] : rects) {\n        cin >> w >> h;\n        w += ceil(3*sigma);\n        h += ceil(3*sigma);\n        w = min(w, 1'000'000'000);\n        h = min(h, 1'000'000'000);\n    }\n    \n    // First attempt: Vertical stack with rotation\n    for (int t=0; t<T; ++t) {\n        cout << N << '\\n';\n        int curr_x = 0, curr_y = 0; // Track max coordinates\n        int last_idx = -1;\n        \n        for (int i=0; i<N; ++i) {\n            auto [rw, rh] = rects[i];\n            bool use_vertical = (i % 2 == 0 || curr_y + rh < curr_x + rw);\n            \n            // Rotate to fit in chosen orientation\n            bool rot = use_vertical ? (rh > rw) : (rw > rh);\n            swap(rw, rh); // After rotation, rw is width, rh is height\n            \n            // Assign direction and reference\n            char dir = use_vertical ? 'U' : 'L';\n            int ref = (dir == 'U') ? last_idx : (i > 0 ? i-1 : -1);\n            \n            if (dir == 'U') {\n                curr_y += rh;\n            } else {\n                curr_x += rw;\n                ref = (i == 0) ? -1 : i-1; // Previous in sequence\n            }\n            \n            cout << i << \" \" << rot << \" \" << dir << \" \" << ref << '\\n';\n            last_idx = i;\n        }\n        cout.flush();\n        \n        if (t < T-1) {\n            int dummy_W, dummy_H;\n            cin >> dummy_W >> dummy_H;\n        }\n    }\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    cin >> N >> M >> H;\n    vector<int> A(N);\n    for (int& a : A) cin >> a;\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // Prepare order by highest beauty first\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return A[a] > A[b];\n    });\n\n    constexpr int UNVISITED = -2;\n    vector<int> parent(N, UNVISITED);\n    vector<bool> visited(N, false);\n\n    auto bfs = [&](int start) {\n        deque<int> q;\n        q.push_back(start);\n        visited[start] = true;\n        parent[start] = -1;\n        int current_height = 0;\n        \n        while (!q.empty() && current_height < H) {\n            int level_size = q.size();\n            current_height++;\n            \n            for (int i = 0; i < level_size; ++i) {\n                int u = q.front();\n                q.pop_front();\n                \n                for (int v : adj[u]) {\n                    if (!visited[v]) {\n                        visited[v] = true;\n                        if (current_height < H) {\n                            parent[v] = u;\n                        } else {\n                            parent[v] = -1;\n                        }\n                        q.push_back(v);\n                    }\n                }\n            }\n        }\n    };\n    \n    for (int u : order) {\n        if (!visited[u]) {\n            bfs(u);\n        }\n    }\n\n    // Ensure all nodes are assigned\n    for (int i = 0; i < N; ++i) {\n        if (parent[i] == UNVISITED) parent[i] = -1;\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        if (parent[i] == -1) continue;\n        int count = 0;\n        int temp = i;\n        while (parent[temp] != -1) {\n            temp = parent[temp];\n            count++;\n            if (count >= H) {\n                parent[i] = -1; // reset to root if exceeds height H\n                break;\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << parent[i] << (i == N-1 ? '\\n' : ' ');\n    }\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<pair<char, int>> remove_oni(int n, vector<string>& board) {\n    vector<pair<char, int>> operations;\n    vector<vector<bool>> visited(n, vector<bool>(n, false));\n\n    auto is_valid = [&](int x, int y) {\n        return x >= 0 && x < n && y >= 0 && y < n;\n    };\n\n    auto has_fuku_in_direction = [&](int x, int y, char dir) {\n        if (dir == 'L') {\n            for (int i = y - 1; i >= 0; --i)\n                if (board[x][i] == 'o') return true;\n        } else if (dir == 'R') {\n            for (int i = y + 1; i < n; ++i)\n                if (board[x][i] == 'o') return true;\n        } else if (dir == 'U') {\n            for (int i = x - 1; i >= 0; --i)\n                if (board[i][y] == 'o') return true;\n        } else if (dir == 'D') {\n            for (int i = x + 1; i < n; ++i)\n                if (board[i][y] == 'o') return true;\n        }\n        return false;\n    };\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (board[i][j] == 'x' && !visited[i][j]) {\n                if (!has_fuku_in_direction(i, j, 'U')) {\n                    for (int k = 0; k <= i; ++k) operations.emplace_back('U', j);\n                    for (int k = 0; k <= i; ++k) operations.emplace_back('D', j);\n                } else if (!has_fuku_in_direction(i, j, 'D')) {\n                    for (int k = 0; k < (n - i); ++k) operations.emplace_back('D', j);\n                    for (int k = 0; k < (n - i); ++k) operations.emplace_back('U', j);\n                } else if (!has_fuku_in_direction(i, j, 'L')) {\n                    for (int k = 0; k <= j; ++k) operations.emplace_back('L', i);\n                    for (int k = 0; k <= j; ++k) operations.emplace_back('R', i);\n                } else {\n                    for (int k = 0; k < (n - j); ++k) operations.emplace_back('R', i);\n                    for (int k = 0; k < (n - j); ++k) operations.emplace_back('L', i);\n                }\n                visited[i][j] = true;\n            }\n        }\n    }\n\n    return operations;\n}\n\nint main() {\n    int n = 20;\n    vector<string> board(n);\n    for (int i = 0; i < n; ++i) cin >> board[i];\n\n    vector<pair<char, int>> operations = remove_oni(n, board);\n\n    if (operations.size() > 1600) {\n        cerr << \"Too many operations!\" << endl;\n        return 0;\n    }\n\n    for (auto& [dir, idx] : operations) {\n        cout << dir << \" \" << idx << endl;\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int N = 100;\n    long long L = 500000;\n    \n    vector<long long> T(N);\n    for (auto& t : T) cin >> t;\n    \n    for (int i = 0; i < N; ++i) {\n        cout << i << ' ' << (i + 1) % N << '\\n';\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> sizes(M);\n    for (int& s : sizes) cin >> s;\n    \n    // Read city input (discard rectangles since centers aren't needed for grouping)\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry; cin >> lx >> rx >> ly >> ry;\n    }\n    \n    vector<int> city_order(N);\n    iota(city_order.begin(), city_order.end(), 0); // Initialize with 0 to N-1\n    \n    vector<vector<int>> groups;\n    int current = 0;\n    for (int sz : sizes) {\n        vector<int> group(city_order.begin() + current, city_order.begin() + current + sz);\n        groups.emplace_back(group);\n        current += sz;\n    }\n    \n    // Collect edges: MST for groups >=3, sequential otherwise\n    vector<tuple<int, int, int>> all_edges; // (g, u, v)\n    for (int g = 0; g < M; ++g) {\n        const auto& group = groups[g];\n        if (group.size() < 3) {\n            for (size_t i = 1; i < group.size(); ++i) {\n                if (Q <= 0) break; // Avoid redundant checks\n                all_edges.emplace_back(g, group[i-1], group[i]);\n            }\n        } else {\n            int start = 0;\n            while (start < group.size() && Q > 0) {\n                int end = min(start + L, (int)group.size());\n                if (end - start < 2) break; // Need at least 2 cities\n                \n                vector<int> subset(group.begin() + start, group.begin() + end);\n                cout << \"? \" << subset.size();\n                for (int city : subset) cout << \" \" << city;\n                cout << endl;\n                \n                for (int i = 1; i < subset.size(); ++i) {\n                    int u, v; cin >> u >> v;\n                    if (u > v) swap(u, v);\n                    all_edges.emplace_back(g, u, v);\n                }\n                \n                start += subset.size() - 1; // Move to next group; overlap last city\n                Q--;\n            }\n            // If queries exhausted, ensure connectivity via sequential edges\n            if (Q <= 0 && all_edges.empty()) {\n                for (size_t i = 1; i < group.size(); ++i)\n                    all_edges.emplace_back(g, group[i-1], group[i]);\n            }\n        }\n    }\n    \n    cout << \"!\" << endl;\n    for (int g = 0; g < M; ++g) {\n        for (int city : groups[g]) cout << city << \" \";\n        cout << endl;\n        \n        vector<pair<int, int>> group_edges;\n        for (const auto& [gid, u, v] : all_edges) {\n            if (gid == g) group_edges.emplace_back(u, v);\n        }\n        if (group_edges.empty() && groups[g].size() > 1) {\n            // Fallback if no MST available (shouldn't happen but safeguard)\n            for (size_t i = 1; i < groups[g].size(); ++i)\n                group_edges.emplace_back(groups[g][i-1], groups[g][i]);\n        }\n        \n        sort(group_edges.begin(), group_edges.end());\n        group_edges.erase(unique(group_edges.begin(), group_edges.end()), group_edges.end());\n        \n        for (const auto& [u, v] : group_edges)\n            cout << u << \" \" << v << endl;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n}","ahc046":"#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define INF (1LL << 60)\ntypedef long long ll;\ntypedef tree<pair<pair<int, int>, vector<pair<int, int>>>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> oset;\n\nstruct VecHash {\n    size_t operator()(const vector<pair<int, int>>& v) const {\n        size_t seed = 0;\n        for (auto x : v) {\n            seed ^= x.first + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            seed ^= x.second + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n        }\n        return seed;\n    }\n};\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dir[] = {'U', 'D', 'L', 'R'};\n\nvoid astar(vector<pair<int, int>>& goals) {\n    int startX = goals.front().first;\n    int startY = goals.front().second;\n    goals.erase(goals.begin());\n    \n    oset pq;\n    map<pair<pair<int, int>, vector<pair<int, int>>>, int, VecHash> dist;\n    pq.insert({{0, {startX, startY, goals}}, {}});\n    dist[{{startX, startY}, goals}] = 0;\n\n    auto get_priority = [&](int x, int y, const auto& path_rem) {\n        int h = 0;\n        if (!path_rem.empty()) {\n            int nx = path_rem[0].first, ny = path_rem[0].second;\n            h = max(abs(nx - x), abs(ny - y));\n        }\n        for (size_t i = 1; i < path_rem.size(); ++i) {\n            int px = path_rem[i-1].first, py = path_rem[i-1].second;\n            int cx = path_rem[i].first, cy = path_rem[i].second;\n            h += max(abs(cx - px), abs(cy - py));\n        }\n        return h + (int)path_rem.size();\n    };\n\n    while (!pq.empty()) {\n        auto current = pq.begin()->second;\n        pq.erase(pq.begin());\n        int x = current.first;\n        int y = current.second.first;\n        auto remaining = current.second.second;\n        \n        if (remaining.empty()) {\n            for (auto& move : dist[current.first]) {\n                cout << move.first << ' ' << move.second << '\\n';\n            }\n            exit(0);\n        }\n\n        int curr_dist = dist[current.first];\n        for (int d = 0; d < 4; ++d) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx < 0 || nx >= 20 || ny < 0 || ny >= 20) continue;\n\n            bool blocked = false;\n            vector<pair<int, int>> new_rem = remaining;\n            if (new_rem.size() > 0 && new_rem[0] == make_pair(nx, ny)) {\n                new_rem.erase(new_rem.begin());\n            }\n\n            string actions = \"MS\";\n            for (char action : actions) {\n                int tx = x, ty = y, steps = 1;\n                if (action == 'S') {\n                    while (tx + dx[d] >= 0 && tx + dx[d] < 20 && ty + dy[d] >= 0 && ty + dy[d] < 20 && \n                           (new_rem.empty() || make_pair(tx+dx[d], ty+dy[d]) != new_rem[0])) {\n                        tx += dx[d]; ty += dy[d]; ++steps;\n                    }\n                    if (new_rem.size() > 0 && make_pair(tx, ty) != new_rem[0]) continue;\n                    if (!new_rem.empty() && make_pair(tx, ty) == new_rem[0]) {\n                        vector<pair<int, int>> next_rem = new_rem;\n                        next_rem.erase(next_rem.begin());\n                        new_rem = next_rem;\n                    }\n                } else {\n                    tx = nx; ty = ny;\n                }\n                \n                if (dist.count({{tx, ty}, new_rem}) && dist[{{tx, ty}, new_rem}] <= curr_dist + 1) continue;\n\n                dist[{{tx, ty}, new_rem}] = curr_dist + 1;\n                int priority = curr_dist + get_priority(tx, ty, new_rem) + 1;\n                pq.insert({{priority, {tx, ty, new_rem}}, {action, dir[d]}});\n                \n                if (action == 'S') dist[{{tx, ty}, new_rem}].push_back({action, dir[d]});\n            }\n        }\n    }\n}\n\nint main() {\n    int N, M; cin >> N >> M;\n    vector<pair<int, int>> goals(M);\n    for (int i = 0; i < M; ++i) {\n        int x, y; cin >> x >> y;\n        goals[i] = {x, y};\n    }\n    astar(goals);\n    return 0;\n}"}}}