{"model_name":"mistral-large-3-2512","codes":{"1":{"ahc001":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Rect {\n    int a, b, c, d;\n    int area() const { return (c - a) * (d - b); }\n    bool contains(int x, int y) const {\n        return a <= x && x < c && b <= y && y < d;\n    }\n    bool overlaps(const Rect& other) const {\n        return !(c <= other.a || other.c <= a || d <= other.b || other.d <= b);\n    }\n};\n\nstruct Company {\n    int x, y, r;\n    Rect rect;\n    double satisfaction() const {\n        int s = rect.area();\n        if (s == 0) return 0.0;\n        double ratio = min(r, s) * 1.0 / max(r, s);\n        return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n    }\n};\n\nint n;\nvector<Company> companies;\nvector<vector<int>> grid(10000, vector<int>(10000, -1));\n\nbool is_valid(const Rect& rect, int ignore = -1) {\n    for (int i = rect.a; i < rect.c; ++i) {\n        for (int j = rect.b; j < rect.d; ++j) {\n            if (grid[i][j] != -1 && grid[i][j] != ignore) {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nvoid place_rect(const Rect& rect, int id) {\n    for (int i = rect.a; i < rect.c; ++i) {\n        for (int j = rect.b; j < rect.d; ++j) {\n            grid[i][j] = id;\n        }\n    }\n}\n\nvoid remove_rect(const Rect& rect) {\n    for (int i = rect.a; i < rect.c; ++i) {\n        for (int j = rect.b; j < rect.d; ++j) {\n            grid[i][j] = -1;\n        }\n    }\n}\n\ndouble total_satisfaction() {\n    double total = 0.0;\n    for (const auto& company : companies) {\n        total += company.satisfaction();\n    }\n    return total;\n}\n\nvoid greedy_initialization() {\n    for (auto& company : companies) {\n        int x = company.x;\n        int y = company.y;\n        // Start with a 1x1 rectangle\n        company.rect = {x, y, x + 1, y + 1};\n        place_rect(company.rect, &company - &companies[0]);\n    }\n}\n\nvoid local_search() {\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (auto& company : companies) {\n            int id = &company - &companies[0];\n            Rect original = company.rect;\n            double original_sat = company.satisfaction();\n            vector<Rect> candidates;\n\n            // Try expanding in all four directions\n            // Expand right\n            if (company.rect.c < 10000) {\n                Rect new_rect = company.rect;\n                new_rect.c++;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand left\n            if (company.rect.a > 0) {\n                Rect new_rect = company.rect;\n                new_rect.a--;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand up\n            if (company.rect.d < 10000) {\n                Rect new_rect = company.rect;\n                new_rect.d++;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand down\n            if (company.rect.b > 0) {\n                Rect new_rect = company.rect;\n                new_rect.b--;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n\n            // Try to find the best candidate\n            double best_sat = original_sat;\n            Rect best_rect = original;\n            for (const auto& rect : candidates) {\n                company.rect = rect;\n                double sat = company.satisfaction();\n                if (sat > best_sat) {\n                    best_sat = sat;\n                    best_rect = rect;\n                }\n            }\n            if (best_sat > original_sat) {\n                remove_rect(original);\n                company.rect = best_rect;\n                place_rect(best_rect, id);\n                improved = true;\n            } else {\n                company.rect = original;\n            }\n        }\n    }\n}\n\nvoid simulated_annealing() {\n    double temperature = 1000.0;\n    double cooling_rate = 0.999;\n    double min_temperature = 0.1;\n    double current_sat = total_satisfaction();\n\n    while (temperature > min_temperature) {\n        for (auto& company : companies) {\n            int id = &company - &companies[0];\n            Rect original = company.rect;\n            double original_sat = company.satisfaction();\n\n            // Randomly choose a direction to expand or shrink\n            int dir = rand() % 4;\n            Rect new_rect = original;\n            switch (dir) {\n                case 0: // right\n                    if (new_rect.c < 10000) new_rect.c++;\n                    break;\n                case 1: // left\n                    if (new_rect.a > 0) new_rect.a--;\n                    break;\n                case 2: // up\n                    if (new_rect.d < 10000) new_rect.d++;\n                    break;\n                case 3: // down\n                    if (new_rect.b > 0) new_rect.b--;\n                    break;\n            }\n\n            if (!is_valid(new_rect, id)) continue;\n\n            company.rect = new_rect;\n            double new_sat = company.satisfaction();\n            double delta = new_sat - original_sat;\n\n            if (delta > 0 || (rand() / (double)RAND_MAX) < exp(delta / temperature)) {\n                remove_rect(original);\n                place_rect(new_rect, id);\n                current_sat += delta;\n            } else {\n                company.rect = original;\n            }\n        }\n        temperature *= cooling_rate;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> n;\n    companies.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n\n    // Initialize grid\n    for (int i = 0; i < 10000; ++i) {\n        fill(grid[i].begin(), grid[i].end(), -1);\n    }\n\n    greedy_initialization();\n    local_search();\n    simulated_annealing();\n\n    for (const auto& company : companies) {\n        cout << company.rect.a << \" \" << company.rect.b << \" \"\n             << company.rect.c << \" \" << company.rect.d << \"\\n\";\n    }\n\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct Tile {\n    vector<pair<int, int>> cells;\n    int sum = 0;\n    int id;\n};\n\nstruct State {\n    int score;\n    int last_tile;\n    int last_x, last_y;\n    vector<bool> visited_tiles;\n    string path;\n\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> t(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> t[i][j];\n        }\n    }\n\n    vector<vector<int>> p(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> p[i][j];\n        }\n    }\n\n    // Step 1: Identify tiles using DSU\n    dsu d(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && t[i][j] == t[ni][nj]) {\n                    d.merge(i * N + j, ni * N + nj);\n                }\n            }\n        }\n    }\n\n    // Step 2: Build tiles\n    map<int, Tile> tiles;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int root = d.leader(i * N + j);\n            tiles[root].cells.emplace_back(i, j);\n            tiles[root].sum += p[i][j];\n            tiles[root].id = root;\n        }\n    }\n\n    // Step 3: Build adjacency list for tiles\n    map<int, vector<int>> adj;\n    for (auto& [root, tile] : tiles) {\n        set<int> neighbors;\n        for (auto [i, j] : tile.cells) {\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                    int nroot = d.leader(ni * N + nj);\n                    if (nroot != root) {\n                        neighbors.insert(nroot);\n                    }\n                }\n            }\n        }\n        for (int nroot : neighbors) {\n            adj[root].push_back(nroot);\n        }\n    }\n\n    // Step 4: Beam search\n    const int BEAM_WIDTH = 1000;\n    priority_queue<State> beam;\n    State initial;\n    int start_root = d.leader(si * N + sj);\n    initial.score = p[si][sj];\n    initial.last_tile = start_root;\n    initial.last_x = si;\n    initial.last_y = sj;\n    initial.visited_tiles.resize(tiles.size(), false);\n    initial.visited_tiles[start_root] = true;\n    initial.path = \"\";\n    beam.push(initial);\n\n    string best_path;\n    int best_score = 0;\n\n    while (!beam.empty()) {\n        priority_queue<State> next_beam;\n        for (int i = 0; i < BEAM_WIDTH && !beam.empty(); ++i) {\n            State current = beam.top();\n            beam.pop();\n\n            if (current.score > best_score) {\n                best_score = current.score;\n                best_path = current.path;\n            }\n\n            for (int next_root : adj[current.last_tile]) {\n                if (current.visited_tiles[next_root]) continue;\n\n                State next = current;\n                next.last_tile = next_root;\n                next.visited_tiles[next_root] = true;\n                next.score += tiles[next_root].sum;\n\n                // Find a path within the next tile to traverse all its cells\n                auto& cells = tiles[next_root].cells;\n                vector<vector<bool>> visited(N, vector<bool>(N, false));\n                vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n                queue<pair<int, int>> q;\n                q.push({current.last_x, current.last_y});\n                visited[current.last_x][current.last_y] = true;\n                bool found = false;\n                pair<int, int> end_pos;\n\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    if (t[x][y] == next_root && (x != current.last_x || y != current.last_y)) {\n                        end_pos = {x, y};\n                        found = true;\n                        break;\n                    }\n                    for (int k = 0; k < 4; ++k) {\n                        int nx = x + dx[k];\n                        int ny = y + dy[k];\n                        if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && t[nx][ny] == next_root) {\n                            visited[nx][ny] = true;\n                            parent[nx][ny] = {x, y};\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n\n                if (!found) continue;\n\n                // Reconstruct path within the tile\n                string tile_path;\n                pair<int, int> pos = end_pos;\n                while (pos != make_pair(current.last_x, current.last_y)) {\n                    auto [px, py] = parent[pos.first][pos.second];\n                    for (int k = 0; k < 4; ++k) {\n                        if (px == pos.first + dx[k] && py == pos.second + dy[k]) {\n                            tile_path += dir[k];\n                            break;\n                        }\n                    }\n                    pos = {px, py};\n                }\n                reverse(tile_path.begin(), tile_path.end());\n                next.path += tile_path;\n                next.last_x = end_pos.first;\n                next.last_y = end_pos.second;\n\n                next_beam.push(next);\n            }\n        }\n        beam = move(next_beam);\n    }\n\n    cout << best_path << endl;\n\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 30;\nconst int INF = 1e9;\nconst double ALPHA = 0.1; // Learning rate\n\nstruct Edge {\n    int to_i, to_j;\n    int dir; // 0: right (R), 1: down (D), 2: left (L), 3: up (U)\n    double weight;\n};\n\nvector<vector<vector<Edge>>> adj(N, vector<vector<Edge>>(N));\nvector<vector<double>> h(N, vector<double>(N-1, 5000.0)); // horizontal edges\nvector<vector<double>> v(N-1, vector<double>(N, 5000.0)); // vertical edges\n\nvoid init_adj() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (j + 1 < N) {\n                adj[i][j].push_back({i, j+1, 0, h[i][j]});\n            }\n            if (i + 1 < N) {\n                adj[i][j].push_back({i+1, j, 1, v[i][j]});\n            }\n            if (j - 1 >= 0) {\n                adj[i][j].push_back({i, j-1, 2, h[i][j-1]});\n            }\n            if (i - 1 >= 0) {\n                adj[i][j].push_back({i-1, j, 3, v[i-1][j]});\n            }\n        }\n    }\n}\n\nstring dijkstra(int si, int sj, int ti, int tj) {\n    vector<vector<double>> dist(N, vector<double>(N, INF));\n    vector<vector<pair<int, int>>> prev(N, vector<pair<int, int>>(N, {-1, -1}));\n    priority_queue<tuple<double, int, int>, vector<tuple<double, int, int>>, greater<>> pq;\n\n    dist[si][sj] = 0.0;\n    pq.emplace(0.0, si, sj);\n\n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top();\n        pq.pop();\n        if (i == ti && j == tj) break;\n        if (d > dist[i][j]) continue;\n        for (const auto& edge : adj[i][j]) {\n            int ni = edge.to_i;\n            int nj = edge.to_j;\n            double nd = d + edge.weight;\n            if (nd < dist[ni][nj]) {\n                dist[ni][nj] = nd;\n                prev[ni][nj] = {i, j};\n                pq.emplace(nd, ni, nj);\n            }\n        }\n    }\n\n    string path;\n    int ci = ti, cj = tj;\n    while (ci != si || cj != sj) {\n        auto [pi, pj] = prev[ci][cj];\n        if (pi == ci && pj == cj - 1) path += 'R';\n        else if (pi == ci && pj == cj + 1) path += 'L';\n        else if (pi == ci - 1 && pj == cj) path += 'D';\n        else if (pi == ci + 1 && pj == cj) path += 'U';\n        ci = pi;\n        cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nvoid update_weights(const string& path, int si, int sj, double total_length) {\n    int ci = si, cj = sj;\n    double path_length = 0.0;\n    for (char dir : path) {\n        int ni = ci, nj = cj;\n        if (dir == 'R') nj++;\n        else if (dir == 'L') nj--;\n        else if (dir == 'D') ni++;\n        else if (dir == 'U') ni--;\n\n        double edge_weight;\n        if (dir == 'R') edge_weight = h[ci][cj];\n        else if (dir == 'L') edge_weight = h[ci][cj-1];\n        else if (dir == 'D') edge_weight = v[ci][cj];\n        else if (dir == 'U') edge_weight = v[ci-1][cj];\n\n        path_length += edge_weight;\n        ci = ni;\n        cj = nj;\n    }\n\n    ci = si;\n    cj = sj;\n    for (char dir : path) {\n        int ni = ci, nj = cj;\n        if (dir == 'R') {\n            double new_weight = total_length * (h[ci][cj] / path_length);\n            h[ci][cj] = (1 - ALPHA) * h[ci][cj] + ALPHA * new_weight;\n            nj++;\n        } else if (dir == 'L') {\n            double new_weight = total_length * (h[ci][cj-1] / path_length);\n            h[ci][cj-1] = (1 - ALPHA) * h[ci][cj-1] + ALPHA * new_weight;\n            nj--;\n        } else if (dir == 'D') {\n            double new_weight = total_length * (v[ci][cj] / path_length);\n            v[ci][cj] = (1 - ALPHA) * v[ci][cj] + ALPHA * new_weight;\n            ni++;\n        } else if (dir == 'U') {\n            double new_weight = total_length * (v[ci-1][cj] / path_length);\n            v[ci-1][cj] = (1 - ALPHA) * v[ci-1][cj] + ALPHA * new_weight;\n            ni--;\n        }\n        ci = ni;\n        cj = nj;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    init_adj();\n\n    for (int k = 0; k < 1000; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n\n        string path = dijkstra(si, sj, ti, tj);\n        cout << path << endl;\n        cout.flush();\n\n        int total_length;\n        cin >> total_length;\n\n        update_weights(path, si, sj, total_length);\n    }\n\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int MAX_LEN = 12;\nconst vector<char> CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', '.'};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct State {\n    vector<string> grid;\n    int c; // number of matched strings\n    int d; // number of '.'\n    double energy;\n};\n\nvector<string> strings;\nint M;\n\nint count_matched(const vector<string>& grid) {\n    int matched = 0;\n    for (const string& s : strings) {\n        int k = s.size();\n        bool found = false;\n        // Check rows\n        for (int i = 0; i < N && !found; ++i) {\n            for (int j = 0; j < N && !found; ++j) {\n                bool match = true;\n                for (int p = 0; p < k; ++p) {\n                    if (grid[i][(j + p) % N] != s[p]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) {\n                    found = true;\n                    break;\n                }\n            }\n        }\n        // Check columns\n        for (int j = 0; j < N && !found; ++j) {\n            for (int i = 0; i < N && !found; ++i) {\n                bool match = true;\n                for (int p = 0; p < k; ++p) {\n                    if (grid[(i + p) % N][j] != s[p]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) {\n                    found = true;\n                    break;\n                }\n            }\n        }\n        if (found) {\n            matched++;\n        }\n    }\n    return matched;\n}\n\nint count_dots(const vector<string>& grid) {\n    int dots = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == '.') {\n                dots++;\n            }\n        }\n    }\n    return dots;\n}\n\ndouble compute_energy(int c, int d) {\n    if (c < M) {\n        return -1e8 * c / M;\n    } else {\n        return -1e8 * (2 * N * N) / (2 * N * N - d);\n    }\n}\n\nState get_initial_state() {\n    State state;\n    state.grid.resize(N, string(N, '.'));\n    state.d = N * N;\n    state.c = 0;\n    state.energy = compute_energy(state.c, state.d);\n\n    // Try to place as many strings as possible greedily\n    vector<bool> placed(M, false);\n    for (int iter = 0; iter < 1000; ++iter) {\n        int best_i = -1, best_j = -1, best_dir = -1, best_str = -1;\n        char best_char = '.';\n        double best_energy = state.energy;\n\n        for (int idx = 0; idx < M; ++idx) {\n            if (placed[idx]) continue;\n            const string& s = strings[idx];\n            int k = s.size();\n            // Try to place horizontally\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    bool can_place = true;\n                    for (int p = 0; p < k; ++p) {\n                        char c = state.grid[i][(j + p) % N];\n                        if (c != '.' && c != s[p]) {\n                            can_place = false;\n                            break;\n                        }\n                    }\n                    if (can_place) {\n                        vector<string> new_grid = state.grid;\n                        int new_d = state.d;\n                        for (int p = 0; p < k; ++p) {\n                            char& c = new_grid[i][(j + p) % N];\n                            if (c == '.') {\n                                c = s[p];\n                                new_d--;\n                            }\n                        }\n                        int new_c = count_matched(new_grid);\n                        int new_dots = count_dots(new_grid);\n                        double new_energy = compute_energy(new_c, new_dots);\n                        if (new_energy < best_energy) {\n                            best_energy = new_energy;\n                            best_i = i;\n                            best_j = j;\n                            best_dir = 0;\n                            best_str = idx;\n                        }\n                    }\n                }\n            }\n            // Try to place vertically\n            for (int j = 0; j < N; ++j) {\n                for (int i = 0; i < N; ++i) {\n                    bool can_place = true;\n                    for (int p = 0; p < k; ++p) {\n                        char c = state.grid[(i + p) % N][j];\n                        if (c != '.' && c != s[p]) {\n                            can_place = false;\n                            break;\n                        }\n                    }\n                    if (can_place) {\n                        vector<string> new_grid = state.grid;\n                        int new_d = state.d;\n                        for (int p = 0; p < k; ++p) {\n                            char& c = new_grid[(i + p) % N][j];\n                            if (c == '.') {\n                                c = s[p];\n                                new_d--;\n                            }\n                        }\n                        int new_c = count_matched(new_grid);\n                        int new_dots = count_dots(new_grid);\n                        double new_energy = compute_energy(new_c, new_dots);\n                        if (new_energy < best_energy) {\n                            best_energy = new_energy;\n                            best_i = i;\n                            best_j = j;\n                            best_dir = 1;\n                            best_str = idx;\n                        }\n                    }\n                }\n            }\n        }\n        if (best_str == -1) break;\n        placed[best_str] = true;\n        const string& s = strings[best_str];\n        int k = s.size();\n        if (best_dir == 0) {\n            for (int p = 0; p < k; ++p) {\n                char& c = state.grid[best_i][(best_j + p) % N];\n                if (c == '.') {\n                    c = s[p];\n                    state.d--;\n                }\n            }\n        } else {\n            for (int p = 0; p < k; ++p) {\n                char& c = state.grid[(best_i + p) % N][best_j];\n                if (c == '.') {\n                    c = s[p];\n                    state.d--;\n                }\n            }\n        }\n        state.c = count_matched(state.grid);\n        state.energy = compute_energy(state.c, state.d);\n    }\n    return state;\n}\n\nState simulated_annealing(State initial_state, double initial_temp, double final_temp, double cooling_rate, int iterations) {\n    State current = initial_state;\n    State best = current;\n    double temp = initial_temp;\n\n    for (int iter = 0; iter < iterations; ++iter) {\n        // Generate neighbor\n        int i = rng() % N;\n        int j = rng() % N;\n        char old_char = current.grid[i][j];\n        char new_char;\n        do {\n            new_char = CHARS[rng() % CHARS.size()];\n        } while (new_char == old_char);\n\n        // Compute new state\n        vector<string> new_grid = current.grid;\n        new_grid[i][j] = new_char;\n        int new_c = count_matched(new_grid);\n        int new_d = count_dots(new_grid);\n        double new_energy = compute_energy(new_c, new_d);\n\n        // Decide whether to accept\n        double delta_energy = new_energy - current.energy;\n        if (delta_energy < 0 || exp(-delta_energy / temp) > (double)rng() / rng.max()) {\n            current.grid = new_grid;\n            current.c = new_c;\n            current.d = new_d;\n            current.energy = new_energy;\n            if (current.energy < best.energy) {\n                best = current;\n            }\n        }\n\n        // Cool down\n        temp *= cooling_rate;\n        if (temp < final_temp) {\n            break;\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M;\n    strings.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i];\n    }\n\n    // Parameters for simulated annealing\n    double initial_temp = 1e4;\n    double final_temp = 1e-3;\n    double cooling_rate = 0.999;\n    int iterations = 1e6;\n\n    State initial_state = get_initial_state();\n    State best_state = simulated_annealing(initial_state, initial_temp, final_temp, cooling_rate, iterations);\n\n    for (const string& row : best_state.grid) {\n        cout << row << '\\n';\n    }\n\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int INF = 1e9;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nint N, si, sj;\nvector<string> grid;\nvector<vector<int>> cost;\nvector<vector<bool>> is_road;\nvector<vector<vector<Point>>> visible;\nvector<vector<int>> dist;\nvector<vector<Point>> parent;\nvector<Point> road_points;\n\nvoid precompute_visible() {\n    visible.assign(N, vector<vector<Point>>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!is_road[i][j]) continue;\n            // Check left\n            for (int k = j - 1; k >= 0; --k) {\n                if (!is_road[i][k]) break;\n                visible[i][j].emplace_back(i, k);\n            }\n            // Check right\n            for (int k = j + 1; k < N; ++k) {\n                if (!is_road[i][k]) break;\n                visible[i][j].emplace_back(i, k);\n            }\n            // Check up\n            for (int k = i - 1; k >= 0; --k) {\n                if (!is_road[k][j]) break;\n                visible[i][j].emplace_back(k, j);\n            }\n            // Check down\n            for (int k = i + 1; k < N; ++k) {\n                if (!is_road[k][j]) break;\n                visible[i][j].emplace_back(k, j);\n            }\n        }\n    }\n}\n\nvoid bfs(Point start) {\n    dist.assign(N, vector<int>(N, INF));\n    parent.assign(N, vector<Point>(N, Point(-1, -1)));\n    queue<Point> q;\n    dist[start.x][start.y] = 0;\n    q.push(start);\n    while (!q.empty()) {\n        Point p = q.front();\n        q.pop();\n        for (int d = 0; d < 4; ++d) {\n            int nx = p.x + dx[d];\n            int ny = p.y + dy[d];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            if (!is_road[nx][ny]) continue;\n            if (dist[nx][ny] > dist[p.x][p.y] + cost[nx][ny]) {\n                dist[nx][ny] = dist[p.x][p.y] + cost[nx][ny];\n                parent[nx][ny] = p;\n                q.push(Point(nx, ny));\n            }\n        }\n    }\n}\n\nstring reconstruct_path(Point start, Point end) {\n    string path;\n    Point p = end;\n    while (!(p == start)) {\n        Point par = parent[p.x][p.y];\n        for (int d = 0; d < 4; ++d) {\n            if (par.x + dx[d] == p.x && par.y + dy[d] == p.y) {\n                path += dir[d];\n                break;\n            }\n        }\n        p = par;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nstring solve() {\n    // Precompute road points\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (is_road[i][j]) {\n                road_points.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Precompute visible squares for each road point\n    precompute_visible();\n\n    // Greedy approach: start from (si, sj) and cover all road points\n    vector<bool> covered(N, vector<bool>(N, false));\n    vector<Point> route;\n    route.emplace_back(si, sj);\n    covered[si][sj] = true;\n\n    // Mark all points visible from (si, sj) as covered\n    for (const auto& p : visible[si][sj]) {\n        covered[p.x][p.y] = true;\n    }\n\n    // While there are uncovered points\n    while (true) {\n        bool all_covered = true;\n        for (const auto& p : road_points) {\n            if (!covered[p.x][p.y]) {\n                all_covered = false;\n                break;\n            }\n        }\n        if (all_covered) break;\n\n        // Find the nearest uncovered point\n        int min_dist = INF;\n        Point next_point;\n        string best_path;\n        for (const auto& p : road_points) {\n            if (covered[p.x][p.y]) continue;\n            bfs(route.back());\n            if (dist[p.x][p.y] < min_dist) {\n                min_dist = dist[p.x][p.y];\n                next_point = p;\n                best_path = reconstruct_path(route.back(), p);\n            }\n        }\n\n        // Move to the next point\n        route.push_back(next_point);\n        for (char c : best_path) {\n            if (c == 'U') route.emplace_back(route.back().x - 1, route.back().y);\n            else if (c == 'D') route.emplace_back(route.back().x + 1, route.back().y);\n            else if (c == 'L') route.emplace_back(route.back().x, route.back().y - 1);\n            else if (c == 'R') route.emplace_back(route.back().x, route.back().y + 1);\n        }\n\n        // Mark all points visible from the new point as covered\n        for (const auto& p : visible[next_point.x][next_point.y]) {\n            covered[p.x][p.y] = true;\n        }\n    }\n\n    // Return to start\n    bfs(route.back());\n    string return_path = reconstruct_path(route.back(), Point(si, sj));\n    for (char c : return_path) {\n        if (c == 'U') route.emplace_back(route.back().x - 1, route.back().y);\n        else if (c == 'D') route.emplace_back(route.back().x + 1, route.back().y);\n        else if (c == 'L') route.emplace_back(route.back().x, route.back().y - 1);\n        else if (c == 'R') route.emplace_back(route.back().x, route.back().y + 1);\n    }\n\n    // Reconstruct the path string\n    string result;\n    for (int i = 1; i < route.size(); ++i) {\n        Point prev = route[i-1];\n        Point curr = route[i];\n        if (prev.x == curr.x && prev.y == curr.y - 1) result += 'R';\n        else if (prev.x == curr.x && prev.y == curr.y + 1) result += 'L';\n        else if (prev.x == curr.x - 1 && prev.y == curr.y) result += 'D';\n        else if (prev.x == curr.x + 1 && prev.y == curr.y) result += 'U';\n    }\n\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> si >> sj;\n    grid.resize(N);\n    cost.assign(N, vector<int>(N));\n    is_road.assign(N, vector<bool>(N, false));\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                is_road[i][j] = true;\n                cost[i][j] = grid[i][j] - '0';\n            }\n        }\n    }\n\n    string ans = solve();\n    cout << ans << endl;\n\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <map>\n#include <set>\n#include <climits>\n#include <cassert>\n\nusing namespace std;\n\nstruct Task {\n    int id;\n    vector<int> difficulty;\n    vector<int> dependencies;\n    int in_degree = 0;\n    bool completed = false;\n    int assigned_member = -1;\n    int start_day = -1;\n    int completion_day = -1;\n};\n\nstruct Member {\n    int id;\n    vector<int> skills;\n    int current_task = -1;\n    int task_end_day = -1;\n    vector<pair<int, int>> task_history; // task_id, completion_time\n};\n\nclass Scheduler {\nprivate:\n    int N, M, K, R;\n    vector<Task> tasks;\n    vector<Member> members;\n    vector<vector<int>> adj;\n    vector<int> in_degree;\n    vector<int> topo_order;\n    vector<vector<int>> task_dependencies;\n    vector<vector<int>> task_dependents;\n    vector<vector<int>> skill_estimates;\n    vector<int> available_members;\n    int current_day = 0;\n    mt19937 rng;\n\n    void topological_sort() {\n        queue<int> q;\n        for (int i = 0; i < N; ++i) {\n            if (in_degree[i] == 0) {\n                q.push(i);\n            }\n        }\n        while (!q.empty()) {\n            int u = q.front();\n            q.pop();\n            topo_order.push_back(u);\n            for (int v : adj[u]) {\n                if (--in_degree[v] == 0) {\n                    q.push(v);\n                }\n            }\n        }\n    }\n\n    void update_skill_estimates(int member_id, int task_id, int completion_time) {\n        Member& member = members[member_id];\n        Task& task = tasks[task_id];\n        member.task_history.emplace_back(task_id, completion_time);\n\n        // Simple heuristic: adjust skills based on completion time\n        for (int k = 0; k < K; ++k) {\n            int diff = task.difficulty[k];\n            int& skill = skill_estimates[member_id][k];\n            if (completion_time == 1) {\n                // Likely skill >= difficulty\n                skill = max(skill, diff);\n            } else {\n                // Likely skill < difficulty\n                skill = min(skill, diff - 1);\n            }\n        }\n    }\n\n    int estimate_completion_time(int member_id, int task_id) {\n        const Member& member = members[member_id];\n        const Task& task = tasks[task_id];\n        int w = 0;\n        for (int k = 0; k < K; ++k) {\n            w += max(0, task.difficulty[k] - skill_estimates[member_id][k]);\n        }\n        if (w == 0) {\n            return 1;\n        } else {\n            // Random component is unknown, so we use a heuristic\n            return max(1, w + 0); // Assuming r_i = 0 for estimation\n        }\n    }\n\n    void assign_tasks() {\n        vector<pair<int, int>> assignments;\n        for (int member_id : available_members) {\n            if (members[member_id].current_task != -1) continue;\n\n            // Find the best task for this member\n            int best_task = -1;\n            int best_time = INT_MAX;\n            for (int task_id : topo_order) {\n                Task& task = tasks[task_id];\n                if (task.completed || task.assigned_member != -1) continue;\n                bool ready = true;\n                for (int dep : task.dependencies) {\n                    if (!tasks[dep].completed) {\n                        ready = false;\n                        break;\n                    }\n                }\n                if (!ready) continue;\n\n                int est_time = estimate_completion_time(member_id, task_id);\n                if (est_time < best_time) {\n                    best_time = est_time;\n                    best_task = task_id;\n                }\n            }\n\n            if (best_task != -1) {\n                Task& task = tasks[best_task];\n                task.assigned_member = member_id;\n                task.start_day = current_day;\n                members[member_id].current_task = best_task;\n                members[member_id].task_end_day = current_day + best_time - 1;\n                assignments.emplace_back(member_id, best_task);\n            }\n        }\n\n        // Output assignments\n        cout << assignments.size();\n        for (auto [member_id, task_id] : assignments) {\n            cout << \" \" << member_id + 1 << \" \" << task_id + 1;\n        }\n        cout << endl;\n    }\n\n    void process_completions(const vector<int>& completed_members) {\n        for (int member_id : completed_members) {\n            Member& member = members[member_id];\n            if (member.current_task == -1) continue;\n\n            Task& task = tasks[member.current_task];\n            task.completed = true;\n            task.completion_day = current_day;\n            member.current_task = -1;\n            member.task_end_day = -1;\n            available_members.push_back(member_id);\n\n            // Update skill estimates\n            int completion_time = current_day - task.start_day + 1;\n            update_skill_estimates(member_id, task.id, completion_time);\n        }\n    }\n\npublic:\n    Scheduler(int N, int M, int K, int R, const vector<vector<int>>& difficulties, const vector<pair<int, int>>& dependencies)\n        : N(N), M(M), K(K), R(R), rng(random_device{}()) {\n        tasks.resize(N);\n        for (int i = 0; i < N; ++i) {\n            tasks[i].id = i;\n            tasks[i].difficulty = difficulties[i];\n        }\n\n        adj.resize(N);\n        in_degree.resize(N, 0);\n        task_dependencies.resize(N);\n        task_dependents.resize(N);\n        for (auto [u, v] : dependencies) {\n            u--; v--;\n            adj[u].push_back(v);\n            in_degree[v]++;\n            task_dependencies[v].push_back(u);\n            task_dependents[u].push_back(v);\n        }\n\n        topological_sort();\n\n        members.resize(M);\n        for (int i = 0; i < M; ++i) {\n            members[i].id = i;\n            members[i].skills.resize(K, 0);\n            skill_estimates.push_back(vector<int>(K, 0)); // Initial estimate: all skills are 0\n            available_members.push_back(i);\n        }\n    }\n\n    void run() {\n        while (current_day < 2000) {\n            current_day++;\n            assign_tasks();\n\n            int n;\n            cin >> n;\n            if (n == -1) {\n                break;\n            }\n            vector<int> completed_members(n);\n            for (int i = 0; i < n; ++i) {\n                cin >> completed_members[i];\n                completed_members[i]--;\n            }\n            process_completions(completed_members);\n        }\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<vector<int>> difficulties(N, vector<int>(K));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> difficulties[i][j];\n        }\n    }\n\n    vector<pair<int, int>> dependencies(R);\n    for (int i = 0; i < R; ++i) {\n        cin >> dependencies[i].first >> dependencies[i].second;\n    }\n\n    Scheduler scheduler(N, M, K, R, difficulties, dependencies);\n    scheduler.run();\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 1000;\nconst int M = 50;\nconst int OFFICE_X = 400;\nconst int OFFICE_Y = 400;\n\nstruct Order {\n    int id;\n    int a, b, c, d;\n    int dist_to_office;\n    int dist_pickup_delivery;\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nvector<Order> orders;\nvector<int> selected_orders;\nvector<pair<int, int>> points;\nvector<int> route;\n\nint compute_total_distance(const vector<int>& route) {\n    int total = 0;\n    for (int i = 0; i < (int)route.size() - 1; ++i) {\n        auto [x1, y1] = points[route[i]];\n        auto [x2, y2] = points[route[i+1]];\n        total += manhattan(x1, y1, x2, y2);\n    }\n    return total;\n}\n\nvoid two_opt(vector<int>& route) {\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 1; i < (int)route.size() - 2; ++i) {\n            for (int j = i + 1; j < (int)route.size() - 1; ++j) {\n                if (j - i == 1) continue;\n                int a = route[i-1];\n                int b = route[i];\n                int c = route[j];\n                int d = route[j+1];\n                int current = manhattan(points[a].first, points[a].second, points[b].first, points[b].second) +\n                              manhattan(points[c].first, points[c].second, points[d].first, points[d].second);\n                int new_dist = manhattan(points[a].first, points[a].second, points[c].first, points[c].second) +\n                               manhattan(points[b].first, points[b].second, points[d].first, points[d].second);\n                if (new_dist < current) {\n                    reverse(route.begin() + i, route.begin() + j + 1);\n                    improved = true;\n                }\n            }\n        }\n    }\n}\n\nvoid solve() {\n    // Read input\n    orders.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n        orders[i].id = i + 1;\n        orders[i].dist_to_office = manhattan(orders[i].a, orders[i].b, OFFICE_X, OFFICE_Y) +\n                                   manhattan(orders[i].c, orders[i].d, OFFICE_X, OFFICE_Y);\n        orders[i].dist_pickup_delivery = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n    }\n\n    // Select orders with smallest dist_to_office\n    sort(orders.begin(), orders.end(), [](const Order& a, const Order& b) {\n        return a.dist_to_office < b.dist_to_office;\n    });\n    selected_orders.clear();\n    for (int i = 0; i < M; ++i) {\n        selected_orders.push_back(orders[i].id);\n    }\n\n    // Prepare points: 0 is office, 1..M are pickups, M+1..2M are deliveries\n    points.clear();\n    points.emplace_back(OFFICE_X, OFFICE_Y); // 0\n    for (int i = 0; i < M; ++i) {\n        points.emplace_back(orders[i].a, orders[i].b); // 1..M\n    }\n    for (int i = 0; i < M; ++i) {\n        points.emplace_back(orders[i].c, orders[i].d); // M+1..2M\n    }\n\n    // Initial route: office -> pickups -> deliveries -> office\n    route.clear();\n    route.push_back(0);\n    for (int i = 1; i <= M; ++i) {\n        route.push_back(i);\n    }\n    for (int i = M + 1; i <= 2 * M; ++i) {\n        route.push_back(i);\n    }\n    route.push_back(0);\n\n    // Optimize with 2-opt\n    two_opt(route);\n\n    // Output\n    cout << M;\n    for (int id : selected_orders) {\n        cout << \" \" << id;\n    }\n    cout << \"\\n\";\n\n    cout << route.size();\n    for (int idx : route) {\n        cout << \" \" << points[idx].first << \" \" << points[idx].second;\n    }\n    cout << \"\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v;\n    int d;\n    int l;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 400;\n    int M = 1995;\n\n    vector<pair<int, int>> points(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> points[i].first >> points[i].second;\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        int dx = points[edges[i].u].first - points[edges[i].v].first;\n        int dy = points[edges[i].u].second - points[edges[i].v].second;\n        edges[i].d = round(sqrt(dx * dx + dy * dy));\n    }\n\n    dsu uf(N);\n    vector<bool> used(M, false);\n    int components = N;\n\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].l;\n        if (uf.same(edges[i].u, edges[i].v)) {\n            cout << 0 << '\\n';\n            cout.flush();\n            continue;\n        }\n        // Accept if the edge is not too expensive relative to d_i\n        if (edges[i].l <= 2 * edges[i].d) {\n            uf.merge(edges[i].u, edges[i].v);\n            cout << 1 << '\\n';\n            cout.flush();\n        } else {\n            cout << 0 << '\\n';\n            cout.flush();\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int GRID_SIZE = 30;\nconst int TURNS = 300;\nconst int MAX_PETS = 20;\nconst int MAX_HUMANS = 10;\n\nstruct Pet {\n    int x, y, type;\n    int target_human = -1;\n    int target_x = -1, target_y = -1;\n};\n\nstruct Human {\n    int x, y;\n};\n\nint N, M;\nvector<Pet> pets;\nvector<Human> humans;\nvector<vector<bool>> blocked(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\nvector<vector<int>> pet_grid(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\nvector<vector<int>> human_grid(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n\nconst vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst string dir_chars = \"udlrUDLR\";\n\nvoid initialize() {\n    cin >> N;\n    pets.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n        pet_grid[pets[i].x][pets[i].y]++;\n    }\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].x >> humans[i].y;\n        human_grid[humans[i].x][humans[i].y]++;\n    }\n    blocked.assign(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\n    for (int i = 0; i <= GRID_SIZE + 1; ++i) {\n        blocked[i][0] = blocked[i][GRID_SIZE + 1] = true;\n        blocked[0][i] = blocked[GRID_SIZE + 1][i] = true;\n    }\n}\n\nbool is_valid(int x, int y) {\n    return x >= 1 && x <= GRID_SIZE && y >= 1 && y <= GRID_SIZE && !blocked[x][y];\n}\n\nbool can_block(int x, int y) {\n    if (x < 1 || x > GRID_SIZE || y < 1 || y > GRID_SIZE) return false;\n    if (blocked[x][y] || pet_grid[x][y] > 0 || human_grid[x][y] > 0) return false;\n    for (auto [dx, dy] : directions) {\n        int nx = x + dx, ny = y + dy;\n        if (nx >= 1 && nx <= GRID_SIZE && ny >= 1 && ny <= GRID_SIZE && pet_grid[nx][ny] > 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvector<pair<int, int>> get_adjacent_passable(int x, int y) {\n    vector<pair<int, int>> res;\n    for (auto [dx, dy] : directions) {\n        int nx = x + dx, ny = y + dy;\n        if (is_valid(nx, ny)) {\n            res.emplace_back(nx, ny);\n        }\n    }\n    return res;\n}\n\nvoid update_grids() {\n    pet_grid.assign(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n    human_grid.assign(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n    for (auto &pet : pets) {\n        pet_grid[pet.x][pet.y]++;\n    }\n    for (auto &human : humans) {\n        human_grid[human.x][human.y]++;\n    }\n}\n\nvoid move_pets() {\n    vector<string> moves(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> moves[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        auto &pet = pets[i];\n        int x = pet.x, y = pet.y;\n        for (char c : moves[i]) {\n            int dx = 0, dy = 0;\n            if (c == 'U') dx = -1;\n            else if (c == 'D') dx = 1;\n            else if (c == 'L') dy = -1;\n            else if (c == 'R') dy = 1;\n            int nx = x + dx, ny = y + dy;\n            if (is_valid(nx, ny)) {\n                x = nx;\n                y = ny;\n            }\n        }\n        pet.x = x;\n        pet.y = y;\n    }\n    update_grids();\n}\n\nint bfs(int x, int y) {\n    vector<vector<bool>> visited(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\n    queue<pair<int, int>> q;\n    q.emplace(x, y);\n    visited[x][y] = true;\n    int count = 0;\n    while (!q.empty()) {\n        auto [cx, cy] = q.front();\n        q.pop();\n        count++;\n        for (auto [dx, dy] : directions) {\n            int nx = cx + dx, ny = cy + dy;\n            if (is_valid(nx, ny) && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return count;\n}\n\nint count_pets_in_area(int x, int y) {\n    vector<vector<bool>> visited(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\n    queue<pair<int, int>> q;\n    q.emplace(x, y);\n    visited[x][y] = true;\n    int count = 0;\n    while (!q.empty()) {\n        auto [cx, cy] = q.front();\n        q.pop();\n        count += pet_grid[cx][cy];\n        for (auto [dx, dy] : directions) {\n            int nx = cx + dx, ny = cy + dy;\n            if (is_valid(nx, ny) && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return count;\n}\n\nvoid decide_human_actions() {\n    string actions;\n    for (int i = 0; i < M; ++i) {\n        auto &human = humans[i];\n        int x = human.x, y = human.y;\n        bool blocked_something = false;\n        for (auto [dx, dy] : directions) {\n            int nx = x + dx, ny = y + dy;\n            if (can_block(nx, ny)) {\n                blocked[nx][ny] = true;\n                actions += dir_chars[dx + 1];\n                blocked_something = true;\n                break;\n            }\n        }\n        if (!blocked_something) {\n            vector<pair<int, int>> adj = get_adjacent_passable(x, y);\n            if (!adj.empty()) {\n                auto [nx, ny] = adj[rand() % adj.size()];\n                human.x = nx;\n                human.y = ny;\n                actions += toupper(dir_chars[rand() % 4]);\n            } else {\n                actions += '.';\n            }\n        }\n    }\n    cout << actions << endl;\n    cout.flush();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    initialize();\n    for (int turn = 0; turn < TURNS; ++turn) {\n        decide_human_actions();\n        move_pets();\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int INF = 1e9;\nconst vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst string dir_chars = \"UDLR\";\n\nint si, sj, ti, tj;\ndouble p;\nvector<string> h, v;\n\nvector<vector<int>> bfs_shortest_path() {\n    vector<vector<int>> dist(N, vector<int>(N, INF));\n    queue<pair<int, int>> q;\n    dist[ti][tj] = 0;\n    q.emplace(ti, tj);\n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && dist[ni][nj] == INF) {\n                dist[ni][nj] = dist[i][j] + 1;\n                q.emplace(ni, nj);\n            }\n        }\n    }\n    return dist;\n}\n\nstring construct_path(const vector<vector<int>>& dist) {\n    string path;\n    int i = si, j = sj;\n    while (i != ti || j != tj) {\n        int best_d = -1;\n        int best_dist = INF;\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && dist[ni][nj] < best_dist) {\n                best_dist = dist[ni][nj];\n                best_d = d;\n            }\n        }\n        if (best_d == -1) break;\n        path += dir_chars[best_d];\n        i += dirs[best_d].first;\n        j += dirs[best_d].second;\n    }\n    return path;\n}\n\nstring make_robust_path(const string& shortest_path) {\n    string robust_path;\n    for (char c : shortest_path) {\n        robust_path += c;\n        robust_path += c;\n    }\n    if (robust_path.size() > 200) {\n        robust_path = shortest_path;\n    }\n    return robust_path;\n}\n\nint main() {\n    cin >> si >> sj >> ti >> tj >> p;\n    h.resize(N);\n    v.resize(N - 1);\n    for (int i = 0; i < N; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N - 1; ++i) {\n        cin >> v[i];\n    }\n\n    auto dist = bfs_shortest_path();\n    string shortest_path = construct_path(dist);\n    string robust_path = make_robust_path(shortest_path);\n\n    // Ensure the path length is <= 200\n    if (robust_path.size() > 200) {\n        robust_path = shortest_path.substr(0, 200);\n    }\n\n    cout << robust_path << endl;\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 30;\nconst int dx[4] = {0, -1, 0, 1};\nconst int dy[4] = {-1, 0, 1, 0};\nconst int to[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\n\nvector<string> initial_tiles;\nvector<vector<int>> tiles;\nvector<vector<int>> rotations;\nvector<vector<bool>> visited;\nvector<pair<int, int>> loop_lengths;\n\nint compute_loop_length(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    do {\n        int d2 = to[tiles[i][j]][d];\n        if (d2 == -1) return 0;\n        i += dx[d2];\n        j += dy[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n    } while (!(i == si && j == sj && d == sd));\n    return length;\n}\n\nvoid find_loops() {\n    visited.assign(N, vector<bool>(N, false));\n    loop_lengths.clear();\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (visited[i][j]) continue;\n            for (int d = 0; d < 4; ++d) {\n                int d2 = to[tiles[i][j]][d];\n                if (d2 == -1) continue;\n                int ni = i + dx[d2];\n                int nj = j + dy[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) % 4;\n                int length = compute_loop_length(i, j, d);\n                if (length > 0) {\n                    loop_lengths.emplace_back(length, (i << 16) | (j << 8) | d);\n                    for (int x = 0; x < N; ++x) {\n                        for (int y = 0; y < N; ++y) {\n                            if (visited[x][y]) continue;\n                            for (int dd = 0; dd < 4; ++dd) {\n                                int l = compute_loop_length(x, y, dd);\n                                if (l == length) {\n                                    visited[x][y] = true;\n                                }\n                            }\n                        }\n                    }\n                    goto next_tile;\n                }\n            }\n        }\n        next_tile:;\n    }\n    sort(loop_lengths.rbegin(), loop_lengths.rend());\n}\n\nlong long evaluate() {\n    find_loops();\n    if (loop_lengths.size() < 2) return 0;\n    return (long long)loop_lengths[0].first * loop_lengths[1].first;\n}\n\nvoid apply_rotations() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int type = initial_tiles[i][j] - '0';\n            int rot = rotations[i][j];\n            tiles[i][j] = (type + rot) % 8;\n            if (type >= 0 && type <= 3) {\n                tiles[i][j] = (type + rot) % 4;\n            } else if (type >= 4 && type <= 5) {\n                tiles[i][j] = 4 + (rot % 2);\n            } else if (type >= 6 && type <= 7) {\n                tiles[i][j] = 6 + (rot % 2);\n            }\n        }\n    }\n}\n\nvoid solve() {\n    initial_tiles.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> initial_tiles[i];\n    }\n\n    rotations.assign(N, vector<int>(N, 0));\n    tiles.assign(N, vector<int>(N, 0));\n    apply_rotations();\n    long long best_score = evaluate();\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n    uniform_real_distribution<> prob(0.0, 1.0);\n\n    int iterations = 10000;\n    double temperature = 1000.0;\n    double cooling_rate = 0.99;\n\n    for (int iter = 0; iter < iterations; ++iter) {\n        int i = gen() % N;\n        int j = gen() % N;\n        int old_rot = rotations[i][j];\n        int new_rot = dis(gen);\n        rotations[i][j] = new_rot;\n        apply_rotations();\n        long long new_score = evaluate();\n        if (new_score > best_score || prob(gen) < exp((new_score - best_score) / temperature)) {\n            best_score = new_score;\n        } else {\n            rotations[i][j] = old_rot;\n            apply_rotations();\n        }\n        temperature *= cooling_rate;\n    }\n\n    string output;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            output += to_string(rotations[i][j]);\n        }\n    }\n    cout << output << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\nconst int rev[] = {2, 3, 0, 1};\n\nstruct State {\n    vector<vector<int>> board;\n    int empty_x, empty_y;\n    string moves;\n    int tree_size;\n    int steps;\n\n    State(int N) : board(N, vector<int>(N)), empty_x(0), empty_y(0), moves(\"\"), tree_size(0), steps(0) {}\n\n    bool operator<(const State& other) const {\n        if (tree_size != other.tree_size) {\n            return tree_size > other.tree_size;\n        }\n        return steps < other.steps;\n    }\n};\n\nint calculate_tree_size(const vector<vector<int>>& board) {\n    int N = board.size();\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    int max_size = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0 || visited[i][j]) continue;\n\n            queue<pair<int, int>> q;\n            q.push({i, j});\n            visited[i][j] = true;\n            int size = 0;\n\n            while (!q.empty()) {\n                auto [x, y] = q.front();\n                q.pop();\n                size++;\n\n                int mask = board[x][y];\n                if (x > 0 && (mask & 2) && (board[x-1][y] & 8) && !visited[x-1][y]) {\n                    visited[x-1][y] = true;\n                    q.push({x-1, y});\n                }\n                if (x < N-1 && (mask & 8) && (board[x+1][y] & 2) && !visited[x+1][y]) {\n                    visited[x+1][y] = true;\n                    q.push({x+1, y});\n                }\n                if (y > 0 && (mask & 1) && (board[x][y-1] & 4) && !visited[x][y-1]) {\n                    visited[x][y-1] = true;\n                    q.push({x, y-1});\n                }\n                if (y < N-1 && (mask & 4) && (board[x][y+1] & 1) && !visited[x][y+1]) {\n                    visited[x][y+1] = true;\n                    q.push({x, y+1});\n                }\n            }\n\n            max_size = max(max_size, size);\n        }\n    }\n\n    return max_size;\n}\n\nvector<State> generate_next_states(const State& current, int N, int T) {\n    vector<State> next_states;\n\n    for (int d = 0; d < 4; ++d) {\n        int nx = current.empty_x + dx[d];\n        int ny = current.empty_y + dy[d];\n\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n\n        State next = current;\n        swap(next.board[current.empty_x][current.empty_y], next.board[nx][ny]);\n        next.empty_x = nx;\n        next.empty_y = ny;\n        next.moves += dir[d];\n        next.steps++;\n\n        if (next.steps > T) continue;\n\n        next.tree_size = calculate_tree_size(next.board);\n        next_states.push_back(next);\n    }\n\n    return next_states;\n}\n\nstring solve(int N, int T, const vector<string>& input) {\n    State initial(N);\n    int empty_count = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = input[i][j];\n            if (c == '0') {\n                initial.board[i][j] = 0;\n                initial.empty_x = i;\n                initial.empty_y = j;\n                empty_count++;\n            } else {\n                initial.board[i][j] = stoi(string(1, c), nullptr, 16);\n            }\n        }\n    }\n\n    if (empty_count != 1) {\n        return \"\";\n    }\n\n    initial.tree_size = calculate_tree_size(initial.board);\n\n    priority_queue<State> pq;\n    pq.push(initial);\n\n    int beam_width = 1000;\n    int max_tree_size = 0;\n    string best_moves;\n\n    while (!pq.empty()) {\n        vector<State> current_level;\n\n        while (!pq.empty() && current_level.size() < beam_width) {\n            current_level.push_back(pq.top());\n            pq.pop();\n        }\n\n        for (const State& current : current_level) {\n            if (current.tree_size == N * N - 1) {\n                return current.moves;\n            }\n\n            if (current.tree_size > max_tree_size) {\n                max_tree_size = current.tree_size;\n                best_moves = current.moves;\n            }\n\n            vector<State> next_states = generate_next_states(current, N, T);\n            for (const State& next : next_states) {\n                pq.push(next);\n            }\n        }\n    }\n\n    return best_moves;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    cin >> N >> T;\n    vector<string> input(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> input[i];\n    }\n\n    string result = solve(N, T, input);\n    cout << result << endl;\n\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int MAX_K = 100;\nconst int MAX_D = 10;\nconst int MAX_A = 100;\nconst int RADIUS = 10000;\nconst int RADIUS_SQ = RADIUS * RADIUS;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n    bool operator==(const Point& p) const {\n        return x == p.x && y == p.y;\n    }\n};\n\nstruct Line {\n    int px, py, qx, qy;\n    Line(int px, int py, int qx, int qy) : px(px), py(py), qx(qx), qy(qy) {}\n};\n\nint N, K;\nvector<int> a(MAX_D + 1);\nvector<Point> strawberries;\nvector<Line> cuts;\n\nint cross(const Point& o, const Point& a, const Point& b) {\n    return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n}\n\nint side(const Line& l, const Point& p) {\n    Point a(l.px, l.py), b(l.qx, l.qy);\n    long long c = (long long)(b.x - a.x) * (p.y - a.y) - (long long)(b.y - a.y) * (p.x - a.x);\n    if (c > 0) return 1;\n    if (c < 0) return -1;\n    return 0;\n}\n\nvector<vector<int>> regions;\n\nvoid init_regions() {\n    regions.clear();\n    regions.push_back(vector<int>());\n    for (int i = 0; i < N; ++i) {\n        regions[0].push_back(i);\n    }\n}\n\nvoid apply_cut(const Line& cut) {\n    vector<vector<int>> new_regions;\n    for (auto& region : regions) {\n        vector<int> left, right, on;\n        for (int idx : region) {\n            int s = side(cut, strawberries[idx]);\n            if (s == 1) left.push_back(idx);\n            else if (s == -1) right.push_back(idx);\n            else on.push_back(idx);\n        }\n        if (!left.empty()) new_regions.push_back(left);\n        if (!right.empty()) new_regions.push_back(right);\n    }\n    regions = new_regions;\n}\n\nint compute_score() {\n    vector<int> counts(MAX_D + 1, 0);\n    for (auto& region : regions) {\n        int cnt = region.size();\n        if (cnt <= MAX_D) counts[cnt]++;\n    }\n    int score = 0;\n    for (int d = 1; d <= MAX_D; ++d) {\n        score += min(a[d], counts[d]);\n    }\n    return score;\n}\n\nLine generate_random_line() {\n    int idx1 = rand() % N;\n    int idx2 = rand() % N;\n    while (idx1 == idx2) idx2 = rand() % N;\n    Point p1 = strawberries[idx1];\n    Point p2 = strawberries[idx2];\n    return Line(p1.x, p1.y, p2.x, p2.y);\n}\n\nLine generate_best_line(int iterations) {\n    Line best_line(0, 0, 0, 0);\n    int best_score = -1;\n    for (int i = 0; i < iterations; ++i) {\n        Line candidate = generate_random_line();\n        vector<vector<int>> temp_regions = regions;\n        apply_cut(candidate);\n        int current_score = compute_score();\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_line = candidate;\n        }\n        regions = temp_regions;\n    }\n    return best_line;\n}\n\nvoid solve() {\n    cin >> N >> K;\n    for (int d = 1; d <= MAX_D; ++d) {\n        cin >> a[d];\n    }\n    strawberries.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> strawberries[i].x >> strawberries[i].y;\n    }\n\n    init_regions();\n    int current_score = compute_score();\n    for (int k = 0; k < K; ++k) {\n        Line best_line = generate_best_line(1000);\n        apply_cut(best_line);\n        int new_score = compute_score();\n        if (new_score > current_score) {\n            current_score = new_score;\n            cuts.push_back(best_line);\n        } else {\n            break;\n        }\n    }\n\n    cout << cuts.size() << endl;\n    for (auto& cut : cuts) {\n        cout << cut.px << \" \" << cut.py << \" \" << cut.qx << \" \" << cut.qy << endl;\n    }\n}\n\nint main() {\n    srand(time(0));\n    solve();\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <cmath>\n#include <unordered_set>\n#include <chrono>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nint N, M;\nvector<Point> initial_dots;\nvector<vector<bool>> has_dot;\nvector<Rectangle> rectangles;\nint center;\nlong long total_weight = 0;\n\nlong long weight(int x, int y) {\n    long long dx = x - center;\n    long long dy = y - center;\n    return dx * dx + dy * dy + 1;\n}\n\nvoid precompute_weights() {\n    center = (N - 1) / 2;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y < N; ++y) {\n            total_weight += weight(x, y);\n        }\n    }\n}\n\nbool is_valid_point(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_perimeter(const Rectangle& rect) {\n    vector<Point> points = {rect.p1, rect.p2, rect.p3, rect.p4};\n    for (int i = 0; i < 4; ++i) {\n        Point a = points[i];\n        Point b = points[(i + 1) % 4];\n        if (a.x == b.x) {\n            int x = a.x;\n            int y1 = min(a.y, b.y);\n            int y2 = max(a.y, b.y);\n            for (int y = y1; y <= y2; ++y) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        } else if (a.y == b.y) {\n            int y = a.y;\n            int x1 = min(a.x, b.x);\n            int x2 = max(a.x, b.x);\n            for (int x = x1; x <= x2; ++x) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        } else {\n            int dx = b.x - a.x;\n            int dy = b.y - a.y;\n            if (abs(dx) != abs(dy)) {\n                return false;\n            }\n            int step = dx > 0 ? 1 : -1;\n            for (int x = a.x, y = a.y; x != b.x; x += step, y += step * dy / dx) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool check_overlap(const Rectangle& new_rect) {\n    for (const auto& rect : rectangles) {\n        vector<Point> new_points = {new_rect.p1, new_rect.p2, new_rect.p3, new_rect.p4};\n        vector<Point> old_points = {rect.p1, rect.p2, rect.p3, rect.p4};\n        for (int i = 0; i < 4; ++i) {\n            Point a1 = new_points[i];\n            Point b1 = new_points[(i + 1) % 4];\n            for (int j = 0; j < 4; ++j) {\n                Point a2 = old_points[j];\n                Point b2 = old_points[(j + 1) % 4];\n                if (a1 == a2 && b1 == b2) return true;\n                if (a1 == b2 && b1 == a2) return true;\n            }\n        }\n    }\n    return false;\n}\n\nvector<Rectangle> generate_candidates() {\n    vector<Rectangle> candidates;\n    for (int i = 0; i < initial_dots.size(); ++i) {\n        for (int j = i + 1; j < initial_dots.size(); ++j) {\n            Point p2 = initial_dots[i];\n            Point p3 = initial_dots[j];\n            // Axis-aligned rectangle\n            {\n                Point p1(p2.x, p3.y);\n                Point p4(p3.x, p2.y);\n                if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                    Rectangle rect(p1, p2, p3, p4);\n                    if (check_perimeter(rect) && !check_overlap(rect)) {\n                        candidates.push_back(rect);\n                    }\n                }\n            }\n            // 45-degree rotated rectangle\n            {\n                int dx = p3.x - p2.x;\n                int dy = p3.y - p2.y;\n                if (abs(dx) == abs(dy)) {\n                    Point p1(p2.x + dy, p2.y - dx);\n                    Point p4(p3.x + dy, p3.y - dx);\n                    if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                        Rectangle rect(p1, p2, p3, p4);\n                        if (check_perimeter(rect) && !check_overlap(rect)) {\n                            candidates.push_back(rect);\n                        }\n                    }\n                    p1 = Point(p2.x - dy, p2.y + dx);\n                    p4 = Point(p3.x - dy, p3.y + dx);\n                    if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                        Rectangle rect(p1, p2, p3, p4);\n                        if (check_perimeter(rect) && !check_overlap(rect)) {\n                            candidates.push_back(rect);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return candidates;\n}\n\nvoid solve() {\n    precompute_weights();\n    has_dot.assign(N, vector<bool>(N, false));\n    for (const auto& dot : initial_dots) {\n        has_dot[dot.x][dot.y] = true;\n    }\n\n    auto start_time = chrono::high_resolution_clock::now();\n    while (true) {\n        auto candidates = generate_candidates();\n        if (candidates.empty()) break;\n\n        Rectangle best_rect;\n        long long best_score = -1;\n        for (const auto& rect : candidates) {\n            long long current_score = weight(rect.p1.x, rect.p1.y);\n            if (current_score > best_score) {\n                best_score = current_score;\n                best_rect = rect;\n            }\n        }\n\n        if (best_score == -1) break;\n\n        rectangles.push_back(best_rect);\n        has_dot[best_rect.p1.x][best_rect.p1.y] = true;\n        initial_dots.push_back(best_rect.p1);\n\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 4500) break;\n    }\n\n    cout << rectangles.size() << endl;\n    for (const auto& rect : rectangles) {\n        cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n             << rect.p2.x << \" \" << rect.p2.y << \" \"\n             << rect.p3.x << \" \" << rect.p3.y << \" \"\n             << rect.p4.x << \" \" << rect.p4.y << endl;\n    }\n}\n\nint main() {\n    cin >> N >> M;\n    initial_dots.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> initial_dots[i].x >> initial_dots[i].y;\n    }\n    solve();\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <cstring>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 10;\nconst int TOTAL_CANDIES = 100;\nconst vector<char> DIRECTIONS = {'F', 'B', 'L', 'R'};\n\nstruct Grid {\n    int cells[N][N];\n    int empty_count;\n\n    Grid() {\n        memset(cells, 0, sizeof(cells));\n        empty_count = N * N;\n    }\n\n    void place_candy(int pos, int flavor) {\n        int idx = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] == 0) {\n                    if (++idx == pos) {\n                        cells[i][j] = flavor;\n                        empty_count--;\n                        return;\n                    }\n                }\n            }\n        }\n    }\n\n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; ++j) {\n                int write_pos = N - 1;\n                for (int i = N - 1; i >= 0; --i) {\n                    if (cells[i][j] != 0) {\n                        cells[write_pos--][j] = cells[i][j];\n                    }\n                }\n                for (int i = write_pos; i >= 0; --i) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; ++j) {\n                int write_pos = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (cells[i][j] != 0) {\n                        cells[write_pos++][j] = cells[i][j];\n                    }\n                }\n                for (int i = write_pos; i < N; ++i) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; ++i) {\n                int write_pos = 0;\n                for (int j = 0; j < N; ++j) {\n                    if (cells[i][j] != 0) {\n                        cells[i][write_pos++] = cells[i][j];\n                    }\n                }\n                for (int j = write_pos; j < N; ++j) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'R') {\n            for (int i = 0; i < N; ++i) {\n                int write_pos = N - 1;\n                for (int j = N - 1; j >= 0; --j) {\n                    if (cells[i][j] != 0) {\n                        cells[i][write_pos--] = cells[i][j];\n                    }\n                }\n                for (int j = write_pos; j >= 0; --j) {\n                    cells[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    vector<int> get_connected_components() {\n        vector<int> component_sizes;\n        bool visited[N][N] = {false};\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0 && !visited[i][j]) {\n                    int flavor = cells[i][j];\n                    int size = 0;\n                    queue<pair<int, int>> q;\n                    q.push({i, j});\n                    visited[i][j] = true;\n\n                    while (!q.empty()) {\n                        auto [x, y] = q.front();\n                        q.pop();\n                        size++;\n\n                        for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                            int nx = x + dx;\n                            int ny = y + dy;\n                            if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && cells[nx][ny] == flavor) {\n                                visited[nx][ny] = true;\n                                q.push({nx, ny});\n                            }\n                        }\n                    }\n                    component_sizes.push_back(size);\n                }\n            }\n        }\n        return component_sizes;\n    }\n\n    double evaluate() {\n        auto components = get_connected_components();\n        double sum_sq = 0;\n        for (int size : components) {\n            sum_sq += size * size;\n        }\n        int counts[4] = {0};\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    counts[cells[i][j]]++;\n                }\n            }\n        }\n        double denom = 0;\n        for (int i = 1; i <= 3; ++i) {\n            denom += counts[i] * counts[i];\n        }\n        if (denom == 0) return 0;\n        return sum_sq / denom;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<int> flavors(TOTAL_CANDIES);\n    for (int i = 0; i < TOTAL_CANDIES; ++i) {\n        cin >> flavors[i];\n    }\n\n    Grid grid;\n    for (int t = 0; t < TOTAL_CANDIES; ++t) {\n        int pos;\n        cin >> pos;\n        grid.place_candy(pos, flavors[t]);\n\n        if (t == TOTAL_CANDIES - 1) {\n            break;\n        }\n\n        double best_score = -1;\n        char best_dir = 'F';\n        for (char dir : DIRECTIONS) {\n            Grid temp_grid = grid;\n            temp_grid.tilt(dir);\n            double score = temp_grid.evaluate();\n            if (score > best_score) {\n                best_score = score;\n                best_dir = dir;\n            }\n        }\n        grid.tilt(best_dir);\n        cout << best_dir << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <random>\n#include <chrono>\n#include <map>\n#include <set>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Graph {\n    int N;\n    vector<vector<bool>> adj;\n    vector<int> degree;\n    int edge_count;\n    vector<int> degree_seq;\n\n    Graph(int n) : N(n), adj(n, vector<bool>(n, false)), degree(n, 0), edge_count(0) {}\n\n    void add_edge(int u, int v) {\n        if (!adj[u][v]) {\n            adj[u][v] = adj[v][u] = true;\n            degree[u]++;\n            degree[v]++;\n            edge_count++;\n        }\n    }\n\n    void compute_degree_seq() {\n        degree_seq = degree;\n        sort(degree_seq.begin(), degree_seq.end(), greater<int>());\n    }\n\n    string to_string() const {\n        string s;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                s += adj[i][j] ? '1' : '0';\n            }\n        }\n        return s;\n    }\n};\n\nvector<Graph> generate_graphs(int M, int N) {\n    vector<Graph> graphs;\n    for (int k = 0; k < M; ++k) {\n        Graph g(N);\n        // Simple strategy: G_k has k edges, but distributed to make degree sequence unique\n        int edges = k;\n        for (int i = 0; i < N && edges > 0; ++i) {\n            for (int j = i + 1; j < N && edges > 0; ++j) {\n                g.add_edge(i, j);\n                edges--;\n            }\n        }\n        g.compute_degree_seq();\n        graphs.push_back(g);\n    }\n    return graphs;\n}\n\nvector<int> compute_degree_sequence(const string& s, int N) {\n    vector<int> degree(N, 0);\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (s[idx++] == '1') {\n                degree[i]++;\n                degree[j]++;\n            }\n        }\n    }\n    sort(degree.begin(), degree.end(), greater<int>());\n    return degree;\n}\n\nint count_edges(const string& s) {\n    return count(s.begin(), s.end(), '1');\n}\n\ndouble compute_distance(const vector<int>& a, const vector<int>& b) {\n    double dist = 0.0;\n    for (int i = 0; i < a.size(); ++i) {\n        dist += abs(a[i] - b[i]);\n    }\n    return dist;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    cin >> M >> eps;\n\n    // Choose N based on M and eps\n    int N = min(100, max(4, M + 10)); // Heuristic: N should be larger for larger M or eps\n    if (eps > 0.2) {\n        N = min(100, N + 20); // Increase N for higher error rates\n    }\n\n    vector<Graph> graphs = generate_graphs(M, N);\n\n    // Output the graphs\n    cout << N << '\\n';\n    for (const auto& g : graphs) {\n        cout << g.to_string() << '\\n';\n    }\n    cout.flush();\n\n    // Precompute invariants for all G_k\n    vector<int> edge_counts;\n    vector<vector<int>> degree_seqs;\n    for (const auto& g : graphs) {\n        edge_counts.push_back(g.edge_count);\n        degree_seqs.push_back(g.degree_seq);\n    }\n\n    // Process queries\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // Compute invariants for H\n        int edges_H = count_edges(H);\n        vector<int> degree_seq_H = compute_degree_sequence(H, N);\n\n        // Find the closest G_k\n        double min_dist = 1e18;\n        int best_k = 0;\n        for (int k = 0; k < M; ++k) {\n            double dist = abs(edges_H - edge_counts[k]) + compute_distance(degree_seq_H, degree_seqs[k]);\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_k = k;\n            }\n        }\n\n        cout << best_k << '\\n';\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int INF = 1e9;\nconst double INIT_TEMP = 1e4;\nconst double FINAL_TEMP = 1e-4;\nconst double COOLING_RATE = 0.999;\nconst int MAX_ITER = 100000;\n\nstruct Edge {\n    int u, v, w, idx;\n};\n\nstruct Point {\n    int x, y;\n};\n\nint N, M, D, K;\nvector<Edge> edges;\nvector<Point> points;\nvector<vector<int>> adj;\nvector<vector<int>> dist;\nvector<int> schedule;\n\nvoid read_input() {\n    cin >> N >> M >> D >> K;\n    edges.resize(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        edges[i].idx = i;\n    }\n    points.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> points[i].x >> points[i].y;\n    }\n}\n\nvoid compute_apsp() {\n    dist.assign(N, vector<int>(N, INF));\n    for (int i = 0; i < N; ++i) {\n        dist[i][i] = 0;\n    }\n    for (const auto& e : edges) {\n        dist[e.u][e.v] = min(dist[e.u][e.v], e.w);\n        dist[e.v][e.u] = min(dist[e.v][e.u], e.w);\n    }\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 (dist[i][k] < INF && dist[k][j] < INF) {\n                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n                }\n            }\n        }\n    }\n}\n\nvector<vector<int>> compute_daily_dist(int day) {\n    vector<vector<int>> daily_dist = dist;\n    for (int i = 0; i < M; ++i) {\n        if (schedule[i] == day) {\n            const auto& e = edges[i];\n            daily_dist[e.u][e.v] = INF;\n            daily_dist[e.v][e.u] = INF;\n        }\n    }\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 (daily_dist[i][k] < INF && daily_dist[k][j] < INF) {\n                    daily_dist[i][j] = min(daily_dist[i][j], daily_dist[i][k] + daily_dist[k][j]);\n                }\n            }\n        }\n    }\n    return daily_dist;\n}\n\ndouble compute_frustration() {\n    double total_frustration = 0.0;\n    for (int day = 1; day <= D; ++day) {\n        auto daily_dist = compute_daily_dist(day);\n        double sum_diff = 0.0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                int original = dist[i][j];\n                int current = daily_dist[i][j];\n                if (current >= INF) current = INF;\n                sum_diff += (current - original);\n            }\n        }\n        double f_k = sum_diff / (N * (N - 1) / 2);\n        total_frustration += f_k;\n    }\n    return total_frustration / D;\n}\n\nvoid initial_schedule() {\n    schedule.assign(M, 0);\n    vector<int> day_counts(D, 0);\n    for (int i = 0; i < M; ++i) {\n        int day = rand() % D + 1;\n        while (day_counts[day - 1] >= K) {\n            day = rand() % D + 1;\n        }\n        schedule[i] = day;\n        day_counts[day - 1]++;\n    }\n}\n\nvoid simulated_annealing() {\n    initial_schedule();\n    double current_frustration = compute_frustration();\n    double temp = INIT_TEMP;\n    int iter = 0;\n    while (temp > FINAL_TEMP && iter < MAX_ITER) {\n        int edge_idx = rand() % M;\n        int old_day = schedule[edge_idx];\n        int new_day = rand() % D + 1;\n        if (count(schedule.begin(), schedule.end(), new_day) >= K) {\n            continue;\n        }\n        schedule[edge_idx] = new_day;\n        double new_frustration = compute_frustration();\n        double delta = new_frustration - current_frustration;\n        if (delta < 0 || exp(-delta / temp) > (double)rand() / RAND_MAX) {\n            current_frustration = new_frustration;\n        } else {\n            schedule[edge_idx] = old_day;\n        }\n        temp *= COOLING_RATE;\n        iter++;\n    }\n}\n\nint main() {\n    srand(time(0));\n    read_input();\n    compute_apsp();\n    simulated_annealing();\n    for (int i = 0; i < M; ++i) {\n        cout << schedule[i] << (i == M - 1 ? \"\\n\" : \" \");\n    }\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <unordered_set>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n    Point(int x = 0, int y = 0, int z = 0) : x(x), y(y), z(z) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y && z == other.z;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        if (y != other.y) return y < other.y;\n        return z < other.z;\n    }\n};\n\nstruct Block {\n    vector<Point> cubes;\n    int id;\n    Block(int id = 0) : id(id) {}\n    void add_cube(const Point& p) {\n        cubes.push_back(p);\n    }\n    bool is_connected() const {\n        if (cubes.empty()) return true;\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        queue<Point> q;\n        q.push(cubes[0]);\n        visited[cubes[0].x][cubes[0].y][cubes[0].z] = true;\n        int count = 1;\n        while (!q.empty()) {\n            Point p = q.front();\n            q.pop();\n            for (const auto& cube : cubes) {\n                if (!visited[cube.x][cube.y][cube.z]) {\n                    int dx = abs(p.x - cube.x);\n                    int dy = abs(p.y - cube.y);\n                    int dz = abs(p.z - cube.z);\n                    if ((dx == 1 && dy == 0 && dz == 0) ||\n                        (dx == 0 && dy == 1 && dz == 0) ||\n                        (dx == 0 && dy == 0 && dz == 1)) {\n                        visited[cube.x][cube.y][cube.z] = true;\n                        q.push(cube);\n                        count++;\n                    }\n                }\n            }\n        }\n        return count == cubes.size();\n    }\n};\n\nint D;\nvector<vector<string>> f(2, vector<string>(D));\nvector<vector<string>> r(2, vector<string>(D));\nvector<vector<vector<int>>> b(2, vector<vector<int>>(D, vector<int>(D, 0)));\nvector<Block> blocks;\nint block_id = 1;\n\nbool can_place_block(const Block& block, int obj_idx, const vector<vector<vector<int>>>& grid) {\n    for (const auto& cube : block.cubes) {\n        if (cube.x < 0 || cube.x >= D || cube.y < 0 || cube.y >= D || cube.z < 0 || cube.z >= D) {\n            return false;\n        }\n        if (grid[cube.x][cube.y][cube.z] != 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid place_block(const Block& block, int obj_idx, int id) {\n    for (const auto& cube : block.cubes) {\n        b[obj_idx][cube.x][cube.y][cube.z] = id;\n    }\n}\n\nvoid remove_block(const Block& block, int obj_idx) {\n    for (const auto& cube : block.cubes) {\n        b[obj_idx][cube.x][cube.y][cube.z] = 0;\n    }\n}\n\nbool satisfies_silhouette(int obj_idx) {\n    for (int z = 0; z < D; ++z) {\n        for (int x = 0; x < D; ++x) {\n            bool found = false;\n            for (int y = 0; y < D; ++y) {\n                if (b[obj_idx][x][y][z] != 0) {\n                    found = true;\n                    break;\n                }\n            }\n            if (f[obj_idx][z][x] == '1' && !found) {\n                return false;\n            }\n        }\n    }\n    for (int z = 0; z < D; ++z) {\n        for (int y = 0; y < D; ++y) {\n            bool found = false;\n            for (int x = 0; x < D; ++x) {\n                if (b[obj_idx][x][y][z] != 0) {\n                    found = true;\n                    break;\n                }\n            }\n            if (r[obj_idx][z][y] == '1' && !found) {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nvoid generate_initial_blocks() {\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[obj_idx][z][x] == '1' && r[obj_idx][z][y] == '1') {\n                        bool found = false;\n                        for (const auto& block : blocks) {\n                            for (const auto& cube : block.cubes) {\n                                if (cube.x == x && cube.y == y && cube.z == z) {\n                                    found = true;\n                                    break;\n                                }\n                            }\n                            if (found) break;\n                        }\n                        if (!found) {\n                            Block block(block_id++);\n                            block.add_cube(Point(x, y, z));\n                            blocks.push_back(block);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid merge_blocks() {\n    bool merged;\n    do {\n        merged = false;\n        for (size_t i = 0; i < blocks.size(); ++i) {\n            for (size_t j = i + 1; j < blocks.size(); ++j) {\n                Block new_block(block_id);\n                for (const auto& cube : blocks[i].cubes) {\n                    new_block.add_cube(cube);\n                }\n                for (const auto& cube : blocks[j].cubes) {\n                    new_block.add_cube(cube);\n                }\n                if (new_block.is_connected()) {\n                    vector<Block> new_blocks;\n                    for (size_t k = 0; k < blocks.size(); ++k) {\n                        if (k != i && k != j) {\n                            new_blocks.push_back(blocks[k]);\n                        }\n                    }\n                    new_blocks.push_back(new_block);\n                    blocks = new_blocks;\n                    block_id++;\n                    merged = true;\n                    break;\n                }\n            }\n            if (merged) break;\n        }\n    } while (merged);\n}\n\nvoid assign_blocks_to_objects() {\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        vector<vector<vector<int>>> grid(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        for (const auto& block : blocks) {\n            bool used = false;\n            for (const auto& cube : block.cubes) {\n                if (f[obj_idx][cube.z][cube.x] == '1' && r[obj_idx][cube.z][cube.y] == '1') {\n                    used = true;\n                    break;\n                }\n            }\n            if (used) {\n                place_block(block, obj_idx, block.id);\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> D;\n    f.resize(2, vector<string>(D));\n    r.resize(2, vector<string>(D));\n    b.resize(2, vector<vector<int>>(D, vector<int>(D, 0)));\n\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> f[i][k];\n        }\n        for (int k = 0; k < D; ++k) {\n            cin >> r[i][k];\n        }\n    }\n\n    generate_initial_blocks();\n    merge_blocks();\n    assign_blocks_to_objects();\n\n    set<int> used_blocks;\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (b[obj_idx][x][y][z] != 0) {\n                        used_blocks.insert(b[obj_idx][x][y][z]);\n                    }\n                }\n            }\n        }\n    }\n\n    vector<int> block_ids;\n    for (const auto& block : blocks) {\n        block_ids.push_back(block.id);\n    }\n    sort(block_ids.begin(), block_ids.end());\n    block_ids.erase(unique(block_ids.begin(), block_ids.end()), block_ids.end());\n\n    cout << block_ids.size() << endl;\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    cout << b[obj_idx][x][y][z] << \" \";\n                }\n            }\n        }\n        cout << endl;\n    }\n\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v, w, idx;\n    double dist;\n};\n\nstruct Resident {\n    int x, y;\n};\n\nstruct Station {\n    int x, y;\n    int P;\n    vector<int> residents;\n};\n\ndouble euclidean(int x1, int y1, int x2, int y2) {\n    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<Station> stations(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> stations[i].x >> stations[i].y;\n        stations[i].P = 0;\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        edges[i].idx = i;\n        edges[i].dist = euclidean(stations[edges[i].u].x, stations[edges[i].u].y,\n                                  stations[edges[i].v].x, stations[edges[i].v].y);\n    }\n\n    vector<Resident> residents(K);\n    for (int i = 0; i < K; ++i) {\n        cin >> residents[i].x >> residents[i].y;\n    }\n\n    // Step 1: Assign residents to nearest station\n    for (int i = 0; i < K; ++i) {\n        double min_dist = 1e9;\n        int best_station = -1;\n        for (int j = 0; j < N; ++j) {\n            double dist = euclidean(residents[i].x, residents[i].y, stations[j].x, stations[j].y);\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_station = j;\n            }\n        }\n        stations[best_station].residents.push_back(i);\n    }\n\n    // Step 2: Compute MST using Kruskal's algorithm\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.w < b.w;\n    });\n\n    dsu uf(N);\n    vector<bool> edge_used(M, false);\n    vector<vector<pair<int, int>>> mst(N); // {neighbor, edge_idx}\n\n    for (const Edge& e : edges) {\n        if (!uf.same(e.u, e.v)) {\n            uf.merge(e.u, e.v);\n            edge_used[e.idx] = true;\n            mst[e.u].emplace_back(e.v, e.idx);\n            mst[e.v].emplace_back(e.u, e.idx);\n        }\n    }\n\n    // Step 3: Set initial P_i to cover all residents\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].residents.empty()) {\n            stations[i].P = 0;\n            continue;\n        }\n        double max_dist = 0;\n        for (int r : stations[i].residents) {\n            double dist = euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y);\n            if (dist > max_dist) {\n                max_dist = dist;\n            }\n        }\n        stations[i].P = min(5000, (int)ceil(max_dist));\n    }\n\n    // Step 4: Optimize P_i and edge selection\n    // Try to reduce P_i for stations where residents are covered by other stations\n    vector<bool> covered(K, false);\n    for (int i = 0; i < N; ++i) {\n        for (int r : stations[i].residents) {\n            if (euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y) <= stations[i].P) {\n                covered[r] = true;\n            }\n        }\n    }\n\n    // If all residents are covered, try to reduce P_i\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].P == 0) continue;\n        int original_P = stations[i].P;\n        for (int p = original_P - 1; p >= 0; --p) {\n            bool can_reduce = true;\n            for (int r : stations[i].residents) {\n                if (!covered[r]) continue;\n                if (euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y) > p) {\n                    bool covered_by_other = false;\n                    for (int j = 0; j < N; ++j) {\n                        if (j == i) continue;\n                        if (euclidean(residents[r].x, residents[r].y, stations[j].x, stations[j].y) <= stations[j].P) {\n                            covered_by_other = true;\n                            break;\n                        }\n                    }\n                    if (!covered_by_other) {\n                        can_reduce = false;\n                        break;\n                    }\n                }\n            }\n            if (can_reduce) {\n                stations[i].P = p;\n                for (int r : stations[i].residents) {\n                    if (euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y) <= p) {\n                        covered[r] = true;\n                    } else {\n                        covered[r] = false;\n                        for (int j = 0; j < N; ++j) {\n                            if (j == i) continue;\n                            if (euclidean(residents[r].x, residents[r].y, stations[j].x, stations[j].y) <= stations[j].P) {\n                                covered[r] = true;\n                                break;\n                            }\n                        }\n                    }\n                }\n            } else {\n                break;\n            }\n        }\n    }\n\n    // Step 5: Output the solution\n    for (int i = 0; i < N; ++i) {\n        cout << stations[i].P << (i == N - 1 ? \"\\n\" : \" \");\n    }\n    for (int i = 0; i < M; ++i) {\n        cout << edge_used[i] << (i == M - 1 ? \"\\n\" : \" \");\n    }\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_map>\n#include <cmath>\n#include <climits>\n#include <set>\n\nusing namespace std;\n\nconst int N = 30;\nconst int TOTAL_BALLS = N * (N + 1) / 2;\nconst int MAX_OPERATIONS = 10000;\n\nstruct Position {\n    int x, y;\n    Position(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Position& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Position& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nvector<Position> directions = {\n    {-1, -1}, {-1, 0}, {0, -1}, {0, 1}, {1, 0}, {1, 1}\n};\n\nvector<vector<int>> pyramid(N, vector<int>(N, -1));\nvector<pair<Position, Position>> operations;\n\nbool is_valid(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y <= x;\n}\n\nvector<Position> get_adjacent_positions(int x, int y) {\n    vector<Position> adj;\n    for (auto& dir : directions) {\n        int nx = x + dir.x;\n        int ny = y + dir.y;\n        if (is_valid(nx, ny)) {\n            adj.emplace_back(nx, ny);\n        }\n    }\n    return adj;\n}\n\nvoid swap_balls(Position a, Position b) {\n    if (!is_valid(a.x, a.y) || !is_valid(b.x, b.y)) return;\n    swap(pyramid[a.x][a.y], pyramid[b.x][b.y]);\n    operations.emplace_back(a, b);\n}\n\nint count_violations() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int current = pyramid[x][y];\n            int child1 = pyramid[x + 1][y];\n            int child2 = pyramid[x + 1][y + 1];\n            if (current > child1) violations++;\n            if (current > child2) violations++;\n        }\n    }\n    return violations;\n}\n\nPosition find_ball(int num) {\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] == num) {\n                return Position(x, y);\n            }\n        }\n    }\n    return Position(-1, -1);\n}\n\nvector<Position> find_path(Position start, Position target) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    vector<vector<Position>> parent(N, vector<Position>(N, Position(-1, -1)));\n    queue<Position> q;\n    q.push(start);\n    visited[start.x][start.y] = true;\n\n    while (!q.empty()) {\n        Position current = q.front();\n        q.pop();\n        if (current.x == target.x && current.y == target.y) {\n            vector<Position> path;\n            while (!(current.x == start.x && current.y == start.y)) {\n                path.push_back(current);\n                current = parent[current.x][current.y];\n            }\n            path.push_back(start);\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        for (auto& dir : directions) {\n            int nx = current.x + dir.x;\n            int ny = current.y + dir.y;\n            if (is_valid(nx, ny) && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                parent[nx][ny] = current;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return {};\n}\n\nvoid move_ball(Position start, Position target) {\n    vector<Position> path = find_path(start, target);\n    if (path.empty()) return;\n    for (size_t i = 0; i < path.size() - 1; ++i) {\n        swap_balls(path[i], path[i + 1]);\n    }\n}\n\nvoid solve() {\n    // Read input\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            cin >> pyramid[x][y];\n        }\n    }\n\n    // Target: smallest numbers at the top\n    // We'll try to place the smallest numbers in the top positions\n    // This is a heuristic approach\n\n    // For each position, find the smallest number that should be there\n    // The target is to have the smallest numbers in the top positions\n    // So, the target for position (x, y) is the (x*(x+1)/2 + y)-th smallest number\n\n    vector<int> sorted_balls(TOTAL_BALLS);\n    for (int i = 0; i < TOTAL_BALLS; ++i) {\n        sorted_balls[i] = i;\n    }\n\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int target_num = sorted_balls[x * (x + 1) / 2 + y];\n            Position current_pos = find_ball(target_num);\n            if (current_pos.x != x || current_pos.y != y) {\n                move_ball(current_pos, Position(x, y));\n                if (operations.size() >= MAX_OPERATIONS) {\n                    goto output;\n                }\n            }\n        }\n    }\n\n    // After initial placement, check for violations and fix them\n    int violations = count_violations();\n    while (violations > 0 && operations.size() < MAX_OPERATIONS) {\n        for (int x = 0; x < N - 1; ++x) {\n            for (int y = 0; y <= x; ++y) {\n                int current = pyramid[x][y];\n                int child1 = pyramid[x + 1][y];\n                int child2 = pyramid[x + 1][y + 1];\n                if (current > child1 || current > child2) {\n                    // Find the smallest adjacent ball to swap with\n                    vector<Position> adj = get_adjacent_positions(x, y);\n                    int min_val = current;\n                    Position best_swap = Position(-1, -1);\n                    for (auto& pos : adj) {\n                        if (pyramid[pos.x][pos.y] < min_val) {\n                            min_val = pyramid[pos.x][pos.y];\n                            best_swap = pos;\n                        }\n                    }\n                    if (best_swap.x != -1) {\n                        swap_balls(Position(x, y), best_swap);\n                        violations = count_violations();\n                        if (operations.size() >= MAX_OPERATIONS) {\n                            goto output;\n                        }\n                    }\n                }\n            }\n        }\n        violations = count_violations();\n    }\n\noutput:\n    cout << operations.size() << endl;\n    for (auto& op : operations) {\n        cout << op.first.x << \" \" << op.first.y << \" \"\n             << op.second.x << \" \" << op.second.y << endl;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <set>\n#include <climits>\n#include <cstring>\n\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = (D - 1) / 2;\n\nstruct Cell {\n    int i, j;\n    bool operator<(const Cell& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nint grid[D][D];\nbool is_obstacle[D][D];\nbool is_container[D][D];\nint container_num[D][D];\nvector<Cell> containers;\n\nint di[] = {-1, 1, 0, 0};\nint dj[] = {0, 0, -1, 1};\n\nbool is_valid(int i, int j) {\n    return i >= 0 && i < D && j >= 0 && j < D;\n}\n\nvector<Cell> bfs_reachable() {\n    vector<Cell> reachable;\n    bool visited[D][D];\n    memset(visited, false, sizeof(visited));\n    queue<Cell> q;\n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n\n    while (!q.empty()) {\n        Cell current = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int ni = current.i + di[k];\n            int nj = current.j + dj[k];\n            if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj] && !is_container[ni][nj]) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n            }\n        }\n    }\n\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            if (visited[i][j] && !is_obstacle[i][j] && !is_container[i][j] && !(i == ENTRANCE_I && j == ENTRANCE_J)) {\n                reachable.push_back({i, j});\n            }\n        }\n    }\n    return reachable;\n}\n\nvector<Cell> bfs_removable() {\n    vector<Cell> removable;\n    bool visited[D][D];\n    memset(visited, false, sizeof(visited));\n    queue<Cell> q;\n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n\n    while (!q.empty()) {\n        Cell current = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int ni = current.i + di[k];\n            int nj = current.j + dj[k];\n            if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj]) {\n                if (is_container[ni][nj]) {\n                    removable.push_back({ni, nj});\n                } else {\n                    visited[ni][nj] = true;\n                    q.push({ni, nj});\n                }\n            }\n        }\n    }\n    return removable;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> D >> N;\n    memset(is_obstacle, false, sizeof(is_obstacle));\n    memset(is_container, false, sizeof(is_container));\n    memset(container_num, -1, sizeof(container_num));\n\n    for (int i = 0; i < N; ++i) {\n        int ri, rj;\n        cin >> ri >> rj;\n        is_obstacle[ri][rj] = true;\n    }\n\n    int total_containers = D * D - 1 - N;\n    for (int d = 0; d < total_containers; ++d) {\n        int t;\n        cin >> t;\n        vector<Cell> reachable = bfs_reachable();\n        if (reachable.empty()) {\n            cerr << \"No reachable cells left!\" << endl;\n            return 1;\n        }\n\n        // Place the container in the cell with the highest BFS distance from entrance\n        // To find the farthest cell, we can perform BFS from entrance and pick the last visited\n        bool visited[D][D];\n        memset(visited, false, sizeof(visited));\n        queue<Cell> q;\n        q.push({ENTRANCE_I, ENTRANCE_J});\n        visited[ENTRANCE_I][ENTRANCE_J] = true;\n        Cell farthest = {ENTRANCE_I, ENTRANCE_J};\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            farthest = current;\n            for (int k = 0; k < 4; ++k) {\n                int ni = current.i + di[k];\n                int nj = current.j + dj[k];\n                if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj] && !is_container[ni][nj]) {\n                    visited[ni][nj] = true;\n                    q.push({ni, nj});\n                }\n            }\n        }\n\n        // Place the container at the farthest cell\n        is_container[farthest.i][farthest.j] = true;\n        container_num[farthest.i][farthest.j] = t;\n        containers.push_back({farthest.i, farthest.j});\n        cout << farthest.i << \" \" << farthest.j << endl;\n        cout.flush();\n    }\n\n    // Determine the removal order\n    vector<Cell> removal_order;\n    while (removal_order.size() < total_containers) {\n        vector<Cell> removable = bfs_removable();\n        if (removable.empty()) {\n            cerr << \"No removable containers left!\" << endl;\n            return 1;\n        }\n\n        // Find the container with the smallest number among removable\n        int min_num = INT_MAX;\n        Cell to_remove;\n        for (const Cell& cell : removable) {\n            if (container_num[cell.i][cell.j] < min_num) {\n                min_num = container_num[cell.i][cell.j];\n                to_remove = cell;\n            }\n        }\n\n        removal_order.push_back(to_remove);\n        is_container[to_remove.i][to_remove.j] = false;\n    }\n\n    for (const Cell& cell : removal_order) {\n        cout << cell.i << \" \" << cell.j << endl;\n    }\n    cout.flush();\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int n = 50;\nconst int m = 100;\nconst int dx[] = {1, 0, -1, 0};\nconst int dy[] = {0, 1, 0, -1};\n\nstruct Cell {\n    int x, y;\n    Cell(int x = 0, int y = 0) : x(x), y(y) {}\n};\n\nvector<vector<int>> input_grid(n, vector<int>(n));\nvector<set<int>> adjacency(m + 1);\nvector<vector<Cell>> ward_cells(m + 1);\nvector<vector<bool>> is_boundary(n, vector<bool>(n, false));\n\nvoid read_input() {\n    cin >> n >> m;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> input_grid[i][j];\n            ward_cells[input_grid[i][j]].emplace_back(i, j);\n        }\n    }\n}\n\nvoid compute_adjacency() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            int c = input_grid[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = input_grid[ni][nj];\n                    if (nc != c) {\n                        adjacency[c].insert(nc);\n                        adjacency[nc].insert(c);\n                    }\n                } else {\n                    adjacency[c].insert(0);\n                    adjacency[0].insert(c);\n                }\n            }\n        }\n    }\n}\n\nvoid compute_boundary() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni < 0 || ni >= n || nj < 0 || nj >= n) {\n                    is_boundary[i][j] = true;\n                    break;\n                }\n            }\n        }\n    }\n}\n\nvector<vector<int>> create_initial_solution() {\n    vector<vector<int>> grid(n, vector<int>(n, 0));\n    vector<set<int>> required_adj(m + 1);\n    for (int c = 1; c <= m; ++c) {\n        required_adj[c] = adjacency[c];\n    }\n\n    // Place each ward as a single cell\n    vector<Cell> positions;\n    for (int c = 1; c <= m; ++c) {\n        if (!ward_cells[c].empty()) {\n            Cell pos = ward_cells[c][0];\n            grid[pos.x][pos.y] = c;\n            positions.emplace_back(pos.x, pos.y);\n        }\n    }\n\n    // Expand wards to satisfy adjacency\n    for (int c = 1; c <= m; ++c) {\n        if (ward_cells[c].empty()) continue;\n        queue<Cell> q;\n        vector<vector<bool>> visited(n, vector<bool>(n, false));\n        for (const auto& cell : ward_cells[c]) {\n            if (grid[cell.x][cell.y] == c) {\n                q.push(cell);\n                visited[cell.x][cell.y] = true;\n            }\n        }\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int ni = current.x + dx[d];\n                int nj = current.y + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj]) {\n                    int nc = grid[ni][nj];\n                    if (nc == 0) {\n                        if (required_adj[c].count(0) || !required_adj[c].empty()) {\n                            grid[ni][nj] = c;\n                            visited[ni][nj] = true;\n                            q.push(Cell(ni, nj));\n                        }\n                    } else if (nc != c) {\n                        if (required_adj[c].count(nc)) {\n                            required_adj[c].erase(nc);\n                            required_adj[nc].erase(c);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Ensure all adjacencies are satisfied\n    for (int c = 1; c <= m; ++c) {\n        if (!required_adj[c].empty()) {\n            for (int nc : required_adj[c]) {\n                if (nc == 0) continue;\n                // Find a cell of c and nc to connect\n                for (const auto& cell : ward_cells[c]) {\n                    if (grid[cell.x][cell.y] != c) continue;\n                    for (int d = 0; d < 4; ++d) {\n                        int ni = cell.x + dx[d];\n                        int nj = cell.y + dy[d];\n                        if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] == 0) {\n                            grid[ni][nj] = c;\n                            break;\n                        }\n                    }\n                    break;\n                }\n            }\n        }\n    }\n\n    return grid;\n}\n\nvoid optimize_solution(vector<vector<int>>& grid) {\n    // Simple optimization: try to replace color-0 cells with adjacent colors if possible\n    bool improved;\n    do {\n        improved = false;\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] != 0) continue;\n                set<int> adjacent_colors;\n                for (int d = 0; d < 4; ++d) {\n                    int ni = i + dx[d];\n                    int nj = j + dy[d];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                        adjacent_colors.insert(grid[ni][nj]);\n                    }\n                }\n                if (adjacent_colors.size() == 1) {\n                    int c = *adjacent_colors.begin();\n                    if (c != 0) {\n                        grid[i][j] = c;\n                        improved = true;\n                    }\n                }\n            }\n        }\n    } while (improved);\n}\n\nbool check_connectivity(const vector<vector<int>>& grid) {\n    for (int c = 1; c <= m; ++c) {\n        vector<vector<bool>> visited(n, vector<bool>(n, false));\n        queue<Cell> q;\n        bool found = false;\n        for (int i = 0; i < n && !found; ++i) {\n            for (int j = 0; j < n && !found; ++j) {\n                if (grid[i][j] == c) {\n                    q.push(Cell(i, j));\n                    visited[i][j] = true;\n                    found = true;\n                }\n            }\n        }\n        if (!found) continue;\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int ni = current.x + dx[d];\n                int nj = current.y + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj] && grid[ni][nj] == c) {\n                    visited[ni][nj] = true;\n                    q.push(Cell(ni, nj));\n                }\n            }\n        }\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] == c && !visited[i][j]) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool check_adjacency(const vector<vector<int>>& grid) {\n    vector<set<int>> current_adj(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            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = grid[ni][nj];\n                    if (nc != c) {\n                        current_adj[c].insert(nc);\n                        current_adj[nc].insert(c);\n                    }\n                } else {\n                    current_adj[c].insert(0);\n                    current_adj[0].insert(c);\n                }\n            }\n        }\n    }\n    for (int c = 0; c <= m; ++c) {\n        if (current_adj[c] != adjacency[c]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    read_input();\n    compute_adjacency();\n    compute_boundary();\n\n    vector<vector<int>> grid = create_initial_solution();\n    optimize_solution(grid);\n\n    // Verify the solution\n    if (!check_connectivity(grid) || !check_adjacency(grid)) {\n        // Fallback: output the original grid (though it may not be optimal)\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << input_grid[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n    } else {\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << grid[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <queue>\n#include <set>\n#include <map>\n#include <chrono>\n#include <cassert>\n\nusing namespace std;\nusing namespace std::chrono;\n\nstruct Item {\n    int id;\n    double weight;\n    bool operator<(const Item& other) const {\n        return weight > other.weight; // For max-heap\n    }\n};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nvector<int> solve(int N, int D, int Q) {\n    vector<double> weights(N, 1.0); // Initial guess\n    vector<vector<double>> constraints;\n    vector<int> comparison_results;\n\n    auto query = [&](const vector<int>& L, const vector<int>& R) {\n        cout << L.size() << \" \" << R.size();\n        for (int l : L) cout << \" \" << l;\n        for (int r : R) cout << \" \" << r;\n        cout << endl;\n        cout.flush();\n\n        string result;\n        cin >> result;\n        if (result == \"<\") return -1;\n        else if (result == \">\") return 1;\n        else return 0;\n    };\n\n    // Initial pairwise comparisons to establish order\n    for (int i = 0; i < N && Q > 0; ++i) {\n        for (int j = i + 1; j < N && Q > 0; ++j) {\n            vector<int> L = {i}, R = {j};\n            int res = query(L, R);\n            comparison_results.push_back(res);\n            Q--;\n            if (res == -1) {\n                weights[i] = 0.9 * weights[i];\n                weights[j] = 1.1 * weights[j];\n            } else if (res == 1) {\n                weights[i] = 1.1 * weights[i];\n                weights[j] = 0.9 * weights[j];\n            }\n        }\n    }\n\n    // Refine weights using more queries\n    while (Q > 0) {\n        vector<int> L, R;\n        uniform_int_distribution<int> dist(0, N - 1);\n        int size = min(5, N / 2);\n        set<int> used;\n        while (L.size() < size) {\n            int item = dist(rng);\n            if (used.count(item)) continue;\n            used.insert(item);\n            L.push_back(item);\n        }\n        used.clear();\n        while (R.size() < size) {\n            int item = dist(rng);\n            if (used.count(item) || find(L.begin(), L.end(), item) != L.end()) continue;\n            used.insert(item);\n            R.push_back(item);\n        }\n        if (L.empty() || R.empty()) continue;\n        int res = query(L, R);\n        Q--;\n        double sum_L = accumulate(L.begin(), L.end(), 0.0, [&](double s, int i) { return s + weights[i]; });\n        double sum_R = accumulate(R.begin(), R.end(), 0.0, [&](double s, int i) { return s + weights[i]; });\n        if (res == -1) {\n            for (int l : L) weights[l] *= 0.99;\n            for (int r : R) weights[r] *= 1.01;\n        } else if (res == 1) {\n            for (int l : L) weights[l] *= 1.01;\n            for (int r : R) weights[r] *= 0.99;\n        }\n    }\n\n    // Partition into D sets\n    vector<int> assignment(N, 0);\n    vector<double> set_sums(D, 0.0);\n    vector<Item> items;\n    for (int i = 0; i < N; ++i) {\n        items.push_back({i, weights[i]});\n    }\n    sort(items.begin(), items.end(), [](const Item& a, const Item& b) {\n        return a.weight > b.weight;\n    });\n\n    for (const auto& item : items) {\n        int best_set = 0;\n        double min_sum = set_sums[0];\n        for (int d = 1; d < D; ++d) {\n            if (set_sums[d] < min_sum) {\n                min_sum = set_sums[d];\n                best_set = d;\n            }\n        }\n        assignment[item.id] = best_set;\n        set_sums[best_set] += item.weight;\n    }\n\n    return assignment;\n}\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n\n    auto assignment = solve(N, D, Q);\n\n    for (int i = 0; i < N; ++i) {\n        cout << assignment[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n    cout.flush();\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Box {\n    int value;\n    int stack;\n    int pos; // position from bottom (0-based)\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n = 200, m = 10;\n    cin >> n >> m;\n\n    vector<vector<int>> stacks(m);\n    unordered_map<int, Box> box_info;\n    vector<int> next_box_pos(m, 0); // next position to check in each stack (from top)\n\n    for (int i = 0; i < m; ++i) {\n        stacks[i].resize(n / m);\n        for (int j = 0; j < n / m; ++j) {\n            cin >> stacks[i][j];\n            box_info[stacks[i][j]] = {stacks[i][j], i, j};\n        }\n    }\n\n    vector<pair<int, int>> operations;\n    int next_box = 1;\n    int total_energy = 0;\n    int max_operations = 5000;\n\n    auto get_top_box = [&](int stack_idx) {\n        if (stacks[stack_idx].empty()) return -1;\n        return stacks[stack_idx].back();\n    };\n\n    auto move_boxes = [&](int v, int dest_stack) {\n        int src_stack = box_info[v].stack;\n        int pos = box_info[v].pos;\n        int num_boxes = stacks[src_stack].size() - pos;\n        if (num_boxes <= 0) return false; // should not happen\n\n        // Remove boxes from src_stack\n        vector<int> moved_boxes;\n        for (int i = pos; i < stacks[src_stack].size(); ++i) {\n            moved_boxes.push_back(stacks[src_stack][i]);\n        }\n        stacks[src_stack].resize(pos);\n\n        // Add to dest_stack\n        for (int box : moved_boxes) {\n            stacks[dest_stack].push_back(box);\n            box_info[box].stack = dest_stack;\n            box_info[box].pos = stacks[dest_stack].size() - 1;\n        }\n\n        operations.emplace_back(v, dest_stack);\n        total_energy += num_boxes + 1;\n        return true;\n    };\n\n    auto carry_out = [&](int v) {\n        int stack = box_info[v].stack;\n        stacks[stack].pop_back();\n        operations.emplace_back(v, 0);\n    };\n\n    auto find_dest_stack = [&](int v) {\n        int src_stack = box_info[v].stack;\n        vector<int> candidates;\n        for (int i = 0; i < m; ++i) {\n            if (i == src_stack) continue;\n            if (stacks[i].empty()) {\n                candidates.push_back(i);\n                continue;\n            }\n            int top_box = get_top_box(i);\n            if (top_box > v) {\n                candidates.push_back(i);\n            }\n        }\n\n        if (candidates.empty()) {\n            for (int i = 0; i < m; ++i) {\n                if (i != src_stack) {\n                    candidates.push_back(i);\n                }\n            }\n        }\n\n        // Choose the stack with the smallest size\n        int best_stack = candidates[0];\n        for (int stack : candidates) {\n            if (stacks[stack].size() < stacks[best_stack].size()) {\n                best_stack = stack;\n            }\n        }\n        return best_stack;\n    };\n\n    while (next_box <= n && operations.size() < max_operations) {\n        int stack = box_info[next_box].stack;\n        int pos = box_info[next_box].pos;\n        if (pos == stacks[stack].size() - 1) {\n            carry_out(next_box);\n            next_box++;\n        } else {\n            int dest_stack = find_dest_stack(next_box);\n            move_boxes(next_box, dest_stack);\n        }\n    }\n\n    // Output operations\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <climits>\n#include <unordered_set>\n#include <tuple>\n\nusing namespace std;\n\nconst int MAX_N = 40;\nconst int MAX_MOVES = 100000;\nconst vector<pair<int, int>> DIJ = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\nconst string DIR = \"RDLU\";\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<int>> dist;\nvector<vector<bool>> visited;\nstring route;\n\nvoid bfs() {\n    dist.assign(N, vector<int>(N, -1));\n    queue<pair<int, int>> q;\n    q.push({0, 0});\n    dist[0][0] = 0;\n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        for (auto [di, dj] : DIJ) {\n            int ni = i + di;\n            int nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (di == 0) {\n                if (dj == 1 && v[i][min(j, nj)] == '1') continue;\n                if (dj == -1 && v[i][min(j, nj)] == '1') continue;\n            } else {\n                if (di == 1 && h[min(i, ni)][j] == '1') continue;\n                if (di == -1 && h[min(i, ni)][j] == '1') continue;\n            }\n            if (dist[ni][nj] == -1) {\n                dist[ni][nj] = dist[i][j] + 1;\n                q.push({ni, nj});\n            }\n        }\n    }\n}\n\nvoid dfs(int i, int j) {\n    visited[i][j] = true;\n    vector<pair<double, pair<int, int>>> neighbors;\n    for (int dir = 0; dir < 4; ++dir) {\n        auto [di, dj] = DIJ[dir];\n        int ni = i + di;\n        int nj = j + dj;\n        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n        if (visited[ni][nj]) continue;\n        if (di == 0) {\n            if (dj == 1 && v[i][min(j, nj)] == '1') continue;\n            if (dj == -1 && v[i][min(j, nj)] == '1') continue;\n        } else {\n            if (di == 1 && h[min(i, ni)][j] == '1') continue;\n            if (di == -1 && h[min(i, ni)][j] == '1') continue;\n        }\n        double priority = (double)d[ni][nj] / (dist[ni][nj] + 1);\n        neighbors.emplace_back(priority, make_pair(ni, nj));\n    }\n    sort(neighbors.rbegin(), neighbors.rend());\n    for (auto [priority, p] : neighbors) {\n        auto [ni, nj] = p;\n        route += DIR[dir];\n        dfs(ni, nj);\n        route += DIR[(dir + 2) % 4];\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; ++i) {\n        cin >> h[i];\n    }\n    v.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> v[i];\n    }\n    d.resize(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    bfs();\n    visited.assign(N, vector<bool>(N, false));\n    dfs(0, 0);\n\n    if (route.size() > MAX_MOVES) {\n        route = route.substr(0, MAX_MOVES);\n    }\n    cout << route << endl;\n\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 15;\nconst int M = 200;\nconst int MAX_OPERATIONS = 5000;\nconst int BEAM_WIDTH = 1000;\n\nstruct State {\n    string s;\n    int i, j;\n    bitset<M> covered;\n    int cost;\n    vector<pair<int, int>> path;\n\n    bool operator<(const State& other) const {\n        return cost > other.cost; // For min-heap\n    }\n};\n\nvector<string> t(M);\nvector<vector<pair<int, int>>> char_positions(26);\nvector<vector<vector<pair<int, int>>>> word_positions(M);\n\nint manhattan(int i1, int j1, int i2, int j2) {\n    return abs(i1 - i2) + abs(j1 - j2);\n}\n\nvoid preprocess(const vector<string>& grid) {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = grid[i][j];\n            char_positions[c - 'A'].emplace_back(i, j);\n        }\n    }\n\n    for (int k = 0; k < M; ++k) {\n        const string& word = t[k];\n        vector<vector<pair<int, int>>> positions;\n        for (char c : word) {\n            positions.push_back(char_positions[c - 'A']);\n        }\n        word_positions[k] = positions;\n    }\n}\n\nint estimate_remaining_cost(const State& state) {\n    int remaining = 0;\n    for (int k = 0; k < M; ++k) {\n        if (!state.covered[k]) {\n            remaining += 5; // Each word has 5 characters\n        }\n    }\n    return remaining;\n}\n\nvector<pair<int, int>> beam_search(const vector<string>& grid, int si, int sj) {\n    priority_queue<State> pq;\n    State initial;\n    initial.s = \"\";\n    initial.i = si;\n    initial.j = sj;\n    initial.cost = 0;\n    initial.path = {{si, sj}};\n    pq.push(initial);\n\n    vector<pair<int, int>> best_path;\n    int best_cost = INT_MAX;\n    bitset<M> best_covered;\n\n    while (!pq.empty() && pq.top().cost < best_cost) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.covered.all()) {\n            if (current.cost < best_cost) {\n                best_cost = current.cost;\n                best_path = current.path;\n                best_covered = current.covered;\n            }\n            continue;\n        }\n\n        if (current.path.size() >= MAX_OPERATIONS) {\n            continue;\n        }\n\n        // Generate next states\n        for (int c = 0; c < 26; ++c) {\n            for (auto [ni, nj] : char_positions[c]) {\n                int move_cost = manhattan(current.i, current.j, ni, nj) + 1;\n                State next = current;\n                next.s += ('A' + c);\n                next.i = ni;\n                next.j = nj;\n                next.cost += move_cost;\n                next.path.emplace_back(ni, nj);\n\n                // Check if new character helps cover any words\n                for (int k = 0; k < M; ++k) {\n                    if (!next.covered[k]) {\n                        const string& word = t[k];\n                        if (next.s.size() >= word.size()) {\n                            bool match = true;\n                            for (int l = 0; l < word.size(); ++l) {\n                                if (next.s[next.s.size() - word.size() + l] != word[l]) {\n                                    match = false;\n                                    break;\n                                }\n                            }\n                            if (match) {\n                                next.covered[k] = true;\n                            }\n                        }\n                    }\n                }\n\n                if (next.cost + estimate_remaining_cost(next) < best_cost) {\n                    pq.push(next);\n                    if (pq.size() > BEAM_WIDTH) {\n                        pq.pop();\n                    }\n                }\n            }\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, M_in;\n    cin >> N_in >> M_in;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> grid(N_in);\n    for (int i = 0; i < N_in; ++i) {\n        cin >> grid[i];\n    }\n    for (int k = 0; k < M_in; ++k) {\n        cin >> t[k];\n    }\n\n    preprocess(grid);\n    auto path = beam_search(grid, si, sj);\n\n    for (auto [i, j] : path) {\n        cout << i << \" \" << j << \"\\n\";\n    }\n\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int i, j;\n    Point(int i = 0, int j = 0) : i(i), j(j) {}\n    bool operator<(const Point& other) const {\n        return i < other.i || (i == other.i && j < other.j);\n    }\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nstruct OilField {\n    int d;\n    vector<Point> cells;\n    OilField(int d = 0) : d(d) {}\n};\n\nstruct QueryResult {\n    double value;\n    double variance;\n    int k;\n};\n\nclass Solver {\nprivate:\n    int N, M;\n    double eps;\n    vector<OilField> fields;\n    vector<vector<int>> grid;\n    vector<vector<double>> estimate;\n    vector<vector<double>> variance;\n    vector<vector<bool>> drilled;\n    vector<Point> drilled_points;\n    vector<QueryResult> divinations;\n    mt19937 rng;\n\n    double normal_cdf(double x) {\n        return 0.5 * (1.0 + erf(x / sqrt(2.0)));\n    }\n\n    double normal_pdf(double x) {\n        return exp(-0.5 * x * x) / sqrt(2.0 * M_PI);\n    }\n\n    double update_estimate(double prior_mean, double prior_var, double observed, double obs_var) {\n        double precision = 1.0 / prior_var;\n        double obs_precision = 1.0 / obs_var;\n        double new_precision = precision + obs_precision;\n        double new_mean = (prior_mean * precision + observed * obs_precision) / new_precision;\n        return new_mean;\n    }\n\n    void update_variance(double& prior_var, double obs_var) {\n        double precision = 1.0 / prior_var;\n        double obs_precision = 1.0 / obs_var;\n        prior_var = 1.0 / (precision + obs_precision);\n    }\n\npublic:\n    Solver(int N, int M, double eps, const vector<OilField>& fields)\n        : N(N), M(M), eps(eps), fields(fields), rng(random_device{}()) {\n        grid.assign(N, vector<int>(N, 0));\n        estimate.assign(N, vector<double>(N, 0.0));\n        variance.assign(N, vector<double>(N, 1e9));\n        drilled.assign(N, vector<bool>(N, false));\n    }\n\n    void set_grid(const vector<vector<int>>& g) {\n        grid = g;\n    }\n\n    void drill(int i, int j) {\n        cout << \"q 1 \" << i << \" \" << j << endl;\n        cout.flush();\n        int v;\n        cin >> v;\n        drilled[i][j] = true;\n        drilled_points.emplace_back(i, j);\n        estimate[i][j] = v;\n        variance[i][j] = 0.0;\n    }\n\n    QueryResult divine(const vector<Point>& points) {\n        int k = points.size();\n        cout << \"q \" << k;\n        for (const auto& p : points) {\n            cout << \" \" << p.i << \" \" << p.j;\n        }\n        cout << endl;\n        cout.flush();\n\n        double observed;\n        cin >> observed;\n\n        double mu = (k - observed) * eps + observed * (1 - eps);\n        double sigma_sq = k * eps * (1 - eps);\n        double sigma = sqrt(sigma_sq);\n\n        // Sample from normal distribution\n        normal_distribution<double> dist(mu, sigma);\n        double sampled = dist(rng);\n        double rounded = max(0.0, round(sampled));\n\n        QueryResult res;\n        res.value = rounded;\n        res.variance = sigma_sq;\n        res.k = k;\n        divinations.push_back(res);\n\n        return res;\n    }\n\n    void update_estimates(const vector<Point>& points, const QueryResult& res) {\n        double total_estimate = 0.0;\n        for (const auto& p : points) {\n            total_estimate += estimate[p.i][p.j];\n        }\n\n        double new_estimate = res.value;\n        double obs_var = res.variance;\n\n        for (const auto& p : points) {\n            if (drilled[p.i][p.j]) continue;\n\n            double prior_mean = estimate[p.i][p.j];\n            double prior_var = variance[p.i][p.j];\n\n            double new_mean = update_estimate(prior_mean, prior_var, new_estimate, obs_var);\n            estimate[p.i][p.j] = new_mean;\n            update_variance(variance[p.i][p.j], obs_var / points.size());\n        }\n    }\n\n    vector<Point> get_high_variance_points(int count) {\n        vector<pair<double, Point>> candidates;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (!drilled[i][j]) {\n                    candidates.emplace_back(variance[i][j], Point(i, j));\n                }\n            }\n        }\n        sort(candidates.rbegin(), candidates.rend());\n        vector<Point> result;\n        for (int i = 0; i < min(count, (int)candidates.size()); ++i) {\n            result.push_back(candidates[i].second);\n        }\n        return result;\n    }\n\n    vector<Point> get_high_estimate_points(int count) {\n        vector<pair<double, Point>> candidates;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (!drilled[i][j]) {\n                    candidates.emplace_back(estimate[i][j], Point(i, j));\n                }\n            }\n        }\n        sort(candidates.rbegin(), candidates.rend());\n        vector<Point> result;\n        for (int i = 0; i < min(count, (int)candidates.size()); ++i) {\n            result.push_back(candidates[i].second);\n        }\n        return result;\n    }\n\n    vector<Point> get_quadrant_points(int i_start, int i_end, int j_start, int j_end) {\n        vector<Point> points;\n        for (int i = i_start; i < i_end; ++i) {\n            for (int j = j_start; j < j_end; ++j) {\n                points.emplace_back(i, j);\n            }\n        }\n        return points;\n    }\n\n    void solve() {\n        // Initial divination of the whole grid\n        auto all_points = get_quadrant_points(0, N, 0, N);\n        auto res = divine(all_points);\n        update_estimates(all_points, res);\n\n        // Hierarchical divination\n        for (int level = 0; level < 3; ++level) {\n            int step = N / (1 << level);\n            for (int i = 0; i < N; i += step) {\n                for (int j = 0; j < N; j += step) {\n                    int i_end = min(i + step, N);\n                    int j_end = min(j + step, N);\n                    auto points = get_quadrant_points(i, i_end, j, j_end);\n                    if (points.size() < 2) continue;\n                    res = divine(points);\n                    update_estimates(points, res);\n                }\n            }\n        }\n\n        // Drill high variance points\n        for (int i = 0; i < 50; ++i) {\n            auto points = get_high_variance_points(1);\n            if (points.empty()) break;\n            drill(points[0].i, points[0].j);\n        }\n\n        // Drill high estimate points\n        for (int i = 0; i < 50; ++i) {\n            auto points = get_high_estimate_points(1);\n            if (points.empty()) break;\n            drill(points[0].i, points[0].j);\n        }\n\n        // Final guess\n        vector<Point> oil_squares;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (estimate[i][j] > 0.5) {\n                    oil_squares.emplace_back(i, j);\n                }\n            }\n        }\n\n        // Ensure all drilled oil squares are included\n        for (const auto& p : drilled_points) {\n            if (grid[p.i][p.j] > 0 && find(oil_squares.begin(), oil_squares.end(), p) == oil_squares.end()) {\n                oil_squares.push_back(p);\n            }\n        }\n\n        cout << \"a \" << oil_squares.size();\n        for (const auto& p : oil_squares) {\n            cout << \" \" << p.i << \" \" << p.j;\n        }\n        cout << endl;\n        cout.flush();\n\n        int correct;\n        cin >> correct;\n        if (correct == 1) {\n            return;\n        }\n\n        // If wrong, try again with more drilling\n        for (int i = 0; i < 100; ++i) {\n            auto points = get_high_estimate_points(1);\n            if (points.empty()) break;\n            drill(points[0].i, points[0].j);\n        }\n\n        oil_squares.clear();\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (estimate[i][j] > 0.5) {\n                    oil_squares.emplace_back(i, j);\n                }\n            }\n        }\n\n        for (const auto& p : drilled_points) {\n            if (grid[p.i][p.j] > 0 && find(oil_squares.begin(), oil_squares.end(), p) == oil_squares.end()) {\n                oil_squares.push_back(p);\n            }\n        }\n\n        cout << \"a \" << oil_squares.size();\n        for (const auto& p : oil_squares) {\n            cout << \" \" << p.i << \" \" << p.j;\n        }\n        cout << endl;\n        cout.flush();\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n\n    vector<OilField> fields(M);\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        fields[k].d = d;\n        for (int i = 0; i < d; ++i) {\n            int x, y;\n            cin >> x >> y;\n            fields[k].cells.emplace_back(x, y);\n        }\n    }\n\n    Solver solver(N, M, eps, fields);\n    solver.solve();\n\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int W = 1000;\nconst int MAX_D = 50;\nconst int MAX_N = 50;\n\nstruct Rect {\n    int i1, j1, i2, j2;\n    Rect(int i1 = 0, int j1 = 0, int i2 = 0, int j2 = 0) : i1(i1), j1(j1), i2(i2), j2(j2) {}\n    int area() const { return (i2 - i1) * (j2 - j1); }\n};\n\nvector<vector<Rect>> solve(int D, int N, const vector<vector<int>>& a) {\n    vector<vector<Rect>> res(D, vector<Rect>(N));\n\n    // For each day, we'll partition the grid into N rectangles\n    for (int d = 0; d < D; ++d) {\n        vector<int> areas = a[d];\n        sort(areas.begin(), areas.end(), greater<int>());\n        vector<Rect> rects;\n        int remaining_height = W;\n        int remaining_width = W;\n        int current_i = 0;\n        int current_j = 0;\n\n        for (int k = 0; k < N; ++k) {\n            int target = areas[k];\n            if (k == N - 1) {\n                // Last rectangle takes the remaining space\n                rects.emplace_back(current_i, current_j, W, W);\n                break;\n            }\n            // Decide whether to split vertically or horizontally\n            int split_height = (target + remaining_width - 1) / remaining_width;\n            if (split_height > remaining_height) {\n                split_height = remaining_height;\n            }\n            int split_width = (target + split_height - 1) / split_height;\n            if (split_width > remaining_width) {\n                split_width = remaining_width;\n            }\n\n            // Try to split vertically first\n            int best_split = -1;\n            int best_diff = INT_MAX;\n            for (int split = 1; split <= remaining_width; ++split) {\n                int h = (target + split - 1) / split;\n                if (h > remaining_height) continue;\n                int diff = abs(target - split * h);\n                if (diff < best_diff) {\n                    best_diff = diff;\n                    best_split = split;\n                }\n            }\n            // Try to split horizontally\n            for (int split = 1; split <= remaining_height; ++split) {\n                int w = (target + split - 1) / split;\n                if (w > remaining_width) continue;\n                int diff = abs(target - split * w);\n                if (diff < best_diff) {\n                    best_diff = diff;\n                    best_split = -split; // negative indicates horizontal split\n                }\n            }\n\n            if (best_split > 0) {\n                // Vertical split\n                int split = best_split;\n                int h = (target + split - 1) / split;\n                rects.emplace_back(current_i, current_j, current_i + h, current_j + split);\n                current_j += split;\n                remaining_width -= split;\n            } else {\n                // Horizontal split\n                int split = -best_split;\n                int w = (target + split - 1) / split;\n                rects.emplace_back(current_i, current_j, current_i + split, current_j + w);\n                current_i += split;\n                remaining_height -= split;\n            }\n        }\n        res[d] = rects;\n    }\n\n    // Now, try to minimize partition changes between days\n    for (int d = 1; d < D; ++d) {\n        // For simplicity, we'll just use the same partitioning as the previous day\n        // and adjust the rectangles to meet the new area requirements\n        // This is a placeholder; a better approach would involve more sophisticated matching\n        res[d] = res[d-1];\n        for (int k = 0; k < N; ++k) {\n            int target = a[d][k];\n            Rect& r = res[d][k];\n            int current_area = r.area();\n            if (current_area < target) {\n                // Need to expand the rectangle\n                // Try to expand to the right or down\n                if (r.j2 < W) {\n                    int new_width = (target + (r.i2 - r.i1) - 1) / (r.i2 - r.i1);\n                    if (new_width > W - r.j1) new_width = W - r.j1;\n                    r.j2 = r.j1 + new_width;\n                } else if (r.i2 < W) {\n                    int new_height = (target + (r.j2 - r.j1) - 1) / (r.j2 - r.j1);\n                    if (new_height > W - r.i1) new_height = W - r.i1;\n                    r.i2 = r.i1 + new_height;\n                }\n            } else if (current_area > target) {\n                // Need to shrink the rectangle\n                // Try to shrink from the right or bottom\n                int shrink_area = current_area - target;\n                if (r.j2 > r.j1) {\n                    int shrink_width = min(shrink_area / (r.i2 - r.i1), r.j2 - r.j1 - 1);\n                    r.j2 -= shrink_width;\n                } else if (r.i2 > r.i1) {\n                    int shrink_height = min(shrink_area / (r.j2 - r.j1), r.i2 - r.i1 - 1);\n                    r.i2 -= shrink_height;\n                }\n            }\n        }\n    }\n\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int W_in, D, N;\n    cin >> W_in >> D >> 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    }\n\n    auto res = solve(D, N, a);\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            const auto& r = res[d][k];\n            cout << r.i1 << \" \" << r.j1 << \" \" << r.i2 << \" \" << r.j2 << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K_MAX = 81;\nconst int STAMP_SIZE = 3;\n\nint a[N][N];\nint s[M][STAMP_SIZE][STAMP_SIZE];\nint b[N][N];\nint d[N][N]; // deficit: MOD - 1 - (b[i][j] % MOD)\n\nstruct Operation {\n    int m, p, q;\n};\n\nvector<Operation> operations;\n\nvoid apply_stamp(int m, int p, int q) {\n    for (int i = 0; i < STAMP_SIZE; ++i) {\n        for (int j = 0; j < STAMP_SIZE; ++j) {\n            b[p + i][q + j] += s[m][i][j];\n        }\n    }\n}\n\nvoid update_deficits() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            d[i][j] = (MOD - 1 - (b[i][j] % MOD)) % MOD;\n        }\n    }\n}\n\nint compute_contribution(int m, int p, int q) {\n    int contribution = 0;\n    for (int i = 0; i < STAMP_SIZE; ++i) {\n        for (int j = 0; j < STAMP_SIZE; ++j) {\n            int ni = p + i;\n            int nj = q + j;\n            if (ni >= N || nj >= N) continue;\n            int add = min(s[m][i][j], d[ni][nj]);\n            contribution += add;\n        }\n    }\n    return contribution;\n}\n\nvoid greedy_solve() {\n    // Initialize b and d\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            b[i][j] = a[i][j];\n        }\n    }\n    update_deficits();\n\n    operations.clear();\n    for (int k = 0; k < K_MAX; ++k) {\n        int best_contribution = -1;\n        int best_m = -1, best_p = -1, best_q = -1;\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - STAMP_SIZE; ++p) {\n                for (int q = 0; q <= N - STAMP_SIZE; ++q) {\n                    int contribution = compute_contribution(m, p, q);\n                    if (contribution > best_contribution) {\n                        best_contribution = contribution;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_contribution <= 0) break;\n\n        operations.push_back({best_m, best_p, best_q});\n        apply_stamp(best_m, best_p, best_q);\n        update_deficits();\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, M_in, K_in;\n    cin >> N_in >> M_in >> K_in;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> a[i][j];\n        }\n    }\n    for (int m = 0; m < M; ++m) {\n        for (int i = 0; i < STAMP_SIZE; ++i) {\n            for (int j = 0; j < STAMP_SIZE; ++j) {\n                cin >> s[m][i][j];\n            }\n        }\n    }\n\n    greedy_solve();\n\n    cout << operations.size() << '\\n';\n    for (const auto& op : operations) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 5;\nconst int MAX_TURNS = 10000;\n\nstruct Container {\n    int id;\n    int target_gate;\n    int current_i, current_j;\n    bool is_held;\n    int held_by;\n};\n\nstruct Crane {\n    int id;\n    int i, j;\n    bool is_large;\n    bool is_holding;\n    int holding_id;\n    bool is_bombed;\n};\n\nvector<Container> containers;\nvector<Crane> cranes;\nvector<vector<int>> grid(N, vector<int>(N, -1)); // -1: empty, -2: crane, otherwise container id\nvector<vector<int>> A(N, vector<int>(N));\nvector<string> operations(N);\n\nvoid initialize() {\n    containers.clear();\n    cranes.clear();\n    grid.assign(N, vector<int>(N, -1));\n    operations.assign(N, \"\");\n\n    // Initialize cranes\n    for (int i = 0; i < N; ++i) {\n        cranes.push_back({i, i, 0, i == 0, false, -1, false});\n        grid[i][0] = -2; // Mark crane position\n    }\n\n    // Initialize containers\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int id = A[i][j];\n            int target_gate = id / N;\n            containers.push_back({id, target_gate, i, 0, false, -1});\n        }\n    }\n}\n\nbool is_valid_move(int crane_id, int di, int dj) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed) return false;\n    int ni = crane.i + di;\n    int nj = crane.j + dj;\n    if (ni < 0 || ni >= N || nj < 0 || nj >= N) return false;\n\n    // Check if destination is occupied by another crane\n    for (int i = 0; i < N; ++i) {\n        if (i == crane_id) continue;\n        if (cranes[i].i == ni && cranes[i].j == nj && !cranes[i].is_bombed) {\n            return false;\n        }\n    }\n\n    // Check if carrying and small crane\n    if (crane.is_holding && !crane.is_large) {\n        if (grid[ni][nj] != -1) return false; // Small crane cannot move to occupied square while carrying\n    }\n\n    return true;\n}\n\nvoid move_crane(int crane_id, char dir) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed) return;\n\n    int di = 0, dj = 0;\n    switch (dir) {\n        case 'U': di = -1; break;\n        case 'D': di = 1; break;\n        case 'L': dj = -1; break;\n        case 'R': dj = 1; break;\n        default: return;\n    }\n\n    if (!is_valid_move(crane_id, di, dj)) return;\n\n    // Update grid\n    grid[crane.i][crane.j] = -1;\n    crane.i += di;\n    crane.j += dj;\n    grid[crane.i][crane.j] = -2;\n}\n\nvoid pick_up(int crane_id) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed || crane.is_holding) return;\n\n    if (grid[crane.i][crane.j] != -1) {\n        int container_id = grid[crane.i][crane.j];\n        if (container_id >= 0 && container_id < N*N) {\n            containers[container_id].is_held = true;\n            containers[container_id].held_by = crane_id;\n            crane.is_holding = true;\n            crane.holding_id = container_id;\n            grid[crane.i][crane.j] = -1;\n        }\n    }\n}\n\nvoid release(int crane_id) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed || !crane.is_holding) return;\n\n    if (grid[crane.i][crane.j] == -1) {\n        int container_id = crane.holding_id;\n        containers[container_id].is_held = false;\n        containers[container_id].held_by = -1;\n        containers[container_id].current_i = crane.i;\n        containers[container_id].current_j = crane.j;\n        crane.is_holding = false;\n        crane.holding_id = -1;\n        grid[crane.i][crane.j] = container_id;\n    }\n}\n\nvoid bomb(int crane_id) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed || crane.is_holding) return;\n\n    crane.is_bombed = true;\n    grid[crane.i][crane.j] = -1;\n}\n\nvoid do_nothing(int crane_id) {\n    // Do nothing\n}\n\nvoid simulate_turn() {\n    // Step 1: Place new containers at Receiving Gates\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] == -1) {\n            for (int j = 0; j < N; ++j) {\n                int id = A[i][j];\n                if (!containers[id].is_held && containers[id].current_i == i && containers[id].current_j == 0) {\n                    grid[i][0] = id;\n                    containers[id].current_i = i;\n                    containers[id].current_j = 0;\n                    break;\n                }\n            }\n        }\n    }\n\n    // Step 2: Perform crane actions\n    for (int i = 0; i < N; ++i) {\n        if (operations[i].empty()) continue;\n        char action = operations[i].back();\n        operations[i].pop_back();\n\n        switch (action) {\n            case 'P': pick_up(i); break;\n            case 'Q': release(i); break;\n            case 'U': move_crane(i, 'U'); break;\n            case 'D': move_crane(i, 'D'); break;\n            case 'L': move_crane(i, 'L'); break;\n            case 'R': move_crane(i, 'R'); break;\n            case 'B': bomb(i); break;\n            case '.': do_nothing(i); break;\n        }\n    }\n\n    // Step 3: Dispatch containers at Dispatch Gates\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][N-1] != -1) {\n            int id = grid[i][N-1];\n            if (id >= 0 && id < N*N) {\n                grid[i][N-1] = -1;\n            }\n        }\n    }\n}\n\nvoid plan_operations() {\n    // Simple heuristic: move containers to their target gates\n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        bool all_dispatched = true;\n        for (const auto &container : containers) {\n            if (!container.is_held && grid[container.current_i][container.current_j] != -1) {\n                all_dispatched = false;\n                break;\n            }\n        }\n        if (all_dispatched) break;\n\n        for (int i = 0; i < N; ++i) {\n            Crane &crane = cranes[i];\n            if (crane.is_bombed) {\n                operations[i] += '.';\n                continue;\n            }\n\n            if (crane.is_holding) {\n                int container_id = crane.holding_id;\n                int target_gate = containers[container_id].target_gate;\n                int target_i = target_gate;\n                int target_j = N-1;\n\n                if (crane.i == target_i && crane.j == target_j) {\n                    operations[i] += 'Q';\n                } else {\n                    // Move towards target\n                    if (crane.j < target_j) {\n                        operations[i] += 'R';\n                    } else if (crane.j > target_j) {\n                        operations[i] += 'L';\n                    } else if (crane.i < target_i) {\n                        operations[i] += 'D';\n                    } else if (crane.i > target_i) {\n                        operations[i] += 'U';\n                    }\n                }\n            } else {\n                // Find the nearest container to pick up\n                int nearest_id = -1;\n                int min_dist = INT_MAX;\n                for (int id = 0; id < N*N; ++id) {\n                    if (!containers[id].is_held && grid[containers[id].current_i][containers[id].current_j] != -1) {\n                        int dist = abs(crane.i - containers[id].current_i) + abs(crane.j - containers[id].current_j);\n                        if (dist < min_dist) {\n                            min_dist = dist;\n                            nearest_id = id;\n                        }\n                    }\n                }\n\n                if (nearest_id != -1) {\n                    int target_i = containers[nearest_id].current_i;\n                    int target_j = containers[nearest_id].current_j;\n\n                    if (crane.i == target_i && crane.j == target_j) {\n                        operations[i] += 'P';\n                    } else {\n                        // Move towards container\n                        if (crane.j < target_j) {\n                            operations[i] += 'R';\n                        } else if (crane.j > target_j) {\n                            operations[i] += 'L';\n                        } else if (crane.i < target_i) {\n                            operations[i] += 'D';\n                        } else if (crane.i > target_i) {\n                            operations[i] += 'U';\n                        }\n                    }\n                } else {\n                    operations[i] += '.';\n                }\n            }\n        }\n\n        simulate_turn();\n    }\n\n    // Reverse operations to get correct order\n    for (int i = 0; i < N; ++i) {\n        reverse(operations[i].begin(), operations[i].end());\n    }\n}\n\nint main() {\n    cin >> N;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n        }\n    }\n\n    initialize();\n    plan_operations();\n\n    // Output operations\n    for (int i = 0; i < N; ++i) {\n        cout << operations[i] << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 20;\n    vector<vector<int>> grid(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> grid[i][j];\n        }\n    }\n\n    // Local balancing: try to push soil to adjacent cells\n    vector<string> ops;\n    int x = 0, y = 0;\n    int load = 0;\n\n    auto move_to = [&](int nx, int ny) {\n        while (x != nx || y != ny) {\n            if (x < nx) { ops.push_back(\"D\"); x++; }\n            else if (x > nx) { ops.push_back(\"U\"); x--; }\n            else if (y < ny) { ops.push_back(\"R\"); y++; }\n            else if (y > ny) { ops.push_back(\"L\"); y--; }\n        }\n    };\n\n    // Local balancing: for each cell, try to push to adjacent cells\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] <= 0) continue;\n            move_to(i, j);\n            // Try to push to adjacent cells\n            vector<pair<int, int>> adj = {{i-1,j}, {i+1,j}, {i,j-1}, {i,j+1}};\n            for (auto [ni, nj] : adj) {\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                if (grid[ni][nj] >= 0) continue;\n                int d = min(grid[i][j], -grid[ni][nj]);\n                if (d <= 0) continue;\n                // Move to (ni, nj)\n                move_to(ni, nj);\n                // Unload d\n                ops.push_back(\"-\" + to_string(d));\n                grid[ni][nj] += d;\n                load -= d;\n                // Move back to (i,j)\n                move_to(i, j);\n                // Load d\n                ops.push_back(\"+\" + to_string(d));\n                grid[i][j] -= d;\n                load += d;\n            }\n        }\n    }\n\n    // Snake traversal for global balancing\n    vector<pair<int, int>> order;\n    for (int i = 0; i < N; ++i) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; ++j) order.emplace_back(i, j);\n        } else {\n            for (int j = N - 1; j >= 0; --j) order.emplace_back(i, j);\n        }\n    }\n\n    for (auto [i, j] : order) {\n        move_to(i, j);\n        if (grid[i][j] > 0) {\n            int d = min(grid[i][j], 1000000);\n            ops.push_back(\"+\" + to_string(d));\n            grid[i][j] -= d;\n            load += d;\n        } else if (grid[i][j] < 0) {\n            int d = min(-grid[i][j], load);\n            if (d > 0) {\n                ops.push_back(\"-\" + to_string(d));\n                grid[i][j] += d;\n                load -= d;\n            }\n        }\n    }\n\n    // Final unload if needed\n    if (load > 0) {\n        move_to(0, 0);\n        ops.push_back(\"-\" + to_string(load));\n    }\n\n    // Output\n    for (const string& op : ops) {\n        cout << op << '\\n';\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Seed {\n    vector<int> eval;\n    int value;\n    int id;\n};\n\nbool compareSeeds(const Seed &a, const Seed &b) {\n    return a.value > b.value;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 6, M = 15, T = 10;\n    int seed_count = 2 * N * (N - 1);\n    vector<Seed> seeds(seed_count);\n\n    for (int i = 0; i < seed_count; ++i) {\n        seeds[i].eval.resize(M);\n        seeds[i].id = i;\n        for (int j = 0; j < M; ++j) {\n            cin >> seeds[i].eval[j];\n        }\n        seeds[i].value = accumulate(seeds[i].eval.begin(), seeds[i].eval.end(), 0);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        // Sort seeds by value in descending order\n        sort(seeds.begin(), seeds.end(), compareSeeds);\n\n        // Select top N*N seeds\n        vector<Seed> selected_seeds(seeds.begin(), seeds.begin() + N * N);\n\n        // Create a grid to place the selected seeds\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                grid[i][j] = selected_seeds[i * N + j].id;\n            }\n        }\n\n        // Output the grid\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << grid[i][j];\n                if (j < N - 1) {\n                    cout << \" \";\n                }\n            }\n            cout << endl;\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seed_count; ++i) {\n            seeds[i].eval.resize(M);\n            seeds[i].id = i;\n            for (int j = 0; j < M; ++j) {\n                cin >> seeds[i].eval[j];\n            }\n            seeds[i].value = accumulate(seeds[i].eval.begin(), seeds[i].eval.end(), 0);\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        return x < other.x || (x == other.x && y < other.y);\n    }\n};\n\nstruct Takoyaki {\n    Point source, target;\n    bool operator<(const Takoyaki& other) const {\n        return source < other.source || (source == other.source && target < other.target);\n    }\n};\n\nvector<Point> find_takoyaki(const vector<string>& grid, char c) {\n    vector<Point> res;\n    for (int i = 0; i < grid.size(); ++i) {\n        for (int j = 0; j < grid[i].size(); ++j) {\n            if (grid[i][j] == c) {\n                res.emplace_back(i, j);\n            }\n        }\n    }\n    return res;\n}\n\nvector<Takoyaki> create_takoyaki_list(const vector<Point>& sources, const vector<Point>& targets) {\n    vector<Takoyaki> res;\n    for (int i = 0; i < sources.size(); ++i) {\n        res.push_back({sources[i], targets[i]});\n    }\n    return res;\n}\n\nstruct TreeNode {\n    int parent;\n    int length;\n    TreeNode(int p = -1, int l = 1) : parent(p), length(l) {}\n};\n\nvector<TreeNode> design_tree(int V) {\n    vector<TreeNode> tree;\n    if (V == 1) {\n        return tree;\n    }\n    tree.emplace_back(0, 1);\n    if (V == 2) {\n        return tree;\n    }\n    tree.emplace_back(0, 2);\n    if (V == 3) {\n        return tree;\n    }\n    for (int i = 2; i < V; ++i) {\n        int p = (i - 1) / 2;\n        int l = 1 + (i % 2);\n        tree.emplace_back(p, l);\n    }\n    return tree;\n}\n\nPoint initial_root_position(int N, const vector<Takoyaki>& takoyakis) {\n    int sum_x = 0, sum_y = 0;\n    for (const auto& t : takoyakis) {\n        sum_x += t.source.x + t.target.x;\n        sum_y += t.source.y + t.target.y;\n    }\n    int cnt = 2 * takoyakis.size();\n    return Point(sum_x / cnt, sum_y / cnt);\n}\n\nvector<string> generate_operations(const vector<TreeNode>& tree, const Point& root_pos,\n                                   const vector<Takoyaki>& takoyakis, int N) {\n    vector<string> operations;\n    int V = tree.size() + 1;\n    vector<Point> fingertip_pos(V);\n    vector<int> dir(V, 0); // 0: right, 1: down, 2: left, 3: up\n    vector<bool> holding(V, false);\n    vector<Point> current_pos(V);\n    current_pos[0] = root_pos;\n\n    auto update_positions = [&]() {\n        for (int i = 1; i < V; ++i) {\n            int p = tree[i-1].parent;\n            int l = tree[i-1].length;\n            int dx = 0, dy = 0;\n            if (dir[i] == 0) { dx = l; }\n            else if (dir[i] == 1) { dy = l; }\n            else if (dir[i] == 2) { dx = -l; }\n            else if (dir[i] == 3) { dy = -l; }\n            current_pos[i] = Point(current_pos[p].x + dx, current_pos[p].y + dy);\n        }\n    };\n\n    update_positions();\n\n    auto move_root = [&](int dx, int dy) {\n        current_pos[0].x += dx;\n        current_pos[0].y += dy;\n        update_positions();\n    };\n\n    auto rotate_subtree = [&](int u, bool clockwise) {\n        if (clockwise) {\n            dir[u] = (dir[u] + 1) % 4;\n        } else {\n            dir[u] = (dir[u] + 3) % 4;\n        }\n        update_positions();\n    };\n\n    auto can_grab = [&](int u, const Point& p) {\n        return current_pos[u] == p && !holding[u];\n    };\n\n    auto can_release = [&](int u, const Point& p) {\n        return current_pos[u] == p && holding[u];\n    };\n\n    auto bfs_path = [&](Point start, Point target) {\n        vector<vector<int>> dist(N, vector<int>(N, -1));\n        vector<vector<Point>> prev(N, vector<Point>(N, Point(-1, -1)));\n        queue<Point> q;\n        dist[start.x][start.y] = 0;\n        q.push(start);\n        vector<int> dx = {0, 1, 0, -1};\n        vector<int> dy = {1, 0, -1, 0};\n        while (!q.empty()) {\n            Point p = q.front();\n            q.pop();\n            if (p == target) {\n                vector<Point> path;\n                while (p != start) {\n                    path.push_back(p);\n                    p = prev[p.x][p.y];\n                }\n                reverse(path.begin(), path.end());\n                return path;\n            }\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + dx[i];\n                int ny = p.y + dy[i];\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N && dist[nx][ny] == -1) {\n                    dist[nx][ny] = dist[p.x][p.y] + 1;\n                    prev[nx][ny] = p;\n                    q.emplace(nx, ny);\n                }\n            }\n        }\n        return vector<Point>();\n    };\n\n    auto move_to = [&](Point target) {\n        vector<Point> path = bfs_path(current_pos[0], target);\n        for (Point p : path) {\n            int dx = p.x - current_pos[0].x;\n            int dy = p.y - current_pos[0].y;\n            if (dx == 1) {\n                operations.push_back(\"D\" + string(V-1, '.') + string(V, '.'));\n                move_root(1, 0);\n            } else if (dx == -1) {\n                operations.push_back(\"U\" + string(V-1, '.') + string(V, '.'));\n                move_root(-1, 0);\n            } else if (dy == 1) {\n                operations.push_back(\"R\" + string(V-1, '.') + string(V, '.'));\n                move_root(0, 1);\n            } else if (dy == -1) {\n                operations.push_back(\"L\" + string(V-1, '.') + string(V, '.'));\n                move_root(0, -1);\n            }\n        }\n    };\n\n    auto align_fingertip = [&](int u, Point target) {\n        Point p = current_pos[u];\n        int dx = target.x - p.x;\n        int dy = target.y - p.y;\n        int required_dir = -1;\n        if (dx > 0 && dy == 0) required_dir = 0;\n        else if (dx == 0 && dy > 0) required_dir = 1;\n        else if (dx < 0 && dy == 0) required_dir = 2;\n        else if (dx == 0 && dy < 0) required_dir = 3;\n        if (required_dir == -1) return;\n        while (dir[u] != required_dir) {\n            bool clockwise = (dir[u] + 1) % 4 == required_dir;\n            string op(V*2, '.');\n            op[0] = '.';\n            op[u] = clockwise ? 'R' : 'L';\n            operations.push_back(op);\n            rotate_subtree(u, clockwise);\n        }\n    };\n\n    auto process_takoyaki = [&](const Takoyaki& t) {\n        // Move to source\n        move_to(t.source);\n        // Align fingertip to source\n        for (int u = 1; u < V; ++u) {\n            if (!holding[u]) {\n                align_fingertip(u, t.source);\n                if (can_grab(u, t.source)) {\n                    string op(V*2, '.');\n                    op[V + u] = 'P';\n                    operations.push_back(op);\n                    holding[u] = true;\n                    break;\n                }\n            }\n        }\n        // Move to target\n        move_to(t.target);\n        // Align fingertip to target\n        for (int u = 1; u < V; ++u) {\n            if (holding[u]) {\n                align_fingertip(u, t.target);\n                if (can_release(u, t.target)) {\n                    string op(V*2, '.');\n                    op[V + u] = 'P';\n                    operations.push_back(op);\n                    holding[u] = false;\n                    break;\n                }\n            }\n        }\n    };\n\n    for (const auto& t : takoyakis) {\n        process_takoyaki(t);\n    }\n\n    return operations;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, V;\n    cin >> N >> M >> V;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        cin >> t[i];\n    }\n\n    vector<Point> sources = find_takoyaki(s, '1');\n    vector<Point> targets = find_takoyaki(t, '1');\n    vector<Takoyaki> takoyakis = create_takoyaki_list(sources, targets);\n\n    vector<TreeNode> tree = design_tree(V);\n    Point root_pos = initial_root_position(N, takoyakis);\n\n    cout << tree.size() + 1 << '\\n';\n    for (const auto& node : tree) {\n        cout << node.parent << ' ' << node.length << '\\n';\n    }\n    cout << root_pos.x << ' ' << root_pos.y << '\\n';\n\n    vector<string> operations = generate_operations(tree, root_pos, takoyakis, N);\n    for (const string& op : operations) {\n        cout << op << '\\n';\n    }\n\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n    bool operator==(const Point& p) const {\n        return x == p.x && y == p.y;\n    }\n};\n\nint N;\nvector<Point> mackerels, sardines;\nvector<Point> polygon;\n\nbool is_inside(const vector<Point>& poly, const Point& p) {\n    int n = poly.size();\n    bool inside = false;\n    for (int i = 0, j = n - 1; i < n; j = i++) {\n        const Point& a = poly[i];\n        const Point& b = poly[j];\n        if (a.y == b.y) {\n            if (p.y == a.y && min(a.x, b.x) <= p.x && p.x <= max(a.x, b.x)) {\n                return true;\n            }\n            continue;\n        }\n        if ((a.y > p.y) != (b.y > p.y)) {\n            int x_intersect = (p.y - a.y) * (b.x - a.x) / (b.y - a.y) + a.x;\n            if (p.x == x_intersect) {\n                return true;\n            }\n            if (p.x < x_intersect) {\n                inside = !inside;\n            }\n        }\n    }\n    return inside;\n}\n\nint compute_score(const vector<Point>& poly) {\n    int a = 0, b = 0;\n    for (const Point& p : mackerels) {\n        if (is_inside(poly, p)) {\n            a++;\n        }\n    }\n    for (const Point& p : sardines) {\n        if (is_inside(poly, p)) {\n            b++;\n        }\n    }\n    return max(0, a - b + 1);\n}\n\nvector<Point> initial_polygon() {\n    int min_x = 1e9, max_x = -1, min_y = 1e9, max_y = -1;\n    for (const Point& p : mackerels) {\n        min_x = min(min_x, p.x);\n        max_x = max(max_x, p.x);\n        min_y = min(min_y, p.y);\n        max_y = max(max_y, p.y);\n    }\n    vector<Point> poly = {\n        {min_x, min_y},\n        {max_x, min_y},\n        {max_x, max_y},\n        {min_x, max_y}\n    };\n    return poly;\n}\n\nvector<Point> adjust_polygon(vector<Point> poly) {\n    int m = poly.size();\n    int total_length = 0;\n    for (int i = 0; i < m; ++i) {\n        int j = (i + 1) % m;\n        total_length += abs(poly[i].x - poly[j].x) + abs(poly[i].y - poly[j].y);\n    }\n\n    auto can_add_vertex = [&]() {\n        return poly.size() < 1000 && total_length < 400000;\n    };\n\n    auto add_vertex = [&](int edge_idx, Point new_vertex) {\n        if (!can_add_vertex()) return false;\n        int i = edge_idx;\n        int j = (i + 1) % poly.size();\n        int new_length = total_length - (abs(poly[i].x - poly[j].x) + abs(poly[i].y - poly[j].y))\n                         + (abs(poly[i].x - new_vertex.x) + abs(poly[i].y - new_vertex.y))\n                         + (abs(new_vertex.x - poly[j].x) + abs(new_vertex.y - poly[j].y));\n        if (new_length > 400000) return false;\n        poly.insert(poly.begin() + i + 1, new_vertex);\n        total_length = new_length;\n        return true;\n    };\n\n    auto move_vertex = [&](int vertex_idx, Point new_pos) {\n        int i = vertex_idx;\n        int prev = (i - 1 + poly.size()) % poly.size();\n        int next = (i + 1) % poly.size();\n        int old_length = abs(poly[prev].x - poly[i].x) + abs(poly[prev].y - poly[i].y)\n                       + abs(poly[i].x - poly[next].x) + abs(poly[i].y - poly[next].y);\n        int new_length = abs(poly[prev].x - new_pos.x) + abs(poly[prev].y - new_pos.y)\n                       + abs(new_pos.x - poly[next].x) + abs(new_pos.y - poly[next].y);\n        if (total_length - old_length + new_length > 400000) return false;\n        poly[i] = new_pos;\n        total_length = total_length - old_length + new_length;\n        return true;\n    };\n\n    auto try_improve = [&]() {\n        int best_score = compute_score(poly);\n        vector<Point> best_poly = poly;\n        for (int iter = 0; iter < 100; ++iter) {\n            int edge_idx = rand() % poly.size();\n            int i = edge_idx;\n            int j = (i + 1) % poly.size();\n            if (poly[i].x == poly[j].x) {\n                int x = poly[i].x;\n                int y_min = min(poly[i].y, poly[j].y);\n                int y_max = max(poly[i].y, poly[j].y);\n                for (int y = y_min + 1; y < y_max; ++y) {\n                    Point new_vertex(x, y);\n                    if (add_vertex(edge_idx, new_vertex)) {\n                        int score = compute_score(poly);\n                        if (score > best_score) {\n                            best_score = score;\n                            best_poly = poly;\n                        } else {\n                            poly = best_poly;\n                        }\n                    }\n                }\n            } else if (poly[i].y == poly[j].y) {\n                int y = poly[i].y;\n                int x_min = min(poly[i].x, poly[j].x);\n                int x_max = max(poly[i].x, poly[j].x);\n                for (int x = x_min + 1; x < x_max; ++x) {\n                    Point new_vertex(x, y);\n                    if (add_vertex(edge_idx, new_vertex)) {\n                        int score = compute_score(poly);\n                        if (score > best_score) {\n                            best_score = score;\n                            best_poly = poly;\n                        } else {\n                            poly = best_poly;\n                        }\n                    }\n                }\n            }\n            for (int vertex_idx = 0; vertex_idx < poly.size(); ++vertex_idx) {\n                Point original = poly[vertex_idx];\n                for (int dx = -1; dx <= 1; ++dx) {\n                    for (int dy = -1; dy <= 1; ++dy) {\n                        if (dx == 0 && dy == 0) continue;\n                        Point new_pos(original.x + dx, original.y + dy);\n                        if (move_vertex(vertex_idx, new_pos)) {\n                            int score = compute_score(poly);\n                            if (score > best_score) {\n                                best_score = score;\n                                best_poly = poly;\n                            } else {\n                                poly = best_poly;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        return best_poly;\n    };\n\n    return try_improve();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    mackerels.resize(N);\n    sardines.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> mackerels[i].x >> mackerels[i].y;\n    }\n    for (int i = 0; i < N; ++i) {\n        cin >> sardines[i].x >> sardines[i].y;\n    }\n\n    polygon = initial_polygon();\n    polygon = adjust_polygon(polygon);\n\n    cout << polygon.size() << '\\n';\n    for (const Point& p : polygon) {\n        cout << p.x << ' ' << p.y << '\\n';\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <climits>\n#include <iomanip>\n#include <chrono>\n#include <map>\n#include <set>\n\nusing namespace std;\nusing namespace std::chrono;\n\nstruct Rectangle {\n    int id;\n    int w, h;\n    int x, y;\n    bool rotated;\n};\n\nstruct Placement {\n    int p, r;\n    char d;\n    int b;\n};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint normal_round(double value, int sigma) {\n    normal_distribution<double> dist(value, sigma);\n    double sample = dist(rng);\n    int rounded = static_cast<int>(round(sample));\n    if (rounded < 1) rounded = 1;\n    if (rounded > 1e9) rounded = 1e9;\n    return rounded;\n}\n\nvector<Rectangle> place_rectangles(const vector<pair<int, int>>& observed, const vector<Placement>& placements) {\n    vector<Rectangle> placed;\n    for (const auto& pl : placements) {\n        int id = pl.p;\n        bool rotated = pl.r;\n        int w = observed[id].first;\n        int h = observed[id].second;\n        if (rotated) swap(w, h);\n\n        int x = 0, y = 0;\n        if (pl.d == 'U') {\n            if (pl.b == -1) {\n                x = 0;\n            } else {\n                x = placed[pl.b].x + placed[pl.b].w;\n            }\n            int max_y = 0;\n            for (const auto& rect : placed) {\n                if (rect.x < x + w && rect.x + rect.w > x) {\n                    if (rect.y + rect.h > max_y) {\n                        max_y = rect.y + rect.h;\n                    }\n                }\n            }\n            y = max_y;\n        } else if (pl.d == 'L') {\n            if (pl.b == -1) {\n                y = 0;\n            } else {\n                y = placed[pl.b].y + placed[pl.b].h;\n            }\n            int max_x = 0;\n            for (const auto& rect : placed) {\n                if (rect.y < y + h && rect.y + rect.h > y) {\n                    if (rect.x + rect.w > max_x) {\n                        max_x = rect.x + rect.w;\n                    }\n                }\n            }\n            x = max_x;\n        }\n        placed.push_back({id, w, h, x, y, rotated});\n    }\n    return placed;\n}\n\npair<int, int> calculate_dimensions(const vector<Rectangle>& placed) {\n    int max_x = 0, max_y = 0;\n    for (const auto& rect : placed) {\n        max_x = max(max_x, rect.x + rect.w);\n        max_y = max(max_y, rect.y + rect.h);\n    }\n    return {max_x, max_y};\n}\n\nvector<Placement> generate_placements(const vector<pair<int, int>>& observed, int T, int sigma) {\n    int N = observed.size();\n    vector<Placement> best_placements;\n    int best_score = INT_MAX;\n\n    for (int t = 0; t < T; ++t) {\n        vector<Placement> placements;\n        vector<bool> used(N, false);\n        int current_score = 0;\n        int max_x = 0, max_y = 0;\n\n        for (int i = 0; i < N; ++i) {\n            int best_p = -1, best_r = -1, best_b = -1;\n            char best_d = 'U';\n            int min_increase = INT_MAX;\n\n            for (int p = 0; p < N; ++p) {\n                if (used[p]) continue;\n                for (int r = 0; r < 2; ++r) {\n                    for (char d : {'U', 'L'}) {\n                        int b_start = (d == 'U') ? -1 : -1;\n                        int b_end = (int)placements.size() - 1;\n                        for (int b = b_start; b <= b_end; ++b) {\n                            placements.push_back({p, r, d, b});\n                            auto placed = place_rectangles(observed, placements);\n                            auto [W, H] = calculate_dimensions(placed);\n                            int increase = W + H;\n                            int unused = 0;\n                            for (int j = 0; j < N; ++j) {\n                                if (!used[j]) {\n                                    unused += observed[j].first + observed[j].second;\n                                }\n                            }\n                            int score = increase + unused;\n                            if (score < min_increase) {\n                                min_increase = score;\n                                best_p = p;\n                                best_r = r;\n                                best_d = d;\n                                best_b = b;\n                            }\n                            placements.pop_back();\n                        }\n                    }\n                }\n            }\n\n            if (best_p == -1) break;\n            placements.push_back({best_p, best_r, best_d, best_b});\n            used[best_p] = true;\n        }\n\n        auto placed = place_rectangles(observed, placements);\n        auto [W, H] = calculate_dimensions(placed);\n        int unused = 0;\n        for (int i = 0; i < N; ++i) {\n            bool found = false;\n            for (const auto& rect : placed) {\n                if (rect.id == i) {\n                    found = true;\n                    break;\n                }\n            }\n            if (!found) {\n                unused += observed[i].first + observed[i].second;\n            }\n        }\n        int score = W + H + unused;\n        if (score < best_score) {\n            best_score = score;\n            best_placements = placements;\n        }\n    }\n\n    return best_placements;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n    vector<pair<int, int>> observed(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> observed[i].first >> observed[i].second;\n    }\n\n    for (int t = 0; t < T; ++t) {\n        vector<Placement> placements;\n        vector<bool> used(N, false);\n        int max_x = 0, max_y = 0;\n\n        for (int i = 0; i < N; ++i) {\n            int best_p = -1, best_r = -1, best_b = -1;\n            char best_d = 'U';\n            int min_increase = INT_MAX;\n\n            for (int p = 0; p < N; ++p) {\n                if (used[p]) continue;\n                for (int r = 0; r < 2; ++r) {\n                    for (char d : {'U', 'L'}) {\n                        int b_start = (d == 'U') ? -1 : -1;\n                        int b_end = (int)placements.size() - 1;\n                        for (int b = b_start; b <= b_end; ++b) {\n                            placements.push_back({p, r, d, b});\n                            auto placed = place_rectangles(observed, placements);\n                            auto [W, H] = calculate_dimensions(placed);\n                            int increase = W + H;\n                            if (increase < min_increase) {\n                                min_increase = increase;\n                                best_p = p;\n                                best_r = r;\n                                best_d = d;\n                                best_b = b;\n                            }\n                            placements.pop_back();\n                        }\n                    }\n                }\n            }\n\n            if (best_p == -1) break;\n            placements.push_back({best_p, best_r, best_d, best_b});\n            used[best_p] = true;\n        }\n\n        cout << placements.size() << '\\n';\n        for (const auto& pl : placements) {\n            cout << pl.p << ' ' << pl.r << ' ' << pl.d << ' ' << pl.b << '\\n';\n        }\n        cout.flush();\n\n        int W_prime, H_prime;\n        cin >> W_prime >> H_prime;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <set>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nstruct Vertex {\n    int id;\n    int a;\n    int x, y;\n    vector<int> neighbors;\n};\n\nstruct BFSState {\n    int vertex;\n    int parent;\n    int depth;\n    bool operator<(const BFSState& other) const {\n        if (depth != other.depth) return depth > other.depth;\n        return a[vertex] < a[other.vertex];\n    }\n    static vector<int> a;\n};\n\nvector<int> BFSState::a;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    cin >> N >> M >> H;\n\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> A[i];\n    }\n    BFSState::a = A;\n\n    vector<pair<int, int>> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].first >> edges[i].second;\n    }\n\n    vector<pair<int, int>> coords(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> coords[i].first >> coords[i].second;\n    }\n\n    vector<Vertex> vertices(N);\n    for (int i = 0; i < N; ++i) {\n        vertices[i].id = i;\n        vertices[i].a = A[i];\n        vertices[i].x = coords[i].first;\n        vertices[i].y = coords[i].second;\n    }\n\n    for (const auto& edge : edges) {\n        int u = edge.first;\n        int v = edge.second;\n        vertices[u].neighbors.push_back(v);\n        vertices[v].neighbors.push_back(u);\n    }\n\n    vector<int> parent(N, -1);\n    vector<bool> assigned(N, false);\n\n    while (true) {\n        int root = -1;\n        int max_a = -1;\n        for (int i = 0; i < N; ++i) {\n            if (!assigned[i] && A[i] > max_a) {\n                max_a = A[i];\n                root = i;\n            }\n        }\n        if (root == -1) break;\n\n        priority_queue<BFSState> pq;\n        pq.push({root, -1, 0});\n        vector<bool> visited(N, false);\n        visited[root] = true;\n\n        while (!pq.empty()) {\n            BFSState current = pq.top();\n            pq.pop();\n            if (current.depth > H) continue;\n            if (assigned[current.vertex]) continue;\n\n            parent[current.vertex] = current.parent;\n            assigned[current.vertex] = true;\n\n            for (int neighbor : vertices[current.vertex].neighbors) {\n                if (!visited[neighbor] && !assigned[neighbor]) {\n                    visited[neighbor] = true;\n                    pq.push({neighbor, current.vertex, current.depth + 1});\n                }\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <set>\n#include <map>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_MOVES = 4 * N * N;\n\nstruct Piece {\n    int i, j;\n    char type; // 'x' for Oni, 'o' for Fukunokami\n};\n\nvector<string> board;\nvector<Piece> oni_list;\nvector<Piece> fuku_list;\nvector<vector<bool>> safe_up, safe_down, safe_left, safe_right;\n\nvoid preprocess() {\n    // Initialize safe directions\n    safe_up.assign(N, vector<bool>(N, true));\n    safe_down.assign(N, vector<bool>(N, true));\n    safe_left.assign(N, vector<bool>(N, true));\n    safe_right.assign(N, vector<bool>(N, true));\n\n    // Mark unsafe directions for Oni\n    for (const auto& fuku : fuku_list) {\n        int i = fuku.i, j = fuku.j;\n        // Up: all squares above (i,j) in column j are unsafe for Oni below\n        for (int k = 0; k < i; ++k) {\n            safe_down[k][j] = false;\n        }\n        // Down: all squares below (i,j) in column j are unsafe for Oni above\n        for (int k = i + 1; k < N; ++k) {\n            safe_up[k][j] = false;\n        }\n        // Left: all squares left of (i,j) in row i are unsafe for Oni to the right\n        for (int k = 0; k < j; ++k) {\n            safe_right[i][k] = false;\n        }\n        // Right: all squares right of (i,j) in row i are unsafe for Oni to the left\n        for (int k = j + 1; k < N; ++k) {\n            safe_left[i][k] = false;\n        }\n    }\n}\n\nvector<pair<char, int>> moves;\n\nvoid shift_row_left(int i) {\n    moves.emplace_back('L', i);\n    char first = board[i][0];\n    for (int j = 0; j < N - 1; ++j) {\n        board[i][j] = board[i][j + 1];\n    }\n    board[i][N - 1] = '.';\n}\n\nvoid shift_row_right(int i) {\n    moves.emplace_back('R', i);\n    char last = board[i][N - 1];\n    for (int j = N - 1; j > 0; --j) {\n        board[i][j] = board[i][j - 1];\n    }\n    board[i][0] = '.';\n}\n\nvoid shift_col_up(int j) {\n    moves.emplace_back('U', j);\n    char first = board[0][j];\n    for (int i = 0; i < N - 1; ++i) {\n        board[i][j] = board[i + 1][j];\n    }\n    board[N - 1][j] = '.';\n}\n\nvoid shift_col_down(int j) {\n    moves.emplace_back('D', j);\n    char last = board[N - 1][j];\n    for (int i = N - 1; i > 0; --i) {\n        board[i][j] = board[i - 1][j];\n    }\n    board[0][j] = '.';\n}\n\nvoid remove_oni() {\n    while (true) {\n        // Check if all Oni are removed\n        bool all_removed = true;\n        for (const auto& row : board) {\n            if (row.find('x') != string::npos) {\n                all_removed = false;\n                break;\n            }\n        }\n        if (all_removed) break;\n\n        // Find the row or column with the most removable Oni\n        int max_oni = 0;\n        char best_dir = ' ';\n        int best_idx = -1;\n\n        // Check rows for left/right shifts\n        for (int i = 0; i < N; ++i) {\n            int left_oni = 0, right_oni = 0;\n            for (int j = 0; j < N; ++j) {\n                if (board[i][j] == 'x') {\n                    if (safe_left[i][j]) left_oni++;\n                    if (safe_right[i][j]) right_oni++;\n                }\n            }\n            if (left_oni > max_oni) {\n                max_oni = left_oni;\n                best_dir = 'L';\n                best_idx = i;\n            }\n            if (right_oni > max_oni) {\n                max_oni = right_oni;\n                best_dir = 'R';\n                best_idx = i;\n            }\n        }\n\n        // Check columns for up/down shifts\n        for (int j = 0; j < N; ++j) {\n            int up_oni = 0, down_oni = 0;\n            for (int i = 0; i < N; ++i) {\n                if (board[i][j] == 'x') {\n                    if (safe_up[i][j]) up_oni++;\n                    if (safe_down[i][j]) down_oni++;\n                }\n            }\n            if (up_oni > max_oni) {\n                max_oni = up_oni;\n                best_dir = 'U';\n                best_idx = j;\n            }\n            if (down_oni > max_oni) {\n                max_oni = down_oni;\n                best_dir = 'D';\n                best_idx = j;\n            }\n        }\n\n        if (max_oni == 0) {\n            // No removable Oni found (should not happen due to problem guarantee)\n            break;\n        }\n\n        // Perform the best shift\n        if (best_dir == 'L') shift_row_left(best_idx);\n        else if (best_dir == 'R') shift_row_right(best_idx);\n        else if (best_dir == 'U') shift_col_up(best_idx);\n        else if (best_dir == 'D') shift_col_down(best_idx);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    board.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n    }\n\n    // Collect Oni and Fukunokami positions\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                oni_list.push_back({i, j, 'x'});\n            } else if (board[i][j] == 'o') {\n                fuku_list.push_back({i, j, 'o'});\n            }\n        }\n    }\n\n    preprocess();\n    remove_oni();\n\n    // Output the moves\n    for (const auto& move : moves) {\n        cout << move.first << \" \" << move.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <climits>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 100;\nconst int L = 500000;\n\nstruct Employee {\n    int a, b;\n};\n\nvector<int> simulate(const vector<Employee>& employees, const vector<int>& T) {\n    vector<int> t(N, 0);\n    int current = 0;\n    t[current]++;\n    for (int week = 1; week < L; ++week) {\n        int cnt = t[current];\n        if (cnt % 2 == 1) {\n            current = employees[current].a;\n        } else {\n            current = employees[current].b;\n        }\n        t[current]++;\n    }\n    return t;\n}\n\nlong long calculate_error(const vector<int>& t, const vector<int>& T) {\n    long long error = 0;\n    for (int i = 0; i < N; ++i) {\n        error += abs(t[i] - T[i]);\n    }\n    return error;\n}\n\nvector<Employee> greedy_initial(const vector<int>& T) {\n    vector<Employee> employees(N);\n    vector<int> current_t(N, 0);\n    current_t[0] = 1;\n    int current = 0;\n    for (int week = 1; week < L; ++week) {\n        int cnt = current_t[current];\n        vector<pair<int, int>> candidates;\n        for (int i = 0; i < N; ++i) {\n            candidates.emplace_back(T[i] - current_t[i], i);\n        }\n        sort(candidates.rbegin(), candidates.rend());\n        int next = candidates[0].second;\n        if (cnt % 2 == 1) {\n            employees[current].a = next;\n        } else {\n            employees[current].b = next;\n        }\n        current = next;\n        current_t[current]++;\n    }\n    return employees;\n}\n\nvector<Employee> local_search(const vector<int>& T, vector<Employee> employees, int max_iter = 1000) {\n    auto t = simulate(employees, T);\n    long long best_error = calculate_error(t, T);\n    vector<Employee> best_employees = employees;\n\n    for (int iter = 0; iter < max_iter; ++iter) {\n        bool improved = false;\n        for (int i = 0; i < N; ++i) {\n            for (int new_a = 0; new_a < N; ++new_a) {\n                if (new_a == employees[i].a) continue;\n                auto old_a = employees[i].a;\n                employees[i].a = new_a;\n                auto new_t = simulate(employees, T);\n                long long new_error = calculate_error(new_t, T);\n                if (new_error < best_error) {\n                    best_error = new_error;\n                    best_employees = employees;\n                    improved = true;\n                } else {\n                    employees[i].a = old_a;\n                }\n            }\n            for (int new_b = 0; new_b < N; ++new_b) {\n                if (new_b == employees[i].b) continue;\n                auto old_b = employees[i].b;\n                employees[i].b = new_b;\n                auto new_t = simulate(employees, T);\n                long long new_error = calculate_error(new_t, T);\n                if (new_error < best_error) {\n                    best_error = new_error;\n                    best_employees = employees;\n                    improved = true;\n                } else {\n                    employees[i].b = old_b;\n                }\n            }\n        }\n        if (!improved) break;\n        employees = best_employees;\n    }\n    return best_employees;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, L_in;\n    cin >> N_in >> L_in;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    auto employees = greedy_initial(T);\n    employees = local_search(T, employees);\n\n    for (const auto& emp : employees) {\n        cout << emp.a << \" \" << emp.b << \"\\n\";\n    }\n\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct City {\n    int lx, rx, ly, ry;\n    int x, y; // Estimated or true coordinates\n};\n\nint N, M, Q, L, W;\nvector<int> G;\nvector<City> cities;\nvector<vector<int>> groups;\nvector<vector<pair<int, int>>> edges;\n\nvector<pair<int, int>> query(const vector<int>& C) {\n    cout << \"? \" << C.size();\n    for (int c : C) cout << \" \" << c;\n    cout << endl;\n    cout.flush();\n\n    vector<pair<int, int>> res;\n    for (int i = 0; i < (int)C.size() - 1; ++i) {\n        int a, b;\n        cin >> a >> b;\n        res.emplace_back(a, b);\n    }\n    return res;\n}\n\nvoid answer() {\n    cout << \"!\" << endl;\n    for (int k = 0; k < M; ++k) {\n        for (int c : groups[k]) cout << c << \" \";\n        cout << endl;\n        for (auto [a, b] : edges[k]) {\n            cout << a << \" \" << b << endl;\n        }\n    }\n    cout.flush();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M >> Q >> L >> W;\n    G.resize(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    cities.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].x = (cities[i].lx + cities[i].rx) / 2;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2;\n    }\n\n    // Initial grouping based on estimated coordinates\n    vector<int> city_indices(N);\n    iota(city_indices.begin(), city_indices.end(), 0);\n    sort(city_indices.begin(), city_indices.end(), [&](int a, int b) {\n        if (cities[a].x != cities[b].x) return cities[a].x < cities[b].x;\n        return cities[a].y < cities[b].y;\n    });\n\n    groups.resize(M);\n    int start = 0;\n    for (int k = 0; k < M; ++k) {\n        for (int i = 0; i < G[k]; ++i) {\n            groups[k].push_back(city_indices[start + i]);\n        }\n        start += G[k];\n    }\n\n    // Perform queries to get MST edges\n    edges.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int n = groups[k].size();\n        for (int i = 0; i < n - 1; i += 2) {\n            if (i + 2 < n) {\n                vector<int> subset = {groups[k][i], groups[k][i+1], groups[k][i+2]};\n                auto res = query(subset);\n                for (auto [a, b] : res) {\n                    edges[k].emplace_back(a, b);\n                }\n            } else {\n                edges[k].emplace_back(groups[k][i], groups[k][i+1]);\n            }\n        }\n    }\n\n    answer();\n\n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int M = 40;\nconst int MAX_ACTIONS = 2 * N * M;\nconst int BEAM_WIDTH = 1000;\n\nstruct State {\n    int i, j;\n    vector<pair<int, int>> blocks;\n    int next_target;\n    vector<pair<char, char>> actions;\n    int score;\n\n    State(int i, int j, vector<pair<int, int>> blocks, int next_target, vector<pair<char, char>> actions)\n        : i(i), j(j), blocks(blocks), next_target(next_target), actions(actions), score(0) {}\n\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n};\n\nvector<pair<int, int>> targets;\n\nint manhattan(int i1, int j1, int i2, int j2) {\n    return abs(i1 - i2) + abs(j1 - j2);\n}\n\nbool is_blocked(int i, int j, const vector<pair<int, int>>& blocks) {\n    if (i < 0 || i >= N || j < 0 || j >= N) return true;\n    for (auto [bi, bj] : blocks) {\n        if (bi == i && bj == j) return true;\n    }\n    return false;\n}\n\nvector<State> expand(const State& state) {\n    vector<State> next_states;\n    vector<char> actions = {'M', 'S', 'A'};\n    vector<char> directions = {'U', 'D', 'L', 'R'};\n\n    for (char a : actions) {\n        for (char d : directions) {\n            State new_state = state;\n            new_state.actions.emplace_back(a, d);\n            int di = 0, dj = 0;\n            if (d == 'U') di = -1;\n            if (d == 'D') di = 1;\n            if (d == 'L') dj = -1;\n            if (d == 'R') dj = 1;\n\n            if (a == 'M') {\n                int ni = state.i + di, nj = state.j + dj;\n                if (!is_blocked(ni, nj, state.blocks)) {\n                    new_state.i = ni;\n                    new_state.j = nj;\n                } else {\n                    continue;\n                }\n            } else if (a == 'S') {\n                int ni = state.i, nj = state.j;\n                while (true) {\n                    int nni = ni + di, nnj = nj + dj;\n                    if (is_blocked(nni, nnj, state.blocks)) break;\n                    ni = nni;\n                    nj = nnj;\n                }\n                new_state.i = ni;\n                new_state.j = nj;\n            } else if (a == 'A') {\n                int ni = state.i + di, nj = state.j + dj;\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                bool found = false;\n                for (auto& block : new_state.blocks) {\n                    if (block.first == ni && block.second == nj) {\n                        block = new_state.blocks.back();\n                        new_state.blocks.pop_back();\n                        found = true;\n                        break;\n                    }\n                }\n                if (!found) {\n                    new_state.blocks.emplace_back(ni, nj);\n                }\n            }\n\n            // Check if next target is reached\n            if (new_state.next_target < M &&\n                new_state.i == targets[new_state.next_target].first &&\n                new_state.j == targets[new_state.next_target].second) {\n                new_state.next_target++;\n            }\n\n            // Evaluate score\n            int dist = manhattan(new_state.i, new_state.j, targets[new_state.next_target].first, targets[new_state.next_target].second);\n            new_state.score = -new_state.actions.size() - dist;\n            next_states.push_back(new_state);\n        }\n    }\n    return next_states;\n}\n\nvector<pair<char, char>> beam_search(int start_i, int start_j) {\n    vector<pair<int, int>> initial_blocks;\n    State initial_state(start_i, start_j, initial_blocks, 0, {});\n    priority_queue<State> beam;\n    beam.push(initial_state);\n\n    for (int step = 0; step < MAX_ACTIONS; ++step) {\n        priority_queue<State> next_beam;\n        for (int i = 0; i < BEAM_WIDTH && !beam.empty(); ++i) {\n            State current = beam.top();\n            beam.pop();\n            if (current.next_target == M) {\n                return current.actions;\n            }\n            vector<State> next_states = expand(current);\n            for (State& next_state : next_states) {\n                next_beam.push(next_state);\n            }\n        }\n        beam = move(next_beam);\n    }\n\n    // Return the best found\n    State best = beam.top();\n    return best.actions;\n}\n\nint main() {\n    int N_in, M_in;\n    cin >> N_in >> M_in;\n    targets.resize(M_in);\n    for (int i = 0; i < M_in; ++i) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n\n    vector<pair<char, char>> actions = beam_search(targets[0].first, targets[0].second);\n    for (auto [a, d] : actions) {\n        cout << a << \" \" << d << \"\\n\";\n    }\n    return 0;\n}"},"2":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Rect {\n    int a, b, c, d;\n    int area() const { return (c - a) * (d - b); }\n    bool contains(int x, int y) const {\n        return a <= x && x < c && b <= y && y < d;\n    }\n    bool overlaps(const Rect& other) const {\n        return !(c <= other.a || other.c <= a || d <= other.b || other.d <= b);\n    }\n};\n\nstruct Company {\n    int x, y, r;\n    Rect rect;\n    double satisfaction() const {\n        int s = rect.area();\n        if (s == 0) return 0.0;\n        double ratio = min(r, s) * 1.0 / max(r, s);\n        return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n    }\n};\n\nint n;\nvector<Company> companies;\nvector<Rect> placed_rects;\n\nbool is_valid(const Rect& rect, int ignore = -1) {\n    for (int i = 0; i < placed_rects.size(); ++i) {\n        if (i == ignore) continue;\n        if (rect.overlaps(placed_rects[i])) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid place_rect(const Rect& rect) {\n    placed_rects.push_back(rect);\n}\n\nvoid remove_rect(int id) {\n    placed_rects.erase(placed_rects.begin() + id);\n}\n\ndouble total_satisfaction() {\n    double total = 0.0;\n    for (const auto& company : companies) {\n        total += company.satisfaction();\n    }\n    return total;\n}\n\nvoid greedy_initialization() {\n    for (auto& company : companies) {\n        int x = company.x;\n        int y = company.y;\n        // Start with a 1x1 rectangle\n        company.rect = {x, y, x + 1, y + 1};\n        place_rect(company.rect);\n    }\n}\n\nvoid local_search() {\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (auto& company : companies) {\n            int id = &company - &companies[0];\n            Rect original = company.rect;\n            double original_sat = company.satisfaction();\n            vector<Rect> candidates;\n\n            // Try expanding in all four directions\n            // Expand right\n            if (company.rect.c < 10000) {\n                Rect new_rect = company.rect;\n                new_rect.c++;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand left\n            if (company.rect.a > 0) {\n                Rect new_rect = company.rect;\n                new_rect.a--;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand up\n            if (company.rect.d < 10000) {\n                Rect new_rect = company.rect;\n                new_rect.d++;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand down\n            if (company.rect.b > 0) {\n                Rect new_rect = company.rect;\n                new_rect.b--;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n\n            // Try to find the best candidate\n            double best_sat = original_sat;\n            Rect best_rect = original;\n            for (const auto& rect : candidates) {\n                company.rect = rect;\n                double sat = company.satisfaction();\n                if (sat > best_sat) {\n                    best_sat = sat;\n                    best_rect = rect;\n                }\n            }\n            if (best_sat > original_sat) {\n                remove_rect(id);\n                company.rect = best_rect;\n                place_rect(best_rect);\n                improved = true;\n            } else {\n                company.rect = original;\n            }\n        }\n    }\n}\n\nvoid simulated_annealing() {\n    double temperature = 1000.0;\n    double cooling_rate = 0.999;\n    double min_temperature = 0.1;\n    double current_sat = total_satisfaction();\n\n    while (temperature > min_temperature) {\n        for (auto& company : companies) {\n            int id = &company - &companies[0];\n            Rect original = company.rect;\n            double original_sat = company.satisfaction();\n\n            // Randomly choose a direction to expand or shrink\n            int dir = rand() % 4;\n            Rect new_rect = original;\n            switch (dir) {\n                case 0: // right\n                    if (new_rect.c < 10000) new_rect.c++;\n                    break;\n                case 1: // left\n                    if (new_rect.a > 0) new_rect.a--;\n                    break;\n                case 2: // up\n                    if (new_rect.d < 10000) new_rect.d++;\n                    break;\n                case 3: // down\n                    if (new_rect.b > 0) new_rect.b--;\n                    break;\n            }\n\n            if (!is_valid(new_rect, id)) continue;\n\n            company.rect = new_rect;\n            double new_sat = company.satisfaction();\n            double delta = new_sat - original_sat;\n\n            if (delta > 0 || (rand() / (double)RAND_MAX) < exp(delta / temperature)) {\n                remove_rect(id);\n                place_rect(new_rect);\n                current_sat += delta;\n            } else {\n                company.rect = original;\n            }\n        }\n        temperature *= cooling_rate;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> n;\n    companies.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n\n    greedy_initialization();\n    local_search();\n    simulated_annealing();\n\n    for (const auto& company : companies) {\n        cout << company.rect.a << \" \" << company.rect.b << \" \"\n             << company.rect.c << \" \" << company.rect.d << \"\\n\";\n    }\n\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct Tile {\n    vector<pair<int, int>> cells;\n    int sum = 0;\n    int id;\n};\n\nstruct State {\n    int score;\n    int last_tile;\n    int last_x, last_y;\n    vector<bool> visited_tiles;\n    string path;\n\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> t(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> t[i][j];\n        }\n    }\n\n    vector<vector<int>> p(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> p[i][j];\n        }\n    }\n\n    // Step 1: Identify tiles using DSU\n    dsu d(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && t[i][j] == t[ni][nj]) {\n                    d.merge(i * N + j, ni * N + nj);\n                }\n            }\n        }\n    }\n\n    // Step 2: Build tiles\n    map<int, Tile> tiles;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int root = d.leader(i * N + j);\n            tiles[root].cells.emplace_back(i, j);\n            tiles[root].sum += p[i][j];\n            tiles[root].id = root;\n        }\n    }\n\n    // Step 3: Build adjacency list for tiles\n    map<int, vector<int>> adj;\n    for (auto& [root, tile] : tiles) {\n        set<int> neighbors;\n        for (auto [i, j] : tile.cells) {\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                    int nroot = d.leader(ni * N + nj);\n                    if (nroot != root) {\n                        neighbors.insert(nroot);\n                    }\n                }\n            }\n        }\n        for (int nroot : neighbors) {\n            adj[root].push_back(nroot);\n        }\n    }\n\n    // Step 4: Beam search\n    const int BEAM_WIDTH = 1000;\n    priority_queue<State> beam;\n    State initial;\n    int start_root = d.leader(si * N + sj);\n    initial.score = p[si][sj];\n    initial.last_tile = start_root;\n    initial.last_x = si;\n    initial.last_y = sj;\n    initial.visited_tiles.resize(tiles.size(), false);\n    initial.visited_tiles[start_root] = true;\n    initial.path = \"\";\n    beam.push(initial);\n\n    string best_path;\n    int best_score = 0;\n\n    while (!beam.empty()) {\n        priority_queue<State> next_beam;\n        for (int i = 0; i < BEAM_WIDTH && !beam.empty(); ++i) {\n            State current = beam.top();\n            beam.pop();\n\n            if (current.score > best_score) {\n                best_score = current.score;\n                best_path = current.path;\n            }\n\n            for (int next_root : adj[current.last_tile]) {\n                if (current.visited_tiles[next_root]) continue;\n\n                State next = current;\n                next.last_tile = next_root;\n                next.visited_tiles[next_root] = true;\n                next.score += tiles[next_root].sum;\n\n                // Find a path within the next tile to traverse all its cells\n                auto& cells = tiles[next_root].cells;\n                vector<vector<bool>> visited(N, vector<bool>(N, false));\n                vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n                queue<pair<int, int>> q;\n                q.push({current.last_x, current.last_y});\n                visited[current.last_x][current.last_y] = true;\n                bool found = false;\n                pair<int, int> end_pos;\n\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    if (t[x][y] == next_root && (x != current.last_x || y != current.last_y)) {\n                        end_pos = {x, y};\n                        found = true;\n                        break;\n                    }\n                    for (int k = 0; k < 4; ++k) {\n                        int nx = x + dx[k];\n                        int ny = y + dy[k];\n                        if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && t[nx][ny] == next_root) {\n                            visited[nx][ny] = true;\n                            parent[nx][ny] = {x, y};\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n\n                if (!found) continue;\n\n                // Reconstruct path within the tile\n                string tile_path;\n                pair<int, int> pos = end_pos;\n                while (pos != make_pair(current.last_x, current.last_y)) {\n                    auto [px, py] = parent[pos.first][pos.second];\n                    for (int k = 0; k < 4; ++k) {\n                        if (px == pos.first + dx[k] && py == pos.second + dy[k]) {\n                            tile_path += dir[k];\n                            break;\n                        }\n                    }\n                    pos = {px, py};\n                }\n                reverse(tile_path.begin(), tile_path.end());\n                next.path += tile_path;\n                next.last_x = end_pos.first;\n                next.last_y = end_pos.second;\n\n                next_beam.push(next);\n            }\n        }\n        beam = move(next_beam);\n    }\n\n    cout << best_path << endl;\n\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 30;\nconst int INF = 1e9;\nconst double ALPHA = 0.1; // Learning rate\n\nstruct Edge {\n    int to_i, to_j;\n    int dir; // 0: right (R), 1: down (D), 2: left (L), 3: up (U)\n    double weight;\n};\n\nvector<vector<vector<Edge>>> adj(N, vector<vector<Edge>>(N));\nvector<vector<double>> h(N, vector<double>(N-1, 5000.0)); // horizontal edges\nvector<vector<double>> v(N-1, vector<double>(N, 5000.0)); // vertical edges\n\nvoid init_adj() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (j + 1 < N) {\n                adj[i][j].push_back({i, j+1, 0, h[i][j]});\n            }\n            if (i + 1 < N) {\n                adj[i][j].push_back({i+1, j, 1, v[i][j]});\n            }\n            if (j - 1 >= 0) {\n                adj[i][j].push_back({i, j-1, 2, h[i][j-1]});\n            }\n            if (i - 1 >= 0) {\n                adj[i][j].push_back({i-1, j, 3, v[i-1][j]});\n            }\n        }\n    }\n}\n\nstring dijkstra(int si, int sj, int ti, int tj) {\n    vector<vector<double>> dist(N, vector<double>(N, INF));\n    vector<vector<pair<int, int>>> prev(N, vector<pair<int, int>>(N, {-1, -1}));\n    priority_queue<tuple<double, int, int>, vector<tuple<double, int, int>>, greater<>> pq;\n\n    dist[si][sj] = 0.0;\n    pq.emplace(0.0, si, sj);\n\n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top();\n        pq.pop();\n        if (i == ti && j == tj) break;\n        if (d > dist[i][j]) continue;\n        for (const auto& edge : adj[i][j]) {\n            int ni = edge.to_i;\n            int nj = edge.to_j;\n            double nd = d + edge.weight;\n            if (nd < dist[ni][nj]) {\n                dist[ni][nj] = nd;\n                prev[ni][nj] = {i, j};\n                pq.emplace(nd, ni, nj);\n            }\n        }\n    }\n\n    string path;\n    int ci = ti, cj = tj;\n    while (ci != si || cj != sj) {\n        auto [pi, pj] = prev[ci][cj];\n        if (pi == ci && pj == cj - 1) path += 'R';\n        else if (pi == ci && pj == cj + 1) path += 'L';\n        else if (pi == ci - 1 && pj == cj) path += 'D';\n        else if (pi == ci + 1 && pj == cj) path += 'U';\n        ci = pi;\n        cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nvoid update_weights(const string& path, int si, int sj, double total_length) {\n    int ci = si, cj = sj;\n    double path_length = 0.0;\n    for (char dir : path) {\n        int ni = ci, nj = cj;\n        if (dir == 'R') nj++;\n        else if (dir == 'L') nj--;\n        else if (dir == 'D') ni++;\n        else if (dir == 'U') ni--;\n\n        double edge_weight;\n        if (dir == 'R') edge_weight = h[ci][cj];\n        else if (dir == 'L') edge_weight = h[ci][cj-1];\n        else if (dir == 'D') edge_weight = v[ci][cj];\n        else if (dir == 'U') edge_weight = v[ci-1][cj];\n\n        path_length += edge_weight;\n        ci = ni;\n        cj = nj;\n    }\n\n    ci = si;\n    cj = sj;\n    for (char dir : path) {\n        int ni = ci, nj = cj;\n        if (dir == 'R') {\n            double new_weight = total_length * (h[ci][cj] / path_length);\n            h[ci][cj] = (1 - ALPHA) * h[ci][cj] + ALPHA * new_weight;\n            nj++;\n        } else if (dir == 'L') {\n            double new_weight = total_length * (h[ci][cj-1] / path_length);\n            h[ci][cj-1] = (1 - ALPHA) * h[ci][cj-1] + ALPHA * new_weight;\n            nj--;\n        } else if (dir == 'D') {\n            double new_weight = total_length * (v[ci][cj] / path_length);\n            v[ci][cj] = (1 - ALPHA) * v[ci][cj] + ALPHA * new_weight;\n            ni++;\n        } else if (dir == 'U') {\n            double new_weight = total_length * (v[ci-1][cj] / path_length);\n            v[ci-1][cj] = (1 - ALPHA) * v[ci-1][cj] + ALPHA * new_weight;\n            ni--;\n        }\n        ci = ni;\n        cj = nj;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    init_adj();\n\n    for (int k = 0; k < 1000; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n\n        string path = dijkstra(si, sj, ti, tj);\n        cout << path << endl;\n        cout.flush();\n\n        int total_length;\n        cin >> total_length;\n\n        update_weights(path, si, sj, total_length);\n    }\n\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int MAX_LEN = 12;\nconst vector<char> CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', '.'};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct State {\n    vector<string> grid;\n    int c; // number of matched strings\n    int d; // number of '.'\n    double energy;\n};\n\nvector<string> strings;\nint M;\n\nint count_matched(const vector<string>& grid) {\n    int matched = 0;\n    for (const string& s : strings) {\n        int k = s.size();\n        bool found = false;\n        // Check rows\n        for (int i = 0; i < N && !found; ++i) {\n            for (int j = 0; j < N && !found; ++j) {\n                bool match = true;\n                for (int p = 0; p < k; ++p) {\n                    if (grid[i][(j + p) % N] != s[p]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) {\n                    found = true;\n                    break;\n                }\n            }\n        }\n        // Check columns\n        for (int j = 0; j < N && !found; ++j) {\n            for (int i = 0; i < N && !found; ++i) {\n                bool match = true;\n                for (int p = 0; p < k; ++p) {\n                    if (grid[(i + p) % N][j] != s[p]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) {\n                    found = true;\n                    break;\n                }\n            }\n        }\n        if (found) {\n            matched++;\n        }\n    }\n    return matched;\n}\n\nint count_dots(const vector<string>& grid) {\n    int dots = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == '.') {\n                dots++;\n            }\n        }\n    }\n    return dots;\n}\n\ndouble compute_energy(int c, int d) {\n    if (c < M) {\n        return -1e8 * c / M;\n    } else {\n        return -1e8 * (2 * N * N) / (2 * N * N - d);\n    }\n}\n\nState get_initial_state() {\n    State state;\n    state.grid.resize(N, string(N, '.'));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            state.grid[i][j] = CHARS[rng() % (CHARS.size() - 1)];\n        }\n    }\n    state.d = count_dots(state.grid);\n    state.c = count_matched(state.grid);\n    state.energy = compute_energy(state.c, state.d);\n    return state;\n}\n\nState simulated_annealing(State initial_state, double initial_temp, double final_temp, double cooling_rate, int iterations) {\n    State current = initial_state;\n    State best = current;\n    double temp = initial_temp;\n\n    for (int iter = 0; iter < iterations; ++iter) {\n        // Generate neighbor\n        int i = rng() % N;\n        int j = rng() % N;\n        char old_char = current.grid[i][j];\n        char new_char;\n        do {\n            new_char = CHARS[rng() % CHARS.size()];\n        } while (new_char == old_char);\n\n        // Compute new state\n        vector<string> new_grid = current.grid;\n        new_grid[i][j] = new_char;\n        int new_c = count_matched(new_grid);\n        int new_d = count_dots(new_grid);\n        double new_energy = compute_energy(new_c, new_d);\n\n        // Decide whether to accept\n        double delta_energy = new_energy - current.energy;\n        if (delta_energy < 0 || exp(-delta_energy / temp) > (double)rng() / rng.max()) {\n            current.grid = new_grid;\n            current.c = new_c;\n            current.d = new_d;\n            current.energy = new_energy;\n            if (current.energy < best.energy) {\n                best = current;\n            }\n        }\n\n        // Cool down\n        temp *= cooling_rate;\n        if (temp < final_temp) {\n            break;\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> M;\n    strings.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i];\n    }\n\n    // Parameters for simulated annealing\n    double initial_temp = 1e4;\n    double final_temp = 1e-3;\n    double cooling_rate = 0.999;\n    int iterations = 1e6;\n\n    State initial_state = get_initial_state();\n    State best_state = simulated_annealing(initial_state, initial_temp, final_temp, cooling_rate, iterations);\n\n    for (const string& row : best_state.grid) {\n        cout << row << '\\n';\n    }\n\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int INF = 1e9;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nint N, si, sj;\nvector<string> grid;\nvector<vector<int>> cost;\nvector<vector<bool>> is_road;\nvector<vector<vector<Point>>> visible;\nvector<vector<int>> dist;\nvector<vector<Point>> parent;\nvector<Point> road_points;\n\nvoid precompute_visible() {\n    visible.assign(N, vector<vector<Point>>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!is_road[i][j]) continue;\n            // Check left\n            for (int k = j - 1; k >= 0; --k) {\n                if (!is_road[i][k]) break;\n                visible[i][j].emplace_back(i, k);\n            }\n            // Check right\n            for (int k = j + 1; k < N; ++k) {\n                if (!is_road[i][k]) break;\n                visible[i][j].emplace_back(i, k);\n            }\n            // Check up\n            for (int k = i - 1; k >= 0; --k) {\n                if (!is_road[k][j]) break;\n                visible[i][j].emplace_back(k, j);\n            }\n            // Check down\n            for (int k = i + 1; k < N; ++k) {\n                if (!is_road[k][j]) break;\n                visible[i][j].emplace_back(k, j);\n            }\n        }\n    }\n}\n\nvoid bfs(Point start) {\n    dist.assign(N, vector<int>(N, INF));\n    parent.assign(N, vector<Point>(N, Point(-1, -1)));\n    queue<Point> q;\n    dist[start.x][start.y] = 0;\n    q.push(start);\n    while (!q.empty()) {\n        Point p = q.front();\n        q.pop();\n        for (int d = 0; d < 4; ++d) {\n            int nx = p.x + dx[d];\n            int ny = p.y + dy[d];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            if (!is_road[nx][ny]) continue;\n            if (dist[nx][ny] > dist[p.x][p.y] + cost[nx][ny]) {\n                dist[nx][ny] = dist[p.x][p.y] + cost[nx][ny];\n                parent[nx][ny] = p;\n                q.push(Point(nx, ny));\n            }\n        }\n    }\n}\n\nstring reconstruct_path(Point start, Point end) {\n    string path;\n    Point p = end;\n    while (!(p == start)) {\n        Point par = parent[p.x][p.y];\n        for (int d = 0; d < 4; ++d) {\n            if (par.x + dx[d] == p.x && par.y + dy[d] == p.y) {\n                path += dir[d];\n                break;\n            }\n        }\n        p = par;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nstring solve() {\n    // Precompute road points\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (is_road[i][j]) {\n                road_points.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Precompute visible squares for each road point\n    precompute_visible();\n\n    // Greedy approach: start from (si, sj) and cover all road points\n    vector<bool> covered(N, vector<bool>(N, false));\n    vector<Point> route;\n    route.emplace_back(si, sj);\n    covered[si][sj] = true;\n\n    // Mark all points visible from (si, sj) as covered\n    for (const auto& p : visible[si][sj]) {\n        covered[p.x][p.y] = true;\n    }\n\n    // While there are uncovered points\n    while (true) {\n        bool all_covered = true;\n        for (const auto& p : road_points) {\n            if (!covered[p.x][p.y]) {\n                all_covered = false;\n                break;\n            }\n        }\n        if (all_covered) break;\n\n        // Find the nearest uncovered point\n        int min_dist = INF;\n        Point next_point;\n        string best_path;\n        for (const auto& p : road_points) {\n            if (covered[p.x][p.y]) continue;\n            bfs(route.back());\n            if (dist[p.x][p.y] < min_dist) {\n                min_dist = dist[p.x][p.y];\n                next_point = p;\n                best_path = reconstruct_path(route.back(), p);\n            }\n        }\n\n        // Move to the next point\n        route.push_back(next_point);\n        for (char c : best_path) {\n            if (c == 'U') route.emplace_back(route.back().x - 1, route.back().y);\n            else if (c == 'D') route.emplace_back(route.back().x + 1, route.back().y);\n            else if (c == 'L') route.emplace_back(route.back().x, route.back().y - 1);\n            else if (c == 'R') route.emplace_back(route.back().x, route.back().y + 1);\n        }\n\n        // Mark all points visible from the new point as covered\n        for (const auto& p : visible[next_point.x][next_point.y]) {\n            covered[p.x][p.y] = true;\n        }\n    }\n\n    // Return to start\n    bfs(route.back());\n    string return_path = reconstruct_path(route.back(), Point(si, sj));\n    for (char c : return_path) {\n        if (c == 'U') route.emplace_back(route.back().x - 1, route.back().y);\n        else if (c == 'D') route.emplace_back(route.back().x + 1, route.back().y);\n        else if (c == 'L') route.emplace_back(route.back().x, route.back().y - 1);\n        else if (c == 'R') route.emplace_back(route.back().x, route.back().y + 1);\n    }\n\n    // Reconstruct the path string\n    string result;\n    for (int i = 1; i < route.size(); ++i) {\n        Point prev = route[i-1];\n        Point curr = route[i];\n        if (prev.x == curr.x && prev.y == curr.y - 1) result += 'R';\n        else if (prev.x == curr.x && prev.y == curr.y + 1) result += 'L';\n        else if (prev.x == curr.x - 1 && prev.y == curr.y) result += 'D';\n        else if (prev.x == curr.x + 1 && prev.y == curr.y) result += 'U';\n    }\n\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> si >> sj;\n    grid.resize(N);\n    cost.assign(N, vector<int>(N));\n    is_road.assign(N, vector<bool>(N, false));\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                is_road[i][j] = true;\n                cost[i][j] = grid[i][j] - '0';\n            }\n        }\n    }\n\n    string ans = solve();\n    cout << ans << endl;\n\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <map>\n#include <set>\n#include <climits>\n#include <cassert>\n\nusing namespace std;\n\nstruct Task {\n    int id;\n    vector<int> difficulty;\n    vector<int> dependencies;\n    vector<int> dependents;\n    int in_degree = 0;\n    bool completed = false;\n    int assigned_member = -1;\n    int start_day = -1;\n    int completion_day = -1;\n};\n\nstruct Member {\n    int id;\n    vector<int> skills;\n    int current_task = -1;\n    int task_end_day = -1;\n    vector<pair<int, int>> task_history; // task_id, completion_time\n};\n\nclass Scheduler {\nprivate:\n    int N, M, K, R;\n    vector<Task> tasks;\n    vector<Member> members;\n    vector<vector<int>> adj;\n    vector<int> in_degree;\n    vector<int> topo_order;\n    vector<vector<int>> task_dependencies;\n    vector<vector<int>> task_dependents;\n    vector<vector<int>> skill_estimates;\n    vector<int> available_members;\n    int current_day = 0;\n    mt19937 rng;\n\n    void topological_sort() {\n        queue<int> q;\n        for (int i = 0; i < N; ++i) {\n            if (in_degree[i] == 0) {\n                q.push(i);\n            }\n        }\n        while (!q.empty()) {\n            int u = q.front();\n            q.pop();\n            topo_order.push_back(u);\n            for (int v : adj[u]) {\n                if (--in_degree[v] == 0) {\n                    q.push(v);\n                }\n            }\n        }\n    }\n\n    void update_skill_estimates(int member_id, int task_id, int completion_time) {\n        Member& member = members[member_id];\n        Task& task = tasks[task_id];\n        member.task_history.emplace_back(task_id, completion_time);\n\n        for (int k = 0; k < K; ++k) {\n            int diff = task.difficulty[k];\n            int& skill = skill_estimates[member_id][k];\n            if (completion_time == 1) {\n                skill = max(skill, diff);\n            } else {\n                skill = min(skill, diff - 1);\n            }\n        }\n    }\n\n    int estimate_completion_time(int member_id, int task_id) {\n        const Task& task = tasks[task_id];\n        int w = 0;\n        for (int k = 0; k < K; ++k) {\n            w += max(0, task.difficulty[k] - skill_estimates[member_id][k]);\n        }\n        if (w == 0) {\n            return 1;\n        } else {\n            return max(1, w + 0); // Assuming r_i = 0 for estimation\n        }\n    }\n\n    bool is_task_ready(int task_id) {\n        for (int dep : tasks[task_id].dependencies) {\n            if (!tasks[dep].completed) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    void assign_tasks() {\n        vector<pair<int, int>> assignments;\n        for (int member_id : available_members) {\n            if (members[member_id].current_task != -1) continue;\n\n            int best_task = -1;\n            int best_time = INT_MAX;\n            for (int task_id : topo_order) {\n                Task& task = tasks[task_id];\n                if (task.completed || task.assigned_member != -1) continue;\n                if (!is_task_ready(task_id)) continue;\n\n                int est_time = estimate_completion_time(member_id, task_id);\n                if (est_time < best_time) {\n                    best_time = est_time;\n                    best_task = task_id;\n                }\n            }\n\n            if (best_task != -1) {\n                Task& task = tasks[best_task];\n                task.assigned_member = member_id;\n                task.start_day = current_day;\n                members[member_id].current_task = best_task;\n                members[member_id].task_end_day = current_day + best_time - 1;\n                assignments.emplace_back(member_id, best_task);\n            }\n        }\n\n        cout << assignments.size();\n        for (auto [member_id, task_id] : assignments) {\n            cout << \" \" << member_id + 1 << \" \" << task_id + 1;\n        }\n        cout << endl;\n    }\n\n    void process_completions(const vector<int>& completed_members) {\n        for (int member_id : completed_members) {\n            Member& member = members[member_id];\n            if (member.current_task == -1) continue;\n\n            Task& task = tasks[member.current_task];\n            task.completed = true;\n            task.completion_day = current_day;\n            member.current_task = -1;\n            member.task_end_day = -1;\n            available_members.push_back(member_id);\n\n            int completion_time = current_day - task.start_day + 1;\n            update_skill_estimates(member_id, task.id, completion_time);\n        }\n    }\n\npublic:\n    Scheduler(int N, int M, int K, int R, const vector<vector<int>>& difficulties, const vector<pair<int, int>>& dependencies)\n        : N(N), M(M), K(K), R(R), rng(random_device{}()) {\n        tasks.resize(N);\n        for (int i = 0; i < N; ++i) {\n            tasks[i].id = i;\n            tasks[i].difficulty = difficulties[i];\n        }\n\n        adj.resize(N);\n        in_degree.resize(N, 0);\n        task_dependencies.resize(N);\n        task_dependents.resize(N);\n        for (auto [u, v] : dependencies) {\n            u--; v--;\n            adj[u].push_back(v);\n            in_degree[v]++;\n            task_dependencies[v].push_back(u);\n            task_dependents[u].push_back(v);\n        }\n\n        for (int i = 0; i < N; ++i) {\n            tasks[i].dependencies = task_dependencies[i];\n            tasks[i].dependents = task_dependents[i];\n        }\n\n        topological_sort();\n\n        members.resize(M);\n        for (int i = 0; i < M; ++i) {\n            members[i].id = i;\n            members[i].skills.resize(K, 0);\n            skill_estimates.push_back(vector<int>(K, 0));\n            available_members.push_back(i);\n        }\n    }\n\n    void run() {\n        while (current_day < 2000) {\n            current_day++;\n            assign_tasks();\n\n            int n;\n            cin >> n;\n            if (n == -1) {\n                break;\n            }\n            vector<int> completed_members(n);\n            for (int i = 0; i < n; ++i) {\n                cin >> completed_members[i];\n                completed_members[i]--;\n            }\n            process_completions(completed_members);\n        }\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<vector<int>> difficulties(N, vector<int>(K));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> difficulties[i][j];\n        }\n    }\n\n    vector<pair<int, int>> dependencies(R);\n    for (int i = 0; i < R; ++i) {\n        cin >> dependencies[i].first >> dependencies[i].second;\n    }\n\n    Scheduler scheduler(N, M, K, R, difficulties, dependencies);\n    scheduler.run();\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1000;\nconst int M = 50;\nconst int OFFICE_X = 400;\nconst int OFFICE_Y = 400;\n\nstruct Order {\n    int id;\n    int a, b, c, d;\n    int dist_to_office;\n    int dist_pickup_delivery;\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nvector<Order> orders;\nvector<int> selected_orders;\nvector<pair<int, int>> points;\nvector<int> route;\n\nint compute_total_distance(const vector<int>& route) {\n    int total = 0;\n    for (int i = 0; i < (int)route.size() - 1; ++i) {\n        auto [x1, y1] = points[route[i]];\n        auto [x2, y2] = points[route[i+1]];\n        total += manhattan(x1, y1, x2, y2);\n    }\n    return total;\n}\n\nbool check_precedence(const vector<int>& route) {\n    vector<int> pickup_pos(M + 1, -1);\n    vector<int> delivery_pos(M + 1, -1);\n    for (int i = 0; i < (int)route.size(); ++i) {\n        int idx = route[i];\n        if (idx >= 1 && idx <= M) {\n            pickup_pos[idx] = i;\n        } else if (idx >= M + 1 && idx <= 2 * M) {\n            delivery_pos[idx - M] = i;\n        }\n    }\n    for (int i = 1; i <= M; ++i) {\n        if (pickup_pos[i] == -1 || delivery_pos[i] == -1) {\n            return false;\n        }\n        if (pickup_pos[i] >= delivery_pos[i]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid two_opt_with_precedence(vector<int>& route) {\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 1; i < (int)route.size() - 2; ++i) {\n            for (int j = i + 1; j < (int)route.size() - 1; ++j) {\n                if (j - i == 1) continue;\n                vector<int> new_route = route;\n                reverse(new_route.begin() + i, new_route.begin() + j + 1);\n                if (check_precedence(new_route)) {\n                    int current_dist = compute_total_distance(route);\n                    int new_dist = compute_total_distance(new_route);\n                    if (new_dist < current_dist) {\n                        route = new_route;\n                        improved = true;\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid solve() {\n    // Read input\n    orders.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n        orders[i].id = i + 1;\n        orders[i].dist_to_office = manhattan(orders[i].a, orders[i].b, OFFICE_X, OFFICE_Y) +\n                                   manhattan(orders[i].c, orders[i].d, OFFICE_X, OFFICE_Y);\n        orders[i].dist_pickup_delivery = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n    }\n\n    // Select orders with smallest dist_to_office\n    sort(orders.begin(), orders.end(), [](const Order& a, const Order& b) {\n        return a.dist_to_office < b.dist_to_office;\n    });\n    selected_orders.clear();\n    for (int i = 0; i < M; ++i) {\n        selected_orders.push_back(orders[i].id);\n    }\n\n    // Prepare points: 0 is office, 1..M are pickups, M+1..2M are deliveries\n    points.clear();\n    points.emplace_back(OFFICE_X, OFFICE_Y); // 0\n    for (int i = 0; i < M; ++i) {\n        points.emplace_back(orders[i].a, orders[i].b); // 1..M\n    }\n    for (int i = 0; i < M; ++i) {\n        points.emplace_back(orders[i].c, orders[i].d); // M+1..2M\n    }\n\n    // Initial route: office -> pickups in order -> deliveries in order -> office\n    route.clear();\n    route.push_back(0);\n    for (int i = 1; i <= M; ++i) {\n        route.push_back(i);\n    }\n    for (int i = M + 1; i <= 2 * M; ++i) {\n        route.push_back(i);\n    }\n    route.push_back(0);\n\n    // Optimize with 2-opt while respecting precedence\n    two_opt_with_precedence(route);\n\n    // Output\n    cout << M;\n    for (int id : selected_orders) {\n        cout << \" \" << id;\n    }\n    cout << \"\\n\";\n\n    cout << route.size();\n    for (int idx : route) {\n        cout << \" \" << points[idx].first << \" \" << points[idx].second;\n    }\n    cout << \"\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v;\n    int d;\n    int l;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 400;\n    int M = 1995;\n\n    vector<pair<int, int>> points(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> points[i].first >> points[i].second;\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        int dx = points[edges[i].u].first - points[edges[i].v].first;\n        int dy = points[edges[i].u].second - points[edges[i].v].second;\n        edges[i].d = round(sqrt(dx * dx + dy * dy));\n    }\n\n    dsu uf(N);\n    vector<bool> used(M, false);\n    int components = N;\n\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].l;\n        if (uf.same(edges[i].u, edges[i].v)) {\n            cout << 0 << '\\n';\n            cout.flush();\n            continue;\n        }\n        // Accept if the edge is not too expensive relative to d_i\n        if (edges[i].l <= 2 * edges[i].d) {\n            uf.merge(edges[i].u, edges[i].v);\n            cout << 1 << '\\n';\n            cout.flush();\n        } else {\n            cout << 0 << '\\n';\n            cout.flush();\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int GRID_SIZE = 30;\nconst int TURNS = 300;\nconst int MAX_PETS = 20;\nconst int MAX_HUMANS = 10;\n\nstruct Pet {\n    int x, y, type;\n    int target_human = -1;\n    int target_x = -1, target_y = -1;\n};\n\nstruct Human {\n    int x, y;\n};\n\nint N, M;\nvector<Pet> pets;\nvector<Human> humans;\nvector<vector<bool>> blocked(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\nvector<vector<int>> pet_grid(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\nvector<vector<int>> human_grid(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n\nconst vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst string dir_chars = \"udlrUDLR\";\n\nvoid initialize() {\n    cin >> N;\n    pets.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n        pet_grid[pets[i].x][pets[i].y]++;\n    }\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].x >> humans[i].y;\n        human_grid[humans[i].x][humans[i].y]++;\n    }\n    blocked.assign(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\n    for (int i = 0; i <= GRID_SIZE + 1; ++i) {\n        blocked[i][0] = blocked[i][GRID_SIZE + 1] = true;\n        blocked[0][i] = blocked[GRID_SIZE + 1][i] = true;\n    }\n}\n\nbool is_valid(int x, int y) {\n    return x >= 1 && x <= GRID_SIZE && y >= 1 && y <= GRID_SIZE && !blocked[x][y];\n}\n\nbool can_block(int x, int y) {\n    if (x < 1 || x > GRID_SIZE || y < 1 || y > GRID_SIZE) return false;\n    if (blocked[x][y] || pet_grid[x][y] > 0 || human_grid[x][y] > 0) return false;\n    for (auto [dx, dy] : directions) {\n        int nx = x + dx, ny = y + dy;\n        if (nx >= 1 && nx <= GRID_SIZE && ny >= 1 && ny <= GRID_SIZE && pet_grid[nx][ny] > 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvector<pair<int, int>> get_adjacent_passable(int x, int y) {\n    vector<pair<int, int>> res;\n    for (auto [dx, dy] : directions) {\n        int nx = x + dx, ny = y + dy;\n        if (is_valid(nx, ny)) {\n            res.emplace_back(nx, ny);\n        }\n    }\n    return res;\n}\n\nvoid update_grids() {\n    pet_grid.assign(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n    human_grid.assign(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n    for (auto &pet : pets) {\n        pet_grid[pet.x][pet.y]++;\n    }\n    for (auto &human : humans) {\n        human_grid[human.x][human.y]++;\n    }\n}\n\nvoid move_pets() {\n    vector<string> moves(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> moves[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        auto &pet = pets[i];\n        int x = pet.x, y = pet.y;\n        for (char c : moves[i]) {\n            int dx = 0, dy = 0;\n            if (c == 'U') dx = -1;\n            else if (c == 'D') dx = 1;\n            else if (c == 'L') dy = -1;\n            else if (c == 'R') dy = 1;\n            int nx = x + dx, ny = y + dy;\n            if (is_valid(nx, ny)) {\n                x = nx;\n                y = ny;\n            }\n        }\n        pet.x = x;\n        pet.y = y;\n    }\n    update_grids();\n}\n\nvoid decide_human_actions() {\n    string actions;\n    for (int i = 0; i < M; ++i) {\n        auto &human = humans[i];\n        int x = human.x, y = human.y;\n        bool blocked_something = false;\n        vector<pair<int, int>> possible_blocks;\n        for (auto [dx, dy] : directions) {\n            int nx = x + dx, ny = y + dy;\n            if (can_block(nx, ny)) {\n                possible_blocks.emplace_back(nx, ny);\n            }\n        }\n        if (!possible_blocks.empty()) {\n            auto [nx, ny] = possible_blocks[rand() % possible_blocks.size()];\n            blocked[nx][ny] = true;\n            if (nx == x - 1) actions += 'u';\n            else if (nx == x + 1) actions += 'd';\n            else if (ny == y - 1) actions += 'l';\n            else if (ny == y + 1) actions += 'r';\n            blocked_something = true;\n        }\n        if (!blocked_something) {\n            vector<pair<int, int>> adj = get_adjacent_passable(x, y);\n            if (!adj.empty()) {\n                auto [nx, ny] = adj[rand() % adj.size()];\n                human.x = nx;\n                human.y = ny;\n                if (nx == x - 1) actions += 'U';\n                else if (nx == x + 1) actions += 'D';\n                else if (ny == y - 1) actions += 'L';\n                else if (ny == y + 1) actions += 'R';\n            } else {\n                actions += '.';\n            }\n        }\n    }\n    cout << actions << endl;\n    cout.flush();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    initialize();\n    for (int turn = 0; turn < TURNS; ++turn) {\n        decide_human_actions();\n        move_pets();\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int INF = 1e9;\nconst vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst string dir_chars = \"UDLR\";\n\nint si, sj, ti, tj;\ndouble p;\nvector<string> h, v;\n\nvector<vector<int>> bfs_shortest_path() {\n    vector<vector<int>> dist(N, vector<int>(N, INF));\n    queue<pair<int, int>> q;\n    dist[ti][tj] = 0;\n    q.emplace(ti, tj);\n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && dist[ni][nj] == INF) {\n                dist[ni][nj] = dist[i][j] + 1;\n                q.emplace(ni, nj);\n            }\n        }\n    }\n    return dist;\n}\n\nstring construct_path(const vector<vector<int>>& dist) {\n    string path;\n    int i = si, j = sj;\n    while (i != ti || j != tj) {\n        int best_d = -1;\n        int best_dist = INF;\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && dist[ni][nj] < best_dist) {\n                best_dist = dist[ni][nj];\n                best_d = d;\n            }\n        }\n        if (best_d == -1) break;\n        path += dir_chars[best_d];\n        i += dirs[best_d].first;\n        j += dirs[best_d].second;\n    }\n    return path;\n}\n\nstring make_robust_path(const string& shortest_path) {\n    string robust_path;\n    for (char c : shortest_path) {\n        robust_path += c;\n        robust_path += c;\n    }\n    if (robust_path.size() > 200) {\n        robust_path = shortest_path;\n    }\n    return robust_path;\n}\n\nint main() {\n    cin >> si >> sj >> ti >> tj >> p;\n    h.resize(N);\n    v.resize(N - 1);\n    for (int i = 0; i < N; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N - 1; ++i) {\n        cin >> v[i];\n    }\n\n    auto dist = bfs_shortest_path();\n    string shortest_path = construct_path(dist);\n    string robust_path = make_robust_path(shortest_path);\n\n    // Ensure the path length is <= 200\n    if (robust_path.size() > 200) {\n        robust_path = shortest_path.substr(0, 200);\n    }\n\n    cout << robust_path << endl;\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 30;\nconst int dx[4] = {0, -1, 0, 1};\nconst int dy[4] = {-1, 0, 1, 0};\nconst int to[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\n\nvector<string> initial_tiles;\nvector<vector<int>> tiles;\nvector<vector<int>> rotations;\nvector<vector<bool>> visited;\nvector<pair<int, int>> loop_lengths;\n\nint compute_loop_length(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    do {\n        int d2 = to[tiles[i][j]][d];\n        if (d2 == -1) return 0;\n        i += dx[d2];\n        j += dy[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n    } while (!(i == si && j == sj && d == sd));\n    return length;\n}\n\nvoid find_loops() {\n    visited.assign(N, vector<bool>(N, false));\n    loop_lengths.clear();\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (visited[i][j]) continue;\n            for (int d = 0; d < 4; ++d) {\n                int d2 = to[tiles[i][j]][d];\n                if (d2 == -1) continue;\n                int ni = i + dx[d2];\n                int nj = j + dy[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) % 4;\n                int length = compute_loop_length(i, j, d);\n                if (length > 0) {\n                    loop_lengths.emplace_back(length, (i << 16) | (j << 8) | d);\n                    for (int x = 0; x < N; ++x) {\n                        for (int y = 0; y < N; ++y) {\n                            if (visited[x][y]) continue;\n                            for (int dd = 0; dd < 4; ++dd) {\n                                int l = compute_loop_length(x, y, dd);\n                                if (l == length) {\n                                    visited[x][y] = true;\n                                }\n                            }\n                        }\n                    }\n                    goto next_tile;\n                }\n            }\n        }\n        next_tile:;\n    }\n    sort(loop_lengths.rbegin(), loop_lengths.rend());\n}\n\nlong long evaluate() {\n    find_loops();\n    if (loop_lengths.size() < 2) return 0;\n    return (long long)loop_lengths[0].first * loop_lengths[1].first;\n}\n\nvoid apply_rotations() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int type = initial_tiles[i][j] - '0';\n            int rot = rotations[i][j];\n            tiles[i][j] = (type + rot) % 8;\n            if (type >= 0 && type <= 3) {\n                tiles[i][j] = (type + rot) % 4;\n            } else if (type >= 4 && type <= 5) {\n                tiles[i][j] = 4 + (rot % 2);\n            } else if (type >= 6 && type <= 7) {\n                tiles[i][j] = 6 + (rot % 2);\n            }\n        }\n    }\n}\n\nvoid solve() {\n    initial_tiles.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> initial_tiles[i];\n    }\n\n    rotations.assign(N, vector<int>(N, 0));\n    tiles.assign(N, vector<int>(N, 0));\n    apply_rotations();\n    long long best_score = evaluate();\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n    uniform_real_distribution<> prob(0.0, 1.0);\n\n    int iterations = 10000;\n    double temperature = 1000.0;\n    double cooling_rate = 0.99;\n\n    for (int iter = 0; iter < iterations; ++iter) {\n        int i = gen() % N;\n        int j = gen() % N;\n        int old_rot = rotations[i][j];\n        int new_rot = dis(gen);\n        rotations[i][j] = new_rot;\n        apply_rotations();\n        long long new_score = evaluate();\n        if (new_score > best_score || prob(gen) < exp((new_score - best_score) / temperature)) {\n            best_score = new_score;\n        } else {\n            rotations[i][j] = old_rot;\n            apply_rotations();\n        }\n        temperature *= cooling_rate;\n    }\n\n    string output;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            output += to_string(rotations[i][j]);\n        }\n    }\n    cout << output << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\nconst int rev[] = {2, 3, 0, 1};\n\nstruct State {\n    vector<vector<int>> board;\n    int empty_x, empty_y;\n    string moves;\n    int tree_size;\n    int steps;\n\n    State(int N) : board(N, vector<int>(N)), empty_x(0), empty_y(0), moves(\"\"), tree_size(0), steps(0) {}\n\n    bool operator<(const State& other) const {\n        if (tree_size != other.tree_size) {\n            return tree_size > other.tree_size;\n        }\n        return steps < other.steps;\n    }\n};\n\nint calculate_tree_size(const vector<vector<int>>& board) {\n    int N = board.size();\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    int max_size = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0 || visited[i][j]) continue;\n\n            queue<pair<int, int>> q;\n            q.push({i, j});\n            visited[i][j] = true;\n            int size = 0;\n\n            while (!q.empty()) {\n                auto [x, y] = q.front();\n                q.pop();\n                size++;\n\n                int mask = board[x][y];\n                if (x > 0 && (mask & 2) && (board[x-1][y] & 8) && !visited[x-1][y]) {\n                    visited[x-1][y] = true;\n                    q.push({x-1, y});\n                }\n                if (x < N-1 && (mask & 8) && (board[x+1][y] & 2) && !visited[x+1][y]) {\n                    visited[x+1][y] = true;\n                    q.push({x+1, y});\n                }\n                if (y > 0 && (mask & 1) && (board[x][y-1] & 4) && !visited[x][y-1]) {\n                    visited[x][y-1] = true;\n                    q.push({x, y-1});\n                }\n                if (y < N-1 && (mask & 4) && (board[x][y+1] & 1) && !visited[x][y+1]) {\n                    visited[x][y+1] = true;\n                    q.push({x, y+1});\n                }\n            }\n\n            max_size = max(max_size, size);\n        }\n    }\n\n    return max_size;\n}\n\nvector<State> generate_next_states(const State& current, int N, int T) {\n    vector<State> next_states;\n\n    for (int d = 0; d < 4; ++d) {\n        int nx = current.empty_x + dx[d];\n        int ny = current.empty_y + dy[d];\n\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n\n        State next = current;\n        swap(next.board[current.empty_x][current.empty_y], next.board[nx][ny]);\n        next.empty_x = nx;\n        next.empty_y = ny;\n        next.moves += dir[d];\n        next.steps++;\n\n        if (next.steps > T) continue;\n\n        next.tree_size = calculate_tree_size(next.board);\n        next_states.push_back(next);\n    }\n\n    return next_states;\n}\n\nstring solve(int N, int T, const vector<string>& input) {\n    State initial(N);\n    int empty_count = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = input[i][j];\n            if (c == '0') {\n                initial.board[i][j] = 0;\n                initial.empty_x = i;\n                initial.empty_y = j;\n                empty_count++;\n            } else {\n                initial.board[i][j] = stoi(string(1, c), nullptr, 16);\n            }\n        }\n    }\n\n    if (empty_count != 1) {\n        return \"\";\n    }\n\n    initial.tree_size = calculate_tree_size(initial.board);\n\n    priority_queue<State> pq;\n    pq.push(initial);\n\n    int beam_width = 1000;\n    int max_tree_size = 0;\n    string best_moves;\n\n    while (!pq.empty()) {\n        vector<State> current_level;\n\n        while (!pq.empty() && current_level.size() < beam_width) {\n            current_level.push_back(pq.top());\n            pq.pop();\n        }\n\n        for (const State& current : current_level) {\n            if (current.tree_size == N * N - 1) {\n                return current.moves;\n            }\n\n            if (current.tree_size > max_tree_size) {\n                max_tree_size = current.tree_size;\n                best_moves = current.moves;\n            }\n\n            vector<State> next_states = generate_next_states(current, N, T);\n            for (const State& next : next_states) {\n                pq.push(next);\n            }\n        }\n    }\n\n    return best_moves;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    cin >> N >> T;\n    vector<string> input(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> input[i];\n    }\n\n    string result = solve(N, T, input);\n    cout << result << endl;\n\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int MAX_K = 100;\nconst int MAX_D = 10;\nconst int MAX_A = 100;\nconst int RADIUS = 10000;\nconst int RADIUS_SQ = RADIUS * RADIUS;\nconst int MAX_ITERATIONS = 100;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n    bool operator==(const Point& p) const {\n        return x == p.x && y == p.y;\n    }\n};\n\nstruct Line {\n    int px, py, qx, qy;\n    Line(int px, int py, int qx, int qy) : px(px), py(py), qx(qx), qy(qy) {}\n};\n\nint N, K;\nvector<int> a(MAX_D + 1);\nvector<Point> strawberries;\nvector<Line> cuts;\n\nint cross(const Point& o, const Point& a, const Point& b) {\n    return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n}\n\nint side(const Line& l, const Point& p) {\n    Point a(l.px, l.py), b(l.qx, l.qy);\n    long long c = (long long)(b.x - a.x) * (p.y - a.y) - (long long)(b.y - a.y) * (p.x - a.x);\n    if (c > 0) return 1;\n    if (c < 0) return -1;\n    return 0;\n}\n\nvector<vector<int>> regions;\n\nvoid init_regions() {\n    regions.clear();\n    regions.push_back(vector<int>());\n    for (int i = 0; i < N; ++i) {\n        regions[0].push_back(i);\n    }\n}\n\nvoid apply_cut(const Line& cut) {\n    vector<vector<int>> new_regions;\n    for (auto& region : regions) {\n        vector<int> left, right, on;\n        for (int idx : region) {\n            int s = side(cut, strawberries[idx]);\n            if (s == 1) left.push_back(idx);\n            else if (s == -1) right.push_back(idx);\n            else on.push_back(idx);\n        }\n        if (!left.empty()) new_regions.push_back(left);\n        if (!right.empty()) new_regions.push_back(right);\n    }\n    regions = new_regions;\n}\n\nint compute_score() {\n    vector<int> counts(MAX_D + 1, 0);\n    for (auto& region : regions) {\n        int cnt = region.size();\n        if (cnt <= MAX_D) counts[cnt]++;\n    }\n    int score = 0;\n    for (int d = 1; d <= MAX_D; ++d) {\n        score += min(a[d], counts[d]);\n    }\n    return score;\n}\n\nLine generate_line(int idx1, int idx2) {\n    Point p1 = strawberries[idx1];\n    Point p2 = strawberries[idx2];\n    return Line(p1.x, p1.y, p2.x, p2.y);\n}\n\nLine generate_best_line() {\n    Line best_line(0, 0, 0, 0);\n    int best_score = -1;\n    for (int i = 0; i < MAX_ITERATIONS; ++i) {\n        int idx1 = rand() % N;\n        int idx2 = rand() % N;\n        while (idx1 == idx2) idx2 = rand() % N;\n        Line candidate = generate_line(idx1, idx2);\n        vector<vector<int>> temp_regions = regions;\n        apply_cut(candidate);\n        int current_score = compute_score();\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_line = candidate;\n        }\n        regions = temp_regions;\n    }\n    return best_line;\n}\n\nvoid solve() {\n    cin >> N >> K;\n    for (int d = 1; d <= MAX_D; ++d) {\n        cin >> a[d];\n    }\n    strawberries.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> strawberries[i].x >> strawberries[i].y;\n    }\n\n    init_regions();\n    int current_score = compute_score();\n    for (int k = 0; k < K; ++k) {\n        Line best_line = generate_best_line();\n        apply_cut(best_line);\n        int new_score = compute_score();\n        if (new_score > current_score) {\n            current_score = new_score;\n            cuts.push_back(best_line);\n        } else {\n            break;\n        }\n    }\n\n    cout << cuts.size() << endl;\n    for (auto& cut : cuts) {\n        cout << cut.px << \" \" << cut.py << \" \" << cut.qx << \" \" << cut.qy << endl;\n    }\n}\n\nint main() {\n    srand(time(0));\n    solve();\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <cmath>\n#include <unordered_set>\n#include <chrono>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nint N, M;\nvector<Point> initial_dots;\nvector<vector<bool>> has_dot;\nvector<Rectangle> rectangles;\nint center;\nlong long total_weight = 0;\n\nlong long weight(int x, int y) {\n    long long dx = x - center;\n    long long dy = y - center;\n    return dx * dx + dy * dy + 1;\n}\n\nvoid precompute_weights() {\n    center = (N - 1) / 2;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y < N; ++y) {\n            total_weight += weight(x, y);\n        }\n    }\n}\n\nbool is_valid_point(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_perimeter(const Rectangle& rect) {\n    vector<Point> points = {rect.p1, rect.p2, rect.p3, rect.p4};\n    for (int i = 0; i < 4; ++i) {\n        Point a = points[i];\n        Point b = points[(i + 1) % 4];\n        if (a.x == b.x) {\n            int x = a.x;\n            int y1 = min(a.y, b.y);\n            int y2 = max(a.y, b.y);\n            for (int y = y1; y <= y2; ++y) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        } else if (a.y == b.y) {\n            int y = a.y;\n            int x1 = min(a.x, b.x);\n            int x2 = max(a.x, b.x);\n            for (int x = x1; x <= x2; ++x) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        } else {\n            int dx = b.x - a.x;\n            int dy = b.y - a.y;\n            if (abs(dx) != abs(dy)) {\n                return false;\n            }\n            int step = dx > 0 ? 1 : -1;\n            for (int x = a.x, y = a.y; x != b.x; x += step, y += step * dy / dx) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool check_overlap(const Rectangle& new_rect) {\n    for (const auto& rect : rectangles) {\n        vector<Point> new_points = {new_rect.p1, new_rect.p2, new_rect.p3, new_rect.p4};\n        vector<Point> old_points = {rect.p1, rect.p2, rect.p3, rect.p4};\n        for (int i = 0; i < 4; ++i) {\n            Point a1 = new_points[i];\n            Point b1 = new_points[(i + 1) % 4];\n            for (int j = 0; j < 4; ++j) {\n                Point a2 = old_points[j];\n                Point b2 = old_points[(j + 1) % 4];\n                if (a1 == a2 && b1 == b2) return true;\n                if (a1 == b2 && b1 == a2) return true;\n            }\n        }\n    }\n    return false;\n}\n\nvector<Rectangle> generate_candidates() {\n    vector<Rectangle> candidates;\n    for (int i = 0; i < initial_dots.size(); ++i) {\n        for (int j = i + 1; j < initial_dots.size(); ++j) {\n            Point p2 = initial_dots[i];\n            Point p3 = initial_dots[j];\n            // Axis-aligned rectangle\n            {\n                Point p1(p2.x, p3.y);\n                Point p4(p3.x, p2.y);\n                if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                    Rectangle rect(p1, p2, p3, p4);\n                    if (check_perimeter(rect) && !check_overlap(rect)) {\n                        candidates.push_back(rect);\n                    }\n                }\n            }\n            // 45-degree rotated rectangle\n            {\n                int dx = p3.x - p2.x;\n                int dy = p3.y - p2.y;\n                if (abs(dx) == abs(dy)) {\n                    Point p1(p2.x + dy, p2.y - dx);\n                    Point p4(p3.x + dy, p3.y - dx);\n                    if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                        Rectangle rect(p1, p2, p3, p4);\n                        if (check_perimeter(rect) && !check_overlap(rect)) {\n                            candidates.push_back(rect);\n                        }\n                    }\n                    p1 = Point(p2.x - dy, p2.y + dx);\n                    p4 = Point(p3.x - dy, p3.y + dx);\n                    if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                        Rectangle rect(p1, p2, p3, p4);\n                        if (check_perimeter(rect) && !check_overlap(rect)) {\n                            candidates.push_back(rect);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return candidates;\n}\n\nvoid solve() {\n    precompute_weights();\n    has_dot.assign(N, vector<bool>(N, false));\n    for (const auto& dot : initial_dots) {\n        has_dot[dot.x][dot.y] = true;\n    }\n\n    auto start_time = chrono::high_resolution_clock::now();\n    while (true) {\n        auto candidates = generate_candidates();\n        if (candidates.empty()) break;\n\n        Rectangle best_rect;\n        long long best_score = -1;\n        for (const auto& rect : candidates) {\n            long long current_score = weight(rect.p1.x, rect.p1.y);\n            if (current_score > best_score) {\n                best_score = current_score;\n                best_rect = rect;\n            }\n        }\n\n        if (best_score == -1) break;\n\n        rectangles.push_back(best_rect);\n        has_dot[best_rect.p1.x][best_rect.p1.y] = true;\n        initial_dots.push_back(best_rect.p1);\n\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 4500) break;\n    }\n\n    cout << rectangles.size() << endl;\n    for (const auto& rect : rectangles) {\n        cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n             << rect.p2.x << \" \" << rect.p2.y << \" \"\n             << rect.p3.x << \" \" << rect.p3.y << \" \"\n             << rect.p4.x << \" \" << rect.p4.y << endl;\n    }\n}\n\nint main() {\n    cin >> N >> M;\n    initial_dots.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> initial_dots[i].x >> initial_dots[i].y;\n    }\n    solve();\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <cstring>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 10;\nconst int TOTAL_CANDIES = 100;\nconst vector<char> DIRECTIONS = {'F', 'B', 'L', 'R'};\n\nstruct Grid {\n    int cells[N][N];\n    int empty_count;\n\n    Grid() {\n        memset(cells, 0, sizeof(cells));\n        empty_count = N * N;\n    }\n\n    void place_candy(int pos, int flavor) {\n        int idx = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] == 0) {\n                    if (++idx == pos) {\n                        cells[i][j] = flavor;\n                        empty_count--;\n                        return;\n                    }\n                }\n            }\n        }\n    }\n\n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; ++j) {\n                int write_pos = N - 1;\n                for (int i = N - 1; i >= 0; --i) {\n                    if (cells[i][j] != 0) {\n                        cells[write_pos--][j] = cells[i][j];\n                    }\n                }\n                for (int i = write_pos; i >= 0; --i) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; ++j) {\n                int write_pos = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (cells[i][j] != 0) {\n                        cells[write_pos++][j] = cells[i][j];\n                    }\n                }\n                for (int i = write_pos; i < N; ++i) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; ++i) {\n                int write_pos = 0;\n                for (int j = 0; j < N; ++j) {\n                    if (cells[i][j] != 0) {\n                        cells[i][write_pos++] = cells[i][j];\n                    }\n                }\n                for (int j = write_pos; j < N; ++j) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'R') {\n            for (int i = 0; i < N; ++i) {\n                int write_pos = N - 1;\n                for (int j = N - 1; j >= 0; --j) {\n                    if (cells[i][j] != 0) {\n                        cells[i][write_pos--] = cells[i][j];\n                    }\n                }\n                for (int j = write_pos; j >= 0; --j) {\n                    cells[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    vector<int> get_connected_components() {\n        vector<int> component_sizes;\n        bool visited[N][N] = {false};\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0 && !visited[i][j]) {\n                    int flavor = cells[i][j];\n                    int size = 0;\n                    queue<pair<int, int>> q;\n                    q.push({i, j});\n                    visited[i][j] = true;\n\n                    while (!q.empty()) {\n                        auto [x, y] = q.front();\n                        q.pop();\n                        size++;\n\n                        for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                            int nx = x + dx;\n                            int ny = y + dy;\n                            if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && cells[nx][ny] == flavor) {\n                                visited[nx][ny] = true;\n                                q.push({nx, ny});\n                            }\n                        }\n                    }\n                    component_sizes.push_back(size);\n                }\n            }\n        }\n        return component_sizes;\n    }\n\n    double evaluate() {\n        auto components = get_connected_components();\n        double sum_sq = 0;\n        for (int size : components) {\n            sum_sq += size * size;\n        }\n        int counts[4] = {0};\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    counts[cells[i][j]]++;\n                }\n            }\n        }\n        double denom = 0;\n        for (int i = 1; i <= 3; ++i) {\n            denom += counts[i] * counts[i];\n        }\n        if (denom == 0) return 0;\n        return sum_sq / denom;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<int> flavors(TOTAL_CANDIES);\n    for (int i = 0; i < TOTAL_CANDIES; ++i) {\n        cin >> flavors[i];\n    }\n\n    Grid grid;\n    for (int t = 0; t < TOTAL_CANDIES; ++t) {\n        int pos;\n        cin >> pos;\n        grid.place_candy(pos, flavors[t]);\n\n        if (t == TOTAL_CANDIES - 1) {\n            break;\n        }\n\n        double best_score = -1;\n        char best_dir = 'F';\n        for (char dir : DIRECTIONS) {\n            Grid temp_grid = grid;\n            temp_grid.tilt(dir);\n            double score = temp_grid.evaluate();\n            if (score > best_score) {\n                best_score = score;\n                best_dir = dir;\n            }\n        }\n        grid.tilt(best_dir);\n        cout << best_dir << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <random>\n#include <chrono>\n#include <map>\n#include <set>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Graph {\n    int N;\n    vector<vector<bool>> adj;\n    vector<int> degree;\n    int edge_count;\n    vector<int> degree_seq;\n\n    Graph(int n) : N(n), adj(n, vector<bool>(n, false)), degree(n, 0), edge_count(0) {}\n\n    void add_edge(int u, int v) {\n        if (!adj[u][v]) {\n            adj[u][v] = adj[v][u] = true;\n            degree[u]++;\n            degree[v]++;\n            edge_count++;\n        }\n    }\n\n    void compute_degree_seq() {\n        degree_seq = degree;\n        sort(degree_seq.begin(), degree_seq.end(), greater<int>());\n    }\n\n    string to_string() const {\n        string s;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                s += adj[i][j] ? '1' : '0';\n            }\n        }\n        return s;\n    }\n};\n\nvector<Graph> generate_graphs(int M, int N) {\n    vector<Graph> graphs;\n    for (int k = 0; k < M; ++k) {\n        Graph g(N);\n        // Simple strategy: G_k has k edges, but distributed to make degree sequence unique\n        int edges = k;\n        for (int i = 0; i < N && edges > 0; ++i) {\n            for (int j = i + 1; j < N && edges > 0; ++j) {\n                g.add_edge(i, j);\n                edges--;\n            }\n        }\n        g.compute_degree_seq();\n        graphs.push_back(g);\n    }\n    return graphs;\n}\n\nvector<int> compute_degree_sequence(const string& s, int N) {\n    vector<int> degree(N, 0);\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (s[idx++] == '1') {\n                degree[i]++;\n                degree[j]++;\n            }\n        }\n    }\n    sort(degree.begin(), degree.end(), greater<int>());\n    return degree;\n}\n\nint count_edges(const string& s) {\n    return count(s.begin(), s.end(), '1');\n}\n\ndouble compute_distance(const vector<int>& a, const vector<int>& b) {\n    double dist = 0.0;\n    for (int i = 0; i < a.size(); ++i) {\n        dist += abs(a[i] - b[i]);\n    }\n    return dist;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    cin >> M >> eps;\n\n    // Choose N based on M and eps\n    int N = min(100, max(4, M + 10)); // Heuristic: N should be larger for larger M or eps\n    if (eps > 0.2) {\n        N = min(100, N + 20); // Increase N for higher error rates\n    }\n\n    vector<Graph> graphs = generate_graphs(M, N);\n\n    // Output the graphs\n    cout << N << '\\n';\n    for (const auto& g : graphs) {\n        cout << g.to_string() << '\\n';\n    }\n    cout.flush();\n\n    // Precompute invariants for all G_k\n    vector<int> edge_counts;\n    vector<vector<int>> degree_seqs;\n    for (const auto& g : graphs) {\n        edge_counts.push_back(g.edge_count);\n        degree_seqs.push_back(g.degree_seq);\n    }\n\n    // Process queries\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // Compute invariants for H\n        int edges_H = count_edges(H);\n        vector<int> degree_seq_H = compute_degree_sequence(H, N);\n\n        // Find the closest G_k\n        double min_dist = 1e18;\n        int best_k = 0;\n        for (int k = 0; k < M; ++k) {\n            double dist = abs(edges_H - edge_counts[k]) + compute_distance(degree_seq_H, degree_seqs[k]);\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_k = k;\n            }\n        }\n\n        cout << best_k << '\\n';\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int INF = 1e9;\nconst double INIT_TEMP = 1e4;\nconst double FINAL_TEMP = 1e-4;\nconst double COOLING_RATE = 0.999;\nconst int MAX_ITER = 100000;\n\nstruct Edge {\n    int u, v, w, idx;\n};\n\nstruct Point {\n    int x, y;\n};\n\nint N, M, D, K;\nvector<Edge> edges;\nvector<Point> points;\nvector<vector<int>> adj;\nvector<vector<int>> dist;\nvector<int> schedule;\n\nvoid read_input() {\n    cin >> N >> M >> D >> K;\n    edges.resize(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        edges[i].idx = i;\n    }\n    points.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> points[i].x >> points[i].y;\n    }\n}\n\nvoid compute_apsp() {\n    dist.assign(N, vector<int>(N, INF));\n    for (int i = 0; i < N; ++i) {\n        dist[i][i] = 0;\n    }\n    for (const auto& e : edges) {\n        dist[e.u][e.v] = min(dist[e.u][e.v], e.w);\n        dist[e.v][e.u] = min(dist[e.v][e.u], e.w);\n    }\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 (dist[i][k] < INF && dist[k][j] < INF) {\n                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n                }\n            }\n        }\n    }\n}\n\nvector<vector<int>> compute_daily_dist(int day) {\n    vector<vector<int>> daily_dist = dist;\n    for (int i = 0; i < M; ++i) {\n        if (schedule[i] == day) {\n            const auto& e = edges[i];\n            daily_dist[e.u][e.v] = INF;\n            daily_dist[e.v][e.u] = INF;\n        }\n    }\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 (daily_dist[i][k] < INF && daily_dist[k][j] < INF) {\n                    daily_dist[i][j] = min(daily_dist[i][j], daily_dist[i][k] + daily_dist[k][j]);\n                }\n            }\n        }\n    }\n    return daily_dist;\n}\n\ndouble compute_frustration() {\n    double total_frustration = 0.0;\n    for (int day = 1; day <= D; ++day) {\n        auto daily_dist = compute_daily_dist(day);\n        double sum_diff = 0.0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                int original = dist[i][j];\n                int current = daily_dist[i][j];\n                if (current >= INF) current = INF;\n                sum_diff += (current - original);\n            }\n        }\n        double f_k = sum_diff / (N * (N - 1) / 2);\n        total_frustration += f_k;\n    }\n    return total_frustration / D;\n}\n\nvoid initial_schedule() {\n    schedule.assign(M, 0);\n    vector<int> day_counts(D, 0);\n    for (int i = 0; i < M; ++i) {\n        int day = rand() % D + 1;\n        while (day_counts[day - 1] >= K) {\n            day = rand() % D + 1;\n        }\n        schedule[i] = day;\n        day_counts[day - 1]++;\n    }\n}\n\nvoid simulated_annealing() {\n    initial_schedule();\n    double current_frustration = compute_frustration();\n    double temp = INIT_TEMP;\n    int iter = 0;\n    while (temp > FINAL_TEMP && iter < MAX_ITER) {\n        int edge_idx = rand() % M;\n        int old_day = schedule[edge_idx];\n        int new_day = rand() % D + 1;\n        if (count(schedule.begin(), schedule.end(), new_day) >= K) {\n            continue;\n        }\n        schedule[edge_idx] = new_day;\n        double new_frustration = compute_frustration();\n        double delta = new_frustration - current_frustration;\n        if (delta < 0 || exp(-delta / temp) > (double)rand() / RAND_MAX) {\n            current_frustration = new_frustration;\n        } else {\n            schedule[edge_idx] = old_day;\n        }\n        temp *= COOLING_RATE;\n        iter++;\n    }\n}\n\nint main() {\n    srand(time(0));\n    read_input();\n    compute_apsp();\n    simulated_annealing();\n    for (int i = 0; i < M; ++i) {\n        cout << schedule[i] << (i == M - 1 ? \"\\n\" : \" \");\n    }\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <unordered_set>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n    Point(int x = 0, int y = 0, int z = 0) : x(x), y(y), z(z) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y && z == other.z;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        if (y != other.y) return y < other.y;\n        return z < other.z;\n    }\n};\n\nstruct Block {\n    vector<Point> cubes;\n    int id;\n    Block(int id = 0) : id(id) {}\n    void add_cube(const Point& p) {\n        cubes.push_back(p);\n    }\n    bool is_connected() const {\n        if (cubes.empty()) return true;\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        queue<Point> q;\n        q.push(cubes[0]);\n        visited[cubes[0].x][cubes[0].y][cubes[0].z] = true;\n        int count = 1;\n        while (!q.empty()) {\n            Point p = q.front();\n            q.pop();\n            for (const auto& cube : cubes) {\n                if (!visited[cube.x][cube.y][cube.z]) {\n                    int dx = abs(p.x - cube.x);\n                    int dy = abs(p.y - cube.y);\n                    int dz = abs(p.z - cube.z);\n                    if ((dx == 1 && dy == 0 && dz == 0) ||\n                        (dx == 0 && dy == 1 && dz == 0) ||\n                        (dx == 0 && dy == 0 && dz == 1)) {\n                        visited[cube.x][cube.y][cube.z] = true;\n                        q.push(cube);\n                        count++;\n                    }\n                }\n            }\n        }\n        return count == cubes.size();\n    }\n};\n\nint D;\nvector<vector<string>> f(2, vector<string>(D));\nvector<vector<string>> r(2, vector<string>(D));\nvector<vector<vector<int>>> b(2, vector<vector<int>>(D, vector<int>(D, 0)));\nvector<Block> blocks;\nint block_id = 1;\n\nbool can_place_block(const Block& block, int obj_idx, const vector<vector<vector<int>>>& grid) {\n    for (const auto& cube : block.cubes) {\n        if (cube.x < 0 || cube.x >= D || cube.y < 0 || cube.y >= D || cube.z < 0 || cube.z >= D) {\n            return false;\n        }\n        if (grid[cube.x][cube.y][cube.z] != 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid place_block(const Block& block, int obj_idx, int id) {\n    for (const auto& cube : block.cubes) {\n        b[obj_idx][cube.x][cube.y][cube.z] = id;\n    }\n}\n\nvoid remove_block(const Block& block, int obj_idx) {\n    for (const auto& cube : block.cubes) {\n        b[obj_idx][cube.x][cube.y][cube.z] = 0;\n    }\n}\n\nbool satisfies_silhouette(int obj_idx) {\n    for (int z = 0; z < D; ++z) {\n        for (int x = 0; x < D; ++x) {\n            bool found = false;\n            for (int y = 0; y < D; ++y) {\n                if (b[obj_idx][x][y][z] != 0) {\n                    found = true;\n                    break;\n                }\n            }\n            if (f[obj_idx][z][x] == '1' && !found) {\n                return false;\n            }\n        }\n    }\n    for (int z = 0; z < D; ++z) {\n        for (int y = 0; y < D; ++y) {\n            bool found = false;\n            for (int x = 0; x < D; ++x) {\n                if (b[obj_idx][x][y][z] != 0) {\n                    found = true;\n                    break;\n                }\n            }\n            if (r[obj_idx][z][y] == '1' && !found) {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nvoid generate_initial_blocks() {\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[obj_idx][z][x] == '1' && r[obj_idx][z][y] == '1') {\n                        bool found = false;\n                        for (const auto& block : blocks) {\n                            for (const auto& cube : block.cubes) {\n                                if (cube.x == x && cube.y == y && cube.z == z) {\n                                    found = true;\n                                    break;\n                                }\n                            }\n                            if (found) break;\n                        }\n                        if (!found) {\n                            Block block(block_id++);\n                            block.add_cube(Point(x, y, z));\n                            blocks.push_back(block);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid merge_blocks() {\n    bool merged;\n    do {\n        merged = false;\n        for (size_t i = 0; i < blocks.size(); ++i) {\n            for (size_t j = i + 1; j < blocks.size(); ++j) {\n                Block new_block(block_id);\n                for (const auto& cube : blocks[i].cubes) {\n                    new_block.add_cube(cube);\n                }\n                for (const auto& cube : blocks[j].cubes) {\n                    new_block.add_cube(cube);\n                }\n                if (new_block.is_connected()) {\n                    vector<Block> new_blocks;\n                    for (size_t k = 0; k < blocks.size(); ++k) {\n                        if (k != i && k != j) {\n                            new_blocks.push_back(blocks[k]);\n                        }\n                    }\n                    new_blocks.push_back(new_block);\n                    blocks = new_blocks;\n                    block_id++;\n                    merged = true;\n                    break;\n                }\n            }\n            if (merged) break;\n        }\n    } while (merged);\n}\n\nvoid assign_blocks_to_objects() {\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        vector<vector<vector<int>>> grid(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        for (const auto& block : blocks) {\n            bool used = false;\n            for (const auto& cube : block.cubes) {\n                if (f[obj_idx][cube.z][cube.x] == '1' && r[obj_idx][cube.z][cube.y] == '1') {\n                    used = true;\n                    break;\n                }\n            }\n            if (used) {\n                place_block(block, obj_idx, block.id);\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> D;\n    f.resize(2, vector<string>(D));\n    r.resize(2, vector<string>(D));\n    b.resize(2, vector<vector<int>>(D, vector<int>(D, 0)));\n\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> f[i][k];\n        }\n        for (int k = 0; k < D; ++k) {\n            cin >> r[i][k];\n        }\n    }\n\n    generate_initial_blocks();\n    merge_blocks();\n    assign_blocks_to_objects();\n\n    set<int> used_blocks;\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (b[obj_idx][x][y][z] != 0) {\n                        used_blocks.insert(b[obj_idx][x][y][z]);\n                    }\n                }\n            }\n        }\n    }\n\n    vector<int> block_ids;\n    for (const auto& block : blocks) {\n        block_ids.push_back(block.id);\n    }\n    sort(block_ids.begin(), block_ids.end());\n    block_ids.erase(unique(block_ids.begin(), block_ids.end()), block_ids.end());\n\n    cout << block_ids.size() << endl;\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    cout << b[obj_idx][x][y][z] << \" \";\n                }\n            }\n        }\n        cout << endl;\n    }\n\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v, w, idx;\n    double dist;\n};\n\nstruct Resident {\n    int x, y;\n};\n\nstruct Station {\n    int x, y;\n    int P;\n    vector<int> residents;\n};\n\ndouble euclidean(int x1, int y1, int x2, int y2) {\n    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<Station> stations(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> stations[i].x >> stations[i].y;\n        stations[i].P = 0;\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        edges[i].idx = i;\n        edges[i].dist = euclidean(stations[edges[i].u].x, stations[edges[i].u].y,\n                                  stations[edges[i].v].x, stations[edges[i].v].y);\n    }\n\n    vector<Resident> residents(K);\n    for (int i = 0; i < K; ++i) {\n        cin >> residents[i].x >> residents[i].y;\n    }\n\n    // Step 1: Assign residents to nearest station\n    for (int i = 0; i < K; ++i) {\n        double min_dist = 1e9;\n        int best_station = -1;\n        for (int j = 0; j < N; ++j) {\n            double dist = euclidean(residents[i].x, residents[i].y, stations[j].x, stations[j].y);\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_station = j;\n            }\n        }\n        stations[best_station].residents.push_back(i);\n    }\n\n    // Step 2: Compute MST using Kruskal's algorithm\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.w < b.w;\n    });\n\n    dsu uf(N);\n    vector<bool> edge_used(M, false);\n    vector<vector<pair<int, int>>> mst(N); // {neighbor, edge_idx}\n\n    for (const Edge& e : edges) {\n        if (!uf.same(e.u, e.v)) {\n            uf.merge(e.u, e.v);\n            edge_used[e.idx] = true;\n            mst[e.u].emplace_back(e.v, e.idx);\n            mst[e.v].emplace_back(e.u, e.idx);\n        }\n    }\n\n    // Step 3: Set initial P_i to cover all residents\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].residents.empty()) {\n            stations[i].P = 0;\n            continue;\n        }\n        double max_dist = 0;\n        for (int r : stations[i].residents) {\n            double dist = euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y);\n            if (dist > max_dist) {\n                max_dist = dist;\n            }\n        }\n        stations[i].P = min(5000, (int)ceil(max_dist));\n    }\n\n    // Step 4: Optimize P_i and edge selection\n    vector<bool> covered(K, false);\n    auto check_coverage = [&]() {\n        fill(covered.begin(), covered.end(), false);\n        for (int i = 0; i < N; ++i) {\n            for (int r : stations[i].residents) {\n                if (euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y) <= stations[i].P) {\n                    covered[r] = true;\n                }\n            }\n        }\n        return all_of(covered.begin(), covered.end(), [](bool c) { return c; });\n    };\n\n    if (!check_coverage()) {\n        // Fallback: ensure all residents are covered\n        for (int i = 0; i < N; ++i) {\n            double max_dist = 0;\n            for (int r : stations[i].residents) {\n                double dist = euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y);\n                if (dist > max_dist) {\n                    max_dist = dist;\n                }\n            }\n            stations[i].P = min(5000, (int)ceil(max_dist));\n        }\n    }\n\n    // Try to reduce P_i\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].P == 0) continue;\n        int original_P = stations[i].P;\n        for (int p = original_P - 1; p >= 0; --p) {\n            int old_P = stations[i].P;\n            stations[i].P = p;\n            if (!check_coverage()) {\n                stations[i].P = old_P;\n                break;\n            }\n        }\n    }\n\n    // Step 5: Prune unnecessary edges\n    vector<bool> necessary_edge(M, false);\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].P > 0) {\n            // BFS to mark necessary edges\n            vector<bool> visited(N, false);\n            queue<int> q;\n            q.push(i);\n            visited[i] = true;\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (auto [v, idx] : mst[u]) {\n                    if (!visited[v] && edge_used[idx]) {\n                        necessary_edge[idx] = true;\n                        visited[v] = true;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n\n    // Ensure station 1 is connected\n    vector<bool> visited(N, false);\n    queue<int> q;\n    q.push(0);\n    visited[0] = true;\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        for (auto [v, idx] : mst[u]) {\n            if (!visited[v] && edge_used[idx]) {\n                necessary_edge[idx] = true;\n                visited[v] = true;\n                q.push(v);\n            }\n        }\n    }\n\n    for (int i = 0; i < M; ++i) {\n        if (!necessary_edge[i]) {\n            edge_used[i] = false;\n        }\n    }\n\n    // Step 6: Output the solution\n    for (int i = 0; i < N; ++i) {\n        cout << stations[i].P << (i == N - 1 ? \"\\n\" : \" \");\n    }\n    for (int i = 0; i < M; ++i) {\n        cout << edge_used[i] << (i == M - 1 ? \"\\n\" : \" \");\n    }\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_map>\n#include <cmath>\n#include <climits>\n#include <set>\n\nusing namespace std;\n\nconst int N = 30;\nconst int TOTAL_BALLS = N * (N + 1) / 2;\nconst int MAX_OPERATIONS = 10000;\n\nstruct Position {\n    int x, y;\n    Position(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Position& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Position& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nvector<Position> directions = {\n    {-1, -1}, {-1, 0}, {0, -1}, {0, 1}, {1, 0}, {1, 1}\n};\n\nvector<vector<int>> pyramid(N, vector<int>(N, -1));\nvector<pair<Position, Position>> operations;\n\nbool is_valid(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y <= x;\n}\n\nvector<Position> get_adjacent_positions(int x, int y) {\n    vector<Position> adj;\n    for (auto& dir : directions) {\n        int nx = x + dir.x;\n        int ny = y + dir.y;\n        if (is_valid(nx, ny)) {\n            adj.emplace_back(nx, ny);\n        }\n    }\n    return adj;\n}\n\nvoid swap_balls(Position a, Position b) {\n    if (!is_valid(a.x, a.y) || !is_valid(b.x, b.y)) return;\n    swap(pyramid[a.x][a.y], pyramid[b.x][b.y]);\n    operations.emplace_back(a, b);\n}\n\nint count_violations() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int current = pyramid[x][y];\n            int child1 = pyramid[x + 1][y];\n            int child2 = pyramid[x + 1][y + 1];\n            if (current > child1) violations++;\n            if (current > child2) violations++;\n        }\n    }\n    return violations;\n}\n\nPosition find_ball(int num) {\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] == num) {\n                return Position(x, y);\n            }\n        }\n    }\n    return Position(-1, -1);\n}\n\nvector<Position> find_path(Position start, Position target) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    vector<vector<Position>> parent(N, vector<Position>(N, Position(-1, -1)));\n    queue<Position> q;\n    q.push(start);\n    visited[start.x][start.y] = true;\n\n    while (!q.empty()) {\n        Position current = q.front();\n        q.pop();\n        if (current.x == target.x && current.y == target.y) {\n            vector<Position> path;\n            while (!(current.x == start.x && current.y == start.y)) {\n                path.push_back(current);\n                current = parent[current.x][current.y];\n            }\n            path.push_back(start);\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        for (auto& dir : directions) {\n            int nx = current.x + dir.x;\n            int ny = current.y + dir.y;\n            if (is_valid(nx, ny) && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                parent[nx][ny] = current;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return {};\n}\n\nvoid move_ball(Position start, Position target) {\n    vector<Position> path = find_path(start, target);\n    if (path.empty()) return;\n    for (size_t i = 0; i < path.size() - 1; ++i) {\n        swap_balls(path[i], path[i + 1]);\n    }\n}\n\nvoid solve() {\n    // Read input\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            cin >> pyramid[x][y];\n        }\n    }\n\n    // Target: smallest numbers at the top\n    // We'll try to place the smallest numbers in the top positions\n    // This is a heuristic approach\n\n    // For each position, find the smallest number that should be there\n    // The target is to have the smallest numbers in the top positions\n    // So, the target for position (x, y) is the (x*(x+1)/2 + y)-th smallest number\n\n    vector<int> sorted_balls(TOTAL_BALLS);\n    for (int i = 0; i < TOTAL_BALLS; ++i) {\n        sorted_balls[i] = i;\n    }\n\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int target_num = sorted_balls[x * (x + 1) / 2 + y];\n            Position current_pos = find_ball(target_num);\n            if (current_pos.x != x || current_pos.y != y) {\n                move_ball(current_pos, Position(x, y));\n                if (operations.size() >= MAX_OPERATIONS) {\n                    goto output;\n                }\n            }\n        }\n    }\n\n    // After initial placement, check for violations and fix them\n    int violations = count_violations();\n    while (violations > 0 && operations.size() < MAX_OPERATIONS) {\n        for (int x = 0; x < N - 1; ++x) {\n            for (int y = 0; y <= x; ++y) {\n                int current = pyramid[x][y];\n                int child1 = pyramid[x + 1][y];\n                int child2 = pyramid[x + 1][y + 1];\n                if (current > child1 || current > child2) {\n                    // Find the smallest adjacent ball to swap with\n                    vector<Position> adj = get_adjacent_positions(x, y);\n                    int min_val = current;\n                    Position best_swap = Position(-1, -1);\n                    for (auto& pos : adj) {\n                        if (pyramid[pos.x][pos.y] < min_val) {\n                            min_val = pyramid[pos.x][pos.y];\n                            best_swap = pos;\n                        }\n                    }\n                    if (best_swap.x != -1) {\n                        swap_balls(Position(x, y), best_swap);\n                        violations = count_violations();\n                        if (operations.size() >= MAX_OPERATIONS) {\n                            goto output;\n                        }\n                    }\n                }\n            }\n        }\n        violations = count_violations();\n    }\n\noutput:\n    cout << operations.size() << endl;\n    for (auto& op : operations) {\n        cout << op.first.x << \" \" << op.first.y << \" \"\n             << op.second.x << \" \" << op.second.y << endl;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <set>\n#include <climits>\n#include <cstring>\n\nusing namespace std;\n\nconst int GRID_SIZE = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = (GRID_SIZE - 1) / 2;\n\nstruct Cell {\n    int i, j;\n    bool operator<(const Cell& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nint grid[GRID_SIZE][GRID_SIZE];\nbool is_obstacle[GRID_SIZE][GRID_SIZE];\nbool is_container[GRID_SIZE][GRID_SIZE];\nint container_num[GRID_SIZE][GRID_SIZE];\nvector<Cell> containers;\n\nint di[] = {-1, 1, 0, 0};\nint dj[] = {0, 0, -1, 1};\n\nbool is_valid(int i, int j) {\n    return i >= 0 && i < GRID_SIZE && j >= 0 && j < GRID_SIZE;\n}\n\nvector<Cell> bfs_reachable() {\n    vector<Cell> reachable;\n    bool visited[GRID_SIZE][GRID_SIZE];\n    memset(visited, false, sizeof(visited));\n    queue<Cell> q;\n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n\n    while (!q.empty()) {\n        Cell current = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int ni = current.i + di[k];\n            int nj = current.j + dj[k];\n            if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj] && !is_container[ni][nj]) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n            }\n        }\n    }\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (visited[i][j] && !is_obstacle[i][j] && !is_container[i][j] && !(i == ENTRANCE_I && j == ENTRANCE_J)) {\n                reachable.push_back({i, j});\n            }\n        }\n    }\n    return reachable;\n}\n\nvector<Cell> bfs_removable() {\n    vector<Cell> removable;\n    bool visited[GRID_SIZE][GRID_SIZE];\n    memset(visited, false, sizeof(visited));\n    queue<Cell> q;\n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n\n    while (!q.empty()) {\n        Cell current = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int ni = current.i + di[k];\n            int nj = current.j + dj[k];\n            if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj]) {\n                if (is_container[ni][nj]) {\n                    removable.push_back({ni, nj});\n                } else {\n                    visited[ni][nj] = true;\n                    q.push({ni, nj});\n                }\n            }\n        }\n    }\n    return removable;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int D, N;\n    cin >> D >> N;\n    memset(is_obstacle, false, sizeof(is_obstacle));\n    memset(is_container, false, sizeof(is_container));\n    memset(container_num, -1, sizeof(container_num));\n\n    for (int i = 0; i < N; ++i) {\n        int ri, rj;\n        cin >> ri >> rj;\n        is_obstacle[ri][rj] = true;\n    }\n\n    int total_containers = GRID_SIZE * GRID_SIZE - 1 - N;\n    for (int d = 0; d < total_containers; ++d) {\n        int t;\n        cin >> t;\n        vector<Cell> reachable = bfs_reachable();\n        if (reachable.empty()) {\n            cerr << \"No reachable cells left!\" << endl;\n            return 1;\n        }\n\n        // Place the container in the cell with the highest BFS distance from entrance\n        bool visited[GRID_SIZE][GRID_SIZE];\n        memset(visited, false, sizeof(visited));\n        queue<Cell> q;\n        q.push({ENTRANCE_I, ENTRANCE_J});\n        visited[ENTRANCE_I][ENTRANCE_J] = true;\n        Cell farthest = {ENTRANCE_I, ENTRANCE_J};\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            farthest = current;\n            for (int k = 0; k < 4; ++k) {\n                int ni = current.i + di[k];\n                int nj = current.j + dj[k];\n                if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj] && !is_container[ni][nj]) {\n                    visited[ni][nj] = true;\n                    q.push({ni, nj});\n                }\n            }\n        }\n\n        // Place the container at the farthest cell\n        is_container[farthest.i][farthest.j] = true;\n        container_num[farthest.i][farthest.j] = t;\n        containers.push_back({farthest.i, farthest.j});\n        cout << farthest.i << \" \" << farthest.j << endl;\n        cout.flush();\n    }\n\n    // Determine the removal order\n    vector<Cell> removal_order;\n    while (removal_order.size() < total_containers) {\n        vector<Cell> removable = bfs_removable();\n        if (removable.empty()) {\n            cerr << \"No removable containers left!\" << endl;\n            return 1;\n        }\n\n        // Find the container with the smallest number among removable\n        int min_num = INT_MAX;\n        Cell to_remove;\n        for (const Cell& cell : removable) {\n            if (container_num[cell.i][cell.j] < min_num) {\n                min_num = container_num[cell.i][cell.j];\n                to_remove = cell;\n            }\n        }\n\n        removal_order.push_back(to_remove);\n        is_container[to_remove.i][to_remove.j] = false;\n    }\n\n    for (const Cell& cell : removal_order) {\n        cout << cell.i << \" \" << cell.j << endl;\n    }\n    cout.flush();\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int n = 50;\nconst int m = 100;\nconst int dx[] = {1, 0, -1, 0};\nconst int dy[] = {0, 1, 0, -1};\n\nstruct Cell {\n    int x, y;\n    Cell(int x = 0, int y = 0) : x(x), y(y) {}\n};\n\nvector<vector<int>> input_grid(n, vector<int>(n));\nvector<set<int>> adjacency(m + 1);\nvector<vector<Cell>> ward_cells(m + 1);\nvector<vector<bool>> is_boundary(n, vector<bool>(n, false));\n\nvoid read_input() {\n    cin >> n >> m;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> input_grid[i][j];\n            ward_cells[input_grid[i][j]].emplace_back(i, j);\n        }\n    }\n}\n\nvoid compute_adjacency() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            int c = input_grid[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = input_grid[ni][nj];\n                    if (nc != c) {\n                        adjacency[c].insert(nc);\n                        adjacency[nc].insert(c);\n                    }\n                } else {\n                    adjacency[c].insert(0);\n                    adjacency[0].insert(c);\n                }\n            }\n        }\n    }\n}\n\nvoid compute_boundary() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni < 0 || ni >= n || nj < 0 || nj >= n) {\n                    is_boundary[i][j] = true;\n                    break;\n                }\n            }\n        }\n    }\n}\n\nvector<vector<int>> create_initial_solution() {\n    vector<vector<int>> grid(n, vector<int>(n, 0));\n    vector<set<int>> required_adj(m + 1);\n    for (int c = 1; c <= m; ++c) {\n        required_adj[c] = adjacency[c];\n    }\n\n    // Place each ward as a single cell\n    vector<Cell> positions;\n    for (int c = 1; c <= m; ++c) {\n        if (!ward_cells[c].empty()) {\n            Cell pos = ward_cells[c][0];\n            grid[pos.x][pos.y] = c;\n            positions.emplace_back(pos.x, pos.y);\n        }\n    }\n\n    // Expand wards to satisfy adjacency\n    for (int c = 1; c <= m; ++c) {\n        if (ward_cells[c].empty()) continue;\n        queue<Cell> q;\n        vector<vector<bool>> visited(n, vector<bool>(n, false));\n        for (const auto& cell : ward_cells[c]) {\n            if (grid[cell.x][cell.y] == c) {\n                q.push(cell);\n                visited[cell.x][cell.y] = true;\n            }\n        }\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int ni = current.x + dx[d];\n                int nj = current.y + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj]) {\n                    int nc = grid[ni][nj];\n                    if (nc == 0) {\n                        if (required_adj[c].count(0) || !required_adj[c].empty()) {\n                            grid[ni][nj] = c;\n                            visited[ni][nj] = true;\n                            q.push(Cell(ni, nj));\n                        }\n                    } else if (nc != c) {\n                        if (required_adj[c].count(nc)) {\n                            required_adj[c].erase(nc);\n                            required_adj[nc].erase(c);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Ensure all adjacencies are satisfied\n    for (int c = 1; c <= m; ++c) {\n        if (!required_adj[c].empty()) {\n            for (int nc : required_adj[c]) {\n                if (nc == 0) continue;\n                // Find a cell of c and nc to connect\n                for (const auto& cell : ward_cells[c]) {\n                    if (grid[cell.x][cell.y] != c) continue;\n                    for (int d = 0; d < 4; ++d) {\n                        int ni = cell.x + dx[d];\n                        int nj = cell.y + dy[d];\n                        if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] == 0) {\n                            grid[ni][nj] = c;\n                            break;\n                        }\n                    }\n                    break;\n                }\n            }\n        }\n    }\n\n    return grid;\n}\n\nvoid optimize_solution(vector<vector<int>>& grid) {\n    // Simple optimization: try to replace color-0 cells with adjacent colors if possible\n    bool improved;\n    do {\n        improved = false;\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] != 0) continue;\n                set<int> adjacent_colors;\n                for (int d = 0; d < 4; ++d) {\n                    int ni = i + dx[d];\n                    int nj = j + dy[d];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                        adjacent_colors.insert(grid[ni][nj]);\n                    }\n                }\n                if (adjacent_colors.size() == 1) {\n                    int c = *adjacent_colors.begin();\n                    if (c != 0) {\n                        grid[i][j] = c;\n                        improved = true;\n                    }\n                }\n            }\n        }\n    } while (improved);\n}\n\nbool check_connectivity(const vector<vector<int>>& grid) {\n    for (int c = 1; c <= m; ++c) {\n        vector<vector<bool>> visited(n, vector<bool>(n, false));\n        queue<Cell> q;\n        bool found = false;\n        for (int i = 0; i < n && !found; ++i) {\n            for (int j = 0; j < n && !found; ++j) {\n                if (grid[i][j] == c) {\n                    q.push(Cell(i, j));\n                    visited[i][j] = true;\n                    found = true;\n                }\n            }\n        }\n        if (!found) continue;\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int ni = current.x + dx[d];\n                int nj = current.y + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj] && grid[ni][nj] == c) {\n                    visited[ni][nj] = true;\n                    q.push(Cell(ni, nj));\n                }\n            }\n        }\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] == c && !visited[i][j]) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool check_adjacency(const vector<vector<int>>& grid) {\n    vector<set<int>> current_adj(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            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = grid[ni][nj];\n                    if (nc != c) {\n                        current_adj[c].insert(nc);\n                        current_adj[nc].insert(c);\n                    }\n                } else {\n                    current_adj[c].insert(0);\n                    current_adj[0].insert(c);\n                }\n            }\n        }\n    }\n    for (int c = 0; c <= m; ++c) {\n        if (current_adj[c] != adjacency[c]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    read_input();\n    compute_adjacency();\n    compute_boundary();\n\n    vector<vector<int>> grid = create_initial_solution();\n    optimize_solution(grid);\n\n    // Verify the solution\n    if (!check_connectivity(grid) || !check_adjacency(grid)) {\n        // Fallback: output the original grid (though it may not be optimal)\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << input_grid[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n    } else {\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << grid[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <queue>\n#include <set>\n#include <map>\n#include <chrono>\n#include <cassert>\n\nusing namespace std;\nusing namespace std::chrono;\n\nstruct Item {\n    int id;\n    double weight;\n    bool operator<(const Item& other) const {\n        return weight > other.weight; // For max-heap\n    }\n};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nvector<int> solve(int N, int D, int Q) {\n    vector<double> weights(N, 1.0); // Initial guess\n    vector<vector<double>> constraints;\n    vector<int> comparison_results;\n\n    auto query = [&](const vector<int>& L, const vector<int>& R) {\n        cout << L.size() << \" \" << R.size();\n        for (int l : L) cout << \" \" << l;\n        for (int r : R) cout << \" \" << r;\n        cout << endl;\n        cout.flush();\n\n        string result;\n        cin >> result;\n        if (result == \"<\") return -1;\n        else if (result == \">\") return 1;\n        else return 0;\n    };\n\n    // Initial pairwise comparisons to establish order\n    for (int i = 0; i < N && Q > 0; ++i) {\n        for (int j = i + 1; j < N && Q > 0; ++j) {\n            vector<int> L = {i}, R = {j};\n            int res = query(L, R);\n            comparison_results.push_back(res);\n            Q--;\n            if (res == -1) {\n                weights[i] = 0.9 * weights[i];\n                weights[j] = 1.1 * weights[j];\n            } else if (res == 1) {\n                weights[i] = 1.1 * weights[i];\n                weights[j] = 0.9 * weights[j];\n            }\n        }\n    }\n\n    // Refine weights using more queries\n    while (Q > 0) {\n        vector<int> L, R;\n        uniform_int_distribution<int> dist(0, N - 1);\n        int size = min(5, N / 2);\n        set<int> used;\n        while (L.size() < size) {\n            int item = dist(rng);\n            if (used.count(item)) continue;\n            used.insert(item);\n            L.push_back(item);\n        }\n        used.clear();\n        while (R.size() < size) {\n            int item = dist(rng);\n            if (used.count(item) || find(L.begin(), L.end(), item) != L.end()) continue;\n            used.insert(item);\n            R.push_back(item);\n        }\n        if (L.empty() || R.empty()) continue;\n        int res = query(L, R);\n        Q--;\n        double sum_L = accumulate(L.begin(), L.end(), 0.0, [&](double s, int i) { return s + weights[i]; });\n        double sum_R = accumulate(R.begin(), R.end(), 0.0, [&](double s, int i) { return s + weights[i]; });\n        if (res == -1) {\n            for (int l : L) weights[l] *= 0.99;\n            for (int r : R) weights[r] *= 1.01;\n        } else if (res == 1) {\n            for (int l : L) weights[l] *= 1.01;\n            for (int r : R) weights[r] *= 0.99;\n        }\n    }\n\n    // Partition into D sets\n    vector<int> assignment(N, 0);\n    vector<double> set_sums(D, 0.0);\n    vector<Item> items;\n    for (int i = 0; i < N; ++i) {\n        items.push_back({i, weights[i]});\n    }\n    sort(items.begin(), items.end(), [](const Item& a, const Item& b) {\n        return a.weight > b.weight;\n    });\n\n    for (const auto& item : items) {\n        int best_set = 0;\n        double min_sum = set_sums[0];\n        for (int d = 1; d < D; ++d) {\n            if (set_sums[d] < min_sum) {\n                min_sum = set_sums[d];\n                best_set = d;\n            }\n        }\n        assignment[item.id] = best_set;\n        set_sums[best_set] += item.weight;\n    }\n\n    return assignment;\n}\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n\n    auto assignment = solve(N, D, Q);\n\n    for (int i = 0; i < N; ++i) {\n        cout << assignment[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n    cout.flush();\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Box {\n    int value;\n    int stack;\n    int pos; // position from bottom (0-based)\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n = 200, m = 10;\n    cin >> n >> m;\n\n    vector<vector<int>> stacks(m);\n    unordered_map<int, Box> box_info;\n    vector<int> next_box_pos(m, 0); // next position to check in each stack (from top)\n\n    for (int i = 0; i < m; ++i) {\n        stacks[i].resize(n / m);\n        for (int j = 0; j < n / m; ++j) {\n            cin >> stacks[i][j];\n            box_info[stacks[i][j]] = {stacks[i][j], i, j};\n        }\n    }\n\n    vector<pair<int, int>> operations;\n    int next_box = 1;\n    int total_energy = 0;\n    int max_operations = 5000;\n\n    auto get_top_box = [&](int stack_idx) {\n        if (stacks[stack_idx].empty()) return -1;\n        return stacks[stack_idx].back();\n    };\n\n    auto move_boxes = [&](int v, int dest_stack) {\n        int src_stack = box_info[v].stack;\n        int pos = box_info[v].pos;\n        int num_boxes = stacks[src_stack].size() - pos;\n        if (num_boxes <= 0) return false; // should not happen\n\n        // Remove boxes from src_stack\n        vector<int> moved_boxes;\n        for (int i = pos; i < stacks[src_stack].size(); ++i) {\n            moved_boxes.push_back(stacks[src_stack][i]);\n        }\n        stacks[src_stack].resize(pos);\n\n        // Add to dest_stack\n        for (int box : moved_boxes) {\n            stacks[dest_stack].push_back(box);\n            box_info[box].stack = dest_stack;\n            box_info[box].pos = stacks[dest_stack].size() - 1;\n        }\n\n        operations.emplace_back(v, dest_stack);\n        total_energy += num_boxes + 1;\n        return true;\n    };\n\n    auto carry_out = [&](int v) {\n        int stack = box_info[v].stack;\n        stacks[stack].pop_back();\n        operations.emplace_back(v, 0);\n    };\n\n    auto find_dest_stack = [&](int v) {\n        int src_stack = box_info[v].stack;\n        vector<int> candidates;\n        for (int i = 0; i < m; ++i) {\n            if (i == src_stack) continue;\n            if (stacks[i].empty()) {\n                candidates.push_back(i);\n                continue;\n            }\n            int top_box = get_top_box(i);\n            if (top_box > v) {\n                candidates.push_back(i);\n            }\n        }\n\n        if (candidates.empty()) {\n            for (int i = 0; i < m; ++i) {\n                if (i != src_stack) {\n                    candidates.push_back(i);\n                }\n            }\n        }\n\n        // Choose the stack with the smallest size\n        int best_stack = candidates[0];\n        for (int stack : candidates) {\n            if (stacks[stack].size() < stacks[best_stack].size()) {\n                best_stack = stack;\n            }\n        }\n        return best_stack;\n    };\n\n    while (next_box <= n && operations.size() < max_operations) {\n        int stack = box_info[next_box].stack;\n        int pos = box_info[next_box].pos;\n        if (pos == stacks[stack].size() - 1) {\n            carry_out(next_box);\n            next_box++;\n        } else {\n            int dest_stack = find_dest_stack(next_box);\n            move_boxes(next_box, dest_stack);\n        }\n    }\n\n    // Output operations\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <climits>\n#include <tuple>\n\nusing namespace std;\n\nconst int MAX_N = 40;\nconst int MAX_MOVES = 100000;\nconst vector<pair<int, int>> DIJ = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\nconst string DIR = \"RDLU\";\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<int>> dist;\nvector<vector<bool>> visited;\nstring route;\n\nvoid bfs() {\n    dist.assign(N, vector<int>(N, -1));\n    queue<pair<int, int>> q;\n    q.push({0, 0});\n    dist[0][0] = 0;\n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        for (int dir = 0; dir < 4; ++dir) {\n            auto [di, dj] = DIJ[dir];\n            int ni = i + di;\n            int nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (di == 0) {\n                if (dj == 1 && v[i][min(j, nj)] == '1') continue;\n                if (dj == -1 && v[i][min(j, nj)] == '1') continue;\n            } else {\n                if (di == 1 && h[min(i, ni)][j] == '1') continue;\n                if (di == -1 && h[min(i, ni)][j] == '1') continue;\n            }\n            if (dist[ni][nj] == -1) {\n                dist[ni][nj] = dist[i][j] + 1;\n                q.push({ni, nj});\n            }\n        }\n    }\n}\n\nvoid dfs(int i, int j) {\n    visited[i][j] = true;\n    vector<tuple<double, int, int, int>> neighbors; // priority, ni, nj, dir\n    for (int dir = 0; dir < 4; ++dir) {\n        auto [di, dj] = DIJ[dir];\n        int ni = i + di;\n        int nj = j + dj;\n        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n        if (visited[ni][nj]) continue;\n        if (di == 0) {\n            if (dj == 1 && v[i][min(j, nj)] == '1') continue;\n            if (dj == -1 && v[i][min(j, nj)] == '1') continue;\n        } else {\n            if (di == 1 && h[min(i, ni)][j] == '1') continue;\n            if (di == -1 && h[min(i, ni)][j] == '1') continue;\n        }\n        double priority = (double)d[ni][nj] / (dist[ni][nj] + 1);\n        neighbors.emplace_back(priority, ni, nj, dir);\n    }\n    sort(neighbors.rbegin(), neighbors.rend());\n    for (auto [priority, ni, nj, dir] : neighbors) {\n        route += DIR[dir];\n        dfs(ni, nj);\n        route += DIR[(dir + 2) % 4];\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; ++i) {\n        cin >> h[i];\n    }\n    v.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> v[i];\n    }\n    d.resize(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    bfs();\n    visited.assign(N, vector<bool>(N, false));\n    dfs(0, 0);\n\n    if (route.size() > MAX_MOVES) {\n        route = route.substr(0, MAX_MOVES);\n    }\n    cout << route << endl;\n\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 15;\nconst int M = 200;\nconst int MAX_OPERATIONS = 5000;\nconst int BEAM_WIDTH = 1000;\n\nstruct State {\n    string s;\n    int i, j;\n    bitset<M> covered;\n    int cost;\n    vector<pair<int, int>> path;\n\n    bool operator<(const State& other) const {\n        return cost > other.cost; // For min-heap\n    }\n};\n\nvector<string> t(M);\nvector<vector<pair<int, int>>> char_positions(26);\nvector<vector<vector<pair<int, int>>>> word_positions(M);\n\nint manhattan(int i1, int j1, int i2, int j2) {\n    return abs(i1 - i2) + abs(j1 - j2);\n}\n\nvoid preprocess(const vector<string>& grid) {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = grid[i][j];\n            char_positions[c - 'A'].emplace_back(i, j);\n        }\n    }\n\n    for (int k = 0; k < M; ++k) {\n        const string& word = t[k];\n        vector<vector<pair<int, int>>> positions;\n        for (char c : word) {\n            positions.push_back(char_positions[c - 'A']);\n        }\n        word_positions[k] = positions;\n    }\n}\n\nint estimate_remaining_cost(const State& state) {\n    int remaining = 0;\n    for (int k = 0; k < M; ++k) {\n        if (!state.covered[k]) {\n            remaining += 5; // Each word has 5 characters\n        }\n    }\n    return remaining;\n}\n\nvector<pair<int, int>> beam_search(const vector<string>& grid, int si, int sj) {\n    priority_queue<State> pq;\n    State initial;\n    initial.s = \"\";\n    initial.i = si;\n    initial.j = sj;\n    initial.cost = 0;\n    initial.path = {{si, sj}};\n    pq.push(initial);\n\n    vector<pair<int, int>> best_path;\n    int best_cost = INT_MAX;\n    bitset<M> best_covered;\n\n    while (!pq.empty() && pq.top().cost < best_cost) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.covered.all()) {\n            if (current.cost < best_cost) {\n                best_cost = current.cost;\n                best_path = current.path;\n                best_covered = current.covered;\n            }\n            continue;\n        }\n\n        if (current.path.size() >= MAX_OPERATIONS) {\n            continue;\n        }\n\n        // Generate next states\n        for (int c = 0; c < 26; ++c) {\n            for (auto [ni, nj] : char_positions[c]) {\n                int move_cost = manhattan(current.i, current.j, ni, nj) + 1;\n                State next = current;\n                next.s += ('A' + c);\n                next.i = ni;\n                next.j = nj;\n                next.cost += move_cost;\n                next.path.emplace_back(ni, nj);\n\n                // Check if new character helps cover any words\n                for (int k = 0; k < M; ++k) {\n                    if (!next.covered[k]) {\n                        const string& word = t[k];\n                        if (next.s.size() >= word.size()) {\n                            bool match = true;\n                            for (int l = 0; l < word.size(); ++l) {\n                                if (next.s[next.s.size() - word.size() + l] != word[l]) {\n                                    match = false;\n                                    break;\n                                }\n                            }\n                            if (match) {\n                                next.covered[k] = true;\n                            }\n                        }\n                    }\n                }\n\n                if (next.cost + estimate_remaining_cost(next) < best_cost) {\n                    pq.push(next);\n                    if (pq.size() > BEAM_WIDTH) {\n                        pq.pop();\n                    }\n                }\n            }\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, M_in;\n    cin >> N_in >> M_in;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> grid(N_in);\n    for (int i = 0; i < N_in; ++i) {\n        cin >> grid[i];\n    }\n    for (int k = 0; k < M_in; ++k) {\n        cin >> t[k];\n    }\n\n    preprocess(grid);\n    auto path = beam_search(grid, si, sj);\n\n    for (auto [i, j] : path) {\n        cout << i << \" \" << j << \"\\n\";\n    }\n\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int i, j;\n    Point(int i = 0, int j = 0) : i(i), j(j) {}\n};\n\nstruct OilField {\n    int d;\n    vector<Point> cells;\n};\n\nclass Solver {\nprivate:\n    int N, M;\n    double eps;\n    vector<OilField> fields;\n    vector<vector<int>> grid;\n    vector<vector<bool>> drilled;\n    vector<Point> oil_squares;\n\n    void read_input() {\n        cin >> N >> M >> eps;\n        fields.resize(M);\n\n        for (int k = 0; k < M; ++k) {\n            cin >> fields[k].d;\n            fields[k].cells.resize(fields[k].d);\n            for (int i = 0; i < fields[k].d; ++i) {\n                cin >> fields[k].cells[i].i >> fields[k].cells[i].j;\n            }\n        }\n    }\n\n    void drill_all() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << \"q 1 \" << i << \" \" << j << endl;\n                cout.flush();\n\n                int v;\n                cin >> v;\n                if (v > 0) {\n                    oil_squares.emplace_back(i, j);\n                }\n            }\n        }\n    }\n\npublic:\n    Solver() {\n        read_input();\n        grid.assign(N, vector<int>(N, 0));\n        drilled.assign(N, vector<bool>(N, false));\n    }\n\n    void solve() {\n        // Simple solution: drill all squares\n        drill_all();\n\n        // Output the answer\n        cout << \"a \" << oil_squares.size();\n        for (const auto& p : oil_squares) {\n            cout << \" \" << p.i << \" \" << p.j;\n        }\n        cout << endl;\n        cout.flush();\n\n        int correct;\n        cin >> correct;\n        if (correct != 1) {\n            // If wrong, try again with all squares (shouldn't happen)\n            cout << \"a \" << N*N;\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    cout << \" \" << i << \" \" << j;\n                }\n            }\n            cout << endl;\n            cout.flush();\n        }\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    Solver solver;\n    solver.solve();\n\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int W = 1000;\nconst int MAX_D = 50;\nconst int MAX_N = 50;\n\nstruct Rect {\n    int i1, j1, i2, j2;\n    Rect(int i1 = 0, int j1 = 0, int i2 = 0, int j2 = 0) : i1(i1), j1(j1), i2(i2), j2(j2) {}\n    int area() const { return (i2 - i1) * (j2 - j1); }\n};\n\nvector<vector<Rect>> solve(int D, int N, const vector<vector<int>>& a) {\n    vector<vector<Rect>> res(D, vector<Rect>(N));\n\n    // For each day, we'll partition the grid into N rectangles\n    for (int d = 0; d < D; ++d) {\n        vector<int> areas = a[d];\n        sort(areas.begin(), areas.end(), greater<int>());\n        vector<Rect> rects;\n        int remaining_height = W;\n        int remaining_width = W;\n        int current_i = 0;\n        int current_j = 0;\n\n        for (int k = 0; k < N; ++k) {\n            int target = areas[k];\n            if (k == N - 1) {\n                // Last rectangle takes the remaining space\n                rects.emplace_back(current_i, current_j, W, W);\n                break;\n            }\n            // Decide whether to split vertically or horizontally\n            int split_height = (target + remaining_width - 1) / remaining_width;\n            if (split_height > remaining_height) {\n                split_height = remaining_height;\n            }\n            int split_width = (target + split_height - 1) / split_height;\n            if (split_width > remaining_width) {\n                split_width = remaining_width;\n            }\n\n            // Try to split vertically first\n            int best_split = -1;\n            int best_diff = INT_MAX;\n            for (int split = 1; split <= remaining_width; ++split) {\n                int h = (target + split - 1) / split;\n                if (h > remaining_height) continue;\n                int diff = abs(target - split * h);\n                if (diff < best_diff) {\n                    best_diff = diff;\n                    best_split = split;\n                }\n            }\n            // Try to split horizontally\n            for (int split = 1; split <= remaining_height; ++split) {\n                int w = (target + split - 1) / split;\n                if (w > remaining_width) continue;\n                int diff = abs(target - split * w);\n                if (diff < best_diff) {\n                    best_diff = diff;\n                    best_split = -split; // negative indicates horizontal split\n                }\n            }\n\n            if (best_split > 0) {\n                // Vertical split\n                int split = best_split;\n                int h = (target + split - 1) / split;\n                rects.emplace_back(current_i, current_j, current_i + h, current_j + split);\n                current_j += split;\n                remaining_width -= split;\n            } else {\n                // Horizontal split\n                int split = -best_split;\n                int w = (target + split - 1) / split;\n                rects.emplace_back(current_i, current_j, current_i + split, current_j + w);\n                current_i += split;\n                remaining_height -= split;\n            }\n        }\n        res[d] = rects;\n    }\n\n    // Now, try to minimize partition changes between days\n    for (int d = 1; d < D; ++d) {\n        // For simplicity, we'll just use the same partitioning as the previous day\n        // and adjust the rectangles to meet the new area requirements\n        // This is a placeholder; a better approach would involve more sophisticated matching\n        res[d] = res[d-1];\n        for (int k = 0; k < N; ++k) {\n            int target = a[d][k];\n            Rect& r = res[d][k];\n            int current_area = r.area();\n            if (current_area < target) {\n                // Need to expand the rectangle\n                // Try to expand to the right or down\n                if (r.j2 < W) {\n                    int new_width = (target + (r.i2 - r.i1) - 1) / (r.i2 - r.i1);\n                    if (new_width > W - r.j1) new_width = W - r.j1;\n                    r.j2 = r.j1 + new_width;\n                } else if (r.i2 < W) {\n                    int new_height = (target + (r.j2 - r.j1) - 1) / (r.j2 - r.j1);\n                    if (new_height > W - r.i1) new_height = W - r.i1;\n                    r.i2 = r.i1 + new_height;\n                }\n            } else if (current_area > target) {\n                // Need to shrink the rectangle\n                // Try to shrink from the right or bottom\n                int shrink_area = current_area - target;\n                if (r.j2 > r.j1) {\n                    int shrink_width = min(shrink_area / (r.i2 - r.i1), r.j2 - r.j1 - 1);\n                    r.j2 -= shrink_width;\n                } else if (r.i2 > r.i1) {\n                    int shrink_height = min(shrink_area / (r.j2 - r.j1), r.i2 - r.i1 - 1);\n                    r.i2 -= shrink_height;\n                }\n            }\n        }\n    }\n\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int W_in, D, N;\n    cin >> W_in >> D >> 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    }\n\n    auto res = solve(D, N, a);\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            const auto& r = res[d][k];\n            cout << r.i1 << \" \" << r.j1 << \" \" << r.i2 << \" \" << r.j2 << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K_MAX = 81;\nconst int STAMP_SIZE = 3;\n\nint a[N][N];\nint s[M][STAMP_SIZE][STAMP_SIZE];\nint b[N][N];\nint d[N][N]; // deficit: MOD - 1 - (b[i][j] % MOD)\n\nstruct Operation {\n    int m, p, q;\n};\n\nvector<Operation> operations;\n\nvoid apply_stamp(int m, int p, int q) {\n    for (int i = 0; i < STAMP_SIZE; ++i) {\n        for (int j = 0; j < STAMP_SIZE; ++j) {\n            b[p + i][q + j] += s[m][i][j];\n        }\n    }\n}\n\nvoid update_deficits() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            d[i][j] = (MOD - 1 - (b[i][j] % MOD)) % MOD;\n        }\n    }\n}\n\nint compute_contribution(int m, int p, int q) {\n    int contribution = 0;\n    for (int i = 0; i < STAMP_SIZE; ++i) {\n        for (int j = 0; j < STAMP_SIZE; ++j) {\n            int ni = p + i;\n            int nj = q + j;\n            if (ni >= N || nj >= N) continue;\n            int add = min(s[m][i][j], d[ni][nj]);\n            contribution += add;\n        }\n    }\n    return contribution;\n}\n\nvoid greedy_solve() {\n    // Initialize b and d\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            b[i][j] = a[i][j];\n        }\n    }\n    update_deficits();\n\n    operations.clear();\n    for (int k = 0; k < K_MAX; ++k) {\n        int best_contribution = -1;\n        int best_m = -1, best_p = -1, best_q = -1;\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - STAMP_SIZE; ++p) {\n                for (int q = 0; q <= N - STAMP_SIZE; ++q) {\n                    int contribution = compute_contribution(m, p, q);\n                    if (contribution > best_contribution) {\n                        best_contribution = contribution;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_contribution <= 0) break;\n\n        operations.push_back({best_m, best_p, best_q});\n        apply_stamp(best_m, best_p, best_q);\n        update_deficits();\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, M_in, K_in;\n    cin >> N_in >> M_in >> K_in;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> a[i][j];\n        }\n    }\n    for (int m = 0; m < M; ++m) {\n        for (int i = 0; i < STAMP_SIZE; ++i) {\n            for (int j = 0; j < STAMP_SIZE; ++j) {\n                cin >> s[m][i][j];\n            }\n        }\n    }\n\n    greedy_solve();\n\n    cout << operations.size() << '\\n';\n    for (const auto& op : operations) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 5;\nconst int MAX_TURNS = 10000;\n\nstruct Container {\n    int id;\n    int target_gate;\n    int current_i, current_j;\n    bool is_held;\n    int held_by;\n};\n\nstruct Crane {\n    int id;\n    int i, j;\n    bool is_large;\n    bool is_holding;\n    int holding_id;\n    bool is_bombed;\n};\n\nvector<Container> containers;\nvector<Crane> cranes;\nvector<vector<int>> grid(N, vector<int>(N, -1)); // -1: empty, -2: crane, otherwise container id\nvector<vector<int>> A(N, vector<int>(N));\nvector<string> operations(N);\n\nvoid initialize() {\n    containers.clear();\n    cranes.clear();\n    grid.assign(N, vector<int>(N, -1));\n    operations.assign(N, \"\");\n\n    // Initialize cranes\n    for (int i = 0; i < N; ++i) {\n        cranes.push_back({i, i, 0, i == 0, false, -1, false});\n        grid[i][0] = -2; // Mark crane position\n    }\n\n    // Initialize containers\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int id = A[i][j];\n            int target_gate = id / N;\n            containers.push_back({id, target_gate, i, 0, false, -1});\n        }\n    }\n}\n\nbool is_valid_move(int crane_id, int di, int dj) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed) return false;\n    int ni = crane.i + di;\n    int nj = crane.j + dj;\n    if (ni < 0 || ni >= N || nj < 0 || nj >= N) return false;\n\n    // Check if destination is occupied by another crane\n    for (int i = 0; i < N; ++i) {\n        if (i == crane_id) continue;\n        if (cranes[i].i == ni && cranes[i].j == nj && !cranes[i].is_bombed) {\n            return false;\n        }\n    }\n\n    // Check if carrying and small crane\n    if (crane.is_holding && !crane.is_large) {\n        if (grid[ni][nj] != -1) return false; // Small crane cannot move to occupied square while carrying\n    }\n\n    return true;\n}\n\nvoid move_crane(int crane_id, char dir) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed) return;\n\n    int di = 0, dj = 0;\n    switch (dir) {\n        case 'U': di = -1; break;\n        case 'D': di = 1; break;\n        case 'L': dj = -1; break;\n        case 'R': dj = 1; break;\n        default: return;\n    }\n\n    if (!is_valid_move(crane_id, di, dj)) return;\n\n    // Update grid\n    grid[crane.i][crane.j] = -1;\n    crane.i += di;\n    crane.j += dj;\n    grid[crane.i][crane.j] = -2;\n}\n\nvoid pick_up(int crane_id) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed || crane.is_holding) return;\n\n    if (grid[crane.i][crane.j] != -1) {\n        int container_id = grid[crane.i][crane.j];\n        if (container_id >= 0 && container_id < N*N) {\n            containers[container_id].is_held = true;\n            containers[container_id].held_by = crane_id;\n            crane.is_holding = true;\n            crane.holding_id = container_id;\n            grid[crane.i][crane.j] = -1;\n        }\n    }\n}\n\nvoid release(int crane_id) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed || !crane.is_holding) return;\n\n    if (grid[crane.i][crane.j] == -1) {\n        int container_id = crane.holding_id;\n        containers[container_id].is_held = false;\n        containers[container_id].held_by = -1;\n        containers[container_id].current_i = crane.i;\n        containers[container_id].current_j = crane.j;\n        crane.is_holding = false;\n        crane.holding_id = -1;\n        grid[crane.i][crane.j] = container_id;\n    }\n}\n\nvoid bomb(int crane_id) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed || crane.is_holding) return;\n\n    crane.is_bombed = true;\n    grid[crane.i][crane.j] = -1;\n}\n\nvoid do_nothing(int crane_id) {\n    // Do nothing\n}\n\nvoid simulate_turn() {\n    // Step 1: Place new containers at Receiving Gates\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] == -1) {\n            for (int j = 0; j < N; ++j) {\n                int id = A[i][j];\n                if (!containers[id].is_held && containers[id].current_i == i && containers[id].current_j == 0) {\n                    grid[i][0] = id;\n                    containers[id].current_i = i;\n                    containers[id].current_j = 0;\n                    break;\n                }\n            }\n        }\n    }\n\n    // Step 2: Perform crane actions\n    for (int i = 0; i < N; ++i) {\n        if (operations[i].empty()) continue;\n        char action = operations[i].back();\n        operations[i].pop_back();\n\n        switch (action) {\n            case 'P': pick_up(i); break;\n            case 'Q': release(i); break;\n            case 'U': move_crane(i, 'U'); break;\n            case 'D': move_crane(i, 'D'); break;\n            case 'L': move_crane(i, 'L'); break;\n            case 'R': move_crane(i, 'R'); break;\n            case 'B': bomb(i); break;\n            case '.': do_nothing(i); break;\n        }\n    }\n\n    // Step 3: Dispatch containers at Dispatch Gates\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][N-1] != -1) {\n            int id = grid[i][N-1];\n            if (id >= 0 && id < N*N) {\n                grid[i][N-1] = -1;\n            }\n        }\n    }\n}\n\nvoid plan_operations() {\n    // Simple heuristic: move containers to their target gates\n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        bool all_dispatched = true;\n        for (const auto &container : containers) {\n            if (!container.is_held && grid[container.current_i][container.current_j] != -1) {\n                all_dispatched = false;\n                break;\n            }\n        }\n        if (all_dispatched) break;\n\n        for (int i = 0; i < N; ++i) {\n            Crane &crane = cranes[i];\n            if (crane.is_bombed) {\n                operations[i] += '.';\n                continue;\n            }\n\n            if (crane.is_holding) {\n                int container_id = crane.holding_id;\n                int target_gate = containers[container_id].target_gate;\n                int target_i = target_gate;\n                int target_j = N-1;\n\n                if (crane.i == target_i && crane.j == target_j) {\n                    operations[i] += 'Q';\n                } else {\n                    // Move towards target\n                    if (crane.j < target_j) {\n                        operations[i] += 'R';\n                    } else if (crane.j > target_j) {\n                        operations[i] += 'L';\n                    } else if (crane.i < target_i) {\n                        operations[i] += 'D';\n                    } else if (crane.i > target_i) {\n                        operations[i] += 'U';\n                    }\n                }\n            } else {\n                // Find the nearest container to pick up\n                int nearest_id = -1;\n                int min_dist = INT_MAX;\n                for (int id = 0; id < N*N; ++id) {\n                    if (!containers[id].is_held && grid[containers[id].current_i][containers[id].current_j] != -1) {\n                        int dist = abs(crane.i - containers[id].current_i) + abs(crane.j - containers[id].current_j);\n                        if (dist < min_dist) {\n                            min_dist = dist;\n                            nearest_id = id;\n                        }\n                    }\n                }\n\n                if (nearest_id != -1) {\n                    int target_i = containers[nearest_id].current_i;\n                    int target_j = containers[nearest_id].current_j;\n\n                    if (crane.i == target_i && crane.j == target_j) {\n                        operations[i] += 'P';\n                    } else {\n                        // Move towards container\n                        if (crane.j < target_j) {\n                            operations[i] += 'R';\n                        } else if (crane.j > target_j) {\n                            operations[i] += 'L';\n                        } else if (crane.i < target_i) {\n                            operations[i] += 'D';\n                        } else if (crane.i > target_i) {\n                            operations[i] += 'U';\n                        }\n                    }\n                } else {\n                    operations[i] += '.';\n                }\n            }\n        }\n\n        simulate_turn();\n    }\n\n    // Reverse operations to get correct order\n    for (int i = 0; i < N; ++i) {\n        reverse(operations[i].begin(), operations[i].end());\n    }\n}\n\nint main() {\n    cin >> N;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n        }\n    }\n\n    initialize();\n    plan_operations();\n\n    // Output operations\n    for (int i = 0; i < N; ++i) {\n        cout << operations[i] << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 20;\n    vector<vector<int>> grid(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> grid[i][j];\n        }\n    }\n\n    // Snake traversal order\n    vector<pair<int, int>> order;\n    for (int i = 0; i < N; ++i) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; ++j) {\n                order.emplace_back(i, j);\n            }\n        } else {\n            for (int j = N - 1; j >= 0; --j) {\n                order.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Current position and load\n    int x = 0, y = 0;\n    int load = 0;\n    vector<string> ops;\n\n    // Function to move to (nx, ny)\n    auto move_to = [&](int nx, int ny) {\n        while (x != nx || y != ny) {\n            if (x < nx) { ops.push_back(\"D\"); x++; }\n            else if (x > nx) { ops.push_back(\"U\"); x--; }\n            else if (y < ny) { ops.push_back(\"R\"); y++; }\n            else if (y > ny) { ops.push_back(\"L\"); y--; }\n        }\n    };\n\n    // Traverse in order\n    for (auto [i, j] : order) {\n        move_to(i, j);\n\n        // Load if positive\n        if (grid[i][j] > 0) {\n            int d = min(grid[i][j], 1000000);\n            ops.push_back(\"+\" + to_string(d));\n            grid[i][j] -= d;\n            load += d;\n        }\n        // Unload if negative and truck has load\n        else if (grid[i][j] < 0 && load > 0) {\n            int d = min(-grid[i][j], load);\n            ops.push_back(\"-\" + to_string(d));\n            grid[i][j] += d;\n            load -= d;\n        }\n    }\n\n    // Final unload if needed (should not happen, but safe)\n    if (load > 0) {\n        move_to(0, 0);\n        ops.push_back(\"-\" + to_string(load));\n    }\n\n    // Output all operations\n    for (const string& op : ops) {\n        cout << op << '\\n';\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Seed {\n    vector<int> eval;\n    int value;\n    int id;\n};\n\nbool compareSeeds(const Seed &a, const Seed &b) {\n    return a.value > b.value;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 6, M = 15, T = 10;\n    int seed_count = 2 * N * (N - 1);\n    vector<Seed> seeds(seed_count);\n\n    for (int i = 0; i < seed_count; ++i) {\n        seeds[i].eval.resize(M);\n        seeds[i].id = i;\n        for (int j = 0; j < M; ++j) {\n            cin >> seeds[i].eval[j];\n        }\n        seeds[i].value = accumulate(seeds[i].eval.begin(), seeds[i].eval.end(), 0);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        // Sort seeds by value in descending order\n        sort(seeds.begin(), seeds.end(), compareSeeds);\n\n        // Select top N*N seeds\n        vector<Seed> selected_seeds(seeds.begin(), seeds.begin() + N * N);\n\n        // Create a grid to place the selected seeds\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                grid[i][j] = selected_seeds[i * N + j].id;\n            }\n        }\n\n        // Output the grid\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << grid[i][j];\n                if (j < N - 1) {\n                    cout << \" \";\n                }\n            }\n            cout << endl;\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seed_count; ++i) {\n            seeds[i].eval.resize(M);\n            seeds[i].id = i;\n            for (int j = 0; j < M; ++j) {\n                cin >> seeds[i].eval[j];\n            }\n            seeds[i].value = accumulate(seeds[i].eval.begin(), seeds[i].eval.end(), 0);\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        return x < other.x || (x == other.x && y < other.y);\n    }\n};\n\nstruct Takoyaki {\n    Point source, target;\n    bool operator<(const Takoyaki& other) const {\n        return source < other.source || (source == other.source && target < other.target);\n    }\n};\n\nvector<Point> find_takoyaki(const vector<string>& grid, char c) {\n    vector<Point> res;\n    for (int i = 0; i < grid.size(); ++i) {\n        for (int j = 0; j < grid[i].size(); ++j) {\n            if (grid[i][j] == c) {\n                res.emplace_back(i, j);\n            }\n        }\n    }\n    return res;\n}\n\nvector<Takoyaki> create_takoyaki_list(const vector<Point>& sources, const vector<Point>& targets) {\n    vector<Takoyaki> res;\n    for (int i = 0; i < sources.size(); ++i) {\n        res.push_back({sources[i], targets[i]});\n    }\n    return res;\n}\n\nstruct TreeNode {\n    int parent;\n    int length;\n    TreeNode(int p = -1, int l = 1) : parent(p), length(l) {}\n};\n\nvector<TreeNode> design_tree(int V) {\n    vector<TreeNode> tree;\n    if (V == 1) {\n        return tree;\n    }\n    tree.emplace_back(0, 1);\n    if (V == 2) {\n        return tree;\n    }\n    tree.emplace_back(0, 2);\n    if (V == 3) {\n        return tree;\n    }\n    for (int i = 2; i < V; ++i) {\n        int p = (i - 1) / 2;\n        int l = 1 + (i % 2);\n        tree.emplace_back(p, l);\n    }\n    return tree;\n}\n\nPoint initial_root_position(int N, const vector<Takoyaki>& takoyakis) {\n    int sum_x = 0, sum_y = 0;\n    for (const auto& t : takoyakis) {\n        sum_x += t.source.x + t.target.x;\n        sum_y += t.source.y + t.target.y;\n    }\n    int cnt = 2 * takoyakis.size();\n    return Point(sum_x / cnt, sum_y / cnt);\n}\n\nvector<string> generate_operations(const vector<TreeNode>& tree, const Point& root_pos,\n                                   const vector<Takoyaki>& takoyakis, int N) {\n    vector<string> operations;\n    int V = tree.size() + 1;\n    vector<Point> fingertip_pos(V);\n    vector<int> dir(V, 0); // 0: right, 1: down, 2: left, 3: up\n    vector<bool> holding(V, false);\n    vector<Point> current_pos(V);\n    current_pos[0] = root_pos;\n\n    auto update_positions = [&]() {\n        for (int i = 1; i < V; ++i) {\n            int p = tree[i-1].parent;\n            int l = tree[i-1].length;\n            int dx = 0, dy = 0;\n            if (dir[i] == 0) { dx = l; }\n            else if (dir[i] == 1) { dy = l; }\n            else if (dir[i] == 2) { dx = -l; }\n            else if (dir[i] == 3) { dy = -l; }\n            current_pos[i] = Point(current_pos[p].x + dx, current_pos[p].y + dy);\n        }\n    };\n\n    update_positions();\n\n    auto move_root = [&](int dx, int dy) {\n        current_pos[0].x += dx;\n        current_pos[0].y += dy;\n        update_positions();\n    };\n\n    auto rotate_subtree = [&](int u, bool clockwise) {\n        if (clockwise) {\n            dir[u] = (dir[u] + 1) % 4;\n        } else {\n            dir[u] = (dir[u] + 3) % 4;\n        }\n        update_positions();\n    };\n\n    auto can_grab = [&](int u, const Point& p) {\n        return current_pos[u] == p && !holding[u];\n    };\n\n    auto can_release = [&](int u, const Point& p) {\n        return current_pos[u] == p && holding[u];\n    };\n\n    auto bfs_path = [&](Point start, Point target) {\n        vector<vector<int>> dist(N, vector<int>(N, -1));\n        vector<vector<Point>> prev(N, vector<Point>(N, Point(-1, -1)));\n        queue<Point> q;\n        dist[start.x][start.y] = 0;\n        q.push(start);\n        vector<int> dx = {0, 1, 0, -1};\n        vector<int> dy = {1, 0, -1, 0};\n        while (!q.empty()) {\n            Point p = q.front();\n            q.pop();\n            if (p == target) {\n                vector<Point> path;\n                while (p != start) {\n                    path.push_back(p);\n                    p = prev[p.x][p.y];\n                }\n                reverse(path.begin(), path.end());\n                return path;\n            }\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + dx[i];\n                int ny = p.y + dy[i];\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N && dist[nx][ny] == -1) {\n                    dist[nx][ny] = dist[p.x][p.y] + 1;\n                    prev[nx][ny] = p;\n                    q.emplace(nx, ny);\n                }\n            }\n        }\n        return vector<Point>();\n    };\n\n    auto move_to = [&](Point target) {\n        vector<Point> path = bfs_path(current_pos[0], target);\n        for (Point p : path) {\n            int dx = p.x - current_pos[0].x;\n            int dy = p.y - current_pos[0].y;\n            if (dx == 1) {\n                operations.push_back(\"D\" + string(V-1, '.') + string(V, '.'));\n                move_root(1, 0);\n            } else if (dx == -1) {\n                operations.push_back(\"U\" + string(V-1, '.') + string(V, '.'));\n                move_root(-1, 0);\n            } else if (dy == 1) {\n                operations.push_back(\"R\" + string(V-1, '.') + string(V, '.'));\n                move_root(0, 1);\n            } else if (dy == -1) {\n                operations.push_back(\"L\" + string(V-1, '.') + string(V, '.'));\n                move_root(0, -1);\n            }\n        }\n    };\n\n    auto align_fingertip = [&](int u, Point target) {\n        Point p = current_pos[u];\n        int dx = target.x - p.x;\n        int dy = target.y - p.y;\n        int required_dir = -1;\n        if (dx > 0 && dy == 0) required_dir = 0;\n        else if (dx == 0 && dy > 0) required_dir = 1;\n        else if (dx < 0 && dy == 0) required_dir = 2;\n        else if (dx == 0 && dy < 0) required_dir = 3;\n        if (required_dir == -1) return;\n        while (dir[u] != required_dir) {\n            bool clockwise = (dir[u] + 1) % 4 == required_dir;\n            string op(V*2, '.');\n            op[0] = '.';\n            op[u] = clockwise ? 'R' : 'L';\n            operations.push_back(op);\n            rotate_subtree(u, clockwise);\n        }\n    };\n\n    auto process_takoyaki = [&](const Takoyaki& t) {\n        // Move to source\n        move_to(t.source);\n        // Align fingertip to source\n        for (int u = 1; u < V; ++u) {\n            if (!holding[u]) {\n                align_fingertip(u, t.source);\n                if (can_grab(u, t.source)) {\n                    string op(V*2, '.');\n                    op[V + u] = 'P';\n                    operations.push_back(op);\n                    holding[u] = true;\n                    break;\n                }\n            }\n        }\n        // Move to target\n        move_to(t.target);\n        // Align fingertip to target\n        for (int u = 1; u < V; ++u) {\n            if (holding[u]) {\n                align_fingertip(u, t.target);\n                if (can_release(u, t.target)) {\n                    string op(V*2, '.');\n                    op[V + u] = 'P';\n                    operations.push_back(op);\n                    holding[u] = false;\n                    break;\n                }\n            }\n        }\n    };\n\n    for (const auto& t : takoyakis) {\n        process_takoyaki(t);\n    }\n\n    return operations;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, V;\n    cin >> N >> M >> V;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        cin >> t[i];\n    }\n\n    vector<Point> sources = find_takoyaki(s, '1');\n    vector<Point> targets = find_takoyaki(t, '1');\n    vector<Takoyaki> takoyakis = create_takoyaki_list(sources, targets);\n\n    vector<TreeNode> tree = design_tree(V);\n    Point root_pos = initial_root_position(N, takoyakis);\n\n    cout << tree.size() + 1 << '\\n';\n    for (const auto& node : tree) {\n        cout << node.parent << ' ' << node.length << '\\n';\n    }\n    cout << root_pos.x << ' ' << root_pos.y << '\\n';\n\n    vector<string> operations = generate_operations(tree, root_pos, takoyakis, N);\n    for (const string& op : operations) {\n        cout << op << '\\n';\n    }\n\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n    bool operator==(const Point& p) const {\n        return x == p.x && y == p.y;\n    }\n};\n\nint N;\nvector<Point> mackerels, sardines;\nvector<Point> polygon;\n\nbool is_inside(const vector<Point>& poly, const Point& p) {\n    int n = poly.size();\n    bool inside = false;\n    for (int i = 0, j = n - 1; i < n; j = i++) {\n        const Point& a = poly[i];\n        const Point& b = poly[j];\n        if (a.y == b.y) {\n            if (p.y == a.y && min(a.x, b.x) <= p.x && p.x <= max(a.x, b.x)) {\n                return true;\n            }\n            continue;\n        }\n        if ((a.y > p.y) != (b.y > p.y)) {\n            int x_intersect = (p.y - a.y) * (b.x - a.x) / (b.y - a.y) + a.x;\n            if (p.x == x_intersect) {\n                return true;\n            }\n            if (p.x < x_intersect) {\n                inside = !inside;\n            }\n        }\n    }\n    return inside;\n}\n\nint compute_score(const vector<Point>& poly) {\n    int a = 0, b = 0;\n    for (const Point& p : mackerels) {\n        if (is_inside(poly, p)) {\n            a++;\n        }\n    }\n    for (const Point& p : sardines) {\n        if (is_inside(poly, p)) {\n            b++;\n        }\n    }\n    return max(0, a - b + 1);\n}\n\nvector<Point> initial_polygon() {\n    int min_x = 1e9, max_x = -1, min_y = 1e9, max_y = -1;\n    for (const Point& p : mackerels) {\n        min_x = min(min_x, p.x);\n        max_x = max(max_x, p.x);\n        min_y = min(min_y, p.y);\n        max_y = max(max_y, p.y);\n    }\n    vector<Point> poly = {\n        {min_x, min_y},\n        {max_x, min_y},\n        {max_x, max_y},\n        {min_x, max_y}\n    };\n    return poly;\n}\n\nvector<Point> adjust_polygon(vector<Point> poly) {\n    int m = poly.size();\n    int total_length = 0;\n    for (int i = 0; i < m; ++i) {\n        int j = (i + 1) % m;\n        total_length += abs(poly[i].x - poly[j].x) + abs(poly[i].y - poly[j].y);\n    }\n\n    auto can_add_vertex = [&]() {\n        return poly.size() < 1000 && total_length < 400000;\n    };\n\n    auto add_vertex = [&](int edge_idx, Point new_vertex) {\n        if (!can_add_vertex()) return false;\n        int i = edge_idx;\n        int j = (i + 1) % poly.size();\n        int new_length = total_length - (abs(poly[i].x - poly[j].x) + abs(poly[i].y - poly[j].y))\n                         + (abs(poly[i].x - new_vertex.x) + abs(poly[i].y - new_vertex.y))\n                         + (abs(new_vertex.x - poly[j].x) + abs(new_vertex.y - poly[j].y));\n        if (new_length > 400000) return false;\n        poly.insert(poly.begin() + i + 1, new_vertex);\n        total_length = new_length;\n        return true;\n    };\n\n    auto move_vertex = [&](int vertex_idx, Point new_pos) {\n        int i = vertex_idx;\n        int prev = (i - 1 + poly.size()) % poly.size();\n        int next = (i + 1) % poly.size();\n        int old_length = abs(poly[prev].x - poly[i].x) + abs(poly[prev].y - poly[i].y)\n                       + abs(poly[i].x - poly[next].x) + abs(poly[i].y - poly[next].y);\n        int new_length = abs(poly[prev].x - new_pos.x) + abs(poly[prev].y - new_pos.y)\n                       + abs(new_pos.x - poly[next].x) + abs(new_pos.y - poly[next].y);\n        if (total_length - old_length + new_length > 400000) return false;\n        poly[i] = new_pos;\n        total_length = total_length - old_length + new_length;\n        return true;\n    };\n\n    auto try_improve = [&]() {\n        int best_score = compute_score(poly);\n        vector<Point> best_poly = poly;\n        for (int iter = 0; iter < 100; ++iter) {\n            int edge_idx = rand() % poly.size();\n            int i = edge_idx;\n            int j = (i + 1) % poly.size();\n            if (poly[i].x == poly[j].x) {\n                int x = poly[i].x;\n                int y_min = min(poly[i].y, poly[j].y);\n                int y_max = max(poly[i].y, poly[j].y);\n                for (int y = y_min + 1; y < y_max; ++y) {\n                    Point new_vertex(x, y);\n                    if (add_vertex(edge_idx, new_vertex)) {\n                        int score = compute_score(poly);\n                        if (score > best_score) {\n                            best_score = score;\n                            best_poly = poly;\n                        } else {\n                            poly = best_poly;\n                        }\n                    }\n                }\n            } else if (poly[i].y == poly[j].y) {\n                int y = poly[i].y;\n                int x_min = min(poly[i].x, poly[j].x);\n                int x_max = max(poly[i].x, poly[j].x);\n                for (int x = x_min + 1; x < x_max; ++x) {\n                    Point new_vertex(x, y);\n                    if (add_vertex(edge_idx, new_vertex)) {\n                        int score = compute_score(poly);\n                        if (score > best_score) {\n                            best_score = score;\n                            best_poly = poly;\n                        } else {\n                            poly = best_poly;\n                        }\n                    }\n                }\n            }\n            for (int vertex_idx = 0; vertex_idx < poly.size(); ++vertex_idx) {\n                Point original = poly[vertex_idx];\n                for (int dx = -1; dx <= 1; ++dx) {\n                    for (int dy = -1; dy <= 1; ++dy) {\n                        if (dx == 0 && dy == 0) continue;\n                        Point new_pos(original.x + dx, original.y + dy);\n                        if (move_vertex(vertex_idx, new_pos)) {\n                            int score = compute_score(poly);\n                            if (score > best_score) {\n                                best_score = score;\n                                best_poly = poly;\n                            } else {\n                                poly = best_poly;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        return best_poly;\n    };\n\n    return try_improve();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    mackerels.resize(N);\n    sardines.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> mackerels[i].x >> mackerels[i].y;\n    }\n    for (int i = 0; i < N; ++i) {\n        cin >> sardines[i].x >> sardines[i].y;\n    }\n\n    polygon = initial_polygon();\n    polygon = adjust_polygon(polygon);\n\n    cout << polygon.size() << '\\n';\n    for (const Point& p : polygon) {\n        cout << p.x << ' ' << p.y << '\\n';\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <climits>\n#include <iomanip>\n#include <chrono>\n#include <map>\n#include <set>\n\nusing namespace std;\nusing namespace std::chrono;\n\nstruct Rectangle {\n    int id;\n    int w, h;\n    int x, y;\n    bool rotated;\n};\n\nstruct Placement {\n    int p, r;\n    char d;\n    int b;\n};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint normal_round(double value, int sigma) {\n    normal_distribution<double> dist(value, sigma);\n    double sample = dist(rng);\n    int rounded = static_cast<int>(round(sample));\n    if (rounded < 1) rounded = 1;\n    if (rounded > 1e9) rounded = 1e9;\n    return rounded;\n}\n\nvector<Rectangle> place_rectangles(const vector<pair<int, int>>& observed, const vector<Placement>& placements) {\n    vector<Rectangle> placed;\n    for (const auto& pl : placements) {\n        int id = pl.p;\n        bool rotated = pl.r;\n        int w = observed[id].first;\n        int h = observed[id].second;\n        if (rotated) swap(w, h);\n\n        int x = 0, y = 0;\n        if (pl.d == 'U') {\n            if (pl.b == -1) {\n                x = 0;\n            } else {\n                x = placed[pl.b].x + placed[pl.b].w;\n            }\n            int max_y = 0;\n            for (const auto& rect : placed) {\n                if (rect.x < x + w && rect.x + rect.w > x) {\n                    if (rect.y + rect.h > max_y) {\n                        max_y = rect.y + rect.h;\n                    }\n                }\n            }\n            y = max_y;\n        } else if (pl.d == 'L') {\n            if (pl.b == -1) {\n                y = 0;\n            } else {\n                y = placed[pl.b].y + placed[pl.b].h;\n            }\n            int max_x = 0;\n            for (const auto& rect : placed) {\n                if (rect.y < y + h && rect.y + rect.h > y) {\n                    if (rect.x + rect.w > max_x) {\n                        max_x = rect.x + rect.w;\n                    }\n                }\n            }\n            x = max_x;\n        }\n        placed.push_back({id, w, h, x, y, rotated});\n    }\n    return placed;\n}\n\npair<int, int> calculate_dimensions(const vector<Rectangle>& placed) {\n    int max_x = 0, max_y = 0;\n    for (const auto& rect : placed) {\n        max_x = max(max_x, rect.x + rect.w);\n        max_y = max(max_y, rect.y + rect.h);\n    }\n    return {max_x, max_y};\n}\n\nvector<Placement> generate_placements(const vector<pair<int, int>>& observed, int T, int sigma) {\n    int N = observed.size();\n    vector<Placement> best_placements;\n    int best_score = INT_MAX;\n\n    for (int t = 0; t < T; ++t) {\n        vector<Placement> placements;\n        vector<bool> used(N, false);\n        int current_score = 0;\n        int max_x = 0, max_y = 0;\n\n        for (int i = 0; i < N; ++i) {\n            int best_p = -1, best_r = -1, best_b = -1;\n            char best_d = 'U';\n            int min_increase = INT_MAX;\n\n            for (int p = 0; p < N; ++p) {\n                if (used[p]) continue;\n                for (int r = 0; r < 2; ++r) {\n                    for (char d : {'U', 'L'}) {\n                        int b_start = (d == 'U') ? -1 : -1;\n                        int b_end = (int)placements.size() - 1;\n                        for (int b = b_start; b <= b_end; ++b) {\n                            placements.push_back({p, r, d, b});\n                            auto placed = place_rectangles(observed, placements);\n                            auto [W, H] = calculate_dimensions(placed);\n                            int increase = W + H;\n                            int unused = 0;\n                            for (int j = 0; j < N; ++j) {\n                                if (!used[j]) {\n                                    unused += observed[j].first + observed[j].second;\n                                }\n                            }\n                            int score = increase + unused;\n                            if (score < min_increase) {\n                                min_increase = score;\n                                best_p = p;\n                                best_r = r;\n                                best_d = d;\n                                best_b = b;\n                            }\n                            placements.pop_back();\n                        }\n                    }\n                }\n            }\n\n            if (best_p == -1) break;\n            placements.push_back({best_p, best_r, best_d, best_b});\n            used[best_p] = true;\n        }\n\n        auto placed = place_rectangles(observed, placements);\n        auto [W, H] = calculate_dimensions(placed);\n        int unused = 0;\n        for (int i = 0; i < N; ++i) {\n            bool found = false;\n            for (const auto& rect : placed) {\n                if (rect.id == i) {\n                    found = true;\n                    break;\n                }\n            }\n            if (!found) {\n                unused += observed[i].first + observed[i].second;\n            }\n        }\n        int score = W + H + unused;\n        if (score < best_score) {\n            best_score = score;\n            best_placements = placements;\n        }\n    }\n\n    return best_placements;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n    vector<pair<int, int>> observed(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> observed[i].first >> observed[i].second;\n    }\n\n    for (int t = 0; t < T; ++t) {\n        vector<Placement> placements;\n        vector<bool> used(N, false);\n        int max_x = 0, max_y = 0;\n\n        for (int i = 0; i < N; ++i) {\n            int best_p = -1, best_r = -1, best_b = -1;\n            char best_d = 'U';\n            int min_increase = INT_MAX;\n\n            for (int p = 0; p < N; ++p) {\n                if (used[p]) continue;\n                for (int r = 0; r < 2; ++r) {\n                    for (char d : {'U', 'L'}) {\n                        int b_start = (d == 'U') ? -1 : -1;\n                        int b_end = (int)placements.size() - 1;\n                        for (int b = b_start; b <= b_end; ++b) {\n                            placements.push_back({p, r, d, b});\n                            auto placed = place_rectangles(observed, placements);\n                            auto [W, H] = calculate_dimensions(placed);\n                            int increase = W + H;\n                            if (increase < min_increase) {\n                                min_increase = increase;\n                                best_p = p;\n                                best_r = r;\n                                best_d = d;\n                                best_b = b;\n                            }\n                            placements.pop_back();\n                        }\n                    }\n                }\n            }\n\n            if (best_p == -1) break;\n            placements.push_back({best_p, best_r, best_d, best_b});\n            used[best_p] = true;\n        }\n\n        cout << placements.size() << '\\n';\n        for (const auto& pl : placements) {\n            cout << pl.p << ' ' << pl.r << ' ' << pl.d << ' ' << pl.b << '\\n';\n        }\n        cout.flush();\n\n        int W_prime, H_prime;\n        cin >> W_prime >> H_prime;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <set>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nstruct Vertex {\n    int id;\n    int a;\n    int x, y;\n    vector<int> neighbors;\n};\n\nstruct BFSState {\n    int vertex;\n    int parent;\n    int depth;\n    bool operator<(const BFSState& other) const {\n        if (depth != other.depth) return depth > other.depth;\n        return a[vertex] < a[other.vertex];\n    }\n    static vector<int> a;\n};\n\nvector<int> BFSState::a;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    cin >> N >> M >> H;\n\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> A[i];\n    }\n    BFSState::a = A;\n\n    vector<pair<int, int>> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].first >> edges[i].second;\n    }\n\n    vector<pair<int, int>> coords(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> coords[i].first >> coords[i].second;\n    }\n\n    vector<Vertex> vertices(N);\n    for (int i = 0; i < N; ++i) {\n        vertices[i].id = i;\n        vertices[i].a = A[i];\n        vertices[i].x = coords[i].first;\n        vertices[i].y = coords[i].second;\n    }\n\n    for (const auto& edge : edges) {\n        int u = edge.first;\n        int v = edge.second;\n        vertices[u].neighbors.push_back(v);\n        vertices[v].neighbors.push_back(u);\n    }\n\n    vector<int> parent(N, -1);\n    vector<bool> assigned(N, false);\n\n    while (true) {\n        int root = -1;\n        int max_a = -1;\n        for (int i = 0; i < N; ++i) {\n            if (!assigned[i] && A[i] > max_a) {\n                max_a = A[i];\n                root = i;\n            }\n        }\n        if (root == -1) break;\n\n        priority_queue<BFSState> pq;\n        pq.push({root, -1, 0});\n        vector<bool> visited(N, false);\n        visited[root] = true;\n\n        while (!pq.empty()) {\n            BFSState current = pq.top();\n            pq.pop();\n            if (current.depth > H) continue;\n            if (assigned[current.vertex]) continue;\n\n            parent[current.vertex] = current.parent;\n            assigned[current.vertex] = true;\n\n            for (int neighbor : vertices[current.vertex].neighbors) {\n                if (!visited[neighbor] && !assigned[neighbor]) {\n                    visited[neighbor] = true;\n                    pq.push({neighbor, current.vertex, current.depth + 1});\n                }\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <set>\n#include <map>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_MOVES = 4 * N * N;\n\nstruct Piece {\n    int i, j;\n    char type; // 'x' for Oni, 'o' for Fukunokami\n};\n\nvector<string> board;\nvector<Piece> oni_list;\nvector<Piece> fuku_list;\nvector<vector<bool>> safe_up, safe_down, safe_left, safe_right;\n\nvoid preprocess() {\n    // Initialize safe directions\n    safe_up.assign(N, vector<bool>(N, true));\n    safe_down.assign(N, vector<bool>(N, true));\n    safe_left.assign(N, vector<bool>(N, true));\n    safe_right.assign(N, vector<bool>(N, true));\n\n    // Mark unsafe directions for Oni\n    for (const auto& fuku : fuku_list) {\n        int i = fuku.i, j = fuku.j;\n        // Up: all squares above (i,j) in column j are unsafe for Oni below\n        for (int k = 0; k < i; ++k) {\n            safe_down[k][j] = false;\n        }\n        // Down: all squares below (i,j) in column j are unsafe for Oni above\n        for (int k = i + 1; k < N; ++k) {\n            safe_up[k][j] = false;\n        }\n        // Left: all squares left of (i,j) in row i are unsafe for Oni to the right\n        for (int k = 0; k < j; ++k) {\n            safe_right[i][k] = false;\n        }\n        // Right: all squares right of (i,j) in row i are unsafe for Oni to the left\n        for (int k = j + 1; k < N; ++k) {\n            safe_left[i][k] = false;\n        }\n    }\n}\n\nvector<pair<char, int>> moves;\n\nvoid shift_row_left(int i) {\n    moves.emplace_back('L', i);\n    char first = board[i][0];\n    for (int j = 0; j < N - 1; ++j) {\n        board[i][j] = board[i][j + 1];\n    }\n    board[i][N - 1] = '.';\n}\n\nvoid shift_row_right(int i) {\n    moves.emplace_back('R', i);\n    char last = board[i][N - 1];\n    for (int j = N - 1; j > 0; --j) {\n        board[i][j] = board[i][j - 1];\n    }\n    board[i][0] = '.';\n}\n\nvoid shift_col_up(int j) {\n    moves.emplace_back('U', j);\n    char first = board[0][j];\n    for (int i = 0; i < N - 1; ++i) {\n        board[i][j] = board[i + 1][j];\n    }\n    board[N - 1][j] = '.';\n}\n\nvoid shift_col_down(int j) {\n    moves.emplace_back('D', j);\n    char last = board[N - 1][j];\n    for (int i = N - 1; i > 0; --i) {\n        board[i][j] = board[i - 1][j];\n    }\n    board[0][j] = '.';\n}\n\nvoid remove_oni() {\n    while (true) {\n        // Check if all Oni are removed\n        bool all_removed = true;\n        for (const auto& row : board) {\n            if (row.find('x') != string::npos) {\n                all_removed = false;\n                break;\n            }\n        }\n        if (all_removed) break;\n\n        // Find the row or column with the most removable Oni\n        int max_oni = 0;\n        char best_dir = ' ';\n        int best_idx = -1;\n\n        // Check rows for left/right shifts\n        for (int i = 0; i < N; ++i) {\n            int left_oni = 0, right_oni = 0;\n            for (int j = 0; j < N; ++j) {\n                if (board[i][j] == 'x') {\n                    if (safe_left[i][j]) left_oni++;\n                    if (safe_right[i][j]) right_oni++;\n                }\n            }\n            if (left_oni > max_oni) {\n                max_oni = left_oni;\n                best_dir = 'L';\n                best_idx = i;\n            }\n            if (right_oni > max_oni) {\n                max_oni = right_oni;\n                best_dir = 'R';\n                best_idx = i;\n            }\n        }\n\n        // Check columns for up/down shifts\n        for (int j = 0; j < N; ++j) {\n            int up_oni = 0, down_oni = 0;\n            for (int i = 0; i < N; ++i) {\n                if (board[i][j] == 'x') {\n                    if (safe_up[i][j]) up_oni++;\n                    if (safe_down[i][j]) down_oni++;\n                }\n            }\n            if (up_oni > max_oni) {\n                max_oni = up_oni;\n                best_dir = 'U';\n                best_idx = j;\n            }\n            if (down_oni > max_oni) {\n                max_oni = down_oni;\n                best_dir = 'D';\n                best_idx = j;\n            }\n        }\n\n        if (max_oni == 0) {\n            // No removable Oni found (should not happen due to problem guarantee)\n            break;\n        }\n\n        // Perform the best shift\n        if (best_dir == 'L') shift_row_left(best_idx);\n        else if (best_dir == 'R') shift_row_right(best_idx);\n        else if (best_dir == 'U') shift_col_up(best_idx);\n        else if (best_dir == 'D') shift_col_down(best_idx);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    board.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n    }\n\n    // Collect Oni and Fukunokami positions\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                oni_list.push_back({i, j, 'x'});\n            } else if (board[i][j] == 'o') {\n                fuku_list.push_back({i, j, 'o'});\n            }\n        }\n    }\n\n    preprocess();\n    remove_oni();\n\n    // Output the moves\n    for (const auto& move : moves) {\n        cout << move.first << \" \" << move.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <climits>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 100;\nconst int L = 500000;\n\nstruct Employee {\n    int a, b;\n};\n\nvector<int> simulate(const vector<Employee>& employees, const vector<int>& T) {\n    vector<int> t(N, 0);\n    int current = 0;\n    t[current]++;\n    for (int week = 1; week < L; ++week) {\n        int cnt = t[current];\n        if (cnt % 2 == 1) {\n            current = employees[current].a;\n        } else {\n            current = employees[current].b;\n        }\n        t[current]++;\n    }\n    return t;\n}\n\nlong long calculate_error(const vector<int>& t, const vector<int>& T) {\n    long long error = 0;\n    for (int i = 0; i < N; ++i) {\n        error += abs(t[i] - T[i]);\n    }\n    return error;\n}\n\nvector<Employee> greedy_initial(const vector<int>& T) {\n    vector<Employee> employees(N);\n    vector<int> current_t(N, 0);\n    current_t[0] = 1;\n    int current = 0;\n    for (int week = 1; week < L; ++week) {\n        int cnt = current_t[current];\n        vector<pair<int, int>> candidates;\n        for (int i = 0; i < N; ++i) {\n            candidates.emplace_back(T[i] - current_t[i], i);\n        }\n        sort(candidates.rbegin(), candidates.rend());\n        int next = candidates[0].second;\n        if (cnt % 2 == 1) {\n            employees[current].a = next;\n        } else {\n            employees[current].b = next;\n        }\n        current = next;\n        current_t[current]++;\n    }\n    return employees;\n}\n\nvector<Employee> local_search(const vector<int>& T, vector<Employee> employees, int max_iter = 1000) {\n    auto t = simulate(employees, T);\n    long long best_error = calculate_error(t, T);\n    vector<Employee> best_employees = employees;\n\n    for (int iter = 0; iter < max_iter; ++iter) {\n        bool improved = false;\n        for (int i = 0; i < N; ++i) {\n            for (int new_a = 0; new_a < N; ++new_a) {\n                if (new_a == employees[i].a) continue;\n                auto old_a = employees[i].a;\n                employees[i].a = new_a;\n                auto new_t = simulate(employees, T);\n                long long new_error = calculate_error(new_t, T);\n                if (new_error < best_error) {\n                    best_error = new_error;\n                    best_employees = employees;\n                    improved = true;\n                } else {\n                    employees[i].a = old_a;\n                }\n            }\n            for (int new_b = 0; new_b < N; ++new_b) {\n                if (new_b == employees[i].b) continue;\n                auto old_b = employees[i].b;\n                employees[i].b = new_b;\n                auto new_t = simulate(employees, T);\n                long long new_error = calculate_error(new_t, T);\n                if (new_error < best_error) {\n                    best_error = new_error;\n                    best_employees = employees;\n                    improved = true;\n                } else {\n                    employees[i].b = old_b;\n                }\n            }\n        }\n        if (!improved) break;\n        employees = best_employees;\n    }\n    return best_employees;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, L_in;\n    cin >> N_in >> L_in;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    auto employees = greedy_initial(T);\n    employees = local_search(T, employees);\n\n    for (const auto& emp : employees) {\n        cout << emp.a << \" \" << emp.b << \"\\n\";\n    }\n\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct City {\n    int lx, rx, ly, ry;\n    int x, y; // Estimated coordinates\n};\n\nint N, M, Q, L, W;\nvector<int> G;\nvector<City> cities;\nvector<vector<int>> groups;\nvector<vector<pair<int, int>>> edges;\n\nvector<pair<int, int>> query(const vector<int>& C) {\n    cout << \"? \" << C.size();\n    for (int c : C) cout << \" \" << c;\n    cout << endl;\n    cout.flush();\n\n    vector<pair<int, int>> res;\n    for (int i = 0; i < (int)C.size() - 1; ++i) {\n        int a, b;\n        cin >> a >> b;\n        res.emplace_back(a, b);\n    }\n    return res;\n}\n\nvoid answer() {\n    cout << \"!\" << endl;\n    for (int k = 0; k < M; ++k) {\n        for (int c : groups[k]) cout << c << \" \";\n        cout << endl;\n        for (auto [a, b] : edges[k]) {\n            cout << a << \" \" << b << endl;\n        }\n    }\n    cout.flush();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M >> Q >> L >> W;\n    G.resize(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    cities.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].x = (cities[i].lx + cities[i].rx) / 2;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2;\n    }\n\n    // Initial grouping based on estimated coordinates\n    vector<int> city_indices(N);\n    iota(city_indices.begin(), city_indices.end(), 0);\n    sort(city_indices.begin(), city_indices.end(), [&](int a, int b) {\n        if (cities[a].x != cities[b].x) return cities[a].x < cities[b].x;\n        return cities[a].y < cities[b].y;\n    });\n\n    groups.resize(M);\n    int start = 0;\n    for (int k = 0; k < M; ++k) {\n        for (int i = 0; i < G[k]; ++i) {\n            groups[k].push_back(city_indices[start + i]);\n        }\n        start += G[k];\n    }\n\n    // Perform queries to get MST edges\n    edges.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int n = groups[k].size();\n        if (n == 1) continue;\n        if (n == 2) {\n            edges[k].emplace_back(groups[k][0], groups[k][1]);\n            continue;\n        }\n        for (int i = 0; i < n - 1; i += L - 1) {\n            int end = min(i + L, n);\n            vector<int> subset(groups[k].begin() + i, groups[k].begin() + end);\n            auto res = query(subset);\n            for (auto [a, b] : res) {\n                edges[k].emplace_back(a, b);\n            }\n        }\n    }\n\n    // Refinement step: Ensure each group is connected\n    for (int k = 0; k < M; ++k) {\n        if (groups[k].size() == 1) continue;\n        dsu d(groups[k].size());\n        for (auto [a, b] : edges[k]) {\n            int u = find(groups[k].begin(), groups[k].end(), a) - groups[k].begin();\n            int v = find(groups[k].begin(), groups[k].end(), b) - groups[k].begin();\n            d.merge(u, v);\n        }\n        if (d.size(0) != groups[k].size()) {\n            // Need to add more edges to connect the group\n            for (int i = 1; i < groups[k].size(); ++i) {\n                if (!d.same(0, i)) {\n                    edges[k].emplace_back(groups[k][0], groups[k][i]);\n                    d.merge(0, i);\n                }\n            }\n        }\n    }\n\n    answer();\n\n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\nconst int M = 40;\nconst int MAX_ACTIONS = 2 * N * M;\nconst int BEAM_WIDTH = 100;\n\nstruct State {\n    int i, j;\n    vector<vector<bool>> blocks;\n    int next_target;\n    vector<pair<char, char>> actions;\n    int score;\n\n    State(int i, int j, vector<vector<bool>> blocks, int next_target, vector<pair<char, char>> actions)\n        : i(i), j(j), blocks(blocks), next_target(next_target), actions(actions), score(0) {}\n\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n};\n\nvector<pair<int, int>> targets;\n\nint manhattan(int i1, int j1, int i2, int j2) {\n    return abs(i1 - i2) + abs(j1 - j2);\n}\n\nbool is_blocked(int i, int j, const vector<vector<bool>>& blocks) {\n    if (i < 0 || i >= N || j < 0 || j >= N) return true;\n    return blocks[i][j];\n}\n\nvector<State> expand(const State& state) {\n    vector<State> next_states;\n    vector<char> actions = {'M', 'S', 'A'};\n    vector<char> directions = {'U', 'D', 'L', 'R'};\n\n    for (char a : actions) {\n        for (char d : directions) {\n            State new_state = state;\n            new_state.actions.emplace_back(a, d);\n            int di = 0, dj = 0;\n            if (d == 'U') di = -1;\n            if (d == 'D') di = 1;\n            if (d == 'L') dj = -1;\n            if (d == 'R') dj = 1;\n\n            if (a == 'M') {\n                int ni = state.i + di, nj = state.j + dj;\n                if (!is_blocked(ni, nj, state.blocks)) {\n                    new_state.i = ni;\n                    new_state.j = nj;\n                } else {\n                    continue;\n                }\n            } else if (a == 'S') {\n                int ni = state.i, nj = state.j;\n                while (true) {\n                    int nni = ni + di, nnj = nj + dj;\n                    if (is_blocked(nni, nnj, state.blocks)) break;\n                    ni = nni;\n                    nj = nnj;\n                }\n                new_state.i = ni;\n                new_state.j = nj;\n            } else if (a == 'A') {\n                int ni = state.i + di, nj = state.j + dj;\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                new_state.blocks[ni][nj] = !new_state.blocks[ni][nj];\n            }\n\n            // Check if next target is reached\n            if (new_state.next_target < M &&\n                new_state.i == targets[new_state.next_target].first &&\n                new_state.j == targets[new_state.next_target].second) {\n                new_state.next_target++;\n            }\n\n            // Evaluate score\n            int dist = 0;\n            if (new_state.next_target < M) {\n                dist = manhattan(new_state.i, new_state.j, targets[new_state.next_target].first, targets[new_state.next_target].second);\n            }\n            new_state.score = -new_state.actions.size() - dist - (M - new_state.next_target) * 100;\n            next_states.push_back(new_state);\n        }\n    }\n    return next_states;\n}\n\nvector<pair<char, char>> beam_search(int start_i, int start_j) {\n    vector<vector<bool>> initial_blocks(N, vector<bool>(N, false));\n    State initial_state(start_i, start_j, initial_blocks, 0, {});\n    priority_queue<State> beam;\n    beam.push(initial_state);\n\n    for (int step = 0; step < MAX_ACTIONS; ++step) {\n        priority_queue<State> next_beam;\n        for (int i = 0; i < BEAM_WIDTH && !beam.empty(); ++i) {\n            State current = beam.top();\n            beam.pop();\n            if (current.next_target == M) {\n                return current.actions;\n            }\n            vector<State> next_states = expand(current);\n            for (State& next_state : next_states) {\n                if (next_state.actions.size() <= MAX_ACTIONS) {\n                    next_beam.push(next_state);\n                }\n            }\n        }\n        beam = move(next_beam);\n    }\n\n    // Return the best found\n    State best = beam.top();\n    return best.actions;\n}\n\nint main() {\n    int N_in, M_in;\n    cin >> N_in >> M_in;\n    targets.resize(M_in);\n    for (int i = 0; i < M_in; ++i) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n\n    vector<pair<char, char>> actions = beam_search(targets[0].first, targets[0].second);\n    for (auto [a, d] : actions) {\n        cout << a << \" \" << d << \"\\n\";\n    }\n    return 0;\n}"},"4":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Rect {\n    int a, b, c, d;\n    int area() const { return (c - a) * (d - b); }\n    bool contains(int x, int y) const {\n        return a <= x && x < c && b <= y && y < d;\n    }\n    bool overlaps(const Rect& other) const {\n        return !(c <= other.a || other.c <= a || d <= other.b || other.d <= b);\n    }\n};\n\nstruct Company {\n    int x, y, r;\n    Rect rect;\n    double satisfaction() const {\n        int s = rect.area();\n        if (s == 0) return 0.0;\n        double ratio = min(r, s) * 1.0 / max(r, s);\n        return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n    }\n};\n\nint n;\nvector<Company> companies;\nvector<Rect> placed_rects;\n\nbool is_valid(const Rect& rect, int ignore = -1) {\n    for (int i = 0; i < placed_rects.size(); ++i) {\n        if (i == ignore) continue;\n        if (rect.overlaps(placed_rects[i])) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid place_rect(const Rect& rect) {\n    placed_rects.push_back(rect);\n}\n\nvoid remove_rect(int id) {\n    placed_rects.erase(placed_rects.begin() + id);\n}\n\ndouble total_satisfaction() {\n    double total = 0.0;\n    for (const auto& company : companies) {\n        total += company.satisfaction();\n    }\n    return total;\n}\n\nvoid greedy_initialization() {\n    for (auto& company : companies) {\n        int x = company.x;\n        int y = company.y;\n        // Start with a 1x1 rectangle\n        company.rect = {x, y, x + 1, y + 1};\n        place_rect(company.rect);\n    }\n}\n\nvoid local_search() {\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (auto& company : companies) {\n            int id = &company - &companies[0];\n            Rect original = company.rect;\n            double original_sat = company.satisfaction();\n            vector<Rect> candidates;\n\n            // Try expanding in all four directions\n            // Expand right\n            if (company.rect.c < 10000) {\n                Rect new_rect = company.rect;\n                new_rect.c++;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand left\n            if (company.rect.a > 0) {\n                Rect new_rect = company.rect;\n                new_rect.a--;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand up\n            if (company.rect.d < 10000) {\n                Rect new_rect = company.rect;\n                new_rect.d++;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand down\n            if (company.rect.b > 0) {\n                Rect new_rect = company.rect;\n                new_rect.b--;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n\n            // Try to find the best candidate\n            double best_sat = original_sat;\n            Rect best_rect = original;\n            for (const auto& rect : candidates) {\n                company.rect = rect;\n                double sat = company.satisfaction();\n                if (sat > best_sat) {\n                    best_sat = sat;\n                    best_rect = rect;\n                }\n            }\n            if (best_sat > original_sat) {\n                remove_rect(id);\n                company.rect = best_rect;\n                place_rect(best_rect);\n                improved = true;\n            } else {\n                company.rect = original;\n            }\n        }\n    }\n}\n\nvoid simulated_annealing() {\n    double temperature = 1000.0;\n    double cooling_rate = 0.999;\n    double min_temperature = 0.1;\n    double current_sat = total_satisfaction();\n\n    while (temperature > min_temperature) {\n        for (auto& company : companies) {\n            int id = &company - &companies[0];\n            Rect original = company.rect;\n            double original_sat = company.satisfaction();\n\n            // Randomly choose a direction to expand or shrink\n            int dir = rand() % 4;\n            Rect new_rect = original;\n            switch (dir) {\n                case 0: // right\n                    if (new_rect.c < 10000) new_rect.c++;\n                    break;\n                case 1: // left\n                    if (new_rect.a > 0) new_rect.a--;\n                    break;\n                case 2: // up\n                    if (new_rect.d < 10000) new_rect.d++;\n                    break;\n                case 3: // down\n                    if (new_rect.b > 0) new_rect.b--;\n                    break;\n            }\n\n            if (!is_valid(new_rect, id)) continue;\n\n            company.rect = new_rect;\n            double new_sat = company.satisfaction();\n            double delta = new_sat - original_sat;\n\n            if (delta > 0 || (rand() / (double)RAND_MAX) < exp(delta / temperature)) {\n                remove_rect(id);\n                place_rect(new_rect);\n                current_sat += delta;\n            } else {\n                company.rect = original;\n            }\n        }\n        temperature *= cooling_rate;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> n;\n    companies.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n\n    greedy_initialization();\n    local_search();\n    simulated_annealing();\n\n    for (const auto& company : companies) {\n        cout << company.rect.a << \" \" << company.rect.b << \" \"\n             << company.rect.c << \" \" << company.rect.d << \"\\n\";\n    }\n\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct Tile {\n    vector<pair<int, int>> cells;\n    int sum = 0;\n    int id;\n};\n\nstruct State {\n    int score;\n    int last_tile;\n    int last_x, last_y;\n    vector<bool> visited_tiles;\n    string path;\n\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> t(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> t[i][j];\n        }\n    }\n\n    vector<vector<int>> p(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> p[i][j];\n        }\n    }\n\n    // Step 1: Identify tiles using DSU\n    dsu d(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && t[i][j] == t[ni][nj]) {\n                    d.merge(i * N + j, ni * N + nj);\n                }\n            }\n        }\n    }\n\n    // Step 2: Build tiles\n    map<int, Tile> tiles;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int root = d.leader(i * N + j);\n            tiles[root].cells.emplace_back(i, j);\n            tiles[root].sum += p[i][j];\n            tiles[root].id = root;\n        }\n    }\n\n    // Step 3: Build adjacency list for tiles\n    map<int, vector<int>> adj;\n    for (auto& [root, tile] : tiles) {\n        set<int> neighbors;\n        for (auto [i, j] : tile.cells) {\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                    int nroot = d.leader(ni * N + nj);\n                    if (nroot != root) {\n                        neighbors.insert(nroot);\n                    }\n                }\n            }\n        }\n        for (int nroot : neighbors) {\n            adj[root].push_back(nroot);\n        }\n    }\n\n    // Step 4: Beam search\n    const int BEAM_WIDTH = 1000;\n    priority_queue<State> beam;\n    State initial;\n    int start_root = d.leader(si * N + sj);\n    initial.score = p[si][sj];\n    initial.last_tile = start_root;\n    initial.last_x = si;\n    initial.last_y = sj;\n    initial.visited_tiles.resize(tiles.size(), false);\n    initial.visited_tiles[start_root] = true;\n    initial.path = \"\";\n    beam.push(initial);\n\n    string best_path;\n    int best_score = 0;\n\n    while (!beam.empty()) {\n        priority_queue<State> next_beam;\n        for (int i = 0; i < BEAM_WIDTH && !beam.empty(); ++i) {\n            State current = beam.top();\n            beam.pop();\n\n            if (current.score > best_score) {\n                best_score = current.score;\n                best_path = current.path;\n            }\n\n            for (int next_root : adj[current.last_tile]) {\n                if (current.visited_tiles[next_root]) continue;\n\n                State next = current;\n                next.last_tile = next_root;\n                next.visited_tiles[next_root] = true;\n                next.score += tiles[next_root].sum;\n\n                // Find a path within the next tile to traverse all its cells\n                auto& cells = tiles[next_root].cells;\n                vector<vector<bool>> visited(N, vector<bool>(N, false));\n                vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n                queue<pair<int, int>> q;\n                q.push({current.last_x, current.last_y});\n                visited[current.last_x][current.last_y] = true;\n                bool found = false;\n                pair<int, int> end_pos;\n\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    if (t[x][y] == next_root && (x != current.last_x || y != current.last_y)) {\n                        end_pos = {x, y};\n                        found = true;\n                        break;\n                    }\n                    for (int k = 0; k < 4; ++k) {\n                        int nx = x + dx[k];\n                        int ny = y + dy[k];\n                        if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && t[nx][ny] == next_root) {\n                            visited[nx][ny] = true;\n                            parent[nx][ny] = {x, y};\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n\n                if (!found) continue;\n\n                // Reconstruct path within the tile\n                string tile_path;\n                pair<int, int> pos = end_pos;\n                while (pos != make_pair(current.last_x, current.last_y)) {\n                    auto [px, py] = parent[pos.first][pos.second];\n                    for (int k = 0; k < 4; ++k) {\n                        if (px == pos.first + dx[k] && py == pos.second + dy[k]) {\n                            tile_path += dir[k];\n                            break;\n                        }\n                    }\n                    pos = {px, py};\n                }\n                reverse(tile_path.begin(), tile_path.end());\n                next.path += tile_path;\n                next.last_x = end_pos.first;\n                next.last_y = end_pos.second;\n\n                next_beam.push(next);\n            }\n        }\n        beam = move(next_beam);\n    }\n\n    cout << best_path << endl;\n\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 30;\nconst int INF = 1e9;\nconst double ALPHA = 0.1; // Learning rate\n\nstruct Edge {\n    int to_i, to_j;\n    int dir; // 0: right (R), 1: down (D), 2: left (L), 3: up (U)\n    double weight;\n};\n\nvector<vector<vector<Edge>>> adj(N, vector<vector<Edge>>(N));\nvector<vector<double>> h(N, vector<double>(N-1, 5000.0)); // horizontal edges\nvector<vector<double>> v(N-1, vector<double>(N, 5000.0)); // vertical edges\n\nvoid init_adj() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (j + 1 < N) {\n                adj[i][j].push_back({i, j+1, 0, h[i][j]});\n            }\n            if (i + 1 < N) {\n                adj[i][j].push_back({i+1, j, 1, v[i][j]});\n            }\n            if (j - 1 >= 0) {\n                adj[i][j].push_back({i, j-1, 2, h[i][j-1]});\n            }\n            if (i - 1 >= 0) {\n                adj[i][j].push_back({i-1, j, 3, v[i-1][j]});\n            }\n        }\n    }\n}\n\nstring dijkstra(int si, int sj, int ti, int tj) {\n    vector<vector<double>> dist(N, vector<double>(N, INF));\n    vector<vector<pair<int, int>>> prev(N, vector<pair<int, int>>(N, {-1, -1}));\n    priority_queue<tuple<double, int, int>, vector<tuple<double, int, int>>, greater<>> pq;\n\n    dist[si][sj] = 0.0;\n    pq.emplace(0.0, si, sj);\n\n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top();\n        pq.pop();\n        if (i == ti && j == tj) break;\n        if (d > dist[i][j]) continue;\n        for (const auto& edge : adj[i][j]) {\n            int ni = edge.to_i;\n            int nj = edge.to_j;\n            double nd = d + edge.weight;\n            if (nd < dist[ni][nj]) {\n                dist[ni][nj] = nd;\n                prev[ni][nj] = {i, j};\n                pq.emplace(nd, ni, nj);\n            }\n        }\n    }\n\n    string path;\n    int ci = ti, cj = tj;\n    while (ci != si || cj != sj) {\n        auto [pi, pj] = prev[ci][cj];\n        if (pi == ci && pj == cj - 1) path += 'R';\n        else if (pi == ci && pj == cj + 1) path += 'L';\n        else if (pi == ci - 1 && pj == cj) path += 'D';\n        else if (pi == ci + 1 && pj == cj) path += 'U';\n        ci = pi;\n        cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nvoid update_weights(const string& path, int si, int sj, double total_length) {\n    int ci = si, cj = sj;\n    double path_length = 0.0;\n    for (char dir : path) {\n        int ni = ci, nj = cj;\n        if (dir == 'R') nj++;\n        else if (dir == 'L') nj--;\n        else if (dir == 'D') ni++;\n        else if (dir == 'U') ni--;\n\n        double edge_weight;\n        if (dir == 'R') edge_weight = h[ci][cj];\n        else if (dir == 'L') edge_weight = h[ci][cj-1];\n        else if (dir == 'D') edge_weight = v[ci][cj];\n        else if (dir == 'U') edge_weight = v[ci-1][cj];\n\n        path_length += edge_weight;\n        ci = ni;\n        cj = nj;\n    }\n\n    ci = si;\n    cj = sj;\n    for (char dir : path) {\n        int ni = ci, nj = cj;\n        if (dir == 'R') {\n            double new_weight = total_length * (h[ci][cj] / path_length);\n            h[ci][cj] = (1 - ALPHA) * h[ci][cj] + ALPHA * new_weight;\n            nj++;\n        } else if (dir == 'L') {\n            double new_weight = total_length * (h[ci][cj-1] / path_length);\n            h[ci][cj-1] = (1 - ALPHA) * h[ci][cj-1] + ALPHA * new_weight;\n            nj--;\n        } else if (dir == 'D') {\n            double new_weight = total_length * (v[ci][cj] / path_length);\n            v[ci][cj] = (1 - ALPHA) * v[ci][cj] + ALPHA * new_weight;\n            ni++;\n        } else if (dir == 'U') {\n            double new_weight = total_length * (v[ci-1][cj] / path_length);\n            v[ci-1][cj] = (1 - ALPHA) * v[ci-1][cj] + ALPHA * new_weight;\n            ni--;\n        }\n        ci = ni;\n        cj = nj;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    init_adj();\n\n    for (int k = 0; k < 1000; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n\n        string path = dijkstra(si, sj, ti, tj);\n        cout << path << endl;\n        cout.flush();\n\n        int total_length;\n        cin >> total_length;\n\n        update_weights(path, si, sj, total_length);\n    }\n\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int MAX_LEN = 12;\nconst vector<char> CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', '.'};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct State {\n    vector<string> grid;\n    int c; // number of matched strings\n    int d; // number of '.'\n    double energy;\n};\n\nvector<string> strings;\nint M;\n\nint count_matched(const vector<string>& grid) {\n    int matched = 0;\n    for (const string& s : strings) {\n        int k = s.size();\n        bool found = false;\n        // Check rows\n        for (int i = 0; i < N && !found; ++i) {\n            for (int j = 0; j < N && !found; ++j) {\n                bool match = true;\n                for (int p = 0; p < k; ++p) {\n                    if (grid[i][(j + p) % N] != s[p]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) {\n                    found = true;\n                    break;\n                }\n            }\n        }\n        // Check columns\n        for (int j = 0; j < N && !found; ++j) {\n            for (int i = 0; i < N && !found; ++i) {\n                bool match = true;\n                for (int p = 0; p < k; ++p) {\n                    if (grid[(i + p) % N][j] != s[p]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) {\n                    found = true;\n                    break;\n                }\n            }\n        }\n        if (found) {\n            matched++;\n        }\n    }\n    return matched;\n}\n\nint count_dots(const vector<string>& grid) {\n    int dots = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == '.') {\n                dots++;\n            }\n        }\n    }\n    return dots;\n}\n\ndouble compute_energy(int c, int d) {\n    if (c < M) {\n        return -1e8 * c / M;\n    } else {\n        return -1e8 * (2 * N * N) / (2 * N * N - d);\n    }\n}\n\nState get_initial_state() {\n    State state;\n    state.grid.resize(N, string(N, '.'));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            state.grid[i][j] = CHARS[rng() % (CHARS.size() - 1)];\n        }\n    }\n    state.d = count_dots(state.grid);\n    state.c = count_matched(state.grid);\n    state.energy = compute_energy(state.c, state.d);\n    return state;\n}\n\nState simulated_annealing(State initial_state, double initial_temp, double final_temp, double cooling_rate, int iterations) {\n    State current = initial_state;\n    State best = current;\n    double temp = initial_temp;\n\n    for (int iter = 0; iter < iterations; ++iter) {\n        // Generate neighbor\n        int i = rng() % N;\n        int j = rng() % N;\n        char old_char = current.grid[i][j];\n        char new_char;\n        do {\n            new_char = CHARS[rng() % CHARS.size()];\n        } while (new_char == old_char);\n\n        // Compute new state\n        vector<string> new_grid = current.grid;\n        new_grid[i][j] = new_char;\n        int new_c = count_matched(new_grid);\n        int new_d = count_dots(new_grid);\n        double new_energy = compute_energy(new_c, new_d);\n\n        // Decide whether to accept\n        double delta_energy = new_energy - current.energy;\n        if (delta_energy < 0 || exp(-delta_energy / temp) > (double)rng() / rng.max()) {\n            current.grid = new_grid;\n            current.c = new_c;\n            current.d = new_d;\n            current.energy = new_energy;\n            if (current.energy < best.energy) {\n                best = current;\n            }\n        }\n\n        // Cool down\n        temp *= cooling_rate;\n        if (temp < final_temp) {\n            break;\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> M;\n    strings.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i];\n    }\n\n    // Parameters for simulated annealing\n    double initial_temp = 1e4;\n    double final_temp = 1e-3;\n    double cooling_rate = 0.999;\n    int iterations = 1e6;\n\n    State initial_state = get_initial_state();\n    State best_state = simulated_annealing(initial_state, initial_temp, final_temp, cooling_rate, iterations);\n\n    for (const string& row : best_state.grid) {\n        cout << row << '\\n';\n    }\n\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int INF = 1e9;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nint N, si, sj;\nvector<string> grid;\nvector<vector<int>> cost;\nvector<vector<bool>> is_road;\nvector<vector<vector<Point>>> visible;\nvector<vector<int>> dist;\nvector<vector<Point>> parent;\nvector<Point> road_points;\n\nvoid precompute_visible() {\n    visible.assign(N, vector<vector<Point>>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!is_road[i][j]) continue;\n            // Check left\n            for (int k = j - 1; k >= 0; --k) {\n                if (!is_road[i][k]) break;\n                visible[i][j].emplace_back(i, k);\n            }\n            // Check right\n            for (int k = j + 1; k < N; ++k) {\n                if (!is_road[i][k]) break;\n                visible[i][j].emplace_back(i, k);\n            }\n            // Check up\n            for (int k = i - 1; k >= 0; --k) {\n                if (!is_road[k][j]) break;\n                visible[i][j].emplace_back(k, j);\n            }\n            // Check down\n            for (int k = i + 1; k < N; ++k) {\n                if (!is_road[k][j]) break;\n                visible[i][j].emplace_back(k, j);\n            }\n        }\n    }\n}\n\nvoid dijkstra(Point start) {\n    dist.assign(N, vector<int>(N, INF));\n    parent.assign(N, vector<Point>(N, Point(-1, -1)));\n    priority_queue<pair<int, Point>, vector<pair<int, Point>>, greater<pair<int, Point>>> pq;\n    dist[start.x][start.y] = 0;\n    pq.emplace(0, start);\n    while (!pq.empty()) {\n        auto [current_dist, p] = pq.top();\n        pq.pop();\n        if (current_dist > dist[p.x][p.y]) continue;\n        for (int d = 0; d < 4; ++d) {\n            int nx = p.x + dx[d];\n            int ny = p.y + dy[d];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            if (!is_road[nx][ny]) continue;\n            int new_dist = current_dist + cost[nx][ny];\n            if (new_dist < dist[nx][ny]) {\n                dist[nx][ny] = new_dist;\n                parent[nx][ny] = p;\n                pq.emplace(new_dist, Point(nx, ny));\n            }\n        }\n    }\n}\n\nstring reconstruct_path(Point start, Point end) {\n    string path;\n    Point p = end;\n    while (!(p == start)) {\n        Point par = parent[p.x][p.y];\n        for (int d = 0; d < 4; ++d) {\n            if (par.x + dx[d] == p.x && par.y + dy[d] == p.y) {\n                path += dir[d];\n                break;\n            }\n        }\n        p = par;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nstring solve() {\n    // Precompute road points\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (is_road[i][j]) {\n                road_points.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Precompute visible squares for each road point\n    precompute_visible();\n\n    // Greedy approach: start from (si, sj) and cover all road points\n    vector<vector<bool>> covered(N, vector<bool>(N, false));\n    vector<Point> route;\n    route.emplace_back(si, sj);\n    covered[si][sj] = true;\n\n    // Mark all points visible from (si, sj) as covered\n    for (const auto& p : visible[si][sj]) {\n        covered[p.x][p.y] = true;\n    }\n\n    // Priority queue to keep track of uncovered road points sorted by distance\n    priority_queue<pair<int, Point>, vector<pair<int, Point>>, greater<pair<int, Point>>> pq;\n    dijkstra(route.back());\n    for (const auto& p : road_points) {\n        if (!covered[p.x][p.y]) {\n            pq.emplace(dist[p.x][p.y], p);\n        }\n    }\n\n    // While there are uncovered points\n    while (!pq.empty()) {\n        auto [current_dist, next_point] = pq.top();\n        pq.pop();\n        if (covered[next_point.x][next_point.y]) continue;\n\n        // Move to the next point\n        dijkstra(route.back());\n        string best_path = reconstruct_path(route.back(), next_point);\n        for (char c : best_path) {\n            if (c == 'U') route.emplace_back(route.back().x - 1, route.back().y);\n            else if (c == 'D') route.emplace_back(route.back().x + 1, route.back().y);\n            else if (c == 'L') route.emplace_back(route.back().x, route.back().y - 1);\n            else if (c == 'R') route.emplace_back(route.back().x, route.back().y + 1);\n        }\n        route.push_back(next_point);\n\n        // Mark all points visible from the new point as covered\n        for (const auto& p : visible[next_point.x][next_point.y]) {\n            if (!covered[p.x][p.y]) {\n                covered[p.x][p.y] = true;\n                // Update the priority queue with new distances\n                dijkstra(route.back());\n                pq.emplace(dist[p.x][p.y], p);\n            }\n        }\n    }\n\n    // Return to start\n    dijkstra(route.back());\n    string return_path = reconstruct_path(route.back(), Point(si, sj));\n    for (char c : return_path) {\n        if (c == 'U') route.emplace_back(route.back().x - 1, route.back().y);\n        else if (c == 'D') route.emplace_back(route.back().x + 1, route.back().y);\n        else if (c == 'L') route.emplace_back(route.back().x, route.back().y - 1);\n        else if (c == 'R') route.emplace_back(route.back().x, route.back().y + 1);\n    }\n\n    // Reconstruct the path string\n    string result;\n    for (size_t i = 1; i < route.size(); ++i) {\n        Point prev = route[i-1];\n        Point curr = route[i];\n        if (prev.x == curr.x && prev.y == curr.y - 1) result += 'R';\n        else if (prev.x == curr.x && prev.y == curr.y + 1) result += 'L';\n        else if (prev.x == curr.x - 1 && prev.y == curr.y) result += 'D';\n        else if (prev.x == curr.x + 1 && prev.y == curr.y) result += 'U';\n    }\n\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> si >> sj;\n    grid.resize(N);\n    cost.assign(N, vector<int>(N));\n    is_road.assign(N, vector<bool>(N, false));\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                is_road[i][j] = true;\n                cost[i][j] = grid[i][j] - '0';\n            }\n        }\n    }\n\n    string ans = solve();\n    cout << ans << endl;\n\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <map>\n#include <set>\n#include <climits>\n#include <cassert>\n\nusing namespace std;\n\nstruct Task {\n    int id;\n    vector<int> difficulty;\n    vector<int> dependencies;\n    vector<int> dependents;\n    int in_degree = 0;\n    bool completed = false;\n    int assigned_member = -1;\n    int start_day = -1;\n    int completion_day = -1;\n    int critical_path = 0;\n};\n\nstruct Member {\n    int id;\n    vector<int> skills;\n    int current_task = -1;\n    int task_end_day = -1;\n    vector<pair<int, int>> task_history; // task_id, completion_time\n};\n\nclass Scheduler {\nprivate:\n    int N, M, K, R;\n    vector<Task> tasks;\n    vector<Member> members;\n    vector<vector<int>> adj;\n    vector<int> in_degree;\n    vector<int> topo_order;\n    vector<vector<int>> task_dependencies;\n    vector<vector<int>> task_dependents;\n    vector<vector<int>> skill_estimates;\n    vector<int> available_members;\n    int current_day = 0;\n    mt19937 rng;\n\n    void topological_sort() {\n        queue<int> q;\n        for (int i = 0; i < N; ++i) {\n            if (in_degree[i] == 0) {\n                q.push(i);\n            }\n        }\n        while (!q.empty()) {\n            int u = q.front();\n            q.pop();\n            topo_order.push_back(u);\n            for (int v : adj[u]) {\n                if (--in_degree[v] == 0) {\n                    q.push(v);\n                }\n            }\n        }\n    }\n\n    void calculate_critical_paths() {\n        vector<int> max_path(N, 0);\n        for (int u : topo_order) {\n            for (int v : tasks[u].dependents) {\n                max_path[v] = max(max_path[v], max_path[u] + 1);\n            }\n        }\n        for (int i = 0; i < N; ++i) {\n            tasks[i].critical_path = max_path[i];\n        }\n    }\n\n    void update_skill_estimates(int member_id, int task_id, int completion_time) {\n        Member& member = members[member_id];\n        Task& task = tasks[task_id];\n        member.task_history.emplace_back(task_id, completion_time);\n\n        for (int k = 0; k < K; ++k) {\n            int diff = task.difficulty[k];\n            int& skill = skill_estimates[member_id][k];\n            if (completion_time == 1) {\n                skill = max(skill, diff);\n            } else {\n                skill = min(skill, diff - 1);\n            }\n        }\n    }\n\n    int estimate_completion_time(int member_id, int task_id) {\n        const Task& task = tasks[task_id];\n        int w = 0;\n        for (int k = 0; k < K; ++k) {\n            w += max(0, task.difficulty[k] - skill_estimates[member_id][k]);\n        }\n        if (w == 0) {\n            return 1;\n        } else {\n            return max(1, w + 0); // Assuming r_i = 0 for estimation\n        }\n    }\n\n    bool is_task_ready(int task_id) {\n        for (int dep : tasks[task_id].dependencies) {\n            if (!tasks[dep].completed) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    void assign_tasks() {\n        vector<pair<int, int>> assignments;\n        for (int member_id : available_members) {\n            if (members[member_id].current_task != -1) continue;\n\n            int best_task = -1;\n            int best_priority = -1;\n            for (int task_id : topo_order) {\n                Task& task = tasks[task_id];\n                if (task.completed || task.assigned_member != -1) continue;\n                if (!is_task_ready(task_id)) continue;\n\n                int priority = task.critical_path * 1000 + (int)task.dependents.size();\n                if (priority > best_priority) {\n                    best_priority = priority;\n                    best_task = task_id;\n                }\n            }\n\n            if (best_task != -1) {\n                Task& task = tasks[best_task];\n                int est_time = estimate_completion_time(member_id, best_task);\n                task.assigned_member = member_id;\n                task.start_day = current_day;\n                members[member_id].current_task = best_task;\n                members[member_id].task_end_day = current_day + est_time - 1;\n                assignments.emplace_back(member_id, best_task);\n            }\n        }\n\n        cout << assignments.size();\n        for (auto [member_id, task_id] : assignments) {\n            cout << \" \" << member_id + 1 << \" \" << task_id + 1;\n        }\n        cout << endl;\n    }\n\n    void process_completions(const vector<int>& completed_members) {\n        for (int member_id : completed_members) {\n            Member& member = members[member_id];\n            if (member.current_task == -1) continue;\n\n            Task& task = tasks[member.current_task];\n            task.completed = true;\n            task.completion_day = current_day;\n            member.current_task = -1;\n            member.task_end_day = -1;\n            available_members.push_back(member_id);\n\n            int completion_time = current_day - task.start_day + 1;\n            update_skill_estimates(member_id, task.id, completion_time);\n        }\n    }\n\npublic:\n    Scheduler(int N, int M, int K, int R, const vector<vector<int>>& difficulties, const vector<pair<int, int>>& dependencies)\n        : N(N), M(M), K(K), R(R), rng(random_device{}()) {\n        tasks.resize(N);\n        for (int i = 0; i < N; ++i) {\n            tasks[i].id = i;\n            tasks[i].difficulty = difficulties[i];\n        }\n\n        adj.resize(N);\n        in_degree.resize(N, 0);\n        task_dependencies.resize(N);\n        task_dependents.resize(N);\n        for (auto [u, v] : dependencies) {\n            u--; v--;\n            adj[u].push_back(v);\n            in_degree[v]++;\n            task_dependencies[v].push_back(u);\n            task_dependents[u].push_back(v);\n        }\n\n        for (int i = 0; i < N; ++i) {\n            tasks[i].dependencies = task_dependencies[i];\n            tasks[i].dependents = task_dependents[i];\n        }\n\n        topological_sort();\n        calculate_critical_paths();\n\n        members.resize(M);\n        for (int i = 0; i < M; ++i) {\n            members[i].id = i;\n            members[i].skills.resize(K, 0);\n            skill_estimates.push_back(vector<int>(K, 0));\n            available_members.push_back(i);\n        }\n    }\n\n    void run() {\n        while (current_day < 2000) {\n            current_day++;\n            assign_tasks();\n\n            int n;\n            cin >> n;\n            if (n == -1) {\n                break;\n            }\n            vector<int> completed_members(n);\n            for (int i = 0; i < n; ++i) {\n                cin >> completed_members[i];\n                completed_members[i]--;\n            }\n            process_completions(completed_members);\n        }\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<vector<int>> difficulties(N, vector<int>(K));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> difficulties[i][j];\n        }\n    }\n\n    vector<pair<int, int>> dependencies(R);\n    for (int i = 0; i < R; ++i) {\n        cin >> dependencies[i].first >> dependencies[i].second;\n    }\n\n    Scheduler scheduler(N, M, K, R, difficulties, dependencies);\n    scheduler.run();\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1000;\nconst int M = 50;\nconst int OFFICE_X = 400;\nconst int OFFICE_Y = 400;\n\nstruct Order {\n    int id;\n    int a, b, c, d;\n    int dist_to_office;\n    int dist_pickup_delivery;\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nvector<Order> orders;\nvector<int> selected_orders;\nvector<pair<int, int>> points;\nvector<int> route;\n\nint compute_total_distance(const vector<int>& route) {\n    int total = 0;\n    for (int i = 0; i < (int)route.size() - 1; ++i) {\n        auto [x1, y1] = points[route[i]];\n        auto [x2, y2] = points[route[i+1]];\n        total += manhattan(x1, y1, x2, y2);\n    }\n    return total;\n}\n\nbool check_precedence(const vector<int>& route) {\n    vector<int> pickup_pos(M + 1, -1);\n    vector<int> delivery_pos(M + 1, -1);\n    for (int i = 0; i < (int)route.size(); ++i) {\n        int idx = route[i];\n        if (idx >= 1 && idx <= M) {\n            pickup_pos[idx] = i;\n        } else if (idx >= M + 1 && idx <= 2 * M) {\n            delivery_pos[idx - M] = i;\n        }\n    }\n    for (int i = 1; i <= M; ++i) {\n        if (pickup_pos[i] == -1 || delivery_pos[i] == -1) {\n            return false;\n        }\n        if (pickup_pos[i] >= delivery_pos[i]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid two_opt_with_precedence(vector<int>& route) {\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 1; i < (int)route.size() - 2; ++i) {\n            for (int j = i + 1; j < (int)route.size() - 1; ++j) {\n                if (j - i == 1) continue;\n                vector<int> new_route = route;\n                reverse(new_route.begin() + i, new_route.begin() + j + 1);\n                if (check_precedence(new_route)) {\n                    int current_dist = compute_total_distance(route);\n                    int new_dist = compute_total_distance(new_route);\n                    if (new_dist < current_dist) {\n                        route = new_route;\n                        improved = true;\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid solve() {\n    // Read input\n    orders.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n        orders[i].id = i + 1;\n        orders[i].dist_to_office = manhattan(orders[i].a, orders[i].b, OFFICE_X, OFFICE_Y) +\n                                   manhattan(orders[i].c, orders[i].d, OFFICE_X, OFFICE_Y);\n        orders[i].dist_pickup_delivery = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n    }\n\n    // Select orders with smallest dist_to_office\n    sort(orders.begin(), orders.end(), [](const Order& a, const Order& b) {\n        return a.dist_to_office < b.dist_to_office;\n    });\n    selected_orders.clear();\n    for (int i = 0; i < M; ++i) {\n        selected_orders.push_back(orders[i].id);\n    }\n\n    // Prepare points: 0 is office, 1..M are pickups, M+1..2M are deliveries\n    points.clear();\n    points.emplace_back(OFFICE_X, OFFICE_Y); // 0\n    for (int i = 0; i < M; ++i) {\n        points.emplace_back(orders[i].a, orders[i].b); // 1..M\n    }\n    for (int i = 0; i < M; ++i) {\n        points.emplace_back(orders[i].c, orders[i].d); // M+1..2M\n    }\n\n    // Initial route: office -> pickups in order -> deliveries in order -> office\n    route.clear();\n    route.push_back(0);\n    for (int i = 1; i <= M; ++i) {\n        route.push_back(i);\n    }\n    for (int i = M + 1; i <= 2 * M; ++i) {\n        route.push_back(i);\n    }\n    route.push_back(0);\n\n    // Optimize with 2-opt while respecting precedence\n    two_opt_with_precedence(route);\n\n    // Output\n    cout << M;\n    for (int id : selected_orders) {\n        cout << \" \" << id;\n    }\n    cout << \"\\n\";\n\n    cout << route.size();\n    for (int idx : route) {\n        cout << \" \" << points[idx].first << \" \" << points[idx].second;\n    }\n    cout << \"\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v;\n    int d;\n    int l;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 400;\n    int M = 1995;\n\n    vector<pair<int, int>> points(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> points[i].first >> points[i].second;\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        int dx = points[edges[i].u].first - points[edges[i].v].first;\n        int dy = points[edges[i].u].second - points[edges[i].v].second;\n        edges[i].d = round(sqrt(dx * dx + dy * dy));\n    }\n\n    dsu uf(N);\n    int components = N;\n\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].l;\n        if (uf.same(edges[i].u, edges[i].v)) {\n            cout << 0 << '\\n';\n            cout.flush();\n            continue;\n        }\n        // Always accept edges that connect new components\n        if (components > 1) {\n            uf.merge(edges[i].u, edges[i].v);\n            components--;\n            cout << 1 << '\\n';\n            cout.flush();\n        } else {\n            // After ensuring connectivity, be more selective\n            if (edges[i].l <= 2 * edges[i].d) {\n                cout << 1 << '\\n';\n                cout.flush();\n            } else {\n                cout << 0 << '\\n';\n                cout.flush();\n            }\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int GRID_SIZE = 30;\nconst int TURNS = 300;\nconst int MAX_PETS = 20;\nconst int MAX_HUMANS = 10;\n\nstruct Pet {\n    int x, y, type;\n    int target_human = -1;\n    int target_x = -1, target_y = -1;\n};\n\nstruct Human {\n    int x, y;\n};\n\nint N, M;\nvector<Pet> pets;\nvector<Human> humans;\nvector<vector<bool>> blocked(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\nvector<vector<int>> pet_grid(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\nvector<vector<int>> human_grid(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n\nconst vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst string dir_chars = \"udlrUDLR\";\n\nvoid initialize() {\n    cin >> N;\n    pets.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n        pet_grid[pets[i].x][pets[i].y]++;\n    }\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].x >> humans[i].y;\n        human_grid[humans[i].x][humans[i].y]++;\n    }\n    blocked.assign(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\n    for (int i = 0; i <= GRID_SIZE + 1; ++i) {\n        blocked[i][0] = blocked[i][GRID_SIZE + 1] = true;\n        blocked[0][i] = blocked[GRID_SIZE + 1][i] = true;\n    }\n}\n\nbool is_valid(int x, int y) {\n    return x >= 1 && x <= GRID_SIZE && y >= 1 && y <= GRID_SIZE && !blocked[x][y];\n}\n\nbool can_block(int x, int y) {\n    if (x < 1 || x > GRID_SIZE || y < 1 || y > GRID_SIZE) return false;\n    if (blocked[x][y] || pet_grid[x][y] > 0 || human_grid[x][y] > 0) return false;\n    for (auto [dx, dy] : directions) {\n        int nx = x + dx, ny = y + dy;\n        if (nx >= 1 && nx <= GRID_SIZE && ny >= 1 && ny <= GRID_SIZE && pet_grid[nx][ny] > 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvector<pair<int, int>> get_adjacent_passable(int x, int y) {\n    vector<pair<int, int>> res;\n    for (auto [dx, dy] : directions) {\n        int nx = x + dx, ny = y + dy;\n        if (is_valid(nx, ny)) {\n            res.emplace_back(nx, ny);\n        }\n    }\n    return res;\n}\n\nvoid update_grids() {\n    pet_grid.assign(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n    human_grid.assign(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n    for (auto &pet : pets) {\n        pet_grid[pet.x][pet.y]++;\n    }\n    for (auto &human : humans) {\n        human_grid[human.x][human.y]++;\n    }\n}\n\nvoid move_pets() {\n    vector<string> moves(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> moves[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        auto &pet = pets[i];\n        int x = pet.x, y = pet.y;\n        for (char c : moves[i]) {\n            int dx = 0, dy = 0;\n            if (c == 'U') dx = -1;\n            else if (c == 'D') dx = 1;\n            else if (c == 'L') dy = -1;\n            else if (c == 'R') dy = 1;\n            int nx = x + dx, ny = y + dy;\n            if (is_valid(nx, ny)) {\n                x = nx;\n                y = ny;\n            }\n        }\n        pet.x = x;\n        pet.y = y;\n    }\n    update_grids();\n}\n\nvoid decide_human_actions() {\n    string actions;\n    for (int i = 0; i < M; ++i) {\n        auto &human = humans[i];\n        int x = human.x, y = human.y;\n        bool blocked_something = false;\n        vector<pair<int, int>> possible_blocks;\n        for (auto [dx, dy] : directions) {\n            int nx = x + dx, ny = y + dy;\n            if (can_block(nx, ny)) {\n                possible_blocks.emplace_back(nx, ny);\n            }\n        }\n        if (!possible_blocks.empty()) {\n            auto [nx, ny] = possible_blocks[rand() % possible_blocks.size()];\n            blocked[nx][ny] = true;\n            if (nx == x - 1) actions += 'u';\n            else if (nx == x + 1) actions += 'd';\n            else if (ny == y - 1) actions += 'l';\n            else if (ny == y + 1) actions += 'r';\n            blocked_something = true;\n        }\n        if (!blocked_something) {\n            vector<pair<int, int>> adj = get_adjacent_passable(x, y);\n            if (!adj.empty()) {\n                auto [nx, ny] = adj[rand() % adj.size()];\n                human.x = nx;\n                human.y = ny;\n                if (nx == x - 1) actions += 'U';\n                else if (nx == x + 1) actions += 'D';\n                else if (ny == y - 1) actions += 'L';\n                else if (ny == y + 1) actions += 'R';\n            } else {\n                actions += '.';\n            }\n        }\n    }\n    cout << actions << endl;\n    cout.flush();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    initialize();\n    for (int turn = 0; turn < TURNS; ++turn) {\n        decide_human_actions();\n        move_pets();\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int INF = 1e9;\nconst vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst string dir_chars = \"UDLR\";\n\nint si, sj, ti, tj;\ndouble p;\nvector<string> h, v;\n\nvector<vector<int>> bfs_shortest_path() {\n    vector<vector<int>> dist(N, vector<int>(N, INF));\n    queue<pair<int, int>> q;\n    dist[ti][tj] = 0;\n    q.emplace(ti, tj);\n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && dist[ni][nj] == INF) {\n                dist[ni][nj] = dist[i][j] + 1;\n                q.emplace(ni, nj);\n            }\n        }\n    }\n    return dist;\n}\n\nstring construct_path(const vector<vector<int>>& dist) {\n    string path;\n    int i = si, j = sj;\n    while (i != ti || j != tj) {\n        int best_d = -1;\n        int best_dist = INF;\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && dist[ni][nj] < best_dist) {\n                best_dist = dist[ni][nj];\n                best_d = d;\n            }\n        }\n        if (best_d == -1) break;\n        path += dir_chars[best_d];\n        i += dirs[best_d].first;\n        j += dirs[best_d].second;\n    }\n    return path;\n}\n\nstring make_robust_path(const string& shortest_path) {\n    string robust_path;\n    for (char c : shortest_path) {\n        robust_path += c;\n        if (p > 0.15) {\n            robust_path += c;\n            if (p > 0.3) {\n                robust_path += c;\n                if (p > 0.45) {\n                    robust_path += c;\n                }\n            }\n        }\n    }\n    if (robust_path.size() > 200) {\n        robust_path = shortest_path.substr(0, 200);\n    }\n    return robust_path;\n}\n\nint main() {\n    cin >> si >> sj >> ti >> tj >> p;\n    h.resize(N);\n    v.resize(N - 1);\n    for (int i = 0; i < N; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N - 1; ++i) {\n        cin >> v[i];\n    }\n\n    auto dist = bfs_shortest_path();\n    string shortest_path = construct_path(dist);\n    string robust_path = make_robust_path(shortest_path);\n\n    // Ensure the path length is <= 200\n    if (robust_path.size() > 200) {\n        robust_path = shortest_path.substr(0, 200);\n    }\n\n    cout << robust_path << endl;\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 30;\nconst int dx[4] = {0, -1, 0, 1};\nconst int dy[4] = {-1, 0, 1, 0};\nconst int to[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\n\nvector<string> initial_tiles;\nvector<vector<int>> tiles;\nvector<vector<int>> rotations;\nvector<vector<bool>> visited;\nvector<int> loop_lengths;\n\nint compute_loop_length(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    do {\n        int d2 = to[tiles[i][j]][d];\n        if (d2 == -1) return 0;\n        i += dx[d2];\n        j += dy[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (length > 1000) return 0; // Prevent infinite loops\n    } while (!(i == si && j == sj && d == sd));\n    return length;\n}\n\nvoid find_loops() {\n    visited.assign(N, vector<bool>(N, false));\n    loop_lengths.clear();\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (visited[i][j]) continue;\n            for (int d = 0; d < 4; ++d) {\n                int d2 = to[tiles[i][j]][d];\n                if (d2 == -1) continue;\n                int ni = i + dx[d2];\n                int nj = j + dy[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) % 4;\n                int length = compute_loop_length(i, j, d);\n                if (length > 0) {\n                    loop_lengths.push_back(length);\n                    for (int x = 0; x < N; ++x) {\n                        for (int y = 0; y < N; ++y) {\n                            if (visited[x][y]) continue;\n                            for (int dd = 0; dd < 4; ++dd) {\n                                if (compute_loop_length(x, y, dd) == length) {\n                                    visited[x][y] = true;\n                                }\n                            }\n                        }\n                    }\n                    goto next_tile;\n                }\n            }\n        }\n        next_tile:;\n    }\n    sort(loop_lengths.rbegin(), loop_lengths.rend());\n}\n\nlong long evaluate() {\n    find_loops();\n    if (loop_lengths.size() < 2) return 0;\n    return (long long)loop_lengths[0] * loop_lengths[1];\n}\n\nvoid apply_rotations() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int type = initial_tiles[i][j] - '0';\n            int rot = rotations[i][j];\n            if (type >= 0 && type <= 3) {\n                tiles[i][j] = (type + rot) % 4;\n            } else if (type >= 4 && type <= 5) {\n                tiles[i][j] = 4 + (rot % 2);\n            } else if (type >= 6 && type <= 7) {\n                tiles[i][j] = 6 + (rot % 2);\n            }\n        }\n    }\n}\n\nvoid solve() {\n    initial_tiles.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> initial_tiles[i];\n    }\n\n    rotations.assign(N, vector<int>(N, 0));\n    tiles.assign(N, vector<int>(N, 0));\n    apply_rotations();\n    long long best_score = evaluate();\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n    uniform_real_distribution<> prob(0.0, 1.0);\n\n    int iterations = 2000;\n    double temperature = 1000.0;\n    double cooling_rate = 0.99;\n\n    for (int iter = 0; iter < iterations; ++iter) {\n        int i = gen() % N;\n        int j = gen() % N;\n        int old_rot = rotations[i][j];\n        int new_rot = dis(gen);\n        rotations[i][j] = new_rot;\n        apply_rotations();\n        long long new_score = evaluate();\n        if (new_score > best_score || prob(gen) < exp((new_score - best_score) / temperature)) {\n            best_score = new_score;\n        } else {\n            rotations[i][j] = old_rot;\n            apply_rotations();\n        }\n        temperature *= cooling_rate;\n    }\n\n    string output;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            output += to_string(rotations[i][j]);\n        }\n    }\n    cout << output << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\nconst int rev[] = {2, 3, 0, 1};\n\nstruct State {\n    vector<vector<int>> board;\n    int empty_x, empty_y;\n    string moves;\n    int tree_size;\n    int steps;\n\n    State() : board(), empty_x(0), empty_y(0), moves(\"\"), tree_size(0), steps(0) {}\n    State(int N) : board(N, vector<int>(N)), empty_x(0), empty_y(0), moves(\"\"), tree_size(0), steps(0) {}\n\n    bool operator<(const State& other) const {\n        if (tree_size != other.tree_size) {\n            return tree_size > other.tree_size;\n        }\n        return steps < other.steps;\n    }\n};\n\nint calculate_tree_size(const vector<vector<int>>& board) {\n    int N = board.size();\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    int max_size = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0 || visited[i][j]) continue;\n\n            queue<pair<int, int>> q;\n            q.push({i, j});\n            visited[i][j] = true;\n            int size = 0;\n\n            while (!q.empty()) {\n                auto [x, y] = q.front();\n                q.pop();\n                size++;\n\n                int mask = board[x][y];\n                if (x > 0 && (mask & 2) && (board[x-1][y] & 8) && !visited[x-1][y]) {\n                    visited[x-1][y] = true;\n                    q.push({x-1, y});\n                }\n                if (x < N-1 && (mask & 8) && (board[x+1][y] & 2) && !visited[x+1][y]) {\n                    visited[x+1][y] = true;\n                    q.push({x+1, y});\n                }\n                if (y > 0 && (mask & 1) && (board[x][y-1] & 4) && !visited[x][y-1]) {\n                    visited[x][y-1] = true;\n                    q.push({x, y-1});\n                }\n                if (y < N-1 && (mask & 4) && (board[x][y+1] & 1) && !visited[x][y+1]) {\n                    visited[x][y+1] = true;\n                    q.push({x, y+1});\n                }\n            }\n\n            max_size = max(max_size, size);\n        }\n    }\n\n    return max_size;\n}\n\nvector<State> generate_next_states(const State& current, int N, int T) {\n    vector<State> next_states;\n\n    for (int d = 0; d < 4; ++d) {\n        int nx = current.empty_x + dx[d];\n        int ny = current.empty_y + dy[d];\n\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n\n        State next = current;\n        swap(next.board[current.empty_x][current.empty_y], next.board[nx][ny]);\n        next.empty_x = nx;\n        next.empty_y = ny;\n        next.moves += dir[d];\n        next.steps++;\n\n        if (next.steps > T) continue;\n\n        next.tree_size = calculate_tree_size(next.board);\n        next_states.push_back(next);\n    }\n\n    return next_states;\n}\n\nstring solve(int N, int T, const vector<string>& input) {\n    State initial(N);\n    int empty_count = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = input[i][j];\n            if (c == '0') {\n                initial.board[i][j] = 0;\n                initial.empty_x = i;\n                initial.empty_y = j;\n                empty_count++;\n            } else {\n                initial.board[i][j] = stoi(string(1, c), nullptr, 16);\n            }\n        }\n    }\n\n    if (empty_count != 1) {\n        return \"\";\n    }\n\n    initial.tree_size = calculate_tree_size(initial.board);\n\n    vector<State> current_level;\n    current_level.push_back(initial);\n\n    int beam_width = 50;\n    int max_tree_size = 0;\n    string best_moves;\n\n    for (int step = 0; step < T; ++step) {\n        vector<State> next_level;\n\n        for (const State& current : current_level) {\n            if (current.tree_size == N * N - 1) {\n                return current.moves;\n            }\n\n            if (current.tree_size > max_tree_size) {\n                max_tree_size = current.tree_size;\n                best_moves = current.moves;\n            }\n\n            vector<State> next_states = generate_next_states(current, N, T);\n            for (const State& next : next_states) {\n                next_level.push_back(next);\n            }\n        }\n\n        if (next_level.empty()) {\n            break;\n        }\n\n        sort(next_level.begin(), next_level.end());\n        if (static_cast<int>(next_level.size()) > beam_width) {\n            next_level.resize(beam_width);\n        }\n\n        current_level = next_level;\n    }\n\n    return best_moves;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    cin >> N >> T;\n    vector<string> input(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> input[i];\n    }\n\n    string result = solve(N, T, input);\n    cout << result << endl;\n\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_K = 100;\nconst int MAX_D = 10;\nconst int MAX_A = 100;\nconst int MAX_ITERATIONS = 200;\nconst int RADIUS = 10000;\nconst int RADIUS_SQ = RADIUS * RADIUS;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n    bool operator==(const Point& p) const {\n        return x == p.x && y == p.y;\n    }\n};\n\nstruct Line {\n    int px, py, qx, qy;\n    Line(int px, int py, int qx, int qy) : px(px), py(py), qx(qx), qy(qy) {}\n};\n\nint N, K;\nvector<int> a(MAX_D + 1);\nvector<Point> strawberries;\nvector<Line> cuts;\n\nint cross(const Point& o, const Point& a, const Point& b) {\n    return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n}\n\nint side(const Line& l, const Point& p) {\n    Point a(l.px, l.py), b(l.qx, l.qy);\n    long long c = (long long)(b.x - a.x) * (p.y - a.y) - (long long)(b.y - a.y) * (p.x - a.x);\n    if (c > 0) return 1;\n    if (c < 0) return -1;\n    return 0;\n}\n\nvector<vector<int>> regions;\n\nvoid init_regions() {\n    regions.clear();\n    regions.push_back(vector<int>());\n    for (int i = 0; i < N; ++i) {\n        regions[0].push_back(i);\n    }\n}\n\nvoid apply_cut(const Line& cut) {\n    vector<vector<int>> new_regions;\n    for (auto& region : regions) {\n        vector<int> left, right, on;\n        for (int idx : region) {\n            int s = side(cut, strawberries[idx]);\n            if (s == 1) left.push_back(idx);\n            else if (s == -1) right.push_back(idx);\n            else on.push_back(idx);\n        }\n        if (!left.empty()) new_regions.push_back(left);\n        if (!right.empty()) new_regions.push_back(right);\n    }\n    regions = new_regions;\n}\n\nint compute_score() {\n    vector<int> counts(MAX_D + 1, 0);\n    for (auto& region : regions) {\n        int cnt = region.size();\n        if (cnt <= MAX_D) counts[cnt]++;\n    }\n    int score = 0;\n    for (int d = 1; d <= MAX_D; ++d) {\n        score += min(a[d], counts[d]);\n    }\n    return score;\n}\n\nLine generate_line(int idx1, int idx2) {\n    Point p1 = strawberries[idx1];\n    Point p2 = strawberries[idx2];\n    return Line(p1.x, p1.y, p2.x, p2.y);\n}\n\nLine generate_best_line() {\n    Line best_line(0, 0, 0, 0);\n    int best_score = -1;\n    for (int i = 0; i < MAX_ITERATIONS; ++i) {\n        int idx1 = rand() % N;\n        int idx2 = rand() % N;\n        while (idx1 == idx2) idx2 = rand() % N;\n        Line candidate = generate_line(idx1, idx2);\n        vector<vector<int>> temp_regions = regions;\n        apply_cut(candidate);\n        int current_score = compute_score();\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_line = candidate;\n        }\n        regions = temp_regions;\n    }\n    return best_line;\n}\n\nvoid solve() {\n    cin >> N >> K;\n    for (int d = 1; d <= MAX_D; ++d) {\n        cin >> a[d];\n    }\n    strawberries.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> strawberries[i].x >> strawberries[i].y;\n    }\n\n    init_regions();\n    int current_score = compute_score();\n    for (int k = 0; k < K; ++k) {\n        Line best_line = generate_best_line();\n        apply_cut(best_line);\n        int new_score = compute_score();\n        if (new_score > current_score) {\n            current_score = new_score;\n            cuts.push_back(best_line);\n        } else {\n            regions = vector<vector<int>>(1, vector<int>(N));\n            for (int i = 0; i < N; ++i) {\n                regions[0][i] = i;\n            }\n            current_score = compute_score();\n        }\n    }\n\n    cout << cuts.size() << endl;\n    for (auto& cut : cuts) {\n        cout << cut.px << \" \" << cut.py << \" \" << cut.qx << \" \" << cut.qy << endl;\n    }\n}\n\nint main() {\n    srand(time(0));\n    solve();\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <cmath>\n#include <unordered_set>\n#include <chrono>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nint N, M;\nvector<Point> initial_dots;\nvector<vector<bool>> has_dot;\nvector<Rectangle> rectangles;\nint center;\nlong long total_weight = 0;\n\nlong long weight(int x, int y) {\n    long long dx = x - center;\n    long long dy = y - center;\n    return dx * dx + dy * dy + 1;\n}\n\nvoid precompute_weights() {\n    center = (N - 1) / 2;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y < N; ++y) {\n            total_weight += weight(x, y);\n        }\n    }\n}\n\nbool is_valid_point(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_perimeter(const Rectangle& rect) {\n    vector<Point> points = {rect.p1, rect.p2, rect.p3, rect.p4};\n    for (int i = 0; i < 4; ++i) {\n        Point a = points[i];\n        Point b = points[(i + 1) % 4];\n        if (a.x == b.x) {\n            int x = a.x;\n            int y1 = min(a.y, b.y);\n            int y2 = max(a.y, b.y);\n            for (int y = y1; y <= y2; ++y) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        } else if (a.y == b.y) {\n            int y = a.y;\n            int x1 = min(a.x, b.x);\n            int x2 = max(a.x, b.x);\n            for (int x = x1; x <= x2; ++x) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        } else {\n            int dx = b.x - a.x;\n            int dy = b.y - a.y;\n            if (abs(dx) != abs(dy)) {\n                return false;\n            }\n            int step = dx > 0 ? 1 : -1;\n            for (int x = a.x, y = a.y; x != b.x; x += step, y += step * dy / dx) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool check_overlap(const Rectangle& new_rect) {\n    for (const auto& rect : rectangles) {\n        vector<Point> new_points = {new_rect.p1, new_rect.p2, new_rect.p3, new_rect.p4};\n        vector<Point> old_points = {rect.p1, rect.p2, rect.p3, rect.p4};\n        for (int i = 0; i < 4; ++i) {\n            Point a1 = new_points[i];\n            Point b1 = new_points[(i + 1) % 4];\n            for (int j = 0; j < 4; ++j) {\n                Point a2 = old_points[j];\n                Point b2 = old_points[(j + 1) % 4];\n                if (a1 == a2 && b1 == b2) return true;\n                if (a1 == b2 && b1 == a2) return true;\n            }\n        }\n    }\n    return false;\n}\n\nvector<Rectangle> generate_candidates() {\n    vector<Rectangle> candidates;\n    for (int i = 0; i < initial_dots.size(); ++i) {\n        for (int j = i + 1; j < initial_dots.size(); ++j) {\n            Point p2 = initial_dots[i];\n            Point p3 = initial_dots[j];\n            // Axis-aligned rectangle\n            {\n                Point p1(p2.x, p3.y);\n                Point p4(p3.x, p2.y);\n                if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                    Rectangle rect(p1, p2, p3, p4);\n                    if (check_perimeter(rect) && !check_overlap(rect)) {\n                        candidates.push_back(rect);\n                    }\n                }\n            }\n            // 45-degree rotated rectangle\n            {\n                int dx = p3.x - p2.x;\n                int dy = p3.y - p2.y;\n                if (abs(dx) == abs(dy)) {\n                    Point p1(p2.x + dy, p2.y - dx);\n                    Point p4(p3.x + dy, p3.y - dx);\n                    if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                        Rectangle rect(p1, p2, p3, p4);\n                        if (check_perimeter(rect) && !check_overlap(rect)) {\n                            candidates.push_back(rect);\n                        }\n                    }\n                    p1 = Point(p2.x - dy, p2.y + dx);\n                    p4 = Point(p3.x - dy, p3.y + dx);\n                    if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                        Rectangle rect(p1, p2, p3, p4);\n                        if (check_perimeter(rect) && !check_overlap(rect)) {\n                            candidates.push_back(rect);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return candidates;\n}\n\nvoid solve() {\n    precompute_weights();\n    has_dot.assign(N, vector<bool>(N, false));\n    for (const auto& dot : initial_dots) {\n        has_dot[dot.x][dot.y] = true;\n    }\n\n    auto start_time = chrono::high_resolution_clock::now();\n    while (true) {\n        auto candidates = generate_candidates();\n        if (candidates.empty()) break;\n\n        Rectangle best_rect;\n        long long best_score = -1;\n        for (const auto& rect : candidates) {\n            long long current_score = weight(rect.p1.x, rect.p1.y);\n            if (current_score > best_score) {\n                best_score = current_score;\n                best_rect = rect;\n            }\n        }\n\n        if (best_score == -1) break;\n\n        rectangles.push_back(best_rect);\n        has_dot[best_rect.p1.x][best_rect.p1.y] = true;\n        initial_dots.push_back(best_rect.p1);\n\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 4500) break;\n    }\n\n    cout << rectangles.size() << endl;\n    for (const auto& rect : rectangles) {\n        cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n             << rect.p2.x << \" \" << rect.p2.y << \" \"\n             << rect.p3.x << \" \" << rect.p3.y << \" \"\n             << rect.p4.x << \" \" << rect.p4.y << endl;\n    }\n}\n\nint main() {\n    cin >> N >> M;\n    initial_dots.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> initial_dots[i].x >> initial_dots[i].y;\n    }\n    solve();\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <cstring>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 10;\nconst int TOTAL_CANDIES = 100;\nconst vector<char> DIRECTIONS = {'F', 'B', 'L', 'R'};\n\nstruct Grid {\n    int cells[N][N];\n    int empty_count;\n\n    Grid() {\n        memset(cells, 0, sizeof(cells));\n        empty_count = N * N;\n    }\n\n    void place_candy(int pos, int flavor) {\n        int idx = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] == 0) {\n                    if (++idx == pos) {\n                        cells[i][j] = flavor;\n                        empty_count--;\n                        return;\n                    }\n                }\n            }\n        }\n    }\n\n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; ++j) {\n                int write_pos = N - 1;\n                for (int i = N - 1; i >= 0; --i) {\n                    if (cells[i][j] != 0) {\n                        cells[write_pos--][j] = cells[i][j];\n                    }\n                }\n                for (int i = write_pos; i >= 0; --i) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; ++j) {\n                int write_pos = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (cells[i][j] != 0) {\n                        cells[write_pos++][j] = cells[i][j];\n                    }\n                }\n                for (int i = write_pos; i < N; ++i) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; ++i) {\n                int write_pos = 0;\n                for (int j = 0; j < N; ++j) {\n                    if (cells[i][j] != 0) {\n                        cells[i][write_pos++] = cells[i][j];\n                    }\n                }\n                for (int j = write_pos; j < N; ++j) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'R') {\n            for (int i = 0; i < N; ++i) {\n                int write_pos = N - 1;\n                for (int j = N - 1; j >= 0; --j) {\n                    if (cells[i][j] != 0) {\n                        cells[i][write_pos--] = cells[i][j];\n                    }\n                }\n                for (int j = write_pos; j >= 0; --j) {\n                    cells[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    vector<int> get_connected_components() {\n        vector<int> component_sizes;\n        bool visited[N][N] = {false};\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0 && !visited[i][j]) {\n                    int flavor = cells[i][j];\n                    int size = 0;\n                    queue<pair<int, int>> q;\n                    q.push({i, j});\n                    visited[i][j] = true;\n\n                    while (!q.empty()) {\n                        auto [x, y] = q.front();\n                        q.pop();\n                        size++;\n\n                        for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                            int nx = x + dx;\n                            int ny = y + dy;\n                            if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && cells[nx][ny] == flavor) {\n                                visited[nx][ny] = true;\n                                q.push({nx, ny});\n                            }\n                        }\n                    }\n                    component_sizes.push_back(size);\n                }\n            }\n        }\n        return component_sizes;\n    }\n\n    double evaluate() {\n        auto components = get_connected_components();\n        double sum_sq = 0;\n        for (int size : components) {\n            sum_sq += size * size;\n        }\n        int counts[4] = {0};\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    counts[cells[i][j]]++;\n                }\n            }\n        }\n        double denom = 0;\n        for (int i = 1; i <= 3; ++i) {\n            denom += counts[i] * counts[i];\n        }\n        if (denom == 0) return 0;\n        return sum_sq / denom;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<int> flavors(TOTAL_CANDIES);\n    for (int i = 0; i < TOTAL_CANDIES; ++i) {\n        cin >> flavors[i];\n    }\n\n    Grid grid;\n    for (int t = 0; t < TOTAL_CANDIES; ++t) {\n        int pos;\n        cin >> pos;\n        grid.place_candy(pos, flavors[t]);\n\n        if (t == TOTAL_CANDIES - 1) {\n            break;\n        }\n\n        double best_score = -1;\n        char best_dir = 'F';\n        for (char dir : DIRECTIONS) {\n            Grid temp_grid = grid;\n            temp_grid.tilt(dir);\n            double score = temp_grid.evaluate();\n            if (score > best_score) {\n                best_score = score;\n                best_dir = dir;\n            }\n        }\n        grid.tilt(best_dir);\n        cout << best_dir << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <random>\n#include <chrono>\n#include <map>\n#include <set>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Graph {\n    int N;\n    vector<vector<bool>> adj;\n    vector<int> degree;\n    int edge_count;\n    vector<int> degree_seq;\n\n    Graph(int n) : N(n), adj(n, vector<bool>(n, false)), degree(n, 0), edge_count(0) {}\n\n    void add_edge(int u, int v) {\n        if (!adj[u][v]) {\n            adj[u][v] = adj[v][u] = true;\n            degree[u]++;\n            degree[v]++;\n            edge_count++;\n        }\n    }\n\n    void compute_degree_seq() {\n        degree_seq = degree;\n        sort(degree_seq.begin(), degree_seq.end(), greater<int>());\n    }\n\n    string to_string() const {\n        string s;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                s += adj[i][j] ? '1' : '0';\n            }\n        }\n        return s;\n    }\n};\n\nvector<Graph> generate_graphs(int M, int N) {\n    vector<Graph> graphs;\n    for (int k = 0; k < M; ++k) {\n        Graph g(N);\n        // Simple strategy: G_k has k edges, but distributed to make degree sequence unique\n        int edges = k;\n        for (int i = 0; i < N && edges > 0; ++i) {\n            for (int j = i + 1; j < N && edges > 0; ++j) {\n                g.add_edge(i, j);\n                edges--;\n            }\n        }\n        g.compute_degree_seq();\n        graphs.push_back(g);\n    }\n    return graphs;\n}\n\nvector<int> compute_degree_sequence(const string& s, int N) {\n    vector<int> degree(N, 0);\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (s[idx++] == '1') {\n                degree[i]++;\n                degree[j]++;\n            }\n        }\n    }\n    sort(degree.begin(), degree.end(), greater<int>());\n    return degree;\n}\n\nint count_edges(const string& s) {\n    return count(s.begin(), s.end(), '1');\n}\n\ndouble compute_distance(const vector<int>& a, const vector<int>& b) {\n    double dist = 0.0;\n    for (int i = 0; i < a.size(); ++i) {\n        dist += abs(a[i] - b[i]);\n    }\n    return dist;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    cin >> M >> eps;\n\n    // Choose N based on M and eps\n    int N = min(100, max(4, M + 10)); // Heuristic: N should be larger for larger M or eps\n    if (eps > 0.2) {\n        N = min(100, N + 20); // Increase N for higher error rates\n    }\n\n    vector<Graph> graphs = generate_graphs(M, N);\n\n    // Output the graphs\n    cout << N << '\\n';\n    for (const auto& g : graphs) {\n        cout << g.to_string() << '\\n';\n    }\n    cout.flush();\n\n    // Precompute invariants for all G_k\n    vector<int> edge_counts;\n    vector<vector<int>> degree_seqs;\n    for (const auto& g : graphs) {\n        edge_counts.push_back(g.edge_count);\n        degree_seqs.push_back(g.degree_seq);\n    }\n\n    // Process queries\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // Compute invariants for H\n        int edges_H = count_edges(H);\n        vector<int> degree_seq_H = compute_degree_sequence(H, N);\n\n        // Find the closest G_k\n        double min_dist = 1e18;\n        int best_k = 0;\n        for (int k = 0; k < M; ++k) {\n            double dist = abs(edges_H - edge_counts[k]) + compute_distance(degree_seq_H, degree_seqs[k]);\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_k = k;\n            }\n        }\n\n        cout << best_k << '\\n';\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int INF = 1e9;\nconst double INIT_TEMP = 1e4;\nconst double FINAL_TEMP = 1e-4;\nconst double COOLING_RATE = 0.999;\nconst int MAX_ITER = 100000;\n\nstruct Edge {\n    int u, v, w, idx;\n};\n\nstruct Point {\n    int x, y;\n};\n\nint N, M, D, K;\nvector<Edge> edges;\nvector<Point> points;\nvector<vector<int>> adj;\nvector<vector<int>> dist;\nvector<int> schedule;\n\nvoid read_input() {\n    cin >> N >> M >> D >> K;\n    edges.resize(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        edges[i].idx = i;\n    }\n    points.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> points[i].x >> points[i].y;\n    }\n}\n\nvoid compute_apsp() {\n    dist.assign(N, vector<int>(N, INF));\n    for (int i = 0; i < N; ++i) {\n        dist[i][i] = 0;\n    }\n    for (const auto& e : edges) {\n        dist[e.u][e.v] = min(dist[e.u][e.v], e.w);\n        dist[e.v][e.u] = min(dist[e.v][e.u], e.w);\n    }\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 (dist[i][k] < INF && dist[k][j] < INF) {\n                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n                }\n            }\n        }\n    }\n}\n\nvector<vector<int>> compute_daily_dist(int day) {\n    vector<vector<int>> daily_dist = dist;\n    for (int i = 0; i < M; ++i) {\n        if (schedule[i] == day) {\n            const auto& e = edges[i];\n            daily_dist[e.u][e.v] = INF;\n            daily_dist[e.v][e.u] = INF;\n        }\n    }\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 (daily_dist[i][k] < INF && daily_dist[k][j] < INF) {\n                    daily_dist[i][j] = min(daily_dist[i][j], daily_dist[i][k] + daily_dist[k][j]);\n                }\n            }\n        }\n    }\n    return daily_dist;\n}\n\ndouble compute_frustration() {\n    double total_frustration = 0.0;\n    for (int day = 1; day <= D; ++day) {\n        auto daily_dist = compute_daily_dist(day);\n        double sum_diff = 0.0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                int original = dist[i][j];\n                int current = daily_dist[i][j];\n                if (current >= INF) current = INF;\n                sum_diff += (current - original);\n            }\n        }\n        double f_k = sum_diff / (N * (N - 1) / 2);\n        total_frustration += f_k;\n    }\n    return total_frustration / D;\n}\n\nvoid initial_schedule() {\n    schedule.assign(M, 0);\n    vector<int> day_counts(D, 0);\n    for (int i = 0; i < M; ++i) {\n        int day = rand() % D + 1;\n        while (day_counts[day - 1] >= K) {\n            day = rand() % D + 1;\n        }\n        schedule[i] = day;\n        day_counts[day - 1]++;\n    }\n}\n\nvoid simulated_annealing() {\n    initial_schedule();\n    double current_frustration = compute_frustration();\n    double temp = INIT_TEMP;\n    int iter = 0;\n    while (temp > FINAL_TEMP && iter < MAX_ITER) {\n        int edge_idx = rand() % M;\n        int old_day = schedule[edge_idx];\n        int new_day = rand() % D + 1;\n        if (count(schedule.begin(), schedule.end(), new_day) >= K) {\n            continue;\n        }\n        schedule[edge_idx] = new_day;\n        double new_frustration = compute_frustration();\n        double delta = new_frustration - current_frustration;\n        if (delta < 0 || exp(-delta / temp) > (double)rand() / RAND_MAX) {\n            current_frustration = new_frustration;\n        } else {\n            schedule[edge_idx] = old_day;\n        }\n        temp *= COOLING_RATE;\n        iter++;\n    }\n}\n\nint main() {\n    srand(time(0));\n    read_input();\n    compute_apsp();\n    simulated_annealing();\n    for (int i = 0; i < M; ++i) {\n        cout << schedule[i] << (i == M - 1 ? \"\\n\" : \" \");\n    }\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <unordered_set>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n    Point(int x = 0, int y = 0, int z = 0) : x(x), y(y), z(z) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y && z == other.z;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        if (y != other.y) return y < other.y;\n        return z < other.z;\n    }\n};\n\nstruct Block {\n    vector<Point> cubes;\n    int id;\n    Block(int id = 0) : id(id) {}\n    void add_cube(const Point& p) {\n        cubes.push_back(p);\n    }\n    bool is_connected() const {\n        if (cubes.empty()) return true;\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        queue<Point> q;\n        q.push(cubes[0]);\n        visited[cubes[0].x][cubes[0].y][cubes[0].z] = true;\n        int count = 1;\n        while (!q.empty()) {\n            Point p = q.front();\n            q.pop();\n            for (const auto& cube : cubes) {\n                if (!visited[cube.x][cube.y][cube.z]) {\n                    int dx = abs(p.x - cube.x);\n                    int dy = abs(p.y - cube.y);\n                    int dz = abs(p.z - cube.z);\n                    if ((dx == 1 && dy == 0 && dz == 0) ||\n                        (dx == 0 && dy == 1 && dz == 0) ||\n                        (dx == 0 && dy == 0 && dz == 1)) {\n                        visited[cube.x][cube.y][cube.z] = true;\n                        q.push(cube);\n                        count++;\n                    }\n                }\n            }\n        }\n        return count == cubes.size();\n    }\n};\n\nint D;\nvector<vector<string>> f(2, vector<string>(D));\nvector<vector<string>> r(2, vector<string>(D));\nvector<vector<vector<int>>> b(2, vector<vector<int>>(D, vector<int>(D, 0)));\nvector<Block> blocks;\nint block_id = 1;\n\nbool can_place_block(const Block& block, int obj_idx, const vector<vector<vector<int>>>& grid) {\n    for (const auto& cube : block.cubes) {\n        if (cube.x < 0 || cube.x >= D || cube.y < 0 || cube.y >= D || cube.z < 0 || cube.z >= D) {\n            return false;\n        }\n        if (grid[cube.x][cube.y][cube.z] != 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid place_block(const Block& block, int obj_idx, int id) {\n    for (const auto& cube : block.cubes) {\n        b[obj_idx][cube.x][cube.y][cube.z] = id;\n    }\n}\n\nvoid remove_block(const Block& block, int obj_idx) {\n    for (const auto& cube : block.cubes) {\n        b[obj_idx][cube.x][cube.y][cube.z] = 0;\n    }\n}\n\nbool satisfies_silhouette(int obj_idx) {\n    for (int z = 0; z < D; ++z) {\n        for (int x = 0; x < D; ++x) {\n            bool found = false;\n            for (int y = 0; y < D; ++y) {\n                if (b[obj_idx][x][y][z] != 0) {\n                    found = true;\n                    break;\n                }\n            }\n            if (f[obj_idx][z][x] == '1' && !found) {\n                return false;\n            }\n        }\n    }\n    for (int z = 0; z < D; ++z) {\n        for (int y = 0; y < D; ++y) {\n            bool found = false;\n            for (int x = 0; x < D; ++x) {\n                if (b[obj_idx][x][y][z] != 0) {\n                    found = true;\n                    break;\n                }\n            }\n            if (r[obj_idx][z][y] == '1' && !found) {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nvoid generate_initial_blocks() {\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[obj_idx][z][x] == '1' && r[obj_idx][z][y] == '1') {\n                        bool found = false;\n                        for (const auto& block : blocks) {\n                            for (const auto& cube : block.cubes) {\n                                if (cube.x == x && cube.y == y && cube.z == z) {\n                                    found = true;\n                                    break;\n                                }\n                            }\n                            if (found) break;\n                        }\n                        if (!found) {\n                            Block block(block_id++);\n                            block.add_cube(Point(x, y, z));\n                            blocks.push_back(block);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid merge_blocks() {\n    bool merged;\n    do {\n        merged = false;\n        for (size_t i = 0; i < blocks.size(); ++i) {\n            for (size_t j = i + 1; j < blocks.size(); ++j) {\n                Block new_block(block_id);\n                for (const auto& cube : blocks[i].cubes) {\n                    new_block.add_cube(cube);\n                }\n                for (const auto& cube : blocks[j].cubes) {\n                    new_block.add_cube(cube);\n                }\n                if (new_block.is_connected()) {\n                    vector<Block> new_blocks;\n                    for (size_t k = 0; k < blocks.size(); ++k) {\n                        if (k != i && k != j) {\n                            new_blocks.push_back(blocks[k]);\n                        }\n                    }\n                    new_blocks.push_back(new_block);\n                    blocks = new_blocks;\n                    block_id++;\n                    merged = true;\n                    break;\n                }\n            }\n            if (merged) break;\n        }\n    } while (merged);\n}\n\nvoid assign_blocks_to_objects() {\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        vector<vector<vector<int>>> grid(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        for (const auto& block : blocks) {\n            bool used = false;\n            for (const auto& cube : block.cubes) {\n                if (f[obj_idx][cube.z][cube.x] == '1' && r[obj_idx][cube.z][cube.y] == '1') {\n                    used = true;\n                    break;\n                }\n            }\n            if (used) {\n                place_block(block, obj_idx, block.id);\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> D;\n    f.resize(2, vector<string>(D));\n    r.resize(2, vector<string>(D));\n    b.resize(2, vector<vector<int>>(D, vector<int>(D, 0)));\n\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> f[i][k];\n        }\n        for (int k = 0; k < D; ++k) {\n            cin >> r[i][k];\n        }\n    }\n\n    generate_initial_blocks();\n    merge_blocks();\n    assign_blocks_to_objects();\n\n    set<int> used_blocks;\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (b[obj_idx][x][y][z] != 0) {\n                        used_blocks.insert(b[obj_idx][x][y][z]);\n                    }\n                }\n            }\n        }\n    }\n\n    vector<int> block_ids;\n    for (const auto& block : blocks) {\n        block_ids.push_back(block.id);\n    }\n    sort(block_ids.begin(), block_ids.end());\n    block_ids.erase(unique(block_ids.begin(), block_ids.end()), block_ids.end());\n\n    cout << block_ids.size() << endl;\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    cout << b[obj_idx][x][y][z] << \" \";\n                }\n            }\n        }\n        cout << endl;\n    }\n\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v, w, idx;\n    double dist;\n};\n\nstruct Resident {\n    int x, y;\n};\n\nstruct Station {\n    int x, y;\n    int P;\n    vector<int> residents;\n};\n\ndouble euclidean(int x1, int y1, int x2, int y2) {\n    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<Station> stations(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> stations[i].x >> stations[i].y;\n        stations[i].P = 0;\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        edges[i].idx = i;\n        edges[i].dist = euclidean(stations[edges[i].u].x, stations[edges[i].u].y,\n                                  stations[edges[i].v].x, stations[edges[i].v].y);\n    }\n\n    vector<Resident> residents(K);\n    for (int i = 0; i < K; ++i) {\n        cin >> residents[i].x >> residents[i].y;\n    }\n\n    // Step 1: Assign residents to nearest station\n    for (int i = 0; i < K; ++i) {\n        double min_dist = 1e9;\n        int best_station = -1;\n        for (int j = 0; j < N; ++j) {\n            double dist = euclidean(residents[i].x, residents[i].y, stations[j].x, stations[j].y);\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_station = j;\n            }\n        }\n        stations[best_station].residents.push_back(i);\n    }\n\n    // Step 2: Compute MST using Kruskal's algorithm\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.w < b.w;\n    });\n\n    dsu uf(N);\n    vector<bool> edge_used(M, false);\n    vector<vector<pair<int, int>>> mst(N); // {neighbor, edge_idx}\n\n    for (const Edge& e : edges) {\n        if (!uf.same(e.u, e.v)) {\n            uf.merge(e.u, e.v);\n            edge_used[e.idx] = true;\n            mst[e.u].emplace_back(e.v, e.idx);\n            mst[e.v].emplace_back(e.u, e.idx);\n        }\n    }\n\n    // Step 3: Set initial P_i to cover all residents\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].residents.empty()) {\n            stations[i].P = 0;\n            continue;\n        }\n        double max_dist = 0;\n        for (int r : stations[i].residents) {\n            double dist = euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y);\n            if (dist > max_dist) {\n                max_dist = dist;\n            }\n        }\n        stations[i].P = min(5000, (int)ceil(max_dist));\n    }\n\n    // Step 4: Optimize P_i and edge selection\n    vector<bool> covered(K, false);\n    auto check_coverage = [&]() {\n        fill(covered.begin(), covered.end(), false);\n        for (int i = 0; i < N; ++i) {\n            for (int r : stations[i].residents) {\n                if (euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y) <= stations[i].P) {\n                    covered[r] = true;\n                }\n            }\n        }\n        return all_of(covered.begin(), covered.end(), [](bool c) { return c; });\n    };\n\n    if (!check_coverage()) {\n        // Fallback: ensure all residents are covered\n        for (int i = 0; i < N; ++i) {\n            double max_dist = 0;\n            for (int r : stations[i].residents) {\n                double dist = euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y);\n                if (dist > max_dist) {\n                    max_dist = dist;\n                }\n            }\n            stations[i].P = min(5000, (int)ceil(max_dist));\n        }\n    }\n\n    // Try to reduce P_i\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].P == 0) continue;\n        int original_P = stations[i].P;\n        for (int p = original_P - 1; p >= 0; --p) {\n            int old_P = stations[i].P;\n            stations[i].P = p;\n            if (!check_coverage()) {\n                stations[i].P = old_P;\n                break;\n            }\n        }\n    }\n\n    // Step 5: Prune unnecessary edges\n    vector<bool> necessary_edge(M, false);\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].P > 0) {\n            // BFS to mark necessary edges\n            vector<bool> visited(N, false);\n            queue<int> q;\n            q.push(i);\n            visited[i] = true;\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (auto [v, idx] : mst[u]) {\n                    if (!visited[v] && edge_used[idx]) {\n                        necessary_edge[idx] = true;\n                        visited[v] = true;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n\n    // Ensure station 1 is connected\n    vector<bool> visited(N, false);\n    queue<int> q;\n    q.push(0);\n    visited[0] = true;\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        for (auto [v, idx] : mst[u]) {\n            if (!visited[v] && edge_used[idx]) {\n                necessary_edge[idx] = true;\n                visited[v] = true;\n                q.push(v);\n            }\n        }\n    }\n\n    for (int i = 0; i < M; ++i) {\n        if (!necessary_edge[i]) {\n            edge_used[i] = false;\n        }\n    }\n\n    // Step 6: Output the solution\n    for (int i = 0; i < N; ++i) {\n        cout << stations[i].P << (i == N - 1 ? \"\\n\" : \" \");\n    }\n    for (int i = 0; i < M; ++i) {\n        cout << edge_used[i] << (i == M - 1 ? \"\\n\" : \" \");\n    }\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nconst int N = 30;\nconst int TOTAL_BALLS = N * (N + 1) / 2;\nconst int MAX_OPERATIONS = 10000;\n\nstruct Position {\n    int x, y;\n    Position(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Position& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Position& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nvector<Position> directions = {\n    {-1, -1}, {-1, 0}, {0, -1}, {0, 1}, {1, 0}, {1, 1}\n};\n\nvector<vector<int>> pyramid(N, vector<int>(N, -1));\nvector<pair<Position, Position>> operations;\n\nbool is_valid(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y <= x;\n}\n\nvector<Position> get_adjacent_positions(int x, int y) {\n    vector<Position> adj;\n    for (auto& dir : directions) {\n        int nx = x + dir.x;\n        int ny = y + dir.y;\n        if (is_valid(nx, ny)) {\n            adj.emplace_back(nx, ny);\n        }\n    }\n    return adj;\n}\n\nvoid swap_balls(Position a, Position b) {\n    if (!is_valid(a.x, a.y) || !is_valid(b.x, b.y)) return;\n    swap(pyramid[a.x][a.y], pyramid[b.x][b.y]);\n    operations.emplace_back(a, b);\n}\n\nint count_violations() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int current = pyramid[x][y];\n            int child1 = pyramid[x + 1][y];\n            int child2 = pyramid[x + 1][y + 1];\n            if (current > child1) violations++;\n            if (current > child2) violations++;\n        }\n    }\n    return violations;\n}\n\nPosition find_ball(int num) {\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] == num) {\n                return Position(x, y);\n            }\n        }\n    }\n    return Position(-1, -1);\n}\n\nvector<Position> find_path(Position start, Position target) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    vector<vector<Position>> parent(N, vector<Position>(N, Position(-1, -1)));\n    queue<Position> q;\n    q.push(start);\n    visited[start.x][start.y] = true;\n\n    while (!q.empty()) {\n        Position current = q.front();\n        q.pop();\n        if (current.x == target.x && current.y == target.y) {\n            vector<Position> path;\n            while (!(current.x == start.x && current.y == start.y)) {\n                path.push_back(current);\n                current = parent[current.x][current.y];\n            }\n            path.push_back(start);\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        for (auto& dir : directions) {\n            int nx = current.x + dir.x;\n            int ny = current.y + dir.y;\n            if (is_valid(nx, ny) && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                parent[nx][ny] = current;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return {};\n}\n\nvoid move_ball(Position start, Position target) {\n    vector<Position> path = find_path(start, target);\n    if (path.empty()) return;\n    for (size_t i = 0; i < path.size() - 1; ++i) {\n        swap_balls(path[i], path[i + 1]);\n        if (operations.size() >= MAX_OPERATIONS) {\n            return;\n        }\n    }\n}\n\nvoid solve() {\n    // Read input\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            cin >> pyramid[x][y];\n        }\n    }\n\n    // Target: smallest numbers at the top\n    vector<int> sorted_balls(TOTAL_BALLS);\n    for (int i = 0; i < TOTAL_BALLS; ++i) {\n        sorted_balls[i] = i;\n    }\n\n    // Initial placement\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int target_num = sorted_balls[x * (x + 1) / 2 + y];\n            Position current_pos = find_ball(target_num);\n            if (current_pos.x != x || current_pos.y != y) {\n                move_ball(current_pos, Position(x, y));\n                if (operations.size() >= MAX_OPERATIONS) {\n                    cout << operations.size() << endl;\n                    for (auto& op : operations) {\n                        cout << op.first.x << \" \" << op.first.y << \" \"\n                             << op.second.x << \" \" << op.second.y << endl;\n                    }\n                    return;\n                }\n            }\n        }\n    }\n\n    // Fix violations\n    int violations = count_violations();\n    while (violations > 0 && operations.size() < MAX_OPERATIONS) {\n        bool improved = false;\n        for (int x = 0; x < N - 1; ++x) {\n            for (int y = 0; y <= x; ++y) {\n                int current = pyramid[x][y];\n                int child1 = pyramid[x + 1][y];\n                int child2 = pyramid[x + 1][y + 1];\n                if (current > child1 || current > child2) {\n                    vector<Position> adj = get_adjacent_positions(x, y);\n                    int min_val = current;\n                    Position best_swap = Position(-1, -1);\n                    for (auto& pos : adj) {\n                        if (pyramid[pos.x][pos.y] < min_val) {\n                            min_val = pyramid[pos.x][pos.y];\n                            best_swap = pos;\n                        }\n                    }\n                    if (best_swap.x != -1) {\n                        swap_balls(Position(x, y), best_swap);\n                        improved = true;\n                        if (operations.size() >= MAX_OPERATIONS) {\n                            cout << operations.size() << endl;\n                            for (auto& op : operations) {\n                                cout << op.first.x << \" \" << op.first.y << \" \"\n                                     << op.second.x << \" \" << op.second.y << endl;\n                            }\n                            return;\n                        }\n                    }\n                }\n            }\n        }\n        if (!improved) break;\n        violations = count_violations();\n    }\n\n    cout << operations.size() << endl;\n    for (auto& op : operations) {\n        cout << op.first.x << \" \" << op.first.y << \" \"\n             << op.second.x << \" \" << op.second.y << endl;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <set>\n#include <climits>\n#include <cstring>\n\nusing namespace std;\n\nconst int GRID_SIZE = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = (GRID_SIZE - 1) / 2;\n\nstruct Cell {\n    int i, j;\n    bool operator<(const Cell& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nint grid[GRID_SIZE][GRID_SIZE];\nbool is_obstacle[GRID_SIZE][GRID_SIZE];\nbool is_container[GRID_SIZE][GRID_SIZE];\nint container_num[GRID_SIZE][GRID_SIZE];\nvector<Cell> containers;\n\nint di[] = {-1, 1, 0, 0};\nint dj[] = {0, 0, -1, 1};\n\nbool is_valid(int i, int j) {\n    return i >= 0 && i < GRID_SIZE && j >= 0 && j < GRID_SIZE;\n}\n\nvector<Cell> bfs_reachable() {\n    vector<Cell> reachable;\n    bool visited[GRID_SIZE][GRID_SIZE];\n    memset(visited, false, sizeof(visited));\n    queue<Cell> q;\n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n\n    while (!q.empty()) {\n        Cell current = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int ni = current.i + di[k];\n            int nj = current.j + dj[k];\n            if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj] && !is_container[ni][nj]) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n            }\n        }\n    }\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (visited[i][j] && !is_obstacle[i][j] && !is_container[i][j] && !(i == ENTRANCE_I && j == ENTRANCE_J)) {\n                reachable.push_back({i, j});\n            }\n        }\n    }\n    return reachable;\n}\n\nvector<Cell> bfs_removable() {\n    vector<Cell> removable;\n    bool visited[GRID_SIZE][GRID_SIZE];\n    memset(visited, false, sizeof(visited));\n    queue<Cell> q;\n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n\n    while (!q.empty()) {\n        Cell current = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int ni = current.i + di[k];\n            int nj = current.j + dj[k];\n            if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj]) {\n                if (is_container[ni][nj]) {\n                    removable.push_back({ni, nj});\n                } else {\n                    visited[ni][nj] = true;\n                    q.push({ni, nj});\n                }\n            }\n        }\n    }\n    return removable;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int D, N;\n    cin >> D >> N;\n    memset(is_obstacle, false, sizeof(is_obstacle));\n    memset(is_container, false, sizeof(is_container));\n    memset(container_num, -1, sizeof(container_num));\n\n    for (int i = 0; i < N; ++i) {\n        int ri, rj;\n        cin >> ri >> rj;\n        is_obstacle[ri][rj] = true;\n    }\n\n    int total_containers = GRID_SIZE * GRID_SIZE - 1 - N;\n    for (int d = 0; d < total_containers; ++d) {\n        int t;\n        cin >> t;\n        vector<Cell> reachable = bfs_reachable();\n        if (reachable.empty()) {\n            cerr << \"No reachable cells left!\" << endl;\n            return 1;\n        }\n\n        // Place the container in the cell with the highest BFS distance from entrance\n        bool visited[GRID_SIZE][GRID_SIZE];\n        memset(visited, false, sizeof(visited));\n        queue<Cell> q;\n        q.push({ENTRANCE_I, ENTRANCE_J});\n        visited[ENTRANCE_I][ENTRANCE_J] = true;\n        Cell farthest = {ENTRANCE_I, ENTRANCE_J};\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            farthest = current;\n            for (int k = 0; k < 4; ++k) {\n                int ni = current.i + di[k];\n                int nj = current.j + dj[k];\n                if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj] && !is_container[ni][nj]) {\n                    visited[ni][nj] = true;\n                    q.push({ni, nj});\n                }\n            }\n        }\n\n        // Place the container at the farthest cell\n        is_container[farthest.i][farthest.j] = true;\n        container_num[farthest.i][farthest.j] = t;\n        containers.push_back({farthest.i, farthest.j});\n        cout << farthest.i << \" \" << farthest.j << endl;\n        cout.flush();\n    }\n\n    // Determine the removal order\n    vector<Cell> removal_order;\n    while (removal_order.size() < total_containers) {\n        vector<Cell> removable = bfs_removable();\n        if (removable.empty()) {\n            cerr << \"No removable containers left!\" << endl;\n            return 1;\n        }\n\n        // Find the container with the smallest number among removable\n        int min_num = INT_MAX;\n        Cell to_remove;\n        for (const Cell& cell : removable) {\n            if (container_num[cell.i][cell.j] < min_num) {\n                min_num = container_num[cell.i][cell.j];\n                to_remove = cell;\n            }\n        }\n\n        removal_order.push_back(to_remove);\n        is_container[to_remove.i][to_remove.j] = false;\n    }\n\n    for (const Cell& cell : removal_order) {\n        cout << cell.i << \" \" << cell.j << endl;\n    }\n    cout.flush();\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int n = 50;\nconst int m = 100;\nconst int dx[] = {1, 0, -1, 0};\nconst int dy[] = {0, 1, 0, -1};\n\nstruct Cell {\n    int x, y;\n    Cell(int x = 0, int y = 0) : x(x), y(y) {}\n};\n\nvector<vector<int>> input_grid(n, vector<int>(n));\nvector<set<int>> adjacency(m + 1);\nvector<vector<Cell>> ward_cells(m + 1);\nvector<vector<bool>> is_boundary(n, vector<bool>(n, false));\n\nvoid read_input() {\n    cin >> n >> m;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> input_grid[i][j];\n            ward_cells[input_grid[i][j]].emplace_back(i, j);\n        }\n    }\n}\n\nvoid compute_adjacency() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            int c = input_grid[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = input_grid[ni][nj];\n                    if (nc != c) {\n                        adjacency[c].insert(nc);\n                        adjacency[nc].insert(c);\n                    }\n                } else {\n                    adjacency[c].insert(0);\n                    adjacency[0].insert(c);\n                }\n            }\n        }\n    }\n}\n\nvoid compute_boundary() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni < 0 || ni >= n || nj < 0 || nj >= n) {\n                    is_boundary[i][j] = true;\n                    break;\n                }\n            }\n        }\n    }\n}\n\nvector<vector<int>> create_initial_solution() {\n    vector<vector<int>> grid(n, vector<int>(n, 0));\n    vector<set<int>> required_adj(m + 1);\n    for (int c = 1; c <= m; ++c) {\n        required_adj[c] = adjacency[c];\n    }\n\n    // Place each ward as a single cell\n    vector<Cell> positions;\n    for (int c = 1; c <= m; ++c) {\n        if (!ward_cells[c].empty()) {\n            Cell pos = ward_cells[c][0];\n            grid[pos.x][pos.y] = c;\n            positions.emplace_back(pos.x, pos.y);\n        }\n    }\n\n    // Expand wards to satisfy adjacency\n    for (int c = 1; c <= m; ++c) {\n        if (ward_cells[c].empty()) continue;\n        queue<Cell> q;\n        vector<vector<bool>> visited(n, vector<bool>(n, false));\n        for (const auto& cell : ward_cells[c]) {\n            if (grid[cell.x][cell.y] == c) {\n                q.push(cell);\n                visited[cell.x][cell.y] = true;\n            }\n        }\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int ni = current.x + dx[d];\n                int nj = current.y + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj]) {\n                    int nc = grid[ni][nj];\n                    if (nc == 0) {\n                        if (required_adj[c].count(0) || !required_adj[c].empty()) {\n                            grid[ni][nj] = c;\n                            visited[ni][nj] = true;\n                            q.push(Cell(ni, nj));\n                        }\n                    } else if (nc != c) {\n                        if (required_adj[c].count(nc)) {\n                            required_adj[c].erase(nc);\n                            required_adj[nc].erase(c);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Ensure all adjacencies are satisfied\n    for (int c = 1; c <= m; ++c) {\n        if (!required_adj[c].empty()) {\n            for (int nc : required_adj[c]) {\n                if (nc == 0) continue;\n                // Find a cell of c and nc to connect\n                for (const auto& cell : ward_cells[c]) {\n                    if (grid[cell.x][cell.y] != c) continue;\n                    for (int d = 0; d < 4; ++d) {\n                        int ni = cell.x + dx[d];\n                        int nj = cell.y + dy[d];\n                        if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] == 0) {\n                            grid[ni][nj] = c;\n                            break;\n                        }\n                    }\n                    break;\n                }\n            }\n        }\n    }\n\n    return grid;\n}\n\nvoid optimize_solution(vector<vector<int>>& grid) {\n    // Simple optimization: try to replace color-0 cells with adjacent colors if possible\n    bool improved;\n    do {\n        improved = false;\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] != 0) continue;\n                set<int> adjacent_colors;\n                for (int d = 0; d < 4; ++d) {\n                    int ni = i + dx[d];\n                    int nj = j + dy[d];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                        adjacent_colors.insert(grid[ni][nj]);\n                    }\n                }\n                if (adjacent_colors.size() == 1) {\n                    int c = *adjacent_colors.begin();\n                    if (c != 0) {\n                        grid[i][j] = c;\n                        improved = true;\n                    }\n                }\n            }\n        }\n    } while (improved);\n}\n\nbool check_connectivity(const vector<vector<int>>& grid) {\n    for (int c = 1; c <= m; ++c) {\n        vector<vector<bool>> visited(n, vector<bool>(n, false));\n        queue<Cell> q;\n        bool found = false;\n        for (int i = 0; i < n && !found; ++i) {\n            for (int j = 0; j < n && !found; ++j) {\n                if (grid[i][j] == c) {\n                    q.push(Cell(i, j));\n                    visited[i][j] = true;\n                    found = true;\n                }\n            }\n        }\n        if (!found) continue;\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int ni = current.x + dx[d];\n                int nj = current.y + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj] && grid[ni][nj] == c) {\n                    visited[ni][nj] = true;\n                    q.push(Cell(ni, nj));\n                }\n            }\n        }\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] == c && !visited[i][j]) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool check_adjacency(const vector<vector<int>>& grid) {\n    vector<set<int>> current_adj(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            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = grid[ni][nj];\n                    if (nc != c) {\n                        current_adj[c].insert(nc);\n                        current_adj[nc].insert(c);\n                    }\n                } else {\n                    current_adj[c].insert(0);\n                    current_adj[0].insert(c);\n                }\n            }\n        }\n    }\n    for (int c = 0; c <= m; ++c) {\n        if (current_adj[c] != adjacency[c]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    read_input();\n    compute_adjacency();\n    compute_boundary();\n\n    vector<vector<int>> grid = create_initial_solution();\n    optimize_solution(grid);\n\n    // Verify the solution\n    if (!check_connectivity(grid) || !check_adjacency(grid)) {\n        // Fallback: output the original grid (though it may not be optimal)\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << input_grid[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n    } else {\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << grid[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <queue>\n#include <set>\n#include <map>\n#include <chrono>\n#include <cassert>\n\nusing namespace std;\nusing namespace std::chrono;\n\nstruct Item {\n    int id;\n    double weight;\n    bool operator<(const Item& other) const {\n        return weight > other.weight; // For max-heap\n    }\n};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nvector<int> solve(int N, int D, int Q) {\n    vector<double> weights(N, 1.0); // Initial guess\n    vector<vector<double>> constraints;\n    vector<int> comparison_results;\n\n    auto query = [&](const vector<int>& L, const vector<int>& R) {\n        cout << L.size() << \" \" << R.size();\n        for (int l : L) cout << \" \" << l;\n        for (int r : R) cout << \" \" << r;\n        cout << endl;\n        cout.flush();\n\n        string result;\n        cin >> result;\n        if (result == \"<\") return -1;\n        else if (result == \">\") return 1;\n        else return 0;\n    };\n\n    // Initial pairwise comparisons to establish order\n    for (int i = 0; i < N && Q > 0; ++i) {\n        for (int j = i + 1; j < N && Q > 0; ++j) {\n            vector<int> L = {i}, R = {j};\n            int res = query(L, R);\n            comparison_results.push_back(res);\n            Q--;\n            if (res == -1) {\n                weights[i] = 0.9 * weights[i];\n                weights[j] = 1.1 * weights[j];\n            } else if (res == 1) {\n                weights[i] = 1.1 * weights[i];\n                weights[j] = 0.9 * weights[j];\n            }\n        }\n    }\n\n    // Refine weights using more queries\n    while (Q > 0) {\n        vector<int> L, R;\n        uniform_int_distribution<int> dist(0, N - 1);\n        int size = min(5, N / 2);\n        set<int> used;\n        while (L.size() < size) {\n            int item = dist(rng);\n            if (used.count(item)) continue;\n            used.insert(item);\n            L.push_back(item);\n        }\n        used.clear();\n        while (R.size() < size) {\n            int item = dist(rng);\n            if (used.count(item) || find(L.begin(), L.end(), item) != L.end()) continue;\n            used.insert(item);\n            R.push_back(item);\n        }\n        if (L.empty() || R.empty()) continue;\n        int res = query(L, R);\n        Q--;\n        double sum_L = accumulate(L.begin(), L.end(), 0.0, [&](double s, int i) { return s + weights[i]; });\n        double sum_R = accumulate(R.begin(), R.end(), 0.0, [&](double s, int i) { return s + weights[i]; });\n        if (res == -1) {\n            for (int l : L) weights[l] *= 0.99;\n            for (int r : R) weights[r] *= 1.01;\n        } else if (res == 1) {\n            for (int l : L) weights[l] *= 1.01;\n            for (int r : R) weights[r] *= 0.99;\n        }\n    }\n\n    // Partition into D sets\n    vector<int> assignment(N, 0);\n    vector<double> set_sums(D, 0.0);\n    vector<Item> items;\n    for (int i = 0; i < N; ++i) {\n        items.push_back({i, weights[i]});\n    }\n    sort(items.begin(), items.end(), [](const Item& a, const Item& b) {\n        return a.weight > b.weight;\n    });\n\n    for (const auto& item : items) {\n        int best_set = 0;\n        double min_sum = set_sums[0];\n        for (int d = 1; d < D; ++d) {\n            if (set_sums[d] < min_sum) {\n                min_sum = set_sums[d];\n                best_set = d;\n            }\n        }\n        assignment[item.id] = best_set;\n        set_sums[best_set] += item.weight;\n    }\n\n    return assignment;\n}\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n\n    auto assignment = solve(N, D, Q);\n\n    for (int i = 0; i < N; ++i) {\n        cout << assignment[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n    cout.flush();\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Box {\n    int value;\n    int stack;\n    int pos; // position from bottom (0-based)\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n = 200, m = 10;\n    cin >> n >> m;\n\n    vector<vector<int>> stacks(m);\n    unordered_map<int, Box> box_info;\n    vector<int> next_box_pos(m, 0); // next position to check in each stack (from top)\n\n    for (int i = 0; i < m; ++i) {\n        stacks[i].resize(n / m);\n        for (int j = 0; j < n / m; ++j) {\n            cin >> stacks[i][j];\n            box_info[stacks[i][j]] = {stacks[i][j], i, j};\n        }\n    }\n\n    vector<pair<int, int>> operations;\n    int next_box = 1;\n    int total_energy = 0;\n    int max_operations = 5000;\n\n    auto get_top_box = [&](int stack_idx) {\n        if (stacks[stack_idx].empty()) return -1;\n        return stacks[stack_idx].back();\n    };\n\n    auto move_boxes = [&](int v, int dest_stack) {\n        int src_stack = box_info[v].stack;\n        int pos = box_info[v].pos;\n        int num_boxes = stacks[src_stack].size() - pos;\n        if (num_boxes <= 0) return false; // should not happen\n\n        // Remove boxes from src_stack\n        vector<int> moved_boxes;\n        for (int i = pos; i < stacks[src_stack].size(); ++i) {\n            moved_boxes.push_back(stacks[src_stack][i]);\n        }\n        stacks[src_stack].resize(pos);\n\n        // Add to dest_stack\n        for (int box : moved_boxes) {\n            stacks[dest_stack].push_back(box);\n            box_info[box].stack = dest_stack;\n            box_info[box].pos = stacks[dest_stack].size() - 1;\n        }\n\n        operations.emplace_back(v, dest_stack);\n        total_energy += num_boxes + 1;\n        return true;\n    };\n\n    auto carry_out = [&](int v) {\n        int stack = box_info[v].stack;\n        stacks[stack].pop_back();\n        operations.emplace_back(v, 0);\n    };\n\n    auto find_dest_stack = [&](int v) {\n        int src_stack = box_info[v].stack;\n        vector<int> candidates;\n        for (int i = 0; i < m; ++i) {\n            if (i == src_stack) continue;\n            if (stacks[i].empty()) {\n                candidates.push_back(i);\n                continue;\n            }\n            int top_box = get_top_box(i);\n            if (top_box > v) {\n                candidates.push_back(i);\n            }\n        }\n\n        if (candidates.empty()) {\n            for (int i = 0; i < m; ++i) {\n                if (i != src_stack) {\n                    candidates.push_back(i);\n                }\n            }\n        }\n\n        // Choose the stack with the smallest size\n        int best_stack = candidates[0];\n        for (int stack : candidates) {\n            if (stacks[stack].size() < stacks[best_stack].size()) {\n                best_stack = stack;\n            }\n        }\n        return best_stack;\n    };\n\n    while (next_box <= n && operations.size() < max_operations) {\n        int stack = box_info[next_box].stack;\n        int pos = box_info[next_box].pos;\n        if (pos == stacks[stack].size() - 1) {\n            carry_out(next_box);\n            next_box++;\n        } else {\n            int dest_stack = find_dest_stack(next_box);\n            move_boxes(next_box, dest_stack);\n        }\n    }\n\n    // Output operations\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <climits>\n#include <tuple>\n\nusing namespace std;\n\nconst int MAX_N = 40;\nconst int MAX_MOVES = 100000;\nconst vector<pair<int, int>> DIJ = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\nconst string DIR = \"RDLU\";\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<int>> dist;\nvector<vector<bool>> visited;\nstring route;\n\nvoid bfs() {\n    dist.assign(N, vector<int>(N, -1));\n    queue<pair<int, int>> q;\n    q.push({0, 0});\n    dist[0][0] = 0;\n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        for (int dir = 0; dir < 4; ++dir) {\n            auto [di, dj] = DIJ[dir];\n            int ni = i + di;\n            int nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (di == 0) {\n                if (dj == 1 && v[i][min(j, nj)] == '1') continue;\n                if (dj == -1 && v[i][min(j, nj)] == '1') continue;\n            } else {\n                if (di == 1 && h[min(i, ni)][j] == '1') continue;\n                if (di == -1 && h[min(i, ni)][j] == '1') continue;\n            }\n            if (dist[ni][nj] == -1) {\n                dist[ni][nj] = dist[i][j] + 1;\n                q.push({ni, nj});\n            }\n        }\n    }\n}\n\nvoid dfs(int i, int j) {\n    visited[i][j] = true;\n    vector<tuple<double, int, int, int>> neighbors; // priority, ni, nj, dir\n    for (int dir = 0; dir < 4; ++dir) {\n        auto [di, dj] = DIJ[dir];\n        int ni = i + di;\n        int nj = j + dj;\n        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n        if (visited[ni][nj]) continue;\n        if (di == 0) {\n            if (dj == 1 && v[i][min(j, nj)] == '1') continue;\n            if (dj == -1 && v[i][min(j, nj)] == '1') continue;\n        } else {\n            if (di == 1 && h[min(i, ni)][j] == '1') continue;\n            if (di == -1 && h[min(i, ni)][j] == '1') continue;\n        }\n        double priority = (double)d[ni][nj] / (dist[ni][nj] + 1);\n        neighbors.emplace_back(priority, ni, nj, dir);\n    }\n    sort(neighbors.rbegin(), neighbors.rend());\n    for (auto [priority, ni, nj, dir] : neighbors) {\n        route += DIR[dir];\n        dfs(ni, nj);\n        route += DIR[(dir + 2) % 4];\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; ++i) {\n        cin >> h[i];\n    }\n    v.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> v[i];\n    }\n    d.resize(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    bfs();\n    visited.assign(N, vector<bool>(N, false));\n    dfs(0, 0);\n\n    if (route.size() > MAX_MOVES) {\n        route = route.substr(0, MAX_MOVES);\n    }\n    cout << route << endl;\n\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 15;\nconst int M = 200;\nconst int MAX_OPERATIONS = 5000;\nconst int BEAM_WIDTH = 1000;\n\nstruct State {\n    string s;\n    int i, j;\n    bitset<M> covered;\n    int cost;\n    vector<pair<int, int>> path;\n\n    bool operator<(const State& other) const {\n        return cost > other.cost; // For min-heap\n    }\n};\n\nvector<string> t(M);\nvector<vector<pair<int, int>>> char_positions(26);\nvector<vector<vector<pair<int, int>>>> word_positions(M);\n\nint manhattan(int i1, int j1, int i2, int j2) {\n    return abs(i1 - i2) + abs(j1 - j2);\n}\n\nvoid preprocess(const vector<string>& grid) {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = grid[i][j];\n            char_positions[c - 'A'].emplace_back(i, j);\n        }\n    }\n\n    for (int k = 0; k < M; ++k) {\n        const string& word = t[k];\n        vector<vector<pair<int, int>>> positions;\n        for (char c : word) {\n            positions.push_back(char_positions[c - 'A']);\n        }\n        word_positions[k] = positions;\n    }\n}\n\nint estimate_remaining_cost(const State& state) {\n    int remaining = 0;\n    for (int k = 0; k < M; ++k) {\n        if (!state.covered[k]) {\n            remaining += 5; // Each word has 5 characters\n        }\n    }\n    return remaining;\n}\n\nvector<pair<int, int>> beam_search(const vector<string>& grid, int si, int sj) {\n    priority_queue<State> pq;\n    State initial;\n    initial.s = \"\";\n    initial.i = si;\n    initial.j = sj;\n    initial.cost = 0;\n    initial.path = {{si, sj}};\n    pq.push(initial);\n\n    vector<pair<int, int>> best_path;\n    int best_cost = INT_MAX;\n    bitset<M> best_covered;\n\n    while (!pq.empty() && pq.top().cost < best_cost) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.covered.all()) {\n            if (current.cost < best_cost) {\n                best_cost = current.cost;\n                best_path = current.path;\n                best_covered = current.covered;\n            }\n            continue;\n        }\n\n        if (current.path.size() >= MAX_OPERATIONS) {\n            continue;\n        }\n\n        // Generate next states\n        for (int c = 0; c < 26; ++c) {\n            for (auto [ni, nj] : char_positions[c]) {\n                int move_cost = manhattan(current.i, current.j, ni, nj) + 1;\n                State next = current;\n                next.s += ('A' + c);\n                next.i = ni;\n                next.j = nj;\n                next.cost += move_cost;\n                next.path.emplace_back(ni, nj);\n\n                // Check if new character helps cover any words\n                for (int k = 0; k < M; ++k) {\n                    if (!next.covered[k]) {\n                        const string& word = t[k];\n                        if (next.s.size() >= word.size()) {\n                            bool match = true;\n                            for (int l = 0; l < word.size(); ++l) {\n                                if (next.s[next.s.size() - word.size() + l] != word[l]) {\n                                    match = false;\n                                    break;\n                                }\n                            }\n                            if (match) {\n                                next.covered[k] = true;\n                            }\n                        }\n                    }\n                }\n\n                if (next.cost + estimate_remaining_cost(next) < best_cost) {\n                    pq.push(next);\n                    if (pq.size() > BEAM_WIDTH) {\n                        pq.pop();\n                    }\n                }\n            }\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, M_in;\n    cin >> N_in >> M_in;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> grid(N_in);\n    for (int i = 0; i < N_in; ++i) {\n        cin >> grid[i];\n    }\n    for (int k = 0; k < M_in; ++k) {\n        cin >> t[k];\n    }\n\n    preprocess(grid);\n    auto path = beam_search(grid, si, sj);\n\n    for (auto [i, j] : path) {\n        cout << i << \" \" << j << \"\\n\";\n    }\n\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int i, j;\n    Point(int i = 0, int j = 0) : i(i), j(j) {}\n};\n\nstruct OilField {\n    int d;\n    vector<Point> cells;\n};\n\nclass Solver {\nprivate:\n    int N, M;\n    double eps;\n    vector<OilField> fields;\n    vector<vector<int>> grid;\n    vector<vector<bool>> drilled;\n    vector<Point> oil_squares;\n\n    void read_input() {\n        cin >> N >> M >> eps;\n        fields.resize(M);\n\n        for (int k = 0; k < M; ++k) {\n            cin >> fields[k].d;\n            fields[k].cells.resize(fields[k].d);\n            for (int i = 0; i < fields[k].d; ++i) {\n                cin >> fields[k].cells[i].i >> fields[k].cells[i].j;\n            }\n        }\n    }\n\n    void drill_all() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << \"q 1 \" << i << \" \" << j << endl;\n                cout.flush();\n\n                int v;\n                cin >> v;\n                if (v > 0) {\n                    oil_squares.emplace_back(i, j);\n                }\n            }\n        }\n    }\n\npublic:\n    Solver() {\n        read_input();\n        grid.assign(N, vector<int>(N, 0));\n        drilled.assign(N, vector<bool>(N, false));\n    }\n\n    void solve() {\n        // Simple solution: drill all squares\n        drill_all();\n\n        // Output the answer\n        cout << \"a \" << oil_squares.size();\n        for (const auto& p : oil_squares) {\n            cout << \" \" << p.i << \" \" << p.j;\n        }\n        cout << endl;\n        cout.flush();\n\n        int correct;\n        cin >> correct;\n        if (correct != 1) {\n            // If wrong, try again with all squares (shouldn't happen)\n            cout << \"a \" << N*N;\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    cout << \" \" << i << \" \" << j;\n                }\n            }\n            cout << endl;\n            cout.flush();\n        }\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    Solver solver;\n    solver.solve();\n\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int W = 1000;\nconst int MAX_D = 50;\nconst int MAX_N = 50;\n\nstruct Rect {\n    int i1, j1, i2, j2;\n    Rect(int i1 = 0, int j1 = 0, int i2 = 0, int j2 = 0) : i1(i1), j1(j1), i2(i2), j2(j2) {}\n    int area() const { return (i2 - i1) * (j2 - j1); }\n};\n\nvector<vector<Rect>> solve(int D, int N, const vector<vector<int>>& a) {\n    vector<vector<Rect>> res(D, vector<Rect>(N));\n\n    // For each day, we'll partition the grid into N rectangles\n    for (int d = 0; d < D; ++d) {\n        vector<int> areas = a[d];\n        sort(areas.begin(), areas.end(), greater<int>());\n        vector<Rect> rects;\n        int remaining_height = W;\n        int remaining_width = W;\n        int current_i = 0;\n        int current_j = 0;\n\n        for (int k = 0; k < N; ++k) {\n            int target = areas[k];\n            if (k == N - 1) {\n                // Last rectangle takes the remaining space\n                rects.emplace_back(current_i, current_j, W, W);\n                break;\n            }\n            // Decide whether to split vertically or horizontally\n            int split_height = (target + remaining_width - 1) / remaining_width;\n            if (split_height > remaining_height) {\n                split_height = remaining_height;\n            }\n            int split_width = (target + split_height - 1) / split_height;\n            if (split_width > remaining_width) {\n                split_width = remaining_width;\n            }\n\n            // Try to split vertically first\n            int best_split = -1;\n            int best_diff = INT_MAX;\n            for (int split = 1; split <= remaining_width; ++split) {\n                int h = (target + split - 1) / split;\n                if (h > remaining_height) continue;\n                int diff = abs(target - split * h);\n                if (diff < best_diff) {\n                    best_diff = diff;\n                    best_split = split;\n                }\n            }\n            // Try to split horizontally\n            for (int split = 1; split <= remaining_height; ++split) {\n                int w = (target + split - 1) / split;\n                if (w > remaining_width) continue;\n                int diff = abs(target - split * w);\n                if (diff < best_diff) {\n                    best_diff = diff;\n                    best_split = -split; // negative indicates horizontal split\n                }\n            }\n\n            if (best_split > 0) {\n                // Vertical split\n                int split = best_split;\n                int h = (target + split - 1) / split;\n                rects.emplace_back(current_i, current_j, current_i + h, current_j + split);\n                current_j += split;\n                remaining_width -= split;\n            } else {\n                // Horizontal split\n                int split = -best_split;\n                int w = (target + split - 1) / split;\n                rects.emplace_back(current_i, current_j, current_i + split, current_j + w);\n                current_i += split;\n                remaining_height -= split;\n            }\n        }\n        res[d] = rects;\n    }\n\n    // Now, try to minimize partition changes between days\n    for (int d = 1; d < D; ++d) {\n        // For simplicity, we'll just use the same partitioning as the previous day\n        // and adjust the rectangles to meet the new area requirements\n        // This is a placeholder; a better approach would involve more sophisticated matching\n        res[d] = res[d-1];\n        for (int k = 0; k < N; ++k) {\n            int target = a[d][k];\n            Rect& r = res[d][k];\n            int current_area = r.area();\n            if (current_area < target) {\n                // Need to expand the rectangle\n                // Try to expand to the right or down\n                if (r.j2 < W) {\n                    int new_width = (target + (r.i2 - r.i1) - 1) / (r.i2 - r.i1);\n                    if (new_width > W - r.j1) new_width = W - r.j1;\n                    r.j2 = r.j1 + new_width;\n                } else if (r.i2 < W) {\n                    int new_height = (target + (r.j2 - r.j1) - 1) / (r.j2 - r.j1);\n                    if (new_height > W - r.i1) new_height = W - r.i1;\n                    r.i2 = r.i1 + new_height;\n                }\n            } else if (current_area > target) {\n                // Need to shrink the rectangle\n                // Try to shrink from the right or bottom\n                int shrink_area = current_area - target;\n                if (r.j2 > r.j1) {\n                    int shrink_width = min(shrink_area / (r.i2 - r.i1), r.j2 - r.j1 - 1);\n                    r.j2 -= shrink_width;\n                } else if (r.i2 > r.i1) {\n                    int shrink_height = min(shrink_area / (r.j2 - r.j1), r.i2 - r.i1 - 1);\n                    r.i2 -= shrink_height;\n                }\n            }\n        }\n    }\n\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int W_in, D, N;\n    cin >> W_in >> D >> 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    }\n\n    auto res = solve(D, N, a);\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            const auto& r = res[d][k];\n            cout << r.i1 << \" \" << r.j1 << \" \" << r.i2 << \" \" << r.j2 << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K_MAX = 81;\nconst int STAMP_SIZE = 3;\n\nint a[N][N];\nint s[M][STAMP_SIZE][STAMP_SIZE];\nint b[N][N];\nint d[N][N]; // deficit: MOD - 1 - (b[i][j] % MOD)\n\nstruct Operation {\n    int m, p, q;\n};\n\nvector<Operation> operations;\n\nvoid apply_stamp(int m, int p, int q) {\n    for (int i = 0; i < STAMP_SIZE; ++i) {\n        for (int j = 0; j < STAMP_SIZE; ++j) {\n            b[p + i][q + j] += s[m][i][j];\n        }\n    }\n}\n\nvoid update_deficits() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            d[i][j] = (MOD - 1 - (b[i][j] % MOD)) % MOD;\n        }\n    }\n}\n\nint compute_contribution(int m, int p, int q) {\n    int contribution = 0;\n    for (int i = 0; i < STAMP_SIZE; ++i) {\n        for (int j = 0; j < STAMP_SIZE; ++j) {\n            int ni = p + i;\n            int nj = q + j;\n            if (ni >= N || nj >= N) continue;\n            int add = min(s[m][i][j], d[ni][nj]);\n            contribution += add;\n        }\n    }\n    return contribution;\n}\n\nvoid greedy_solve() {\n    // Initialize b and d\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            b[i][j] = a[i][j];\n        }\n    }\n    update_deficits();\n\n    operations.clear();\n    for (int k = 0; k < K_MAX; ++k) {\n        int best_contribution = -1;\n        int best_m = -1, best_p = -1, best_q = -1;\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - STAMP_SIZE; ++p) {\n                for (int q = 0; q <= N - STAMP_SIZE; ++q) {\n                    int contribution = compute_contribution(m, p, q);\n                    if (contribution > best_contribution) {\n                        best_contribution = contribution;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_contribution <= 0) break;\n\n        operations.push_back({best_m, best_p, best_q});\n        apply_stamp(best_m, best_p, best_q);\n        update_deficits();\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, M_in, K_in;\n    cin >> N_in >> M_in >> K_in;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> a[i][j];\n        }\n    }\n    for (int m = 0; m < M; ++m) {\n        for (int i = 0; i < STAMP_SIZE; ++i) {\n            for (int j = 0; j < STAMP_SIZE; ++j) {\n                cin >> s[m][i][j];\n            }\n        }\n    }\n\n    greedy_solve();\n\n    cout << operations.size() << '\\n';\n    for (const auto& op : operations) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 5;\nconst int MAX_TURNS = 10000;\n\nstruct Container {\n    int id;\n    int target_gate;\n    int current_i, current_j;\n    bool is_held;\n    int held_by;\n};\n\nstruct Crane {\n    int id;\n    int i, j;\n    bool is_large;\n    bool is_holding;\n    int holding_id;\n    bool is_bombed;\n};\n\nvector<Container> containers;\nvector<Crane> cranes;\nvector<vector<int>> grid(N, vector<int>(N, -1)); // -1: empty, -2: crane, otherwise container id\nvector<vector<int>> A(N, vector<int>(N));\nvector<string> operations(N);\n\nvoid initialize() {\n    containers.clear();\n    cranes.clear();\n    grid.assign(N, vector<int>(N, -1));\n    operations.assign(N, \"\");\n\n    // Initialize cranes\n    for (int i = 0; i < N; ++i) {\n        cranes.push_back({i, i, 0, i == 0, false, -1, false});\n        grid[i][0] = -2; // Mark crane position\n    }\n\n    // Initialize containers\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int id = A[i][j];\n            int target_gate = id / N;\n            containers.push_back({id, target_gate, i, 0, false, -1});\n        }\n    }\n}\n\nbool is_valid_move(int crane_id, int di, int dj) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed) return false;\n    int ni = crane.i + di;\n    int nj = crane.j + dj;\n    if (ni < 0 || ni >= N || nj < 0 || nj >= N) return false;\n\n    // Check if destination is occupied by another crane\n    for (int i = 0; i < N; ++i) {\n        if (i == crane_id) continue;\n        if (cranes[i].i == ni && cranes[i].j == nj && !cranes[i].is_bombed) {\n            return false;\n        }\n    }\n\n    // Check if carrying and small crane\n    if (crane.is_holding && !crane.is_large) {\n        if (grid[ni][nj] != -1) return false; // Small crane cannot move to occupied square while carrying\n    }\n\n    return true;\n}\n\nvoid move_crane(int crane_id, char dir) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed) return;\n\n    int di = 0, dj = 0;\n    switch (dir) {\n        case 'U': di = -1; break;\n        case 'D': di = 1; break;\n        case 'L': dj = -1; break;\n        case 'R': dj = 1; break;\n        default: return;\n    }\n\n    if (!is_valid_move(crane_id, di, dj)) return;\n\n    // Update grid\n    grid[crane.i][crane.j] = -1;\n    crane.i += di;\n    crane.j += dj;\n    grid[crane.i][crane.j] = -2;\n}\n\nvoid pick_up(int crane_id) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed || crane.is_holding) return;\n\n    if (grid[crane.i][crane.j] != -1) {\n        int container_id = grid[crane.i][crane.j];\n        if (container_id >= 0 && container_id < N*N) {\n            containers[container_id].is_held = true;\n            containers[container_id].held_by = crane_id;\n            crane.is_holding = true;\n            crane.holding_id = container_id;\n            grid[crane.i][crane.j] = -1;\n        }\n    }\n}\n\nvoid release(int crane_id) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed || !crane.is_holding) return;\n\n    if (grid[crane.i][crane.j] == -1) {\n        int container_id = crane.holding_id;\n        containers[container_id].is_held = false;\n        containers[container_id].held_by = -1;\n        containers[container_id].current_i = crane.i;\n        containers[container_id].current_j = crane.j;\n        crane.is_holding = false;\n        crane.holding_id = -1;\n        grid[crane.i][crane.j] = container_id;\n    }\n}\n\nvoid bomb(int crane_id) {\n    Crane &crane = cranes[crane_id];\n    if (crane.is_bombed || crane.is_holding) return;\n\n    crane.is_bombed = true;\n    grid[crane.i][crane.j] = -1;\n}\n\nvoid do_nothing(int crane_id) {\n    // Do nothing\n}\n\nvoid simulate_turn() {\n    // Step 1: Place new containers at Receiving Gates\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][0] == -1) {\n            for (int j = 0; j < N; ++j) {\n                int id = A[i][j];\n                if (!containers[id].is_held && containers[id].current_i == i && containers[id].current_j == 0) {\n                    grid[i][0] = id;\n                    containers[id].current_i = i;\n                    containers[id].current_j = 0;\n                    break;\n                }\n            }\n        }\n    }\n\n    // Step 2: Perform crane actions\n    for (int i = 0; i < N; ++i) {\n        if (operations[i].empty()) continue;\n        char action = operations[i].back();\n        operations[i].pop_back();\n\n        switch (action) {\n            case 'P': pick_up(i); break;\n            case 'Q': release(i); break;\n            case 'U': move_crane(i, 'U'); break;\n            case 'D': move_crane(i, 'D'); break;\n            case 'L': move_crane(i, 'L'); break;\n            case 'R': move_crane(i, 'R'); break;\n            case 'B': bomb(i); break;\n            case '.': do_nothing(i); break;\n        }\n    }\n\n    // Step 3: Dispatch containers at Dispatch Gates\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][N-1] != -1) {\n            int id = grid[i][N-1];\n            if (id >= 0 && id < N*N) {\n                grid[i][N-1] = -1;\n            }\n        }\n    }\n}\n\nvoid plan_operations() {\n    // Simple heuristic: move containers to their target gates\n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        bool all_dispatched = true;\n        for (const auto &container : containers) {\n            if (!container.is_held && grid[container.current_i][container.current_j] != -1) {\n                all_dispatched = false;\n                break;\n            }\n        }\n        if (all_dispatched) break;\n\n        for (int i = 0; i < N; ++i) {\n            Crane &crane = cranes[i];\n            if (crane.is_bombed) {\n                operations[i] += '.';\n                continue;\n            }\n\n            if (crane.is_holding) {\n                int container_id = crane.holding_id;\n                int target_gate = containers[container_id].target_gate;\n                int target_i = target_gate;\n                int target_j = N-1;\n\n                if (crane.i == target_i && crane.j == target_j) {\n                    operations[i] += 'Q';\n                } else {\n                    // Move towards target\n                    if (crane.j < target_j) {\n                        operations[i] += 'R';\n                    } else if (crane.j > target_j) {\n                        operations[i] += 'L';\n                    } else if (crane.i < target_i) {\n                        operations[i] += 'D';\n                    } else if (crane.i > target_i) {\n                        operations[i] += 'U';\n                    }\n                }\n            } else {\n                // Find the nearest container to pick up\n                int nearest_id = -1;\n                int min_dist = INT_MAX;\n                for (int id = 0; id < N*N; ++id) {\n                    if (!containers[id].is_held && grid[containers[id].current_i][containers[id].current_j] != -1) {\n                        int dist = abs(crane.i - containers[id].current_i) + abs(crane.j - containers[id].current_j);\n                        if (dist < min_dist) {\n                            min_dist = dist;\n                            nearest_id = id;\n                        }\n                    }\n                }\n\n                if (nearest_id != -1) {\n                    int target_i = containers[nearest_id].current_i;\n                    int target_j = containers[nearest_id].current_j;\n\n                    if (crane.i == target_i && crane.j == target_j) {\n                        operations[i] += 'P';\n                    } else {\n                        // Move towards container\n                        if (crane.j < target_j) {\n                            operations[i] += 'R';\n                        } else if (crane.j > target_j) {\n                            operations[i] += 'L';\n                        } else if (crane.i < target_i) {\n                            operations[i] += 'D';\n                        } else if (crane.i > target_i) {\n                            operations[i] += 'U';\n                        }\n                    }\n                } else {\n                    operations[i] += '.';\n                }\n            }\n        }\n\n        simulate_turn();\n    }\n\n    // Reverse operations to get correct order\n    for (int i = 0; i < N; ++i) {\n        reverse(operations[i].begin(), operations[i].end());\n    }\n}\n\nint main() {\n    cin >> N;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n        }\n    }\n\n    initialize();\n    plan_operations();\n\n    // Output operations\n    for (int i = 0; i < N; ++i) {\n        cout << operations[i] << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 20;\n    vector<vector<int>> grid(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> grid[i][j];\n        }\n    }\n\n    // Snake traversal order\n    vector<pair<int, int>> order;\n    for (int i = 0; i < N; ++i) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; ++j) {\n                order.emplace_back(i, j);\n            }\n        } else {\n            for (int j = N - 1; j >= 0; --j) {\n                order.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Current position and load\n    int x = 0, y = 0;\n    int load = 0;\n    vector<string> ops;\n\n    // Function to move to (nx, ny)\n    auto move_to = [&](int nx, int ny) {\n        while (x != nx || y != ny) {\n            if (x < nx) { ops.push_back(\"D\"); x++; }\n            else if (x > nx) { ops.push_back(\"U\"); x--; }\n            else if (y < ny) { ops.push_back(\"R\"); y++; }\n            else if (y > ny) { ops.push_back(\"L\"); y--; }\n        }\n    };\n\n    // Traverse in order\n    for (auto [i, j] : order) {\n        move_to(i, j);\n\n        // Load if positive\n        if (grid[i][j] > 0) {\n            int d = min(grid[i][j], 1000000);\n            ops.push_back(\"+\" + to_string(d));\n            grid[i][j] -= d;\n            load += d;\n        }\n        // Unload if negative and truck has load\n        else if (grid[i][j] < 0 && load > 0) {\n            int d = min(-grid[i][j], load);\n            ops.push_back(\"-\" + to_string(d));\n            grid[i][j] += d;\n            load -= d;\n        }\n    }\n\n    // Final unload if needed (should not happen, but safe)\n    if (load > 0) {\n        move_to(0, 0);\n        ops.push_back(\"-\" + to_string(load));\n    }\n\n    // Output all operations\n    for (const string& op : ops) {\n        cout << op << '\\n';\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Seed {\n    vector<int> eval;\n    int value;\n    int id;\n};\n\nbool compareSeeds(const Seed &a, const Seed &b) {\n    return a.value > b.value;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 6, M = 15, T = 10;\n    int seed_count = 2 * N * (N - 1);\n    vector<Seed> seeds(seed_count);\n\n    for (int i = 0; i < seed_count; ++i) {\n        seeds[i].eval.resize(M);\n        seeds[i].id = i;\n        for (int j = 0; j < M; ++j) {\n            cin >> seeds[i].eval[j];\n        }\n        seeds[i].value = accumulate(seeds[i].eval.begin(), seeds[i].eval.end(), 0);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        // Sort seeds by value in descending order\n        sort(seeds.begin(), seeds.end(), compareSeeds);\n\n        // Select top N*N seeds\n        vector<Seed> selected_seeds(seeds.begin(), seeds.begin() + N * N);\n\n        // Create a grid to place the selected seeds\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                grid[i][j] = selected_seeds[i * N + j].id;\n            }\n        }\n\n        // Output the grid\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << grid[i][j];\n                if (j < N - 1) {\n                    cout << \" \";\n                }\n            }\n            cout << endl;\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seed_count; ++i) {\n            seeds[i].eval.resize(M);\n            seeds[i].id = i;\n            for (int j = 0; j < M; ++j) {\n                cin >> seeds[i].eval[j];\n            }\n            seeds[i].value = accumulate(seeds[i].eval.begin(), seeds[i].eval.end(), 0);\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        return x < other.x || (x == other.x && y < other.y);\n    }\n};\n\nstruct Takoyaki {\n    Point source, target;\n    bool operator<(const Takoyaki& other) const {\n        return source < other.source || (source == other.source && target < other.target);\n    }\n};\n\nvector<Point> find_takoyaki(const vector<string>& grid, char c) {\n    vector<Point> res;\n    for (int i = 0; i < grid.size(); ++i) {\n        for (int j = 0; j < grid[i].size(); ++j) {\n            if (grid[i][j] == c) {\n                res.emplace_back(i, j);\n            }\n        }\n    }\n    return res;\n}\n\nvector<Takoyaki> create_takoyaki_list(const vector<Point>& sources, const vector<Point>& targets) {\n    vector<Takoyaki> res;\n    for (int i = 0; i < sources.size(); ++i) {\n        res.push_back({sources[i], targets[i]});\n    }\n    return res;\n}\n\nstruct TreeNode {\n    int parent;\n    int length;\n    TreeNode(int p = -1, int l = 1) : parent(p), length(l) {}\n};\n\nvector<TreeNode> design_tree(int V) {\n    vector<TreeNode> tree;\n    if (V == 1) {\n        return tree;\n    }\n    tree.emplace_back(0, 1);\n    if (V == 2) {\n        return tree;\n    }\n    tree.emplace_back(0, 2);\n    if (V == 3) {\n        return tree;\n    }\n    for (int i = 2; i < V; ++i) {\n        int p = (i - 1) / 2;\n        int l = 1 + (i % 2);\n        tree.emplace_back(p, l);\n    }\n    return tree;\n}\n\nPoint initial_root_position(int N, const vector<Takoyaki>& takoyakis) {\n    int sum_x = 0, sum_y = 0;\n    for (const auto& t : takoyakis) {\n        sum_x += t.source.x + t.target.x;\n        sum_y += t.source.y + t.target.y;\n    }\n    int cnt = 2 * takoyakis.size();\n    return Point(sum_x / cnt, sum_y / cnt);\n}\n\nvector<string> generate_operations(const vector<TreeNode>& tree, const Point& root_pos,\n                                   const vector<Takoyaki>& takoyakis, int N) {\n    vector<string> operations;\n    int V = tree.size() + 1;\n    vector<Point> fingertip_pos(V);\n    vector<int> dir(V, 0); // 0: right, 1: down, 2: left, 3: up\n    vector<bool> holding(V, false);\n    vector<Point> current_pos(V);\n    current_pos[0] = root_pos;\n\n    auto update_positions = [&]() {\n        for (int i = 1; i < V; ++i) {\n            int p = tree[i-1].parent;\n            int l = tree[i-1].length;\n            int dx = 0, dy = 0;\n            if (dir[i] == 0) { dx = l; }\n            else if (dir[i] == 1) { dy = l; }\n            else if (dir[i] == 2) { dx = -l; }\n            else if (dir[i] == 3) { dy = -l; }\n            current_pos[i] = Point(current_pos[p].x + dx, current_pos[p].y + dy);\n        }\n    };\n\n    update_positions();\n\n    auto move_root = [&](int dx, int dy) {\n        current_pos[0].x += dx;\n        current_pos[0].y += dy;\n        update_positions();\n    };\n\n    auto rotate_subtree = [&](int u, bool clockwise) {\n        if (clockwise) {\n            dir[u] = (dir[u] + 1) % 4;\n        } else {\n            dir[u] = (dir[u] + 3) % 4;\n        }\n        update_positions();\n    };\n\n    auto can_grab = [&](int u, const Point& p) {\n        return current_pos[u] == p && !holding[u];\n    };\n\n    auto can_release = [&](int u, const Point& p) {\n        return current_pos[u] == p && holding[u];\n    };\n\n    auto bfs_path = [&](Point start, Point target) {\n        vector<vector<int>> dist(N, vector<int>(N, -1));\n        vector<vector<Point>> prev(N, vector<Point>(N, Point(-1, -1)));\n        queue<Point> q;\n        dist[start.x][start.y] = 0;\n        q.push(start);\n        vector<int> dx = {0, 1, 0, -1};\n        vector<int> dy = {1, 0, -1, 0};\n        while (!q.empty()) {\n            Point p = q.front();\n            q.pop();\n            if (p == target) {\n                vector<Point> path;\n                while (p != start) {\n                    path.push_back(p);\n                    p = prev[p.x][p.y];\n                }\n                reverse(path.begin(), path.end());\n                return path;\n            }\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + dx[i];\n                int ny = p.y + dy[i];\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N && dist[nx][ny] == -1) {\n                    dist[nx][ny] = dist[p.x][p.y] + 1;\n                    prev[nx][ny] = p;\n                    q.emplace(nx, ny);\n                }\n            }\n        }\n        return vector<Point>();\n    };\n\n    auto move_to = [&](Point target) {\n        vector<Point> path = bfs_path(current_pos[0], target);\n        for (Point p : path) {\n            int dx = p.x - current_pos[0].x;\n            int dy = p.y - current_pos[0].y;\n            if (dx == 1) {\n                operations.push_back(\"D\" + string(V-1, '.') + string(V, '.'));\n                move_root(1, 0);\n            } else if (dx == -1) {\n                operations.push_back(\"U\" + string(V-1, '.') + string(V, '.'));\n                move_root(-1, 0);\n            } else if (dy == 1) {\n                operations.push_back(\"R\" + string(V-1, '.') + string(V, '.'));\n                move_root(0, 1);\n            } else if (dy == -1) {\n                operations.push_back(\"L\" + string(V-1, '.') + string(V, '.'));\n                move_root(0, -1);\n            }\n        }\n    };\n\n    auto align_fingertip = [&](int u, Point target) {\n        Point p = current_pos[u];\n        int dx = target.x - p.x;\n        int dy = target.y - p.y;\n        int required_dir = -1;\n        if (dx > 0 && dy == 0) required_dir = 0;\n        else if (dx == 0 && dy > 0) required_dir = 1;\n        else if (dx < 0 && dy == 0) required_dir = 2;\n        else if (dx == 0 && dy < 0) required_dir = 3;\n        if (required_dir == -1) return;\n        while (dir[u] != required_dir) {\n            bool clockwise = (dir[u] + 1) % 4 == required_dir;\n            string op(V*2, '.');\n            op[0] = '.';\n            op[u] = clockwise ? 'R' : 'L';\n            operations.push_back(op);\n            rotate_subtree(u, clockwise);\n        }\n    };\n\n    auto process_takoyaki = [&](const Takoyaki& t) {\n        // Move to source\n        move_to(t.source);\n        // Align fingertip to source\n        for (int u = 1; u < V; ++u) {\n            if (!holding[u]) {\n                align_fingertip(u, t.source);\n                if (can_grab(u, t.source)) {\n                    string op(V*2, '.');\n                    op[V + u] = 'P';\n                    operations.push_back(op);\n                    holding[u] = true;\n                    break;\n                }\n            }\n        }\n        // Move to target\n        move_to(t.target);\n        // Align fingertip to target\n        for (int u = 1; u < V; ++u) {\n            if (holding[u]) {\n                align_fingertip(u, t.target);\n                if (can_release(u, t.target)) {\n                    string op(V*2, '.');\n                    op[V + u] = 'P';\n                    operations.push_back(op);\n                    holding[u] = false;\n                    break;\n                }\n            }\n        }\n    };\n\n    for (const auto& t : takoyakis) {\n        process_takoyaki(t);\n    }\n\n    return operations;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, V;\n    cin >> N >> M >> V;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        cin >> t[i];\n    }\n\n    vector<Point> sources = find_takoyaki(s, '1');\n    vector<Point> targets = find_takoyaki(t, '1');\n    vector<Takoyaki> takoyakis = create_takoyaki_list(sources, targets);\n\n    vector<TreeNode> tree = design_tree(V);\n    Point root_pos = initial_root_position(N, takoyakis);\n\n    cout << tree.size() + 1 << '\\n';\n    for (const auto& node : tree) {\n        cout << node.parent << ' ' << node.length << '\\n';\n    }\n    cout << root_pos.x << ' ' << root_pos.y << '\\n';\n\n    vector<string> operations = generate_operations(tree, root_pos, takoyakis, N);\n    for (const string& op : operations) {\n        cout << op << '\\n';\n    }\n\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n    bool operator==(const Point& p) const {\n        return x == p.x && y == p.y;\n    }\n};\n\nint N;\nvector<Point> mackerels, sardines;\nvector<Point> polygon;\n\nbool is_inside(const vector<Point>& poly, const Point& p) {\n    int n = poly.size();\n    bool inside = false;\n    for (int i = 0, j = n - 1; i < n; j = i++) {\n        const Point& a = poly[i];\n        const Point& b = poly[j];\n        if (a.y == b.y) {\n            if (p.y == a.y && min(a.x, b.x) <= p.x && p.x <= max(a.x, b.x)) {\n                return true;\n            }\n            continue;\n        }\n        if ((a.y > p.y) != (b.y > p.y)) {\n            int x_intersect = (p.y - a.y) * (b.x - a.x) / (b.y - a.y) + a.x;\n            if (p.x == x_intersect) {\n                return true;\n            }\n            if (p.x < x_intersect) {\n                inside = !inside;\n            }\n        }\n    }\n    return inside;\n}\n\nint compute_score(const vector<Point>& poly) {\n    int a = 0, b = 0;\n    for (const Point& p : mackerels) {\n        if (is_inside(poly, p)) {\n            a++;\n        }\n    }\n    for (const Point& p : sardines) {\n        if (is_inside(poly, p)) {\n            b++;\n        }\n    }\n    return max(0, a - b + 1);\n}\n\nvector<Point> initial_polygon() {\n    int min_x = 1e9, max_x = -1, min_y = 1e9, max_y = -1;\n    for (const Point& p : mackerels) {\n        min_x = min(min_x, p.x);\n        max_x = max(max_x, p.x);\n        min_y = min(min_y, p.y);\n        max_y = max(max_y, p.y);\n    }\n    vector<Point> poly = {\n        {min_x, min_y},\n        {max_x, min_y},\n        {max_x, max_y},\n        {min_x, max_y}\n    };\n    return poly;\n}\n\nvector<Point> adjust_polygon(vector<Point> poly) {\n    int m = poly.size();\n    int total_length = 0;\n    for (int i = 0; i < m; ++i) {\n        int j = (i + 1) % m;\n        total_length += abs(poly[i].x - poly[j].x) + abs(poly[i].y - poly[j].y);\n    }\n\n    auto can_add_vertex = [&]() {\n        return poly.size() < 1000 && total_length < 400000;\n    };\n\n    auto add_vertex = [&](int edge_idx, Point new_vertex) {\n        if (!can_add_vertex()) return false;\n        int i = edge_idx;\n        int j = (i + 1) % poly.size();\n        int new_length = total_length - (abs(poly[i].x - poly[j].x) + abs(poly[i].y - poly[j].y))\n                         + (abs(poly[i].x - new_vertex.x) + abs(poly[i].y - new_vertex.y))\n                         + (abs(new_vertex.x - poly[j].x) + abs(new_vertex.y - poly[j].y));\n        if (new_length > 400000) return false;\n        poly.insert(poly.begin() + i + 1, new_vertex);\n        total_length = new_length;\n        return true;\n    };\n\n    auto move_vertex = [&](int vertex_idx, Point new_pos) {\n        int i = vertex_idx;\n        int prev = (i - 1 + poly.size()) % poly.size();\n        int next = (i + 1) % poly.size();\n        int old_length = abs(poly[prev].x - poly[i].x) + abs(poly[prev].y - poly[i].y)\n                       + abs(poly[i].x - poly[next].x) + abs(poly[i].y - poly[next].y);\n        int new_length = abs(poly[prev].x - new_pos.x) + abs(poly[prev].y - new_pos.y)\n                       + abs(new_pos.x - poly[next].x) + abs(new_pos.y - poly[next].y);\n        if (total_length - old_length + new_length > 400000) return false;\n        poly[i] = new_pos;\n        total_length = total_length - old_length + new_length;\n        return true;\n    };\n\n    auto try_improve = [&]() {\n        int best_score = compute_score(poly);\n        vector<Point> best_poly = poly;\n        for (int iter = 0; iter < 100; ++iter) {\n            int edge_idx = rand() % poly.size();\n            int i = edge_idx;\n            int j = (i + 1) % poly.size();\n            if (poly[i].x == poly[j].x) {\n                int x = poly[i].x;\n                int y_min = min(poly[i].y, poly[j].y);\n                int y_max = max(poly[i].y, poly[j].y);\n                for (int y = y_min + 1; y < y_max; ++y) {\n                    Point new_vertex(x, y);\n                    if (add_vertex(edge_idx, new_vertex)) {\n                        int score = compute_score(poly);\n                        if (score > best_score) {\n                            best_score = score;\n                            best_poly = poly;\n                        } else {\n                            poly = best_poly;\n                        }\n                    }\n                }\n            } else if (poly[i].y == poly[j].y) {\n                int y = poly[i].y;\n                int x_min = min(poly[i].x, poly[j].x);\n                int x_max = max(poly[i].x, poly[j].x);\n                for (int x = x_min + 1; x < x_max; ++x) {\n                    Point new_vertex(x, y);\n                    if (add_vertex(edge_idx, new_vertex)) {\n                        int score = compute_score(poly);\n                        if (score > best_score) {\n                            best_score = score;\n                            best_poly = poly;\n                        } else {\n                            poly = best_poly;\n                        }\n                    }\n                }\n            }\n            for (int vertex_idx = 0; vertex_idx < poly.size(); ++vertex_idx) {\n                Point original = poly[vertex_idx];\n                for (int dx = -1; dx <= 1; ++dx) {\n                    for (int dy = -1; dy <= 1; ++dy) {\n                        if (dx == 0 && dy == 0) continue;\n                        Point new_pos(original.x + dx, original.y + dy);\n                        if (move_vertex(vertex_idx, new_pos)) {\n                            int score = compute_score(poly);\n                            if (score > best_score) {\n                                best_score = score;\n                                best_poly = poly;\n                            } else {\n                                poly = best_poly;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        return best_poly;\n    };\n\n    return try_improve();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    mackerels.resize(N);\n    sardines.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> mackerels[i].x >> mackerels[i].y;\n    }\n    for (int i = 0; i < N; ++i) {\n        cin >> sardines[i].x >> sardines[i].y;\n    }\n\n    polygon = initial_polygon();\n    polygon = adjust_polygon(polygon);\n\n    cout << polygon.size() << '\\n';\n    for (const Point& p : polygon) {\n        cout << p.x << ' ' << p.y << '\\n';\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n#include <chrono>\n\nusing namespace std;\nusing namespace std::chrono;\n\nstruct Rectangle {\n    int id;\n    int w, h;\n    int x, y;\n    bool rotated;\n};\n\nstruct Placement {\n    int p, r;\n    char d;\n    int b;\n};\n\nvector<Rectangle> place_rectangles(const vector<pair<int, int>>& observed, const vector<Placement>& placements) {\n    vector<Rectangle> placed;\n    for (const auto& pl : placements) {\n        int id = pl.p;\n        bool rotated = pl.r;\n        int w = observed[id].first;\n        int h = observed[id].second;\n        if (rotated) swap(w, h);\n\n        int x = 0, y = 0;\n        if (pl.d == 'U') {\n            if (pl.b == -1) {\n                x = 0;\n            } else {\n                x = placed[pl.b].x + placed[pl.b].w;\n            }\n            int max_y = 0;\n            for (const auto& rect : placed) {\n                if (rect.x < x + w && rect.x + rect.w > x) {\n                    if (rect.y + rect.h > max_y) {\n                        max_y = rect.y + rect.h;\n                    }\n                }\n            }\n            y = max_y;\n        } else if (pl.d == 'L') {\n            if (pl.b == -1) {\n                y = 0;\n            } else {\n                y = placed[pl.b].y + placed[pl.b].h;\n            }\n            int max_x = 0;\n            for (const auto& rect : placed) {\n                if (rect.y < y + h && rect.y + rect.h > y) {\n                    if (rect.x + rect.w > max_x) {\n                        max_x = rect.x + rect.w;\n                    }\n                }\n            }\n            x = max_x;\n        }\n        placed.push_back({id, w, h, x, y, rotated});\n    }\n    return placed;\n}\n\npair<int, int> calculate_dimensions(const vector<Rectangle>& placed) {\n    int max_x = 0, max_y = 0;\n    for (const auto& rect : placed) {\n        max_x = max(max_x, rect.x + rect.w);\n        max_y = max(max_y, rect.y + rect.h);\n    }\n    return {max_x, max_y};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n    vector<pair<int, int>> observed(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> observed[i].first >> observed[i].second;\n    }\n\n    for (int t = 0; t < T; ++t) {\n        vector<Placement> placements;\n        vector<bool> used(N, false);\n\n        for (int i = 0; i < N; ++i) {\n            int best_r = 0;\n            char best_d = 'U';\n            int best_b = -1;\n            int min_max_dim = INT_MAX;\n\n            for (int r = 0; r < 2; ++r) {\n                for (char d : {'U', 'L'}) {\n                    int b_start = -1;\n                    int b_end = min((int)placements.size() - 1, 5); // Limit reference rectangles to last 5\n                    for (int b = b_start; b <= b_end; ++b) {\n                        placements.push_back({i, r, d, b});\n                        auto placed = place_rectangles(observed, placements);\n                        auto [W, H] = calculate_dimensions(placed);\n                        int max_dim = max(W, H);\n                        if (max_dim < min_max_dim) {\n                            min_max_dim = max_dim;\n                            best_r = r;\n                            best_d = d;\n                            best_b = b;\n                        }\n                        placements.pop_back();\n                    }\n                }\n            }\n\n            placements.push_back({i, best_r, best_d, best_b});\n        }\n\n        cout << placements.size() << '\\n';\n        for (const auto& pl : placements) {\n            cout << pl.p << ' ' << pl.r << ' ' << pl.d << ' ' << pl.b << '\\n';\n        }\n        cout.flush();\n\n        int W_prime, H_prime;\n        cin >> W_prime >> H_prime;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <set>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nstruct Vertex {\n    int id;\n    int a;\n    int x, y;\n    vector<int> neighbors;\n};\n\nstruct BFSState {\n    int vertex;\n    int parent;\n    int depth;\n    bool operator<(const BFSState& other) const {\n        if (depth != other.depth) return depth > other.depth;\n        return a[vertex] < a[other.vertex];\n    }\n    static vector<int> a;\n};\n\nvector<int> BFSState::a;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    cin >> N >> M >> H;\n\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> A[i];\n    }\n    BFSState::a = A;\n\n    vector<pair<int, int>> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].first >> edges[i].second;\n    }\n\n    vector<pair<int, int>> coords(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> coords[i].first >> coords[i].second;\n    }\n\n    vector<Vertex> vertices(N);\n    for (int i = 0; i < N; ++i) {\n        vertices[i].id = i;\n        vertices[i].a = A[i];\n        vertices[i].x = coords[i].first;\n        vertices[i].y = coords[i].second;\n    }\n\n    for (const auto& edge : edges) {\n        int u = edge.first;\n        int v = edge.second;\n        vertices[u].neighbors.push_back(v);\n        vertices[v].neighbors.push_back(u);\n    }\n\n    vector<int> parent(N, -1);\n    vector<bool> assigned(N, false);\n\n    while (true) {\n        int root = -1;\n        int max_a = -1;\n        for (int i = 0; i < N; ++i) {\n            if (!assigned[i] && A[i] > max_a) {\n                max_a = A[i];\n                root = i;\n            }\n        }\n        if (root == -1) break;\n\n        priority_queue<BFSState> pq;\n        pq.push({root, -1, 0});\n        vector<bool> visited(N, false);\n        visited[root] = true;\n\n        while (!pq.empty()) {\n            BFSState current = pq.top();\n            pq.pop();\n            if (current.depth > H) continue;\n            if (assigned[current.vertex]) continue;\n\n            parent[current.vertex] = current.parent;\n            assigned[current.vertex] = true;\n\n            for (int neighbor : vertices[current.vertex].neighbors) {\n                if (!visited[neighbor] && !assigned[neighbor]) {\n                    visited[neighbor] = true;\n                    pq.push({neighbor, current.vertex, current.depth + 1});\n                }\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <set>\n#include <map>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_MOVES = 4 * N * N;\n\nstruct Piece {\n    int i, j;\n    char type; // 'x' for Oni, 'o' for Fukunokami\n};\n\nvector<string> board;\nvector<Piece> oni_list;\nvector<Piece> fuku_list;\nvector<vector<bool>> safe_up, safe_down, safe_left, safe_right;\n\nvoid preprocess() {\n    // Initialize safe directions\n    safe_up.assign(N, vector<bool>(N, true));\n    safe_down.assign(N, vector<bool>(N, true));\n    safe_left.assign(N, vector<bool>(N, true));\n    safe_right.assign(N, vector<bool>(N, true));\n\n    // Mark unsafe directions for Oni\n    for (const auto& fuku : fuku_list) {\n        int i = fuku.i, j = fuku.j;\n        // Up: all squares above (i,j) in column j are unsafe for Oni below\n        for (int k = 0; k < i; ++k) {\n            safe_down[k][j] = false;\n        }\n        // Down: all squares below (i,j) in column j are unsafe for Oni above\n        for (int k = i + 1; k < N; ++k) {\n            safe_up[k][j] = false;\n        }\n        // Left: all squares left of (i,j) in row i are unsafe for Oni to the right\n        for (int k = 0; k < j; ++k) {\n            safe_right[i][k] = false;\n        }\n        // Right: all squares right of (i,j) in row i are unsafe for Oni to the left\n        for (int k = j + 1; k < N; ++k) {\n            safe_left[i][k] = false;\n        }\n    }\n}\n\nvector<pair<char, int>> moves;\n\nvoid shift_row_left(int i) {\n    moves.emplace_back('L', i);\n    char first = board[i][0];\n    for (int j = 0; j < N - 1; ++j) {\n        board[i][j] = board[i][j + 1];\n    }\n    board[i][N - 1] = '.';\n}\n\nvoid shift_row_right(int i) {\n    moves.emplace_back('R', i);\n    char last = board[i][N - 1];\n    for (int j = N - 1; j > 0; --j) {\n        board[i][j] = board[i][j - 1];\n    }\n    board[i][0] = '.';\n}\n\nvoid shift_col_up(int j) {\n    moves.emplace_back('U', j);\n    char first = board[0][j];\n    for (int i = 0; i < N - 1; ++i) {\n        board[i][j] = board[i + 1][j];\n    }\n    board[N - 1][j] = '.';\n}\n\nvoid shift_col_down(int j) {\n    moves.emplace_back('D', j);\n    char last = board[N - 1][j];\n    for (int i = N - 1; i > 0; --i) {\n        board[i][j] = board[i - 1][j];\n    }\n    board[0][j] = '.';\n}\n\nvoid remove_oni() {\n    while (true) {\n        // Check if all Oni are removed\n        bool all_removed = true;\n        for (const auto& row : board) {\n            if (row.find('x') != string::npos) {\n                all_removed = false;\n                break;\n            }\n        }\n        if (all_removed) break;\n\n        // Find the row or column with the most removable Oni\n        int max_oni = 0;\n        char best_dir = ' ';\n        int best_idx = -1;\n\n        // Check rows for left/right shifts\n        for (int i = 0; i < N; ++i) {\n            int left_oni = 0, right_oni = 0;\n            for (int j = 0; j < N; ++j) {\n                if (board[i][j] == 'x') {\n                    if (safe_left[i][j]) left_oni++;\n                    if (safe_right[i][j]) right_oni++;\n                }\n            }\n            if (left_oni > max_oni) {\n                max_oni = left_oni;\n                best_dir = 'L';\n                best_idx = i;\n            }\n            if (right_oni > max_oni) {\n                max_oni = right_oni;\n                best_dir = 'R';\n                best_idx = i;\n            }\n        }\n\n        // Check columns for up/down shifts\n        for (int j = 0; j < N; ++j) {\n            int up_oni = 0, down_oni = 0;\n            for (int i = 0; i < N; ++i) {\n                if (board[i][j] == 'x') {\n                    if (safe_up[i][j]) up_oni++;\n                    if (safe_down[i][j]) down_oni++;\n                }\n            }\n            if (up_oni > max_oni) {\n                max_oni = up_oni;\n                best_dir = 'U';\n                best_idx = j;\n            }\n            if (down_oni > max_oni) {\n                max_oni = down_oni;\n                best_dir = 'D';\n                best_idx = j;\n            }\n        }\n\n        if (max_oni == 0) {\n            // No removable Oni found (should not happen due to problem guarantee)\n            break;\n        }\n\n        // Perform the best shift\n        if (best_dir == 'L') shift_row_left(best_idx);\n        else if (best_dir == 'R') shift_row_right(best_idx);\n        else if (best_dir == 'U') shift_col_up(best_idx);\n        else if (best_dir == 'D') shift_col_down(best_idx);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    board.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n    }\n\n    // Collect Oni and Fukunokami positions\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                oni_list.push_back({i, j, 'x'});\n            } else if (board[i][j] == 'o') {\n                fuku_list.push_back({i, j, 'o'});\n            }\n        }\n    }\n\n    preprocess();\n    remove_oni();\n\n    // Output the moves\n    for (const auto& move : moves) {\n        cout << move.first << \" \" << move.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <climits>\n#include <cmath>\n#include <chrono>\n#include <numeric>\n\nusing namespace std;\n\nconst int N = 100;\nconst int L = 500000;\n\nstruct Employee {\n    int a, b;\n};\n\nvector<int> simulate(const vector<Employee>& employees, const vector<int>& T, int max_weeks = L) {\n    vector<int> t(N, 0);\n    int current = 0;\n    t[current]++;\n    for (int week = 1; week < max_weeks; ++week) {\n        int cnt = t[current];\n        if (cnt % 2 == 1) {\n            current = employees[current].a;\n        } else {\n            current = employees[current].b;\n        }\n        t[current]++;\n    }\n    return t;\n}\n\nlong long calculate_error(const vector<int>& t, const vector<int>& T) {\n    long long error = 0;\n    for (int i = 0; i < N; ++i) {\n        error += abs(t[i] - T[i]);\n    }\n    return error;\n}\n\nvector<Employee> greedy_initial(const vector<int>& T) {\n    vector<Employee> employees(N);\n    vector<int> current_t(N, 0);\n    current_t[0] = 1;\n    int current = 0;\n    for (int week = 1; week < L; ++week) {\n        int cnt = current_t[current];\n        vector<pair<int, int>> candidates;\n        for (int i = 0; i < N; ++i) {\n            candidates.emplace_back(T[i] - current_t[i], i);\n        }\n        sort(candidates.rbegin(), candidates.rend());\n        int next = candidates[0].second;\n        if (cnt % 2 == 1) {\n            employees[current].a = next;\n        } else {\n            employees[current].b = next;\n        }\n        current = next;\n        current_t[current]++;\n    }\n    return employees;\n}\n\nvector<Employee> optimized_local_search(const vector<int>& T, vector<Employee> employees, int max_iter = 5, int sample_size = 10000) {\n    auto t = simulate(employees, T, sample_size);\n    long long best_error = calculate_error(t, T);\n    vector<Employee> best_employees = employees;\n\n    random_device rd;\n    mt19937 gen(rd());\n\n    for (int iter = 0; iter < max_iter; ++iter) {\n        bool improved = false;\n        vector<int> indices(N);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), gen);\n\n        for (int i : indices) {\n            vector<int> candidates;\n            for (int j = 0; j < N; ++j) {\n                if (j != employees[i].a) candidates.push_back(j);\n                if (j != employees[i].b) candidates.push_back(j);\n            }\n            shuffle(candidates.begin(), candidates.end(), gen);\n            candidates.resize(min(10, (int)candidates.size()));\n\n            for (int new_val : candidates) {\n                if (new_val == employees[i].a) continue;\n                auto old_a = employees[i].a;\n                employees[i].a = new_val;\n                auto new_t = simulate(employees, T, sample_size);\n                long long new_error = calculate_error(new_t, T);\n                if (new_error < best_error) {\n                    best_error = new_error;\n                    best_employees = employees;\n                    improved = true;\n                    break;\n                } else {\n                    employees[i].a = old_a;\n                }\n            }\n\n            if (improved) break;\n\n            for (int new_val : candidates) {\n                if (new_val == employees[i].b) continue;\n                auto old_b = employees[i].b;\n                employees[i].b = new_val;\n                auto new_t = simulate(employees, T, sample_size);\n                long long new_error = calculate_error(new_t, T);\n                if (new_error < best_error) {\n                    best_error = new_error;\n                    best_employees = employees;\n                    improved = true;\n                    break;\n                } else {\n                    employees[i].b = old_b;\n                }\n            }\n\n            if (improved) break;\n        }\n\n        if (!improved) break;\n        employees = best_employees;\n    }\n    return best_employees;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, L_in;\n    cin >> N_in >> L_in;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    auto employees = greedy_initial(T);\n    employees = optimized_local_search(T, employees);\n\n    for (const auto& emp : employees) {\n        cout << emp.a << \" \" << emp.b << \"\\n\";\n    }\n\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct City {\n    int lx, rx, ly, ry;\n    int x, y; // Estimated coordinates\n};\n\nint N, M, Q, L, W;\nvector<int> G;\nvector<City> cities;\nvector<vector<int>> groups;\nvector<vector<pair<int, int>>> edges;\n\nvector<pair<int, int>> query(const vector<int>& C) {\n    cout << \"? \" << C.size();\n    for (int c : C) cout << \" \" << c;\n    cout << endl;\n    cout.flush();\n\n    vector<pair<int, int>> res;\n    for (int i = 0; i < (int)C.size() - 1; ++i) {\n        int a, b;\n        cin >> a >> b;\n        res.emplace_back(a, b);\n    }\n    return res;\n}\n\nvoid answer() {\n    cout << \"!\" << endl;\n    for (int k = 0; k < M; ++k) {\n        for (int c : groups[k]) cout << c << \" \";\n        cout << endl;\n        for (auto [a, b] : edges[k]) {\n            cout << a << \" \" << b << endl;\n        }\n    }\n    cout.flush();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M >> Q >> L >> W;\n    G.resize(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    cities.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].x = (cities[i].lx + cities[i].rx) / 2;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2;\n    }\n\n    // Initial grouping based on estimated coordinates\n    vector<int> city_indices(N);\n    iota(city_indices.begin(), city_indices.end(), 0);\n    sort(city_indices.begin(), city_indices.end(), [&](int a, int b) {\n        if (cities[a].x != cities[b].x) return cities[a].x < cities[b].x;\n        return cities[a].y < cities[b].y;\n    });\n\n    groups.resize(M);\n    int start = 0;\n    for (int k = 0; k < M; ++k) {\n        for (int i = 0; i < G[k]; ++i) {\n            groups[k].push_back(city_indices[start + i]);\n        }\n        start += G[k];\n    }\n\n    // Perform queries to get MST edges\n    edges.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int n = groups[k].size();\n        if (n == 1) continue;\n        if (n == 2) {\n            edges[k].emplace_back(groups[k][0], groups[k][1]);\n            continue;\n        }\n        for (int i = 0; i < n - 1; i += L - 1) {\n            int end = min(i + L, n);\n            vector<int> subset(groups[k].begin() + i, groups[k].begin() + end);\n            auto res = query(subset);\n            for (auto [a, b] : res) {\n                edges[k].emplace_back(a, b);\n            }\n        }\n    }\n\n    // Refinement step: Ensure each group is connected\n    for (int k = 0; k < M; ++k) {\n        if (groups[k].size() == 1) continue;\n        dsu d(groups[k].size());\n        for (auto [a, b] : edges[k]) {\n            int u = find(groups[k].begin(), groups[k].end(), a) - groups[k].begin();\n            int v = find(groups[k].begin(), groups[k].end(), b) - groups[k].begin();\n            d.merge(u, v);\n        }\n        if (d.size(0) != groups[k].size()) {\n            // Need to add more edges to connect the group\n            for (int i = 1; i < groups[k].size(); ++i) {\n                if (!d.same(0, i)) {\n                    edges[k].emplace_back(groups[k][0], groups[k][i]);\n                    d.merge(0, i);\n                }\n            }\n        }\n    }\n\n    answer();\n\n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\nconst int M = 40;\nconst int MAX_ACTIONS = 2 * N * M;\nconst int BEAM_WIDTH = 100;\n\nstruct State {\n    int i, j;\n    vector<vector<bool>> blocks;\n    int next_target;\n    vector<pair<char, char>> actions;\n    int score;\n\n    State(int i, int j, vector<vector<bool>> blocks, int next_target, vector<pair<char, char>> actions)\n        : i(i), j(j), blocks(blocks), next_target(next_target), actions(actions), score(0) {}\n\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n};\n\nvector<pair<int, int>> targets;\n\nint manhattan(int i1, int j1, int i2, int j2) {\n    return abs(i1 - i2) + abs(j1 - j2);\n}\n\nbool is_blocked(int i, int j, const vector<vector<bool>>& blocks) {\n    if (i < 0 || i >= N || j < 0 || j >= N) return true;\n    return blocks[i][j];\n}\n\nvector<State> expand(const State& state) {\n    vector<State> next_states;\n    vector<char> actions = {'M', 'S', 'A'};\n    vector<char> directions = {'U', 'D', 'L', 'R'};\n\n    for (char a : actions) {\n        for (char d : directions) {\n            State new_state = state;\n            new_state.actions.emplace_back(a, d);\n            int di = 0, dj = 0;\n            if (d == 'U') di = -1;\n            if (d == 'D') di = 1;\n            if (d == 'L') dj = -1;\n            if (d == 'R') dj = 1;\n\n            if (a == 'M') {\n                int ni = state.i + di, nj = state.j + dj;\n                if (!is_blocked(ni, nj, state.blocks)) {\n                    new_state.i = ni;\n                    new_state.j = nj;\n                } else {\n                    continue;\n                }\n            } else if (a == 'S') {\n                int ni = state.i, nj = state.j;\n                while (true) {\n                    int nni = ni + di, nnj = nj + dj;\n                    if (is_blocked(nni, nnj, state.blocks)) break;\n                    ni = nni;\n                    nj = nnj;\n                }\n                new_state.i = ni;\n                new_state.j = nj;\n            } else if (a == 'A') {\n                int ni = state.i + di, nj = state.j + dj;\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                new_state.blocks[ni][nj] = !new_state.blocks[ni][nj];\n            }\n\n            // Check if next target is reached\n            if (new_state.next_target < M &&\n                new_state.i == targets[new_state.next_target].first &&\n                new_state.j == targets[new_state.next_target].second) {\n                new_state.next_target++;\n            }\n\n            // Evaluate score\n            int dist = 0;\n            if (new_state.next_target < M) {\n                dist = manhattan(new_state.i, new_state.j, targets[new_state.next_target].first, targets[new_state.next_target].second);\n            }\n            new_state.score = -new_state.actions.size() - dist - (M - new_state.next_target) * 100;\n            next_states.push_back(new_state);\n        }\n    }\n    return next_states;\n}\n\nvector<pair<char, char>> beam_search(int start_i, int start_j) {\n    vector<vector<bool>> initial_blocks(N, vector<bool>(N, false));\n    State initial_state(start_i, start_j, initial_blocks, 0, {});\n    priority_queue<State> beam;\n    beam.push(initial_state);\n\n    for (int step = 0; step < MAX_ACTIONS; ++step) {\n        priority_queue<State> next_beam;\n        for (int i = 0; i < BEAM_WIDTH && !beam.empty(); ++i) {\n            State current = beam.top();\n            beam.pop();\n            if (current.next_target == M) {\n                return current.actions;\n            }\n            vector<State> next_states = expand(current);\n            for (State& next_state : next_states) {\n                if (next_state.actions.size() <= MAX_ACTIONS) {\n                    next_beam.push(next_state);\n                }\n            }\n        }\n        beam = move(next_beam);\n    }\n\n    // Return the best found\n    State best = beam.top();\n    return best.actions;\n}\n\nint main() {\n    int N_in, M_in;\n    cin >> N_in >> M_in;\n    targets.resize(M_in);\n    for (int i = 0; i < M_in; ++i) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n\n    vector<pair<char, char>> actions = beam_search(targets[0].first, targets[0].second);\n    for (auto [a, d] : actions) {\n        cout << a << \" \" << d << \"\\n\";\n    }\n    return 0;\n}"},"8":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Rect {\n    int a, b, c, d;\n    int area() const { return (c - a) * (d - b); }\n    bool contains(int x, int y) const {\n        return a <= x && x < c && b <= y && y < d;\n    }\n    bool overlaps(const Rect& other) const {\n        return !(c <= other.a || other.c <= a || d <= other.b || other.d <= b);\n    }\n};\n\nstruct Company {\n    int x, y, r;\n    Rect rect;\n    double satisfaction() const {\n        int s = rect.area();\n        if (s == 0) return 0.0;\n        double ratio = min(r, s) * 1.0 / max(r, s);\n        return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n    }\n};\n\nint n;\nvector<Company> companies;\nvector<Rect> placed_rects;\n\nbool is_valid(const Rect& rect, int ignore = -1) {\n    for (int i = 0; i < placed_rects.size(); ++i) {\n        if (i == ignore) continue;\n        if (rect.overlaps(placed_rects[i])) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid place_rect(const Rect& rect) {\n    placed_rects.push_back(rect);\n}\n\nvoid remove_rect(int id) {\n    placed_rects.erase(placed_rects.begin() + id);\n}\n\ndouble total_satisfaction() {\n    double total = 0.0;\n    for (const auto& company : companies) {\n        total += company.satisfaction();\n    }\n    return total;\n}\n\nvoid greedy_initialization() {\n    for (auto& company : companies) {\n        int x = company.x;\n        int y = company.y;\n        // Start with a 1x1 rectangle\n        company.rect = {x, y, x + 1, y + 1};\n        place_rect(company.rect);\n    }\n}\n\nvoid local_search() {\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (auto& company : companies) {\n            int id = &company - &companies[0];\n            Rect original = company.rect;\n            double original_sat = company.satisfaction();\n            vector<Rect> candidates;\n\n            // Try expanding in all four directions\n            // Expand right\n            if (company.rect.c < 10000) {\n                Rect new_rect = company.rect;\n                new_rect.c++;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand left\n            if (company.rect.a > 0) {\n                Rect new_rect = company.rect;\n                new_rect.a--;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand up\n            if (company.rect.d < 10000) {\n                Rect new_rect = company.rect;\n                new_rect.d++;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand down\n            if (company.rect.b > 0) {\n                Rect new_rect = company.rect;\n                new_rect.b--;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n\n            // Try to find the best candidate\n            double best_sat = original_sat;\n            Rect best_rect = original;\n            for (const auto& rect : candidates) {\n                company.rect = rect;\n                double sat = company.satisfaction();\n                if (sat > best_sat) {\n                    best_sat = sat;\n                    best_rect = rect;\n                }\n            }\n            if (best_sat > original_sat) {\n                remove_rect(id);\n                company.rect = best_rect;\n                place_rect(best_rect);\n                improved = true;\n            } else {\n                company.rect = original;\n            }\n        }\n    }\n}\n\nvoid simulated_annealing() {\n    double temperature = 1000.0;\n    double cooling_rate = 0.999;\n    double min_temperature = 0.1;\n    double current_sat = total_satisfaction();\n\n    while (temperature > min_temperature) {\n        for (auto& company : companies) {\n            int id = &company - &companies[0];\n            Rect original = company.rect;\n            double original_sat = company.satisfaction();\n\n            // Randomly choose a direction to expand or shrink\n            int dir = rand() % 4;\n            Rect new_rect = original;\n            switch (dir) {\n                case 0: // right\n                    if (new_rect.c < 10000) new_rect.c++;\n                    break;\n                case 1: // left\n                    if (new_rect.a > 0) new_rect.a--;\n                    break;\n                case 2: // up\n                    if (new_rect.d < 10000) new_rect.d++;\n                    break;\n                case 3: // down\n                    if (new_rect.b > 0) new_rect.b--;\n                    break;\n            }\n\n            if (!is_valid(new_rect, id)) continue;\n\n            company.rect = new_rect;\n            double new_sat = company.satisfaction();\n            double delta = new_sat - original_sat;\n\n            if (delta > 0 || (rand() / (double)RAND_MAX) < exp(delta / temperature)) {\n                remove_rect(id);\n                place_rect(new_rect);\n                current_sat += delta;\n            } else {\n                company.rect = original;\n            }\n        }\n        temperature *= cooling_rate;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> n;\n    companies.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n\n    greedy_initialization();\n    local_search();\n    simulated_annealing();\n\n    for (const auto& company : companies) {\n        cout << company.rect.a << \" \" << company.rect.b << \" \"\n             << company.rect.c << \" \" << company.rect.d << \"\\n\";\n    }\n\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct Tile {\n    vector<pair<int, int>> cells;\n    int sum = 0;\n    int id;\n};\n\nstruct State {\n    int score;\n    int last_tile;\n    int last_x, last_y;\n    vector<bool> visited_tiles;\n    string path;\n\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> t(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> t[i][j];\n        }\n    }\n\n    vector<vector<int>> p(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> p[i][j];\n        }\n    }\n\n    // Step 1: Identify tiles using DSU\n    dsu d(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && t[i][j] == t[ni][nj]) {\n                    d.merge(i * N + j, ni * N + nj);\n                }\n            }\n        }\n    }\n\n    // Step 2: Build tiles\n    map<int, Tile> tiles;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int root = d.leader(i * N + j);\n            tiles[root].cells.emplace_back(i, j);\n            tiles[root].sum += p[i][j];\n            tiles[root].id = root;\n        }\n    }\n\n    // Step 3: Build adjacency list for tiles\n    map<int, vector<int>> adj;\n    for (auto& [root, tile] : tiles) {\n        set<int> neighbors;\n        for (auto [i, j] : tile.cells) {\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                    int nroot = d.leader(ni * N + nj);\n                    if (nroot != root) {\n                        neighbors.insert(nroot);\n                    }\n                }\n            }\n        }\n        for (int nroot : neighbors) {\n            adj[root].push_back(nroot);\n        }\n    }\n\n    // Step 4: Beam search\n    const int BEAM_WIDTH = 1000;\n    priority_queue<State> beam;\n    State initial;\n    int start_root = d.leader(si * N + sj);\n    initial.score = p[si][sj];\n    initial.last_tile = start_root;\n    initial.last_x = si;\n    initial.last_y = sj;\n    initial.visited_tiles.resize(tiles.size(), false);\n    initial.visited_tiles[start_root] = true;\n    initial.path = \"\";\n    beam.push(initial);\n\n    string best_path;\n    int best_score = 0;\n\n    while (!beam.empty()) {\n        priority_queue<State> next_beam;\n        for (int i = 0; i < BEAM_WIDTH && !beam.empty(); ++i) {\n            State current = beam.top();\n            beam.pop();\n\n            if (current.score > best_score) {\n                best_score = current.score;\n                best_path = current.path;\n            }\n\n            for (int next_root : adj[current.last_tile]) {\n                if (current.visited_tiles[next_root]) continue;\n\n                State next = current;\n                next.last_tile = next_root;\n                next.visited_tiles[next_root] = true;\n                next.score += tiles[next_root].sum;\n\n                // Find a path within the next tile to traverse all its cells\n                auto& cells = tiles[next_root].cells;\n                vector<vector<bool>> visited(N, vector<bool>(N, false));\n                vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n                queue<pair<int, int>> q;\n                q.push({current.last_x, current.last_y});\n                visited[current.last_x][current.last_y] = true;\n                bool found = false;\n                pair<int, int> end_pos;\n\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    if (t[x][y] == next_root && (x != current.last_x || y != current.last_y)) {\n                        end_pos = {x, y};\n                        found = true;\n                        break;\n                    }\n                    for (int k = 0; k < 4; ++k) {\n                        int nx = x + dx[k];\n                        int ny = y + dy[k];\n                        if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && t[nx][ny] == next_root) {\n                            visited[nx][ny] = true;\n                            parent[nx][ny] = {x, y};\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n\n                if (!found) continue;\n\n                // Reconstruct path within the tile\n                string tile_path;\n                pair<int, int> pos = end_pos;\n                while (pos != make_pair(current.last_x, current.last_y)) {\n                    auto [px, py] = parent[pos.first][pos.second];\n                    for (int k = 0; k < 4; ++k) {\n                        if (px == pos.first + dx[k] && py == pos.second + dy[k]) {\n                            tile_path += dir[k];\n                            break;\n                        }\n                    }\n                    pos = {px, py};\n                }\n                reverse(tile_path.begin(), tile_path.end());\n                next.path += tile_path;\n                next.last_x = end_pos.first;\n                next.last_y = end_pos.second;\n\n                next_beam.push(next);\n            }\n        }\n        beam = move(next_beam);\n    }\n\n    cout << best_path << endl;\n\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 30;\nconst int INF = 1e9;\nconst double ALPHA = 0.1; // Learning rate\n\nstruct Edge {\n    int to_i, to_j;\n    int dir; // 0: right (R), 1: down (D), 2: left (L), 3: up (U)\n    double weight;\n};\n\nvector<vector<vector<Edge>>> adj(N, vector<vector<Edge>>(N));\nvector<vector<double>> h(N, vector<double>(N-1, 5000.0)); // horizontal edges\nvector<vector<double>> v(N-1, vector<double>(N, 5000.0)); // vertical edges\n\nvoid init_adj() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (j + 1 < N) {\n                adj[i][j].push_back({i, j+1, 0, h[i][j]});\n            }\n            if (i + 1 < N) {\n                adj[i][j].push_back({i+1, j, 1, v[i][j]});\n            }\n            if (j - 1 >= 0) {\n                adj[i][j].push_back({i, j-1, 2, h[i][j-1]});\n            }\n            if (i - 1 >= 0) {\n                adj[i][j].push_back({i-1, j, 3, v[i-1][j]});\n            }\n        }\n    }\n}\n\nstring dijkstra(int si, int sj, int ti, int tj) {\n    vector<vector<double>> dist(N, vector<double>(N, INF));\n    vector<vector<pair<int, int>>> prev(N, vector<pair<int, int>>(N, {-1, -1}));\n    priority_queue<tuple<double, int, int>, vector<tuple<double, int, int>>, greater<>> pq;\n\n    dist[si][sj] = 0.0;\n    pq.emplace(0.0, si, sj);\n\n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top();\n        pq.pop();\n        if (i == ti && j == tj) break;\n        if (d > dist[i][j]) continue;\n        for (const auto& edge : adj[i][j]) {\n            int ni = edge.to_i;\n            int nj = edge.to_j;\n            double nd = d + edge.weight;\n            if (nd < dist[ni][nj]) {\n                dist[ni][nj] = nd;\n                prev[ni][nj] = {i, j};\n                pq.emplace(nd, ni, nj);\n            }\n        }\n    }\n\n    string path;\n    int ci = ti, cj = tj;\n    while (ci != si || cj != sj) {\n        auto [pi, pj] = prev[ci][cj];\n        if (pi == ci && pj == cj - 1) path += 'R';\n        else if (pi == ci && pj == cj + 1) path += 'L';\n        else if (pi == ci - 1 && pj == cj) path += 'D';\n        else if (pi == ci + 1 && pj == cj) path += 'U';\n        ci = pi;\n        cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nvoid update_weights(const string& path, int si, int sj, double total_length) {\n    int ci = si, cj = sj;\n    double path_length = 0.0;\n    for (char dir : path) {\n        int ni = ci, nj = cj;\n        if (dir == 'R') nj++;\n        else if (dir == 'L') nj--;\n        else if (dir == 'D') ni++;\n        else if (dir == 'U') ni--;\n\n        double edge_weight;\n        if (dir == 'R') edge_weight = h[ci][cj];\n        else if (dir == 'L') edge_weight = h[ci][cj-1];\n        else if (dir == 'D') edge_weight = v[ci][cj];\n        else if (dir == 'U') edge_weight = v[ci-1][cj];\n\n        path_length += edge_weight;\n        ci = ni;\n        cj = nj;\n    }\n\n    ci = si;\n    cj = sj;\n    for (char dir : path) {\n        int ni = ci, nj = cj;\n        if (dir == 'R') {\n            double new_weight = total_length * (h[ci][cj] / path_length);\n            h[ci][cj] = (1 - ALPHA) * h[ci][cj] + ALPHA * new_weight;\n            nj++;\n        } else if (dir == 'L') {\n            double new_weight = total_length * (h[ci][cj-1] / path_length);\n            h[ci][cj-1] = (1 - ALPHA) * h[ci][cj-1] + ALPHA * new_weight;\n            nj--;\n        } else if (dir == 'D') {\n            double new_weight = total_length * (v[ci][cj] / path_length);\n            v[ci][cj] = (1 - ALPHA) * v[ci][cj] + ALPHA * new_weight;\n            ni++;\n        } else if (dir == 'U') {\n            double new_weight = total_length * (v[ci-1][cj] / path_length);\n            v[ci-1][cj] = (1 - ALPHA) * v[ci-1][cj] + ALPHA * new_weight;\n            ni--;\n        }\n        ci = ni;\n        cj = nj;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    init_adj();\n\n    for (int k = 0; k < 1000; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n\n        string path = dijkstra(si, sj, ti, tj);\n        cout << path << endl;\n        cout.flush();\n\n        int total_length;\n        cin >> total_length;\n\n        update_weights(path, si, sj, total_length);\n    }\n\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_LEN = 12;\nconst vector<char> CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};\nconst vector<char> ALL_CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', '.'};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct State {\n    vector<string> grid;\n    int c; // number of matched strings\n    int d; // number of '.'\n    double energy;\n};\n\nvector<string> strings;\nint M;\n\nint count_matched(const vector<string>& grid) {\n    int matched = 0;\n    for (const string& s : strings) {\n        int k = s.size();\n        bool found = false;\n        // Check rows\n        for (int i = 0; i < N && !found; ++i) {\n            for (int j = 0; j < N && !found; ++j) {\n                bool match = true;\n                for (int p = 0; p < k; ++p) {\n                    if (grid[i][(j + p) % N] != s[p]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) {\n                    found = true;\n                    break;\n                }\n            }\n        }\n        // Check columns\n        for (int j = 0; j < N && !found; ++j) {\n            for (int i = 0; i < N && !found; ++i) {\n                bool match = true;\n                for (int p = 0; p < k; ++p) {\n                    if (grid[(i + p) % N][j] != s[p]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) {\n                    found = true;\n                    break;\n                }\n            }\n        }\n        if (found) {\n            matched++;\n        }\n    }\n    return matched;\n}\n\nint count_dots(const vector<string>& grid) {\n    int dots = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == '.') {\n                dots++;\n            }\n        }\n    }\n    return dots;\n}\n\ndouble compute_energy(int c, int d) {\n    if (c < M) {\n        return -1e8 * c / M;\n    } else {\n        return -1e8 * (2 * N * N) / (2 * N * N - d);\n    }\n}\n\nState get_initial_state() {\n    State state;\n    state.grid.resize(N, string(N, '.'));\n    state.d = N * N;\n    state.c = 0;\n    state.energy = compute_energy(state.c, state.d);\n\n    // Sort strings by length in descending order to place longer strings first\n    vector<pair<int, string>> sorted_strings;\n    for (const string& s : strings) {\n        sorted_strings.emplace_back(s.size(), s);\n    }\n    sort(sorted_strings.rbegin(), sorted_strings.rend());\n\n    for (const auto& [len, s] : sorted_strings) {\n        bool placed = false;\n        // Try to place horizontally\n        for (int i = 0; i < N && !placed; ++i) {\n            for (int j = 0; j < N && !placed; ++j) {\n                bool can_place = true;\n                for (int p = 0; p < len; ++p) {\n                    char c = state.grid[i][(j + p) % N];\n                    if (c != '.' && c != s[p]) {\n                        can_place = false;\n                        break;\n                    }\n                }\n                if (can_place) {\n                    for (int p = 0; p < len; ++p) {\n                        char& c = state.grid[i][(j + p) % N];\n                        if (c == '.') {\n                            c = s[p];\n                            state.d--;\n                        }\n                    }\n                    placed = true;\n                }\n            }\n        }\n        // Try to place vertically\n        for (int j = 0; j < N && !placed; ++j) {\n            for (int i = 0; i < N && !placed; ++i) {\n                bool can_place = true;\n                for (int p = 0; p < len; ++p) {\n                    char c = state.grid[(i + p) % N][j];\n                    if (c != '.' && c != s[p]) {\n                        can_place = false;\n                        break;\n                    }\n                }\n                if (can_place) {\n                    for (int p = 0; p < len; ++p) {\n                        char& c = state.grid[(i + p) % N][j];\n                        if (c == '.') {\n                            c = s[p];\n                            state.d--;\n                        }\n                    }\n                    placed = true;\n                }\n            }\n        }\n    }\n    state.c = count_matched(state.grid);\n    state.energy = compute_energy(state.c, state.d);\n    return state;\n}\n\nState simulated_annealing(State initial_state, double initial_temp, double final_temp, double cooling_rate, int iterations) {\n    State current = initial_state;\n    State best = current;\n    double temp = initial_temp;\n\n    for (int iter = 0; iter < iterations; ++iter) {\n        // Generate neighbor\n        int i = rng() % N;\n        int j = rng() % N;\n        char old_char = current.grid[i][j];\n        char new_char;\n        do {\n            new_char = CHARS[rng() % CHARS.size()]; // Only pick from A-H\n        } while (new_char == old_char);\n\n        // Compute new state\n        vector<string> new_grid = current.grid;\n        new_grid[i][j] = new_char;\n        int new_c = count_matched(new_grid);\n        int new_d = count_dots(new_grid);\n        double new_energy = compute_energy(new_c, new_d);\n\n        // Decide whether to accept\n        double delta_energy = new_energy - current.energy;\n        if (delta_energy < 0 || exp(-delta_energy / temp) > (double)rng() / rng.max()) {\n            current.grid = new_grid;\n            current.c = new_c;\n            current.d = new_d;\n            current.energy = new_energy;\n            if (current.energy < best.energy) {\n                best = current;\n            }\n        }\n\n        // Cool down\n        temp *= cooling_rate;\n        if (temp < final_temp) {\n            break;\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> M;\n    strings.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i];\n    }\n\n    // Parameters for simulated annealing\n    double initial_temp = 1e5;\n    double final_temp = 1e-4;\n    double cooling_rate = 0.9995;\n    int iterations = 2e6;\n\n    State initial_state = get_initial_state();\n    State best_state = simulated_annealing(initial_state, initial_temp, final_temp, cooling_rate, iterations);\n\n    // Ensure all characters are valid\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (best_state.grid[i][j] != '.' && (best_state.grid[i][j] < 'A' || best_state.grid[i][j] > 'H')) {\n                best_state.grid[i][j] = '.'; // Replace illegal characters with '.'\n            }\n        }\n    }\n\n    for (const string& row : best_state.grid) {\n        cout << row << '\\n';\n    }\n\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int INF = 1e9;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nint N, si, sj;\nvector<string> grid;\nvector<vector<int>> cost;\nvector<vector<bool>> is_road;\nvector<vector<vector<Point>>> visible;\nvector<vector<int>> dist;\nvector<vector<Point>> parent;\nvector<Point> road_points;\n\nvoid precompute_visible() {\n    visible.assign(N, vector<vector<Point>>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!is_road[i][j]) continue;\n            // Check left\n            for (int k = j - 1; k >= 0; --k) {\n                if (!is_road[i][k]) break;\n                visible[i][j].emplace_back(i, k);\n            }\n            // Check right\n            for (int k = j + 1; k < N; ++k) {\n                if (!is_road[i][k]) break;\n                visible[i][j].emplace_back(i, k);\n            }\n            // Check up\n            for (int k = i - 1; k >= 0; --k) {\n                if (!is_road[k][j]) break;\n                visible[i][j].emplace_back(k, j);\n            }\n            // Check down\n            for (int k = i + 1; k < N; ++k) {\n                if (!is_road[k][j]) break;\n                visible[i][j].emplace_back(k, j);\n            }\n        }\n    }\n}\n\nvoid dijkstra(Point start) {\n    dist.assign(N, vector<int>(N, INF));\n    parent.assign(N, vector<Point>(N, Point(-1, -1)));\n    priority_queue<pair<int, Point>, vector<pair<int, Point>>, greater<pair<int, Point>>> pq;\n    dist[start.x][start.y] = 0;\n    pq.emplace(0, start);\n    while (!pq.empty()) {\n        auto [current_dist, p] = pq.top();\n        pq.pop();\n        if (current_dist > dist[p.x][p.y]) continue;\n        for (int d = 0; d < 4; ++d) {\n            int nx = p.x + dx[d];\n            int ny = p.y + dy[d];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            if (!is_road[nx][ny]) continue;\n            int new_dist = current_dist + cost[nx][ny];\n            if (new_dist < dist[nx][ny]) {\n                dist[nx][ny] = new_dist;\n                parent[nx][ny] = p;\n                pq.emplace(new_dist, Point(nx, ny));\n            }\n        }\n    }\n}\n\nstring reconstruct_path(Point start, Point end) {\n    string path;\n    Point p = end;\n    while (!(p == start)) {\n        Point par = parent[p.x][p.y];\n        for (int d = 0; d < 4; ++d) {\n            if (par.x + dx[d] == p.x && par.y + dy[d] == p.y) {\n                path += dir[d];\n                break;\n            }\n        }\n        p = par;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nstring solve() {\n    // Precompute road points\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (is_road[i][j]) {\n                road_points.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Precompute visible squares for each road point\n    precompute_visible();\n\n    // Greedy approach: start from (si, sj) and cover all road points\n    vector<vector<bool>> covered(N, vector<bool>(N, false));\n    vector<Point> route;\n    route.emplace_back(si, sj);\n    covered[si][sj] = true;\n\n    // Mark all points visible from (si, sj) as covered\n    for (const auto& p : visible[si][sj]) {\n        covered[p.x][p.y] = true;\n    }\n\n    // Priority queue to keep track of uncovered road points sorted by distance\n    priority_queue<pair<int, Point>, vector<pair<int, Point>>, greater<pair<int, Point>>> pq;\n    dijkstra(route.back());\n    for (const auto& p : road_points) {\n        if (!covered[p.x][p.y]) {\n            pq.emplace(dist[p.x][p.y], p);\n        }\n    }\n\n    // While there are uncovered points\n    while (!pq.empty()) {\n        auto [current_dist, next_point] = pq.top();\n        pq.pop();\n        if (covered[next_point.x][next_point.y]) continue;\n\n        // Move to the next point\n        dijkstra(route.back());\n        string best_path = reconstruct_path(route.back(), next_point);\n        for (char c : best_path) {\n            if (c == 'U') route.emplace_back(route.back().x - 1, route.back().y);\n            else if (c == 'D') route.emplace_back(route.back().x + 1, route.back().y);\n            else if (c == 'L') route.emplace_back(route.back().x, route.back().y - 1);\n            else if (c == 'R') route.emplace_back(route.back().x, route.back().y + 1);\n        }\n        route.push_back(next_point);\n\n        // Mark all points visible from the new point as covered\n        for (const auto& p : visible[next_point.x][next_point.y]) {\n            if (!covered[p.x][p.y]) {\n                covered[p.x][p.y] = true;\n                // Update the priority queue with new distances\n                dijkstra(route.back());\n                pq.emplace(dist[p.x][p.y], p);\n            }\n        }\n    }\n\n    // Return to start\n    dijkstra(route.back());\n    string return_path = reconstruct_path(route.back(), Point(si, sj));\n    for (char c : return_path) {\n        if (c == 'U') route.emplace_back(route.back().x - 1, route.back().y);\n        else if (c == 'D') route.emplace_back(route.back().x + 1, route.back().y);\n        else if (c == 'L') route.emplace_back(route.back().x, route.back().y - 1);\n        else if (c == 'R') route.emplace_back(route.back().x, route.back().y + 1);\n    }\n\n    // Reconstruct the path string\n    string result;\n    for (size_t i = 1; i < route.size(); ++i) {\n        Point prev = route[i-1];\n        Point curr = route[i];\n        if (prev.x == curr.x && prev.y == curr.y - 1) result += 'R';\n        else if (prev.x == curr.x && prev.y == curr.y + 1) result += 'L';\n        else if (prev.x == curr.x - 1 && prev.y == curr.y) result += 'D';\n        else if (prev.x == curr.x + 1 && prev.y == curr.y) result += 'U';\n    }\n\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> si >> sj;\n    grid.resize(N);\n    cost.assign(N, vector<int>(N));\n    is_road.assign(N, vector<bool>(N, false));\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                is_road[i][j] = true;\n                cost[i][j] = grid[i][j] - '0';\n            }\n        }\n    }\n\n    string ans = solve();\n    cout << ans << endl;\n\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <map>\n#include <set>\n#include <climits>\n#include <cassert>\n\nusing namespace std;\n\nstruct Task {\n    int id;\n    vector<int> difficulty;\n    vector<int> dependencies;\n    vector<int> dependents;\n    int in_degree = 0;\n    bool completed = false;\n    int assigned_member = -1;\n    int start_day = -1;\n    int completion_day = -1;\n    int critical_path = 0;\n};\n\nstruct Member {\n    int id;\n    vector<int> skills;\n    int current_task = -1;\n    int task_end_day = -1;\n    vector<pair<int, int>> task_history; // task_id, completion_time\n};\n\nclass Scheduler {\nprivate:\n    int N, M, K, R;\n    vector<Task> tasks;\n    vector<Member> members;\n    vector<vector<int>> adj;\n    vector<int> in_degree;\n    vector<int> topo_order;\n    vector<vector<int>> task_dependencies;\n    vector<vector<int>> task_dependents;\n    vector<vector<int>> skill_estimates;\n    vector<int> available_members;\n    int current_day = 0;\n    mt19937 rng;\n\n    void topological_sort() {\n        queue<int> q;\n        for (int i = 0; i < N; ++i) {\n            if (in_degree[i] == 0) {\n                q.push(i);\n            }\n        }\n        while (!q.empty()) {\n            int u = q.front();\n            q.pop();\n            topo_order.push_back(u);\n            for (int v : adj[u]) {\n                if (--in_degree[v] == 0) {\n                    q.push(v);\n                }\n            }\n        }\n    }\n\n    void calculate_critical_paths() {\n        vector<int> max_path(N, 0);\n        for (int u : topo_order) {\n            for (int v : tasks[u].dependents) {\n                max_path[v] = max(max_path[v], max_path[u] + 1);\n            }\n        }\n        for (int i = 0; i < N; ++i) {\n            tasks[i].critical_path = max_path[i];\n        }\n    }\n\n    void update_skill_estimates(int member_id, int task_id, int completion_time) {\n        Member& member = members[member_id];\n        Task& task = tasks[task_id];\n        member.task_history.emplace_back(task_id, completion_time);\n\n        for (int k = 0; k < K; ++k) {\n            int diff = task.difficulty[k];\n            int& skill = skill_estimates[member_id][k];\n            if (completion_time == 1) {\n                skill = max(skill, diff);\n            } else {\n                skill = min(skill, diff - 1);\n            }\n        }\n    }\n\n    int estimate_completion_time(int member_id, int task_id) {\n        const Task& task = tasks[task_id];\n        int w = 0;\n        for (int k = 0; k < K; ++k) {\n            w += max(0, task.difficulty[k] - skill_estimates[member_id][k]);\n        }\n        if (w == 0) {\n            return 1;\n        } else {\n            return max(1, w + 0); // Assuming r_i = 0 for estimation\n        }\n    }\n\n    bool is_task_ready(int task_id) {\n        for (int dep : tasks[task_id].dependencies) {\n            if (!tasks[dep].completed) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    void assign_tasks() {\n        vector<pair<int, int>> assignments;\n        for (int member_id : available_members) {\n            if (members[member_id].current_task != -1) continue;\n\n            int best_task = -1;\n            int best_priority = -1;\n            for (int task_id : topo_order) {\n                Task& task = tasks[task_id];\n                if (task.completed || task.assigned_member != -1) continue;\n                if (!is_task_ready(task_id)) continue;\n\n                int priority = task.critical_path * 1000 + (int)task.dependents.size();\n                if (priority > best_priority) {\n                    best_priority = priority;\n                    best_task = task_id;\n                }\n            }\n\n            if (best_task != -1) {\n                Task& task = tasks[best_task];\n                int est_time = estimate_completion_time(member_id, best_task);\n                task.assigned_member = member_id;\n                task.start_day = current_day;\n                members[member_id].current_task = best_task;\n                members[member_id].task_end_day = current_day + est_time - 1;\n                assignments.emplace_back(member_id, best_task);\n            }\n        }\n\n        cout << assignments.size();\n        for (auto [member_id, task_id] : assignments) {\n            cout << \" \" << member_id + 1 << \" \" << task_id + 1;\n        }\n        cout << endl;\n    }\n\n    void process_completions(const vector<int>& completed_members) {\n        for (int member_id : completed_members) {\n            Member& member = members[member_id];\n            if (member.current_task == -1) continue;\n\n            Task& task = tasks[member.current_task];\n            task.completed = true;\n            task.completion_day = current_day;\n            member.current_task = -1;\n            member.task_end_day = -1;\n            available_members.push_back(member_id);\n\n            int completion_time = current_day - task.start_day + 1;\n            update_skill_estimates(member_id, task.id, completion_time);\n        }\n    }\n\npublic:\n    Scheduler(int N, int M, int K, int R, const vector<vector<int>>& difficulties, const vector<pair<int, int>>& dependencies)\n        : N(N), M(M), K(K), R(R), rng(random_device{}()) {\n        tasks.resize(N);\n        for (int i = 0; i < N; ++i) {\n            tasks[i].id = i;\n            tasks[i].difficulty = difficulties[i];\n        }\n\n        adj.resize(N);\n        in_degree.resize(N, 0);\n        task_dependencies.resize(N);\n        task_dependents.resize(N);\n        for (auto [u, v] : dependencies) {\n            u--; v--;\n            adj[u].push_back(v);\n            in_degree[v]++;\n            task_dependencies[v].push_back(u);\n            task_dependents[u].push_back(v);\n        }\n\n        for (int i = 0; i < N; ++i) {\n            tasks[i].dependencies = task_dependencies[i];\n            tasks[i].dependents = task_dependents[i];\n        }\n\n        topological_sort();\n        calculate_critical_paths();\n\n        members.resize(M);\n        for (int i = 0; i < M; ++i) {\n            members[i].id = i;\n            members[i].skills.resize(K, 0);\n            skill_estimates.push_back(vector<int>(K, 0));\n            available_members.push_back(i);\n        }\n    }\n\n    void run() {\n        while (current_day < 2000) {\n            current_day++;\n            assign_tasks();\n\n            int n;\n            cin >> n;\n            if (n == -1) {\n                break;\n            }\n            vector<int> completed_members(n);\n            for (int i = 0; i < n; ++i) {\n                cin >> completed_members[i];\n                completed_members[i]--;\n            }\n            process_completions(completed_members);\n        }\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<vector<int>> difficulties(N, vector<int>(K));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> difficulties[i][j];\n        }\n    }\n\n    vector<pair<int, int>> dependencies(R);\n    for (int i = 0; i < R; ++i) {\n        cin >> dependencies[i].first >> dependencies[i].second;\n    }\n\n    Scheduler scheduler(N, M, K, R, difficulties, dependencies);\n    scheduler.run();\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1000;\nconst int M = 50;\nconst int OFFICE_X = 400;\nconst int OFFICE_Y = 400;\n\nstruct Order {\n    int id;\n    int a, b, c, d;\n    int dist_to_office;\n    int dist_pickup_delivery;\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nvector<Order> orders;\nvector<int> selected_orders;\nvector<pair<int, int>> points;\nvector<int> route;\n\nint compute_total_distance(const vector<int>& route) {\n    int total = 0;\n    for (int i = 0; i < (int)route.size() - 1; ++i) {\n        auto [x1, y1] = points[route[i]];\n        auto [x2, y2] = points[route[i+1]];\n        total += manhattan(x1, y1, x2, y2);\n    }\n    return total;\n}\n\nbool check_precedence(const vector<int>& route) {\n    vector<int> pickup_pos(M + 1, -1);\n    vector<int> delivery_pos(M + 1, -1);\n    for (int i = 0; i < (int)route.size(); ++i) {\n        int idx = route[i];\n        if (idx >= 1 && idx <= M) {\n            pickup_pos[idx] = i;\n        } else if (idx >= M + 1 && idx <= 2 * M) {\n            delivery_pos[idx - M] = i;\n        }\n    }\n    for (int i = 1; i <= M; ++i) {\n        if (pickup_pos[i] == -1 || delivery_pos[i] == -1) {\n            return false;\n        }\n        if (pickup_pos[i] >= delivery_pos[i]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid two_opt_with_precedence(vector<int>& route) {\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 1; i < (int)route.size() - 2; ++i) {\n            for (int j = i + 1; j < (int)route.size() - 1; ++j) {\n                if (j - i == 1) continue;\n                vector<int> new_route = route;\n                reverse(new_route.begin() + i, new_route.begin() + j + 1);\n                if (check_precedence(new_route)) {\n                    int current_dist = compute_total_distance(route);\n                    int new_dist = compute_total_distance(new_route);\n                    if (new_dist < current_dist) {\n                        route = new_route;\n                        improved = true;\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid solve() {\n    // Read input\n    orders.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n        orders[i].id = i + 1;\n        orders[i].dist_to_office = manhattan(orders[i].a, orders[i].b, OFFICE_X, OFFICE_Y) +\n                                   manhattan(orders[i].c, orders[i].d, OFFICE_X, OFFICE_Y);\n        orders[i].dist_pickup_delivery = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n    }\n\n    // Select orders with smallest dist_to_office\n    sort(orders.begin(), orders.end(), [](const Order& a, const Order& b) {\n        return a.dist_to_office < b.dist_to_office;\n    });\n    selected_orders.clear();\n    for (int i = 0; i < M; ++i) {\n        selected_orders.push_back(orders[i].id);\n    }\n\n    // Prepare points: 0 is office, 1..M are pickups, M+1..2M are deliveries\n    points.clear();\n    points.emplace_back(OFFICE_X, OFFICE_Y); // 0\n    for (int i = 0; i < M; ++i) {\n        points.emplace_back(orders[i].a, orders[i].b); // 1..M\n    }\n    for (int i = 0; i < M; ++i) {\n        points.emplace_back(orders[i].c, orders[i].d); // M+1..2M\n    }\n\n    // Initial route: office -> pickups in order -> deliveries in order -> office\n    route.clear();\n    route.push_back(0);\n    for (int i = 1; i <= M; ++i) {\n        route.push_back(i);\n    }\n    for (int i = M + 1; i <= 2 * M; ++i) {\n        route.push_back(i);\n    }\n    route.push_back(0);\n\n    // Optimize with 2-opt while respecting precedence\n    two_opt_with_precedence(route);\n\n    // Output\n    cout << M;\n    for (int id : selected_orders) {\n        cout << \" \" << id;\n    }\n    cout << \"\\n\";\n\n    cout << route.size();\n    for (int idx : route) {\n        cout << \" \" << points[idx].first << \" \" << points[idx].second;\n    }\n    cout << \"\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v;\n    int d;\n    int l;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 400;\n    int M = 1995;\n\n    vector<pair<int, int>> points(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> points[i].first >> points[i].second;\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        int dx = points[edges[i].u].first - points[edges[i].v].first;\n        int dy = points[edges[i].u].second - points[edges[i].v].second;\n        edges[i].d = round(sqrt(dx * dx + dy * dy));\n    }\n\n    dsu uf(N);\n    int components = N;\n\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].l;\n        if (uf.same(edges[i].u, edges[i].v)) {\n            cout << 0 << '\\n';\n            cout.flush();\n            continue;\n        }\n        // Always accept edges that connect new components\n        if (components > 1) {\n            uf.merge(edges[i].u, edges[i].v);\n            components--;\n            cout << 1 << '\\n';\n            cout.flush();\n        } else {\n            // After ensuring connectivity, be more selective\n            if (edges[i].l <= 2 * edges[i].d) {\n                cout << 1 << '\\n';\n                cout.flush();\n            } else {\n                cout << 0 << '\\n';\n                cout.flush();\n            }\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int GRID_SIZE = 30;\nconst int TURNS = 300;\nconst int MAX_PETS = 20;\nconst int MAX_HUMANS = 10;\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nint N, M;\nvector<Pet> pets;\nvector<Human> humans;\nvector<vector<bool>> blocked(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\nvector<vector<int>> pet_grid(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\nvector<vector<int>> human_grid(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n\nconst vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst string dir_chars = \"udlrUDLR\";\n\nvoid initialize() {\n    cin >> N;\n    pets.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n        pet_grid[pets[i].x][pets[i].y]++;\n    }\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].x >> humans[i].y;\n        human_grid[humans[i].x][humans[i].y]++;\n    }\n    blocked.assign(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\n    for (int i = 0; i <= GRID_SIZE + 1; ++i) {\n        blocked[i][0] = blocked[i][GRID_SIZE + 1] = true;\n        blocked[0][i] = blocked[GRID_SIZE + 1][i] = true;\n    }\n}\n\nbool is_valid(int x, int y) {\n    return x >= 1 && x <= GRID_SIZE && y >= 1 && y <= GRID_SIZE && !blocked[x][y];\n}\n\nbool can_block(int x, int y) {\n    if (x < 1 || x > GRID_SIZE || y < 1 || y > GRID_SIZE) return false;\n    if (blocked[x][y] || pet_grid[x][y] > 0 || human_grid[x][y] > 0) return false;\n    for (auto [dx, dy] : directions) {\n        int nx = x + dx, ny = y + dy;\n        if (nx >= 1 && nx <= GRID_SIZE && ny >= 1 && ny <= GRID_SIZE && pet_grid[nx][ny] > 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvector<pair<int, int>> get_adjacent_passable(int x, int y) {\n    vector<pair<int, int>> res;\n    for (auto [dx, dy] : directions) {\n        int nx = x + dx, ny = y + dy;\n        if (is_valid(nx, ny)) {\n            res.emplace_back(nx, ny);\n        }\n    }\n    return res;\n}\n\nvoid update_grids() {\n    pet_grid.assign(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n    human_grid.assign(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n    for (auto &pet : pets) {\n        pet_grid[pet.x][pet.y]++;\n    }\n    for (auto &human : humans) {\n        human_grid[human.x][human.y]++;\n    }\n}\n\nvoid move_pets() {\n    vector<string> moves(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> moves[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        auto &pet = pets[i];\n        int x = pet.x, y = pet.y;\n        for (char c : moves[i]) {\n            int dx = 0, dy = 0;\n            if (c == 'U') dx = -1;\n            else if (c == 'D') dx = 1;\n            else if (c == 'L') dy = -1;\n            else if (c == 'R') dy = 1;\n            int nx = x + dx, ny = y + dy;\n            if (is_valid(nx, ny)) {\n                x = nx;\n                y = ny;\n            }\n        }\n        pet.x = x;\n        pet.y = y;\n    }\n    update_grids();\n}\n\nvoid decide_human_actions() {\n    string actions;\n    for (int i = 0; i < M; ++i) {\n        auto &human = humans[i];\n        int x = human.x, y = human.y;\n        bool blocked_something = false;\n\n        // Try to block adjacent squares\n        for (auto [dx, dy] : directions) {\n            int nx = x + dx, ny = y + dy;\n            if (can_block(nx, ny)) {\n                blocked[nx][ny] = true;\n                if (dx == -1) actions += 'u';\n                else if (dx == 1) actions += 'd';\n                else if (dy == -1) actions += 'l';\n                else if (dy == 1) actions += 'r';\n                blocked_something = true;\n                break;\n            }\n        }\n\n        // If couldn't block, try to move\n        if (!blocked_something) {\n            vector<pair<int, int>> adj = get_adjacent_passable(x, y);\n            if (!adj.empty()) {\n                auto [nx, ny] = adj[rand() % adj.size()];\n                human.x = nx;\n                human.y = ny;\n                if (nx == x - 1) actions += 'U';\n                else if (nx == x + 1) actions += 'D';\n                else if (ny == y - 1) actions += 'L';\n                else if (ny == y + 1) actions += 'R';\n            } else {\n                actions += '.';\n            }\n        }\n    }\n\n    // Ensure the output has exactly M characters\n    if (actions.size() != M) {\n        actions = string(M, '.');\n    }\n\n    cout << actions << endl;\n    cout.flush();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    initialize();\n    for (int turn = 0; turn < TURNS; ++turn) {\n        decide_human_actions();\n        move_pets();\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int INF = 1e9;\nconst vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst string dir_chars = \"UDLR\";\n\nint si, sj, ti, tj;\ndouble p;\nvector<string> h, v;\n\nvector<vector<int>> bfs_shortest_path() {\n    vector<vector<int>> dist(N, vector<int>(N, INF));\n    queue<pair<int, int>> q;\n    dist[ti][tj] = 0;\n    q.emplace(ti, tj);\n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && dist[ni][nj] == INF) {\n                dist[ni][nj] = dist[i][j] + 1;\n                q.emplace(ni, nj);\n            }\n        }\n    }\n    return dist;\n}\n\nstring construct_path(const vector<vector<int>>& dist) {\n    string path;\n    int i = si, j = sj;\n    while (i != ti || j != tj) {\n        int best_d = -1;\n        int best_dist = INF;\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && dist[ni][nj] < best_dist) {\n                best_dist = dist[ni][nj];\n                best_d = d;\n            }\n        }\n        if (best_d == -1) break;\n        path += dir_chars[best_d];\n        i += dirs[best_d].first;\n        j += dirs[best_d].second;\n    }\n    return path;\n}\n\nstring make_robust_path(const string& path) {\n    string robust_path;\n    for (char c : path) {\n        robust_path += c;\n        if (p > 0.1) {\n            robust_path += c;\n            if (p > 0.25) {\n                robust_path += c;\n                if (p > 0.4) {\n                    robust_path += c;\n                }\n            }\n        }\n    }\n    if (robust_path.size() > 200) {\n        robust_path = path;\n        if (robust_path.size() > 200) {\n            robust_path = path.substr(0, 200);\n        }\n    }\n    return robust_path;\n}\n\nint main() {\n    cin >> si >> sj >> ti >> tj >> p;\n    h.resize(N);\n    v.resize(N - 1);\n    for (int i = 0; i < N; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N - 1; ++i) {\n        cin >> v[i];\n    }\n\n    auto dist = bfs_shortest_path();\n    string path = construct_path(dist);\n    string robust_path = make_robust_path(path);\n\n    cout << robust_path << endl;\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 30;\nconst int dx[4] = {0, -1, 0, 1};\nconst int dy[4] = {-1, 0, 1, 0};\nconst int to[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\n\nvector<string> initial_tiles;\nvector<vector<int>> tiles;\nvector<vector<int>> rotations;\nvector<vector<bool>> visited;\nvector<int> loop_lengths;\n\nint compute_loop_length(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    do {\n        int d2 = to[tiles[i][j]][d];\n        if (d2 == -1) return 0;\n        i += dx[d2];\n        j += dy[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (length > 1000) return 0; // Prevent infinite loops\n    } while (!(i == si && j == sj && d == sd));\n    return length;\n}\n\nvoid find_loops() {\n    visited.assign(N, vector<bool>(N, false));\n    loop_lengths.clear();\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (visited[i][j]) continue;\n            for (int d = 0; d < 4; ++d) {\n                int d2 = to[tiles[i][j]][d];\n                if (d2 == -1) continue;\n                int ni = i + dx[d2];\n                int nj = j + dy[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) % 4;\n                int length = compute_loop_length(i, j, d);\n                if (length > 0) {\n                    loop_lengths.push_back(length);\n                    for (int x = 0; x < N; ++x) {\n                        for (int y = 0; y < N; ++y) {\n                            if (visited[x][y]) continue;\n                            for (int dd = 0; dd < 4; ++dd) {\n                                if (compute_loop_length(x, y, dd) == length) {\n                                    visited[x][y] = true;\n                                }\n                            }\n                        }\n                    }\n                    goto next_tile;\n                }\n            }\n        }\n        next_tile:;\n    }\n    sort(loop_lengths.rbegin(), loop_lengths.rend());\n}\n\nlong long evaluate() {\n    find_loops();\n    if (loop_lengths.size() < 2) return 0;\n    return (long long)loop_lengths[0] * loop_lengths[1];\n}\n\nvoid apply_rotations() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int type = initial_tiles[i][j] - '0';\n            int rot = rotations[i][j];\n            if (type >= 0 && type <= 3) {\n                tiles[i][j] = (type + rot) % 4;\n            } else if (type >= 4 && type <= 5) {\n                tiles[i][j] = 4 + (rot % 2);\n            } else if (type >= 6 && type <= 7) {\n                tiles[i][j] = 6 + (rot % 2);\n            }\n        }\n    }\n}\n\nvoid solve() {\n    initial_tiles.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> initial_tiles[i];\n    }\n\n    rotations.assign(N, vector<int>(N, 0));\n    tiles.assign(N, vector<int>(N, 0));\n    apply_rotations();\n    long long best_score = evaluate();\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n    uniform_real_distribution<> prob(0.0, 1.0);\n\n    int iterations = 2000;\n    double temperature = 1000.0;\n    double cooling_rate = 0.99;\n\n    for (int iter = 0; iter < iterations; ++iter) {\n        int i = gen() % N;\n        int j = gen() % N;\n        int old_rot = rotations[i][j];\n        int new_rot = dis(gen);\n        rotations[i][j] = new_rot;\n        apply_rotations();\n        long long new_score = evaluate();\n        if (new_score > best_score || prob(gen) < exp((new_score - best_score) / temperature)) {\n            best_score = new_score;\n        } else {\n            rotations[i][j] = old_rot;\n            apply_rotations();\n        }\n        temperature *= cooling_rate;\n    }\n\n    string output;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            output += to_string(rotations[i][j]);\n        }\n    }\n    cout << output << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\nconst int rev[] = {2, 3, 0, 1};\n\nstruct State {\n    vector<vector<int>> board;\n    int empty_x, empty_y;\n    string moves;\n    int tree_size;\n    int steps;\n\n    State() : board(), empty_x(0), empty_y(0), moves(\"\"), tree_size(0), steps(0) {}\n    State(int N) : board(N, vector<int>(N)), empty_x(0), empty_y(0), moves(\"\"), tree_size(0), steps(0) {}\n\n    bool operator<(const State& other) const {\n        if (tree_size != other.tree_size) {\n            return tree_size > other.tree_size;\n        }\n        return steps < other.steps;\n    }\n};\n\nint calculate_tree_size(const vector<vector<int>>& board) {\n    int N = board.size();\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    int max_size = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0 || visited[i][j]) continue;\n\n            queue<pair<int, int>> q;\n            q.push({i, j});\n            visited[i][j] = true;\n            int size = 0;\n\n            while (!q.empty()) {\n                auto [x, y] = q.front();\n                q.pop();\n                size++;\n\n                int mask = board[x][y];\n                if (x > 0 && (mask & 2) && (board[x-1][y] & 8) && !visited[x-1][y]) {\n                    visited[x-1][y] = true;\n                    q.push({x-1, y});\n                }\n                if (x < N-1 && (mask & 8) && (board[x+1][y] & 2) && !visited[x+1][y]) {\n                    visited[x+1][y] = true;\n                    q.push({x+1, y});\n                }\n                if (y > 0 && (mask & 1) && (board[x][y-1] & 4) && !visited[x][y-1]) {\n                    visited[x][y-1] = true;\n                    q.push({x, y-1});\n                }\n                if (y < N-1 && (mask & 4) && (board[x][y+1] & 1) && !visited[x][y+1]) {\n                    visited[x][y+1] = true;\n                    q.push({x, y+1});\n                }\n            }\n\n            max_size = max(max_size, size);\n        }\n    }\n\n    return max_size;\n}\n\nvector<State> generate_next_states(const State& current, int N, int T) {\n    vector<State> next_states;\n\n    for (int d = 0; d < 4; ++d) {\n        int nx = current.empty_x + dx[d];\n        int ny = current.empty_y + dy[d];\n\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n\n        State next = current;\n        swap(next.board[current.empty_x][current.empty_y], next.board[nx][ny]);\n        next.empty_x = nx;\n        next.empty_y = ny;\n        next.moves += dir[d];\n        next.steps++;\n\n        if (next.steps > T) continue;\n\n        next.tree_size = calculate_tree_size(next.board);\n        next_states.push_back(next);\n    }\n\n    return next_states;\n}\n\nstring solve(int N, int T, const vector<string>& input) {\n    State initial(N);\n    int empty_count = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = input[i][j];\n            if (c == '0') {\n                initial.board[i][j] = 0;\n                initial.empty_x = i;\n                initial.empty_y = j;\n                empty_count++;\n            } else {\n                initial.board[i][j] = stoi(string(1, c), nullptr, 16);\n            }\n        }\n    }\n\n    if (empty_count != 1) {\n        return \"\";\n    }\n\n    initial.tree_size = calculate_tree_size(initial.board);\n\n    vector<State> current_level;\n    current_level.push_back(initial);\n\n    int beam_width = 50;\n    int max_tree_size = 0;\n    string best_moves;\n\n    for (int step = 0; step < T; ++step) {\n        vector<State> next_level;\n\n        for (const State& current : current_level) {\n            if (current.tree_size == N * N - 1) {\n                return current.moves;\n            }\n\n            if (current.tree_size > max_tree_size) {\n                max_tree_size = current.tree_size;\n                best_moves = current.moves;\n            }\n\n            vector<State> next_states = generate_next_states(current, N, T);\n            for (const State& next : next_states) {\n                next_level.push_back(next);\n            }\n        }\n\n        if (next_level.empty()) {\n            break;\n        }\n\n        sort(next_level.begin(), next_level.end());\n        if (static_cast<int>(next_level.size()) > beam_width) {\n            next_level.resize(beam_width);\n        }\n\n        current_level = next_level;\n    }\n\n    return best_moves;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    cin >> N >> T;\n    vector<string> input(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> input[i];\n    }\n\n    string result = solve(N, T, input);\n    cout << result << endl;\n\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_K = 100;\nconst int MAX_D = 10;\nconst int MAX_A = 100;\nconst int MAX_ITERATIONS = 200;\nconst int RADIUS = 10000;\nconst int RADIUS_SQ = RADIUS * RADIUS;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n    bool operator==(const Point& p) const {\n        return x == p.x && y == p.y;\n    }\n};\n\nstruct Line {\n    int px, py, qx, qy;\n    Line(int px, int py, int qx, int qy) : px(px), py(py), qx(qx), qy(qy) {}\n};\n\nint N, K;\nvector<int> a(MAX_D + 1);\nvector<Point> strawberries;\nvector<Line> cuts;\n\nint cross(const Point& o, const Point& a, const Point& b) {\n    return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n}\n\nint side(const Line& l, const Point& p) {\n    Point a(l.px, l.py), b(l.qx, l.qy);\n    long long c = (long long)(b.x - a.x) * (p.y - a.y) - (long long)(b.y - a.y) * (p.x - a.x);\n    if (c > 0) return 1;\n    if (c < 0) return -1;\n    return 0;\n}\n\nvector<vector<int>> regions;\n\nvoid init_regions() {\n    regions.clear();\n    regions.push_back(vector<int>());\n    for (int i = 0; i < N; ++i) {\n        regions[0].push_back(i);\n    }\n}\n\nvoid apply_cut(const Line& cut) {\n    vector<vector<int>> new_regions;\n    for (auto& region : regions) {\n        vector<int> left, right, on;\n        for (int idx : region) {\n            int s = side(cut, strawberries[idx]);\n            if (s == 1) left.push_back(idx);\n            else if (s == -1) right.push_back(idx);\n            else on.push_back(idx);\n        }\n        if (!left.empty()) new_regions.push_back(left);\n        if (!right.empty()) new_regions.push_back(right);\n    }\n    regions = new_regions;\n}\n\nint compute_score() {\n    vector<int> counts(MAX_D + 1, 0);\n    for (auto& region : regions) {\n        int cnt = region.size();\n        if (cnt <= MAX_D) counts[cnt]++;\n    }\n    int score = 0;\n    for (int d = 1; d <= MAX_D; ++d) {\n        score += min(a[d], counts[d]);\n    }\n    return score;\n}\n\nLine generate_line(int idx1, int idx2) {\n    Point p1 = strawberries[idx1];\n    Point p2 = strawberries[idx2];\n    return Line(p1.x, p1.y, p2.x, p2.y);\n}\n\nLine generate_best_line() {\n    Line best_line(0, 0, 0, 0);\n    int best_score = -1;\n    for (int i = 0; i < MAX_ITERATIONS; ++i) {\n        int idx1 = rand() % N;\n        int idx2 = rand() % N;\n        while (idx1 == idx2) idx2 = rand() % N;\n        Line candidate = generate_line(idx1, idx2);\n        vector<vector<int>> temp_regions = regions;\n        apply_cut(candidate);\n        int current_score = compute_score();\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_line = candidate;\n        }\n        regions = temp_regions;\n    }\n    return best_line;\n}\n\nvoid solve() {\n    cin >> N >> K;\n    for (int d = 1; d <= MAX_D; ++d) {\n        cin >> a[d];\n    }\n    strawberries.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> strawberries[i].x >> strawberries[i].y;\n    }\n\n    init_regions();\n    int current_score = compute_score();\n    for (int k = 0; k < K; ++k) {\n        Line best_line = generate_best_line();\n        apply_cut(best_line);\n        int new_score = compute_score();\n        if (new_score > current_score) {\n            current_score = new_score;\n            cuts.push_back(best_line);\n        } else {\n            regions = vector<vector<int>>(1, vector<int>(N));\n            for (int i = 0; i < N; ++i) {\n                regions[0][i] = i;\n            }\n            current_score = compute_score();\n        }\n    }\n\n    cout << cuts.size() << endl;\n    for (auto& cut : cuts) {\n        cout << cut.px << \" \" << cut.py << \" \" << cut.qx << \" \" << cut.qy << endl;\n    }\n}\n\nint main() {\n    srand(time(0));\n    solve();\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <cmath>\n#include <unordered_set>\n#include <chrono>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nint N, M;\nvector<Point> initial_dots;\nvector<vector<bool>> has_dot;\nvector<Rectangle> rectangles;\nint center;\nlong long total_weight = 0;\n\nlong long weight(int x, int y) {\n    long long dx = x - center;\n    long long dy = y - center;\n    return dx * dx + dy * dy + 1;\n}\n\nvoid precompute_weights() {\n    center = (N - 1) / 2;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y < N; ++y) {\n            total_weight += weight(x, y);\n        }\n    }\n}\n\nbool is_valid_point(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_perimeter(const Rectangle& rect) {\n    vector<Point> points = {rect.p1, rect.p2, rect.p3, rect.p4};\n    for (int i = 0; i < 4; ++i) {\n        Point a = points[i];\n        Point b = points[(i + 1) % 4];\n        if (a.x == b.x) {\n            int x = a.x;\n            int y1 = min(a.y, b.y);\n            int y2 = max(a.y, b.y);\n            for (int y = y1; y <= y2; ++y) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        } else if (a.y == b.y) {\n            int y = a.y;\n            int x1 = min(a.x, b.x);\n            int x2 = max(a.x, b.x);\n            for (int x = x1; x <= x2; ++x) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        } else {\n            int dx = b.x - a.x;\n            int dy = b.y - a.y;\n            if (abs(dx) != abs(dy)) {\n                return false;\n            }\n            int step = dx > 0 ? 1 : -1;\n            for (int x = a.x, y = a.y; x != b.x; x += step, y += step * dy / dx) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool check_overlap(const Rectangle& new_rect) {\n    for (const auto& rect : rectangles) {\n        vector<Point> new_points = {new_rect.p1, new_rect.p2, new_rect.p3, new_rect.p4};\n        vector<Point> old_points = {rect.p1, rect.p2, rect.p3, rect.p4};\n        for (int i = 0; i < 4; ++i) {\n            Point a1 = new_points[i];\n            Point b1 = new_points[(i + 1) % 4];\n            for (int j = 0; j < 4; ++j) {\n                Point a2 = old_points[j];\n                Point b2 = old_points[(j + 1) % 4];\n                if (a1 == a2 && b1 == b2) return true;\n                if (a1 == b2 && b1 == a2) return true;\n            }\n        }\n    }\n    return false;\n}\n\nvector<Rectangle> generate_candidates() {\n    vector<Rectangle> candidates;\n    for (int i = 0; i < initial_dots.size(); ++i) {\n        for (int j = i + 1; j < initial_dots.size(); ++j) {\n            Point p2 = initial_dots[i];\n            Point p3 = initial_dots[j];\n            // Axis-aligned rectangle\n            {\n                Point p1(p2.x, p3.y);\n                Point p4(p3.x, p2.y);\n                if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                    Rectangle rect(p1, p2, p3, p4);\n                    if (check_perimeter(rect) && !check_overlap(rect)) {\n                        candidates.push_back(rect);\n                    }\n                }\n            }\n            // 45-degree rotated rectangle\n            {\n                int dx = p3.x - p2.x;\n                int dy = p3.y - p2.y;\n                if (abs(dx) == abs(dy)) {\n                    Point p1(p2.x + dy, p2.y - dx);\n                    Point p4(p3.x + dy, p3.y - dx);\n                    if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                        Rectangle rect(p1, p2, p3, p4);\n                        if (check_perimeter(rect) && !check_overlap(rect)) {\n                            candidates.push_back(rect);\n                        }\n                    }\n                    p1 = Point(p2.x - dy, p2.y + dx);\n                    p4 = Point(p3.x - dy, p3.y + dx);\n                    if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                        Rectangle rect(p1, p2, p3, p4);\n                        if (check_perimeter(rect) && !check_overlap(rect)) {\n                            candidates.push_back(rect);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return candidates;\n}\n\nvoid solve() {\n    precompute_weights();\n    has_dot.assign(N, vector<bool>(N, false));\n    for (const auto& dot : initial_dots) {\n        has_dot[dot.x][dot.y] = true;\n    }\n\n    auto start_time = chrono::high_resolution_clock::now();\n    while (true) {\n        auto candidates = generate_candidates();\n        if (candidates.empty()) break;\n\n        Rectangle best_rect;\n        long long best_score = -1;\n        for (const auto& rect : candidates) {\n            long long current_score = weight(rect.p1.x, rect.p1.y);\n            if (current_score > best_score) {\n                best_score = current_score;\n                best_rect = rect;\n            }\n        }\n\n        if (best_score == -1) break;\n\n        rectangles.push_back(best_rect);\n        has_dot[best_rect.p1.x][best_rect.p1.y] = true;\n        initial_dots.push_back(best_rect.p1);\n\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 4500) break;\n    }\n\n    cout << rectangles.size() << endl;\n    for (const auto& rect : rectangles) {\n        cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n             << rect.p2.x << \" \" << rect.p2.y << \" \"\n             << rect.p3.x << \" \" << rect.p3.y << \" \"\n             << rect.p4.x << \" \" << rect.p4.y << endl;\n    }\n}\n\nint main() {\n    cin >> N >> M;\n    initial_dots.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> initial_dots[i].x >> initial_dots[i].y;\n    }\n    solve();\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <cstring>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n#include <numeric>\n\nusing namespace std;\n\nconst int N = 10;\nconst int TOTAL_CANDIES = 100;\nconst vector<char> DIRECTIONS = {'F', 'B', 'L', 'R'};\n\nstruct Grid {\n    int cells[N][N];\n    int empty_count;\n\n    Grid() {\n        memset(cells, 0, sizeof(cells));\n        empty_count = N * N;\n    }\n\n    void place_candy(int pos, int flavor) {\n        int idx = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] == 0) {\n                    if (++idx == pos) {\n                        cells[i][j] = flavor;\n                        empty_count--;\n                        return;\n                    }\n                }\n            }\n        }\n    }\n\n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; ++j) {\n                int write_pos = N - 1;\n                for (int i = N - 1; i >= 0; --i) {\n                    if (cells[i][j] != 0) {\n                        cells[write_pos--][j] = cells[i][j];\n                    }\n                }\n                for (int i = write_pos; i >= 0; --i) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; ++j) {\n                int write_pos = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (cells[i][j] != 0) {\n                        cells[write_pos++][j] = cells[i][j];\n                    }\n                }\n                for (int i = write_pos; i < N; ++i) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; ++i) {\n                int write_pos = 0;\n                for (int j = 0; j < N; ++j) {\n                    if (cells[i][j] != 0) {\n                        cells[i][write_pos++] = cells[i][j];\n                    }\n                }\n                for (int j = write_pos; j < N; ++j) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'R') {\n            for (int i = 0; i < N; ++i) {\n                int write_pos = N - 1;\n                for (int j = N - 1; j >= 0; --j) {\n                    if (cells[i][j] != 0) {\n                        cells[i][write_pos--] = cells[i][j];\n                    }\n                }\n                for (int j = write_pos; j >= 0; --j) {\n                    cells[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    vector<int> get_connected_components() {\n        vector<int> component_sizes;\n        bool visited[N][N] = {false};\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0 && !visited[i][j]) {\n                    int flavor = cells[i][j];\n                    int size = 0;\n                    queue<pair<int, int>> q;\n                    q.push({i, j});\n                    visited[i][j] = true;\n\n                    while (!q.empty()) {\n                        auto [x, y] = q.front();\n                        q.pop();\n                        size++;\n\n                        for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                            int nx = x + dx;\n                            int ny = y + dy;\n                            if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && cells[nx][ny] == flavor) {\n                                visited[nx][ny] = true;\n                                q.push({nx, ny});\n                            }\n                        }\n                    }\n                    component_sizes.push_back(size);\n                }\n            }\n        }\n        return component_sizes;\n    }\n\n    double evaluate() {\n        auto components = get_connected_components();\n        double sum_sq = 0;\n        for (int size : components) {\n            sum_sq += size * size;\n        }\n        int counts[4] = {0};\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    counts[cells[i][j]]++;\n                }\n            }\n        }\n        double denom = 0;\n        for (int i = 1; i <= 3; ++i) {\n            denom += counts[i] * counts[i];\n        }\n        if (denom == 0) return 0;\n        return sum_sq / denom;\n    }\n\n    int count_adjacent_pairs() {\n        int pairs = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                        int ni = i + dx;\n                        int nj = j + dy;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N && cells[ni][nj] == cells[i][j]) {\n                            pairs++;\n                        }\n                    }\n                }\n            }\n        }\n        return pairs / 2; // Each pair is counted twice\n    }\n\n    int count_potential_connections() {\n        int potential = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                        int ni = i + dx;\n                        int nj = j + dy;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N && cells[ni][nj] == 0) {\n                            potential++;\n                        }\n                    }\n                }\n            }\n        }\n        return potential;\n    }\n\n    double calculate_flavor_distribution() {\n        int flavor_counts[4] = {0};\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    flavor_counts[cells[i][j]]++;\n                }\n            }\n        }\n        double variance = 0;\n        double mean = (flavor_counts[1] + flavor_counts[2] + flavor_counts[3]) / 3.0;\n        for (int i = 1; i <= 3; ++i) {\n            variance += (flavor_counts[i] - mean) * (flavor_counts[i] - mean);\n        }\n        return variance;\n    }\n\n    double calculate_cluster_quality() {\n        auto components = get_connected_components();\n        if (components.empty()) return 0;\n        double max_size = *max_element(components.begin(), components.end());\n        double avg_size = accumulate(components.begin(), components.end(), 0.0) / components.size();\n        return max_size / avg_size;\n    }\n\n    double calculate_edge_density() {\n        int edge_pairs = 0;\n        int total_pairs = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                        int ni = i + dx;\n                        int nj = j + dy;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                            total_pairs++;\n                            if (cells[ni][nj] == cells[i][j]) {\n                                edge_pairs++;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        return total_pairs == 0 ? 0 : static_cast<double>(edge_pairs) / total_pairs;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<int> flavors(TOTAL_CANDIES);\n    for (int i = 0; i < TOTAL_CANDIES; ++i) {\n        cin >> flavors[i];\n    }\n\n    Grid grid;\n    for (int t = 0; t < TOTAL_CANDIES; ++t) {\n        int pos;\n        cin >> pos;\n        grid.place_candy(pos, flavors[t]);\n\n        if (t == TOTAL_CANDIES - 1) {\n            break;\n        }\n\n        double best_score = -1;\n        char best_dir = 'F';\n        for (char dir : DIRECTIONS) {\n            Grid temp_grid = grid;\n            temp_grid.tilt(dir);\n            double eval_score = temp_grid.evaluate();\n            int pairs = temp_grid.count_adjacent_pairs();\n            int potential = temp_grid.count_potential_connections();\n            double distribution = temp_grid.calculate_flavor_distribution();\n            double cluster_quality = temp_grid.calculate_cluster_quality();\n            double edge_density = temp_grid.calculate_edge_density();\n            double score = eval_score * 0.3 + pairs * 0.2 + potential * 0.1 + cluster_quality * 0.2 + edge_density * 0.1 - distribution * 0.1;\n            if (score > best_score) {\n                best_score = score;\n                best_dir = dir;\n            }\n        }\n        grid.tilt(best_dir);\n        cout << best_dir << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Graph {\n    int N;\n    vector<vector<bool>> adj;\n    vector<int> degree;\n    int edge_count;\n    vector<int> degree_seq;\n\n    Graph(int n) : N(n), adj(n, vector<bool>(n, false)), degree(n, 0), edge_count(0) {}\n\n    void add_edge(int u, int v) {\n        if (!adj[u][v]) {\n            adj[u][v] = adj[v][u] = true;\n            degree[u]++;\n            degree[v]++;\n            edge_count++;\n        }\n    }\n\n    void compute_degree_seq() {\n        degree_seq = degree;\n        sort(degree_seq.begin(), degree_seq.end(), greater<int>());\n    }\n\n    string to_string() const {\n        string s;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                s += adj[i][j] ? '1' : '0';\n            }\n        }\n        return s;\n    }\n};\n\nvector<Graph> generate_graphs(int M, int N) {\n    vector<Graph> graphs;\n    for (int k = 0; k < M; ++k) {\n        Graph g(N);\n        // Construct a graph with unique degree sequence\n        int edges = min(k * 2, N * (N - 1) / 2);\n        for (int i = 0; i < N && edges > 0; ++i) {\n            for (int j = i + 1; j < N && edges > 0; ++j) {\n                g.add_edge(i, j);\n                edges--;\n            }\n        }\n        g.compute_degree_seq();\n        graphs.push_back(g);\n    }\n    return graphs;\n}\n\nvector<int> compute_degree_sequence(const string& s, int N) {\n    vector<int> degree(N, 0);\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (s[idx++] == '1') {\n                degree[i]++;\n                degree[j]++;\n            }\n        }\n    }\n    sort(degree.begin(), degree.end(), greater<int>());\n    return degree;\n}\n\nint count_edges(const string& s) {\n    return count(s.begin(), s.end(), '1');\n}\n\ndouble compute_distance(int edges_H, const vector<int>& degree_seq_H,\n                        int edges_G, const vector<int>& degree_seq_G) {\n    double edge_diff = abs(edges_H - edges_G);\n    double degree_diff = 0.0;\n    for (int i = 0; i < degree_seq_H.size(); ++i) {\n        degree_diff += abs(degree_seq_H[i] - degree_seq_G[i]);\n    }\n    return 0.5 * edge_diff + 0.5 * degree_diff;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    cin >> M >> eps;\n\n    // Adaptive N selection\n    int N = min(100, max(4, M + 5));\n    if (eps > 0.1) N = min(100, N + 5);\n    if (eps > 0.2) N = min(100, N + 5);\n    if (eps > 0.3) N = min(100, N + 5);\n\n    vector<Graph> graphs = generate_graphs(M, N);\n\n    // Output the graphs\n    cout << N << '\\n';\n    for (const auto& g : graphs) {\n        cout << g.to_string() << '\\n';\n    }\n    cout.flush();\n\n    // Precompute invariants for all G_k\n    vector<int> edge_counts;\n    vector<vector<int>> degree_seqs;\n    for (const auto& g : graphs) {\n        edge_counts.push_back(g.edge_count);\n        degree_seqs.push_back(g.degree_seq);\n    }\n\n    // Process queries\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // Compute invariants for H\n        int edges_H = count_edges(H);\n        vector<int> degree_seq_H = compute_degree_sequence(H, N);\n\n        // Find the closest G_k\n        double min_dist = 1e18;\n        int best_k = 0;\n        for (int k = 0; k < M; ++k) {\n            double dist = compute_distance(edges_H, degree_seq_H,\n                                          edge_counts[k], degree_seqs[k]);\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_k = k;\n            }\n        }\n\n        cout << best_k << '\\n';\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int INF = 1e9;\nconst double INIT_TEMP = 1e4;\nconst double FINAL_TEMP = 1e-4;\nconst double COOLING_RATE = 0.999;\nconst int MAX_ITER = 100000;\n\nstruct Edge {\n    int u, v, w, idx;\n};\n\nstruct Point {\n    int x, y;\n};\n\nint N, M, D, K;\nvector<Edge> edges;\nvector<Point> points;\nvector<vector<int>> adj;\nvector<vector<int>> dist;\nvector<int> schedule;\n\nvoid read_input() {\n    cin >> N >> M >> D >> K;\n    edges.resize(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        edges[i].idx = i;\n    }\n    points.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> points[i].x >> points[i].y;\n    }\n}\n\nvoid compute_apsp() {\n    dist.assign(N, vector<int>(N, INF));\n    for (int i = 0; i < N; ++i) {\n        dist[i][i] = 0;\n    }\n    for (const auto& e : edges) {\n        dist[e.u][e.v] = min(dist[e.u][e.v], e.w);\n        dist[e.v][e.u] = min(dist[e.v][e.u], e.w);\n    }\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 (dist[i][k] < INF && dist[k][j] < INF) {\n                    dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n                }\n            }\n        }\n    }\n}\n\nvector<vector<int>> compute_daily_dist(int day) {\n    vector<vector<int>> daily_dist = dist;\n    for (int i = 0; i < M; ++i) {\n        if (schedule[i] == day) {\n            const auto& e = edges[i];\n            daily_dist[e.u][e.v] = INF;\n            daily_dist[e.v][e.u] = INF;\n        }\n    }\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 (daily_dist[i][k] < INF && daily_dist[k][j] < INF) {\n                    daily_dist[i][j] = min(daily_dist[i][j], daily_dist[i][k] + daily_dist[k][j]);\n                }\n            }\n        }\n    }\n    return daily_dist;\n}\n\ndouble compute_frustration() {\n    double total_frustration = 0.0;\n    for (int day = 1; day <= D; ++day) {\n        auto daily_dist = compute_daily_dist(day);\n        double sum_diff = 0.0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                int original = dist[i][j];\n                int current = daily_dist[i][j];\n                if (current >= INF) current = INF;\n                sum_diff += (current - original);\n            }\n        }\n        double f_k = sum_diff / (N * (N - 1) / 2);\n        total_frustration += f_k;\n    }\n    return total_frustration / D;\n}\n\nvoid initial_schedule() {\n    schedule.assign(M, 0);\n    vector<int> day_counts(D, 0);\n    for (int i = 0; i < M; ++i) {\n        int day = rand() % D + 1;\n        while (day_counts[day - 1] >= K) {\n            day = rand() % D + 1;\n        }\n        schedule[i] = day;\n        day_counts[day - 1]++;\n    }\n}\n\nvoid simulated_annealing() {\n    initial_schedule();\n    double current_frustration = compute_frustration();\n    double temp = INIT_TEMP;\n    int iter = 0;\n    while (temp > FINAL_TEMP && iter < MAX_ITER) {\n        int edge_idx = rand() % M;\n        int old_day = schedule[edge_idx];\n        int new_day = rand() % D + 1;\n        if (count(schedule.begin(), schedule.end(), new_day) >= K) {\n            continue;\n        }\n        schedule[edge_idx] = new_day;\n        double new_frustration = compute_frustration();\n        double delta = new_frustration - current_frustration;\n        if (delta < 0 || exp(-delta / temp) > (double)rand() / RAND_MAX) {\n            current_frustration = new_frustration;\n        } else {\n            schedule[edge_idx] = old_day;\n        }\n        temp *= COOLING_RATE;\n        iter++;\n    }\n}\n\nint main() {\n    srand(time(0));\n    read_input();\n    compute_apsp();\n    simulated_annealing();\n    for (int i = 0; i < M; ++i) {\n        cout << schedule[i] << (i == M - 1 ? \"\\n\" : \" \");\n    }\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <unordered_set>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n    Point(int x = 0, int y = 0, int z = 0) : x(x), y(y), z(z) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y && z == other.z;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        if (y != other.y) return y < other.y;\n        return z < other.z;\n    }\n};\n\nstruct Block {\n    vector<Point> cubes;\n    int id;\n    Block(int id = 0) : id(id) {}\n    void add_cube(const Point& p) {\n        cubes.push_back(p);\n    }\n    bool is_connected() const {\n        if (cubes.empty()) return true;\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        queue<Point> q;\n        q.push(cubes[0]);\n        visited[cubes[0].x][cubes[0].y][cubes[0].z] = true;\n        int count = 1;\n        while (!q.empty()) {\n            Point p = q.front();\n            q.pop();\n            for (const auto& cube : cubes) {\n                if (!visited[cube.x][cube.y][cube.z]) {\n                    int dx = abs(p.x - cube.x);\n                    int dy = abs(p.y - cube.y);\n                    int dz = abs(p.z - cube.z);\n                    if ((dx == 1 && dy == 0 && dz == 0) ||\n                        (dx == 0 && dy == 1 && dz == 0) ||\n                        (dx == 0 && dy == 0 && dz == 1)) {\n                        visited[cube.x][cube.y][cube.z] = true;\n                        q.push(cube);\n                        count++;\n                    }\n                }\n            }\n        }\n        return count == cubes.size();\n    }\n};\n\nint D;\nvector<vector<string>> f(2, vector<string>(D));\nvector<vector<string>> r(2, vector<string>(D));\nvector<vector<vector<int>>> b(2, vector<vector<int>>(D, vector<int>(D, 0)));\nvector<Block> blocks;\nint block_id = 1;\n\nbool can_place_block(const Block& block, int obj_idx, const vector<vector<vector<int>>>& grid) {\n    for (const auto& cube : block.cubes) {\n        if (cube.x < 0 || cube.x >= D || cube.y < 0 || cube.y >= D || cube.z < 0 || cube.z >= D) {\n            return false;\n        }\n        if (grid[cube.x][cube.y][cube.z] != 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid place_block(const Block& block, int obj_idx, int id) {\n    for (const auto& cube : block.cubes) {\n        b[obj_idx][cube.x][cube.y][cube.z] = id;\n    }\n}\n\nvoid remove_block(const Block& block, int obj_idx) {\n    for (const auto& cube : block.cubes) {\n        b[obj_idx][cube.x][cube.y][cube.z] = 0;\n    }\n}\n\nbool satisfies_silhouette(int obj_idx) {\n    for (int z = 0; z < D; ++z) {\n        for (int x = 0; x < D; ++x) {\n            bool found = false;\n            for (int y = 0; y < D; ++y) {\n                if (b[obj_idx][x][y][z] != 0) {\n                    found = true;\n                    break;\n                }\n            }\n            if (f[obj_idx][z][x] == '1' && !found) {\n                return false;\n            }\n        }\n    }\n    for (int z = 0; z < D; ++z) {\n        for (int y = 0; y < D; ++y) {\n            bool found = false;\n            for (int x = 0; x < D; ++x) {\n                if (b[obj_idx][x][y][z] != 0) {\n                    found = true;\n                    break;\n                }\n            }\n            if (r[obj_idx][z][y] == '1' && !found) {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nvoid generate_initial_blocks() {\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[obj_idx][z][x] == '1' && r[obj_idx][z][y] == '1') {\n                        bool found = false;\n                        for (const auto& block : blocks) {\n                            for (const auto& cube : block.cubes) {\n                                if (cube.x == x && cube.y == y && cube.z == z) {\n                                    found = true;\n                                    break;\n                                }\n                            }\n                            if (found) break;\n                        }\n                        if (!found) {\n                            Block block(block_id++);\n                            block.add_cube(Point(x, y, z));\n                            blocks.push_back(block);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid merge_blocks() {\n    bool merged;\n    do {\n        merged = false;\n        for (size_t i = 0; i < blocks.size(); ++i) {\n            for (size_t j = i + 1; j < blocks.size(); ++j) {\n                Block new_block(block_id);\n                for (const auto& cube : blocks[i].cubes) {\n                    new_block.add_cube(cube);\n                }\n                for (const auto& cube : blocks[j].cubes) {\n                    new_block.add_cube(cube);\n                }\n                if (new_block.is_connected()) {\n                    vector<Block> new_blocks;\n                    for (size_t k = 0; k < blocks.size(); ++k) {\n                        if (k != i && k != j) {\n                            new_blocks.push_back(blocks[k]);\n                        }\n                    }\n                    new_blocks.push_back(new_block);\n                    blocks = new_blocks;\n                    block_id++;\n                    merged = true;\n                    break;\n                }\n            }\n            if (merged) break;\n        }\n    } while (merged);\n}\n\nvoid assign_blocks_to_objects() {\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        vector<vector<vector<int>>> grid(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        for (const auto& block : blocks) {\n            bool used = false;\n            for (const auto& cube : block.cubes) {\n                if (f[obj_idx][cube.z][cube.x] == '1' && r[obj_idx][cube.z][cube.y] == '1') {\n                    used = true;\n                    break;\n                }\n            }\n            if (used) {\n                place_block(block, obj_idx, block.id);\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> D;\n    f.resize(2, vector<string>(D));\n    r.resize(2, vector<string>(D));\n    b.resize(2, vector<vector<int>>(D, vector<int>(D, 0)));\n\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> f[i][k];\n        }\n        for (int k = 0; k < D; ++k) {\n            cin >> r[i][k];\n        }\n    }\n\n    generate_initial_blocks();\n    merge_blocks();\n    assign_blocks_to_objects();\n\n    set<int> used_blocks;\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (b[obj_idx][x][y][z] != 0) {\n                        used_blocks.insert(b[obj_idx][x][y][z]);\n                    }\n                }\n            }\n        }\n    }\n\n    vector<int> block_ids;\n    for (const auto& block : blocks) {\n        block_ids.push_back(block.id);\n    }\n    sort(block_ids.begin(), block_ids.end());\n    block_ids.erase(unique(block_ids.begin(), block_ids.end()), block_ids.end());\n\n    cout << block_ids.size() << endl;\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    cout << b[obj_idx][x][y][z] << \" \";\n                }\n            }\n        }\n        cout << endl;\n    }\n\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v, w, idx;\n    double dist;\n};\n\nstruct Resident {\n    int x, y;\n};\n\nstruct Station {\n    int x, y;\n    int P;\n    vector<int> residents;\n};\n\ndouble euclidean(int x1, int y1, int x2, int y2) {\n    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<Station> stations(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> stations[i].x >> stations[i].y;\n        stations[i].P = 0;\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        edges[i].idx = i;\n        edges[i].dist = euclidean(stations[edges[i].u].x, stations[edges[i].u].y,\n                                  stations[edges[i].v].x, stations[edges[i].v].y);\n    }\n\n    vector<Resident> residents(K);\n    for (int i = 0; i < K; ++i) {\n        cin >> residents[i].x >> residents[i].y;\n    }\n\n    // Step 1: Assign residents to nearest station\n    for (int i = 0; i < K; ++i) {\n        double min_dist = 1e9;\n        int best_station = -1;\n        for (int j = 0; j < N; ++j) {\n            double dist = euclidean(residents[i].x, residents[i].y, stations[j].x, stations[j].y);\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_station = j;\n            }\n        }\n        stations[best_station].residents.push_back(i);\n    }\n\n    // Step 2: Compute MST using Kruskal's algorithm\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.w < b.w;\n    });\n\n    dsu uf(N);\n    vector<bool> edge_used(M, false);\n    vector<vector<pair<int, int>>> mst(N); // {neighbor, edge_idx}\n\n    for (const Edge& e : edges) {\n        if (!uf.same(e.u, e.v)) {\n            uf.merge(e.u, e.v);\n            edge_used[e.idx] = true;\n            mst[e.u].emplace_back(e.v, e.idx);\n            mst[e.v].emplace_back(e.u, e.idx);\n        }\n    }\n\n    // Step 3: Set initial P_i to cover all residents\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].residents.empty()) {\n            stations[i].P = 0;\n            continue;\n        }\n        double max_dist = 0;\n        for (int r : stations[i].residents) {\n            double dist = euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y);\n            if (dist > max_dist) {\n                max_dist = dist;\n            }\n        }\n        stations[i].P = min(5000, (int)ceil(max_dist));\n    }\n\n    // Step 4: Optimize P_i and edge selection\n    vector<bool> covered(K, false);\n    auto check_coverage = [&]() {\n        fill(covered.begin(), covered.end(), false);\n        for (int i = 0; i < N; ++i) {\n            for (int r : stations[i].residents) {\n                if (euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y) <= stations[i].P) {\n                    covered[r] = true;\n                }\n            }\n        }\n        return all_of(covered.begin(), covered.end(), [](bool c) { return c; });\n    };\n\n    if (!check_coverage()) {\n        // Fallback: ensure all residents are covered\n        for (int i = 0; i < N; ++i) {\n            double max_dist = 0;\n            for (int r : stations[i].residents) {\n                double dist = euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y);\n                if (dist > max_dist) {\n                    max_dist = dist;\n                }\n            }\n            stations[i].P = min(5000, (int)ceil(max_dist));\n        }\n    }\n\n    // Try to reduce P_i\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].P == 0) continue;\n        int original_P = stations[i].P;\n        for (int p = original_P - 1; p >= 0; --p) {\n            int old_P = stations[i].P;\n            stations[i].P = p;\n            if (!check_coverage()) {\n                stations[i].P = old_P;\n                break;\n            }\n        }\n    }\n\n    // Step 5: Prune unnecessary edges\n    vector<bool> necessary_edge(M, false);\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].P > 0) {\n            // BFS to mark necessary edges\n            vector<bool> visited(N, false);\n            queue<int> q;\n            q.push(i);\n            visited[i] = true;\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (auto [v, idx] : mst[u]) {\n                    if (!visited[v] && edge_used[idx]) {\n                        necessary_edge[idx] = true;\n                        visited[v] = true;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n\n    // Ensure station 1 is connected\n    vector<bool> visited(N, false);\n    queue<int> q;\n    q.push(0);\n    visited[0] = true;\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        for (auto [v, idx] : mst[u]) {\n            if (!visited[v] && edge_used[idx]) {\n                necessary_edge[idx] = true;\n                visited[v] = true;\n                q.push(v);\n            }\n        }\n    }\n\n    for (int i = 0; i < M; ++i) {\n        if (!necessary_edge[i]) {\n            edge_used[i] = false;\n        }\n    }\n\n    // Step 6: Output the solution\n    for (int i = 0; i < N; ++i) {\n        cout << stations[i].P << (i == N - 1 ? \"\\n\" : \" \");\n    }\n    for (int i = 0; i < M; ++i) {\n        cout << edge_used[i] << (i == M - 1 ? \"\\n\" : \" \");\n    }\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nconst int N = 30;\nconst int TOTAL_BALLS = N * (N + 1) / 2;\nconst int MAX_OPERATIONS = 10000;\n\nstruct Position {\n    int x, y;\n    Position(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Position& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Position& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nvector<Position> directions = {\n    {-1, -1}, {-1, 0}, {0, -1}, {0, 1}, {1, 0}, {1, 1}\n};\n\nvector<vector<int>> pyramid(N, vector<int>(N, -1));\nvector<pair<Position, Position>> operations;\n\nbool is_valid(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y <= x;\n}\n\nvector<Position> get_adjacent_positions(int x, int y) {\n    vector<Position> adj;\n    for (auto& dir : directions) {\n        int nx = x + dir.x;\n        int ny = y + dir.y;\n        if (is_valid(nx, ny)) {\n            adj.emplace_back(nx, ny);\n        }\n    }\n    return adj;\n}\n\nvoid swap_balls(Position a, Position b) {\n    if (!is_valid(a.x, a.y) || !is_valid(b.x, b.y)) return;\n    swap(pyramid[a.x][a.y], pyramid[b.x][b.y]);\n    operations.emplace_back(a, b);\n}\n\nint count_violations() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int current = pyramid[x][y];\n            int child1 = pyramid[x + 1][y];\n            int child2 = pyramid[x + 1][y + 1];\n            if (current > child1) violations++;\n            if (current > child2) violations++;\n        }\n    }\n    return violations;\n}\n\nPosition find_ball(int num) {\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] == num) {\n                return Position(x, y);\n            }\n        }\n    }\n    return Position(-1, -1);\n}\n\nvector<Position> find_path(Position start, Position target) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    vector<vector<Position>> parent(N, vector<Position>(N, Position(-1, -1)));\n    queue<Position> q;\n    q.push(start);\n    visited[start.x][start.y] = true;\n\n    while (!q.empty()) {\n        Position current = q.front();\n        q.pop();\n        if (current.x == target.x && current.y == target.y) {\n            vector<Position> path;\n            while (!(current.x == start.x && current.y == start.y)) {\n                path.push_back(current);\n                current = parent[current.x][current.y];\n            }\n            path.push_back(start);\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        for (auto& dir : directions) {\n            int nx = current.x + dir.x;\n            int ny = current.y + dir.y;\n            if (is_valid(nx, ny) && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                parent[nx][ny] = current;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return {};\n}\n\nvoid move_ball(Position start, Position target) {\n    vector<Position> path = find_path(start, target);\n    if (path.empty()) return;\n    for (size_t i = 0; i < path.size() - 1; ++i) {\n        swap_balls(path[i], path[i + 1]);\n        if (operations.size() >= MAX_OPERATIONS) {\n            return;\n        }\n    }\n}\n\nvoid solve() {\n    // Read input\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            cin >> pyramid[x][y];\n        }\n    }\n\n    // Target: smallest numbers at the top\n    vector<int> sorted_balls(TOTAL_BALLS);\n    for (int i = 0; i < TOTAL_BALLS; ++i) {\n        sorted_balls[i] = i;\n    }\n\n    // Initial placement with optimized path\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int target_num = sorted_balls[x * (x + 1) / 2 + y];\n            Position current_pos = find_ball(target_num);\n            if (current_pos.x != x || current_pos.y != y) {\n                move_ball(current_pos, Position(x, y));\n                if (operations.size() >= MAX_OPERATIONS) {\n                    cout << operations.size() << endl;\n                    for (auto& op : operations) {\n                        cout << op.first.x << \" \" << op.first.y << \" \"\n                             << op.second.x << \" \" << op.second.y << endl;\n                    }\n                    return;\n                }\n            }\n        }\n    }\n\n    // Fix violations with optimized swaps\n    int violations = count_violations();\n    while (violations > 0 && operations.size() < MAX_OPERATIONS) {\n        bool improved = false;\n        for (int x = N - 2; x >= 0; --x) {\n            for (int y = 0; y <= x; ++y) {\n                int current = pyramid[x][y];\n                int child1 = pyramid[x + 1][y];\n                int child2 = pyramid[x + 1][y + 1];\n                if (current > child1 || current > child2) {\n                    vector<Position> adj = get_adjacent_positions(x, y);\n                    int min_val = current;\n                    Position best_swap = Position(-1, -1);\n                    for (auto& pos : adj) {\n                        if (pyramid[pos.x][pos.y] < min_val) {\n                            min_val = pyramid[pos.x][pos.y];\n                            best_swap = pos;\n                        }\n                    }\n                    if (best_swap.x != -1) {\n                        // Check if swapping reduces violations\n                        int old_violations = 0;\n                        int new_violations = 0;\n                        // Count violations before swap\n                        if (x > 0) {\n                            int parent1 = pyramid[x - 1][y - 1];\n                            int parent2 = pyramid[x - 1][y];\n                            if (parent1 > current) old_violations++;\n                            if (parent2 > current) old_violations++;\n                        }\n                        if (current > child1) old_violations++;\n                        if (current > child2) old_violations++;\n                        // Count violations after swap\n                        int temp = pyramid[best_swap.x][best_swap.y];\n                        if (x > 0) {\n                            int parent1 = pyramid[x - 1][y - 1];\n                            int parent2 = pyramid[x - 1][y];\n                            if (parent1 > temp) new_violations++;\n                            if (parent2 > temp) new_violations++;\n                        }\n                        if (temp > child1) new_violations++;\n                        if (temp > child2) new_violations++;\n                        if (new_violations < old_violations) {\n                            swap_balls(Position(x, y), best_swap);\n                            improved = true;\n                            if (operations.size() >= MAX_OPERATIONS) {\n                                cout << operations.size() << endl;\n                                for (auto& op : operations) {\n                                    cout << op.first.x << \" \" << op.first.y << \" \"\n                                         << op.second.x << \" \" << op.second.y << endl;\n                                }\n                                return;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        if (!improved) break;\n        violations = count_violations();\n    }\n\n    cout << operations.size() << endl;\n    for (auto& op : operations) {\n        cout << op.first.x << \" \" << op.first.y << \" \"\n             << op.second.x << \" \" << op.second.y << endl;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <set>\n#include <climits>\n#include <cstring>\n\nusing namespace std;\n\nconst int GRID_SIZE = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = (GRID_SIZE - 1) / 2;\n\nstruct Cell {\n    int i, j;\n    bool operator<(const Cell& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nint grid[GRID_SIZE][GRID_SIZE];\nbool is_obstacle[GRID_SIZE][GRID_SIZE];\nbool is_container[GRID_SIZE][GRID_SIZE];\nint container_num[GRID_SIZE][GRID_SIZE];\nvector<Cell> containers;\n\nint di[] = {-1, 1, 0, 0};\nint dj[] = {0, 0, -1, 1};\n\nbool is_valid(int i, int j) {\n    return i >= 0 && i < GRID_SIZE && j >= 0 && j < GRID_SIZE;\n}\n\nvector<Cell> bfs_reachable() {\n    vector<Cell> reachable;\n    bool visited[GRID_SIZE][GRID_SIZE];\n    memset(visited, false, sizeof(visited));\n    queue<Cell> q;\n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n\n    while (!q.empty()) {\n        Cell current = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int ni = current.i + di[k];\n            int nj = current.j + dj[k];\n            if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj] && !is_container[ni][nj]) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n            }\n        }\n    }\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (visited[i][j] && !is_obstacle[i][j] && !is_container[i][j] && !(i == ENTRANCE_I && j == ENTRANCE_J)) {\n                reachable.push_back({i, j});\n            }\n        }\n    }\n    return reachable;\n}\n\nvector<Cell> bfs_removable() {\n    vector<Cell> removable;\n    bool visited[GRID_SIZE][GRID_SIZE];\n    memset(visited, false, sizeof(visited));\n    queue<Cell> q;\n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n\n    while (!q.empty()) {\n        Cell current = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int ni = current.i + di[k];\n            int nj = current.j + dj[k];\n            if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj]) {\n                if (is_container[ni][nj]) {\n                    removable.push_back({ni, nj});\n                } else {\n                    visited[ni][nj] = true;\n                    q.push({ni, nj});\n                }\n            }\n        }\n    }\n    return removable;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int D, N;\n    cin >> D >> N;\n    memset(is_obstacle, false, sizeof(is_obstacle));\n    memset(is_container, false, sizeof(is_container));\n    memset(container_num, -1, sizeof(container_num));\n\n    for (int i = 0; i < N; ++i) {\n        int ri, rj;\n        cin >> ri >> rj;\n        is_obstacle[ri][rj] = true;\n    }\n\n    int total_containers = GRID_SIZE * GRID_SIZE - 1 - N;\n    for (int d = 0; d < total_containers; ++d) {\n        int t;\n        cin >> t;\n        vector<Cell> reachable = bfs_reachable();\n        if (reachable.empty()) {\n            cerr << \"No reachable cells left!\" << endl;\n            return 1;\n        }\n\n        // Place the container in the cell with the highest BFS distance from entrance\n        bool visited[GRID_SIZE][GRID_SIZE];\n        memset(visited, false, sizeof(visited));\n        queue<Cell> q;\n        q.push({ENTRANCE_I, ENTRANCE_J});\n        visited[ENTRANCE_I][ENTRANCE_J] = true;\n        Cell farthest = {ENTRANCE_I, ENTRANCE_J};\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            farthest = current;\n            for (int k = 0; k < 4; ++k) {\n                int ni = current.i + di[k];\n                int nj = current.j + dj[k];\n                if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj] && !is_container[ni][nj]) {\n                    visited[ni][nj] = true;\n                    q.push({ni, nj});\n                }\n            }\n        }\n\n        // Place the container at the farthest cell\n        is_container[farthest.i][farthest.j] = true;\n        container_num[farthest.i][farthest.j] = t;\n        containers.push_back({farthest.i, farthest.j});\n        cout << farthest.i << \" \" << farthest.j << endl;\n        cout.flush();\n    }\n\n    // Determine the removal order\n    vector<Cell> removal_order;\n    while (removal_order.size() < total_containers) {\n        vector<Cell> removable = bfs_removable();\n        if (removable.empty()) {\n            cerr << \"No removable containers left!\" << endl;\n            return 1;\n        }\n\n        // Find the container with the smallest number among removable\n        int min_num = INT_MAX;\n        Cell to_remove;\n        for (const Cell& cell : removable) {\n            if (container_num[cell.i][cell.j] < min_num) {\n                min_num = container_num[cell.i][cell.j];\n                to_remove = cell;\n            }\n        }\n\n        removal_order.push_back(to_remove);\n        is_container[to_remove.i][to_remove.j] = false;\n    }\n\n    for (const Cell& cell : removal_order) {\n        cout << cell.i << \" \" << cell.j << endl;\n    }\n    cout.flush();\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int n = 50;\nconst int m = 100;\nconst int dx[] = {1, 0, -1, 0};\nconst int dy[] = {0, 1, 0, -1};\n\nstruct Cell {\n    int x, y;\n    Cell(int x = 0, int y = 0) : x(x), y(y) {}\n};\n\nvector<vector<int>> input_grid(n, vector<int>(n));\nvector<set<int>> adjacency(m + 1);\nvector<vector<Cell>> ward_cells(m + 1);\nvector<vector<bool>> is_boundary(n, vector<bool>(n, false));\n\nvoid read_input() {\n    cin >> n >> m;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> input_grid[i][j];\n            ward_cells[input_grid[i][j]].emplace_back(i, j);\n        }\n    }\n}\n\nvoid compute_adjacency() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            int c = input_grid[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = input_grid[ni][nj];\n                    if (nc != c) {\n                        adjacency[c].insert(nc);\n                        adjacency[nc].insert(c);\n                    }\n                } else {\n                    adjacency[c].insert(0);\n                    adjacency[0].insert(c);\n                }\n            }\n        }\n    }\n}\n\nvoid compute_boundary() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni < 0 || ni >= n || nj < 0 || nj >= n) {\n                    is_boundary[i][j] = true;\n                    break;\n                }\n            }\n        }\n    }\n}\n\nvector<vector<int>> create_initial_solution() {\n    vector<vector<int>> grid(n, vector<int>(n, 0));\n    vector<set<int>> required_adj(m + 1);\n    for (int c = 1; c <= m; ++c) {\n        required_adj[c] = adjacency[c];\n    }\n\n    // Place each ward as a single cell\n    vector<Cell> positions;\n    for (int c = 1; c <= m; ++c) {\n        if (!ward_cells[c].empty()) {\n            Cell pos = ward_cells[c][0];\n            grid[pos.x][pos.y] = c;\n            positions.emplace_back(pos.x, pos.y);\n        }\n    }\n\n    // Expand wards to satisfy adjacency\n    for (int c = 1; c <= m; ++c) {\n        if (ward_cells[c].empty()) continue;\n        queue<Cell> q;\n        vector<vector<bool>> visited(n, vector<bool>(n, false));\n        for (const auto& cell : ward_cells[c]) {\n            if (grid[cell.x][cell.y] == c) {\n                q.push(cell);\n                visited[cell.x][cell.y] = true;\n            }\n        }\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int ni = current.x + dx[d];\n                int nj = current.y + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj]) {\n                    int nc = grid[ni][nj];\n                    if (nc == 0) {\n                        if (required_adj[c].count(0) || !required_adj[c].empty()) {\n                            grid[ni][nj] = c;\n                            visited[ni][nj] = true;\n                            q.push(Cell(ni, nj));\n                        }\n                    } else if (nc != c) {\n                        if (required_adj[c].count(nc)) {\n                            required_adj[c].erase(nc);\n                            required_adj[nc].erase(c);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Ensure all adjacencies are satisfied\n    for (int c = 1; c <= m; ++c) {\n        if (!required_adj[c].empty()) {\n            for (int nc : required_adj[c]) {\n                if (nc == 0) continue;\n                // Find a cell of c and nc to connect\n                for (const auto& cell : ward_cells[c]) {\n                    if (grid[cell.x][cell.y] != c) continue;\n                    for (int d = 0; d < 4; ++d) {\n                        int ni = cell.x + dx[d];\n                        int nj = cell.y + dy[d];\n                        if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] == 0) {\n                            grid[ni][nj] = c;\n                            break;\n                        }\n                    }\n                    break;\n                }\n            }\n        }\n    }\n\n    return grid;\n}\n\nvoid optimize_solution(vector<vector<int>>& grid) {\n    // Simple optimization: try to replace color-0 cells with adjacent colors if possible\n    bool improved;\n    do {\n        improved = false;\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] != 0) continue;\n                set<int> adjacent_colors;\n                for (int d = 0; d < 4; ++d) {\n                    int ni = i + dx[d];\n                    int nj = j + dy[d];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                        adjacent_colors.insert(grid[ni][nj]);\n                    }\n                }\n                if (adjacent_colors.size() == 1) {\n                    int c = *adjacent_colors.begin();\n                    if (c != 0) {\n                        grid[i][j] = c;\n                        improved = true;\n                    }\n                }\n            }\n        }\n    } while (improved);\n}\n\nbool check_connectivity(const vector<vector<int>>& grid) {\n    for (int c = 1; c <= m; ++c) {\n        vector<vector<bool>> visited(n, vector<bool>(n, false));\n        queue<Cell> q;\n        bool found = false;\n        for (int i = 0; i < n && !found; ++i) {\n            for (int j = 0; j < n && !found; ++j) {\n                if (grid[i][j] == c) {\n                    q.push(Cell(i, j));\n                    visited[i][j] = true;\n                    found = true;\n                }\n            }\n        }\n        if (!found) continue;\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int ni = current.x + dx[d];\n                int nj = current.y + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj] && grid[ni][nj] == c) {\n                    visited[ni][nj] = true;\n                    q.push(Cell(ni, nj));\n                }\n            }\n        }\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] == c && !visited[i][j]) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool check_adjacency(const vector<vector<int>>& grid) {\n    vector<set<int>> current_adj(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            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = grid[ni][nj];\n                    if (nc != c) {\n                        current_adj[c].insert(nc);\n                        current_adj[nc].insert(c);\n                    }\n                } else {\n                    current_adj[c].insert(0);\n                    current_adj[0].insert(c);\n                }\n            }\n        }\n    }\n    for (int c = 0; c <= m; ++c) {\n        if (current_adj[c] != adjacency[c]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    read_input();\n    compute_adjacency();\n    compute_boundary();\n\n    vector<vector<int>> grid = create_initial_solution();\n    optimize_solution(grid);\n\n    // Verify the solution\n    if (!check_connectivity(grid) || !check_adjacency(grid)) {\n        // Fallback: output the original grid (though it may not be optimal)\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << input_grid[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n    } else {\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << grid[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <queue>\n#include <set>\n#include <map>\n#include <chrono>\n#include <cassert>\n\nusing namespace std;\nusing namespace std::chrono;\n\nstruct Item {\n    int id;\n    double weight;\n    bool operator<(const Item& other) const {\n        return weight > other.weight; // For max-heap\n    }\n};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nvector<int> solve(int N, int D, int Q) {\n    vector<double> weights(N, 1.0); // Initial guess\n    vector<vector<double>> constraints;\n    vector<int> comparison_results;\n\n    auto query = [&](const vector<int>& L, const vector<int>& R) {\n        cout << L.size() << \" \" << R.size();\n        for (int l : L) cout << \" \" << l;\n        for (int r : R) cout << \" \" << r;\n        cout << endl;\n        cout.flush();\n\n        string result;\n        cin >> result;\n        if (result == \"<\") return -1;\n        else if (result == \">\") return 1;\n        else return 0;\n    };\n\n    // Initial pairwise comparisons to establish order\n    for (int i = 0; i < N && Q > 0; ++i) {\n        for (int j = i + 1; j < N && Q > 0; ++j) {\n            vector<int> L = {i}, R = {j};\n            int res = query(L, R);\n            comparison_results.push_back(res);\n            Q--;\n            if (res == -1) {\n                weights[i] = 0.9 * weights[i];\n                weights[j] = 1.1 * weights[j];\n            } else if (res == 1) {\n                weights[i] = 1.1 * weights[i];\n                weights[j] = 0.9 * weights[j];\n            }\n        }\n    }\n\n    // Refine weights using more queries\n    while (Q > 0) {\n        vector<int> L, R;\n        uniform_int_distribution<int> dist(0, N - 1);\n        int size = min(5, N / 2);\n        set<int> used;\n        while (L.size() < size) {\n            int item = dist(rng);\n            if (used.count(item)) continue;\n            used.insert(item);\n            L.push_back(item);\n        }\n        used.clear();\n        while (R.size() < size) {\n            int item = dist(rng);\n            if (used.count(item) || find(L.begin(), L.end(), item) != L.end()) continue;\n            used.insert(item);\n            R.push_back(item);\n        }\n        if (L.empty() || R.empty()) continue;\n        int res = query(L, R);\n        Q--;\n        double sum_L = accumulate(L.begin(), L.end(), 0.0, [&](double s, int i) { return s + weights[i]; });\n        double sum_R = accumulate(R.begin(), R.end(), 0.0, [&](double s, int i) { return s + weights[i]; });\n        if (res == -1) {\n            for (int l : L) weights[l] *= 0.99;\n            for (int r : R) weights[r] *= 1.01;\n        } else if (res == 1) {\n            for (int l : L) weights[l] *= 1.01;\n            for (int r : R) weights[r] *= 0.99;\n        }\n    }\n\n    // Partition into D sets\n    vector<int> assignment(N, 0);\n    vector<double> set_sums(D, 0.0);\n    vector<Item> items;\n    for (int i = 0; i < N; ++i) {\n        items.push_back({i, weights[i]});\n    }\n    sort(items.begin(), items.end(), [](const Item& a, const Item& b) {\n        return a.weight > b.weight;\n    });\n\n    for (const auto& item : items) {\n        int best_set = 0;\n        double min_sum = set_sums[0];\n        for (int d = 1; d < D; ++d) {\n            if (set_sums[d] < min_sum) {\n                min_sum = set_sums[d];\n                best_set = d;\n            }\n        }\n        assignment[item.id] = best_set;\n        set_sums[best_set] += item.weight;\n    }\n\n    return assignment;\n}\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n\n    auto assignment = solve(N, D, Q);\n\n    for (int i = 0; i < N; ++i) {\n        cout << assignment[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n    cout.flush();\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Box {\n    int value;\n    int stack;\n    int pos; // position from bottom (0-based)\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n = 200, m = 10;\n    cin >> n >> m;\n\n    vector<vector<int>> stacks(m);\n    unordered_map<int, Box> box_info;\n    vector<int> next_box_pos(m, 0); // next position to check in each stack (from top)\n\n    for (int i = 0; i < m; ++i) {\n        stacks[i].resize(n / m);\n        for (int j = 0; j < n / m; ++j) {\n            cin >> stacks[i][j];\n            box_info[stacks[i][j]] = {stacks[i][j], i, j};\n        }\n    }\n\n    vector<pair<int, int>> operations;\n    int next_box = 1;\n    int total_energy = 0;\n    int max_operations = 5000;\n\n    auto get_top_box = [&](int stack_idx) {\n        if (stacks[stack_idx].empty()) return -1;\n        return stacks[stack_idx].back();\n    };\n\n    auto move_boxes = [&](int v, int dest_stack) {\n        int src_stack = box_info[v].stack;\n        int pos = box_info[v].pos;\n        int num_boxes = stacks[src_stack].size() - pos;\n        if (num_boxes <= 0) return false; // should not happen\n\n        // Remove boxes from src_stack\n        vector<int> moved_boxes;\n        for (int i = pos; i < stacks[src_stack].size(); ++i) {\n            moved_boxes.push_back(stacks[src_stack][i]);\n        }\n        stacks[src_stack].resize(pos);\n\n        // Add to dest_stack\n        for (int box : moved_boxes) {\n            stacks[dest_stack].push_back(box);\n            box_info[box].stack = dest_stack;\n            box_info[box].pos = stacks[dest_stack].size() - 1;\n        }\n\n        operations.emplace_back(v, dest_stack);\n        total_energy += num_boxes + 1;\n        return true;\n    };\n\n    auto carry_out = [&](int v) {\n        int stack = box_info[v].stack;\n        stacks[stack].pop_back();\n        operations.emplace_back(v, 0);\n    };\n\n    auto find_dest_stack = [&](int v) {\n        int src_stack = box_info[v].stack;\n        vector<int> candidates;\n        for (int i = 0; i < m; ++i) {\n            if (i == src_stack) continue;\n            if (stacks[i].empty()) {\n                candidates.push_back(i);\n                continue;\n            }\n            int top_box = get_top_box(i);\n            if (top_box > v) {\n                candidates.push_back(i);\n            }\n        }\n\n        if (candidates.empty()) {\n            for (int i = 0; i < m; ++i) {\n                if (i != src_stack) {\n                    candidates.push_back(i);\n                }\n            }\n        }\n\n        // Choose the stack with the smallest size\n        int best_stack = candidates[0];\n        for (int stack : candidates) {\n            if (stacks[stack].size() < stacks[best_stack].size()) {\n                best_stack = stack;\n            }\n        }\n        return best_stack;\n    };\n\n    while (next_box <= n && operations.size() < max_operations) {\n        int stack = box_info[next_box].stack;\n        int pos = box_info[next_box].pos;\n        if (pos == stacks[stack].size() - 1) {\n            carry_out(next_box);\n            next_box++;\n        } else {\n            int dest_stack = find_dest_stack(next_box);\n            move_boxes(next_box, dest_stack);\n        }\n    }\n\n    // Output operations\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <climits>\n#include <functional>\n\nusing namespace std;\n\nconst int MAX_N = 40;\nconst int MAX_MOVES = 100000;\nconst vector<pair<int, int>> DIJ = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\nconst string DIR = \"RDLU\";\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<bool>> visited;\nstring route;\n\nvoid simple_dfs(int i, int j) {\n    visited[i][j] = true;\n    for (int dir = 0; dir < 4; ++dir) {\n        auto [di, dj] = DIJ[dir];\n        int ni = i + di;\n        int nj = j + dj;\n        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n        if (visited[ni][nj]) continue;\n        if (di == 0) {\n            if (dj == 1 && v[i][min(j, nj)] == '1') continue;\n            if (dj == -1 && v[i][min(j, nj)] == '1') continue;\n        } else {\n            if (di == 1 && h[min(i, ni)][j] == '1') continue;\n            if (di == -1 && h[min(i, ni)][j] == '1') continue;\n        }\n        route += DIR[dir];\n        simple_dfs(ni, nj);\n        route += DIR[(dir + 2) % 4];\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; ++i) {\n        cin >> h[i];\n    }\n    v.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> v[i];\n    }\n    d.resize(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    visited.assign(N, vector<bool>(N, false));\n    simple_dfs(0, 0);\n\n    // Ensure route length is within limits\n    if (route.size() > MAX_MOVES) {\n        route = route.substr(0, MAX_MOVES);\n    }\n\n    cout << route << endl;\n\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 15;\nconst int M = 200;\nconst int MAX_OPERATIONS = 5000;\n\nvector<string> t(M);\nvector<vector<pair<int, int>>> char_positions(26);\nvector<unordered_set<int>> char_to_words(26);\nvector<bool> covered(M, false);\n\nint manhattan(int i1, int j1, int i2, int j2) {\n    return abs(i1 - i2) + abs(j1 - j2);\n}\n\nvoid preprocess(const vector<string>& grid) {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = grid[i][j];\n            char_positions[c - 'A'].emplace_back(i, j);\n        }\n    }\n\n    for (int k = 0; k < M; ++k) {\n        for (char c : t[k]) {\n            char_to_words[c - 'A'].insert(k);\n        }\n    }\n}\n\nvector<pair<int, int>> greedy_construction(const vector<string>& grid, int si, int sj) {\n    vector<pair<int, int>> path = {{si, sj}};\n    string s;\n    int current_i = si, current_j = sj;\n    int operations = 0;\n\n    while (operations < MAX_OPERATIONS) {\n        int best_i = -1, best_j = -1;\n        char best_char = '\\0';\n        int best_score = -1;\n        int best_cost = INT_MAX;\n\n        for (char c = 'A'; c <= 'Z'; ++c) {\n            for (auto [i, j] : char_positions[c - 'A']) {\n                int cost = manhattan(current_i, current_j, i, j) + 1;\n                int score = 0;\n\n                for (int k : char_to_words[c - 'A']) {\n                    if (!covered[k]) {\n                        bool can_cover = true;\n                        if (s.size() >= t[k].size()) {\n                            for (int l = 0; l < t[k].size(); ++l) {\n                                if (s[s.size() - t[k].size() + l] != t[k][l]) {\n                                    can_cover = false;\n                                    break;\n                                }\n                            }\n                        } else {\n                            can_cover = false;\n                        }\n                        if (can_cover) {\n                            score++;\n                        }\n                    }\n                }\n\n                if (score > best_score || (score == best_score && cost < best_cost)) {\n                    best_score = score;\n                    best_cost = cost;\n                    best_i = i;\n                    best_j = j;\n                    best_char = c;\n                }\n            }\n        }\n\n        if (best_score == 0) {\n            // No immediate benefit, choose closest character\n            for (char c = 'A'; c <= 'Z'; ++c) {\n                for (auto [i, j] : char_positions[c - 'A']) {\n                    int cost = manhattan(current_i, current_j, i, j) + 1;\n                    if (cost < best_cost) {\n                        best_cost = cost;\n                        best_i = i;\n                        best_j = j;\n                        best_char = c;\n                    }\n                }\n            }\n        }\n\n        s += best_char;\n        current_i = best_i;\n        current_j = best_j;\n        path.emplace_back(best_i, best_j);\n        operations++;\n\n        // Update covered words\n        for (int k : char_to_words[best_char - 'A']) {\n            if (!covered[k]) {\n                bool can_cover = true;\n                if (s.size() >= t[k].size()) {\n                    for (int l = 0; l < t[k].size(); ++l) {\n                        if (s[s.size() - t[k].size() + l] != t[k][l]) {\n                            can_cover = false;\n                            break;\n                        }\n                    }\n                } else {\n                    can_cover = false;\n                }\n                if (can_cover) {\n                    covered[k] = true;\n                }\n            }\n        }\n\n        // Check if all words are covered\n        bool all_covered = true;\n        for (bool cov : covered) {\n            if (!cov) {\n                all_covered = false;\n                break;\n            }\n        }\n        if (all_covered) {\n            break;\n        }\n    }\n\n    return path;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, M_in;\n    cin >> N_in >> M_in;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> grid(N_in);\n    for (int i = 0; i < N_in; ++i) {\n        cin >> grid[i];\n    }\n    for (int k = 0; k < M_in; ++k) {\n        cin >> t[k];\n    }\n\n    preprocess(grid);\n    auto path = greedy_construction(grid, si, sj);\n\n    // Ensure we don't exceed MAX_OPERATIONS\n    if (path.size() > MAX_OPERATIONS) {\n        path.resize(MAX_OPERATIONS);\n    }\n\n    for (auto [i, j] : path) {\n        cout << i << \" \" << j << \"\\n\";\n    }\n\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int i, j;\n    Point(int i = 0, int j = 0) : i(i), j(j) {}\n};\n\nstruct OilField {\n    int d;\n    vector<Point> cells;\n};\n\nclass Solver {\nprivate:\n    int N, M;\n    double eps;\n    vector<OilField> fields;\n    vector<vector<int>> grid;\n    vector<vector<bool>> drilled;\n    vector<Point> oil_squares;\n\n    void read_input() {\n        cin >> N >> M >> eps;\n        fields.resize(M);\n\n        for (int k = 0; k < M; ++k) {\n            cin >> fields[k].d;\n            fields[k].cells.resize(fields[k].d);\n            for (int i = 0; i < fields[k].d; ++i) {\n                cin >> fields[k].cells[i].i >> fields[k].cells[i].j;\n            }\n        }\n    }\n\n    void drill_all() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << \"q 1 \" << i << \" \" << j << endl;\n                cout.flush();\n\n                int v;\n                cin >> v;\n                if (v > 0) {\n                    oil_squares.emplace_back(i, j);\n                }\n            }\n        }\n    }\n\npublic:\n    Solver() {\n        read_input();\n        grid.assign(N, vector<int>(N, 0));\n        drilled.assign(N, vector<bool>(N, false));\n    }\n\n    void solve() {\n        // Simple solution: drill all squares\n        drill_all();\n\n        // Output the answer\n        cout << \"a \" << oil_squares.size();\n        for (const auto& p : oil_squares) {\n            cout << \" \" << p.i << \" \" << p.j;\n        }\n        cout << endl;\n        cout.flush();\n\n        int correct;\n        cin >> correct;\n        if (correct != 1) {\n            // If wrong, try again with all squares (shouldn't happen)\n            cout << \"a \" << N*N;\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    cout << \" \" << i << \" \" << j;\n                }\n            }\n            cout << endl;\n            cout.flush();\n        }\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    Solver solver;\n    solver.solve();\n\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int W = 1000;\nconst int MAX_D = 50;\nconst int MAX_N = 50;\n\nstruct Rect {\n    int i1, j1, i2, j2;\n    Rect(int i1 = 0, int j1 = 0, int i2 = 0, int j2 = 0) : i1(i1), j1(j1), i2(i2), j2(j2) {}\n    int area() const { return (i2 - i1) * (j2 - j1); }\n};\n\nvector<vector<Rect>> solve(int D, int N, const vector<vector<int>>& a) {\n    vector<vector<Rect>> res(D, vector<Rect>(N));\n\n    // For each day, we'll partition the grid into N rectangles\n    for (int d = 0; d < D; ++d) {\n        vector<int> areas = a[d];\n        sort(areas.begin(), areas.end(), greater<int>());\n        vector<Rect> rects;\n        int remaining_height = W;\n        int remaining_width = W;\n        int current_i = 0;\n        int current_j = 0;\n\n        for (int k = 0; k < N; ++k) {\n            int target = areas[k];\n            if (k == N - 1) {\n                // Last rectangle takes the remaining space\n                rects.emplace_back(current_i, current_j, W, W);\n                break;\n            }\n            // Decide whether to split vertically or horizontally\n            int split_height = (target + remaining_width - 1) / remaining_width;\n            if (split_height > remaining_height) {\n                split_height = remaining_height;\n            }\n            int split_width = (target + split_height - 1) / split_height;\n            if (split_width > remaining_width) {\n                split_width = remaining_width;\n            }\n\n            // Try to split vertically first\n            int best_split = -1;\n            int best_diff = INT_MAX;\n            for (int split = 1; split <= remaining_width; ++split) {\n                int h = (target + split - 1) / split;\n                if (h > remaining_height) continue;\n                int diff = abs(target - split * h);\n                if (diff < best_diff) {\n                    best_diff = diff;\n                    best_split = split;\n                }\n            }\n            // Try to split horizontally\n            for (int split = 1; split <= remaining_height; ++split) {\n                int w = (target + split - 1) / split;\n                if (w > remaining_width) continue;\n                int diff = abs(target - split * w);\n                if (diff < best_diff) {\n                    best_diff = diff;\n                    best_split = -split; // negative indicates horizontal split\n                }\n            }\n\n            if (best_split > 0) {\n                // Vertical split\n                int split = best_split;\n                int h = (target + split - 1) / split;\n                rects.emplace_back(current_i, current_j, current_i + h, current_j + split);\n                current_j += split;\n                remaining_width -= split;\n            } else {\n                // Horizontal split\n                int split = -best_split;\n                int w = (target + split - 1) / split;\n                rects.emplace_back(current_i, current_j, current_i + split, current_j + w);\n                current_i += split;\n                remaining_height -= split;\n            }\n        }\n        res[d] = rects;\n    }\n\n    // Now, try to minimize partition changes between days\n    for (int d = 1; d < D; ++d) {\n        // For simplicity, we'll just use the same partitioning as the previous day\n        // and adjust the rectangles to meet the new area requirements\n        // This is a placeholder; a better approach would involve more sophisticated matching\n        res[d] = res[d-1];\n        for (int k = 0; k < N; ++k) {\n            int target = a[d][k];\n            Rect& r = res[d][k];\n            int current_area = r.area();\n            if (current_area < target) {\n                // Need to expand the rectangle\n                // Try to expand to the right or down\n                if (r.j2 < W) {\n                    int new_width = (target + (r.i2 - r.i1) - 1) / (r.i2 - r.i1);\n                    if (new_width > W - r.j1) new_width = W - r.j1;\n                    r.j2 = r.j1 + new_width;\n                } else if (r.i2 < W) {\n                    int new_height = (target + (r.j2 - r.j1) - 1) / (r.j2 - r.j1);\n                    if (new_height > W - r.i1) new_height = W - r.i1;\n                    r.i2 = r.i1 + new_height;\n                }\n            } else if (current_area > target) {\n                // Need to shrink the rectangle\n                // Try to shrink from the right or bottom\n                int shrink_area = current_area - target;\n                if (r.j2 > r.j1) {\n                    int shrink_width = min(shrink_area / (r.i2 - r.i1), r.j2 - r.j1 - 1);\n                    r.j2 -= shrink_width;\n                } else if (r.i2 > r.i1) {\n                    int shrink_height = min(shrink_area / (r.j2 - r.j1), r.i2 - r.i1 - 1);\n                    r.i2 -= shrink_height;\n                }\n            }\n        }\n    }\n\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int W_in, D, N;\n    cin >> W_in >> D >> 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    }\n\n    auto res = solve(D, N, a);\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            const auto& r = res[d][k];\n            cout << r.i1 << \" \" << r.j1 << \" \" << r.i2 << \" \" << r.j2 << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K_MAX = 81;\nconst int STAMP_SIZE = 3;\n\nint a[N][N];\nint s[M][STAMP_SIZE][STAMP_SIZE];\nint b[N][N];\nint d[N][N]; // deficit: MOD - 1 - (b[i][j] % MOD)\n\nstruct Operation {\n    int m, p, q;\n};\n\nvector<Operation> operations;\n\nvoid apply_stamp(int m, int p, int q) {\n    for (int i = 0; i < STAMP_SIZE; ++i) {\n        for (int j = 0; j < STAMP_SIZE; ++j) {\n            b[p + i][q + j] += s[m][i][j];\n        }\n    }\n}\n\nvoid update_deficits() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            d[i][j] = (MOD - 1 - (b[i][j] % MOD)) % MOD;\n        }\n    }\n}\n\nint compute_contribution(int m, int p, int q) {\n    int contribution = 0;\n    for (int i = 0; i < STAMP_SIZE; ++i) {\n        for (int j = 0; j < STAMP_SIZE; ++j) {\n            int ni = p + i;\n            int nj = q + j;\n            if (ni >= N || nj >= N) continue;\n            int add = min(s[m][i][j], d[ni][nj]);\n            contribution += add;\n        }\n    }\n    return contribution;\n}\n\nvoid greedy_solve() {\n    // Initialize b and d\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            b[i][j] = a[i][j];\n        }\n    }\n    update_deficits();\n\n    operations.clear();\n    for (int k = 0; k < K_MAX; ++k) {\n        int best_contribution = -1;\n        int best_m = -1, best_p = -1, best_q = -1;\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - STAMP_SIZE; ++p) {\n                for (int q = 0; q <= N - STAMP_SIZE; ++q) {\n                    int contribution = compute_contribution(m, p, q);\n                    if (contribution > best_contribution) {\n                        best_contribution = contribution;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_contribution <= 0) break;\n\n        operations.push_back({best_m, best_p, best_q});\n        apply_stamp(best_m, best_p, best_q);\n        update_deficits();\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, M_in, K_in;\n    cin >> N_in >> M_in >> K_in;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> a[i][j];\n        }\n    }\n    for (int m = 0; m < M; ++m) {\n        for (int i = 0; i < STAMP_SIZE; ++i) {\n            for (int j = 0; j < STAMP_SIZE; ++j) {\n                cin >> s[m][i][j];\n            }\n        }\n    }\n\n    greedy_solve();\n\n    cout << operations.size() << '\\n';\n    for (const auto& op : operations) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURNS = 10000;\n\nint main() {\n    vector<vector<int>> A(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n        }\n    }\n\n    // For simplicity, we'll output a basic sequence of operations\n    // that moves containers to their target gates without conflicts\n    // This is a placeholder for a more sophisticated solution\n\n    // Each crane will move right to the dispatch gate and then left to pick up\n    // the next container, repeating this pattern\n    vector<string> operations(N, string(MAX_TURNS, '.'));\n\n    for (int i = 0; i < N; ++i) {\n        for (int t = 0; t < MAX_TURNS; ++t) {\n            if (t % 2 == 0) {\n                operations[i][t] = 'R'; // Move right\n            } else {\n                operations[i][t] = 'L'; // Move left\n            }\n        }\n    }\n\n    // Output operations\n    for (int i = 0; i < N; ++i) {\n        cout << operations[i] << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 20;\n    vector<vector<int>> grid(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> grid[i][j];\n        }\n    }\n\n    // Snake traversal order\n    vector<pair<int, int>> order;\n    for (int i = 0; i < N; ++i) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; ++j) {\n                order.emplace_back(i, j);\n            }\n        } else {\n            for (int j = N - 1; j >= 0; --j) {\n                order.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Current position and load\n    int x = 0, y = 0;\n    int load = 0;\n    vector<string> ops;\n\n    // Function to move to (nx, ny)\n    auto move_to = [&](int nx, int ny) {\n        while (x != nx || y != ny) {\n            if (x < nx) { ops.push_back(\"D\"); x++; }\n            else if (x > nx) { ops.push_back(\"U\"); x--; }\n            else if (y < ny) { ops.push_back(\"R\"); y++; }\n            else if (y > ny) { ops.push_back(\"L\"); y--; }\n        }\n    };\n\n    // Traverse in order\n    for (auto [i, j] : order) {\n        move_to(i, j);\n\n        // Load if positive\n        if (grid[i][j] > 0) {\n            int d = min(grid[i][j], 1000000);\n            ops.push_back(\"+\" + to_string(d));\n            grid[i][j] -= d;\n            load += d;\n        }\n        // Unload if negative and truck has load\n        else if (grid[i][j] < 0 && load > 0) {\n            int d = min(-grid[i][j], load);\n            ops.push_back(\"-\" + to_string(d));\n            grid[i][j] += d;\n            load -= d;\n        }\n    }\n\n    // Final unload if needed (should not happen, but safe)\n    if (load > 0) {\n        move_to(0, 0);\n        ops.push_back(\"-\" + to_string(load));\n    }\n\n    // Output all operations\n    for (const string& op : ops) {\n        cout << op << '\\n';\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <queue>\n\nusing namespace std;\n\nstruct Seed {\n    vector<int> eval;\n    int value;\n    int id;\n};\n\nbool compareSeeds(const Seed &a, const Seed &b) {\n    return a.value > b.value;\n}\n\ndouble calculateExpectedValue(const Seed &a, const Seed &b) {\n    double expected = 0.0;\n    for (int i = 0; i < a.eval.size(); ++i) {\n        expected += (a.eval[i] + b.eval[i]) / 2.0;\n    }\n    return expected;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 6, M = 15, T = 10;\n    int seed_count = 2 * N * (N - 1);\n    vector<Seed> seeds(seed_count);\n\n    for (int i = 0; i < seed_count; ++i) {\n        seeds[i].eval.resize(M);\n        seeds[i].id = i;\n        for (int j = 0; j < M; ++j) {\n            cin >> seeds[i].eval[j];\n        }\n        seeds[i].value = accumulate(seeds[i].eval.begin(), seeds[i].eval.end(), 0);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        // Sort seeds by value in descending order\n        sort(seeds.begin(), seeds.end(), compareSeeds);\n\n        // Select top N*N seeds\n        vector<Seed> selected_seeds(seeds.begin(), seeds.begin() + N * N);\n\n        // Create a grid to place the selected seeds\n        vector<vector<int>> grid(N, vector<int>(N, -1));\n\n        // Place the highest value seed in the center\n        grid[N/2][N/2] = selected_seeds[0].id;\n\n        // Use a priority queue to place seeds based on adjacency benefits\n        auto compare = [&](const pair<int, int>& a, const pair<int, int>& b) {\n            int a_neighbors = 0;\n            int b_neighbors = 0;\n            int dx[] = {0, 1, 0, -1};\n            int dy[] = {1, 0, -1, 0};\n            for (int i = 0; i < 4; ++i) {\n                int nx = a.first + dx[i];\n                int ny = a.second + dy[i];\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] != -1) {\n                    a_neighbors++;\n                }\n                nx = b.first + dx[i];\n                ny = b.second + dy[i];\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] != -1) {\n                    b_neighbors++;\n                }\n            }\n            return a_neighbors < b_neighbors;\n        };\n        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(compare)> pq(compare);\n\n        // Add all possible positions to the priority queue\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == -1) {\n                    pq.push({i, j});\n                }\n            }\n        }\n\n        // Place remaining seeds\n        for (int i = 1; i < N * N; ++i) {\n            while (!pq.empty()) {\n                auto pos = pq.top();\n                pq.pop();\n                if (grid[pos.first][pos.second] == -1) {\n                    grid[pos.first][pos.second] = selected_seeds[i].id;\n                    break;\n                }\n            }\n        }\n\n        // Output the grid\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << grid[i][j];\n                if (j < N - 1) {\n                    cout << \" \";\n                }\n            }\n            cout << endl;\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seed_count; ++i) {\n            seeds[i].eval.resize(M);\n            seeds[i].id = i;\n            for (int j = 0; j < M; ++j) {\n                cin >> seeds[i].eval[j];\n            }\n            seeds[i].value = accumulate(seeds[i].eval.begin(), seeds[i].eval.end(), 0);\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        return x < other.x || (x == other.x && y < other.y);\n    }\n};\n\nstruct Takoyaki {\n    Point source, target;\n    bool operator<(const Takoyaki& other) const {\n        return source < other.source || (source == other.source && target < other.target);\n    }\n};\n\nvector<Point> find_takoyaki(const vector<string>& grid, char c) {\n    vector<Point> res;\n    for (int i = 0; i < grid.size(); ++i) {\n        for (int j = 0; j < grid[i].size(); ++j) {\n            if (grid[i][j] == c) {\n                res.emplace_back(i, j);\n            }\n        }\n    }\n    return res;\n}\n\nvector<Takoyaki> create_takoyaki_list(const vector<Point>& sources, const vector<Point>& targets) {\n    vector<Takoyaki> res;\n    for (int i = 0; i < sources.size(); ++i) {\n        res.push_back({sources[i], targets[i]});\n    }\n    return res;\n}\n\nstruct TreeNode {\n    int parent;\n    int length;\n    TreeNode(int p = -1, int l = 1) : parent(p), length(l) {}\n};\n\nvector<TreeNode> design_tree(int V) {\n    vector<TreeNode> tree;\n    if (V == 1) {\n        return tree;\n    }\n    tree.emplace_back(0, 1);\n    if (V == 2) {\n        return tree;\n    }\n    tree.emplace_back(0, 2);\n    if (V == 3) {\n        return tree;\n    }\n    for (int i = 2; i < V; ++i) {\n        int p = (i - 1) / 2;\n        int l = 1 + (i % 2);\n        tree.emplace_back(p, l);\n    }\n    return tree;\n}\n\nPoint initial_root_position(int N, const vector<Takoyaki>& takoyakis) {\n    int sum_x = 0, sum_y = 0;\n    for (const auto& t : takoyakis) {\n        sum_x += t.source.x + t.target.x;\n        sum_y += t.source.y + t.target.y;\n    }\n    int cnt = 2 * takoyakis.size();\n    return Point(sum_x / cnt, sum_y / cnt);\n}\n\nvector<string> generate_operations(const vector<TreeNode>& tree, const Point& root_pos,\n                                   const vector<Takoyaki>& takoyakis, int N) {\n    vector<string> operations;\n    int V = tree.size() + 1;\n    vector<Point> fingertip_pos(V);\n    vector<int> dir(V, 0); // 0: right, 1: down, 2: left, 3: up\n    vector<bool> holding(V, false);\n    vector<Point> current_pos(V);\n    current_pos[0] = root_pos;\n\n    auto update_positions = [&]() {\n        for (int i = 1; i < V; ++i) {\n            int p = tree[i-1].parent;\n            int l = tree[i-1].length;\n            int dx = 0, dy = 0;\n            if (dir[i] == 0) { dx = l; }\n            else if (dir[i] == 1) { dy = l; }\n            else if (dir[i] == 2) { dx = -l; }\n            else if (dir[i] == 3) { dy = -l; }\n            current_pos[i] = Point(current_pos[p].x + dx, current_pos[p].y + dy);\n        }\n    };\n\n    update_positions();\n\n    auto move_root = [&](int dx, int dy) {\n        current_pos[0].x += dx;\n        current_pos[0].y += dy;\n        update_positions();\n    };\n\n    auto rotate_subtree = [&](int u, bool clockwise) {\n        if (clockwise) {\n            dir[u] = (dir[u] + 1) % 4;\n        } else {\n            dir[u] = (dir[u] + 3) % 4;\n        }\n        update_positions();\n    };\n\n    auto can_grab = [&](int u, const Point& p) {\n        return current_pos[u] == p && !holding[u];\n    };\n\n    auto can_release = [&](int u, const Point& p) {\n        return current_pos[u] == p && holding[u];\n    };\n\n    auto bfs_path = [&](Point start, Point target) {\n        vector<vector<int>> dist(N, vector<int>(N, -1));\n        vector<vector<Point>> prev(N, vector<Point>(N, Point(-1, -1)));\n        queue<Point> q;\n        dist[start.x][start.y] = 0;\n        q.push(start);\n        vector<int> dx = {0, 1, 0, -1};\n        vector<int> dy = {1, 0, -1, 0};\n        while (!q.empty()) {\n            Point p = q.front();\n            q.pop();\n            if (p == target) {\n                vector<Point> path;\n                while (p != start) {\n                    path.push_back(p);\n                    p = prev[p.x][p.y];\n                }\n                reverse(path.begin(), path.end());\n                return path;\n            }\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + dx[i];\n                int ny = p.y + dy[i];\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N && dist[nx][ny] == -1) {\n                    dist[nx][ny] = dist[p.x][p.y] + 1;\n                    prev[nx][ny] = p;\n                    q.emplace(nx, ny);\n                }\n            }\n        }\n        return vector<Point>();\n    };\n\n    auto move_to = [&](Point target) {\n        vector<Point> path = bfs_path(current_pos[0], target);\n        for (Point p : path) {\n            int dx = p.x - current_pos[0].x;\n            int dy = p.y - current_pos[0].y;\n            if (dx == 1) {\n                operations.push_back(\"D\" + string(V-1, '.') + string(V, '.'));\n                move_root(1, 0);\n            } else if (dx == -1) {\n                operations.push_back(\"U\" + string(V-1, '.') + string(V, '.'));\n                move_root(-1, 0);\n            } else if (dy == 1) {\n                operations.push_back(\"R\" + string(V-1, '.') + string(V, '.'));\n                move_root(0, 1);\n            } else if (dy == -1) {\n                operations.push_back(\"L\" + string(V-1, '.') + string(V, '.'));\n                move_root(0, -1);\n            }\n        }\n    };\n\n    auto align_fingertip = [&](int u, Point target) {\n        Point p = current_pos[u];\n        int dx = target.x - p.x;\n        int dy = target.y - p.y;\n        int required_dir = -1;\n        if (dx > 0 && dy == 0) required_dir = 0;\n        else if (dx == 0 && dy > 0) required_dir = 1;\n        else if (dx < 0 && dy == 0) required_dir = 2;\n        else if (dx == 0 && dy < 0) required_dir = 3;\n        if (required_dir == -1) return;\n        while (dir[u] != required_dir) {\n            bool clockwise = (dir[u] + 1) % 4 == required_dir;\n            string op(V*2, '.');\n            op[0] = '.';\n            op[u] = clockwise ? 'R' : 'L';\n            operations.push_back(op);\n            rotate_subtree(u, clockwise);\n        }\n    };\n\n    auto process_takoyaki = [&](const Takoyaki& t) {\n        // Move to source\n        move_to(t.source);\n        // Align fingertip to source\n        for (int u = 1; u < V; ++u) {\n            if (!holding[u]) {\n                align_fingertip(u, t.source);\n                if (can_grab(u, t.source)) {\n                    string op(V*2, '.');\n                    op[V + u] = 'P';\n                    operations.push_back(op);\n                    holding[u] = true;\n                    break;\n                }\n            }\n        }\n        // Move to target\n        move_to(t.target);\n        // Align fingertip to target\n        for (int u = 1; u < V; ++u) {\n            if (holding[u]) {\n                align_fingertip(u, t.target);\n                if (can_release(u, t.target)) {\n                    string op(V*2, '.');\n                    op[V + u] = 'P';\n                    operations.push_back(op);\n                    holding[u] = false;\n                    break;\n                }\n            }\n        }\n    };\n\n    for (const auto& t : takoyakis) {\n        process_takoyaki(t);\n    }\n\n    return operations;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, V;\n    cin >> N >> M >> V;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        cin >> t[i];\n    }\n\n    vector<Point> sources = find_takoyaki(s, '1');\n    vector<Point> targets = find_takoyaki(t, '1');\n    vector<Takoyaki> takoyakis = create_takoyaki_list(sources, targets);\n\n    vector<TreeNode> tree = design_tree(V);\n    Point root_pos = initial_root_position(N, takoyakis);\n\n    cout << tree.size() + 1 << '\\n';\n    for (const auto& node : tree) {\n        cout << node.parent << ' ' << node.length << '\\n';\n    }\n    cout << root_pos.x << ' ' << root_pos.y << '\\n';\n\n    vector<string> operations = generate_operations(tree, root_pos, takoyakis, N);\n    for (const string& op : operations) {\n        cout << op << '\\n';\n    }\n\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n    bool operator==(const Point& p) const {\n        return x == p.x && y == p.y;\n    }\n};\n\nint N;\nvector<Point> mackerels, sardines;\nvector<Point> polygon;\n\nbool is_inside(const vector<Point>& poly, const Point& p) {\n    int n = poly.size();\n    bool inside = false;\n    for (int i = 0, j = n - 1; i < n; j = i++) {\n        const Point& a = poly[i];\n        const Point& b = poly[j];\n        if (a.y == b.y) {\n            if (p.y == a.y && min(a.x, b.x) <= p.x && p.x <= max(a.x, b.x)) {\n                return true;\n            }\n            continue;\n        }\n        if ((a.y > p.y) != (b.y > p.y)) {\n            int x_intersect = (p.y - a.y) * (b.x - a.x) / (b.y - a.y) + a.x;\n            if (p.x == x_intersect) {\n                return true;\n            }\n            if (p.x < x_intersect) {\n                inside = !inside;\n            }\n        }\n    }\n    return inside;\n}\n\nvector<Point> initial_polygon() {\n    int min_x = 1e9, max_x = -1, min_y = 1e9, max_y = -1;\n    for (const Point& p : mackerels) {\n        min_x = min(min_x, p.x);\n        max_x = max(max_x, p.x);\n        min_y = min(min_y, p.y);\n        max_y = max(max_y, p.y);\n    }\n    vector<Point> poly = {\n        {min_x, min_y},\n        {max_x, min_y},\n        {max_x, max_y},\n        {min_x, max_y}\n    };\n    return poly;\n}\n\nvector<Point> adjust_polygon(vector<Point> poly) {\n    vector<bool> mackerel_inside(N, false);\n    vector<bool> sardine_inside(N, false);\n    int a = 0, b = 0;\n\n    for (int i = 0; i < N; ++i) {\n        mackerel_inside[i] = is_inside(poly, mackerels[i]);\n        if (mackerel_inside[i]) a++;\n    }\n    for (int i = 0; i < N; ++i) {\n        sardine_inside[i] = is_inside(poly, sardines[i]);\n        if (sardine_inside[i]) b++;\n    }\n\n    int best_score = max(0, a - b + 1);\n    vector<Point> best_poly = poly;\n\n    auto update_counts = [&](const vector<Point>& old_poly, const vector<Point>& new_poly) {\n        int delta_a = 0, delta_b = 0;\n        for (int i = 0; i < N; ++i) {\n            bool old_inside = mackerel_inside[i];\n            bool new_inside = is_inside(new_poly, mackerels[i]);\n            if (old_inside && !new_inside) delta_a--;\n            else if (!old_inside && new_inside) delta_a++;\n            mackerel_inside[i] = new_inside;\n        }\n        for (int i = 0; i < N; ++i) {\n            bool old_inside = sardine_inside[i];\n            bool new_inside = is_inside(new_poly, sardines[i]);\n            if (old_inside && !new_inside) delta_b--;\n            else if (!old_inside && new_inside) delta_b++;\n            sardine_inside[i] = new_inside;\n        }\n        return make_pair(a + delta_a, b + delta_b);\n    };\n\n    auto try_move_vertex = [&](int vertex_idx, int dx, int dy) {\n        if (poly.size() >= 1000) return;\n        vector<Point> new_poly = poly;\n        int prev = (vertex_idx - 1 + poly.size()) % poly.size();\n        int next = (vertex_idx + 1) % poly.size();\n        if (poly[prev].x == poly[vertex_idx].x && poly[vertex_idx].x == poly[next].x) {\n            new_poly[vertex_idx].y += dy;\n        } else if (poly[prev].y == poly[vertex_idx].y && poly[vertex_idx].y == poly[next].y) {\n            new_poly[vertex_idx].x += dx;\n        } else {\n            return;\n        }\n        auto [new_a, new_b] = update_counts(poly, new_poly);\n        int new_score = max(0, new_a - new_b + 1);\n        if (new_score > best_score) {\n            best_score = new_score;\n            best_poly = new_poly;\n            a = new_a;\n            b = new_b;\n            poly = new_poly;\n        }\n    };\n\n    auto try_add_vertex = [&](int edge_idx, Point new_vertex) {\n        if (poly.size() >= 1000) return;\n        int i = edge_idx;\n        int j = (i + 1) % poly.size();\n        if (poly[i].x == poly[j].x) {\n            if (new_vertex.x != poly[i].x) return;\n        } else if (poly[i].y == poly[j].y) {\n            if (new_vertex.y != poly[i].y) return;\n        } else {\n            return;\n        }\n        vector<Point> new_poly = poly;\n        new_poly.insert(new_poly.begin() + i + 1, new_vertex);\n        auto [new_a, new_b] = update_counts(poly, new_poly);\n        int new_score = max(0, new_a - new_b + 1);\n        if (new_score > best_score) {\n            best_score = new_score;\n            best_poly = new_poly;\n            a = new_a;\n            b = new_b;\n            poly = new_poly;\n        }\n    };\n\n    for (int iter = 0; iter < 3; ++iter) {\n        for (int vertex_idx = 0; vertex_idx < poly.size(); ++vertex_idx) {\n            for (int dx = -50; dx <= 50; dx += 50) {\n                try_move_vertex(vertex_idx, dx, 0);\n            }\n            for (int dy = -50; dy <= 50; dy += 50) {\n                try_move_vertex(vertex_idx, 0, dy);\n            }\n        }\n        for (int edge_idx = 0; edge_idx < poly.size(); ++edge_idx) {\n            int i = edge_idx;\n            int j = (i + 1) % poly.size();\n            if (poly[i].x == poly[j].x) {\n                int x = poly[i].x;\n                int y_min = min(poly[i].y, poly[j].y);\n                int y_max = max(poly[i].y, poly[j].y);\n                for (int y = y_min + 50; y < y_max; y += 100) {\n                    try_add_vertex(edge_idx, Point(x, y));\n                }\n            } else if (poly[i].y == poly[j].y) {\n                int y = poly[i].y;\n                int x_min = min(poly[i].x, poly[j].x);\n                int x_max = max(poly[i].x, poly[j].x);\n                for (int x = x_min + 50; x < x_max; x += 100) {\n                    try_add_vertex(edge_idx, Point(x, y));\n                }\n            }\n        }\n    }\n\n    return best_poly;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    mackerels.resize(N);\n    sardines.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> mackerels[i].x >> mackerels[i].y;\n    }\n    for (int i = 0; i < N; ++i) {\n        cin >> sardines[i].x >> sardines[i].y;\n    }\n\n    polygon = initial_polygon();\n    polygon = adjust_polygon(polygon);\n\n    cout << polygon.size() << '\\n';\n    for (const Point& p : polygon) {\n        cout << p.x << ' ' << p.y << '\\n';\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n#include <random>\n#include <chrono>\n\nusing namespace std;\nusing namespace std::chrono;\n\nstruct Rectangle {\n    int id;\n    int w, h;\n    int x, y;\n    bool rotated;\n};\n\nstruct Placement {\n    int p, r;\n    char d;\n    int b;\n};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nvector<Rectangle> place_rectangles(const vector<pair<int, int>>& observed, const vector<Placement>& placements) {\n    vector<Rectangle> placed;\n    for (const auto& pl : placements) {\n        int id = pl.p;\n        bool rotated = pl.r;\n        int w = observed[id].first;\n        int h = observed[id].second;\n        if (rotated) swap(w, h);\n\n        int x = 0, y = 0;\n        if (pl.d == 'U') {\n            if (pl.b == -1) {\n                x = 0;\n            } else {\n                x = placed[pl.b].x + placed[pl.b].w;\n            }\n            int max_y = 0;\n            for (const auto& rect : placed) {\n                if (rect.x < x + w && rect.x + rect.w > x) {\n                    if (rect.y + rect.h > max_y) {\n                        max_y = rect.y + rect.h;\n                    }\n                }\n            }\n            y = max_y;\n        } else if (pl.d == 'L') {\n            if (pl.b == -1) {\n                y = 0;\n            } else {\n                y = placed[pl.b].y + placed[pl.b].h;\n            }\n            int max_x = 0;\n            for (const auto& rect : placed) {\n                if (rect.y < y + h && rect.y + rect.h > y) {\n                    if (rect.x + rect.w > max_x) {\n                        max_x = rect.x + rect.w;\n                    }\n                }\n            }\n            x = max_x;\n        }\n        placed.push_back({id, w, h, x, y, rotated});\n    }\n    return placed;\n}\n\npair<int, int> calculate_dimensions(const vector<Rectangle>& placed) {\n    int max_x = 0, max_y = 0;\n    for (const auto& rect : placed) {\n        max_x = max(max_x, rect.x + rect.w);\n        max_y = max(max_y, rect.y + rect.h);\n    }\n    return {max_x, max_y};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n    vector<pair<int, int>> observed(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> observed[i].first >> observed[i].second;\n    }\n\n    vector<pair<int, int>> measurements;\n    for (int t = 0; t < T; ++t) {\n        vector<Placement> placements;\n        vector<bool> used(N, false);\n\n        for (int i = 0; i < N; ++i) {\n            int best_r = 0;\n            char best_d = 'U';\n            int best_b = -1;\n            int min_score = INT_MAX;\n\n            vector<int> ref_rects = {-1};\n            for (int b = max(0, (int)placements.size() - 5); b < placements.size(); ++b) {\n                ref_rects.push_back(b);\n            }\n\n            for (int r = 0; r < 2; ++r) {\n                for (char d : {'U', 'L'}) {\n                    for (int b : ref_rects) {\n                        placements.push_back({i, r, d, b});\n                        auto placed = place_rectangles(observed, placements);\n                        auto [W, H] = calculate_dimensions(placed);\n                        int score = W + H;\n                        if (score < min_score) {\n                            min_score = score;\n                            best_r = r;\n                            best_d = d;\n                            best_b = b;\n                        }\n                        placements.pop_back();\n                    }\n                }\n            }\n\n            if (t < T / 2 && rng() % 10 < 2) {\n                best_r = rng() % 2;\n                best_d = (rng() % 2) ? 'U' : 'L';\n                best_b = (placements.empty()) ? -1 : rng() % placements.size();\n            }\n\n            placements.push_back({i, best_r, best_d, best_b});\n        }\n\n        cout << placements.size() << '\\n';\n        for (const auto& pl : placements) {\n            cout << pl.p << ' ' << pl.r << ' ' << pl.d << ' ' << pl.b << '\\n';\n        }\n        cout.flush();\n\n        int W_prime, H_prime;\n        cin >> W_prime >> H_prime;\n        measurements.emplace_back(W_prime, H_prime);\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <set>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nstruct Vertex {\n    int id;\n    int a;\n    int x, y;\n    vector<int> neighbors;\n};\n\nstruct BFSState {\n    int vertex;\n    int parent;\n    int depth;\n    bool operator<(const BFSState& other) const {\n        if (depth != other.depth) return depth > other.depth;\n        return a[vertex] < a[other.vertex];\n    }\n    static vector<int> a;\n};\n\nvector<int> BFSState::a;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    cin >> N >> M >> H;\n\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> A[i];\n    }\n    BFSState::a = A;\n\n    vector<pair<int, int>> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].first >> edges[i].second;\n    }\n\n    vector<pair<int, int>> coords(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> coords[i].first >> coords[i].second;\n    }\n\n    vector<Vertex> vertices(N);\n    for (int i = 0; i < N; ++i) {\n        vertices[i].id = i;\n        vertices[i].a = A[i];\n        vertices[i].x = coords[i].first;\n        vertices[i].y = coords[i].second;\n    }\n\n    for (const auto& edge : edges) {\n        int u = edge.first;\n        int v = edge.second;\n        vertices[u].neighbors.push_back(v);\n        vertices[v].neighbors.push_back(u);\n    }\n\n    vector<int> parent(N, -1);\n    vector<bool> assigned(N, false);\n\n    while (true) {\n        int root = -1;\n        int max_a = -1;\n        for (int i = 0; i < N; ++i) {\n            if (!assigned[i] && A[i] > max_a) {\n                max_a = A[i];\n                root = i;\n            }\n        }\n        if (root == -1) break;\n\n        priority_queue<BFSState> pq;\n        pq.push({root, -1, 0});\n        vector<bool> visited(N, false);\n        visited[root] = true;\n\n        while (!pq.empty()) {\n            BFSState current = pq.top();\n            pq.pop();\n            if (current.depth > H) continue;\n            if (assigned[current.vertex]) continue;\n\n            parent[current.vertex] = current.parent;\n            assigned[current.vertex] = true;\n\n            for (int neighbor : vertices[current.vertex].neighbors) {\n                if (!visited[neighbor] && !assigned[neighbor]) {\n                    visited[neighbor] = true;\n                    pq.push({neighbor, current.vertex, current.depth + 1});\n                }\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <set>\n#include <map>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_MOVES = 4 * N * N;\n\nstruct Piece {\n    int i, j;\n    char type; // 'x' for Oni, 'o' for Fukunokami\n};\n\nvector<string> board;\nvector<Piece> oni_list;\nvector<Piece> fuku_list;\nvector<vector<bool>> safe_up, safe_down, safe_left, safe_right;\n\nvoid preprocess() {\n    // Initialize safe directions\n    safe_up.assign(N, vector<bool>(N, true));\n    safe_down.assign(N, vector<bool>(N, true));\n    safe_left.assign(N, vector<bool>(N, true));\n    safe_right.assign(N, vector<bool>(N, true));\n\n    // Mark unsafe directions for Oni\n    for (const auto& fuku : fuku_list) {\n        int i = fuku.i, j = fuku.j;\n        // Up: all squares above (i,j) in column j are unsafe for Oni below\n        for (int k = 0; k < i; ++k) {\n            safe_down[k][j] = false;\n        }\n        // Down: all squares below (i,j) in column j are unsafe for Oni above\n        for (int k = i + 1; k < N; ++k) {\n            safe_up[k][j] = false;\n        }\n        // Left: all squares left of (i,j) in row i are unsafe for Oni to the right\n        for (int k = 0; k < j; ++k) {\n            safe_right[i][k] = false;\n        }\n        // Right: all squares right of (i,j) in row i are unsafe for Oni to the left\n        for (int k = j + 1; k < N; ++k) {\n            safe_left[i][k] = false;\n        }\n    }\n}\n\nvector<pair<char, int>> moves;\n\nvoid shift_row_left(int i) {\n    moves.emplace_back('L', i);\n    char first = board[i][0];\n    for (int j = 0; j < N - 1; ++j) {\n        board[i][j] = board[i][j + 1];\n    }\n    board[i][N - 1] = '.';\n}\n\nvoid shift_row_right(int i) {\n    moves.emplace_back('R', i);\n    char last = board[i][N - 1];\n    for (int j = N - 1; j > 0; --j) {\n        board[i][j] = board[i][j - 1];\n    }\n    board[i][0] = '.';\n}\n\nvoid shift_col_up(int j) {\n    moves.emplace_back('U', j);\n    char first = board[0][j];\n    for (int i = 0; i < N - 1; ++i) {\n        board[i][j] = board[i + 1][j];\n    }\n    board[N - 1][j] = '.';\n}\n\nvoid shift_col_down(int j) {\n    moves.emplace_back('D', j);\n    char last = board[N - 1][j];\n    for (int i = N - 1; i > 0; --i) {\n        board[i][j] = board[i - 1][j];\n    }\n    board[0][j] = '.';\n}\n\nvoid remove_oni() {\n    while (true) {\n        // Check if all Oni are removed\n        bool all_removed = true;\n        for (const auto& row : board) {\n            if (row.find('x') != string::npos) {\n                all_removed = false;\n                break;\n            }\n        }\n        if (all_removed) break;\n\n        // Find the row or column with the most removable Oni\n        int max_oni = 0;\n        char best_dir = ' ';\n        int best_idx = -1;\n\n        // Check rows for left/right shifts\n        for (int i = 0; i < N; ++i) {\n            int left_oni = 0, right_oni = 0;\n            for (int j = 0; j < N; ++j) {\n                if (board[i][j] == 'x') {\n                    if (safe_left[i][j]) left_oni++;\n                    if (safe_right[i][j]) right_oni++;\n                }\n            }\n            if (left_oni > max_oni) {\n                max_oni = left_oni;\n                best_dir = 'L';\n                best_idx = i;\n            }\n            if (right_oni > max_oni) {\n                max_oni = right_oni;\n                best_dir = 'R';\n                best_idx = i;\n            }\n        }\n\n        // Check columns for up/down shifts\n        for (int j = 0; j < N; ++j) {\n            int up_oni = 0, down_oni = 0;\n            for (int i = 0; i < N; ++i) {\n                if (board[i][j] == 'x') {\n                    if (safe_up[i][j]) up_oni++;\n                    if (safe_down[i][j]) down_oni++;\n                }\n            }\n            if (up_oni > max_oni) {\n                max_oni = up_oni;\n                best_dir = 'U';\n                best_idx = j;\n            }\n            if (down_oni > max_oni) {\n                max_oni = down_oni;\n                best_dir = 'D';\n                best_idx = j;\n            }\n        }\n\n        if (max_oni == 0) {\n            // No removable Oni found (should not happen due to problem guarantee)\n            break;\n        }\n\n        // Perform the best shift\n        if (best_dir == 'L') shift_row_left(best_idx);\n        else if (best_dir == 'R') shift_row_right(best_idx);\n        else if (best_dir == 'U') shift_col_up(best_idx);\n        else if (best_dir == 'D') shift_col_down(best_idx);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    board.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n    }\n\n    // Collect Oni and Fukunokami positions\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                oni_list.push_back({i, j, 'x'});\n            } else if (board[i][j] == 'o') {\n                fuku_list.push_back({i, j, 'o'});\n            }\n        }\n    }\n\n    preprocess();\n    remove_oni();\n\n    // Output the moves\n    for (const auto& move : moves) {\n        cout << move.first << \" \" << move.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <climits>\n#include <cmath>\n#include <chrono>\n#include <numeric>\n#include <unordered_set>\n\nusing namespace std;\n\nconst int N = 100;\nconst int L = 500000;\nconst int MAX_ITER = 15;\nconst int NUM_STARTS = 3;\nconst int TABU_TENURE = 20;\n\nstruct Employee {\n    int a, b;\n};\n\nvector<int> simulate(const vector<Employee>& employees, const vector<int>& T, int max_weeks = L) {\n    vector<int> t(N, 0);\n    int current = 0;\n    t[current]++;\n    for (int week = 1; week < max_weeks; ++week) {\n        int cnt = t[current];\n        if (cnt % 2 == 1) {\n            current = employees[current].a;\n        } else {\n            current = employees[current].b;\n        }\n        t[current]++;\n    }\n    return t;\n}\n\nlong long calculate_error(const vector<int>& t, const vector<int>& T) {\n    long long error = 0;\n    for (int i = 0; i < N; ++i) {\n        error += abs(t[i] - T[i]);\n    }\n    return error;\n}\n\nvector<Employee> smart_initial(const vector<int>& T) {\n    vector<Employee> employees(N);\n    vector<int> current_t(N, 0);\n    current_t[0] = 1;\n    int current = 0;\n\n    // Create a priority list based on target counts\n    vector<pair<int, int>> priority;\n    for (int i = 0; i < N; ++i) {\n        priority.emplace_back(T[i], i);\n    }\n    sort(priority.rbegin(), priority.rend());\n\n    for (int week = 1; week < L; ++week) {\n        int cnt = current_t[current];\n        // Find the employee with highest (T[i] - current_t[i])\n        int best_next = -1;\n        int best_diff = -1;\n        for (int i = 0; i < N; ++i) {\n            int diff = T[i] - current_t[i];\n            if (diff > best_diff) {\n                best_diff = diff;\n                best_next = i;\n            }\n        }\n\n        if (cnt % 2 == 1) {\n            employees[current].a = best_next;\n        } else {\n            employees[current].b = best_next;\n        }\n        current = best_next;\n        current_t[current]++;\n    }\n    return employees;\n}\n\nvector<Employee> tabu_search(const vector<int>& T, vector<Employee> employees, int max_iter = MAX_ITER) {\n    auto t = simulate(employees, T, min(L, 50000));\n    long long best_error = calculate_error(t, T);\n    vector<Employee> best_employees = employees;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<double> dist(0.0, 1.0);\n\n    // Tabu list\n    vector<pair<int, int>> tabu_list;\n    int tabu_tenure = TABU_TENURE;\n\n    double temperature = 1.0;\n    double cooling_rate = 0.95;\n\n    for (int iter = 0; iter < max_iter; ++iter) {\n        bool improved = false;\n        vector<int> indices(N);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), gen);\n\n        for (int i : indices) {\n            vector<int> candidates;\n            for (int j = 0; j < N; ++j) {\n                if (j != employees[i].a) candidates.push_back(j);\n                if (j != employees[i].b) candidates.push_back(j);\n            }\n            shuffle(candidates.begin(), candidates.end(), gen);\n            candidates.resize(min(10, (int)candidates.size()));\n\n            for (int new_val : candidates) {\n                // Check if this move is tabu\n                bool is_tabu = false;\n                for (auto& tabu : tabu_list) {\n                    if (tabu.first == i && tabu.second == new_val) {\n                        is_tabu = true;\n                        break;\n                    }\n                }\n                if (is_tabu) continue;\n\n                if (new_val == employees[i].a) continue;\n                auto old_a = employees[i].a;\n                employees[i].a = new_val;\n                auto new_t = simulate(employees, T, min(L, 50000 + iter * 10000));\n                long long new_error = calculate_error(new_t, T);\n                double delta = new_error - best_error;\n\n                if (delta < 0 || dist(gen) < exp(-delta / temperature)) {\n                    if (new_error < best_error) {\n                        best_error = new_error;\n                        best_employees = employees;\n                        improved = true;\n                    }\n                    // Add to tabu list\n                    tabu_list.emplace_back(i, old_a);\n                    if (tabu_list.size() > tabu_tenure) {\n                        tabu_list.erase(tabu_list.begin());\n                    }\n                } else {\n                    employees[i].a = old_a;\n                }\n            }\n\n            if (improved) break;\n\n            for (int new_val : candidates) {\n                // Check if this move is tabu\n                bool is_tabu = false;\n                for (auto& tabu : tabu_list) {\n                    if (tabu.first == i && tabu.second == new_val) {\n                        is_tabu = true;\n                        break;\n                    }\n                }\n                if (is_tabu) continue;\n\n                if (new_val == employees[i].b) continue;\n                auto old_b = employees[i].b;\n                employees[i].b = new_val;\n                auto new_t = simulate(employees, T, min(L, 50000 + iter * 10000));\n                long long new_error = calculate_error(new_t, T);\n                double delta = new_error - best_error;\n\n                if (delta < 0 || dist(gen) < exp(-delta / temperature)) {\n                    if (new_error < best_error) {\n                        best_error = new_error;\n                        best_employees = employees;\n                        improved = true;\n                    }\n                    // Add to tabu list\n                    tabu_list.emplace_back(i, old_b);\n                    if (tabu_list.size() > tabu_tenure) {\n                        tabu_list.erase(tabu_list.begin());\n                    }\n                } else {\n                    employees[i].b = old_b;\n                }\n            }\n\n            if (improved) break;\n        }\n\n        temperature *= cooling_rate;\n        if (!improved) {\n            cooling_rate = max(0.8, cooling_rate * 0.9);\n        }\n    }\n    return best_employees;\n}\n\nvector<Employee> multi_start_search(const vector<int>& T) {\n    vector<Employee> best_employees(N);\n    long long best_error = LLONG_MAX;\n\n    for (int start = 0; start < NUM_STARTS; ++start) {\n        auto employees = smart_initial(T);\n        employees = tabu_search(T, employees);\n        auto t = simulate(employees, T);\n        long long error = calculate_error(t, T);\n\n        if (error < best_error) {\n            best_error = error;\n            best_employees = employees;\n        }\n    }\n\n    return best_employees;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, L_in;\n    cin >> N_in >> L_in;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    auto employees = multi_start_search(T);\n\n    for (const auto& emp : employees) {\n        cout << emp.a << \" \" << emp.b << \"\\n\";\n    }\n\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct City {\n    int lx, rx, ly, ry;\n    int x, y; // Estimated coordinates\n};\n\nint N, M, Q, L, W;\nvector<int> G;\nvector<City> cities;\nvector<vector<int>> groups;\nvector<vector<pair<int, int>>> edges;\n\nvector<pair<int, int>> query(const vector<int>& C) {\n    cout << \"? \" << C.size();\n    for (int c : C) cout << \" \" << c;\n    cout << endl;\n    cout.flush();\n\n    vector<pair<int, int>> res;\n    for (int i = 0; i < (int)C.size() - 1; ++i) {\n        int a, b;\n        cin >> a >> b;\n        res.emplace_back(a, b);\n    }\n    return res;\n}\n\nvoid answer() {\n    cout << \"!\" << endl;\n    for (int k = 0; k < M; ++k) {\n        for (int c : groups[k]) cout << c << \" \";\n        cout << endl;\n        for (auto [a, b] : edges[k]) {\n            cout << a << \" \" << b << endl;\n        }\n    }\n    cout.flush();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M >> Q >> L >> W;\n    G.resize(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    cities.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].x = (cities[i].lx + cities[i].rx) / 2;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2;\n    }\n\n    // Initial grouping based on estimated coordinates\n    vector<int> city_indices(N);\n    iota(city_indices.begin(), city_indices.end(), 0);\n    sort(city_indices.begin(), city_indices.end(), [&](int a, int b) {\n        if (cities[a].x != cities[b].x) return cities[a].x < cities[b].x;\n        return cities[a].y < cities[b].y;\n    });\n\n    groups.resize(M);\n    int start = 0;\n    for (int k = 0; k < M; ++k) {\n        for (int i = 0; i < G[k]; ++i) {\n            groups[k].push_back(city_indices[start + i]);\n        }\n        start += G[k];\n    }\n\n    // Perform queries to get MST edges\n    edges.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int n = groups[k].size();\n        if (n == 1) continue;\n        if (n == 2) {\n            edges[k].emplace_back(groups[k][0], groups[k][1]);\n            continue;\n        }\n        for (int i = 0; i < n - 1; i += L - 1) {\n            int end = min(i + L, n);\n            vector<int> subset(groups[k].begin() + i, groups[k].begin() + end);\n            auto res = query(subset);\n            for (auto [a, b] : res) {\n                edges[k].emplace_back(a, b);\n            }\n        }\n    }\n\n    // Refinement step: Ensure each group is connected\n    for (int k = 0; k < M; ++k) {\n        if (groups[k].size() == 1) continue;\n        dsu d(groups[k].size());\n        for (auto [a, b] : edges[k]) {\n            int u = find(groups[k].begin(), groups[k].end(), a) - groups[k].begin();\n            int v = find(groups[k].begin(), groups[k].end(), b) - groups[k].begin();\n            d.merge(u, v);\n        }\n        if (d.size(0) != groups[k].size()) {\n            // Need to add more edges to connect the group\n            for (int i = 1; i < groups[k].size(); ++i) {\n                if (!d.same(0, i)) {\n                    edges[k].emplace_back(groups[k][0], groups[k][i]);\n                    d.merge(0, i);\n                }\n            }\n        }\n    }\n\n    answer();\n\n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\nconst int M = 40;\nconst int MAX_ACTIONS = 2 * N * M;\nconst int BEAM_WIDTH = 100;\n\nstruct State {\n    int i, j;\n    bitset<N*N> blocks;\n    int next_target;\n    vector<pair<char, char>> actions;\n    int score;\n\n    State(int i, int j, bitset<N*N> blocks, int next_target, vector<pair<char, char>> actions)\n        : i(i), j(j), blocks(blocks), next_target(next_target), actions(actions), score(0) {}\n\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n};\n\nvector<pair<int, int>> targets;\n\nint manhattan(int i1, int j1, int i2, int j2) {\n    return abs(i1 - i2) + abs(j1 - j2);\n}\n\nbool is_blocked(int i, int j, const bitset<N*N>& blocks) {\n    if (i < 0 || i >= N || j < 0 || j >= N) return true;\n    return blocks[i * N + j];\n}\n\nvector<State> expand(const State& state) {\n    vector<State> next_states;\n    vector<char> actions = {'S', 'M', 'A'}; // Prioritize Slide\n    vector<char> directions = {'U', 'D', 'L', 'R'};\n\n    for (char a : actions) {\n        for (char d : directions) {\n            State new_state = state;\n            new_state.actions.emplace_back(a, d);\n            int di = 0, dj = 0;\n            if (d == 'U') di = -1;\n            if (d == 'D') di = 1;\n            if (d == 'L') dj = -1;\n            if (d == 'R') dj = 1;\n\n            if (a == 'M') {\n                int ni = state.i + di, nj = state.j + dj;\n                if (!is_blocked(ni, nj, state.blocks)) {\n                    new_state.i = ni;\n                    new_state.j = nj;\n                } else {\n                    continue;\n                }\n            } else if (a == 'S') {\n                int ni = state.i, nj = state.j;\n                while (true) {\n                    int nni = ni + di, nnj = nj + dj;\n                    if (is_blocked(nni, nnj, state.blocks)) break;\n                    ni = nni;\n                    nj = nnj;\n                }\n                new_state.i = ni;\n                new_state.j = nj;\n            } else if (a == 'A') {\n                int ni = state.i + di, nj = state.j + dj;\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                new_state.blocks.flip(ni * N + nj);\n            }\n\n            // Check if next target is reached\n            if (new_state.next_target < M &&\n                new_state.i == targets[new_state.next_target].first &&\n                new_state.j == targets[new_state.next_target].second) {\n                new_state.next_target++;\n            }\n\n            // Evaluate score\n            int dist = 0;\n            if (new_state.next_target < M) {\n                dist = manhattan(new_state.i, new_state.j, targets[new_state.next_target].first, targets[new_state.next_target].second);\n            }\n            new_state.score = -new_state.actions.size() - dist - (M - new_state.next_target) * 100;\n            next_states.push_back(new_state);\n        }\n    }\n    return next_states;\n}\n\nvector<pair<char, char>> beam_search(int start_i, int start_j) {\n    bitset<N*N> initial_blocks;\n    State initial_state(start_i, start_j, initial_blocks, 0, {});\n    priority_queue<State> beam;\n    beam.push(initial_state);\n\n    for (int step = 0; step < MAX_ACTIONS; ++step) {\n        priority_queue<State> next_beam;\n        for (int i = 0; i < BEAM_WIDTH && !beam.empty(); ++i) {\n            State current = beam.top();\n            beam.pop();\n            if (current.next_target == M) {\n                return current.actions;\n            }\n            vector<State> next_states = expand(current);\n            for (State& next_state : next_states) {\n                if (next_state.actions.size() <= MAX_ACTIONS) {\n                    next_beam.push(next_state);\n                }\n            }\n        }\n        beam = move(next_beam);\n    }\n\n    // Return the best found\n    State best = beam.top();\n    return best.actions;\n}\n\nint main() {\n    int N_in, M_in;\n    cin >> N_in >> M_in;\n    targets.resize(M_in);\n    for (int i = 0; i < M_in; ++i) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n\n    vector<pair<char, char>> actions = beam_search(targets[0].first, targets[0].second);\n    for (auto [a, d] : actions) {\n        cout << a << \" \" << d << \"\\n\";\n    }\n    return 0;\n}"},"16":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Rect {\n    int a, b, c, d;\n    int area() const { return (c - a) * (d - b); }\n    bool contains(int x, int y) const {\n        return a <= x && x < c && b <= y && y < d;\n    }\n    bool overlaps(const Rect& other) const {\n        return !(c <= other.a || other.c <= a || d <= other.b || other.d <= b);\n    }\n};\n\nstruct Company {\n    int x, y, r;\n    Rect rect;\n    double satisfaction() const {\n        int s = rect.area();\n        if (s == 0) return 0.0;\n        double ratio = min(r, s) * 1.0 / max(r, s);\n        return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n    }\n};\n\nint n;\nvector<Company> companies;\nvector<Rect> placed_rects;\n\nbool is_valid(const Rect& rect, int ignore = -1) {\n    for (int i = 0; i < placed_rects.size(); ++i) {\n        if (i == ignore) continue;\n        if (rect.overlaps(placed_rects[i])) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid place_rect(const Rect& rect) {\n    placed_rects.push_back(rect);\n}\n\nvoid remove_rect(int id) {\n    placed_rects.erase(placed_rects.begin() + id);\n}\n\ndouble total_satisfaction() {\n    double total = 0.0;\n    for (const auto& company : companies) {\n        total += company.satisfaction();\n    }\n    return total;\n}\n\nvoid greedy_initialization() {\n    for (auto& company : companies) {\n        int x = company.x;\n        int y = company.y;\n        // Start with a 1x1 rectangle\n        company.rect = {x, y, x + 1, y + 1};\n        place_rect(company.rect);\n    }\n}\n\nvoid local_search() {\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (auto& company : companies) {\n            int id = &company - &companies[0];\n            Rect original = company.rect;\n            double original_sat = company.satisfaction();\n            vector<Rect> candidates;\n\n            // Try expanding in all four directions\n            // Expand right\n            if (company.rect.c < 10000) {\n                Rect new_rect = company.rect;\n                new_rect.c++;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand left\n            if (company.rect.a > 0) {\n                Rect new_rect = company.rect;\n                new_rect.a--;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand up\n            if (company.rect.d < 10000) {\n                Rect new_rect = company.rect;\n                new_rect.d++;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n            // Expand down\n            if (company.rect.b > 0) {\n                Rect new_rect = company.rect;\n                new_rect.b--;\n                if (is_valid(new_rect, id)) {\n                    candidates.push_back(new_rect);\n                }\n            }\n\n            // Try to find the best candidate\n            double best_sat = original_sat;\n            Rect best_rect = original;\n            for (const auto& rect : candidates) {\n                company.rect = rect;\n                double sat = company.satisfaction();\n                if (sat > best_sat) {\n                    best_sat = sat;\n                    best_rect = rect;\n                }\n            }\n            if (best_sat > original_sat) {\n                remove_rect(id);\n                company.rect = best_rect;\n                place_rect(best_rect);\n                improved = true;\n            } else {\n                company.rect = original;\n            }\n        }\n    }\n}\n\nvoid simulated_annealing() {\n    double temperature = 1000.0;\n    double cooling_rate = 0.999;\n    double min_temperature = 0.1;\n    double current_sat = total_satisfaction();\n\n    while (temperature > min_temperature) {\n        for (auto& company : companies) {\n            int id = &company - &companies[0];\n            Rect original = company.rect;\n            double original_sat = company.satisfaction();\n\n            // Randomly choose a direction to expand or shrink\n            int dir = rand() % 4;\n            Rect new_rect = original;\n            switch (dir) {\n                case 0: // right\n                    if (new_rect.c < 10000) new_rect.c++;\n                    break;\n                case 1: // left\n                    if (new_rect.a > 0) new_rect.a--;\n                    break;\n                case 2: // up\n                    if (new_rect.d < 10000) new_rect.d++;\n                    break;\n                case 3: // down\n                    if (new_rect.b > 0) new_rect.b--;\n                    break;\n            }\n\n            if (!is_valid(new_rect, id)) continue;\n\n            company.rect = new_rect;\n            double new_sat = company.satisfaction();\n            double delta = new_sat - original_sat;\n\n            if (delta > 0 || (rand() / (double)RAND_MAX) < exp(delta / temperature)) {\n                remove_rect(id);\n                place_rect(new_rect);\n                current_sat += delta;\n            } else {\n                company.rect = original;\n            }\n        }\n        temperature *= cooling_rate;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> n;\n    companies.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n\n    greedy_initialization();\n    local_search();\n    simulated_annealing();\n\n    for (const auto& company : companies) {\n        cout << company.rect.a << \" \" << company.rect.b << \" \"\n             << company.rect.c << \" \" << company.rect.d << \"\\n\";\n    }\n\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct Tile {\n    vector<pair<int, int>> cells;\n    int sum = 0;\n    int id;\n};\n\nstruct State {\n    int score;\n    int last_tile;\n    int last_x, last_y;\n    vector<bool> visited_tiles;\n    string path;\n\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> t(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> t[i][j];\n        }\n    }\n\n    vector<vector<int>> p(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> p[i][j];\n        }\n    }\n\n    // Step 1: Identify tiles using DSU\n    dsu d(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && t[i][j] == t[ni][nj]) {\n                    d.merge(i * N + j, ni * N + nj);\n                }\n            }\n        }\n    }\n\n    // Step 2: Build tiles\n    map<int, Tile> tiles;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int root = d.leader(i * N + j);\n            tiles[root].cells.emplace_back(i, j);\n            tiles[root].sum += p[i][j];\n            tiles[root].id = root;\n        }\n    }\n\n    // Step 3: Build adjacency list for tiles\n    map<int, vector<int>> adj;\n    for (auto& [root, tile] : tiles) {\n        set<int> neighbors;\n        for (auto [i, j] : tile.cells) {\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                    int nroot = d.leader(ni * N + nj);\n                    if (nroot != root) {\n                        neighbors.insert(nroot);\n                    }\n                }\n            }\n        }\n        for (int nroot : neighbors) {\n            adj[root].push_back(nroot);\n        }\n    }\n\n    // Step 4: Beam search\n    const int BEAM_WIDTH = 1000;\n    priority_queue<State> beam;\n    State initial;\n    int start_root = d.leader(si * N + sj);\n    initial.score = p[si][sj];\n    initial.last_tile = start_root;\n    initial.last_x = si;\n    initial.last_y = sj;\n    initial.visited_tiles.resize(tiles.size(), false);\n    initial.visited_tiles[start_root] = true;\n    initial.path = \"\";\n    beam.push(initial);\n\n    string best_path;\n    int best_score = 0;\n\n    while (!beam.empty()) {\n        priority_queue<State> next_beam;\n        for (int i = 0; i < BEAM_WIDTH && !beam.empty(); ++i) {\n            State current = beam.top();\n            beam.pop();\n\n            if (current.score > best_score) {\n                best_score = current.score;\n                best_path = current.path;\n            }\n\n            for (int next_root : adj[current.last_tile]) {\n                if (current.visited_tiles[next_root]) continue;\n\n                State next = current;\n                next.last_tile = next_root;\n                next.visited_tiles[next_root] = true;\n                next.score += tiles[next_root].sum;\n\n                // Find a path within the next tile to traverse all its cells\n                auto& cells = tiles[next_root].cells;\n                vector<vector<bool>> visited(N, vector<bool>(N, false));\n                vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n                queue<pair<int, int>> q;\n                q.push({current.last_x, current.last_y});\n                visited[current.last_x][current.last_y] = true;\n                bool found = false;\n                pair<int, int> end_pos;\n\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    if (t[x][y] == next_root && (x != current.last_x || y != current.last_y)) {\n                        end_pos = {x, y};\n                        found = true;\n                        break;\n                    }\n                    for (int k = 0; k < 4; ++k) {\n                        int nx = x + dx[k];\n                        int ny = y + dy[k];\n                        if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && t[nx][ny] == next_root) {\n                            visited[nx][ny] = true;\n                            parent[nx][ny] = {x, y};\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n\n                if (!found) continue;\n\n                // Reconstruct path within the tile\n                string tile_path;\n                pair<int, int> pos = end_pos;\n                while (pos != make_pair(current.last_x, current.last_y)) {\n                    auto [px, py] = parent[pos.first][pos.second];\n                    for (int k = 0; k < 4; ++k) {\n                        if (px == pos.first + dx[k] && py == pos.second + dy[k]) {\n                            tile_path += dir[k];\n                            break;\n                        }\n                    }\n                    pos = {px, py};\n                }\n                reverse(tile_path.begin(), tile_path.end());\n                next.path += tile_path;\n                next.last_x = end_pos.first;\n                next.last_y = end_pos.second;\n\n                next_beam.push(next);\n            }\n        }\n        beam = move(next_beam);\n    }\n\n    cout << best_path << endl;\n\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 30;\nconst int INF = 1e9;\nconst double ALPHA = 0.1; // Learning rate\n\nstruct Edge {\n    int to_i, to_j;\n    int dir; // 0: right (R), 1: down (D), 2: left (L), 3: up (U)\n    double weight;\n};\n\nvector<vector<vector<Edge>>> adj(N, vector<vector<Edge>>(N));\nvector<vector<double>> h(N, vector<double>(N-1, 5000.0)); // horizontal edges\nvector<vector<double>> v(N-1, vector<double>(N, 5000.0)); // vertical edges\n\nvoid init_adj() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (j + 1 < N) {\n                adj[i][j].push_back({i, j+1, 0, h[i][j]});\n            }\n            if (i + 1 < N) {\n                adj[i][j].push_back({i+1, j, 1, v[i][j]});\n            }\n            if (j - 1 >= 0) {\n                adj[i][j].push_back({i, j-1, 2, h[i][j-1]});\n            }\n            if (i - 1 >= 0) {\n                adj[i][j].push_back({i-1, j, 3, v[i-1][j]});\n            }\n        }\n    }\n}\n\nstring dijkstra(int si, int sj, int ti, int tj) {\n    vector<vector<double>> dist(N, vector<double>(N, INF));\n    vector<vector<pair<int, int>>> prev(N, vector<pair<int, int>>(N, {-1, -1}));\n    priority_queue<tuple<double, int, int>, vector<tuple<double, int, int>>, greater<>> pq;\n\n    dist[si][sj] = 0.0;\n    pq.emplace(0.0, si, sj);\n\n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top();\n        pq.pop();\n        if (i == ti && j == tj) break;\n        if (d > dist[i][j]) continue;\n        for (const auto& edge : adj[i][j]) {\n            int ni = edge.to_i;\n            int nj = edge.to_j;\n            double nd = d + edge.weight;\n            if (nd < dist[ni][nj]) {\n                dist[ni][nj] = nd;\n                prev[ni][nj] = {i, j};\n                pq.emplace(nd, ni, nj);\n            }\n        }\n    }\n\n    string path;\n    int ci = ti, cj = tj;\n    while (ci != si || cj != sj) {\n        auto [pi, pj] = prev[ci][cj];\n        if (pi == ci && pj == cj - 1) path += 'R';\n        else if (pi == ci && pj == cj + 1) path += 'L';\n        else if (pi == ci - 1 && pj == cj) path += 'D';\n        else if (pi == ci + 1 && pj == cj) path += 'U';\n        ci = pi;\n        cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nvoid update_weights(const string& path, int si, int sj, double total_length) {\n    int ci = si, cj = sj;\n    double path_length = 0.0;\n    for (char dir : path) {\n        int ni = ci, nj = cj;\n        if (dir == 'R') nj++;\n        else if (dir == 'L') nj--;\n        else if (dir == 'D') ni++;\n        else if (dir == 'U') ni--;\n\n        double edge_weight;\n        if (dir == 'R') edge_weight = h[ci][cj];\n        else if (dir == 'L') edge_weight = h[ci][cj-1];\n        else if (dir == 'D') edge_weight = v[ci][cj];\n        else if (dir == 'U') edge_weight = v[ci-1][cj];\n\n        path_length += edge_weight;\n        ci = ni;\n        cj = nj;\n    }\n\n    ci = si;\n    cj = sj;\n    for (char dir : path) {\n        int ni = ci, nj = cj;\n        if (dir == 'R') {\n            double new_weight = total_length * (h[ci][cj] / path_length);\n            h[ci][cj] = (1 - ALPHA) * h[ci][cj] + ALPHA * new_weight;\n            nj++;\n        } else if (dir == 'L') {\n            double new_weight = total_length * (h[ci][cj-1] / path_length);\n            h[ci][cj-1] = (1 - ALPHA) * h[ci][cj-1] + ALPHA * new_weight;\n            nj--;\n        } else if (dir == 'D') {\n            double new_weight = total_length * (v[ci][cj] / path_length);\n            v[ci][cj] = (1 - ALPHA) * v[ci][cj] + ALPHA * new_weight;\n            ni++;\n        } else if (dir == 'U') {\n            double new_weight = total_length * (v[ci-1][cj] / path_length);\n            v[ci-1][cj] = (1 - ALPHA) * v[ci-1][cj] + ALPHA * new_weight;\n            ni--;\n        }\n        ci = ni;\n        cj = nj;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    init_adj();\n\n    for (int k = 0; k < 1000; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n\n        string path = dijkstra(si, sj, ti, tj);\n        cout << path << endl;\n        cout.flush();\n\n        int total_length;\n        cin >> total_length;\n\n        update_weights(path, si, sj, total_length);\n    }\n\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_LEN = 12;\nconst vector<char> CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};\nconst vector<char> ALL_CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', '.'};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct State {\n    vector<string> grid;\n    int c; // number of matched strings\n    int d; // number of '.'\n    double energy;\n};\n\nvector<string> strings;\nint M;\n\nint count_matched(const vector<string>& grid) {\n    int matched = 0;\n    for (const string& s : strings) {\n        int k = s.size();\n        bool found = false;\n        // Check rows\n        for (int i = 0; i < N && !found; ++i) {\n            for (int j = 0; j < N && !found; ++j) {\n                bool match = true;\n                for (int p = 0; p < k; ++p) {\n                    if (grid[i][(j + p) % N] != s[p]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) {\n                    found = true;\n                    break;\n                }\n            }\n        }\n        // Check columns\n        for (int j = 0; j < N && !found; ++j) {\n            for (int i = 0; i < N && !found; ++i) {\n                bool match = true;\n                for (int p = 0; p < k; ++p) {\n                    if (grid[(i + p) % N][j] != s[p]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) {\n                    found = true;\n                    break;\n                }\n            }\n        }\n        if (found) {\n            matched++;\n        }\n    }\n    return matched;\n}\n\nint count_dots(const vector<string>& grid) {\n    int dots = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == '.') {\n                dots++;\n            }\n        }\n    }\n    return dots;\n}\n\ndouble compute_energy(int c, int d) {\n    if (c < M) {\n        return -1e8 * c / M;\n    } else {\n        return -1e8 * (2 * N * N) / (2 * N * N - d);\n    }\n}\n\nState get_initial_state() {\n    State state;\n    state.grid.resize(N, string(N, '.'));\n    state.d = N * N;\n    state.c = 0;\n    state.energy = compute_energy(state.c, state.d);\n\n    // Sort strings by length in descending order to place longer strings first\n    vector<pair<int, string>> sorted_strings;\n    for (const string& s : strings) {\n        sorted_strings.emplace_back(s.size(), s);\n    }\n    sort(sorted_strings.rbegin(), sorted_strings.rend());\n\n    for (const auto& [len, s] : sorted_strings) {\n        bool placed = false;\n        // Try to place horizontally\n        for (int i = 0; i < N && !placed; ++i) {\n            for (int j = 0; j < N && !placed; ++j) {\n                bool can_place = true;\n                for (int p = 0; p < len; ++p) {\n                    char c = state.grid[i][(j + p) % N];\n                    if (c != '.' && c != s[p]) {\n                        can_place = false;\n                        break;\n                    }\n                }\n                if (can_place) {\n                    for (int p = 0; p < len; ++p) {\n                        char& c = state.grid[i][(j + p) % N];\n                        if (c == '.') {\n                            c = s[p];\n                            state.d--;\n                        }\n                    }\n                    placed = true;\n                }\n            }\n        }\n        // Try to place vertically\n        for (int j = 0; j < N && !placed; ++j) {\n            for (int i = 0; i < N && !placed; ++i) {\n                bool can_place = true;\n                for (int p = 0; p < len; ++p) {\n                    char c = state.grid[(i + p) % N][j];\n                    if (c != '.' && c != s[p]) {\n                        can_place = false;\n                        break;\n                    }\n                }\n                if (can_place) {\n                    for (int p = 0; p < len; ++p) {\n                        char& c = state.grid[(i + p) % N][j];\n                        if (c == '.') {\n                            c = s[p];\n                            state.d--;\n                        }\n                    }\n                    placed = true;\n                }\n            }\n        }\n    }\n    state.c = count_matched(state.grid);\n    state.energy = compute_energy(state.c, state.d);\n    return state;\n}\n\nState simulated_annealing(State initial_state, double initial_temp, double final_temp, double cooling_rate, int iterations) {\n    State current = initial_state;\n    State best = current;\n    double temp = initial_temp;\n\n    for (int iter = 0; iter < iterations; ++iter) {\n        // Generate neighbor\n        int i = rng() % N;\n        int j = rng() % N;\n        char old_char = current.grid[i][j];\n        char new_char;\n        do {\n            new_char = CHARS[rng() % CHARS.size()]; // Only pick from A-H\n        } while (new_char == old_char);\n\n        // Compute new state\n        vector<string> new_grid = current.grid;\n        new_grid[i][j] = new_char;\n        int new_c = count_matched(new_grid);\n        int new_d = count_dots(new_grid);\n        double new_energy = compute_energy(new_c, new_d);\n\n        // Decide whether to accept\n        double delta_energy = new_energy - current.energy;\n        if (delta_energy < 0 || exp(-delta_energy / temp) > (double)rng() / rng.max()) {\n            current.grid = new_grid;\n            current.c = new_c;\n            current.d = new_d;\n            current.energy = new_energy;\n            if (current.energy < best.energy) {\n                best = current;\n            }\n        }\n\n        // Cool down\n        temp *= cooling_rate;\n        if (temp < final_temp) {\n            break;\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> M;\n    strings.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i];\n    }\n\n    // Parameters for simulated annealing\n    double initial_temp = 1e5;\n    double final_temp = 1e-4;\n    double cooling_rate = 0.9995;\n    int iterations = 2e6;\n\n    State initial_state = get_initial_state();\n    State best_state = simulated_annealing(initial_state, initial_temp, final_temp, cooling_rate, iterations);\n\n    // Ensure all characters are valid\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (best_state.grid[i][j] != '.' && (best_state.grid[i][j] < 'A' || best_state.grid[i][j] > 'H')) {\n                best_state.grid[i][j] = '.'; // Replace illegal characters with '.'\n            }\n        }\n    }\n\n    for (const string& row : best_state.grid) {\n        cout << row << '\\n';\n    }\n\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int INF = 1e9;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nint N, si, sj;\nvector<string> grid;\nvector<vector<int>> cost;\nvector<vector<bool>> is_road;\nvector<vector<vector<Point>>> visible;\nvector<vector<int>> dist;\nvector<vector<Point>> parent;\nvector<Point> road_points;\n\nvoid precompute_visible() {\n    visible.assign(N, vector<vector<Point>>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!is_road[i][j]) continue;\n            // Check left\n            for (int k = j - 1; k >= 0; --k) {\n                if (!is_road[i][k]) break;\n                visible[i][j].emplace_back(i, k);\n            }\n            // Check right\n            for (int k = j + 1; k < N; ++k) {\n                if (!is_road[i][k]) break;\n                visible[i][j].emplace_back(i, k);\n            }\n            // Check up\n            for (int k = i - 1; k >= 0; --k) {\n                if (!is_road[k][j]) break;\n                visible[i][j].emplace_back(k, j);\n            }\n            // Check down\n            for (int k = i + 1; k < N; ++k) {\n                if (!is_road[k][j]) break;\n                visible[i][j].emplace_back(k, j);\n            }\n        }\n    }\n}\n\nvoid dijkstra(Point start) {\n    dist.assign(N, vector<int>(N, INF));\n    parent.assign(N, vector<Point>(N, Point(-1, -1)));\n    priority_queue<pair<int, Point>, vector<pair<int, Point>>, greater<pair<int, Point>>> pq;\n    dist[start.x][start.y] = 0;\n    pq.emplace(0, start);\n    while (!pq.empty()) {\n        auto [current_dist, p] = pq.top();\n        pq.pop();\n        if (current_dist > dist[p.x][p.y]) continue;\n        for (int d = 0; d < 4; ++d) {\n            int nx = p.x + dx[d];\n            int ny = p.y + dy[d];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            if (!is_road[nx][ny]) continue;\n            int new_dist = current_dist + cost[nx][ny];\n            if (new_dist < dist[nx][ny]) {\n                dist[nx][ny] = new_dist;\n                parent[nx][ny] = p;\n                pq.emplace(new_dist, Point(nx, ny));\n            }\n        }\n    }\n}\n\nstring reconstruct_path(Point start, Point end) {\n    string path;\n    Point p = end;\n    while (!(p == start)) {\n        Point par = parent[p.x][p.y];\n        for (int d = 0; d < 4; ++d) {\n            if (par.x + dx[d] == p.x && par.y + dy[d] == p.y) {\n                path += dir[d];\n                break;\n            }\n        }\n        p = par;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nstring solve() {\n    // Precompute road points\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (is_road[i][j]) {\n                road_points.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Precompute visible squares for each road point\n    precompute_visible();\n\n    // Greedy approach: start from (si, sj) and cover all road points\n    vector<vector<bool>> covered(N, vector<bool>(N, false));\n    vector<Point> route;\n    route.emplace_back(si, sj);\n    covered[si][sj] = true;\n\n    // Mark all points visible from (si, sj) as covered\n    for (const auto& p : visible[si][sj]) {\n        covered[p.x][p.y] = true;\n    }\n\n    // Priority queue to keep track of uncovered road points sorted by distance\n    priority_queue<pair<int, Point>, vector<pair<int, Point>>, greater<pair<int, Point>>> pq;\n    dijkstra(route.back());\n    for (const auto& p : road_points) {\n        if (!covered[p.x][p.y]) {\n            pq.emplace(dist[p.x][p.y], p);\n        }\n    }\n\n    // While there are uncovered points\n    while (!pq.empty()) {\n        auto [current_dist, next_point] = pq.top();\n        pq.pop();\n        if (covered[next_point.x][next_point.y]) continue;\n\n        // Move to the next point\n        dijkstra(route.back());\n        string best_path = reconstruct_path(route.back(), next_point);\n        for (char c : best_path) {\n            if (c == 'U') route.emplace_back(route.back().x - 1, route.back().y);\n            else if (c == 'D') route.emplace_back(route.back().x + 1, route.back().y);\n            else if (c == 'L') route.emplace_back(route.back().x, route.back().y - 1);\n            else if (c == 'R') route.emplace_back(route.back().x, route.back().y + 1);\n        }\n        route.push_back(next_point);\n\n        // Mark all points visible from the new point as covered\n        for (const auto& p : visible[next_point.x][next_point.y]) {\n            if (!covered[p.x][p.y]) {\n                covered[p.x][p.y] = true;\n                // Update the priority queue with new distances\n                dijkstra(route.back());\n                pq.emplace(dist[p.x][p.y], p);\n            }\n        }\n    }\n\n    // Return to start\n    dijkstra(route.back());\n    string return_path = reconstruct_path(route.back(), Point(si, sj));\n    for (char c : return_path) {\n        if (c == 'U') route.emplace_back(route.back().x - 1, route.back().y);\n        else if (c == 'D') route.emplace_back(route.back().x + 1, route.back().y);\n        else if (c == 'L') route.emplace_back(route.back().x, route.back().y - 1);\n        else if (c == 'R') route.emplace_back(route.back().x, route.back().y + 1);\n    }\n\n    // Reconstruct the path string\n    string result;\n    for (size_t i = 1; i < route.size(); ++i) {\n        Point prev = route[i-1];\n        Point curr = route[i];\n        if (prev.x == curr.x && prev.y == curr.y - 1) result += 'R';\n        else if (prev.x == curr.x && prev.y == curr.y + 1) result += 'L';\n        else if (prev.x == curr.x - 1 && prev.y == curr.y) result += 'D';\n        else if (prev.x == curr.x + 1 && prev.y == curr.y) result += 'U';\n    }\n\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> si >> sj;\n    grid.resize(N);\n    cost.assign(N, vector<int>(N));\n    is_road.assign(N, vector<bool>(N, false));\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                is_road[i][j] = true;\n                cost[i][j] = grid[i][j] - '0';\n            }\n        }\n    }\n\n    string ans = solve();\n    cout << ans << endl;\n\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <map>\n#include <set>\n#include <climits>\n#include <cassert>\n\nusing namespace std;\n\nstruct Task {\n    int id;\n    vector<int> difficulty;\n    vector<int> dependencies;\n    vector<int> dependents;\n    int in_degree = 0;\n    bool completed = false;\n    int assigned_member = -1;\n    int start_day = -1;\n    int completion_day = -1;\n    int critical_path = 0;\n    int num_dependents = 0;\n};\n\nstruct Member {\n    int id;\n    vector<double> skills;\n    int current_task = -1;\n    int task_end_day = -1;\n    vector<pair<int, int>> task_history;\n    int current_load = 0;\n    double recent_performance = 1.0;\n    double performance_variance = 0.0;\n};\n\nclass Scheduler {\nprivate:\n    int N, M, K, R;\n    vector<Task> tasks;\n    vector<Member> members;\n    vector<vector<int>> adj;\n    vector<int> in_degree;\n    vector<int> topo_order;\n    vector<vector<int>> task_dependencies;\n    vector<vector<int>> task_dependents;\n    vector<vector<double>> skill_estimates;\n    vector<int> available_members;\n    int current_day = 0;\n    mt19937 rng;\n\n    void topological_sort() {\n        queue<int> q;\n        for (int i = 0; i < N; ++i) {\n            if (in_degree[i] == 0) {\n                q.push(i);\n            }\n        }\n        while (!q.empty()) {\n            int u = q.front();\n            q.pop();\n            topo_order.push_back(u);\n            for (int v : adj[u]) {\n                if (--in_degree[v] == 0) {\n                    q.push(v);\n                }\n            }\n        }\n    }\n\n    void calculate_critical_paths() {\n        vector<int> max_path(N, 0);\n        for (int u : topo_order) {\n            for (int v : tasks[u].dependents) {\n                max_path[v] = max(max_path[v], max_path[u] + 1);\n            }\n        }\n        for (int i = 0; i < N; ++i) {\n            tasks[i].critical_path = max_path[i];\n            tasks[i].num_dependents = tasks[i].dependents.size();\n        }\n    }\n\n    void update_skill_estimates(int member_id, int task_id, int completion_time) {\n        Member& member = members[member_id];\n        Task& task = tasks[task_id];\n        member.task_history.emplace_back(task_id, completion_time);\n\n        double expected_time = estimate_completion_time(member_id, task_id);\n        double error = expected_time - completion_time;\n        member.recent_performance = 0.7 * member.recent_performance + 0.3 * (expected_time / completion_time);\n        member.performance_variance = 0.7 * member.performance_variance + 0.3 * error * error;\n\n        for (int k = 0; k < K; ++k) {\n            double diff = task.difficulty[k];\n            double& skill = skill_estimates[member_id][k];\n            if (completion_time == 1) {\n                skill = max(skill, diff);\n            } else {\n                double weight = 0.5 + 0.4 * member.recent_performance;\n                skill = skill * (1 - weight) + (diff - (completion_time - 1)) * weight;\n            }\n        }\n    }\n\n    double estimate_completion_time(int member_id, int task_id) {\n        const Task& task = tasks[task_id];\n        double w = 0;\n        for (int k = 0; k < K; ++k) {\n            w += max(0.0, (double)task.difficulty[k] - skill_estimates[member_id][k]);\n        }\n        if (w == 0) {\n            return 1.0;\n        } else {\n            double buffer = 1.0 + sqrt(members[member_id].performance_variance);\n            return max(1.0, w + buffer);\n        }\n    }\n\n    bool is_task_ready(int task_id) {\n        for (int dep : tasks[task_id].dependencies) {\n            if (!tasks[dep].completed) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    void assign_tasks() {\n        vector<pair<int, int>> assignments;\n        for (int member_id : available_members) {\n            if (members[member_id].current_task != -1) continue;\n\n            int best_task = -1;\n            double best_score = -1;\n            for (int task_id : topo_order) {\n                Task& task = tasks[task_id];\n                if (task.completed || task.assigned_member != -1) continue;\n                if (!is_task_ready(task_id)) continue;\n\n                double est_time = estimate_completion_time(member_id, task_id);\n                double priority = (task.critical_path * 1000 + task.num_dependents * 200) / est_time;\n                if (priority > best_score) {\n                    best_score = priority;\n                    best_task = task_id;\n                }\n            }\n\n            if (best_task != -1) {\n                Task& task = tasks[best_task];\n                double est_time = estimate_completion_time(member_id, best_task);\n                task.assigned_member = member_id;\n                task.start_day = current_day;\n                members[member_id].current_task = best_task;\n                members[member_id].task_end_day = current_day + (int)est_time - 1;\n                members[member_id].current_load += (int)est_time;\n                assignments.emplace_back(member_id, best_task);\n            }\n        }\n\n        cout << assignments.size();\n        for (auto [member_id, task_id] : assignments) {\n            cout << \" \" << member_id + 1 << \" \" << task_id + 1;\n        }\n        cout << endl;\n    }\n\n    void process_completions(const vector<int>& completed_members) {\n        for (int member_id : completed_members) {\n            Member& member = members[member_id];\n            if (member.current_task == -1) continue;\n\n            Task& task = tasks[member.current_task];\n            task.completed = true;\n            task.completion_day = current_day;\n            member.current_task = -1;\n            member.task_end_day = -1;\n            member.current_load -= (current_day - task.start_day + 1);\n            available_members.push_back(member_id);\n\n            int completion_time = current_day - task.start_day + 1;\n            update_skill_estimates(member_id, task.id, completion_time);\n        }\n    }\n\npublic:\n    Scheduler(int N, int M, int K, int R, const vector<vector<int>>& difficulties, const vector<pair<int, int>>& dependencies)\n        : N(N), M(M), K(K), R(R), rng(random_device{}()) {\n        tasks.resize(N);\n        for (int i = 0; i < N; ++i) {\n            tasks[i].id = i;\n            tasks[i].difficulty = difficulties[i];\n        }\n\n        adj.resize(N);\n        in_degree.resize(N, 0);\n        task_dependencies.resize(N);\n        task_dependents.resize(N);\n        for (auto [u, v] : dependencies) {\n            u--; v--;\n            adj[u].push_back(v);\n            in_degree[v]++;\n            task_dependencies[v].push_back(u);\n            task_dependents[u].push_back(v);\n        }\n\n        for (int i = 0; i < N; ++i) {\n            tasks[i].dependencies = task_dependencies[i];\n            tasks[i].dependents = task_dependents[i];\n        }\n\n        topological_sort();\n        calculate_critical_paths();\n\n        members.resize(M);\n        for (int i = 0; i < M; ++i) {\n            members[i].id = i;\n            members[i].skills.resize(K, 0.0);\n            skill_estimates.push_back(vector<double>(K, 0.0));\n            available_members.push_back(i);\n        }\n    }\n\n    void run() {\n        while (current_day < 2000) {\n            current_day++;\n            assign_tasks();\n\n            int n;\n            cin >> n;\n            if (n == -1) {\n                break;\n            }\n            vector<int> completed_members(n);\n            for (int i = 0; i < n; ++i) {\n                cin >> completed_members[i];\n                completed_members[i]--;\n            }\n            process_completions(completed_members);\n        }\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<vector<int>> difficulties(N, vector<int>(K));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> difficulties[i][j];\n        }\n    }\n\n    vector<pair<int, int>> dependencies(R);\n    for (int i = 0; i < R; ++i) {\n        cin >> dependencies[i].first >> dependencies[i].second;\n    }\n\n    Scheduler scheduler(N, M, K, R, difficulties, dependencies);\n    scheduler.run();\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1000;\nconst int M = 50;\nconst int OFFICE_X = 400;\nconst int OFFICE_Y = 400;\n\nstruct Order {\n    int id;\n    int a, b, c, d;\n    int dist_to_office;\n    int dist_pickup_delivery;\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nvector<Order> orders;\nvector<int> selected_orders;\nvector<pair<int, int>> points;\nvector<int> route;\n\nint compute_total_distance(const vector<int>& route) {\n    int total = 0;\n    for (int i = 0; i < (int)route.size() - 1; ++i) {\n        auto [x1, y1] = points[route[i]];\n        auto [x2, y2] = points[route[i+1]];\n        total += manhattan(x1, y1, x2, y2);\n    }\n    return total;\n}\n\nbool check_precedence(const vector<int>& route) {\n    vector<int> pickup_pos(M + 1, -1);\n    vector<int> delivery_pos(M + 1, -1);\n    for (int i = 0; i < (int)route.size(); ++i) {\n        int idx = route[i];\n        if (idx >= 1 && idx <= M) {\n            pickup_pos[idx] = i;\n        } else if (idx >= M + 1 && idx <= 2 * M) {\n            delivery_pos[idx - M] = i;\n        }\n    }\n    for (int i = 1; i <= M; ++i) {\n        if (pickup_pos[i] == -1 || delivery_pos[i] == -1) {\n            return false;\n        }\n        if (pickup_pos[i] >= delivery_pos[i]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid two_opt_with_precedence(vector<int>& route) {\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 1; i < (int)route.size() - 2; ++i) {\n            for (int j = i + 1; j < (int)route.size() - 1; ++j) {\n                if (j - i == 1) continue;\n                vector<int> new_route = route;\n                reverse(new_route.begin() + i, new_route.begin() + j + 1);\n                if (check_precedence(new_route)) {\n                    int current_dist = compute_total_distance(route);\n                    int new_dist = compute_total_distance(new_route);\n                    if (new_dist < current_dist) {\n                        route = new_route;\n                        improved = true;\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid solve() {\n    // Read input\n    orders.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n        orders[i].id = i + 1;\n        orders[i].dist_to_office = manhattan(orders[i].a, orders[i].b, OFFICE_X, OFFICE_Y) +\n                                   manhattan(orders[i].c, orders[i].d, OFFICE_X, OFFICE_Y);\n        orders[i].dist_pickup_delivery = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n    }\n\n    // Select orders with smallest dist_to_office\n    sort(orders.begin(), orders.end(), [](const Order& a, const Order& b) {\n        return a.dist_to_office < b.dist_to_office;\n    });\n    selected_orders.clear();\n    for (int i = 0; i < M; ++i) {\n        selected_orders.push_back(orders[i].id);\n    }\n\n    // Prepare points: 0 is office, 1..M are pickups, M+1..2M are deliveries\n    points.clear();\n    points.emplace_back(OFFICE_X, OFFICE_Y); // 0\n    for (int i = 0; i < M; ++i) {\n        points.emplace_back(orders[i].a, orders[i].b); // 1..M\n    }\n    for (int i = 0; i < M; ++i) {\n        points.emplace_back(orders[i].c, orders[i].d); // M+1..2M\n    }\n\n    // Initial route: office -> pickups in order -> deliveries in order -> office\n    route.clear();\n    route.push_back(0);\n    for (int i = 1; i <= M; ++i) {\n        route.push_back(i);\n    }\n    for (int i = M + 1; i <= 2 * M; ++i) {\n        route.push_back(i);\n    }\n    route.push_back(0);\n\n    // Optimize with 2-opt while respecting precedence\n    two_opt_with_precedence(route);\n\n    // Output\n    cout << M;\n    for (int id : selected_orders) {\n        cout << \" \" << id;\n    }\n    cout << \"\\n\";\n\n    cout << route.size();\n    for (int idx : route) {\n        cout << \" \" << points[idx].first << \" \" << points[idx].second;\n    }\n    cout << \"\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\n#include <atcoder/dsu>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v;\n    int d;\n    int l;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 400;\n    int M = 1995;\n\n    vector<pair<int, int>> points(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> points[i].first >> points[i].second;\n    }\n\n    vector<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        int dx = points[edges[i].u].first - points[edges[i].v].first;\n        int dy = points[edges[i].u].second - points[edges[i].v].second;\n        edges[i].d = round(sqrt(dx * dx + dy * dy));\n    }\n\n    dsu uf(N);\n    int components = N;\n\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].l;\n        if (uf.same(edges[i].u, edges[i].v)) {\n            cout << 0 << '\\n';\n            cout.flush();\n            continue;\n        }\n        // Always accept edges that connect new components\n        if (components > 1) {\n            uf.merge(edges[i].u, edges[i].v);\n            components--;\n            cout << 1 << '\\n';\n            cout.flush();\n        } else {\n            // After ensuring connectivity, be more selective\n            if (edges[i].l <= 2 * edges[i].d) {\n                cout << 1 << '\\n';\n                cout.flush();\n            } else {\n                cout << 0 << '\\n';\n                cout.flush();\n            }\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int GRID_SIZE = 30;\nconst int TURNS = 300;\nconst int MAX_PETS = 20;\nconst int MAX_HUMANS = 10;\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nint N, M;\nvector<Pet> pets;\nvector<Human> humans;\nvector<vector<bool>> blocked(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\nvector<vector<int>> pet_grid(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\nvector<vector<int>> human_grid(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n\nconst vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst string dir_chars = \"udlrUDLR\";\n\nvoid initialize() {\n    cin >> N;\n    pets.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n        pet_grid[pets[i].x][pets[i].y]++;\n    }\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].x >> humans[i].y;\n        human_grid[humans[i].x][humans[i].y]++;\n    }\n    blocked.assign(GRID_SIZE + 2, vector<bool>(GRID_SIZE + 2, false));\n    for (int i = 0; i <= GRID_SIZE + 1; ++i) {\n        blocked[i][0] = blocked[i][GRID_SIZE + 1] = true;\n        blocked[0][i] = blocked[GRID_SIZE + 1][i] = true;\n    }\n}\n\nbool is_valid(int x, int y) {\n    return x >= 1 && x <= GRID_SIZE && y >= 1 && y <= GRID_SIZE && !blocked[x][y];\n}\n\nbool can_block(int x, int y) {\n    if (x < 1 || x > GRID_SIZE || y < 1 || y > GRID_SIZE) return false;\n    if (blocked[x][y] || pet_grid[x][y] > 0 || human_grid[x][y] > 0) return false;\n    for (auto [dx, dy] : directions) {\n        int nx = x + dx, ny = y + dy;\n        if (nx >= 1 && nx <= GRID_SIZE && ny >= 1 && ny <= GRID_SIZE && pet_grid[nx][ny] > 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvector<pair<int, int>> get_adjacent_passable(int x, int y) {\n    vector<pair<int, int>> res;\n    for (auto [dx, dy] : directions) {\n        int nx = x + dx, ny = y + dy;\n        if (is_valid(nx, ny)) {\n            res.emplace_back(nx, ny);\n        }\n    }\n    return res;\n}\n\nvoid update_grids() {\n    pet_grid.assign(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n    human_grid.assign(GRID_SIZE + 2, vector<int>(GRID_SIZE + 2, 0));\n    for (auto &pet : pets) {\n        pet_grid[pet.x][pet.y]++;\n    }\n    for (auto &human : humans) {\n        human_grid[human.x][human.y]++;\n    }\n}\n\nvoid move_pets() {\n    vector<string> moves(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> moves[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        auto &pet = pets[i];\n        int x = pet.x, y = pet.y;\n        for (char c : moves[i]) {\n            int dx = 0, dy = 0;\n            if (c == 'U') dx = -1;\n            else if (c == 'D') dx = 1;\n            else if (c == 'L') dy = -1;\n            else if (c == 'R') dy = 1;\n            int nx = x + dx, ny = y + dy;\n            if (is_valid(nx, ny)) {\n                x = nx;\n                y = ny;\n            }\n        }\n        pet.x = x;\n        pet.y = y;\n    }\n    update_grids();\n}\n\nvoid decide_human_actions() {\n    string actions;\n    for (int i = 0; i < M; ++i) {\n        auto &human = humans[i];\n        int x = human.x, y = human.y;\n        bool blocked_something = false;\n\n        // Try to block adjacent squares\n        for (auto [dx, dy] : directions) {\n            int nx = x + dx, ny = y + dy;\n            if (can_block(nx, ny)) {\n                blocked[nx][ny] = true;\n                if (dx == -1) actions += 'u';\n                else if (dx == 1) actions += 'd';\n                else if (dy == -1) actions += 'l';\n                else if (dy == 1) actions += 'r';\n                blocked_something = true;\n                break;\n            }\n        }\n\n        // If couldn't block, try to move\n        if (!blocked_something) {\n            vector<pair<int, int>> adj = get_adjacent_passable(x, y);\n            if (!adj.empty()) {\n                auto [nx, ny] = adj[rand() % adj.size()];\n                human.x = nx;\n                human.y = ny;\n                if (nx == x - 1) actions += 'U';\n                else if (nx == x + 1) actions += 'D';\n                else if (ny == y - 1) actions += 'L';\n                else if (ny == y + 1) actions += 'R';\n            } else {\n                actions += '.';\n            }\n        }\n    }\n\n    // Ensure the output has exactly M characters\n    if (actions.size() != M) {\n        actions = string(M, '.');\n    }\n\n    cout << actions << endl;\n    cout.flush();\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    initialize();\n    for (int turn = 0; turn < TURNS; ++turn) {\n        decide_human_actions();\n        move_pets();\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int INF = 1e9;\nconst vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst string dir_chars = \"UDLR\";\n\nint si, sj, ti, tj;\ndouble p;\nvector<string> h, v;\n\nvector<vector<int>> bfs_shortest_path() {\n    vector<vector<int>> dist(N, vector<int>(N, INF));\n    queue<pair<int, int>> q;\n    dist[ti][tj] = 0;\n    q.emplace(ti, tj);\n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && dist[ni][nj] == INF) {\n                dist[ni][nj] = dist[i][j] + 1;\n                q.emplace(ni, nj);\n            }\n        }\n    }\n    return dist;\n}\n\nstring construct_path(const vector<vector<int>>& dist) {\n    string path;\n    int i = si, j = sj;\n    while (i != ti || j != tj) {\n        vector<int> candidates;\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && dist[ni][nj] < dist[i][j]) {\n                candidates.push_back(d);\n            }\n        }\n        if (candidates.empty()) {\n            // Try to find any valid move if stuck\n            for (int d = 0; d < 4; ++d) {\n                auto [di, dj] = dirs[d];\n                int ni = i + di, nj = j + dj;\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                bool has_wall = false;\n                if (d == 0 && v[ni][j] == '1') has_wall = true;\n                if (d == 1 && v[i][j] == '1') has_wall = true;\n                if (d == 2 && h[i][nj] == '1') has_wall = true;\n                if (d == 3 && h[i][j] == '1') has_wall = true;\n                if (!has_wall) {\n                    candidates.push_back(d);\n                }\n            }\n        }\n        if (candidates.empty()) break;\n\n        // Choose the direction that minimizes distance to target\n        int best_d = candidates[0];\n        int best_dist = INF;\n        for (int d : candidates) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (dist[ni][nj] < best_dist) {\n                best_dist = dist[ni][nj];\n                best_d = d;\n            }\n        }\n        path += dir_chars[best_d];\n        i += dirs[best_d].first;\n        j += dirs[best_d].second;\n    }\n    return path;\n}\n\nstring make_robust_path(const string& path) {\n    if (path.empty()) return \"\";\n\n    string robust_path;\n    for (char c : path) {\n        robust_path += c;\n        if (p > 0.1) {\n            robust_path += c;\n            if (p > 0.3) {\n                robust_path += c;\n                if (p > 0.45) {\n                    robust_path += c;\n                }\n            }\n        }\n    }\n\n    // Ensure path length <= 200\n    if (robust_path.size() > 200) {\n        // Try to reduce redundancy while keeping path valid\n        robust_path = path;\n        if (robust_path.size() > 200) {\n            robust_path = path.substr(0, 200);\n        }\n    }\n    return robust_path;\n}\n\nvector<string> find_alternative_paths(const vector<vector<int>>& dist) {\n    vector<string> paths;\n    queue<tuple<int, int, string>> q;\n    q.emplace(si, sj, \"\");\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    visited[si][sj] = true;\n\n    while (!q.empty()) {\n        auto [i, j, path] = q.front();\n        q.pop();\n\n        if (i == ti && j == tj) {\n            paths.push_back(path);\n            continue;\n        }\n\n        for (int d = 0; d < 4; ++d) {\n            auto [di, dj] = dirs[d];\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            bool has_wall = false;\n            if (d == 0 && v[ni][j] == '1') has_wall = true;\n            if (d == 1 && v[i][j] == '1') has_wall = true;\n            if (d == 2 && h[i][nj] == '1') has_wall = true;\n            if (d == 3 && h[i][j] == '1') has_wall = true;\n            if (!has_wall && !visited[ni][nj]) {\n                visited[ni][nj] = true;\n                q.emplace(ni, nj, path + dir_chars[d]);\n            }\n        }\n    }\n    return paths;\n}\n\nint main() {\n    cin >> si >> sj >> ti >> tj >> p;\n    h.resize(N);\n    v.resize(N - 1);\n    for (int i = 0; i < N; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N - 1; ++i) {\n        cin >> v[i];\n    }\n\n    auto dist = bfs_shortest_path();\n    string path = construct_path(dist);\n    string robust_path = make_robust_path(path);\n\n    // If path is empty or too short, try to find alternative paths\n    if (path.empty() || robust_path.size() < 50) {\n        auto alternative_paths = find_alternative_paths(dist);\n        if (!alternative_paths.empty()) {\n            // Select the shortest alternative path\n            string best_alternative = alternative_paths[0];\n            for (const auto& alt : alternative_paths) {\n                if (alt.size() < best_alternative.size()) {\n                    best_alternative = alt;\n                }\n            }\n            robust_path = make_robust_path(best_alternative);\n        }\n    }\n\n    // If still too short, add more redundancy\n    if (robust_path.size() < 50) {\n        string temp_path = robust_path;\n        while (temp_path.size() < 200) {\n            temp_path += robust_path;\n        }\n        robust_path = temp_path.substr(0, 200);\n    }\n\n    cout << robust_path << endl;\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 30;\nconst int dx[4] = {0, -1, 0, 1};\nconst int dy[4] = {-1, 0, 1, 0};\nconst int to[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\n\nvector<string> initial_tiles;\nvector<vector<int>> tiles;\nvector<vector<int>> rotations;\nvector<vector<bool>> visited;\nvector<int> loop_lengths;\n\nint compute_loop_length(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    do {\n        int d2 = to[tiles[i][j]][d];\n        if (d2 == -1) return 0;\n        i += dx[d2];\n        j += dy[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (length > 1000) return 0; // Prevent infinite loops\n    } while (!(i == si && j == sj && d == sd));\n    return length;\n}\n\nvoid find_loops() {\n    visited.assign(N, vector<bool>(N, false));\n    loop_lengths.clear();\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (visited[i][j]) continue;\n            for (int d = 0; d < 4; ++d) {\n                int d2 = to[tiles[i][j]][d];\n                if (d2 == -1) continue;\n                int ni = i + dx[d2];\n                int nj = j + dy[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) % 4;\n                int length = compute_loop_length(i, j, d);\n                if (length > 0) {\n                    loop_lengths.push_back(length);\n                    for (int x = 0; x < N; ++x) {\n                        for (int y = 0; y < N; ++y) {\n                            if (visited[x][y]) continue;\n                            for (int dd = 0; dd < 4; ++dd) {\n                                if (compute_loop_length(x, y, dd) == length) {\n                                    visited[x][y] = true;\n                                }\n                            }\n                        }\n                    }\n                    goto next_tile;\n                }\n            }\n        }\n        next_tile:;\n    }\n    sort(loop_lengths.rbegin(), loop_lengths.rend());\n}\n\nlong long evaluate() {\n    find_loops();\n    if (loop_lengths.size() < 2) return 0;\n    return (long long)loop_lengths[0] * loop_lengths[1];\n}\n\nvoid apply_rotations() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int type = initial_tiles[i][j] - '0';\n            int rot = rotations[i][j];\n            if (type >= 0 && type <= 3) {\n                tiles[i][j] = (type + rot) % 4;\n            } else if (type >= 4 && type <= 5) {\n                tiles[i][j] = 4 + (rot % 2);\n            } else if (type >= 6 && type <= 7) {\n                tiles[i][j] = 6 + (rot % 2);\n            }\n        }\n    }\n}\n\nvoid solve() {\n    initial_tiles.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> initial_tiles[i];\n    }\n\n    rotations.assign(N, vector<int>(N, 0));\n    tiles.assign(N, vector<int>(N, 0));\n    apply_rotations();\n    long long best_score = evaluate();\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n    uniform_real_distribution<> prob(0.0, 1.0);\n\n    int iterations = 2000;\n    double temperature = 1000.0;\n    double cooling_rate = 0.99;\n\n    for (int iter = 0; iter < iterations; ++iter) {\n        int i = gen() % N;\n        int j = gen() % N;\n        int old_rot = rotations[i][j];\n        int new_rot = dis(gen);\n        rotations[i][j] = new_rot;\n        apply_rotations();\n        long long new_score = evaluate();\n        if (new_score > best_score || prob(gen) < exp((new_score - best_score) / temperature)) {\n            best_score = new_score;\n        } else {\n            rotations[i][j] = old_rot;\n            apply_rotations();\n        }\n        temperature *= cooling_rate;\n    }\n\n    string output;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            output += to_string(rotations[i][j]);\n        }\n    }\n    cout << output << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\nconst int rev[] = {2, 3, 0, 1};\n\nstruct State {\n    vector<vector<int>> board;\n    int empty_x, empty_y;\n    string moves;\n    int tree_size;\n    int steps;\n\n    State() : board(), empty_x(0), empty_y(0), moves(\"\"), tree_size(0), steps(0) {}\n    State(int N) : board(N, vector<int>(N)), empty_x(0), empty_y(0), moves(\"\"), tree_size(0), steps(0) {}\n\n    bool operator<(const State& other) const {\n        if (tree_size != other.tree_size) {\n            return tree_size > other.tree_size;\n        }\n        return steps < other.steps;\n    }\n};\n\nint calculate_tree_size(const vector<vector<int>>& board) {\n    int N = board.size();\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    int max_size = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0 || visited[i][j]) continue;\n\n            queue<pair<int, int>> q;\n            q.push({i, j});\n            visited[i][j] = true;\n            int size = 0;\n\n            while (!q.empty()) {\n                auto [x, y] = q.front();\n                q.pop();\n                size++;\n\n                int mask = board[x][y];\n                if (x > 0 && (mask & 2) && (board[x-1][y] & 8) && !visited[x-1][y]) {\n                    visited[x-1][y] = true;\n                    q.push({x-1, y});\n                }\n                if (x < N-1 && (mask & 8) && (board[x+1][y] & 2) && !visited[x+1][y]) {\n                    visited[x+1][y] = true;\n                    q.push({x+1, y});\n                }\n                if (y > 0 && (mask & 1) && (board[x][y-1] & 4) && !visited[x][y-1]) {\n                    visited[x][y-1] = true;\n                    q.push({x, y-1});\n                }\n                if (y < N-1 && (mask & 4) && (board[x][y+1] & 1) && !visited[x][y+1]) {\n                    visited[x][y+1] = true;\n                    q.push({x, y+1});\n                }\n            }\n\n            max_size = max(max_size, size);\n        }\n    }\n\n    return max_size;\n}\n\nvector<State> generate_next_states(const State& current, int N, int T) {\n    vector<State> next_states;\n\n    for (int d = 0; d < 4; ++d) {\n        int nx = current.empty_x + dx[d];\n        int ny = current.empty_y + dy[d];\n\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n\n        State next = current;\n        swap(next.board[current.empty_x][current.empty_y], next.board[nx][ny]);\n        next.empty_x = nx;\n        next.empty_y = ny;\n        next.moves += dir[d];\n        next.steps++;\n\n        if (next.steps > T) continue;\n\n        next.tree_size = calculate_tree_size(next.board);\n        next_states.push_back(next);\n    }\n\n    // Sort moves to prioritize those that might increase tree size\n    sort(next_states.begin(), next_states.end(), [](const State& a, const State& b) {\n        return a.tree_size > b.tree_size;\n    });\n\n    return next_states;\n}\n\nstring solve(int N, int T, const vector<string>& input) {\n    State initial(N);\n    int empty_count = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = input[i][j];\n            if (c == '0') {\n                initial.board[i][j] = 0;\n                initial.empty_x = i;\n                initial.empty_y = j;\n                empty_count++;\n            } else {\n                initial.board[i][j] = stoi(string(1, c), nullptr, 16);\n            }\n        }\n    }\n\n    if (empty_count != 1) {\n        return \"\";\n    }\n\n    initial.tree_size = calculate_tree_size(initial.board);\n\n    vector<State> current_level;\n    current_level.push_back(initial);\n\n    int beam_width = 200;  // Further increased beam width for better exploration\n    int max_tree_size = 0;\n    string best_moves;\n\n    auto start_time = chrono::high_resolution_clock::now();\n\n    for (int step = 0; step < T; ++step) {\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 2800) {  // Leave 200ms buffer\n            break;\n        }\n\n        vector<State> next_level;\n\n        for (const State& current : current_level) {\n            if (current.tree_size == N * N - 1) {\n                return current.moves;\n            }\n\n            if (current.tree_size > max_tree_size) {\n                max_tree_size = current.tree_size;\n                best_moves = current.moves;\n            }\n\n            vector<State> next_states = generate_next_states(current, N, T);\n            for (const State& next : next_states) {\n                next_level.push_back(next);\n            }\n        }\n\n        if (next_level.empty()) {\n            break;\n        }\n\n        sort(next_level.begin(), next_level.end());\n        if (static_cast<int>(next_level.size()) > beam_width) {\n            next_level.resize(beam_width);\n        }\n\n        current_level = next_level;\n    }\n\n    return best_moves;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    cin >> N >> T;\n    vector<string> input(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> input[i];\n    }\n\n    string result = solve(N, T, input);\n    cout << result << endl;\n\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_K = 100;\nconst int MAX_D = 10;\nconst int MAX_A = 100;\nconst int MAX_ITERATIONS = 200;\nconst int RADIUS = 10000;\nconst int RADIUS_SQ = RADIUS * RADIUS;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n    bool operator==(const Point& p) const {\n        return x == p.x && y == p.y;\n    }\n};\n\nstruct Line {\n    int px, py, qx, qy;\n    Line(int px, int py, int qx, int qy) : px(px), py(py), qx(qx), qy(qy) {}\n};\n\nint N, K;\nvector<int> a(MAX_D + 1);\nvector<Point> strawberries;\nvector<Line> cuts;\n\nint cross(const Point& o, const Point& a, const Point& b) {\n    return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n}\n\nint side(const Line& l, const Point& p) {\n    Point a(l.px, l.py), b(l.qx, l.qy);\n    long long c = (long long)(b.x - a.x) * (p.y - a.y) - (long long)(b.y - a.y) * (p.x - a.x);\n    if (c > 0) return 1;\n    if (c < 0) return -1;\n    return 0;\n}\n\nvector<vector<int>> regions;\n\nvoid init_regions() {\n    regions.clear();\n    regions.push_back(vector<int>());\n    for (int i = 0; i < N; ++i) {\n        regions[0].push_back(i);\n    }\n}\n\nvoid apply_cut(const Line& cut) {\n    vector<vector<int>> new_regions;\n    for (auto& region : regions) {\n        vector<int> left, right, on;\n        for (int idx : region) {\n            int s = side(cut, strawberries[idx]);\n            if (s == 1) left.push_back(idx);\n            else if (s == -1) right.push_back(idx);\n            else on.push_back(idx);\n        }\n        if (!left.empty()) new_regions.push_back(left);\n        if (!right.empty()) new_regions.push_back(right);\n    }\n    regions = new_regions;\n}\n\nint compute_score() {\n    vector<int> counts(MAX_D + 1, 0);\n    for (auto& region : regions) {\n        int cnt = region.size();\n        if (cnt <= MAX_D) counts[cnt]++;\n    }\n    int score = 0;\n    for (int d = 1; d <= MAX_D; ++d) {\n        score += min(a[d], counts[d]);\n    }\n    return score;\n}\n\nLine generate_line(int idx1, int idx2) {\n    Point p1 = strawberries[idx1];\n    Point p2 = strawberries[idx2];\n    return Line(p1.x, p1.y, p2.x, p2.y);\n}\n\nLine generate_best_line() {\n    Line best_line(0, 0, 0, 0);\n    int best_score = -1;\n    for (int i = 0; i < MAX_ITERATIONS; ++i) {\n        int idx1 = rand() % N;\n        int idx2 = rand() % N;\n        while (idx1 == idx2) idx2 = rand() % N;\n        Line candidate = generate_line(idx1, idx2);\n        vector<vector<int>> temp_regions = regions;\n        apply_cut(candidate);\n        int current_score = compute_score();\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_line = candidate;\n        }\n        regions = temp_regions;\n    }\n    return best_line;\n}\n\nvoid solve() {\n    cin >> N >> K;\n    for (int d = 1; d <= MAX_D; ++d) {\n        cin >> a[d];\n    }\n    strawberries.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> strawberries[i].x >> strawberries[i].y;\n    }\n\n    init_regions();\n    int current_score = compute_score();\n    for (int k = 0; k < K; ++k) {\n        Line best_line = generate_best_line();\n        apply_cut(best_line);\n        int new_score = compute_score();\n        if (new_score > current_score) {\n            current_score = new_score;\n            cuts.push_back(best_line);\n        } else {\n            regions = vector<vector<int>>(1, vector<int>(N));\n            for (int i = 0; i < N; ++i) {\n                regions[0][i] = i;\n            }\n            current_score = compute_score();\n        }\n    }\n\n    cout << cuts.size() << endl;\n    for (auto& cut : cuts) {\n        cout << cut.px << \" \" << cut.py << \" \" << cut.qx << \" \" << cut.qy << endl;\n    }\n}\n\nint main() {\n    srand(time(0));\n    solve();\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <cmath>\n#include <unordered_set>\n#include <chrono>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nint N, M;\nvector<Point> initial_dots;\nvector<vector<bool>> has_dot;\nvector<Rectangle> rectangles;\nint center;\nlong long total_weight = 0;\n\nlong long weight(int x, int y) {\n    long long dx = x - center;\n    long long dy = y - center;\n    return dx * dx + dy * dy + 1;\n}\n\nvoid precompute_weights() {\n    center = (N - 1) / 2;\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y < N; ++y) {\n            total_weight += weight(x, y);\n        }\n    }\n}\n\nbool is_valid_point(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_perimeter(const Rectangle& rect) {\n    vector<Point> points = {rect.p1, rect.p2, rect.p3, rect.p4};\n    for (int i = 0; i < 4; ++i) {\n        Point a = points[i];\n        Point b = points[(i + 1) % 4];\n        if (a.x == b.x) {\n            int x = a.x;\n            int y1 = min(a.y, b.y);\n            int y2 = max(a.y, b.y);\n            for (int y = y1; y <= y2; ++y) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        } else if (a.y == b.y) {\n            int y = a.y;\n            int x1 = min(a.x, b.x);\n            int x2 = max(a.x, b.x);\n            for (int x = x1; x <= x2; ++x) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        } else {\n            int dx = b.x - a.x;\n            int dy = b.y - a.y;\n            if (abs(dx) != abs(dy)) {\n                return false;\n            }\n            int step = dx > 0 ? 1 : -1;\n            for (int x = a.x, y = a.y; x != b.x; x += step, y += step * dy / dx) {\n                if (has_dot[x][y] && !(x == a.x && y == a.y) && !(x == b.x && y == b.y)) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool check_overlap(const Rectangle& new_rect) {\n    for (const auto& rect : rectangles) {\n        vector<Point> new_points = {new_rect.p1, new_rect.p2, new_rect.p3, new_rect.p4};\n        vector<Point> old_points = {rect.p1, rect.p2, rect.p3, rect.p4};\n        for (int i = 0; i < 4; ++i) {\n            Point a1 = new_points[i];\n            Point b1 = new_points[(i + 1) % 4];\n            for (int j = 0; j < 4; ++j) {\n                Point a2 = old_points[j];\n                Point b2 = old_points[(j + 1) % 4];\n                if (a1 == a2 && b1 == b2) return true;\n                if (a1 == b2 && b1 == a2) return true;\n            }\n        }\n    }\n    return false;\n}\n\nvector<Rectangle> generate_candidates() {\n    vector<Rectangle> candidates;\n    for (int i = 0; i < initial_dots.size(); ++i) {\n        for (int j = i + 1; j < initial_dots.size(); ++j) {\n            Point p2 = initial_dots[i];\n            Point p3 = initial_dots[j];\n            // Axis-aligned rectangle\n            {\n                Point p1(p2.x, p3.y);\n                Point p4(p3.x, p2.y);\n                if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                    Rectangle rect(p1, p2, p3, p4);\n                    if (check_perimeter(rect) && !check_overlap(rect)) {\n                        candidates.push_back(rect);\n                    }\n                }\n            }\n            // 45-degree rotated rectangle\n            {\n                int dx = p3.x - p2.x;\n                int dy = p3.y - p2.y;\n                if (abs(dx) == abs(dy)) {\n                    Point p1(p2.x + dy, p2.y - dx);\n                    Point p4(p3.x + dy, p3.y - dx);\n                    if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                        Rectangle rect(p1, p2, p3, p4);\n                        if (check_perimeter(rect) && !check_overlap(rect)) {\n                            candidates.push_back(rect);\n                        }\n                    }\n                    p1 = Point(p2.x - dy, p2.y + dx);\n                    p4 = Point(p3.x - dy, p3.y + dx);\n                    if (is_valid_point(p1.x, p1.y) && is_valid_point(p4.x, p4.y)) {\n                        Rectangle rect(p1, p2, p3, p4);\n                        if (check_perimeter(rect) && !check_overlap(rect)) {\n                            candidates.push_back(rect);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return candidates;\n}\n\nvoid solve() {\n    precompute_weights();\n    has_dot.assign(N, vector<bool>(N, false));\n    for (const auto& dot : initial_dots) {\n        has_dot[dot.x][dot.y] = true;\n    }\n\n    auto start_time = chrono::high_resolution_clock::now();\n    while (true) {\n        auto candidates = generate_candidates();\n        if (candidates.empty()) break;\n\n        Rectangle best_rect;\n        long long best_score = -1;\n        for (const auto& rect : candidates) {\n            long long current_score = weight(rect.p1.x, rect.p1.y);\n            if (current_score > best_score) {\n                best_score = current_score;\n                best_rect = rect;\n            }\n        }\n\n        if (best_score == -1) break;\n\n        rectangles.push_back(best_rect);\n        has_dot[best_rect.p1.x][best_rect.p1.y] = true;\n        initial_dots.push_back(best_rect.p1);\n\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 4500) break;\n    }\n\n    cout << rectangles.size() << endl;\n    for (const auto& rect : rectangles) {\n        cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n             << rect.p2.x << \" \" << rect.p2.y << \" \"\n             << rect.p3.x << \" \" << rect.p3.y << \" \"\n             << rect.p4.x << \" \" << rect.p4.y << endl;\n    }\n}\n\nint main() {\n    cin >> N >> M;\n    initial_dots.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> initial_dots[i].x >> initial_dots[i].y;\n    }\n    solve();\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <cstring>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n#include <numeric>\n\nusing namespace std;\n\nconst int N = 10;\nconst int TOTAL_CANDIES = 100;\nconst vector<char> DIRECTIONS = {'F', 'B', 'L', 'R'};\n\nstruct Grid {\n    int cells[N][N];\n    int empty_count;\n\n    Grid() {\n        memset(cells, 0, sizeof(cells));\n        empty_count = N * N;\n    }\n\n    void place_candy(int pos, int flavor) {\n        int idx = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] == 0) {\n                    if (++idx == pos) {\n                        cells[i][j] = flavor;\n                        empty_count--;\n                        return;\n                    }\n                }\n            }\n        }\n    }\n\n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; ++j) {\n                int write_pos = N - 1;\n                for (int i = N - 1; i >= 0; --i) {\n                    if (cells[i][j] != 0) {\n                        cells[write_pos--][j] = cells[i][j];\n                    }\n                }\n                for (int i = write_pos; i >= 0; --i) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; ++j) {\n                int write_pos = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (cells[i][j] != 0) {\n                        cells[write_pos++][j] = cells[i][j];\n                    }\n                }\n                for (int i = write_pos; i < N; ++i) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; ++i) {\n                int write_pos = 0;\n                for (int j = 0; j < N; ++j) {\n                    if (cells[i][j] != 0) {\n                        cells[i][write_pos++] = cells[i][j];\n                    }\n                }\n                for (int j = write_pos; j < N; ++j) {\n                    cells[i][j] = 0;\n                }\n            }\n        } else if (dir == 'R') {\n            for (int i = 0; i < N; ++i) {\n                int write_pos = N - 1;\n                for (int j = N - 1; j >= 0; --j) {\n                    if (cells[i][j] != 0) {\n                        cells[i][write_pos--] = cells[i][j];\n                    }\n                }\n                for (int j = write_pos; j >= 0; --j) {\n                    cells[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    vector<int> get_connected_components() {\n        vector<int> component_sizes;\n        bool visited[N][N] = {false};\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0 && !visited[i][j]) {\n                    int flavor = cells[i][j];\n                    int size = 0;\n                    queue<pair<int, int>> q;\n                    q.push({i, j});\n                    visited[i][j] = true;\n\n                    while (!q.empty()) {\n                        auto [x, y] = q.front();\n                        q.pop();\n                        size++;\n\n                        for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                            int nx = x + dx;\n                            int ny = y + dy;\n                            if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && cells[nx][ny] == flavor) {\n                                visited[nx][ny] = true;\n                                q.push({nx, ny});\n                            }\n                        }\n                    }\n                    component_sizes.push_back(size);\n                }\n            }\n        }\n        return component_sizes;\n    }\n\n    double evaluate() {\n        auto components = get_connected_components();\n        double sum_sq = 0;\n        for (int size : components) {\n            sum_sq += size * size;\n        }\n        int counts[4] = {0};\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    counts[cells[i][j]]++;\n                }\n            }\n        }\n        double denom = 0;\n        for (int i = 1; i <= 3; ++i) {\n            denom += counts[i] * counts[i];\n        }\n        if (denom == 0) return 0;\n        return sum_sq / denom;\n    }\n\n    int count_adjacent_pairs() {\n        int pairs = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                        int ni = i + dx;\n                        int nj = j + dy;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N && cells[ni][nj] == cells[i][j]) {\n                            pairs++;\n                        }\n                    }\n                }\n            }\n        }\n        return pairs / 2; // Each pair is counted twice\n    }\n\n    int count_potential_connections() {\n        int potential = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                        int ni = i + dx;\n                        int nj = j + dy;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N && cells[ni][nj] == 0) {\n                            potential++;\n                        }\n                    }\n                }\n            }\n        }\n        return potential;\n    }\n\n    double calculate_cluster_quality() {\n        auto components = get_connected_components();\n        if (components.empty()) return 0;\n        double max_size = *max_element(components.begin(), components.end());\n        double avg_size = accumulate(components.begin(), components.end(), 0.0) / components.size();\n        return max_size / avg_size;\n    }\n\n    int count_isolated_candies() {\n        int isolated = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    bool is_isolated = true;\n                    for (auto [dx, dy] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                        int ni = i + dx;\n                        int nj = j + dy;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N && cells[ni][nj] == cells[i][j]) {\n                            is_isolated = false;\n                            break;\n                        }\n                    }\n                    if (is_isolated) {\n                        isolated++;\n                    }\n                }\n            }\n        }\n        return isolated;\n    }\n\n    double calculate_flavor_distribution() {\n        int flavor_counts[4] = {0};\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (cells[i][j] != 0) {\n                    flavor_counts[cells[i][j]]++;\n                }\n            }\n        }\n        double variance = 0;\n        double mean = (flavor_counts[1] + flavor_counts[2] + flavor_counts[3]) / 3.0;\n        for (int i = 1; i <= 3; ++i) {\n            variance += (flavor_counts[i] - mean) * (flavor_counts[i] - mean);\n        }\n        return variance;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<int> flavors(TOTAL_CANDIES);\n    for (int i = 0; i < TOTAL_CANDIES; ++i) {\n        cin >> flavors[i];\n    }\n\n    Grid grid;\n    for (int t = 0; t < TOTAL_CANDIES; ++t) {\n        int pos;\n        cin >> pos;\n        grid.place_candy(pos, flavors[t]);\n\n        if (t == TOTAL_CANDIES - 1) {\n            break;\n        }\n\n        double best_score = -1;\n        char best_dir = 'F';\n        for (char dir : DIRECTIONS) {\n            Grid temp_grid = grid;\n            temp_grid.tilt(dir);\n            double eval_score = temp_grid.evaluate();\n            int pairs = temp_grid.count_adjacent_pairs();\n            int potential = temp_grid.count_potential_connections();\n            double cluster_quality = temp_grid.calculate_cluster_quality();\n            int isolated = temp_grid.count_isolated_candies();\n            double distribution = temp_grid.calculate_flavor_distribution();\n            double score = eval_score * 0.4 + pairs * 0.25 + potential * 0.1 + cluster_quality * 0.15 - isolated * 0.05 - distribution * 0.05;\n            if (score > best_score) {\n                best_score = score;\n                best_dir = dir;\n            }\n        }\n        grid.tilt(best_dir);\n        cout << best_dir << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <queue>\n#include <unordered_set>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Graph {\n    int N;\n    vector<vector<bool>> adj;\n    vector<int> degree;\n    int edge_count;\n    vector<int> degree_seq;\n    int connected_components;\n    int diameter;\n    double clustering_coefficient;\n    double density;\n    vector<double> spectrum;\n    int triangle_count;\n\n    Graph(int n) : N(n), adj(n, vector<bool>(n, false)), degree(n, 0), edge_count(0),\n                   connected_components(0), diameter(0), clustering_coefficient(0.0),\n                   density(0.0), triangle_count(0) {}\n\n    void add_edge(int u, int v) {\n        if (!adj[u][v]) {\n            adj[u][v] = adj[v][u] = true;\n            degree[u]++;\n            degree[v]++;\n            edge_count++;\n        }\n    }\n\n    void compute_degree_seq() {\n        degree_seq = degree;\n        sort(degree_seq.begin(), degree_seq.end(), greater<int>());\n    }\n\n    void compute_connected_components() {\n        vector<bool> visited(N, false);\n        connected_components = 0;\n        for (int i = 0; i < N; ++i) {\n            if (!visited[i]) {\n                connected_components++;\n                queue<int> q;\n                q.push(i);\n                visited[i] = true;\n                while (!q.empty()) {\n                    int u = q.front();\n                    q.pop();\n                    for (int v = 0; v < N; ++v) {\n                        if (adj[u][v] && !visited[v]) {\n                            visited[v] = true;\n                            q.push(v);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    void compute_diameter() {\n        diameter = 0;\n        for (int i = 0; i < N; ++i) {\n            vector<int> dist(N, -1);\n            queue<int> q;\n            q.push(i);\n            dist[i] = 0;\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (int v = 0; v < N; ++v) {\n                    if (adj[u][v] && dist[v] == -1) {\n                        dist[v] = dist[u] + 1;\n                        q.push(v);\n                    }\n                }\n            }\n            diameter = max(diameter, *max_element(dist.begin(), dist.end()));\n        }\n    }\n\n    void compute_clustering_coefficient() {\n        clustering_coefficient = 0.0;\n        for (int i = 0; i < N; ++i) {\n            if (degree[i] < 2) continue;\n            int triangles = 0;\n            for (int j = 0; j < N; ++j) {\n                if (adj[i][j]) {\n                    for (int k = j + 1; k < N; ++k) {\n                        if (adj[i][k] && adj[j][k]) {\n                            triangles++;\n                        }\n                    }\n                }\n            }\n            clustering_coefficient += 2.0 * triangles / (degree[i] * (degree[i] - 1));\n        }\n        clustering_coefficient /= N;\n    }\n\n    void compute_density() {\n        density = 2.0 * edge_count / (N * (N - 1));\n    }\n\n    void compute_spectrum() {\n        spectrum.resize(N);\n        for (int i = 0; i < N; ++i) {\n            spectrum[i] = degree[i]; // Placeholder for actual eigenvalues\n        }\n        sort(spectrum.begin(), spectrum.end(), greater<double>());\n    }\n\n    void compute_triangle_count() {\n        triangle_count = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (adj[i][j]) {\n                    for (int k = j + 1; k < N; ++k) {\n                        if (adj[i][k] && adj[j][k]) {\n                            triangle_count++;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    string to_string() const {\n        string s;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                s += adj[i][j] ? '1' : '0';\n            }\n        }\n        return s;\n    }\n};\n\nvector<Graph> generate_graphs(int M, int N) {\n    vector<Graph> graphs;\n    for (int k = 0; k < M; ++k) {\n        Graph g(N);\n        // More distinct graph structures\n        if (k < N) {\n            // Star graphs\n            for (int i = 1; i <= k; ++i) {\n                g.add_edge(0, i);\n            }\n        } else if (k < 2*N) {\n            // Path graphs with additional edges\n            for (int i = 0; i < N-1; ++i) {\n                g.add_edge(i, i+1);\n            }\n            for (int i = 0; i < k - (N-1); ++i) {\n                g.add_edge(0, i+2);\n            }\n        } else if (k < 3*N) {\n            // Wheel graphs\n            for (int i = 1; i < N; ++i) {\n                g.add_edge(0, i);\n            }\n            for (int i = 1; i < N-1; ++i) {\n                g.add_edge(i, i+1);\n            }\n            g.add_edge(N-1, 1);\n            for (int i = 0; i < k - (2*N-1); ++i) {\n                g.add_edge(0, i+1);\n            }\n        } else {\n            // Regular graphs with varying degrees\n            int degree = min(k / N, N-1);\n            for (int i = 0; i < N; ++i) {\n                for (int j = i+1; j < N && g.degree[i] < degree; ++j) {\n                    if (g.degree[j] < degree) {\n                        g.add_edge(i, j);\n                    }\n                }\n            }\n        }\n        g.compute_degree_seq();\n        g.compute_connected_components();\n        g.compute_diameter();\n        g.compute_clustering_coefficient();\n        g.compute_density();\n        g.compute_spectrum();\n        g.compute_triangle_count();\n        graphs.push_back(g);\n    }\n    return graphs;\n}\n\nvector<int> compute_degree_sequence(const string& s, int N) {\n    vector<int> degree(N, 0);\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (s[idx++] == '1') {\n                degree[i]++;\n                degree[j]++;\n            }\n        }\n    }\n    sort(degree.begin(), degree.end(), greater<int>());\n    return degree;\n}\n\nint count_edges(const string& s) {\n    return count(s.begin(), s.end(), '1');\n}\n\nint count_connected_components(const string& s, int N) {\n    vector<vector<bool>> adj(N, vector<bool>(N, false));\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            adj[i][j] = adj[j][i] = (s[idx++] == '1');\n        }\n    }\n    vector<bool> visited(N, false);\n    int components = 0;\n    for (int i = 0; i < N; ++i) {\n        if (!visited[i]) {\n            components++;\n            queue<int> q;\n            q.push(i);\n            visited[i] = true;\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (int v = 0; v < N; ++v) {\n                    if (adj[u][v] && !visited[v]) {\n                        visited[v] = true;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n    return components;\n}\n\nint compute_diameter(const string& s, int N) {\n    vector<vector<bool>> adj(N, vector<bool>(N, false));\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            adj[i][j] = adj[j][i] = (s[idx++] == '1');\n        }\n    }\n    int diameter = 0;\n    for (int i = 0; i < N; ++i) {\n        vector<int> dist(N, -1);\n        queue<int> q;\n        q.push(i);\n        dist[i] = 0;\n        while (!q.empty()) {\n            int u = q.front();\n            q.pop();\n            for (int v = 0; v < N; ++v) {\n                if (adj[u][v] && dist[v] == -1) {\n                    dist[v] = dist[u] + 1;\n                    q.push(v);\n                }\n            }\n        }\n        diameter = max(diameter, *max_element(dist.begin(), dist.end()));\n    }\n    return diameter;\n}\n\ndouble compute_clustering_coefficient(const string& s, int N) {\n    vector<vector<bool>> adj(N, vector<bool>(N, false));\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            adj[i][j] = adj[j][i] = (s[idx++] == '1');\n        }\n    }\n    double clustering_coefficient = 0.0;\n    for (int i = 0; i < N; ++i) {\n        int degree_i = 0;\n        for (int j = 0; j < N; ++j) {\n            if (adj[i][j]) degree_i++;\n        }\n        if (degree_i < 2) continue;\n        int triangles = 0;\n        for (int j = 0; j < N; ++j) {\n            if (adj[i][j]) {\n                for (int k = j + 1; k < N; ++k) {\n                    if (adj[i][k] && adj[j][k]) {\n                        triangles++;\n                    }\n                }\n            }\n        }\n        clustering_coefficient += 2.0 * triangles / (degree_i * (degree_i - 1));\n    }\n    return clustering_coefficient / N;\n}\n\ndouble compute_density(const string& s, int N) {\n    int edges = count_edges(s);\n    return 2.0 * edges / (N * (N - 1));\n}\n\nvector<double> compute_spectrum(const string& s, int N) {\n    vector<vector<bool>> adj(N, vector<bool>(N, false));\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            adj[i][j] = adj[j][i] = (s[idx++] == '1');\n        }\n    }\n    vector<double> spectrum(N);\n    for (int i = 0; i < N; ++i) {\n        spectrum[i] = 0;\n        for (int j = 0; j < N; ++j) {\n            if (adj[i][j]) spectrum[i]++;\n        }\n    }\n    sort(spectrum.begin(), spectrum.end(), greater<double>());\n    return spectrum;\n}\n\nint compute_triangle_count(const string& s, int N) {\n    vector<vector<bool>> adj(N, vector<bool>(N, false));\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            adj[i][j] = adj[j][i] = (s[idx++] == '1');\n        }\n    }\n    int triangles = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (adj[i][j]) {\n                for (int k = j + 1; k < N; ++k) {\n                    if (adj[i][k] && adj[j][k]) {\n                        triangles++;\n                    }\n                }\n            }\n        }\n    }\n    return triangles;\n}\n\ndouble compute_distance(int edges_H, const vector<int>& degree_seq_H, int components_H,\n                        int diameter_H, double cc_H, double density_H, const vector<double>& spectrum_H,\n                        int triangles_H, int edges_G, const vector<int>& degree_seq_G, int components_G,\n                        int diameter_G, double cc_G, double density_G, const vector<double>& spectrum_G,\n                        int triangles_G, double eps) {\n    // Fine-tuned weights based on empirical performance\n    double edge_weight = 0.1 + 0.1 * (1 - eps);\n    double degree_weight = 0.2 + 0.2 * (1 - eps);\n    double component_weight = 0.1 + 0.2 * eps;\n    double diameter_weight = 0.1 + 0.1 * eps;\n    double cc_weight = 0.05 + 0.05 * eps;\n    double density_weight = 0.05 + 0.05 * eps;\n    double spectrum_weight = 0.1 + 0.1 * eps;\n    double triangle_weight = 0.2 + 0.2 * eps;\n\n    double edge_diff = abs(edges_H - edges_G);\n    double degree_diff = 0.0;\n    for (int i = 0; i < degree_seq_H.size(); ++i) {\n        degree_diff += abs(degree_seq_H[i] - degree_seq_G[i]);\n    }\n    degree_diff = log(1 + degree_diff); // Logarithmic scaling\n\n    double component_diff = abs(components_H - components_G);\n    double diameter_diff = abs(diameter_H - diameter_G);\n    double cc_diff = abs(cc_H - cc_G);\n    double density_diff = abs(density_H - density_G);\n    double spectrum_diff = 0.0;\n    for (int i = 0; i < spectrum_H.size(); ++i) {\n        spectrum_diff += abs(spectrum_H[i] - spectrum_G[i]);\n    }\n    spectrum_diff = log(1 + spectrum_diff); // Logarithmic scaling\n\n    double triangle_diff = abs(triangles_H - triangles_G);\n    triangle_diff = log(1 + triangle_diff); // Logarithmic scaling\n\n    return edge_weight * edge_diff +\n           degree_weight * degree_diff +\n           component_weight * component_diff +\n           diameter_weight * diameter_diff +\n           cc_weight * cc_diff +\n           density_weight * density_diff +\n           spectrum_weight * spectrum_diff +\n           triangle_weight * triangle_diff;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    cin >> M >> eps;\n\n    // Adaptive N selection with special cases\n    int N = min(100, max(4, M + 5));\n    if (M <= 20) N = min(100, max(4, M + 3));\n    if (M >= 80) N = min(100, max(4, M + 10));\n    if (eps > 0.1) N = min(100, N + 5);\n    if (eps > 0.2) N = min(100, N + 5);\n    if (eps > 0.3) N = min(100, N + 10);\n\n    vector<Graph> graphs = generate_graphs(M, N);\n\n    // Output the graphs\n    cout << N << '\\n';\n    for (const auto& g : graphs) {\n        cout << g.to_string() << '\\n';\n    }\n    cout.flush();\n\n    // Precompute invariants for all G_k\n    vector<int> edge_counts;\n    vector<vector<int>> degree_seqs;\n    vector<int> component_counts;\n    vector<int> diameter_counts;\n    vector<double> cc_counts;\n    vector<double> density_counts;\n    vector<vector<double>> spectra;\n    vector<int> triangle_counts;\n    for (const auto& g : graphs) {\n        edge_counts.push_back(g.edge_count);\n        degree_seqs.push_back(g.degree_seq);\n        component_counts.push_back(g.connected_components);\n        diameter_counts.push_back(g.diameter);\n        cc_counts.push_back(g.clustering_coefficient);\n        density_counts.push_back(g.density);\n        spectra.push_back(g.spectrum);\n        triangle_counts.push_back(g.triangle_count);\n    }\n\n    // Process queries\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // Compute invariants for H\n        int edges_H = count_edges(H);\n        vector<int> degree_seq_H = compute_degree_sequence(H, N);\n        int components_H = count_connected_components(H, N);\n        int diameter_H = compute_diameter(H, N);\n        double cc_H = compute_clustering_coefficient(H, N);\n        double density_H = compute_density(H, N);\n        vector<double> spectrum_H = compute_spectrum(H, N);\n        int triangles_H = compute_triangle_count(H, N);\n\n        // Find the closest G_k\n        double min_dist = 1e18;\n        int best_k = 0;\n        for (int k = 0; k < M; ++k) {\n            double dist = compute_distance(edges_H, degree_seq_H, components_H, diameter_H, cc_H, density_H, spectrum_H, triangles_H,\n                                          edge_counts[k], degree_seqs[k], component_counts[k], diameter_counts[k],\n                                          cc_counts[k], density_counts[k], spectra[k], triangle_counts[k], eps);\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_k = k;\n                // Early termination if confident\n                if (min_dist < 0.1) break;\n            }\n        }\n\n        cout << best_k << '\\n';\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int INF = 1e9;\nconst double INIT_TEMP = 1e2;\nconst double FINAL_TEMP = 1e-4;\nconst double COOLING_RATE = 0.95;\nconst int MAX_ITER = 300;\n\nstruct Edge {\n    int u, v, w, idx;\n};\n\nint N, M, D, K;\nvector<Edge> edges;\nvector<vector<int>> original_dist;\nvector<int> schedule;\nvector<vector<pair<int, int>>> adj;\nvector<vector<int>> critical_edges;\n\nvoid read_input() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> N >> M >> D >> K;\n    edges.resize(M);\n    adj.resize(N);\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        edges[i].idx = i;\n        adj[edges[i].u].emplace_back(edges[i].v, edges[i].w);\n        adj[edges[i].v].emplace_back(edges[i].u, edges[i].w);\n    }\n}\n\nvoid compute_original_dist() {\n    original_dist.assign(N, vector<int>(N, INF));\n    for (int i = 0; i < N; ++i) {\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n        original_dist[i][i] = 0;\n        pq.emplace(0, i);\n        while (!pq.empty()) {\n            auto [d, u] = pq.top();\n            pq.pop();\n            if (d > original_dist[i][u]) continue;\n            for (auto [v, w] : adj[u]) {\n                if (original_dist[i][v] > d + w) {\n                    original_dist[i][v] = d + w;\n                    pq.emplace(original_dist[i][v], v);\n                }\n            }\n        }\n    }\n}\n\nvoid identify_critical_edges() {\n    critical_edges.resize(M);\n    for (int i = 0; i < N; i += 20) {  // Sample every 20th vertex\n        for (int j = i + 1; j < N; j += 20) {  // Sample every 20th vertex\n            for (const auto& e : edges) {\n                if (original_dist[i][e.u] + e.w + original_dist[e.v][j] == original_dist[i][j] ||\n                    original_dist[i][e.v] + e.w + original_dist[e.u][j] == original_dist[i][j]) {\n                    critical_edges[e.idx].push_back(i * N + j);\n                }\n            }\n        }\n    }\n}\n\ndouble approximate_frustration() {\n    double total_frustration = 0.0;\n    for (int day = 1; day <= D; ++day) {\n        vector<bool> removed(M, false);\n        for (int i = 0; i < M; ++i) {\n            if (schedule[i] == day) {\n                removed[i] = true;\n            }\n        }\n\n        unordered_set<int> affected_pairs;\n        for (int k = 0; k < M; ++k) {\n            if (removed[k]) {\n                for (int pair_idx : critical_edges[k]) {\n                    affected_pairs.insert(pair_idx);\n                }\n            }\n        }\n\n        double sum_diff = 0.0;\n        for (int pair_idx : affected_pairs) {\n            int i = pair_idx / N;\n            int j = pair_idx % N;\n            sum_diff += (INF - original_dist[i][j]);\n        }\n        double f_k = (affected_pairs.size() > 0) ? sum_diff / affected_pairs.size() : 0.0;\n        total_frustration += f_k;\n    }\n    return total_frustration / D;\n}\n\nvoid initial_schedule() {\n    schedule.assign(M, 0);\n    vector<int> day_counts(D, 0);\n    for (int i = 0; i < M; ++i) {\n        int day = rand() % D + 1;\n        while (day_counts[day - 1] >= K) {\n            day = rand() % D + 1;\n        }\n        schedule[i] = day;\n        day_counts[day - 1]++;\n    }\n}\n\nvoid simulated_annealing() {\n    initial_schedule();\n    double current_frustration = approximate_frustration();\n    double temp = INIT_TEMP;\n    int iter = 0;\n    int no_improve = 0;\n    while (temp > FINAL_TEMP && iter < MAX_ITER && no_improve < 30) {\n        int edge_idx = rand() % M;\n        int old_day = schedule[edge_idx];\n        int new_day = rand() % D + 1;\n        if (count(schedule.begin(), schedule.end(), new_day) >= K) {\n            continue;\n        }\n        schedule[edge_idx] = new_day;\n        double new_frustration = approximate_frustration();\n        double delta = new_frustration - current_frustration;\n        if (delta < 0 || exp(-delta / temp) > (double)rand() / RAND_MAX) {\n            current_frustration = new_frustration;\n            no_improve = 0;\n        } else {\n            schedule[edge_idx] = old_day;\n            no_improve++;\n        }\n        temp *= COOLING_RATE;\n        iter++;\n    }\n}\n\nint main() {\n    srand(time(0));\n    read_input();\n    compute_original_dist();\n    identify_critical_edges();\n    simulated_annealing();\n    for (int i = 0; i < M; ++i) {\n        cout << schedule[i] << (i == M - 1 ? \"\\n\" : \" \");\n    }\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <unordered_set>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n    Point(int x = 0, int y = 0, int z = 0) : x(x), y(y), z(z) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y && z == other.z;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        if (y != other.y) return y < other.y;\n        return z < other.z;\n    }\n};\n\nstruct Block {\n    vector<Point> cubes;\n    int id;\n    Block(int id = 0) : id(id) {}\n    void add_cube(const Point& p) {\n        cubes.push_back(p);\n    }\n    bool is_connected() const {\n        if (cubes.empty()) return true;\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        queue<Point> q;\n        q.push(cubes[0]);\n        visited[cubes[0].x][cubes[0].y][cubes[0].z] = true;\n        int count = 1;\n        while (!q.empty()) {\n            Point p = q.front();\n            q.pop();\n            for (const auto& cube : cubes) {\n                if (!visited[cube.x][cube.y][cube.z]) {\n                    int dx = abs(p.x - cube.x);\n                    int dy = abs(p.y - cube.y);\n                    int dz = abs(p.z - cube.z);\n                    if ((dx == 1 && dy == 0 && dz == 0) ||\n                        (dx == 0 && dy == 1 && dz == 0) ||\n                        (dx == 0 && dy == 0 && dz == 1)) {\n                        visited[cube.x][cube.y][cube.z] = true;\n                        q.push(cube);\n                        count++;\n                    }\n                }\n            }\n        }\n        return count == cubes.size();\n    }\n};\n\nint D;\nvector<vector<string>> f(2, vector<string>(D));\nvector<vector<string>> r(2, vector<string>(D));\nvector<vector<vector<int>>> b(2, vector<vector<int>>(D, vector<int>(D, 0)));\nvector<Block> blocks;\nint block_id = 1;\n\nbool can_place_block(const Block& block, int obj_idx, const vector<vector<vector<int>>>& grid) {\n    for (const auto& cube : block.cubes) {\n        if (cube.x < 0 || cube.x >= D || cube.y < 0 || cube.y >= D || cube.z < 0 || cube.z >= D) {\n            return false;\n        }\n        if (grid[cube.x][cube.y][cube.z] != 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid place_block(const Block& block, int obj_idx, int id) {\n    for (const auto& cube : block.cubes) {\n        b[obj_idx][cube.x][cube.y][cube.z] = id;\n    }\n}\n\nvoid remove_block(const Block& block, int obj_idx) {\n    for (const auto& cube : block.cubes) {\n        b[obj_idx][cube.x][cube.y][cube.z] = 0;\n    }\n}\n\nbool satisfies_silhouette(int obj_idx) {\n    for (int z = 0; z < D; ++z) {\n        for (int x = 0; x < D; ++x) {\n            bool found = false;\n            for (int y = 0; y < D; ++y) {\n                if (b[obj_idx][x][y][z] != 0) {\n                    found = true;\n                    break;\n                }\n            }\n            if (f[obj_idx][z][x] == '1' && !found) {\n                return false;\n            }\n        }\n    }\n    for (int z = 0; z < D; ++z) {\n        for (int y = 0; y < D; ++y) {\n            bool found = false;\n            for (int x = 0; x < D; ++x) {\n                if (b[obj_idx][x][y][z] != 0) {\n                    found = true;\n                    break;\n                }\n            }\n            if (r[obj_idx][z][y] == '1' && !found) {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nvoid generate_initial_blocks() {\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[obj_idx][z][x] == '1' && r[obj_idx][z][y] == '1') {\n                        bool found = false;\n                        for (const auto& block : blocks) {\n                            for (const auto& cube : block.cubes) {\n                                if (cube.x == x && cube.y == y && cube.z == z) {\n                                    found = true;\n                                    break;\n                                }\n                            }\n                            if (found) break;\n                        }\n                        if (!found) {\n                            Block block(block_id++);\n                            block.add_cube(Point(x, y, z));\n                            blocks.push_back(block);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid merge_blocks() {\n    bool merged;\n    do {\n        merged = false;\n        for (size_t i = 0; i < blocks.size(); ++i) {\n            for (size_t j = i + 1; j < blocks.size(); ++j) {\n                Block new_block(block_id);\n                for (const auto& cube : blocks[i].cubes) {\n                    new_block.add_cube(cube);\n                }\n                for (const auto& cube : blocks[j].cubes) {\n                    new_block.add_cube(cube);\n                }\n                if (new_block.is_connected()) {\n                    vector<Block> new_blocks;\n                    for (size_t k = 0; k < blocks.size(); ++k) {\n                        if (k != i && k != j) {\n                            new_blocks.push_back(blocks[k]);\n                        }\n                    }\n                    new_blocks.push_back(new_block);\n                    blocks = new_blocks;\n                    block_id++;\n                    merged = true;\n                    break;\n                }\n            }\n            if (merged) break;\n        }\n    } while (merged);\n}\n\nvoid assign_blocks_to_objects() {\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        vector<vector<vector<int>>> grid(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        for (const auto& block : blocks) {\n            bool used = false;\n            for (const auto& cube : block.cubes) {\n                if (f[obj_idx][cube.z][cube.x] == '1' && r[obj_idx][cube.z][cube.y] == '1') {\n                    used = true;\n                    break;\n                }\n            }\n            if (used) {\n                place_block(block, obj_idx, block.id);\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> D;\n    f.resize(2, vector<string>(D));\n    r.resize(2, vector<string>(D));\n    b.resize(2, vector<vector<int>>(D, vector<int>(D, 0)));\n\n    for (int i = 0; i < 2; ++i) {\n        for (int k = 0; k < D; ++k) {\n            cin >> f[i][k];\n        }\n        for (int k = 0; k < D; ++k) {\n            cin >> r[i][k];\n        }\n    }\n\n    generate_initial_blocks();\n    merge_blocks();\n    assign_blocks_to_objects();\n\n    set<int> used_blocks;\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (b[obj_idx][x][y][z] != 0) {\n                        used_blocks.insert(b[obj_idx][x][y][z]);\n                    }\n                }\n            }\n        }\n    }\n\n    vector<int> block_ids;\n    for (const auto& block : blocks) {\n        block_ids.push_back(block.id);\n    }\n    sort(block_ids.begin(), block_ids.end());\n    block_ids.erase(unique(block_ids.begin(), block_ids.end()), block_ids.end());\n\n    cout << block_ids.size() << endl;\n    for (int obj_idx = 0; obj_idx < 2; ++obj_idx) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    cout << b[obj_idx][x][y][z] << \" \";\n                }\n            }\n        }\n        cout << endl;\n    }\n\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v, w, idx;\n    double dist;\n};\n\nstruct Resident {\n    int x, y;\n};\n\nstruct Station {\n    int x, y;\n    int P;\n    vector<int> residents;\n};\n\ndouble euclidean(int x1, int y1, int x2, int y2) {\n    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<Station> stations(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> stations[i].x >> stations[i].y;\n        stations[i].P = 0;\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        edges[i].idx = i;\n        edges[i].dist = euclidean(stations[edges[i].u].x, stations[edges[i].u].y,\n                                  stations[edges[i].v].x, stations[edges[i].v].y);\n    }\n\n    vector<Resident> residents(K);\n    for (int i = 0; i < K; ++i) {\n        cin >> residents[i].x >> residents[i].y;\n    }\n\n    // Step 1: Assign residents to nearest station\n    for (int i = 0; i < K; ++i) {\n        double min_dist = 1e9;\n        int best_station = -1;\n        for (int j = 0; j < N; ++j) {\n            double dist = euclidean(residents[i].x, residents[i].y, stations[j].x, stations[j].y);\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_station = j;\n            }\n        }\n        stations[best_station].residents.push_back(i);\n    }\n\n    // Step 2: Compute MST using Kruskal's algorithm\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.w < b.w;\n    });\n\n    dsu uf(N);\n    vector<bool> edge_used(M, false);\n    vector<vector<pair<int, int>>> mst(N); // {neighbor, edge_idx}\n\n    for (const Edge& e : edges) {\n        if (!uf.same(e.u, e.v)) {\n            uf.merge(e.u, e.v);\n            edge_used[e.idx] = true;\n            mst[e.u].emplace_back(e.v, e.idx);\n            mst[e.v].emplace_back(e.u, e.idx);\n        }\n    }\n\n    // Step 3: Set initial P_i to cover all residents\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].residents.empty()) {\n            stations[i].P = 0;\n            continue;\n        }\n        double max_dist = 0;\n        for (int r : stations[i].residents) {\n            double dist = euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y);\n            if (dist > max_dist) {\n                max_dist = dist;\n            }\n        }\n        stations[i].P = min(5000, (int)ceil(max_dist));\n    }\n\n    // Step 4: Optimize P_i and edge selection\n    vector<bool> covered(K, false);\n    auto check_coverage = [&]() {\n        fill(covered.begin(), covered.end(), false);\n        for (int i = 0; i < N; ++i) {\n            for (int r : stations[i].residents) {\n                if (euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y) <= stations[i].P) {\n                    covered[r] = true;\n                }\n            }\n        }\n        return all_of(covered.begin(), covered.end(), [](bool c) { return c; });\n    };\n\n    if (!check_coverage()) {\n        // Fallback: ensure all residents are covered\n        for (int i = 0; i < N; ++i) {\n            double max_dist = 0;\n            for (int r : stations[i].residents) {\n                double dist = euclidean(residents[r].x, residents[r].y, stations[i].x, stations[i].y);\n                if (dist > max_dist) {\n                    max_dist = dist;\n                }\n            }\n            stations[i].P = min(5000, (int)ceil(max_dist));\n        }\n    }\n\n    // Try to reduce P_i\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].P == 0) continue;\n        int original_P = stations[i].P;\n        for (int p = original_P - 1; p >= 0; --p) {\n            int old_P = stations[i].P;\n            stations[i].P = p;\n            if (!check_coverage()) {\n                stations[i].P = old_P;\n                break;\n            }\n        }\n    }\n\n    // Step 5: Prune unnecessary edges\n    vector<bool> necessary_edge(M, false);\n    for (int i = 0; i < N; ++i) {\n        if (stations[i].P > 0) {\n            // BFS to mark necessary edges\n            vector<bool> visited(N, false);\n            queue<int> q;\n            q.push(i);\n            visited[i] = true;\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (auto [v, idx] : mst[u]) {\n                    if (!visited[v] && edge_used[idx]) {\n                        necessary_edge[idx] = true;\n                        visited[v] = true;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n\n    // Ensure station 1 is connected\n    vector<bool> visited(N, false);\n    queue<int> q;\n    q.push(0);\n    visited[0] = true;\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        for (auto [v, idx] : mst[u]) {\n            if (!visited[v] && edge_used[idx]) {\n                necessary_edge[idx] = true;\n                visited[v] = true;\n                q.push(v);\n            }\n        }\n    }\n\n    for (int i = 0; i < M; ++i) {\n        if (!necessary_edge[i]) {\n            edge_used[i] = false;\n        }\n    }\n\n    // Step 6: Output the solution\n    for (int i = 0; i < N; ++i) {\n        cout << stations[i].P << (i == N - 1 ? \"\\n\" : \" \");\n    }\n    for (int i = 0; i < M; ++i) {\n        cout << edge_used[i] << (i == M - 1 ? \"\\n\" : \" \");\n    }\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <climits>\n#include <unordered_map>\n#include <set>\n\nusing namespace std;\n\nconst int N = 30;\nconst int TOTAL_BALLS = N * (N + 1) / 2;\nconst int MAX_OPERATIONS = 10000;\n\nstruct Position {\n    int x, y;\n    Position(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Position& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Position& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nvector<Position> directions = {\n    {-1, -1}, {-1, 0}, {0, -1}, {0, 1}, {1, 0}, {1, 1}\n};\n\nvector<vector<int>> pyramid(N, vector<int>(N, -1));\nvector<pair<Position, Position>> operations;\nunordered_map<int, Position> ball_positions;\n\nbool is_valid(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y <= x;\n}\n\nvector<Position> get_adjacent_positions(int x, int y) {\n    vector<Position> adj;\n    for (auto& dir : directions) {\n        int nx = x + dir.x;\n        int ny = y + dir.y;\n        if (is_valid(nx, ny)) {\n            adj.emplace_back(nx, ny);\n        }\n    }\n    return adj;\n}\n\nvoid swap_balls(Position a, Position b) {\n    if (!is_valid(a.x, a.y) || !is_valid(b.x, b.y)) return;\n    swap(pyramid[a.x][a.y], pyramid[b.x][b.y]);\n    ball_positions[pyramid[a.x][a.y]] = a;\n    ball_positions[pyramid[b.x][b.y]] = b;\n    operations.emplace_back(a, b);\n}\n\nint count_violations() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int current = pyramid[x][y];\n            int child1 = pyramid[x + 1][y];\n            int child2 = pyramid[x + 1][y + 1];\n            if (current > child1) violations++;\n            if (current > child2) violations++;\n        }\n    }\n    return violations;\n}\n\nvector<Position> find_path(Position start, Position target) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    vector<vector<Position>> parent(N, vector<Position>(N, Position(-1, -1)));\n    queue<Position> q;\n    q.push(start);\n    visited[start.x][start.y] = true;\n\n    while (!q.empty()) {\n        Position current = q.front();\n        q.pop();\n        if (current.x == target.x && current.y == target.y) {\n            vector<Position> path;\n            while (!(current.x == start.x && current.y == start.y)) {\n                path.push_back(current);\n                current = parent[current.x][current.y];\n            }\n            path.push_back(start);\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        for (auto& dir : directions) {\n            int nx = current.x + dir.x;\n            int ny = current.y + dir.y;\n            if (is_valid(nx, ny) && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                parent[nx][ny] = current;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n    return {};\n}\n\nvoid move_ball(Position start, Position target) {\n    vector<Position> path = find_path(start, target);\n    if (path.empty()) return;\n    for (size_t i = 0; i < path.size() - 1; ++i) {\n        swap_balls(path[i], path[i + 1]);\n        if (operations.size() >= MAX_OPERATIONS) {\n            return;\n        }\n    }\n}\n\nvoid solve() {\n    // Read input and initialize ball positions\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            cin >> pyramid[x][y];\n            ball_positions[pyramid[x][y]] = Position(x, y);\n        }\n    }\n\n    // Target: smallest numbers at the top\n    vector<int> sorted_balls(TOTAL_BALLS);\n    for (int i = 0; i < TOTAL_BALLS; ++i) {\n        sorted_balls[i] = i;\n    }\n\n    // Initial placement with optimized path\n    for (int x = 0; x < N; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            int target_num = sorted_balls[x * (x + 1) / 2 + y];\n            Position current_pos = ball_positions[target_num];\n            if (current_pos.x != x || current_pos.y != y) {\n                move_ball(current_pos, Position(x, y));\n                if (operations.size() >= MAX_OPERATIONS) {\n                    cout << operations.size() << endl;\n                    for (auto& op : operations) {\n                        cout << op.first.x << \" \" << op.first.y << \" \"\n                             << op.second.x << \" \" << op.second.y << endl;\n                    }\n                    return;\n                }\n            }\n        }\n    }\n\n    // Fix violations with optimized swaps\n    int violations = count_violations();\n    while (violations > 0 && operations.size() < MAX_OPERATIONS) {\n        bool improved = false;\n        // Process from bottom to top\n        for (int x = N - 2; x >= 0; --x) {\n            for (int y = 0; y <= x; ++y) {\n                int current = pyramid[x][y];\n                int child1 = pyramid[x + 1][y];\n                int child2 = pyramid[x + 1][y + 1];\n                if (current > child1 || current > child2) {\n                    vector<Position> adj = get_adjacent_positions(x, y);\n                    // Find the best swap that minimizes violations and distance\n                    int best_score = INT_MAX;\n                    Position best_swap = Position(-1, -1);\n                    for (auto& pos : adj) {\n                        int temp = pyramid[pos.x][pos.y];\n                        // Calculate violations after swap\n                        int new_violations = 0;\n                        if (x > 0) {\n                            int parent1 = pyramid[x - 1][y - 1];\n                            int parent2 = pyramid[x - 1][y];\n                            if (parent1 > temp) new_violations++;\n                            if (parent2 > temp) new_violations++;\n                        }\n                        if (temp > child1) new_violations++;\n                        if (temp > child2) new_violations++;\n                        // Also consider violations at the swapped position\n                        if (pos.x < N - 1) {\n                            int child1_swap = pyramid[pos.x + 1][pos.y];\n                            int child2_swap = pyramid[pos.x + 1][pos.y + 1];\n                            if (current > child1_swap) new_violations++;\n                            if (current > child2_swap) new_violations++;\n                        }\n                        // Consider distance to target position\n                        int target_num = sorted_balls[x * (x + 1) / 2 + y];\n                        Position target_pos = ball_positions[target_num];\n                        int distance = abs(pos.x - target_pos.x) + abs(pos.y - target_pos.y);\n                        int score = new_violations * 10 + distance; // Weighted score\n\n                        if (score < best_score) {\n                            best_score = score;\n                            best_swap = pos;\n                        }\n                    }\n                    if (best_swap.x != -1) {\n                        swap_balls(Position(x, y), best_swap);\n                        improved = true;\n                        if (operations.size() >= MAX_OPERATIONS) {\n                            cout << operations.size() << endl;\n                            for (auto& op : operations) {\n                                cout << op.first.x << \" \" << op.first.y << \" \"\n                                     << op.second.x << \" \" << op.second.y << endl;\n                            }\n                            return;\n                        }\n                    }\n                }\n            }\n        }\n        if (!improved) break;\n        violations = count_violations();\n    }\n\n    cout << operations.size() << endl;\n    for (auto& op : operations) {\n        cout << op.first.x << \" \" << op.first.y << \" \"\n             << op.second.x << \" \" << op.second.y << endl;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <set>\n#include <climits>\n#include <cstring>\n\nusing namespace std;\n\nconst int GRID_SIZE = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = (GRID_SIZE - 1) / 2;\n\nstruct Cell {\n    int i, j;\n    bool operator<(const Cell& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nint grid[GRID_SIZE][GRID_SIZE];\nbool is_obstacle[GRID_SIZE][GRID_SIZE];\nbool is_container[GRID_SIZE][GRID_SIZE];\nint container_num[GRID_SIZE][GRID_SIZE];\nvector<Cell> containers;\n\nint di[] = {-1, 1, 0, 0};\nint dj[] = {0, 0, -1, 1};\n\nbool is_valid(int i, int j) {\n    return i >= 0 && i < GRID_SIZE && j >= 0 && j < GRID_SIZE;\n}\n\nvector<Cell> bfs_reachable() {\n    vector<Cell> reachable;\n    bool visited[GRID_SIZE][GRID_SIZE];\n    memset(visited, false, sizeof(visited));\n    queue<Cell> q;\n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n\n    while (!q.empty()) {\n        Cell current = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int ni = current.i + di[k];\n            int nj = current.j + dj[k];\n            if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj] && !is_container[ni][nj]) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n            }\n        }\n    }\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (visited[i][j] && !is_obstacle[i][j] && !is_container[i][j] && !(i == ENTRANCE_I && j == ENTRANCE_J)) {\n                reachable.push_back({i, j});\n            }\n        }\n    }\n    return reachable;\n}\n\nvector<Cell> bfs_removable() {\n    vector<Cell> removable;\n    bool visited[GRID_SIZE][GRID_SIZE];\n    memset(visited, false, sizeof(visited));\n    queue<Cell> q;\n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n\n    while (!q.empty()) {\n        Cell current = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n            int ni = current.i + di[k];\n            int nj = current.j + dj[k];\n            if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj]) {\n                if (is_container[ni][nj]) {\n                    removable.push_back({ni, nj});\n                } else {\n                    visited[ni][nj] = true;\n                    q.push({ni, nj});\n                }\n            }\n        }\n    }\n    return removable;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int D, N;\n    cin >> D >> N;\n    memset(is_obstacle, false, sizeof(is_obstacle));\n    memset(is_container, false, sizeof(is_container));\n    memset(container_num, -1, sizeof(container_num));\n\n    for (int i = 0; i < N; ++i) {\n        int ri, rj;\n        cin >> ri >> rj;\n        is_obstacle[ri][rj] = true;\n    }\n\n    int total_containers = GRID_SIZE * GRID_SIZE - 1 - N;\n    for (int d = 0; d < total_containers; ++d) {\n        int t;\n        cin >> t;\n        vector<Cell> reachable = bfs_reachable();\n        if (reachable.empty()) {\n            cerr << \"No reachable cells left!\" << endl;\n            return 1;\n        }\n\n        // Place the container in the cell with the highest BFS distance from entrance\n        bool visited[GRID_SIZE][GRID_SIZE];\n        memset(visited, false, sizeof(visited));\n        queue<Cell> q;\n        q.push({ENTRANCE_I, ENTRANCE_J});\n        visited[ENTRANCE_I][ENTRANCE_J] = true;\n        Cell farthest = {ENTRANCE_I, ENTRANCE_J};\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            farthest = current;\n            for (int k = 0; k < 4; ++k) {\n                int ni = current.i + di[k];\n                int nj = current.j + dj[k];\n                if (is_valid(ni, nj) && !visited[ni][nj] && !is_obstacle[ni][nj] && !is_container[ni][nj]) {\n                    visited[ni][nj] = true;\n                    q.push({ni, nj});\n                }\n            }\n        }\n\n        // Place the container at the farthest cell\n        is_container[farthest.i][farthest.j] = true;\n        container_num[farthest.i][farthest.j] = t;\n        containers.push_back({farthest.i, farthest.j});\n        cout << farthest.i << \" \" << farthest.j << endl;\n        cout.flush();\n    }\n\n    // Determine the removal order\n    vector<Cell> removal_order;\n    while (removal_order.size() < total_containers) {\n        vector<Cell> removable = bfs_removable();\n        if (removable.empty()) {\n            cerr << \"No removable containers left!\" << endl;\n            return 1;\n        }\n\n        // Find the container with the smallest number among removable\n        int min_num = INT_MAX;\n        Cell to_remove;\n        for (const Cell& cell : removable) {\n            if (container_num[cell.i][cell.j] < min_num) {\n                min_num = container_num[cell.i][cell.j];\n                to_remove = cell;\n            }\n        }\n\n        removal_order.push_back(to_remove);\n        is_container[to_remove.i][to_remove.j] = false;\n    }\n\n    for (const Cell& cell : removal_order) {\n        cout << cell.i << \" \" << cell.j << endl;\n    }\n    cout.flush();\n\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int n = 50;\nconst int m = 100;\nconst int dx[] = {1, 0, -1, 0};\nconst int dy[] = {0, 1, 0, -1};\n\nstruct Cell {\n    int x, y;\n    Cell(int x = 0, int y = 0) : x(x), y(y) {}\n};\n\nvector<vector<int>> input_grid(n, vector<int>(n));\nvector<set<int>> adjacency(m + 1);\nvector<vector<Cell>> ward_cells(m + 1);\nvector<vector<bool>> is_boundary(n, vector<bool>(n, false));\n\nvoid read_input() {\n    cin >> n >> m;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> input_grid[i][j];\n            ward_cells[input_grid[i][j]].emplace_back(i, j);\n        }\n    }\n}\n\nvoid compute_adjacency() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            int c = input_grid[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = input_grid[ni][nj];\n                    if (nc != c) {\n                        adjacency[c].insert(nc);\n                        adjacency[nc].insert(c);\n                    }\n                } else {\n                    adjacency[c].insert(0);\n                    adjacency[0].insert(c);\n                }\n            }\n        }\n    }\n}\n\nvoid compute_boundary() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni < 0 || ni >= n || nj < 0 || nj >= n) {\n                    is_boundary[i][j] = true;\n                    break;\n                }\n            }\n        }\n    }\n}\n\nvector<vector<int>> create_initial_solution() {\n    vector<vector<int>> grid(n, vector<int>(n, 0));\n    vector<set<int>> required_adj(m + 1);\n    for (int c = 1; c <= m; ++c) {\n        required_adj[c] = adjacency[c];\n    }\n\n    // Place each ward as a single cell\n    vector<Cell> positions;\n    for (int c = 1; c <= m; ++c) {\n        if (!ward_cells[c].empty()) {\n            Cell pos = ward_cells[c][0];\n            grid[pos.x][pos.y] = c;\n            positions.emplace_back(pos.x, pos.y);\n        }\n    }\n\n    // Expand wards to satisfy adjacency\n    for (int c = 1; c <= m; ++c) {\n        if (ward_cells[c].empty()) continue;\n        queue<Cell> q;\n        vector<vector<bool>> visited(n, vector<bool>(n, false));\n        for (const auto& cell : ward_cells[c]) {\n            if (grid[cell.x][cell.y] == c) {\n                q.push(cell);\n                visited[cell.x][cell.y] = true;\n            }\n        }\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int ni = current.x + dx[d];\n                int nj = current.y + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj]) {\n                    int nc = grid[ni][nj];\n                    if (nc == 0) {\n                        if (required_adj[c].count(0) || !required_adj[c].empty()) {\n                            grid[ni][nj] = c;\n                            visited[ni][nj] = true;\n                            q.push(Cell(ni, nj));\n                        }\n                    } else if (nc != c) {\n                        if (required_adj[c].count(nc)) {\n                            required_adj[c].erase(nc);\n                            required_adj[nc].erase(c);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Ensure all adjacencies are satisfied\n    for (int c = 1; c <= m; ++c) {\n        if (!required_adj[c].empty()) {\n            for (int nc : required_adj[c]) {\n                if (nc == 0) continue;\n                // Find a cell of c and nc to connect\n                for (const auto& cell : ward_cells[c]) {\n                    if (grid[cell.x][cell.y] != c) continue;\n                    for (int d = 0; d < 4; ++d) {\n                        int ni = cell.x + dx[d];\n                        int nj = cell.y + dy[d];\n                        if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] == 0) {\n                            grid[ni][nj] = c;\n                            break;\n                        }\n                    }\n                    break;\n                }\n            }\n        }\n    }\n\n    return grid;\n}\n\nvoid optimize_solution(vector<vector<int>>& grid) {\n    // Simple optimization: try to replace color-0 cells with adjacent colors if possible\n    bool improved;\n    do {\n        improved = false;\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] != 0) continue;\n                set<int> adjacent_colors;\n                for (int d = 0; d < 4; ++d) {\n                    int ni = i + dx[d];\n                    int nj = j + dy[d];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                        adjacent_colors.insert(grid[ni][nj]);\n                    }\n                }\n                if (adjacent_colors.size() == 1) {\n                    int c = *adjacent_colors.begin();\n                    if (c != 0) {\n                        grid[i][j] = c;\n                        improved = true;\n                    }\n                }\n            }\n        }\n    } while (improved);\n}\n\nbool check_connectivity(const vector<vector<int>>& grid) {\n    for (int c = 1; c <= m; ++c) {\n        vector<vector<bool>> visited(n, vector<bool>(n, false));\n        queue<Cell> q;\n        bool found = false;\n        for (int i = 0; i < n && !found; ++i) {\n            for (int j = 0; j < n && !found; ++j) {\n                if (grid[i][j] == c) {\n                    q.push(Cell(i, j));\n                    visited[i][j] = true;\n                    found = true;\n                }\n            }\n        }\n        if (!found) continue;\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            for (int d = 0; d < 4; ++d) {\n                int ni = current.x + dx[d];\n                int nj = current.y + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj] && grid[ni][nj] == c) {\n                    visited[ni][nj] = true;\n                    q.push(Cell(ni, nj));\n                }\n            }\n        }\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (grid[i][j] == c && !visited[i][j]) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nbool check_adjacency(const vector<vector<int>>& grid) {\n    vector<set<int>> current_adj(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            for (int d = 0; d < 4; ++d) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = grid[ni][nj];\n                    if (nc != c) {\n                        current_adj[c].insert(nc);\n                        current_adj[nc].insert(c);\n                    }\n                } else {\n                    current_adj[c].insert(0);\n                    current_adj[0].insert(c);\n                }\n            }\n        }\n    }\n    for (int c = 0; c <= m; ++c) {\n        if (current_adj[c] != adjacency[c]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    read_input();\n    compute_adjacency();\n    compute_boundary();\n\n    vector<vector<int>> grid = create_initial_solution();\n    optimize_solution(grid);\n\n    // Verify the solution\n    if (!check_connectivity(grid) || !check_adjacency(grid)) {\n        // Fallback: output the original grid (though it may not be optimal)\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << input_grid[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n    } else {\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cout << grid[i][j] << \" \";\n            }\n            cout << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <queue>\n#include <set>\n#include <map>\n#include <chrono>\n#include <cassert>\n#include <limits>\n\nusing namespace std;\nusing namespace std::chrono;\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct Item {\n    int id;\n    double weight;\n    double uncertainty;\n    double confidence;\n};\n\nvector<int> solve(int N, int D, int Q) {\n    vector<Item> items(N);\n    for (int i = 0; i < N; ++i) {\n        items[i] = {i, 1.0, 1.0, 0.5};\n    }\n\n    auto query = [&](const vector<int>& L, const vector<int>& R) {\n        cout << L.size() << \" \" << R.size();\n        for (int l : L) cout << \" \" << l;\n        for (int r : R) cout << \" \" << r;\n        cout << endl;\n        cout.flush();\n\n        string result;\n        cin >> result;\n        if (result == \"<\") return -1;\n        else if (result == \">\") return 1;\n        else return 0;\n    };\n\n    // Phase 1: Initial weight estimation with adaptive ratios\n    double base_ratio = 0.85;\n    for (int i = 0; i < N && Q > 0; ++i) {\n        for (int j = i + 1; j < N && Q > 0; ++j) {\n            vector<int> L = {i}, R = {j};\n            int res = query(L, R);\n            Q--;\n\n            double ratio = base_ratio * (1.0 - items[i].confidence * items[j].confidence);\n            if (res == -1) {\n                items[i].weight *= (1.0 - ratio);\n                items[j].weight *= (1.0 + ratio);\n            } else if (res == 1) {\n                items[i].weight *= (1.0 + ratio);\n                items[j].weight *= (1.0 - ratio);\n            }\n\n            items[i].uncertainty *= 0.5;\n            items[j].uncertainty *= 0.5;\n            items[i].confidence = 1.0 - items[i].uncertainty;\n            items[j].confidence = 1.0 - items[j].uncertainty;\n        }\n        base_ratio = max(0.1, base_ratio * 0.95);\n    }\n\n    // Phase 2: Adaptive subset queries\n    while (Q > 0) {\n        // Select items with highest uncertainty-to-weight ratio\n        vector<pair<double, int>> candidates;\n        for (int i = 0; i < N; ++i) {\n            double ratio = items[i].uncertainty / (items[i].weight + 1e-6);\n            candidates.emplace_back(ratio, i);\n        }\n        sort(candidates.begin(), candidates.end(), greater<pair<double, int>>());\n\n        vector<int> L, R;\n        set<int> used;\n        int subset_size = min(5, N/2);\n        for (int i = 0; i < subset_size && i < N; ++i) {\n            int item = candidates[i].second;\n            if (used.count(item)) continue;\n            used.insert(item);\n            L.push_back(item);\n        }\n        for (int i = subset_size; i < 2*subset_size && i < N; ++i) {\n            int item = candidates[i].second;\n            if (used.count(item)) continue;\n            used.insert(item);\n            R.push_back(item);\n        }\n\n        if (L.empty() || R.empty()) {\n            // Fallback to random selection\n            L.clear(); R.clear(); used.clear();\n            uniform_int_distribution<int> dist(0, N-1);\n            while (static_cast<int>(L.size()) < subset_size) {\n                int item = dist(rng);\n                if (used.count(item)) continue;\n                used.insert(item);\n                L.push_back(item);\n            }\n            while (static_cast<int>(R.size()) < subset_size) {\n                int item = dist(rng);\n                if (used.count(item)) continue;\n                used.insert(item);\n                R.push_back(item);\n            }\n        }\n\n        int res = query(L, R);\n        Q--;\n\n        double sum_L = accumulate(L.begin(), L.end(), 0.0, [&](double s, int i) { return s + items[i].weight; });\n        double sum_R = accumulate(R.begin(), R.end(), 0.0, [&](double s, int i) { return s + items[i].weight; });\n\n        double adjustment = 0.3 + 0.4 * (1.0 - min(sum_L, sum_R)/max(sum_L, sum_R));\n        if (res == -1) {\n            for (int l : L) items[l].weight *= (1.0 - adjustment);\n            for (int r : R) items[r].weight *= (1.0 + adjustment);\n        } else if (res == 1) {\n            for (int l : L) items[l].weight *= (1.0 + adjustment);\n            for (int r : R) items[r].weight *= (1.0 - adjustment);\n        }\n\n        for (int l : L) {\n            items[l].uncertainty *= 0.55;\n            items[l].confidence = 1.0 - items[l].uncertainty;\n        }\n        for (int r : R) {\n            items[r].uncertainty *= 0.55;\n            items[r].confidence = 1.0 - items[r].uncertainty;\n        }\n    }\n\n    // Special case detection\n    double max_weight = (*max_element(items.begin(), items.end(), [](const Item& a, const Item& b) {\n        return a.weight < b.weight;\n    })).weight;\n    double min_weight = (*min_element(items.begin(), items.end(), [](const Item& a, const Item& b) {\n        return a.weight < b.weight;\n    })).weight;\n    double weight_range = max_weight - min_weight;\n    bool is_extreme_case = (weight_range < 0.2) || (D > N/2) || (N >= 80);\n\n    // Multi-phase partitioning\n    auto greedy_partition = [&](const vector<double>& weights, bool reverse = false) {\n        vector<int> assignment(N);\n        vector<double> set_sums(D, 0.0);\n        vector<pair<double, int>> sorted_items;\n        for (int i = 0; i < N; ++i) {\n            sorted_items.emplace_back(weights[i], i);\n        }\n        if (reverse) {\n            sort(sorted_items.begin(), sorted_items.end());\n        } else {\n            sort(sorted_items.begin(), sorted_items.end(), greater<pair<double, int>>());\n        }\n\n        for (const auto& item : sorted_items) {\n            int best_set = 0;\n            double min_sum = set_sums[0];\n            for (int d = 1; d < D; ++d) {\n                if (set_sums[d] < min_sum) {\n                    min_sum = set_sums[d];\n                    best_set = d;\n                }\n            }\n            assignment[item.second] = best_set;\n            set_sums[best_set] += item.first;\n        }\n        return assignment;\n    };\n\n    auto calculate_variance = [&](const vector<int>& assignment, const vector<double>& weights) {\n        vector<double> sums(D, 0.0);\n        for (int i = 0; i < N; ++i) {\n            sums[assignment[i]] += weights[i];\n        }\n        double mean = accumulate(sums.begin(), sums.end(), 0.0) / D;\n        double variance = 0.0;\n        for (double sum : sums) {\n            variance += (sum - mean) * (sum - mean);\n        }\n        return variance / D;\n    };\n\n    // Phase 1: Initial greedy assignment with multiple strategies\n    vector<double> weights(N);\n    for (int i = 0; i < N; ++i) {\n        weights[i] = items[i].weight;\n    }\n\n    vector<int> best_assignment = greedy_partition(weights);\n    double best_variance = calculate_variance(best_assignment, weights);\n\n    // Try reverse sorting\n    vector<int> reverse_assignment = greedy_partition(weights, true);\n    double reverse_variance = calculate_variance(reverse_assignment, weights);\n    if (reverse_variance < best_variance) {\n        best_variance = reverse_variance;\n        best_assignment = reverse_assignment;\n    }\n\n    // Special case handling\n    if (is_extreme_case) {\n        // Try multiple alternative strategies\n        vector<vector<int>> alternative_assignments;\n        vector<double> alternative_variances;\n\n        // Strategy 1: Round-robin assignment\n        vector<int> rr_assignment(N);\n        for (int i = 0; i < N; ++i) {\n            rr_assignment[i] = i % D;\n        }\n        alternative_assignments.push_back(rr_assignment);\n        alternative_variances.push_back(calculate_variance(rr_assignment, weights));\n\n        // Strategy 2: Random assignment\n        vector<int> rand_assignment(N);\n        uniform_int_distribution<int> dist(0, D-1);\n        for (int i = 0; i < N; ++i) {\n            rand_assignment[i] = dist(rng);\n        }\n        alternative_assignments.push_back(rand_assignment);\n        alternative_variances.push_back(calculate_variance(rand_assignment, weights));\n\n        // Strategy 3: Weight-based round-robin\n        vector<pair<double, int>> sorted_items;\n        for (int i = 0; i < N; ++i) {\n            sorted_items.emplace_back(weights[i], i);\n        }\n        sort(sorted_items.begin(), sorted_items.end(), greater<pair<double, int>>());\n        vector<int> wrr_assignment(N);\n        for (int i = 0; i < N; ++i) {\n            wrr_assignment[sorted_items[i].second] = i % D;\n        }\n        alternative_assignments.push_back(wrr_assignment);\n        alternative_variances.push_back(calculate_variance(wrr_assignment, weights));\n\n        // Strategy 4: Balanced assignment\n        vector<int> bal_assignment(N);\n        vector<double> set_sums(D, 0.0);\n        for (int i = 0; i < N; ++i) {\n            int best_set = 0;\n            double min_sum = set_sums[0];\n            for (int d = 1; d < D; ++d) {\n                if (set_sums[d] < min_sum) {\n                    min_sum = set_sums[d];\n                    best_set = d;\n                }\n            }\n            bal_assignment[i] = best_set;\n            set_sums[best_set] += weights[i];\n        }\n        alternative_assignments.push_back(bal_assignment);\n        alternative_variances.push_back(calculate_variance(bal_assignment, weights));\n\n        // Strategy 5: Cluster-based assignment\n        vector<int> cluster_assignment(N);\n        vector<vector<int>> clusters(D);\n        for (int i = 0; i < N; ++i) {\n            clusters[i % D].push_back(i);\n        }\n        for (int d = 0; d < D; ++d) {\n            for (int idx : clusters[d]) {\n                cluster_assignment[idx] = d;\n            }\n        }\n        alternative_assignments.push_back(cluster_assignment);\n        alternative_variances.push_back(calculate_variance(cluster_assignment, weights));\n\n        // Select the best alternative\n        for (int i = 0; i < alternative_assignments.size(); ++i) {\n            if (alternative_variances[i] < best_variance) {\n                best_variance = alternative_variances[i];\n                best_assignment = alternative_assignments[i];\n            }\n        }\n    }\n\n    // Phase 2: Multiple restarts with adaptive perturbations\n    int restarts = min(30, Q/2 + 1);\n    for (int restart = 0; restart < restarts; ++restart) {\n        vector<double> perturbed_weights = weights;\n        double perturbation = 0.01 + 0.05 * (1.0 - best_variance/1e6);\n        normal_distribution<double> dist(0, perturbation);\n        for (double& w : perturbed_weights) {\n            w *= (1.0 + dist(rng));\n            w = max(0.1, w);\n        }\n\n        vector<int> current_assignment = greedy_partition(perturbed_weights);\n        double current_variance = calculate_variance(current_assignment, weights);\n\n        if (current_variance < best_variance) {\n            best_variance = current_variance;\n            best_assignment = current_assignment;\n        }\n    }\n\n    // Phase 3: Adaptive local search with enhanced parameters\n    uniform_int_distribution<int> item_dist(0, N-1);\n    uniform_int_distribution<int> set_dist(0, D-1);\n    double temperature = 2.5;  // Higher initial temperature\n    double cooling_rate = 0.96;  // Slower cooling\n\n    int iterations = min(30000, Q*60);\n    for (int iter = 0; iter < iterations && temperature > 0.01; ++iter) {\n        int item = item_dist(rng);\n        int old_set = best_assignment[item];\n        int new_set = set_dist(rng);\n        if (old_set == new_set) continue;\n\n        double old_sum = 0.0, new_sum = 0.0;\n        for (int i = 0; i < N; ++i) {\n            if (best_assignment[i] == old_set) old_sum += weights[i];\n            if (best_assignment[i] == new_set) new_sum += weights[i];\n        }\n        old_sum -= weights[item];\n        new_sum += weights[item];\n\n        double old_mean = (accumulate(weights.begin(), weights.end(), 0.0) - weights[item]) / D;\n        double delta_variance = (new_sum - old_mean) * (new_sum - old_mean) +\n                               (old_sum - old_mean) * (old_sum - old_mean) -\n                               (new_sum + weights[item] - old_mean) * (new_sum + weights[item] - old_mean) -\n                               (old_sum - weights[item] - old_mean) * (old_sum - weights[item] - old_mean);\n        delta_variance /= D;\n\n        if (delta_variance < 0 || exp(-delta_variance / temperature) > ((double)rng() / rng.max())) {\n            best_assignment[item] = new_set;\n            best_variance += delta_variance;\n        }\n        temperature *= cooling_rate;\n    }\n\n    return best_assignment;\n}\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n\n    auto assignment = solve(N, D, Q);\n\n    for (int i = 0; i < N; ++i) {\n        cout << assignment[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n    cout.flush();\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Box {\n    int value;\n    int stack;\n    int pos; // position from bottom (0-based)\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n = 200, m = 10;\n    cin >> n >> m;\n\n    vector<vector<int>> stacks(m);\n    unordered_map<int, Box> box_info;\n    vector<int> next_box_pos(m, 0); // next position to check in each stack (from top)\n\n    for (int i = 0; i < m; ++i) {\n        stacks[i].resize(n / m);\n        for (int j = 0; j < n / m; ++j) {\n            cin >> stacks[i][j];\n            box_info[stacks[i][j]] = {stacks[i][j], i, j};\n        }\n    }\n\n    vector<pair<int, int>> operations;\n    int next_box = 1;\n    int total_energy = 0;\n    int max_operations = 5000;\n\n    auto get_top_box = [&](int stack_idx) {\n        if (stacks[stack_idx].empty()) return -1;\n        return stacks[stack_idx].back();\n    };\n\n    auto move_boxes = [&](int v, int dest_stack) {\n        int src_stack = box_info[v].stack;\n        int pos = box_info[v].pos;\n        int num_boxes = stacks[src_stack].size() - pos;\n        if (num_boxes <= 0) return false; // should not happen\n\n        // Remove boxes from src_stack\n        vector<int> moved_boxes;\n        for (int i = pos; i < stacks[src_stack].size(); ++i) {\n            moved_boxes.push_back(stacks[src_stack][i]);\n        }\n        stacks[src_stack].resize(pos);\n\n        // Add to dest_stack\n        for (int box : moved_boxes) {\n            stacks[dest_stack].push_back(box);\n            box_info[box].stack = dest_stack;\n            box_info[box].pos = stacks[dest_stack].size() - 1;\n        }\n\n        operations.emplace_back(v, dest_stack);\n        total_energy += num_boxes + 1;\n        return true;\n    };\n\n    auto carry_out = [&](int v) {\n        int stack = box_info[v].stack;\n        stacks[stack].pop_back();\n        operations.emplace_back(v, 0);\n    };\n\n    auto find_dest_stack = [&](int v) {\n        int src_stack = box_info[v].stack;\n        vector<int> candidates;\n        for (int i = 0; i < m; ++i) {\n            if (i == src_stack) continue;\n            if (stacks[i].empty()) {\n                candidates.push_back(i);\n                continue;\n            }\n            int top_box = get_top_box(i);\n            if (top_box > v) {\n                candidates.push_back(i);\n            }\n        }\n\n        if (candidates.empty()) {\n            for (int i = 0; i < m; ++i) {\n                if (i != src_stack) {\n                    candidates.push_back(i);\n                }\n            }\n        }\n\n        // Choose the stack with the smallest size\n        int best_stack = candidates[0];\n        for (int stack : candidates) {\n            if (stacks[stack].size() < stacks[best_stack].size()) {\n                best_stack = stack;\n            }\n        }\n        return best_stack;\n    };\n\n    while (next_box <= n && operations.size() < max_operations) {\n        int stack = box_info[next_box].stack;\n        int pos = box_info[next_box].pos;\n        if (pos == stacks[stack].size() - 1) {\n            carry_out(next_box);\n            next_box++;\n        } else {\n            int dest_stack = find_dest_stack(next_box);\n            move_boxes(next_box, dest_stack);\n        }\n    }\n\n    // Output operations\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <climits>\n#include <functional>\n\nusing namespace std;\n\nconst int MAX_N = 40;\nconst int MAX_MOVES = 100000;\nconst vector<pair<int, int>> DIJ = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\nconst string DIR = \"RDLU\";\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<bool>> visited;\nstring route;\n\nvoid simple_dfs(int i, int j) {\n    visited[i][j] = true;\n    for (int dir = 0; dir < 4; ++dir) {\n        auto [di, dj] = DIJ[dir];\n        int ni = i + di;\n        int nj = j + dj;\n        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n        if (visited[ni][nj]) continue;\n        if (di == 0) {\n            if (dj == 1 && v[i][min(j, nj)] == '1') continue;\n            if (dj == -1 && v[i][min(j, nj)] == '1') continue;\n        } else {\n            if (di == 1 && h[min(i, ni)][j] == '1') continue;\n            if (di == -1 && h[min(i, ni)][j] == '1') continue;\n        }\n        route += DIR[dir];\n        simple_dfs(ni, nj);\n        route += DIR[(dir + 2) % 4];\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; ++i) {\n        cin >> h[i];\n    }\n    v.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> v[i];\n    }\n    d.resize(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    visited.assign(N, vector<bool>(N, false));\n    simple_dfs(0, 0);\n\n    // Ensure route length is within limits\n    if (route.size() > MAX_MOVES) {\n        route = route.substr(0, MAX_MOVES);\n    }\n\n    cout << route << endl;\n\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 15;\nconst int M = 200;\nconst int MAX_OPERATIONS = 5000;\n\nvector<string> t(M);\nvector<vector<pair<int, int>>> char_positions(26);\nvector<unordered_set<int>> char_to_words(26);\nvector<bool> covered(M, false);\n\nint manhattan(int i1, int j1, int i2, int j2) {\n    return abs(i1 - i2) + abs(j1 - j2);\n}\n\nvoid preprocess(const vector<string>& grid) {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char c = grid[i][j];\n            char_positions[c - 'A'].emplace_back(i, j);\n        }\n    }\n\n    for (int k = 0; k < M; ++k) {\n        for (char c : t[k]) {\n            char_to_words[c - 'A'].insert(k);\n        }\n    }\n}\n\nvector<pair<int, int>> greedy_construction(const vector<string>& grid, int si, int sj) {\n    vector<pair<int, int>> path = {{si, sj}};\n    string s;\n    int current_i = si, current_j = sj;\n    int operations = 0;\n\n    while (operations < MAX_OPERATIONS) {\n        int best_i = -1, best_j = -1;\n        char best_char = '\\0';\n        int best_score = -1;\n        int best_cost = INT_MAX;\n\n        for (char c = 'A'; c <= 'Z'; ++c) {\n            for (auto [i, j] : char_positions[c - 'A']) {\n                int cost = manhattan(current_i, current_j, i, j) + 1;\n                int score = 0;\n\n                for (int k : char_to_words[c - 'A']) {\n                    if (!covered[k]) {\n                        bool can_cover = true;\n                        if (s.size() >= t[k].size()) {\n                            for (int l = 0; l < t[k].size(); ++l) {\n                                if (s[s.size() - t[k].size() + l] != t[k][l]) {\n                                    can_cover = false;\n                                    break;\n                                }\n                            }\n                        } else {\n                            can_cover = false;\n                        }\n                        if (can_cover) {\n                            score++;\n                        }\n                    }\n                }\n\n                if (score > best_score || (score == best_score && cost < best_cost)) {\n                    best_score = score;\n                    best_cost = cost;\n                    best_i = i;\n                    best_j = j;\n                    best_char = c;\n                }\n            }\n        }\n\n        if (best_score == 0) {\n            // No immediate benefit, choose closest character\n            for (char c = 'A'; c <= 'Z'; ++c) {\n                for (auto [i, j] : char_positions[c - 'A']) {\n                    int cost = manhattan(current_i, current_j, i, j) + 1;\n                    if (cost < best_cost) {\n                        best_cost = cost;\n                        best_i = i;\n                        best_j = j;\n                        best_char = c;\n                    }\n                }\n            }\n        }\n\n        s += best_char;\n        current_i = best_i;\n        current_j = best_j;\n        path.emplace_back(best_i, best_j);\n        operations++;\n\n        // Update covered words\n        for (int k : char_to_words[best_char - 'A']) {\n            if (!covered[k]) {\n                bool can_cover = true;\n                if (s.size() >= t[k].size()) {\n                    for (int l = 0; l < t[k].size(); ++l) {\n                        if (s[s.size() - t[k].size() + l] != t[k][l]) {\n                            can_cover = false;\n                            break;\n                        }\n                    }\n                } else {\n                    can_cover = false;\n                }\n                if (can_cover) {\n                    covered[k] = true;\n                }\n            }\n        }\n\n        // Check if all words are covered\n        bool all_covered = true;\n        for (bool cov : covered) {\n            if (!cov) {\n                all_covered = false;\n                break;\n            }\n        }\n        if (all_covered) {\n            break;\n        }\n    }\n\n    return path;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, M_in;\n    cin >> N_in >> M_in;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> grid(N_in);\n    for (int i = 0; i < N_in; ++i) {\n        cin >> grid[i];\n    }\n    for (int k = 0; k < M_in; ++k) {\n        cin >> t[k];\n    }\n\n    preprocess(grid);\n    auto path = greedy_construction(grid, si, sj);\n\n    // Ensure we don't exceed MAX_OPERATIONS\n    if (path.size() > MAX_OPERATIONS) {\n        path.resize(MAX_OPERATIONS);\n    }\n\n    for (auto [i, j] : path) {\n        cout << i << \" \" << j << \"\\n\";\n    }\n\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int i, j;\n    Point(int i = 0, int j = 0) : i(i), j(j) {}\n};\n\nstruct OilField {\n    int d;\n    vector<Point> cells;\n};\n\nclass Solver {\nprivate:\n    int N, M;\n    double eps;\n    vector<OilField> fields;\n    vector<vector<int>> grid;\n    vector<vector<bool>> drilled;\n    vector<Point> oil_squares;\n\n    void read_input() {\n        cin >> N >> M >> eps;\n        fields.resize(M);\n\n        for (int k = 0; k < M; ++k) {\n            cin >> fields[k].d;\n            fields[k].cells.resize(fields[k].d);\n            for (int i = 0; i < fields[k].d; ++i) {\n                cin >> fields[k].cells[i].i >> fields[k].cells[i].j;\n            }\n        }\n    }\n\n    void drill_all() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << \"q 1 \" << i << \" \" << j << endl;\n                cout.flush();\n\n                int v;\n                cin >> v;\n                if (v > 0) {\n                    oil_squares.emplace_back(i, j);\n                }\n            }\n        }\n    }\n\npublic:\n    Solver() {\n        read_input();\n        grid.assign(N, vector<int>(N, 0));\n        drilled.assign(N, vector<bool>(N, false));\n    }\n\n    void solve() {\n        // Simple solution: drill all squares\n        drill_all();\n\n        // Output the answer\n        cout << \"a \" << oil_squares.size();\n        for (const auto& p : oil_squares) {\n            cout << \" \" << p.i << \" \" << p.j;\n        }\n        cout << endl;\n        cout.flush();\n\n        int correct;\n        cin >> correct;\n        if (correct != 1) {\n            // If wrong, try again with all squares (shouldn't happen)\n            cout << \"a \" << N*N;\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    cout << \" \" << i << \" \" << j;\n                }\n            }\n            cout << endl;\n            cout.flush();\n        }\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    Solver solver;\n    solver.solve();\n\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nconst int W = 1000;\nconst int MAX_D = 50;\nconst int MAX_N = 50;\n\nstruct Rect {\n    int i1, j1, i2, j2;\n    Rect(int i1 = 0, int j1 = 0, int i2 = 0, int j2 = 0) : i1(i1), j1(j1), i2(i2), j2(j2) {}\n    int area() const { return (i2 - i1) * (j2 - j1); }\n};\n\nvector<vector<Rect>> solve(int D, int N, const vector<vector<int>>& a) {\n    vector<vector<Rect>> res(D, vector<Rect>(N));\n\n    // For each day, we'll partition the grid into N rectangles\n    for (int d = 0; d < D; ++d) {\n        vector<int> areas = a[d];\n        sort(areas.begin(), areas.end(), greater<int>());\n        vector<Rect> rects;\n        int remaining_height = W;\n        int remaining_width = W;\n        int current_i = 0;\n        int current_j = 0;\n\n        for (int k = 0; k < N; ++k) {\n            int target = areas[k];\n            if (k == N - 1) {\n                // Last rectangle takes the remaining space\n                rects.emplace_back(current_i, current_j, W, W);\n                break;\n            }\n            // Decide whether to split vertically or horizontally\n            int split_height = (target + remaining_width - 1) / remaining_width;\n            if (split_height > remaining_height) {\n                split_height = remaining_height;\n            }\n            int split_width = (target + split_height - 1) / split_height;\n            if (split_width > remaining_width) {\n                split_width = remaining_width;\n            }\n\n            // Try to split vertically first\n            int best_split = -1;\n            int best_diff = INT_MAX;\n            for (int split = 1; split <= remaining_width; ++split) {\n                int h = (target + split - 1) / split;\n                if (h > remaining_height) continue;\n                int diff = abs(target - split * h);\n                if (diff < best_diff) {\n                    best_diff = diff;\n                    best_split = split;\n                }\n            }\n            // Try to split horizontally\n            for (int split = 1; split <= remaining_height; ++split) {\n                int w = (target + split - 1) / split;\n                if (w > remaining_width) continue;\n                int diff = abs(target - split * w);\n                if (diff < best_diff) {\n                    best_diff = diff;\n                    best_split = -split; // negative indicates horizontal split\n                }\n            }\n\n            if (best_split > 0) {\n                // Vertical split\n                int split = best_split;\n                int h = (target + split - 1) / split;\n                rects.emplace_back(current_i, current_j, current_i + h, current_j + split);\n                current_j += split;\n                remaining_width -= split;\n            } else {\n                // Horizontal split\n                int split = -best_split;\n                int w = (target + split - 1) / split;\n                rects.emplace_back(current_i, current_j, current_i + split, current_j + w);\n                current_i += split;\n                remaining_height -= split;\n            }\n        }\n        res[d] = rects;\n    }\n\n    // Now, try to minimize partition changes between days\n    for (int d = 1; d < D; ++d) {\n        // For simplicity, we'll just use the same partitioning as the previous day\n        // and adjust the rectangles to meet the new area requirements\n        // This is a placeholder; a better approach would involve more sophisticated matching\n        res[d] = res[d-1];\n        for (int k = 0; k < N; ++k) {\n            int target = a[d][k];\n            Rect& r = res[d][k];\n            int current_area = r.area();\n            if (current_area < target) {\n                // Need to expand the rectangle\n                // Try to expand to the right or down\n                if (r.j2 < W) {\n                    int new_width = (target + (r.i2 - r.i1) - 1) / (r.i2 - r.i1);\n                    if (new_width > W - r.j1) new_width = W - r.j1;\n                    r.j2 = r.j1 + new_width;\n                } else if (r.i2 < W) {\n                    int new_height = (target + (r.j2 - r.j1) - 1) / (r.j2 - r.j1);\n                    if (new_height > W - r.i1) new_height = W - r.i1;\n                    r.i2 = r.i1 + new_height;\n                }\n            } else if (current_area > target) {\n                // Need to shrink the rectangle\n                // Try to shrink from the right or bottom\n                int shrink_area = current_area - target;\n                if (r.j2 > r.j1) {\n                    int shrink_width = min(shrink_area / (r.i2 - r.i1), r.j2 - r.j1 - 1);\n                    r.j2 -= shrink_width;\n                } else if (r.i2 > r.i1) {\n                    int shrink_height = min(shrink_area / (r.j2 - r.j1), r.i2 - r.i1 - 1);\n                    r.i2 -= shrink_height;\n                }\n            }\n        }\n    }\n\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int W_in, D, N;\n    cin >> W_in >> D >> 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    }\n\n    auto res = solve(D, N, a);\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            const auto& r = res[d][k];\n            cout << r.i1 << \" \" << r.j1 << \" \" << r.i2 << \" \" << r.j2 << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K_MAX = 81;\nconst int STAMP_SIZE = 3;\n\nint a[N][N];\nint s[M][STAMP_SIZE][STAMP_SIZE];\nint b[N][N];\nint d[N][N]; // deficit: MOD - 1 - (b[i][j] % MOD)\n\nstruct Operation {\n    int m, p, q;\n};\n\nvector<Operation> operations;\n\nvoid apply_stamp(int m, int p, int q) {\n    for (int i = 0; i < STAMP_SIZE; ++i) {\n        for (int j = 0; j < STAMP_SIZE; ++j) {\n            b[p + i][q + j] += s[m][i][j];\n        }\n    }\n}\n\nvoid update_deficits() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            d[i][j] = (MOD - 1 - (b[i][j] % MOD)) % MOD;\n        }\n    }\n}\n\nint compute_contribution(int m, int p, int q) {\n    int contribution = 0;\n    for (int i = 0; i < STAMP_SIZE; ++i) {\n        for (int j = 0; j < STAMP_SIZE; ++j) {\n            int ni = p + i;\n            int nj = q + j;\n            if (ni >= N || nj >= N) continue;\n            int add = min(s[m][i][j], d[ni][nj]);\n            contribution += add;\n        }\n    }\n    return contribution;\n}\n\nvoid greedy_solve() {\n    // Initialize b and d\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            b[i][j] = a[i][j];\n        }\n    }\n    update_deficits();\n\n    operations.clear();\n    for (int k = 0; k < K_MAX; ++k) {\n        int best_contribution = -1;\n        int best_m = -1, best_p = -1, best_q = -1;\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - STAMP_SIZE; ++p) {\n                for (int q = 0; q <= N - STAMP_SIZE; ++q) {\n                    int contribution = compute_contribution(m, p, q);\n                    if (contribution > best_contribution) {\n                        best_contribution = contribution;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_contribution <= 0) break;\n\n        operations.push_back({best_m, best_p, best_q});\n        apply_stamp(best_m, best_p, best_q);\n        update_deficits();\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, M_in, K_in;\n    cin >> N_in >> M_in >> K_in;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> a[i][j];\n        }\n    }\n    for (int m = 0; m < M; ++m) {\n        for (int i = 0; i < STAMP_SIZE; ++i) {\n            for (int j = 0; j < STAMP_SIZE; ++j) {\n                cin >> s[m][i][j];\n            }\n        }\n    }\n\n    greedy_solve();\n\n    cout << operations.size() << '\\n';\n    for (const auto& op : operations) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURNS = 10000;\n\nint main() {\n    vector<vector<int>> A(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n        }\n    }\n\n    // For simplicity, we'll output a basic sequence of operations\n    // that moves containers to their target gates without conflicts\n    // This is a placeholder for a more sophisticated solution\n\n    // Each crane will move right to the dispatch gate and then left to pick up\n    // the next container, repeating this pattern\n    vector<string> operations(N, string(MAX_TURNS, '.'));\n\n    for (int i = 0; i < N; ++i) {\n        for (int t = 0; t < MAX_TURNS; ++t) {\n            if (t % 2 == 0) {\n                operations[i][t] = 'R'; // Move right\n            } else {\n                operations[i][t] = 'L'; // Move left\n            }\n        }\n    }\n\n    // Output operations\n    for (int i = 0; i < N; ++i) {\n        cout << operations[i] << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 20;\n    vector<vector<int>> grid(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> grid[i][j];\n        }\n    }\n\n    // Snake traversal order\n    vector<pair<int, int>> order;\n    for (int i = 0; i < N; ++i) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; ++j) {\n                order.emplace_back(i, j);\n            }\n        } else {\n            for (int j = N - 1; j >= 0; --j) {\n                order.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Current position and load\n    int x = 0, y = 0;\n    int load = 0;\n    vector<string> ops;\n\n    // Function to move to (nx, ny)\n    auto move_to = [&](int nx, int ny) {\n        while (x != nx || y != ny) {\n            if (x < nx) { ops.push_back(\"D\"); x++; }\n            else if (x > nx) { ops.push_back(\"U\"); x--; }\n            else if (y < ny) { ops.push_back(\"R\"); y++; }\n            else if (y > ny) { ops.push_back(\"L\"); y--; }\n        }\n    };\n\n    // Traverse in order\n    for (auto [i, j] : order) {\n        move_to(i, j);\n\n        // Load if positive\n        if (grid[i][j] > 0) {\n            int d = min(grid[i][j], 1000000);\n            ops.push_back(\"+\" + to_string(d));\n            grid[i][j] -= d;\n            load += d;\n        }\n        // Unload if negative and truck has load\n        else if (grid[i][j] < 0 && load > 0) {\n            int d = min(-grid[i][j], load);\n            ops.push_back(\"-\" + to_string(d));\n            grid[i][j] += d;\n            load -= d;\n        }\n    }\n\n    // Final unload if needed (should not happen, but safe)\n    if (load > 0) {\n        move_to(0, 0);\n        ops.push_back(\"-\" + to_string(load));\n    }\n\n    // Output all operations\n    for (const string& op : ops) {\n        cout << op << '\\n';\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n\nusing namespace std;\n\nstruct Seed {\n    vector<int> eval;\n    int value;\n    int id;\n    double potential;\n};\n\nbool compareSeeds(const Seed &a, const Seed &b) {\n    return a.potential > b.potential;\n}\n\ndouble calculatePotential(const Seed &s, const vector<Seed> &all_seeds) {\n    double sum = accumulate(s.eval.begin(), s.eval.end(), 0.0);\n    double max_val = *max_element(s.eval.begin(), s.eval.end());\n    double diversity = 0.0;\n    for (int val : s.eval) {\n        diversity += val * val;\n    }\n\n    // Calculate expected value when paired with other seeds\n    double expected_value = 0.0;\n    for (const auto &other : all_seeds) {\n        if (&other == &s) continue;\n        double pair_value = 0.0;\n        for (int i = 0; i < s.eval.size(); ++i) {\n            pair_value += (s.eval[i] + other.eval[i]) / 2.0;\n        }\n        expected_value += pair_value;\n    }\n    expected_value /= all_seeds.size() - 1;\n\n    return sum + 0.5 * max_val + 0.1 * diversity + 0.2 * expected_value;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N = 6, M = 15, T = 10;\n    int seed_count = 2 * N * (N - 1);\n    vector<Seed> seeds(seed_count);\n\n    for (int i = 0; i < seed_count; ++i) {\n        seeds[i].eval.resize(M);\n        seeds[i].id = i;\n        for (int j = 0; j < M; ++j) {\n            cin >> seeds[i].eval[j];\n        }\n        seeds[i].value = accumulate(seeds[i].eval.begin(), seeds[i].eval.end(), 0);\n    }\n\n    for (int t = 0; t < T; ++t) {\n        // Calculate potential for all seeds\n        for (auto &seed : seeds) {\n            seed.potential = calculatePotential(seed, seeds);\n        }\n\n        // Sort seeds by potential in descending order\n        sort(seeds.begin(), seeds.end(), compareSeeds);\n\n        // Select top N*N seeds\n        vector<Seed> selected_seeds(seeds.begin(), seeds.begin() + N * N);\n\n        // Create a grid to place the selected seeds\n        vector<vector<int>> grid(N, vector<int>(N));\n\n        // Optimized placement: highest potential seeds in positions with most neighbors\n        vector<pair<int, int>> positions;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                int neighbors = 0;\n                if (i > 0) neighbors++;\n                if (i < N-1) neighbors++;\n                if (j > 0) neighbors++;\n                if (j < N-1) neighbors++;\n                positions.emplace_back(neighbors, i * N + j);\n            }\n        }\n        sort(positions.rbegin(), positions.rend());\n\n        for (int i = 0; i < N * N; ++i) {\n            int pos = positions[i].second;\n            int x = pos / N;\n            int y = pos % N;\n            grid[x][y] = selected_seeds[i].id;\n        }\n\n        // Output the grid\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << grid[i][j];\n                if (j < N - 1) {\n                    cout << \" \";\n                }\n            }\n            cout << '\\n';\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seed_count; ++i) {\n            seeds[i].eval.resize(M);\n            seeds[i].id = i;\n            for (int j = 0; j < M; ++j) {\n                cin >> seeds[i].eval[j];\n            }\n            seeds[i].value = accumulate(seeds[i].eval.begin(), seeds[i].eval.end(), 0);\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        return x < other.x || (x == other.x && y < other.y);\n    }\n};\n\nstruct Takoyaki {\n    Point source, target;\n    bool operator<(const Takoyaki& other) const {\n        return source < other.source || (source == other.source && target < other.target);\n    }\n};\n\nvector<Point> find_takoyaki(const vector<string>& grid, char c) {\n    vector<Point> res;\n    for (int i = 0; i < grid.size(); ++i) {\n        for (int j = 0; j < grid[i].size(); ++j) {\n            if (grid[i][j] == c) {\n                res.emplace_back(i, j);\n            }\n        }\n    }\n    return res;\n}\n\nvector<Takoyaki> create_takoyaki_list(const vector<Point>& sources, const vector<Point>& targets) {\n    vector<Takoyaki> res;\n    for (int i = 0; i < sources.size(); ++i) {\n        res.push_back({sources[i], targets[i]});\n    }\n    return res;\n}\n\nstruct TreeNode {\n    int parent;\n    int length;\n    TreeNode(int p = -1, int l = 1) : parent(p), length(l) {}\n};\n\nvector<TreeNode> design_tree(int V) {\n    vector<TreeNode> tree;\n    if (V == 1) {\n        return tree;\n    }\n    tree.emplace_back(0, 1);\n    if (V == 2) {\n        return tree;\n    }\n    tree.emplace_back(0, 2);\n    if (V == 3) {\n        return tree;\n    }\n    for (int i = 2; i < V; ++i) {\n        int p = (i - 1) / 2;\n        int l = 1 + (i % 2);\n        tree.emplace_back(p, l);\n    }\n    return tree;\n}\n\nPoint initial_root_position(int N, const vector<Takoyaki>& takoyakis) {\n    int sum_x = 0, sum_y = 0;\n    for (const auto& t : takoyakis) {\n        sum_x += t.source.x + t.target.x;\n        sum_y += t.source.y + t.target.y;\n    }\n    int cnt = 2 * takoyakis.size();\n    return Point(sum_x / cnt, sum_y / cnt);\n}\n\nvector<string> generate_operations(const vector<TreeNode>& tree, const Point& root_pos,\n                                   const vector<Takoyaki>& takoyakis, int N) {\n    vector<string> operations;\n    int V = tree.size() + 1;\n    vector<Point> fingertip_pos(V);\n    vector<int> dir(V, 0); // 0: right, 1: down, 2: left, 3: up\n    vector<bool> holding(V, false);\n    vector<Point> current_pos(V);\n    current_pos[0] = root_pos;\n\n    auto update_positions = [&]() {\n        for (int i = 1; i < V; ++i) {\n            int p = tree[i-1].parent;\n            int l = tree[i-1].length;\n            int dx = 0, dy = 0;\n            if (dir[i] == 0) { dx = l; }\n            else if (dir[i] == 1) { dy = l; }\n            else if (dir[i] == 2) { dx = -l; }\n            else if (dir[i] == 3) { dy = -l; }\n            current_pos[i] = Point(current_pos[p].x + dx, current_pos[p].y + dy);\n        }\n    };\n\n    update_positions();\n\n    auto move_root = [&](int dx, int dy) {\n        current_pos[0].x += dx;\n        current_pos[0].y += dy;\n        update_positions();\n    };\n\n    auto rotate_subtree = [&](int u, bool clockwise) {\n        if (clockwise) {\n            dir[u] = (dir[u] + 1) % 4;\n        } else {\n            dir[u] = (dir[u] + 3) % 4;\n        }\n        update_positions();\n    };\n\n    auto can_grab = [&](int u, const Point& p) {\n        return current_pos[u] == p && !holding[u];\n    };\n\n    auto can_release = [&](int u, const Point& p) {\n        return current_pos[u] == p && holding[u];\n    };\n\n    auto bfs_path = [&](Point start, Point target) {\n        vector<vector<int>> dist(N, vector<int>(N, -1));\n        vector<vector<Point>> prev(N, vector<Point>(N, Point(-1, -1)));\n        queue<Point> q;\n        dist[start.x][start.y] = 0;\n        q.push(start);\n        vector<int> dx = {0, 1, 0, -1};\n        vector<int> dy = {1, 0, -1, 0};\n        while (!q.empty()) {\n            Point p = q.front();\n            q.pop();\n            if (p == target) {\n                vector<Point> path;\n                while (p != start) {\n                    path.push_back(p);\n                    p = prev[p.x][p.y];\n                }\n                reverse(path.begin(), path.end());\n                return path;\n            }\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + dx[i];\n                int ny = p.y + dy[i];\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N && dist[nx][ny] == -1) {\n                    dist[nx][ny] = dist[p.x][p.y] + 1;\n                    prev[nx][ny] = p;\n                    q.emplace(nx, ny);\n                }\n            }\n        }\n        return vector<Point>();\n    };\n\n    auto move_to = [&](Point target) {\n        vector<Point> path = bfs_path(current_pos[0], target);\n        for (Point p : path) {\n            int dx = p.x - current_pos[0].x;\n            int dy = p.y - current_pos[0].y;\n            if (dx == 1) {\n                operations.push_back(\"D\" + string(V-1, '.') + string(V, '.'));\n                move_root(1, 0);\n            } else if (dx == -1) {\n                operations.push_back(\"U\" + string(V-1, '.') + string(V, '.'));\n                move_root(-1, 0);\n            } else if (dy == 1) {\n                operations.push_back(\"R\" + string(V-1, '.') + string(V, '.'));\n                move_root(0, 1);\n            } else if (dy == -1) {\n                operations.push_back(\"L\" + string(V-1, '.') + string(V, '.'));\n                move_root(0, -1);\n            }\n        }\n    };\n\n    auto align_fingertip = [&](int u, Point target) {\n        Point p = current_pos[u];\n        int dx = target.x - p.x;\n        int dy = target.y - p.y;\n        int required_dir = -1;\n        if (dx > 0 && dy == 0) required_dir = 0;\n        else if (dx == 0 && dy > 0) required_dir = 1;\n        else if (dx < 0 && dy == 0) required_dir = 2;\n        else if (dx == 0 && dy < 0) required_dir = 3;\n        if (required_dir == -1) return;\n        while (dir[u] != required_dir) {\n            bool clockwise = (dir[u] + 1) % 4 == required_dir;\n            string op(V*2, '.');\n            op[0] = '.';\n            op[u] = clockwise ? 'R' : 'L';\n            operations.push_back(op);\n            rotate_subtree(u, clockwise);\n        }\n    };\n\n    auto process_takoyaki = [&](const Takoyaki& t) {\n        // Move to source\n        move_to(t.source);\n        // Align fingertip to source\n        for (int u = 1; u < V; ++u) {\n            if (!holding[u]) {\n                align_fingertip(u, t.source);\n                if (can_grab(u, t.source)) {\n                    string op(V*2, '.');\n                    op[V + u] = 'P';\n                    operations.push_back(op);\n                    holding[u] = true;\n                    break;\n                }\n            }\n        }\n        // Move to target\n        move_to(t.target);\n        // Align fingertip to target\n        for (int u = 1; u < V; ++u) {\n            if (holding[u]) {\n                align_fingertip(u, t.target);\n                if (can_release(u, t.target)) {\n                    string op(V*2, '.');\n                    op[V + u] = 'P';\n                    operations.push_back(op);\n                    holding[u] = false;\n                    break;\n                }\n            }\n        }\n    };\n\n    for (const auto& t : takoyakis) {\n        process_takoyaki(t);\n    }\n\n    return operations;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, V;\n    cin >> N >> M >> V;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        cin >> t[i];\n    }\n\n    vector<Point> sources = find_takoyaki(s, '1');\n    vector<Point> targets = find_takoyaki(t, '1');\n    vector<Takoyaki> takoyakis = create_takoyaki_list(sources, targets);\n\n    vector<TreeNode> tree = design_tree(V);\n    Point root_pos = initial_root_position(N, takoyakis);\n\n    cout << tree.size() + 1 << '\\n';\n    for (const auto& node : tree) {\n        cout << node.parent << ' ' << node.length << '\\n';\n    }\n    cout << root_pos.x << ' ' << root_pos.y << '\\n';\n\n    vector<string> operations = generate_operations(tree, root_pos, takoyakis, N);\n    for (const string& op : operations) {\n        cout << op << '\\n';\n    }\n\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n    bool operator==(const Point& p) const {\n        return x == p.x && y == p.y;\n    }\n};\n\nint N;\nvector<Point> mackerels, sardines;\nvector<Point> polygon;\n\nbool is_inside(const vector<Point>& poly, const Point& p) {\n    int n = poly.size();\n    bool inside = false;\n    for (int i = 0, j = n - 1; i < n; j = i++) {\n        const Point& a = poly[i];\n        const Point& b = poly[j];\n        if (a.y == b.y) {\n            if (p.y == a.y && min(a.x, b.x) <= p.x && p.x <= max(a.x, b.x)) {\n                return true;\n            }\n            continue;\n        }\n        if ((a.y > p.y) != (b.y > p.y)) {\n            int x_intersect = (p.y - a.y) * (b.x - a.x) / (b.y - a.y) + a.x;\n            if (p.x == x_intersect) {\n                return true;\n            }\n            if (p.x < x_intersect) {\n                inside = !inside;\n            }\n        }\n    }\n    return inside;\n}\n\nvector<Point> initial_polygon() {\n    int min_x = 1e9, max_x = -1, min_y = 1e9, max_y = -1;\n    for (const Point& p : mackerels) {\n        min_x = min(min_x, p.x);\n        max_x = max(max_x, p.x);\n        min_y = min(min_y, p.y);\n        max_y = max(max_y, p.y);\n    }\n    vector<Point> poly = {\n        {min_x, min_y},\n        {max_x, min_y},\n        {max_x, max_y},\n        {min_x, max_y}\n    };\n    return poly;\n}\n\nvector<Point> adjust_polygon(vector<Point> poly) {\n    vector<bool> mackerel_inside(N, false);\n    vector<bool> sardine_inside(N, false);\n    int a = 0, b = 0;\n\n    for (int i = 0; i < N; ++i) {\n        mackerel_inside[i] = is_inside(poly, mackerels[i]);\n        if (mackerel_inside[i]) a++;\n    }\n    for (int i = 0; i < N; ++i) {\n        sardine_inside[i] = is_inside(poly, sardines[i]);\n        if (sardine_inside[i]) b++;\n    }\n\n    int best_score = max(0, a - b + 1);\n    vector<Point> best_poly = poly;\n\n    auto update_counts = [&](const vector<Point>& old_poly, const vector<Point>& new_poly) {\n        int delta_a = 0, delta_b = 0;\n        for (int i = 0; i < N; ++i) {\n            bool old_inside = mackerel_inside[i];\n            bool new_inside = is_inside(new_poly, mackerels[i]);\n            if (old_inside && !new_inside) delta_a--;\n            else if (!old_inside && new_inside) delta_a++;\n            mackerel_inside[i] = new_inside;\n        }\n        for (int i = 0; i < N; ++i) {\n            bool old_inside = sardine_inside[i];\n            bool new_inside = is_inside(new_poly, sardines[i]);\n            if (old_inside && !new_inside) delta_b--;\n            else if (!old_inside && new_inside) delta_b++;\n            sardine_inside[i] = new_inside;\n        }\n        return make_pair(a + delta_a, b + delta_b);\n    };\n\n    auto try_move_vertex = [&](int vertex_idx, int dx, int dy) {\n        if (poly.size() >= 1000) return;\n        vector<Point> new_poly = poly;\n        int prev = (vertex_idx - 1 + poly.size()) % poly.size();\n        int next = (vertex_idx + 1) % poly.size();\n        if (poly[prev].x == poly[vertex_idx].x && poly[vertex_idx].x == poly[next].x) {\n            new_poly[vertex_idx].y += dy;\n        } else if (poly[prev].y == poly[vertex_idx].y && poly[vertex_idx].y == poly[next].y) {\n            new_poly[vertex_idx].x += dx;\n        } else {\n            return;\n        }\n        auto [new_a, new_b] = update_counts(poly, new_poly);\n        int new_score = max(0, new_a - new_b + 1);\n        if (new_score > best_score) {\n            best_score = new_score;\n            best_poly = new_poly;\n            a = new_a;\n            b = new_b;\n            poly = new_poly;\n        }\n    };\n\n    auto try_add_vertex = [&](int edge_idx, Point new_vertex) {\n        if (poly.size() >= 1000) return;\n        int i = edge_idx;\n        int j = (i + 1) % poly.size();\n        if (poly[i].x == poly[j].x) {\n            if (new_vertex.x != poly[i].x) return;\n        } else if (poly[i].y == poly[j].y) {\n            if (new_vertex.y != poly[i].y) return;\n        } else {\n            return;\n        }\n        vector<Point> new_poly = poly;\n        new_poly.insert(new_poly.begin() + i + 1, new_vertex);\n        auto [new_a, new_b] = update_counts(poly, new_poly);\n        int new_score = max(0, new_a - new_b + 1);\n        if (new_score > best_score) {\n            best_score = new_score;\n            best_poly = new_poly;\n            a = new_a;\n            b = new_b;\n            poly = new_poly;\n        }\n    };\n\n    for (int iter = 0; iter < 3; ++iter) {\n        for (int vertex_idx = 0; vertex_idx < poly.size(); ++vertex_idx) {\n            for (int dx = -50; dx <= 50; dx += 50) {\n                try_move_vertex(vertex_idx, dx, 0);\n            }\n            for (int dy = -50; dy <= 50; dy += 50) {\n                try_move_vertex(vertex_idx, 0, dy);\n            }\n        }\n        for (int edge_idx = 0; edge_idx < poly.size(); ++edge_idx) {\n            int i = edge_idx;\n            int j = (i + 1) % poly.size();\n            if (poly[i].x == poly[j].x) {\n                int x = poly[i].x;\n                int y_min = min(poly[i].y, poly[j].y);\n                int y_max = max(poly[i].y, poly[j].y);\n                for (int y = y_min + 50; y < y_max; y += 100) {\n                    try_add_vertex(edge_idx, Point(x, y));\n                }\n            } else if (poly[i].y == poly[j].y) {\n                int y = poly[i].y;\n                int x_min = min(poly[i].x, poly[j].x);\n                int x_max = max(poly[i].x, poly[j].x);\n                for (int x = x_min + 50; x < x_max; x += 100) {\n                    try_add_vertex(edge_idx, Point(x, y));\n                }\n            }\n        }\n    }\n\n    return best_poly;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    mackerels.resize(N);\n    sardines.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> mackerels[i].x >> mackerels[i].y;\n    }\n    for (int i = 0; i < N; ++i) {\n        cin >> sardines[i].x >> sardines[i].y;\n    }\n\n    polygon = initial_polygon();\n    polygon = adjust_polygon(polygon);\n\n    cout << polygon.size() << '\\n';\n    for (const Point& p : polygon) {\n        cout << p.x << ' ' << p.y << '\\n';\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\nusing namespace std::chrono;\n\nstruct Rectangle {\n    int id;\n    int w, h;\n    int x, y;\n    bool rotated;\n};\n\nstruct Placement {\n    int p, r;\n    char d;\n    int b;\n};\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nvector<Rectangle> place_rectangles(const vector<pair<int, int>>& observed, const vector<Placement>& placements) {\n    vector<Rectangle> placed;\n    for (const auto& pl : placements) {\n        int id = pl.p;\n        bool rotated = pl.r;\n        int w = observed[id].first;\n        int h = observed[id].second;\n        if (rotated) swap(w, h);\n\n        int x = 0, y = 0;\n        if (pl.d == 'U') {\n            if (pl.b == -1) {\n                x = 0;\n            } else {\n                x = placed[pl.b].x + placed[pl.b].w;\n            }\n            int max_y = 0;\n            for (const auto& rect : placed) {\n                if (rect.x < x + w && rect.x + rect.w > x) {\n                    if (rect.y + rect.h > max_y) {\n                        max_y = rect.y + rect.h;\n                    }\n                }\n            }\n            y = max_y;\n        } else if (pl.d == 'L') {\n            if (pl.b == -1) {\n                y = 0;\n            } else {\n                y = placed[pl.b].y + placed[pl.b].h;\n            }\n            int max_x = 0;\n            for (const auto& rect : placed) {\n                if (rect.y < y + h && rect.y + rect.h > y) {\n                    if (rect.x + rect.w > max_x) {\n                        max_x = rect.x + rect.w;\n                    }\n                }\n            }\n            x = max_x;\n        }\n        placed.push_back({id, w, h, x, y, rotated});\n    }\n    return placed;\n}\n\npair<int, int> calculate_dimensions(const vector<Rectangle>& placed) {\n    int max_x = 0, max_y = 0;\n    for (const auto& rect : placed) {\n        max_x = max(max_x, rect.x + rect.w);\n        max_y = max(max_y, rect.y + rect.h);\n    }\n    return {max_x, max_y};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n    vector<pair<int, int>> observed(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> observed[i].first >> observed[i].second;\n    }\n\n    vector<pair<int, int>> measurements;\n    for (int t = 0; t < T; ++t) {\n        vector<Placement> placements;\n        vector<bool> used(N, false);\n\n        for (int i = 0; i < N; ++i) {\n            int best_r = 0;\n            char best_d = 'U';\n            int best_b = -1;\n            double min_score = 1e18;\n\n            // Smart reference selection\n            vector<int> ref_rects = {-1};\n            for (int b = max(0, (int)placements.size() - 10); b < placements.size(); ++b) {\n                ref_rects.push_back(b);\n            }\n\n            for (int r = 0; r < 2; ++r) {\n                for (char d : {'U', 'L'}) {\n                    for (int b : ref_rects) {\n                        placements.push_back({i, r, d, b});\n                        auto placed = place_rectangles(observed, placements);\n                        auto [W, H] = calculate_dimensions(placed);\n                        // Enhanced scoring metric\n                        double aspect_ratio = (double)max(W, H) / min(W, H);\n                        double score = W + H + 0.05 * aspect_ratio * (W + H);\n                        if (score < min_score) {\n                            min_score = score;\n                            best_r = r;\n                            best_d = d;\n                            best_b = b;\n                        }\n                        placements.pop_back();\n                    }\n                }\n            }\n\n            // Adaptive randomness based on turn and current score\n            double random_prob = 0.2 * (1.0 - (double)t/T) * (1.0 - exp(-min_score/1e6));\n            if (t < T/2 && (double)rng()/rng.max() < random_prob) {\n                best_r = rng() % 2;\n                best_d = (rng() % 2) ? 'U' : 'L';\n                best_b = (placements.empty()) ? -1 : rng() % placements.size();\n            }\n\n            placements.push_back({i, best_r, best_d, best_b});\n        }\n\n        cout << placements.size() << '\\n';\n        for (const auto& pl : placements) {\n            cout << pl.p << ' ' << pl.r << ' ' << pl.d << ' ' << pl.b << '\\n';\n        }\n        cout.flush();\n\n        int W_prime, H_prime;\n        cin >> W_prime >> H_prime;\n        measurements.emplace_back(W_prime, H_prime);\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <set>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nstruct Vertex {\n    int id;\n    int a;\n    int x, y;\n    vector<int> neighbors;\n};\n\nstruct BFSState {\n    int vertex;\n    int parent;\n    int depth;\n    bool operator<(const BFSState& other) const {\n        if (depth != other.depth) return depth > other.depth;\n        return a[vertex] < a[other.vertex];\n    }\n    static vector<int> a;\n};\n\nvector<int> BFSState::a;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    cin >> N >> M >> H;\n\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> A[i];\n    }\n    BFSState::a = A;\n\n    vector<pair<int, int>> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].first >> edges[i].second;\n    }\n\n    vector<pair<int, int>> coords(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> coords[i].first >> coords[i].second;\n    }\n\n    vector<Vertex> vertices(N);\n    for (int i = 0; i < N; ++i) {\n        vertices[i].id = i;\n        vertices[i].a = A[i];\n        vertices[i].x = coords[i].first;\n        vertices[i].y = coords[i].second;\n    }\n\n    for (const auto& edge : edges) {\n        int u = edge.first;\n        int v = edge.second;\n        vertices[u].neighbors.push_back(v);\n        vertices[v].neighbors.push_back(u);\n    }\n\n    vector<int> parent(N, -1);\n    vector<bool> assigned(N, false);\n\n    while (true) {\n        int root = -1;\n        int max_a = -1;\n        for (int i = 0; i < N; ++i) {\n            if (!assigned[i] && A[i] > max_a) {\n                max_a = A[i];\n                root = i;\n            }\n        }\n        if (root == -1) break;\n\n        priority_queue<BFSState> pq;\n        pq.push({root, -1, 0});\n        vector<bool> visited(N, false);\n        visited[root] = true;\n\n        while (!pq.empty()) {\n            BFSState current = pq.top();\n            pq.pop();\n            if (current.depth > H) continue;\n            if (assigned[current.vertex]) continue;\n\n            parent[current.vertex] = current.parent;\n            assigned[current.vertex] = true;\n\n            for (int neighbor : vertices[current.vertex].neighbors) {\n                if (!visited[neighbor] && !assigned[neighbor]) {\n                    visited[neighbor] = true;\n                    pq.push({neighbor, current.vertex, current.depth + 1});\n                }\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <set>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_MOVES = 4 * N * N;\n\nvector<string> board;\nvector<pair<int, int>> oni_positions;\nvector<pair<int, int>> fuku_positions;\nvector<pair<char, int>> moves;\n\nvoid update_board() {\n    board.assign(N, string(N, '.'));\n    for (const auto& p : oni_positions) {\n        if (p.first >= 0 && p.first < N && p.second >= 0 && p.second < N) {\n            board[p.first][p.second] = 'x';\n        }\n    }\n    for (const auto& p : fuku_positions) {\n        if (p.first >= 0 && p.first < N && p.second >= 0 && p.second < N) {\n            board[p.first][p.second] = 'o';\n        }\n    }\n}\n\nvoid shift_row_left(int i) {\n    moves.emplace_back('L', i);\n    for (auto& p : oni_positions) {\n        if (p.first == i) {\n            p.second--;\n        }\n    }\n    for (auto& p : fuku_positions) {\n        if (p.first == i) {\n            p.second--;\n        }\n    }\n    update_board();\n}\n\nvoid shift_row_right(int i) {\n    moves.emplace_back('R', i);\n    for (auto& p : oni_positions) {\n        if (p.first == i) {\n            p.second++;\n        }\n    }\n    for (auto& p : fuku_positions) {\n        if (p.first == i) {\n            p.second++;\n        }\n    }\n    update_board();\n}\n\nvoid shift_col_up(int j) {\n    moves.emplace_back('U', j);\n    for (auto& p : oni_positions) {\n        if (p.second == j) {\n            p.first--;\n        }\n    }\n    for (auto& p : fuku_positions) {\n        if (p.second == j) {\n            p.first--;\n        }\n    }\n    update_board();\n}\n\nvoid shift_col_down(int j) {\n    moves.emplace_back('D', j);\n    for (auto& p : oni_positions) {\n        if (p.second == j) {\n            p.first++;\n        }\n    }\n    for (auto& p : fuku_positions) {\n        if (p.second == j) {\n            p.first++;\n        }\n    }\n    update_board();\n}\n\nbool is_safe_up(int i, int j) {\n    for (const auto& p : fuku_positions) {\n        if (p.second == j && p.first < i) {\n            return false;\n        }\n    }\n    return true;\n}\n\nbool is_safe_down(int i, int j) {\n    for (const auto& p : fuku_positions) {\n        if (p.second == j && p.first > i) {\n            return false;\n        }\n    }\n    return true;\n}\n\nbool is_safe_left(int i, int j) {\n    for (const auto& p : fuku_positions) {\n        if (p.first == i && p.second < j) {\n            return false;\n        }\n    }\n    return true;\n}\n\nbool is_safe_right(int i, int j) {\n    for (const auto& p : fuku_positions) {\n        if (p.first == i && p.second > j) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid remove_oni() {\n    set<pair<int, int>> oni_set(oni_positions.begin(), oni_positions.end());\n\n    while (!oni_set.empty()) {\n        // Find the Oni closest to any edge\n        auto best_oni = *oni_set.begin();\n        int min_dist = min({best_oni.first, N-1-best_oni.first,\n                          best_oni.second, N-1-best_oni.second});\n\n        for (const auto& oni : oni_set) {\n            int dist = min({oni.first, N-1-oni.first,\n                          oni.second, N-1-oni.second});\n            if (dist < min_dist) {\n                min_dist = dist;\n                best_oni = oni;\n            }\n        }\n\n        int i = best_oni.first;\n        int j = best_oni.second;\n\n        // Verify the Oni is still on the board\n        if (board[i][j] != 'x') {\n            oni_set.erase(best_oni);\n            continue;\n        }\n\n        // Determine safe directions\n        bool safe_up = is_safe_up(i, j);\n        bool safe_down = is_safe_down(i, j);\n        bool safe_left = is_safe_left(i, j);\n        bool safe_right = is_safe_right(i, j);\n\n        // Choose the direction that requires fewest shifts\n        if (safe_up) {\n            for (int k = 0; k < i + 1; ++k) shift_col_up(j);\n        } else if (safe_down) {\n            for (int k = 0; k < N - i; ++k) shift_col_down(j);\n        } else if (safe_left) {\n            for (int k = 0; k < j + 1; ++k) shift_row_left(i);\n        } else if (safe_right) {\n            for (int k = 0; k < N - j; ++k) shift_row_right(i);\n        }\n\n        // Remove the Oni from our set\n        oni_set.erase(best_oni);\n\n        // Update oni_positions\n        oni_positions.clear();\n        for (const auto& p : oni_set) {\n            oni_positions.push_back(p);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    board.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n    }\n\n    // Collect initial Oni and Fukunokami positions\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                oni_positions.emplace_back(i, j);\n            } else if (board[i][j] == 'o') {\n                fuku_positions.emplace_back(i, j);\n            }\n        }\n    }\n\n    remove_oni();\n\n    // Output the moves\n    for (const auto& move : moves) {\n        cout << move.first << \" \" << move.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <climits>\n#include <cmath>\n#include <numeric>\n#include <queue>\n\nusing namespace std;\n\nconst int N = 100;\nconst int L = 500000;\nconst int MAX_ITER = 25;\nconst int NUM_STARTS = 3;\nconst int INITIAL_TABU_TENURE = 15;\nconst int MIN_NEIGHBORHOOD = 3;\nconst int MAX_NEIGHBORHOOD = 20;\n\nstruct Employee {\n    int a, b;\n};\n\nvector<int> fast_simulate(const vector<Employee>& employees, const vector<int>& T, int max_weeks) {\n    vector<int> t(N, 0);\n    int current = 0;\n    t[current]++;\n    for (int week = 1; week < max_weeks; ++week) {\n        int cnt = t[current];\n        if (cnt % 2 == 1) {\n            current = employees[current].a;\n        } else {\n            current = employees[current].b;\n        }\n        t[current]++;\n    }\n    return t;\n}\n\nlong long calculate_error(const vector<int>& t, const vector<int>& T) {\n    long long error = 0;\n    for (int i = 0; i < N; ++i) {\n        error += abs(t[i] - T[i]);\n    }\n    return error;\n}\n\nvector<Employee> smart_initial(const vector<int>& T) {\n    vector<Employee> employees(N);\n    vector<int> current_t(N, 0);\n    current_t[0] = 1;\n    int current = 0;\n\n    vector<pair<int, int>> priority;\n    for (int i = 0; i < N; ++i) {\n        priority.emplace_back(T[i], i);\n    }\n    sort(priority.rbegin(), priority.rend());\n\n    vector<vector<int>> graph(N);\n    for (int i = 0; i < N; ++i) {\n        graph[i].push_back((i + 1) % N);\n        graph[i].push_back((i - 1 + N) % N);\n        graph[i].push_back((i + 10) % N);\n        graph[i].push_back((i - 10 + N) % N);\n    }\n\n    for (int week = 1; week < L; ++week) {\n        int cnt = current_t[current];\n        int best_next = -1;\n        int best_score = -1;\n        for (auto& p : priority) {\n            int i = p.second;\n            int score = (T[i] - current_t[i]) * 100;\n            for (int neighbor : graph[i]) {\n                score += (T[neighbor] - current_t[neighbor]) * 2;\n            }\n            if (score > best_score) {\n                best_score = score;\n                best_next = i;\n            }\n        }\n\n        if (best_next == -1) {\n            best_next = rand() % N;\n        }\n\n        if (cnt % 2 == 1) {\n            employees[current].a = best_next;\n        } else {\n            employees[current].b = best_next;\n        }\n        current = best_next;\n        current_t[current]++;\n    }\n    return employees;\n}\n\nvector<Employee> optimized_search(const vector<int>& T, vector<Employee> employees, int max_iter = MAX_ITER) {\n    auto t = fast_simulate(employees, T, min(L, 30000));\n    long long best_error = calculate_error(t, T);\n    vector<Employee> best_employees = employees;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<double> dist(0.0, 1.0);\n\n    vector<pair<int, int>> tabu_list;\n    int tabu_tenure = INITIAL_TABU_TENURE;\n\n    double temperature = 1.0;\n    double cooling_rate = 0.95;\n    int neighborhood_size = MIN_NEIGHBORHOOD;\n    int sample_size = 30000;\n\n    for (int iter = 0; iter < max_iter; ++iter) {\n        bool improved = false;\n        vector<int> indices(N);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), gen);\n\n        for (int i : indices) {\n            vector<int> candidates;\n            for (int j = 0; j < N; ++j) {\n                if (j != employees[i].a) candidates.push_back(j);\n                if (j != employees[i].b) candidates.push_back(j);\n            }\n            shuffle(candidates.begin(), candidates.end(), gen);\n            candidates.resize(min(neighborhood_size, (int)candidates.size()));\n\n            for (int new_val : candidates) {\n                bool is_tabu = false;\n                for (auto& tabu : tabu_list) {\n                    if (tabu.first == i && tabu.second == new_val) {\n                        is_tabu = true;\n                        break;\n                    }\n                }\n                if (is_tabu) continue;\n\n                if (new_val == employees[i].a) continue;\n                auto old_a = employees[i].a;\n                employees[i].a = new_val;\n                auto new_t = fast_simulate(employees, T, sample_size);\n                long long new_error = calculate_error(new_t, T);\n                double delta = new_error - best_error;\n\n                if (delta < 0 || (delta > 0 && dist(gen) < exp(-delta / temperature))) {\n                    if (new_error < best_error) {\n                        best_error = new_error;\n                        best_employees = employees;\n                        improved = true;\n                        neighborhood_size = max(MIN_NEIGHBORHOOD, neighborhood_size - 1);\n                    } else {\n                        neighborhood_size = min(MAX_NEIGHBORHOOD, neighborhood_size + 1);\n                    }\n                    tabu_list.emplace_back(i, old_a);\n                    if (tabu_list.size() > tabu_tenure) {\n                        tabu_list.erase(tabu_list.begin());\n                    }\n                } else {\n                    employees[i].a = old_a;\n                }\n            }\n\n            if (improved) break;\n\n            for (int new_val : candidates) {\n                bool is_tabu = false;\n                for (auto& tabu : tabu_list) {\n                    if (tabu.first == i && tabu.second == new_val) {\n                        is_tabu = true;\n                        break;\n                    }\n                }\n                if (is_tabu) continue;\n\n                if (new_val == employees[i].b) continue;\n                auto old_b = employees[i].b;\n                employees[i].b = new_val;\n                auto new_t = fast_simulate(employees, T, sample_size);\n                long long new_error = calculate_error(new_t, T);\n                double delta = new_error - best_error;\n\n                if (delta < 0 || (delta > 0 && dist(gen) < exp(-delta / temperature))) {\n                    if (new_error < best_error) {\n                        best_error = new_error;\n                        best_employees = employees;\n                        improved = true;\n                        neighborhood_size = max(MIN_NEIGHBORHOOD, neighborhood_size - 1);\n                    } else {\n                        neighborhood_size = min(MAX_NEIGHBORHOOD, neighborhood_size + 1);\n                    }\n                    tabu_list.emplace_back(i, old_b);\n                    if (tabu_list.size() > tabu_tenure) {\n                        tabu_list.erase(tabu_list.begin());\n                    }\n                } else {\n                    employees[i].b = old_b;\n                }\n            }\n\n            if (improved) break;\n        }\n\n        temperature *= cooling_rate;\n        sample_size = min(L, sample_size + 15000);\n        if (!improved) {\n            cooling_rate = max(0.8, cooling_rate * 0.95);\n            tabu_tenure = min(40, tabu_tenure + 2);\n        } else {\n            tabu_tenure = max(10, tabu_tenure - 1);\n        }\n    }\n    return best_employees;\n}\n\nvector<Employee> multi_start_search(const vector<int>& T) {\n    vector<Employee> best_employees(N);\n    long long best_error = LLONG_MAX;\n\n    for (int start = 0; start < NUM_STARTS; ++start) {\n        auto employees = smart_initial(T);\n        employees = optimized_search(T, employees);\n        auto t = fast_simulate(employees, T, L);\n        long long error = calculate_error(t, T);\n\n        if (error < best_error) {\n            best_error = error;\n            best_employees = employees;\n        }\n    }\n\n    return best_employees;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in, L_in;\n    cin >> N_in >> L_in;\n    vector<int> T(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    auto employees = multi_start_search(T);\n\n    for (const auto& emp : employees) {\n        cout << emp.a << \" \" << emp.b << \"\\n\";\n    }\n\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <atcoder/all>\nusing namespace std;\nusing namespace atcoder;\n\nstruct City {\n    int lx, rx, ly, ry;\n    int x, y; // Estimated coordinates\n};\n\nint N, M, Q, L, W;\nvector<int> G;\nvector<City> cities;\nvector<vector<int>> groups;\nvector<vector<pair<int, int>>> edges;\n\nvector<pair<int, int>> query(const vector<int>& C) {\n    if (C.size() < 2 || C.size() > L) {\n        cerr << \"Invalid query size: \" << C.size() << endl;\n        exit(1);\n    }\n    cout << \"? \" << C.size();\n    for (int c : C) cout << \" \" << c;\n    cout << endl;\n    cout.flush();\n\n    vector<pair<int, int>> res;\n    for (int i = 0; i < (int)C.size() - 1; ++i) {\n        int a, b;\n        cin >> a >> b;\n        res.emplace_back(a, b);\n    }\n    return res;\n}\n\nvoid answer() {\n    cout << \"!\" << endl;\n    for (int k = 0; k < M; ++k) {\n        for (int c : groups[k]) cout << c << \" \";\n        cout << endl;\n        for (auto [a, b] : edges[k]) {\n            cout << a << \" \" << b << endl;\n        }\n    }\n    cout.flush();\n}\n\nint estimate_distance(int a, int b) {\n    int min_dx = max(cities[a].lx - cities[b].rx, cities[b].lx - cities[a].rx);\n    int max_dx = max(cities[a].rx - cities[b].lx, cities[b].rx - cities[a].lx);\n    int min_dy = max(cities[a].ly - cities[b].ry, cities[b].ly - cities[a].ry);\n    int max_dy = max(cities[a].ry - cities[b].ly, cities[b].ry - cities[a].ly);\n\n    min_dx = max(0, min_dx);\n    min_dy = max(0, min_dy);\n\n    int min_dist = sqrt(min_dx * min_dx + min_dy * min_dy);\n    int max_dist = sqrt(max_dx * max_dx + max_dy * max_dy);\n\n    return (min_dist + max_dist) / 2;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M >> Q >> L >> W;\n    G.resize(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    cities.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].x = (cities[i].lx + cities[i].rx) / 2;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2;\n    }\n\n    // Initial grouping based on estimated coordinates and potential overlaps\n    vector<int> city_indices(N);\n    iota(city_indices.begin(), city_indices.end(), 0);\n    sort(city_indices.begin(), city_indices.end(), [&](int a, int b) {\n        if (cities[a].x != cities[b].x) return cities[a].x < cities[b].x;\n        return cities[a].y < cities[b].y;\n    });\n\n    groups.resize(M);\n    int start = 0;\n    for (int k = 0; k < M; ++k) {\n        for (int i = 0; i < G[k]; ++i) {\n            groups[k].push_back(city_indices[start + i]);\n        }\n        start += G[k];\n    }\n\n    // Perform queries to get MST edges\n    edges.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int n = groups[k].size();\n        if (n == 1) continue;\n        if (n == 2) {\n            edges[k].emplace_back(groups[k][0], groups[k][1]);\n            continue;\n        }\n\n        // Enhanced query strategy: prioritize cities with overlapping regions and close distances\n        vector<bool> queried(n, false);\n        for (int i = 0; i < n; ++i) {\n            if (queried[i]) continue;\n            vector<int> subset;\n            subset.push_back(groups[k][i]);\n            queried[i] = true;\n\n            // Find cities with overlapping regions\n            for (int j = 0; j < n && subset.size() < L; ++j) {\n                if (!queried[j]) {\n                    int a = groups[k][i];\n                    int b = groups[k][j];\n                    if (!(cities[a].rx < cities[b].lx || cities[b].rx < cities[a].lx ||\n                          cities[a].ry < cities[b].ly || cities[b].ry < cities[a].ly)) {\n                        subset.push_back(groups[k][j]);\n                        queried[j] = true;\n                    }\n                }\n            }\n\n            // If not enough overlapping cities, add closest cities based on estimated distance\n            if (subset.size() < 2) {\n                vector<pair<int, int>> candidates;\n                for (int j = 0; j < n; ++j) {\n                    if (!queried[j]) {\n                        int dist = estimate_distance(groups[k][i], groups[k][j]);\n                        candidates.emplace_back(dist, j);\n                    }\n                }\n                sort(candidates.begin(), candidates.end());\n                for (auto [dist, j] : candidates) {\n                    if (subset.size() >= L) break;\n                    subset.push_back(groups[k][j]);\n                    queried[j] = true;\n                }\n            }\n\n            if (subset.size() >= 2) {\n                auto res = query(subset);\n                for (auto [a, b] : res) {\n                    edges[k].emplace_back(a, b);\n                }\n            }\n        }\n    }\n\n    // Refinement step: Ensure each group is connected and minimize total road length\n    for (int k = 0; k < M; ++k) {\n        if (groups[k].size() == 1) continue;\n        dsu d(groups[k].size());\n        vector<pair<int, pair<int, int>>> mst_edges;\n\n        // Add edges from queries\n        for (auto [a, b] : edges[k]) {\n            auto it_a = find(groups[k].begin(), groups[k].end(), a);\n            auto it_b = find(groups[k].begin(), groups[k].end(), b);\n            if (it_a == groups[k].end() || it_b == groups[k].end()) continue;\n            int u = distance(groups[k].begin(), it_a);\n            int v = distance(groups[k].begin(), it_b);\n            mst_edges.emplace_back(0, make_pair(u, v));\n        }\n\n        // Add all possible edges with estimated distances\n        for (int i = 0; i < groups[k].size(); ++i) {\n            for (int j = i + 1; j < groups[k].size(); ++j) {\n                int dist = estimate_distance(groups[k][i], groups[k][j]);\n                mst_edges.emplace_back(dist, make_pair(i, j));\n            }\n        }\n\n        // Sort edges by estimated distance\n        sort(mst_edges.begin(), mst_edges.end());\n\n        // Kruskal's algorithm to find MST\n        edges[k].clear();\n        for (auto [dist, edge] : mst_edges) {\n            int u = edge.first;\n            int v = edge.second;\n            if (!d.same(u, v)) {\n                d.merge(u, v);\n                edges[k].emplace_back(groups[k][u], groups[k][v]);\n            }\n        }\n    }\n\n    // Aggressive refinement: Try to reassign cities to different groups\n    for (int iter = 0; iter < 3; ++iter) {\n        for (int k = 0; k < M; ++k) {\n            for (int i = 0; i < groups[k].size(); ++i) {\n                int city = groups[k][i];\n                for (int l = 0; l < M; ++l) {\n                    if (k == l) continue;\n                    if (groups[l].size() >= G[l]) continue;\n\n                    // Calculate current and potential road lengths\n                    int current_dist = 0;\n                    for (auto [a, b] : edges[k]) {\n                        if (a == city || b == city) {\n                            current_dist += estimate_distance(a, b);\n                        }\n                    }\n\n                    int new_dist = 0;\n                    for (int c : groups[l]) {\n                        new_dist += estimate_distance(city, c);\n                    }\n\n                    if (new_dist < current_dist) {\n                        groups[k].erase(groups[k].begin() + i);\n                        groups[l].push_back(city);\n\n                        // Rebuild MSTs\n                        edges[k].clear();\n                        edges[l].clear();\n\n                        if (groups[k].size() > 1) {\n                            dsu d_k(groups[k].size());\n                            vector<pair<int, pair<int, int>>> mst_edges_k;\n                            for (int ii = 0; ii < groups[k].size(); ++ii) {\n                                for (int jj = ii + 1; jj < groups[k].size(); ++jj) {\n                                    int dist = estimate_distance(groups[k][ii], groups[k][jj]);\n                                    mst_edges_k.emplace_back(dist, make_pair(ii, jj));\n                                }\n                            }\n                            sort(mst_edges_k.begin(), mst_edges_k.end());\n                            for (auto [dist, edge] : mst_edges_k) {\n                                int u = edge.first;\n                                int v = edge.second;\n                                if (!d_k.same(u, v)) {\n                                    d_k.merge(u, v);\n                                    edges[k].emplace_back(groups[k][u], groups[k][v]);\n                                }\n                            }\n                        }\n\n                        if (groups[l].size() > 1) {\n                            dsu d_l(groups[l].size());\n                            vector<pair<int, pair<int, int>>> mst_edges_l;\n                            for (int ii = 0; ii < groups[l].size(); ++ii) {\n                                for (int jj = ii + 1; jj < groups[l].size(); ++jj) {\n                                    int dist = estimate_distance(groups[l][ii], groups[l][jj]);\n                                    mst_edges_l.emplace_back(dist, make_pair(ii, jj));\n                                }\n                            }\n                            sort(mst_edges_l.begin(), mst_edges_l.end());\n                            for (auto [dist, edge] : mst_edges_l) {\n                                int u = edge.first;\n                                int v = edge.second;\n                                if (!d_l.same(u, v)) {\n                                    d_l.merge(u, v);\n                                    edges[l].emplace_back(groups[l][u], groups[l][v]);\n                                }\n                            }\n                        }\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    answer();\n\n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\nconst int M = 40;\nconst int MAX_ACTIONS = 2 * N * M;\nconst int BEAM_WIDTH = 200; // Increased beam width\n\nstruct State {\n    int i, j;\n    bitset<N*N> blocks;\n    int next_target;\n    vector<pair<char, char>> actions;\n    int score;\n\n    State(int i, int j, bitset<N*N> blocks, int next_target, vector<pair<char, char>> actions)\n        : i(i), j(j), blocks(blocks), next_target(next_target), actions(actions), score(0) {}\n\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n};\n\nvector<pair<int, int>> targets;\n\nint manhattan(int i1, int j1, int i2, int j2) {\n    return abs(i1 - i2) + abs(j1 - j2);\n}\n\nbool is_blocked(int i, int j, const bitset<N*N>& blocks) {\n    if (i < 0 || i >= N || j < 0 || j >= N) return true;\n    return blocks[i * N + j];\n}\n\nvector<State> expand(const State& state) {\n    vector<State> next_states;\n    vector<char> actions = {'S', 'A', 'M'}; // Prioritize Slide and Alter\n    vector<char> directions = {'U', 'D', 'L', 'R'};\n\n    for (char a : actions) {\n        for (char d : directions) {\n            State new_state = state;\n            new_state.actions.emplace_back(a, d);\n            int di = 0, dj = 0;\n            if (d == 'U') di = -1;\n            if (d == 'D') di = 1;\n            if (d == 'L') dj = -1;\n            if (d == 'R') dj = 1;\n\n            if (a == 'M') {\n                int ni = state.i + di, nj = state.j + dj;\n                if (!is_blocked(ni, nj, state.blocks)) {\n                    new_state.i = ni;\n                    new_state.j = nj;\n                } else {\n                    continue;\n                }\n            } else if (a == 'S') {\n                int ni = state.i, nj = state.j;\n                while (true) {\n                    int nni = ni + di, nnj = nj + dj;\n                    if (is_blocked(nni, nnj, state.blocks)) break;\n                    ni = nni;\n                    nj = nnj;\n                }\n                new_state.i = ni;\n                new_state.j = nj;\n            } else if (a == 'A') {\n                int ni = state.i + di, nj = state.j + dj;\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                new_state.blocks.flip(ni * N + nj);\n            }\n\n            // Check if next target is reached\n            if (new_state.next_target < M &&\n                new_state.i == targets[new_state.next_target].first &&\n                new_state.j == targets[new_state.next_target].second) {\n                new_state.next_target++;\n            }\n\n            // Enhanced evaluation function\n            int dist = 0;\n            if (new_state.next_target < M) {\n                dist = manhattan(new_state.i, new_state.j,\n                               targets[new_state.next_target].first,\n                               targets[new_state.next_target].second);\n            }\n            int remaining = M - new_state.next_target;\n            new_state.score = -new_state.actions.size() - dist - remaining * 1000;\n            next_states.push_back(new_state);\n        }\n    }\n    return next_states;\n}\n\nvector<pair<char, char>> beam_search(int start_i, int start_j) {\n    bitset<N*N> initial_blocks;\n    State initial_state(start_i, start_j, initial_blocks, 0, {});\n    priority_queue<State> beam;\n    beam.push(initial_state);\n\n    for (int step = 0; step < MAX_ACTIONS; ++step) {\n        priority_queue<State> next_beam;\n        for (int i = 0; i < BEAM_WIDTH && !beam.empty(); ++i) {\n            State current = beam.top();\n            beam.pop();\n            if (current.next_target == M) {\n                return current.actions;\n            }\n            vector<State> next_states = expand(current);\n            for (State& next_state : next_states) {\n                if (next_state.actions.size() <= MAX_ACTIONS) {\n                    next_beam.push(next_state);\n                }\n            }\n        }\n        beam = move(next_beam);\n    }\n\n    // Return the best found even if not all targets are visited\n    State best = beam.top();\n    return best.actions;\n}\n\nint main() {\n    int N_in, M_in;\n    cin >> N_in >> M_in;\n    targets.resize(M_in);\n    for (int i = 0; i < M_in; ++i) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n\n    vector<pair<char, char>> actions = beam_search(targets[0].first, targets[0].second);\n    for (auto [a, d] : actions) {\n        cout << a << \" \" << d << \"\\n\";\n    }\n    return 0;\n}"}}}