{"model_name":"gemini-3.1-flash-lite-preview-high","codes":{"1":{"ahc001":"#include <iostream>\n#include <vector>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Structure to represent an axis-aligned rectangle\nstruct Rect {\n    int x1, y1, x2, y2;\n};\n\nint N;\nvector<int> X, Y, R;\nvector<Rect> rects;\nvector<Rect> best_rects;\ndouble current_total_score = 0;\ndouble best_total_score = 0;\n\n// Calculate satisfaction p_i = 1 - (1 - min/max)^2 = 2x - x^2\ndouble get_p(int i, int s) {\n    double r = R[i];\n    double x = min(r, (double)s) / max(r, (double)s);\n    return 2.0 * x - x * x;\n}\n\n// Calculate the total satisfaction score for the current layout\ndouble get_total_score(const vector<Rect>& current_rects) {\n    double total = 0;\n    for (int i = 0; i < N; ++i) {\n        int s = (current_rects[i].x2 - current_rects[i].x1) * (current_rects[i].y2 - current_rects[i].y1);\n        total += get_p(i, s);\n    }\n    return total;\n}\n\n// Check if rectangle 'r' overlaps with any other rectangle\nbool check_overlap(int i, const Rect& r, const vector<Rect>& current_rects) {\n    for (int j = 0; j < N; ++j) {\n        if (i == j) continue;\n        if (r.x1 < current_rects[j].x2 && r.x2 > current_rects[j].x1 &&\n            r.y1 < current_rects[j].y2 && r.y2 > current_rects[j].y1) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    // Fast I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N)) return 0;\n    X.resize(N);\n    Y.resize(N);\n    R.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> X[i] >> Y[i] >> R[i];\n    }\n\n    // Initial state: Each rectangle is 1x1 at its target location\n    rects.resize(N);\n    for (int i = 0; i < N; ++i) {\n        rects[i] = {X[i], Y[i], X[i] + 1, Y[i] + 1};\n    }\n    best_rects = rects;\n\n    current_total_score = get_total_score(rects);\n    best_total_score = current_total_score;\n\n    mt19937 rng(1337);\n    auto start_time = chrono::steady_clock::now();\n\n    // Simulated Annealing parameters\n    double T_start = 0.1;\n    double T_end = 0.00001;\n    long long max_iterations = 5000000;\n    \n    // Main Simulated Annealing loop\n    for (long long iteration = 0; iteration < max_iterations; ++iteration) {\n        // Check time periodically\n        if ((iteration & 2047) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 4800) break;\n        }\n\n        int i = uniform_int_distribution<int>(0, N - 1)(rng);\n        int side = uniform_int_distribution<int>(0, 3)(rng);\n        \n        // Temperature scheduling\n        double progress = (double)iteration / max_iterations;\n        double T = T_start * pow(T_end / T_start, progress);\n        \n        // Adjust delta based on temperature to focus search\n        int delta_range = max(1.0, 100.0 * T / T_start);\n        int delta = uniform_int_distribution<int>(-delta_range, delta_range)(rng);\n\n        Rect next_rect = rects[i];\n        // Move one side, respecting constraints (must cover X[i], Y[i])\n        if (side == 0) { // x1\n            next_rect.x1 = max(0, min(X[i], next_rect.x1 + delta));\n        } else if (side == 1) { // x2\n            next_rect.x2 = max(X[i] + 1, min(10000, next_rect.x2 + delta));\n        } else if (side == 2) { // y1\n            next_rect.y1 = max(0, min(Y[i], next_rect.y1 + delta));\n        } else { // y2\n            next_rect.y2 = max(Y[i] + 1, min(10000, next_rect.y2 + delta));\n        }\n\n        // Validity check\n        if (next_rect.x1 == next_rect.x2 || next_rect.y1 == next_rect.y2) continue;\n        if (check_overlap(i, next_rect, rects)) continue;\n\n        // Calculate score change\n        int old_s = (rects[i].x2 - rects[i].x1) * (rects[i].y2 - rects[i].y1);\n        int new_s = (next_rect.x2 - next_rect.x1) * (next_rect.y2 - next_rect.y1);\n        \n        double delta_score = get_p(i, new_s) - get_p(i, old_s);\n\n        // Accept move based on Metropolis criterion\n        if (delta_score > 0 || (T > 0 && exp(delta_score / T) > uniform_real_distribution<double>(0, 1)(rng))) {\n            rects[i] = next_rect;\n            current_total_score += delta_score;\n            if (current_total_score > best_total_score) {\n                best_total_score = current_total_score;\n                best_rects = rects;\n            }\n        }\n    }\n\n    // Output final results\n    for (int i = 0; i < N; ++i) {\n        cout << best_rects[i].x1 << \" \" << best_rects[i].y1 << \" \" << best_rects[i].x2 << \" \" << best_rects[i].y2 << \"\\n\";\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\n// Global variables to store the problem data\nint si, sj;\nint t[50][50];\nint p[50][50];\nint M = 0;\nint tile_values[2500];\nvector<int> tile_neighbors[2500];\nbool is_visited_tile[2500];\nbool is_visited_square[50][50];\n\n// Direction arrays for movement\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dchar[] = {'U', 'D', 'L', 'R'};\n\n// Function to count unvisited neighbors of a given tile\nint count_unvisited_neighbors(int tile_id) {\n    int count = 0;\n    for (int neighbor : tile_neighbors[tile_id]) {\n        if (!is_visited_tile[neighbor]) {\n            count++;\n        }\n    }\n    return count;\n}\n\nint main() {\n    // Faster I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read input\n    cin >> si >> sj;\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> t[i][j];\n            M = max(M, t[i][j] + 1);\n        }\n    }\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> p[i][j];\n            tile_values[t[i][j]] += p[i][j];\n        }\n    }\n\n    // Precompute tile adjacency\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            int current_tile = t[i][j];\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dr[k];\n                int nj = j + dc[k];\n                if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n                    int neighbor_tile = t[ni][nj];\n                    if (current_tile != neighbor_tile) {\n                        tile_neighbors[current_tile].push_back(neighbor_tile);\n                    }\n                }\n            }\n        }\n    }\n    // Remove duplicates from neighbor lists\n    for (int i = 0; i < M; ++i) {\n        sort(tile_neighbors[i].begin(), tile_neighbors[i].end());\n        tile_neighbors[i].erase(unique(tile_neighbors[i].begin(), tile_neighbors[i].end()), tile_neighbors[i].end());\n    }\n\n    string best_path = \"\";\n    int max_total_score = -1;\n\n    auto start_time = chrono::high_resolution_clock::now();\n    mt19937 rng(12345);\n\n    // Randomized greedy loop\n    while (true) {\n        auto current_time = chrono::high_resolution_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count() > 1900) {\n            break;\n        }\n\n        // Reset state for each iteration\n        memset(is_visited_tile, 0, sizeof(is_visited_tile));\n        memset(is_visited_square, 0, sizeof(is_visited_square));\n        \n        string current_path = \"\";\n        int current_total_score = 0;\n        \n        int curr_r = si;\n        int curr_c = sj;\n        int curr_t = t[si][sj];\n        \n        is_visited_tile[curr_t] = true;\n        is_visited_square[curr_r][curr_c] = true;\n        current_total_score += p[curr_r][curr_c];\n        \n        // Randomization parameter for heuristic\n        int alpha = rng() % 50;\n\n        while (true) {\n            struct Candidate {\n                int r, c, dir_idx;\n                double score;\n            };\n            vector<Candidate> candidates;\n            \n            // Explore adjacent moves\n            for (int k = 0; k < 4; ++k) {\n                int nr = curr_r + dr[k];\n                int nc = curr_c + dc[k];\n                \n                if (nr >= 0 && nr < 50 && nc >= 0 && nc < 50 && !is_visited_square[nr][nc]) {\n                    int next_t = t[nr][nc];\n                    \n                    // Only move if same tile or new tile\n                    if (next_t == curr_t || !is_visited_tile[next_t]) {\n                        double score = 0;\n                        if (next_t != curr_t) {\n                            score = (double)tile_values[next_t] + (double)alpha * count_unvisited_neighbors(next_t);\n                        }\n                        // Add randomness to explore\n                        score += (rng() % 100) / 10.0;\n                        candidates.push_back({nr, nc, k, score});\n                    }\n                }\n            }\n            \n            if (candidates.empty()) break;\n            \n            // Choose the best candidate based on heuristic\n            int best_idx = 0;\n            for(size_t i = 1; i < candidates.size(); ++i) {\n                if (candidates[i].score > candidates[best_idx].score) best_idx = i;\n            }\n            \n            // Execute move\n            curr_r = candidates[best_idx].r;\n            curr_c = candidates[best_idx].c;\n            int dir = candidates[best_idx].dir_idx;\n            current_path += dchar[dir];\n            \n            int next_t = t[curr_r][curr_c];\n            if (next_t != curr_t) {\n                is_visited_tile[next_t] = true;\n                curr_t = next_t;\n            }\n            is_visited_square[curr_r][curr_c] = true;\n            current_total_score += p[curr_r][curr_c];\n        }\n        \n        // Update best path if we found a better one\n        if (current_total_score > max_total_score) {\n            max_total_score = current_total_score;\n            best_path = current_path;\n        }\n    }\n    \n    cout << best_path << endl;\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Grid dimensions are 30x30\nconst int R = 30;\nconst int C = 30;\n\n// 30x29 horizontal edges, 29x30 vertical edges\ndouble hor[R][C - 1];\ndouble ver[R - 1][C];\n\nstruct Node {\n    int r, c;\n    double dist;\n    bool operator>(const Node& other) const {\n        return dist > other.dist;\n    }\n};\n\n// Function to compute the shortest path using Dijkstra\nstring get_path(int sr, int sc, int tr, int tc) {\n    // Static arrays to avoid repeated reallocation\n    static double dist[R][C];\n    static pair<int, int> parent[R][C];\n    static char dir[R][C];\n    \n    for(int i=0; i<R; ++i) {\n        for(int j=0; j<C; ++j) {\n            dist[i][j] = 1e18;\n            parent[i][j] = {-1, -1};\n            dir[i][j] = ' ';\n        }\n    }\n    \n    priority_queue<Node, vector<Node>, greater<Node>> pq;\n    \n    dist[sr][sc] = 0;\n    pq.push({sr, sc, 0});\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    char dchar[] = {'U', 'D', 'L', 'R'};\n    \n    while (!pq.empty()) {\n        Node current = pq.top();\n        pq.pop();\n        \n        int r = current.r;\n        int c = current.c;\n        \n        if (current.dist > dist[r][c]) continue;\n        if (r == tr && c == tc) break;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i];\n            int nc = c + dc[i];\n            \n            if (nr >= 0 && nr < R && nc >= 0 && nc < C) {\n                double weight = 0;\n                // Determine weight based on movement type\n                if (i == 0) { // U: (r,c) -> (r-1,c)\n                    weight = ver[r - 1][c];\n                } else if (i == 1) { // D: (r,c) -> (r+1,c)\n                    weight = ver[r][c];\n                } else if (i == 2) { // L: (r,c) -> (r,c-1)\n                    weight = hor[r][c - 1];\n                } else if (i == 3) { // R: (r,c) -> (r,c+1)\n                    weight = hor[r][c];\n                }\n                \n                if (dist[nr][nc] > dist[r][c] + weight) {\n                    dist[nr][nc] = dist[r][c] + weight;\n                    parent[nr][nc] = {r, c};\n                    dir[nr][nc] = dchar[i];\n                    pq.push({nr, nc, dist[nr][nc]});\n                }\n            }\n        }\n    }\n    \n    // Reconstruct the path from parent pointers\n    string path = \"\";\n    int curr_r = tr;\n    int curr_c = tc;\n    while (curr_r != sr || curr_c != sc) {\n        char d = dir[curr_r][curr_c];\n        path += d;\n        pair<int, int> p = parent[curr_r][curr_c];\n        curr_r = p.first;\n        curr_c = p.second;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    // Fast I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    // Initialize weights to a neutral middle value 5000.0\n    for (int i = 0; i < R; ++i)\n        for (int j = 0; j < C - 1; ++j) hor[i][j] = 5000.0;\n    for (int i = 0; i < R - 1; ++i)\n        for (int j = 0; j < C; ++j) ver[i][j] = 5000.0;\n    \n    double alpha = 0.2; // Learning rate\n    \n    for (int k = 0; k < 1000; ++k) {\n        int sr, sc, tr, tc;\n        cin >> sr >> sc >> tr >> tc;\n        \n        string path = get_path(sr, sc, tr, tc);\n        cout << path << endl; // Path flushed automatically by endl\n        \n        int measured_len;\n        cin >> measured_len;\n        \n        // Calculate predicted path length based on current estimates\n        double path_len = 0;\n        int curr_r = sr;\n        int curr_c = sc;\n        \n        for (char d : path) {\n            if (d == 'U') path_len += ver[curr_r - 1][curr_c];\n            else if (d == 'D') path_len += ver[curr_r][curr_c];\n            else if (d == 'L') path_len += hor[curr_r][curr_c - 1];\n            else if (d == 'R') path_len += hor[curr_r][curr_c];\n            \n            if (d == 'U') curr_r--;\n            else if (d == 'D') curr_r++;\n            else if (d == 'L') curr_c--;\n            else if (d == 'R') curr_c++;\n        }\n        \n        if (path_len == 0) path_len = 1.0; \n        double ratio = (double)measured_len / path_len;\n        \n        // Update edge weights based on the observation\n        curr_r = sr;\n        curr_c = sc;\n        for (char d : path) {\n            double* w_ptr = nullptr;\n            if (d == 'U') w_ptr = &ver[curr_r - 1][curr_c];\n            else if (d == 'D') w_ptr = &ver[curr_r][curr_c];\n            else if (d == 'L') w_ptr = &hor[curr_r][curr_c - 1];\n            else if (d == 'R') w_ptr = &hor[curr_r][curr_c];\n            \n            *w_ptr *= (1.0 + alpha * (ratio - 1.0));\n            \n            // Constrain weights to prevent unrealistic values\n            if (*w_ptr < 100) *w_ptr = 100;\n            if (*w_ptr > 10000) *w_ptr = 10000;\n            \n            if (d == 'U') curr_r--;\n            else if (d == 'D') curr_r++;\n            else if (d == 'L') curr_c--;\n            else if (d == 'R') curr_c++;\n        }\n    }\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 20;\nint M;\nvector<string> S;\nint grid[N][N]; // 0-7: A-H, 8: .\nint mismatches[800][800];\nint num_valid[800]; // Number of valid placements for each string\nint count_c;\nint count_d; // Number of '.' cells\n\nstruct Placement {\n    int s_idx;\n    int p_idx;\n};\nvector<Placement> affected[N][N];\n\nstruct PlacementInfo {\n    int line_idx;\n    int start_pos;\n    string s;\n};\nvector<PlacementInfo> all_placements[800];\n\nint get_char_idx(char c) {\n    if (c == '.') return 8;\n    return c - 'A';\n}\n\nchar get_char(int idx) {\n    if (idx == 8) return '.';\n    return idx + 'A';\n}\n\nvoid init() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = 8; // '.'\n        }\n    }\n    count_c = 0;\n    count_d = N * N;\n\n    for (int i = 0; i < M; ++i) {\n        string s = S[i];\n        int len = s.length();\n        // 40 lines: 0-19 rows, 20-39 cols\n        for (int line = 0; line < 2 * N; ++line) {\n            for (int start = 0; start < N; ++start) {\n                int p_idx = line * N + start;\n                all_placements[i].push_back({line, start, s});\n                \n                // Mismatches initially len because grid is '.'\n                mismatches[i][p_idx] = len;\n                \n                for (int k = 0; k < len; ++k) {\n                    int r, c;\n                    if (line < N) {\n                        r = line;\n                        c = (start + k) % N;\n                    } else {\n                        r = (start + k) % N;\n                        c = line - N;\n                    }\n                    affected[r][c].push_back({i, p_idx});\n                }\n            }\n        }\n        num_valid[i] = 0;\n    }\n}\n\nvoid update_grid(int r, int c, int new_val) {\n    int old_val = grid[r][c];\n    if (old_val == new_val) return;\n\n    if (old_val == 8 && new_val != 8) count_d--;\n    else if (old_val != 8 && new_val == 8) count_d++;\n\n    grid[r][c] = new_val;\n\n    for (auto& p : affected[r][c]) {\n        int s_idx = p.s_idx;\n        int p_idx = p.p_idx;\n        \n        bool was_valid = (mismatches[s_idx][p_idx] == 0);\n        \n        PlacementInfo& pi = all_placements[s_idx][p_idx];\n        int len = pi.s.length();\n        int k = -1;\n        \n        if (pi.line_idx < N) {\n            k = (c - pi.start_pos + N) % N;\n        } else {\n            k = (r - pi.start_pos + N) % N;\n        }\n        \n        // Target character at this position\n        int target_idx = get_char_idx(pi.s[k]);\n        \n        auto matches = [&](int cell_val, int target) {\n            return cell_val == target;\n        };\n        \n        bool old_match = matches(old_val, target_idx);\n        bool new_match = matches(new_val, target_idx);\n        \n        if (!old_match && new_match) mismatches[s_idx][p_idx]--;\n        else if (old_match && !new_match) mismatches[s_idx][p_idx]++;\n        \n        bool is_valid = (mismatches[s_idx][p_idx] == 0);\n        \n        if (was_valid && !is_valid) {\n            num_valid[s_idx]--;\n            if (num_valid[s_idx] == 0) count_c--;\n        } else if (!was_valid && is_valid) {\n            if (num_valid[s_idx] == 0) count_c++;\n            num_valid[s_idx]++;\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in; cin >> N_in;\n    cin >> M;\n    S.resize(M);\n    for (int i = 0; i < M; ++i) cin >> S[i];\n\n    init();\n    \n    // Greedy initialization\n    vector<int> p(M);\n    for(int i=0; i<M; ++i) p[i] = i;\n    mt19937 rng(1337);\n    shuffle(p.begin(), p.end(), rng);\n    \n    for(int i : p) {\n        if (num_valid[i] > 0) continue;\n        int p_idx = rng() % all_placements[i].size();\n        PlacementInfo& pi = all_placements[i][p_idx];\n        \n        for (int k = 0; k < (int)pi.s.length(); ++k) {\n            int r, c;\n            if (pi.line_idx < N) {\n                r = pi.line_idx;\n                c = (pi.start_pos + k) % N;\n            } else {\n                r = (pi.start_pos + k) % N;\n                c = pi.line_idx - N;\n            }\n            if (grid[r][c] == 8) {\n                update_grid(r, c, get_char_idx(pi.s[k]));\n            }\n        }\n    }\n\n    // SA\n    double T = 1000.0;\n    double T_min = 0.1;\n    int iterations = 200000;\n    \n    auto get_score = [&]() {\n        if (count_c < M) return (long long)count_c * 10000;\n        return (long long)M * 10000 + count_d;\n    };\n    \n    long long current_score = get_score();\n    \n    for (int i = 0; i < iterations; ++i) {\n        int r = rng() % N;\n        int c = rng() % N;\n        int old_val = grid[r][c];\n        int new_val = rng() % 9; \n        \n        if (old_val == new_val) continue;\n        \n        update_grid(r, c, new_val);\n        long long next_score = get_score();\n        \n        double prob = exp((double)(next_score - current_score) / T);\n        if (next_score >= current_score || (rng() % 10000) / 10000.0 < prob) {\n            current_score = next_score;\n        } else {\n            update_grid(r, c, old_val);\n        }\n        T *= pow(T_min / 1000.0, 1.0 / iterations);\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << get_char(grid[i][j]);\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\n// Structure to represent a point on the grid\nstruct Point {\n    int r, c;\n    bool operator==(const Point& other) const {\n        return r == other.r && c == other.c;\n    }\n    bool operator!=(const Point& other) const {\n        return !(*this == other);\n    }\n};\n\nint N;\nint si, sj;\nvector<string> grid;\nvector<vector<int>> weights;\nvector<vector<vector<Point>>> visible_from;\nvector<Point> all_road_squares;\n\n// Helper to check if a square is a road\nbool is_road(int r, int c) {\n    return r >= 0 && r < N && c >= 0 && c < N && grid[r][c] != '#';\n}\n\n// Precompute visibility for all road squares\nvoid precompute_visibility() {\n    visible_from.resize(N, vector<vector<Point>>(N));\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            if (!is_road(r, c)) continue;\n            \n            // The square itself is visible\n            visible_from[r][c].push_back({r, c});\n            \n            // Horizontal and Vertical visibility\n            for (int nc = c + 1; nc < N && is_road(r, nc); ++nc) visible_from[r][c].push_back({r, nc});\n            for (int nc = c - 1; nc >= 0 && is_road(r, nc); --nc) visible_from[r][c].push_back({r, nc});\n            for (int nr = r + 1; nr < N && is_road(nr, c); ++nr) visible_from[r][c].push_back({nr, c});\n            for (int nr = r - 1; nr >= 0 && is_road(nr, c); --nr) visible_from[r][c].push_back({nr, c});\n        }\n    }\n}\n\n// BFS to find shortest paths and distances\nstruct BFSResult {\n    vector<vector<int>> dist;\n    vector<vector<Point>> parent;\n};\n\nBFSResult bfs(Point start) {\n    BFSResult res;\n    res.dist.assign(N, vector<int>(N, 1e9));\n    res.parent.assign(N, vector<Point>(N, {-1, -1}));\n    \n    queue<Point> q;\n    res.dist[start.r][start.c] = 0;\n    q.push(start);\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    \n    while (!q.empty()) {\n        Point curr = q.front();\n        q.pop();\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n            \n            if (is_road(nr, nc)) {\n                int cost = weights[nr][nc];\n                if (res.dist[nr][nc] > res.dist[curr.r][curr.c] + cost) {\n                    res.dist[nr][nc] = res.dist[curr.r][curr.c] + cost;\n                    res.parent[nr][nc] = curr;\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n    return res;\n}\n\n// Reconstruct path from start to end using BFS parent pointers\nstring get_moves(Point start, Point end, const vector<vector<Point>>& parent) {\n    string moves = \"\";\n    Point curr = end;\n    while (curr != start) {\n        Point p = parent[curr.r][curr.c];\n        if (curr.r == p.r - 1) moves += 'U';\n        else if (curr.r == p.r + 1) moves += 'D';\n        else if (curr.c == p.c - 1) moves += 'L';\n        else if (curr.c == p.c + 1) moves += 'R';\n        curr = p;\n    }\n    reverse(moves.begin(), moves.end());\n    return moves;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N >> si >> sj;\n    grid.resize(N);\n    weights.resize(N, vector<int>(N));\n    \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                weights[i][j] = grid[i][j] - '0';\n                all_road_squares.push_back({i, j});\n            }\n        }\n    }\n    \n    precompute_visibility();\n    \n    // Greedy set cover to find necessary squares to visit\n    vector<Point> must_visit;\n    must_visit.push_back({si, sj});\n    \n    vector<vector<bool>> covered(N, vector<bool>(N, false));\n    int uncovered_count = 0;\n    \n    auto mark_covered = [&](Point p) {\n        int count = 0;\n        for (auto& v : visible_from[p.r][p.c]) {\n            if (!covered[v.r][v.c]) {\n                covered[v.r][v.c] = true;\n                count++;\n            }\n        }\n        return count;\n    };\n    \n    uncovered_count = all_road_squares.size() - mark_covered({si, sj});\n    \n    while (uncovered_count > 0) {\n        Point best_p = {-1, -1};\n        int best_cover = -1;\n        \n        for (auto& p : all_road_squares) {\n            int current_cover = 0;\n            for (auto& v : visible_from[p.r][p.c]) {\n                if (!covered[v.r][v.c]) current_cover++;\n            }\n            if (current_cover > best_cover) {\n                best_cover = current_cover;\n                best_p = p;\n            }\n        }\n        \n        if (best_cover <= 0) break;\n        \n        must_visit.push_back(best_p);\n        uncovered_count -= mark_covered(best_p);\n    }\n    \n    // TSP: Nearest Neighbor heuristic\n    vector<Point> tour;\n    tour.push_back({si, sj});\n    \n    vector<bool> visited(must_visit.size(), false);\n    visited[0] = true;\n    \n    Point curr = {si, sj};\n    while (tour.size() < must_visit.size()) {\n        int best_idx = -1;\n        int min_dist = 1e9;\n        \n        BFSResult bfs_res = bfs(curr);\n        \n        for (int i = 0; i < must_visit.size(); ++i) {\n            if (!visited[i]) {\n                if (bfs_res.dist[must_visit[i].r][must_visit[i].c] < min_dist) {\n                    min_dist = bfs_res.dist[must_visit[i].r][must_visit[i].c];\n                    best_idx = i;\n                }\n            }\n        }\n        \n        tour.push_back(must_visit[best_idx]);\n        visited[best_idx] = true;\n        curr = must_visit[best_idx];\n    }\n    \n    // Return to start\n    tour.push_back({si, sj});\n    \n    // Build final path\n    string final_path = \"\";\n    for (int i = 0; i < tour.size() - 1; ++i) {\n        BFSResult bfs_res = bfs(tour[i]);\n        final_path += get_moves(tour[i], tour[i+1], bfs_res.parent);\n    }\n    \n    cout << final_path << endl;\n    \n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\n// Global variables to store problem state\nint N, M, K, R;\nvector<vector<int>> task_difficulty;\nvector<vector<int>> adj;\nvector<int> in_degree;\nvector<int> task_status; // -1: not started, 0: in progress, 1: completed\nvector<int> member_status; // -1: free, >=0: task_id\nvector<int> start_day;\nvector<vector<double>> s; // Skills estimation\nvector<int> H; // Task criticality (longest dependency chain)\n\n// Function to calculate predicted completion time for a task by a member\ndouble predict_t(int task_id, int member_id) {\n    double w = 0;\n    for (int k = 0; k < K; ++k) {\n        w += max(0, task_difficulty[task_id][k] - (int)s[member_id][k]);\n    }\n    // If w=0, completion time is 1. Otherwise, w is a good estimate.\n    if (w == 0) return 1.0;\n    return max(1.0, w);\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read input\n    cin >> N >> M >> K >> R;\n    task_difficulty.resize(N, vector<int>(K));\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            cin >> task_difficulty[i][k];\n        }\n    }\n    adj.resize(N);\n    in_degree.resize(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        adj[u].push_back(v);\n        in_degree[v]++;\n    }\n\n    // Precompute H (criticality/longest path in DAG)\n    H.resize(N, 1);\n    for (int i = N - 1; i >= 0; --i) {\n        for (int v : adj[i]) {\n            H[i] = max(H[i], 1 + H[v]);\n        }\n    }\n\n    // Initialization\n    task_status.assign(N, -1);\n    member_status.assign(M, -1);\n    start_day.assign(N, -1);\n    s.assign(M, vector<double>(K, 30.0)); // Initial skill guess\n    vector<int> ready_tasks;\n    for (int i = 0; i < N; ++i) {\n        if (in_degree[i] == 0) {\n            ready_tasks.push_back(i);\n        }\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n\n        // 1. Assign tasks\n        // Sort ready_tasks by criticality (H)\n        sort(ready_tasks.begin(), ready_tasks.end(), [&](int a, int b) {\n            return H[a] > H[b];\n        });\n\n        vector<pair<int, int>> assignments;\n        vector<int> free_members;\n        for (int j = 0; j < M; ++j) {\n            if (member_status[j] == -1) {\n                free_members.push_back(j);\n            }\n        }\n\n        // Greedy matching of ready tasks to free members\n        vector<bool> task_assigned(ready_tasks.size(), false);\n        vector<bool> member_assigned(free_members.size(), false);\n        \n        for (int i = 0; i < (int)ready_tasks.size(); ++i) {\n            int task_id = ready_tasks[i];\n            \n            // Find best free member for this task\n            int best_member_idx = -1;\n            double min_t = 1e18;\n            for (int j = 0; j < (int)free_members.size(); ++j) {\n                if (member_assigned[j]) continue;\n                double t = predict_t(task_id, free_members[j]);\n                if (t < min_t) {\n                    min_t = t;\n                    best_member_idx = j;\n                }\n            }\n\n            if (best_member_idx != -1) {\n                int member_id = free_members[best_member_idx];\n                assignments.push_back({member_id + 1, task_id + 1});\n                member_status[member_id] = task_id;\n                task_status[task_id] = 0;\n                start_day[task_id] = day;\n                member_assigned[best_member_idx] = true;\n                task_assigned[i] = true;\n            }\n        }\n\n        // Update ready_tasks: remove assigned ones\n        vector<int> next_ready_tasks;\n        for (int i = 0; i < (int)ready_tasks.size(); ++i) {\n            if (!task_assigned[i]) {\n                next_ready_tasks.push_back(ready_tasks[i]);\n            }\n        }\n        ready_tasks = next_ready_tasks;\n\n        // Output assignments and flush\n        cout << assignments.size();\n        for (auto& p : assignments) {\n            cout << \" \" << p.first << \" \" << p.second;\n        }\n        cout << endl;\n\n        // 2. Read completed tasks\n        int n_completed;\n        cin >> n_completed;\n        if (n_completed == -1) break;\n        \n        for (int i = 0; i < n_completed; ++i) {\n            int member_id;\n            cin >> member_id;\n            --member_id;\n            int task_id = member_status[member_id];\n            \n            // Update skill estimations\n            int actual_t = day - start_day[task_id] + 1;\n            double w = 0;\n            for (int k = 0; k < K; ++k) {\n                w += max(0, task_difficulty[task_id][k] - (int)s[member_id][k]);\n            }\n            double error = actual_t - (w == 0 ? 1.0 : w);\n            double learning_rate = 0.1;\n            for (int k = 0; k < K; ++k) {\n                if (task_difficulty[task_id][k] > s[member_id][k]) {\n                    // Update skill s[member_id][k]\n                    s[member_id][k] -= learning_rate * error;\n                    s[member_id][k] = max(0.0, min(100.0, s[member_id][k]));\n                }\n            }\n\n            task_status[task_id] = 1;\n            member_status[member_id] = -1;\n\n            // Update in_degree and ready_tasks\n            for (int next_task : adj[task_id]) {\n                in_degree[next_task]--;\n                if (in_degree[next_task] == 0) {\n                    ready_tasks.push_back(next_task);\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Order structure\nstruct Order {\n    int id;\n    int ax, ay, cx, cy;\n    double dist_from_office;\n};\n\n// Node structure for the route\nstruct Node {\n    int order_id;\n    bool is_pickup;\n    int x, y;\n};\n\n// Manhattan distance\nint dist(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Calculate total route distance\nint calculate_total_dist(const vector<Node>& route) {\n    int d = 0;\n    int cx = 400, cy = 400;\n    for (const auto& node : route) {\n        d += dist(cx, cy, node.x, node.y);\n        cx = node.x;\n        cy = node.y;\n    }\n    d += dist(cx, cy, 400, 400);\n    return d;\n}\n\n// Check if route satisfies precedence constraints\nbool is_valid(const vector<Node>& route, const vector<int>& selected_orders) {\n    vector<int> p_pos(1001, -1);\n    vector<int> d_pos(1001, -1);\n    for (int i = 0; i < route.size(); ++i) {\n        if (route[i].is_pickup) p_pos[route[i].order_id] = i;\n        else d_pos[route[i].order_id] = i;\n    }\n    for (int id : selected_orders) {\n        if (p_pos[id] > d_pos[id]) return false;\n    }\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // Read all orders\n    vector<Order> all_orders(1000);\n    for (int i = 0; i < 1000; ++i) {\n        all_orders[i].id = i + 1;\n        cin >> all_orders[i].ax >> all_orders[i].ay >> all_orders[i].cx >> all_orders[i].cy;\n        all_orders[i].dist_from_office = dist(400, 400, all_orders[i].ax, all_orders[i].ay) +\n                                         dist(all_orders[i].ax, all_orders[i].ay, all_orders[i].cx, all_orders[i].cy) +\n                                         dist(all_orders[i].cx, all_orders[i].cy, 400, 400);\n    }\n\n    // Sort orders by distance and pick top 50\n    vector<Order> sorted_orders = all_orders;\n    sort(sorted_orders.begin(), sorted_orders.end(), [](const Order& a, const Order& b) {\n        return a.dist_from_office < b.dist_from_office;\n    });\n\n    vector<int> selected_orders;\n    for (int i = 0; i < 50; ++i) {\n        selected_orders.push_back(sorted_orders[i].id);\n    }\n\n    // Greedy Initial Route Construction\n    vector<Node> route;\n    vector<bool> p_visited(1001, false);\n    vector<bool> d_visited(1001, false);\n    int cx = 400, cy = 400;\n    \n    while (route.size() < 100) {\n        int best_idx = -1;\n        bool best_is_pickup = false;\n        int min_d = 2000000000;\n        \n        for (int id : selected_orders) {\n            if (!p_visited[id]) {\n                int d = dist(cx, cy, all_orders[id - 1].ax, all_orders[id - 1].ay);\n                if (d < min_d) {\n                    min_d = d;\n                    best_idx = id;\n                    best_is_pickup = true;\n                }\n            }\n            if (p_visited[id] && !d_visited[id]) {\n                int d = dist(cx, cy, all_orders[id - 1].cx, all_orders[id - 1].cy);\n                if (d < min_d) {\n                    min_d = d;\n                    best_idx = id;\n                    best_is_pickup = false;\n                }\n            }\n        }\n        \n        if (best_is_pickup) {\n            route.push_back({best_idx, true, all_orders[best_idx - 1].ax, all_orders[best_idx - 1].ay});\n            p_visited[best_idx] = true;\n            cx = all_orders[best_idx - 1].ax;\n            cy = all_orders[best_idx - 1].ay;\n        } else {\n            route.push_back({best_idx, false, all_orders[best_idx - 1].cx, all_orders[best_idx - 1].cy});\n            d_visited[best_idx] = true;\n            cx = all_orders[best_idx - 1].cx;\n            cy = all_orders[best_idx - 1].cy;\n        }\n    }\n\n    // Refine with local search (Hill Climbing / 2-opt)\n    auto start_time = chrono::steady_clock::now();\n    mt19937 rng(42);\n    int best_dist = calculate_total_dist(route);\n    int iter = 0;\n    \n    while (true) {\n        if ((iter++ & 1023) == 0) { // Check time every 1024 iterations\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1900) break;\n        }\n        \n        int i = rng() % 100;\n        int j = rng() % 100;\n        if (i > j) swap(i, j);\n        if (i == j) continue;\n        \n        // Try reversing the segment [i, j]\n        vector<Node> next_route = route;\n        reverse(next_route.begin() + i, next_route.begin() + j + 1);\n        \n        if (is_valid(next_route, selected_orders)) {\n            int d = calculate_total_dist(next_route);\n            if (d < best_dist) {\n                best_dist = d;\n                route = next_route;\n            }\n        }\n    }\n\n    // Output results\n    cout << 50;\n    for (int id : selected_orders) cout << \" \" << id;\n    cout << endl;\n    \n    cout << 102; // Start, 100 points, End\n    cout << \" 400 400\";\n    for (const auto& node : route) cout << \" \" << node.x << \" \" << node.y;\n    cout << \" 400 400\" << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\n// DSU structure for connectivity checking\nstruct DSU {\n    vector<int> parent;\n    DSU(int n) {\n        parent.resize(n);\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int i) {\n        if (parent[i] == i)\n            return i;\n        return parent[i] = find(parent[i]);\n    }\n    void unite(int i, int j) {\n        int root_i = find(i);\n        int root_j = find(j);\n        if (root_i != root_j) {\n            parent[root_i] = root_j;\n        }\n    }\n    bool same(int i, int j) {\n        return find(i) == find(j);\n    }\n};\n\nstruct Edge {\n    int u, v, d, id;\n};\n\nint main() {\n    // Faster I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N = 400;\n    int M = 1995;\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<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        int dx = coords[edges[i].u].first - coords[edges[i].v].first;\n        int dy = coords[edges[i].u].second - coords[edges[i].v].second;\n        // Euclidean distance rounded to nearest integer\n        edges[i].d = (int)round(sqrt((double)dx * dx + (double)dy * dy));\n        edges[i].id = i;\n    }\n\n    vector<bool> adopted(M, false);\n    \n    // Process each edge as it arrives\n    for (int i = 0; i < M; ++i) {\n        int l_i;\n        cin >> l_i;\n\n        // Adaptive parameter k:\n        // Starts at 1.5, decreases linearly to 1.0.\n        // This makes the algorithm increasingly aggressive as we approach the end.\n        double k = 1.5 - 0.5 * ((double)i / M);\n\n        // 1. Initialize DSU with all already adopted edges\n        DSU dsu(N);\n        for (int j = 0; j < i; ++j) {\n            if (adopted[j]) {\n                dsu.unite(edges[j].u, edges[j].v);\n            }\n        }\n\n        // 2. Prepare candidates: the current edge (cost l_i) and all future edges (estimated cost k*d)\n        struct Candidate {\n            double cost;\n            int id;\n            int u, v;\n        };\n        vector<Candidate> candidates;\n        candidates.reserve(M - i);\n        \n        candidates.push_back({(double)l_i, i, edges[i].u, edges[i].v});\n        \n        for (int j = i + 1; j < M; ++j) {\n            candidates.push_back({k * edges[j].d, j, edges[j].u, edges[j].v});\n        }\n        \n        // Sort candidates by cost to run Kruskal's algorithm\n        sort(candidates.begin(), candidates.end(), [](const Candidate& a, const Candidate& b) {\n            return a.cost < b.cost;\n        });\n        \n        // 3. Run Kruskal's to see if the current edge i is part of the MST\n        bool take_edge = false;\n        for (const auto& cand : candidates) {\n            if (!dsu.same(cand.u, cand.v)) {\n                dsu.unite(cand.u, cand.v);\n                if (cand.id == i) {\n                    take_edge = true;\n                    break;\n                }\n            }\n        }\n        \n        // Output decision and flush\n        if (take_edge) {\n            cout << 1 << endl;\n            adopted[i] = true;\n        } else {\n            cout << 0 << endl;\n            adopted[i] = false;\n        }\n    }\n    \n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int r, c;\n    bool operator==(const Point& other) const { return r == other.r && c == other.c; }\n};\n\nint N, M;\nvector<Point> pets;\nvector<int> pet_types;\nvector<Point> humans;\nbool impassable[30][30];\n\n// Check if a coordinate is within bounds\nbool is_valid(int r, int c) {\n    return r >= 0 && r < 30 && c >= 0 && c < 30;\n}\n\n// Check if a square can be made impassable\nbool can_build(int r, int c) {\n    if (!is_valid(r, c) || impassable[r][c]) return false;\n    // Cannot build if a pet or human is currently at (r, c)\n    for (const auto& p : pets) if (p.r == r && p.c == c) return false;\n    for (const auto& h : humans) if (h.r == r && h.c == c) return false;\n    \n    // Cannot build if an adjacent square contains a pet\n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    for (int i = 0; i < 4; ++i) {\n        int nr = r + dr[i];\n        int nc = c + dc[i];\n        if (is_valid(nr, nc)) {\n            for (const auto& p : pets) {\n                if (p.r == nr && p.c == nc) return false;\n            }\n        }\n    }\n    return true;\n}\n\n// Find the index of the nearest pet\nint get_nearest_pet(Point h) {\n    int min_dist = 1000;\n    int target = -1;\n    for (int i = 0; i < N; ++i) {\n        int d = abs(h.r - pets[i].r) + abs(h.c - pets[i].c);\n        if (d < min_dist) {\n            min_dist = d;\n            target = i;\n        }\n    }\n    return target;\n}\n\n// BFS to find the next move towards the target\nPoint get_next_move(Point start, Point target) {\n    if (start.r == target.r && start.c == target.c) return start;\n    \n    queue<pair<Point, Point>> q; // {current, first_step}\n    bool visited[30][30] = {false};\n    \n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    \n    // Check initial neighbors\n    for (int i = 0; i < 4; ++i) {\n        int nr = start.r + dr[i];\n        int nc = start.c + dc[i];\n        if (is_valid(nr, nc) && !impassable[nr][nc]) {\n            bool occupied = false;\n            for(auto& h : humans) if(h.r == nr && h.c == nc) occupied = true;\n            if(!occupied) {\n                q.push({{nr, nc}, {nr, nc}});\n                visited[nr][nc] = true;\n            }\n        }\n    }\n    \n    while (!q.empty()) {\n        auto [curr, first] = q.front();\n        q.pop();\n        \n        if (curr.r == target.r && curr.c == target.c) return first;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n            if (is_valid(nr, nc) && !impassable[nr][nc] && !visited[nr][nc]) {\n                bool occupied = false;\n                for(auto& h : humans) if(h.r == nr && h.c == nc) occupied = true;\n                if(!occupied) {\n                    visited[nr][nc] = true;\n                    q.push({{nr, nc}, first});\n                }\n            }\n        }\n    }\n    return start; // No path found\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N;\n    pets.resize(N);\n    pet_types.resize(N);\n    for (int i = 0; i < N; ++i) cin >> pets[i].r >> pets[i].c >> pet_types[i];\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) cin >> humans[i].r >> humans[i].c;\n    \n    for (int i = 0; i < 30; ++i) for (int j = 0; j < 30; ++j) impassable[i][j] = false;\n    \n    for (int turn = 0; turn < 300; ++turn) {\n        vector<string> actions(M, \".\");\n        \n        for (int i = 0; i < M; ++i) {\n            int target_idx = get_nearest_pet(humans[i]);\n            if (target_idx == -1) continue;\n            \n            Point pet = pets[target_idx];\n            bool built = false;\n            int dr[] = {0, 0, 1, -1};\n            int dc[] = {1, -1, 0, 0};\n            char wall_chars[] = {'r', 'l', 'd', 'u'};\n            \n            // Try to build a wall near the target pet to trap it\n            for (int k = 0; k < 4; ++k) {\n                int nr = humans[i].r + dr[k];\n                int nc = humans[i].c + dc[k];\n                \n                if (abs(nr - pet.r) + abs(nc - pet.c) <= 2) {\n                    if (can_build(nr, nc)) {\n                        string s(1, wall_chars[k]);\n                        actions[i] = s;\n                        impassable[nr][nc] = true;\n                        built = true;\n                        break;\n                    }\n                }\n            }\n            \n            // If not building, move towards the pet\n            if (!built) {\n                Point next = get_next_move(humans[i], pet);\n                if (!(next == humans[i])) {\n                    if (next.r < humans[i].r) actions[i] = \"U\";\n                    else if (next.r > humans[i].r) actions[i] = \"D\";\n                    else if (next.c < humans[i].c) actions[i] = \"L\";\n                    else if (next.c > humans[i].c) actions[i] = \"R\";\n                    humans[i] = next;\n                }\n            }\n        }\n        \n        // Output actions for this turn\n        for (int i = 0; i < M; ++i) cout << actions[i];\n        cout << endl;\n        \n        // Update pets' positions based on their movements\n        for (int i = 0; i < N; ++i) {\n            string move;\n            cin >> move;\n            for (char c : move) {\n                if (c == 'U') pets[i].r--;\n                else if (c == 'D') pets[i].r++;\n                else if (c == 'L') pets[i].c--;\n                else if (c == 'R') pets[i].c++;\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <string>\n#include <array>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\nusing namespace std;\n\n// State structure for Beam Search\nstruct State {\n    string path;\n    array<array<double, 20>, 20> dist;\n    double reward;\n    double prob_reached;\n    double heuristic; // Lower is better\n};\n\nint Si, Sj, Ti, Tj;\ndouble P;\nvector<string> H, V;\narray<array<int, 20>, 20> min_dist_to_office;\n\n// Function to compute shortest path distances to the office using BFS\nvoid compute_min_dist() {\n    for (int i = 0; i < 20; ++i) {\n        for (int j = 0; j < 20; ++j) {\n            min_dist_to_office[i][j] = 1000;\n        }\n    }\n    queue<pair<int, int>> q;\n    q.push({Ti, Tj});\n    min_dist_to_office[Ti][Tj] = 0;\n\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n\n        // Check U, D, L, R\n        // U: (r-1, c) -> (r, c) - Wall is V[r-1][c]\n        if (r > 0 && V[r - 1][c] == '0' && min_dist_to_office[r - 1][c] == 1000) {\n            min_dist_to_office[r - 1][c] = min_dist_to_office[r][c] + 1;\n            q.push({r - 1, c});\n        }\n        // D: (r+1, c) -> (r, c) - Wall is V[r][c]\n        if (r < 19 && V[r][c] == '0' && min_dist_to_office[r + 1][c] == 1000) {\n            min_dist_to_office[r + 1][c] = min_dist_to_office[r][c] + 1;\n            q.push({r + 1, c});\n        }\n        // L: (r, c-1) -> (r, c) - Wall is H[r][c-1]\n        if (c > 0 && H[r][c - 1] == '0' && min_dist_to_office[r][c - 1] == 1000) {\n            min_dist_to_office[r][c - 1] = min_dist_to_office[r][c] + 1;\n            q.push({r, c - 1});\n        }\n        // R: (r, c+1) -> (r, c) - Wall is H[r][c]\n        if (c < 19 && H[r][c] == '0' && min_dist_to_office[r][c + 1] == 1000) {\n            min_dist_to_office[r][c + 1] = min_dist_to_office[r][c] + 1;\n            q.push({r, c + 1});\n        }\n    }\n}\n\n// Check if a move is possible in the given direction\nbool can_move(int r, int c, char dir) {\n    if (dir == 'U') return r > 0 && V[r - 1][c] == '0';\n    if (dir == 'D') return r < 19 && V[r][c] == '0';\n    if (dir == 'L') return c > 0 && H[r][c - 1] == '0';\n    if (dir == 'R') return c < 19 && H[r][c] == '0';\n    return false;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> Si >> Sj >> Ti >> Tj >> P)) return 0;\n    H.resize(20);\n    for (int i = 0; i < 20; ++i) cin >> H[i];\n    V.resize(19);\n    for (int i = 0; i < 19; ++i) cin >> V[i];\n\n    compute_min_dist();\n\n    // Beam search initialization\n    vector<State> beam;\n    State initial;\n    initial.path = \"\";\n    for (int i = 0; i < 20; ++i)\n        for (int j = 0; j < 20; ++j)\n            initial.dist[i][j] = 0.0;\n    initial.dist[Si][Sj] = 1.0;\n    initial.reward = 0.0;\n    initial.prob_reached = 0.0;\n    initial.heuristic = (double)min_dist_to_office[Si][Sj];\n    beam.push_back(initial);\n\n    int K = 400; // Beam width\n    for (int t = 1; t <= 200; ++t) {\n        vector<State> next_beam;\n        next_beam.reserve(beam.size() * 4);\n        for (const auto& s : beam) {\n            for (char dir : {'U', 'D', 'L', 'R'}) {\n                State next_s;\n                next_s.path = s.path + dir;\n                next_s.prob_reached = s.prob_reached;\n                next_s.reward = s.reward;\n                \n                double prob_reach_at_t = 0.0;\n                for (int i = 0; i < 20; ++i)\n                    for (int j = 0; j < 20; ++j)\n                        next_s.dist[i][j] = 0.0;\n\n                // Propagate probability distribution\n                for (int r = 0; r < 20; ++r) {\n                    for (int c = 0; c < 20; ++c) {\n                        if (s.dist[r][c] == 0) continue;\n                        \n                        // Forgetting: agent stays\n                        next_s.dist[r][c] += s.dist[r][c] * P;\n                        \n                        // Moving: attempts to move\n                        if (can_move(r, c, dir)) {\n                            int nr = r, nc = c;\n                            if (dir == 'U') nr--;\n                            else if (dir == 'D') nr++;\n                            else if (dir == 'L') nc--;\n                            else if (dir == 'R') nc++;\n                            \n                            // Check if reached office\n                            if (nr == Ti && nc == Tj) {\n                                prob_reach_at_t += s.dist[r][c] * (1.0 - P);\n                            } else {\n                                next_s.dist[nr][nc] += s.dist[r][c] * (1.0 - P);\n                            }\n                        } else {\n                            // Wall, stay\n                            next_s.dist[r][c] += s.dist[r][c] * (1.0 - P);\n                        }\n                    }\n                }\n                \n                next_s.prob_reached += prob_reach_at_t;\n                next_s.reward += prob_reach_at_t * (401.0 - t);\n                \n                // Heuristic: sum of dist[r][c] * min_dist_to_office[r][c]\n                double h = 0.0;\n                for (int r = 0; r < 20; ++r) {\n                    for (int c = 0; c < 20; ++c) {\n                        h += next_s.dist[r][c] * min_dist_to_office[r][c];\n                    }\n                }\n                next_s.heuristic = h;\n                \n                next_beam.push_back(next_s);\n            }\n        }\n        \n        // Keep top K sequences\n        sort(next_beam.begin(), next_beam.end(), [](const State& a, const State& b) {\n            if (abs(a.reward - b.reward) > 1e-9) return a.reward > b.reward;\n            if (abs(a.prob_reached - b.prob_reached) > 1e-9) return a.prob_reached > b.prob_reached;\n            return a.heuristic < b.heuristic;\n        });\n        \n        if (next_beam.size() > (size_t)K) {\n            next_beam.resize(K);\n        }\n        beam = next_beam;\n    }\n    \n    cout << beam[0].path << endl;\n    \n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <cstring>\n\nusing namespace std;\n\n// Tile connections for each tile type 0-7 at orientation 0\n// Directions: 0: Left, 1: Up, 2: Right, 3: Down\nint base_to[8][4] = {\n    {1, 0, -1, -1}, // Tile 0: Left <-> Up\n    {3, -1, -1, 0}, // Tile 1: Left <-> Down\n    {-1, -1, 3, 2}, // Tile 2: Right <-> Down\n    {-1, 2, 1, -1}, // Tile 3: Right <-> Up\n    {1, 0, 3, 2},   // Tile 4: Left <-> Up, Right <-> Down\n    {3, 2, 1, 0},   // Tile 5: Left <-> Down, Up <-> Right\n    {2, -1, 0, -1}, // Tile 6: Left <-> Right\n    {-1, 3, -1, 1}, // Tile 7: Up <-> Down\n};\n\n// Map direction based on tile rotation r (0, 1, 2, 3 rotations 90 deg CCW)\ninline int get_to(int type, int r, int d_new) {\n    int d_old = (d_new + r) % 4;\n    int d_old_exit = base_to[type][d_old];\n    if (d_old_exit == -1) return -1;\n    // Map back to the new coordinate system\n    return (d_old_exit - r + 4) % 4;\n}\n\nint N = 30;\nint tiles[30][30];\nint r[30][30];\nint di[4] = {0, -1, 0, 1}; // Left, Up, Right, Down\nint dj[4] = {-1, 0, 1, 0};\n\n// Visited array for cycle finding\nint visited[30][30][4];\n\nlong long calculate_score() {\n    memset(visited, 0, sizeof(visited));\n    vector<int> cycle_lengths;\n    \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                if (visited[i][j][d]) continue;\n                \n                int curr_i = i;\n                int curr_j = j;\n                int curr_d = d;\n                int length = 0;\n                bool closed = false;\n                \n                int path_i = curr_i;\n                int path_j = curr_j;\n                int path_d = curr_d;\n                \n                // Traverse the path\n                while (true) {\n                    int next_d = get_to(tiles[path_i][path_j], r[path_i][path_j], path_d);\n                    if (next_d == -1) break;\n                    \n                    visited[path_i][path_j][path_d] = 1;\n                    \n                    path_i += di[next_d];\n                    path_j += dj[next_d];\n                    \n                    if (path_i < 0 || path_i >= N || path_j < 0 || path_j >= N) break;\n                    \n                    path_d = (next_d + 2) % 4;\n                    length++;\n                    \n                    if (path_i == i && path_j == j && path_d == d) {\n                        closed = true;\n                        break;\n                    }\n                    if (visited[path_i][path_j][path_d]) break;\n                }\n                \n                if (closed) {\n                    cycle_lengths.push_back(length);\n                }\n            }\n        }\n    }\n    \n    if (cycle_lengths.size() < 2) return 0;\n    sort(cycle_lengths.rbegin(), cycle_lengths.rend());\n    return (long long)cycle_lengths[0] * cycle_lengths[1];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    for (int i = 0; i < N; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; ++j) {\n            tiles[i][j] = s[j] - '0';\n            r[i][j] = 0; \n        }\n    }\n    \n    long long current_score = calculate_score();\n    int best_r[30][30];\n    memcpy(best_r, r, sizeof(r));\n    long long best_score = current_score;\n    \n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    double time_limit = 1.95; \n    \n    int iterations = 0;\n    \n    // Simulated Annealing\n    while (true) {\n        if ((iterations & 1023) == 0) {\n            if (chrono::duration<double>(chrono::steady_clock::now() - start_time).count() > time_limit) break;\n        }\n        iterations++;\n        \n        int i = rng() % N;\n        int j = rng() % N;\n        int old_r = r[i][j];\n        r[i][j] = rng() % 4;\n        \n        long long new_score = calculate_score();\n        \n        // Simple cooling schedule\n        double T = 1000.0 * (1.0 - (double)iterations / 2000000.0);\n        double prob = (new_score > current_score) ? 1.0 : exp((double)(new_score - current_score) / (T + 1e-9));\n        \n        if (prob > (double)rng() / rng.max()) {\n            current_score = new_score;\n            if (current_score > best_score) {\n                best_score = current_score;\n                memcpy(best_r, r, sizeof(r));\n            }\n        } else {\n            r[i][j] = old_r;\n        }\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << best_r[i][j];\n        }\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Structure to represent the board\nstruct Board {\n    int N;\n    vector<int> tiles;\n    int empty_r, empty_c;\n\n    Board(int n, const vector<int>& t) : N(n), tiles(t) {\n        for (int i = 0; i < N * N; ++i) {\n            if (tiles[i] == 0) {\n                empty_r = i / N;\n                empty_c = i % N;\n            }\n        }\n    }\n\n    // Apply a sliding move\n    bool apply(char move) {\n        int r = empty_r, c = empty_c;\n        if (move == 'U') r++;\n        else if (move == 'D') r--;\n        else if (move == 'L') c++;\n        else if (move == 'R') c--;\n        else return false;\n\n        if (r < 0 || r >= N || c < 0 || c >= N) return false;\n\n        swap(tiles[empty_r * N + empty_c], tiles[r * N + c]);\n        empty_r = r;\n        empty_c = c;\n        return true;\n    }\n};\n\n// DSU to manage components and check for trees\nstruct DSU {\n    vector<int> parent;\n    vector<int> nodes;\n    vector<int> edges;\n\n    DSU(int n) {\n        parent.resize(n);\n        nodes.resize(n, 1);\n        edges.resize(n, 0);\n        for (int i = 0; i < n; ++i) parent[i] = i;\n    }\n\n    int find(int i) {\n        if (parent[i] == i) return i;\n        return parent[i] = find(parent[i]);\n    }\n\n    void unite(int i, int j) {\n        int root_i = find(i);\n        int root_j = find(j);\n        if (root_i != root_j) {\n            parent[root_j] = root_i;\n            nodes[root_i] += nodes[root_j];\n            edges[root_i] += edges[root_j] + 1;\n        } else {\n            edges[root_i]++;\n        }\n    }\n};\n\n// Calculate the size of the largest tree component\nint calculate_score(const Board& b) {\n    int N = b.N;\n    DSU dsu(N * N);\n    \n    // Set nodes to 0 for empty square (not part of the tree)\n    for (int i = 0; i < N * N; ++i) {\n        if (b.tiles[i] == 0) dsu.nodes[i] = 0;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int u = i * N + j;\n            if (b.tiles[u] == 0) continue;\n\n            // Check rightward connection\n            if (j + 1 < N && b.tiles[i * N + j + 1] != 0) {\n                if ((b.tiles[u] & 4) && (b.tiles[i * N + j + 1] & 1)) {\n                    dsu.unite(u, i * N + j + 1);\n                }\n            }\n            // Check downward connection\n            if (i + 1 < N && b.tiles[(i + 1) * N + j] != 0) {\n                if ((b.tiles[u] & 8) && (b.tiles[(i + 1) * N + j] & 2)) {\n                    dsu.unite(u, (i + 1) * N + j);\n                }\n            }\n        }\n    }\n\n    int max_s = 0;\n    for (int i = 0; i < N * N; ++i) {\n        if (dsu.parent[i] == i) {\n            // A component is a tree if it has V vertices and V-1 edges\n            if (dsu.edges[i] == dsu.nodes[i] - 1) {\n                max_s = max(max_s, dsu.nodes[i]);\n            }\n        }\n    }\n    return max_s;\n}\n\nint hex_to_int(char c) {\n    if (c >= '0' && c <= '9') return c - '0';\n    return c - 'a' + 10;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, T;\n    cin >> N >> T;\n    vector<int> tiles(N * N);\n    for (int i = 0; i < N; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; ++j) {\n            tiles[i * N + j] = hex_to_int(s[j]);\n        }\n    }\n\n    Board initial_board(N, tiles);\n    string best_moves = \"\";\n    int best_S = 0;\n\n    auto start_time = chrono::steady_clock::now();\n    mt19937 rng(42);\n    \n    // Hill Climbing with Random Restarts\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 2500) {\n        Board current_board = initial_board;\n        string current_moves = \"\";\n        int current_S = calculate_score(current_board);\n        \n        for (int i = 0; i < T; ++i) {\n            vector<char> moves = {'U', 'D', 'L', 'R'};\n            shuffle(moves.begin(), moves.end(), rng);\n            \n            bool found_improvement = false;\n            char best_move = ' ';\n            int best_next_S = -1;\n\n            for (char move : moves) {\n                // Prevent reversing the last move\n                if (!current_moves.empty()) {\n                    char last = current_moves.back();\n                    if ((move == 'U' && last == 'D') || (move == 'D' && last == 'U') ||\n                        (move == 'L' && last == 'R') || (move == 'R' && last == 'L')) continue;\n                }\n                \n                Board next_board = current_board;\n                if (!next_board.apply(move)) continue;\n                \n                int next_S = calculate_score(next_board);\n                if (next_S > current_S) {\n                    current_S = next_S;\n                    current_board = next_board;\n                    current_moves += move;\n                    found_improvement = true;\n                    break; // Greedy: take first improvement\n                }\n                if (next_S > best_next_S) {\n                    best_next_S = next_S;\n                    best_move = move;\n                }\n            }\n            \n            if (current_S == N * N - 1) break;\n            \n            if (!found_improvement) {\n                // If no improvement, pick the best move or a random move\n                if (best_next_S != -1) {\n                    current_board.apply(best_move);\n                    current_moves += best_move;\n                    current_S = best_next_S;\n                } else {\n                    char move = moves[rng() % 4];\n                    Board next_board = current_board;\n                    if (next_board.apply(move)) {\n                        current_board = next_board;\n                        current_moves += move;\n                        current_S = calculate_score(current_board);\n                    }\n                }\n            }\n        }\n        \n        if (current_S > best_S) {\n            best_S = current_S;\n            best_moves = current_moves;\n        }\n        \n        if (best_S == N * N - 1) break;\n    }\n    \n    cout << best_moves << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent a point\nstruct Point {\n    long long x, y;\n};\n\n// Structure to represent a line: ax + by + c = 0\nstruct Line {\n    long long a, b, c;\n    Point p1, p2;\n};\n\n// Global data\nint N, K;\nvector<int> a(11);\nvector<Point> strawberries;\nmt19937 rng(1337);\n\n// Function to calculate the score: sum(min(a_d, b_d))\nint calculate_score(const vector<vector<int>>& groups) {\n    vector<int> b(11, 0);\n    for (const auto& g : groups) {\n        if (g.size() >= 1 && g.size() <= 10) {\n            b[g.size()]++;\n        }\n    }\n    int score = 0;\n    for (int d = 1; d <= 10; ++d) {\n        score += min(a[d], b[d]);\n    }\n    return score;\n}\n\n// Generate a random line that intersects the cake\nLine generate_random_line() {\n    uniform_int_distribution<long long> dist(-10000, 10000);\n    while (true) {\n        Point p1 = {dist(rng), dist(rng)};\n        Point p2 = {dist(rng), dist(rng)};\n        if (p1.x == p2.x && p1.y == p2.y) continue;\n\n        // Line equation: (y1 - y2)x + (x2 - x1)y + (x1y2 - x2y1) = 0\n        long long a = p1.y - p2.y;\n        long long b = p2.x - p1.x;\n        long long c = -a * p1.x - b * p1.y;\n\n        // Check if the line cuts the cake (distance from origin < 10000)\n        // Distance = |c| / sqrt(a^2 + b^2)\n        // |c| < 10000 * sqrt(a^2 + b^2)\n        // c^2 < 10^8 * (a^2 + b^2)\n        __int128 c2 = (__int128)c * c;\n        __int128 dist2 = (__int128)a * a + (__int128)b * b;\n        if (c2 < (__int128)100000000 * dist2) {\n            return {a, b, c, p1, p2};\n        }\n    }\n}\n\n// Update strawberry groups based on a new line\nvector<vector<int>> update_groups(const vector<vector<int>>& current_groups, const Line& line) {\n    vector<vector<int>> next_groups;\n    for (const auto& g : current_groups) {\n        vector<int> left, right;\n        for (int idx : g) {\n            long long val = line.a * strawberries[idx].x + line.b * strawberries[idx].y + line.c;\n            if (val < 0) left.push_back(idx);\n            else if (val > 0) right.push_back(idx);\n            // If val == 0, the strawberry is on the line and is effectively removed\n        }\n        if (!left.empty()) next_groups.push_back(left);\n        if (!right.empty()) next_groups.push_back(right);\n    }\n    return next_groups;\n}\n\nint main() {\n    // Optimize I/O\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N >> K)) return 0;\n    for (int i = 1; i <= 10; ++i) cin >> a[i];\n    strawberries.resize(N);\n    for (int i = 0; i < N; ++i) cin >> strawberries[i].x >> strawberries[i].y;\n\n    vector<vector<int>> groups;\n    vector<int> initial_group(N);\n    for (int i = 0; i < N; ++i) initial_group[i] = i;\n    groups.push_back(initial_group);\n\n    vector<Line> lines;\n\n    // Greedy construction of lines\n    for (int k = 0; k < K; ++k) {\n        int best_score = -1;\n        Line best_line;\n        bool found = false;\n\n        // Try 500 random lines and pick the best one\n        for (int trial = 0; trial < 500; ++trial) {\n            Line line = generate_random_line();\n            auto next_groups = update_groups(groups, line);\n            int score = calculate_score(next_groups);\n            if (score > best_score) {\n                best_score = score;\n                best_line = line;\n                found = true;\n            }\n        }\n        \n        if (found) {\n            lines.push_back(best_line);\n            groups = update_groups(groups, best_line);\n        } else {\n            // If no line improves the score, stop adding lines\n            break;\n        }\n    }\n\n    // Output the result\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line.p1.x << \" \" << line.p1.y << \" \" << line.p2.x << \" \" << line.p2.y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nint N, M;\nvector<vector<bool>> has_dot;\nvector<vector<vector<bool>>> used_seg; // 0: horiz, 1: vert, 2: diag1, 3: diag2\n\nint weight(int x, int y) {\n    int cx = (N - 1) / 2;\n    int cy = (N - 1) / 2;\n    return (x - cx) * (x - cx) + (y - cy) * (y - cy) + 1;\n}\n\nbool is_valid(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool is_segment_used(int x1, int y1, int x2, int y2) {\n    int dx = x2 - x1;\n    int dy = y2 - y1;\n    if (dy == 0) { // horiz\n        int x = min(x1, x2);\n        return used_seg[0][x][y1];\n    } else if (dx == 0) { // vert\n        int y = min(y1, y2);\n        return used_seg[1][x1][y];\n    } else if (dx == dy) { // diag1 (slope 1)\n        int x = min(x1, x2);\n        int y = min(y1, y2);\n        return used_seg[2][x][y];\n    } else { // diag2 (slope -1)\n        int x = min(x1, x2);\n        int y = max(y1, y2);\n        return used_seg[3][x][y - 1];\n    }\n}\n\nvoid mark_segment(int x1, int y1, int x2, int y2) {\n    int dx = x2 - x1;\n    int dy = y2 - y1;\n    if (dy == 0) {\n        int x = min(x1, x2);\n        used_seg[0][x][y1] = true;\n    } else if (dx == 0) {\n        int y = min(y1, y2);\n        used_seg[1][x1][y] = true;\n    } else if (dx == dy) {\n        int x = min(x1, x2);\n        int y = min(y1, y2);\n        used_seg[2][x][y] = true;\n    } else {\n        int x = min(x1, x2);\n        int y = max(y1, y2);\n        used_seg[3][x][y - 1] = true;\n    }\n}\n\n// Checks if any unit segment on the line between p1 and p2 is used\nbool is_path_used(int x1, int y1, int x2, int y2) {\n    int dx = (x2 > x1) ? 1 : ((x2 < x1) ? -1 : 0);\n    int dy = (y2 > y1) ? 1 : ((y2 < y1) ? -1 : 0);\n    int dist = max(abs(x2 - x1), abs(y2 - y1));\n    for (int i = 0; i < dist; ++i) {\n        if (is_segment_used(x1 + i * dx, y1 + i * dy, x1 + (i + 1) * dx, y1 + (i + 1) * dy)) return true;\n    }\n    return false;\n}\n\n// Checks if any dot exists on the path between p1 and p2 (excluding endpoints)\nbool is_path_clear(int x1, int y1, int x2, int y2, const Point& p_ex1, const Point& p_ex2, const Point& p_ex3) {\n    int dx = (x2 > x1) ? 1 : ((x2 < x1) ? -1 : 0);\n    int dy = (y2 > y1) ? 1 : ((y2 < y1) ? -1 : 0);\n    int dist = max(abs(x2 - x1), abs(y2 - y1));\n    for (int i = 1; i < dist; ++i) {\n        int cx = x1 + i * dx, cy = y1 + i * dy;\n        if ((cx == p_ex1.x && cy == p_ex1.y) || (cx == p_ex2.x && cy == p_ex2.y) || (cx == p_ex3.x && cy == p_ex3.y)) continue;\n        if (has_dot[cx][cy]) return false;\n    }\n    return true;\n}\n\nbool check_rect(Point p1, Point p2, Point p3, Point p4) {\n    if (!is_valid(p1.x, p1.y) || !is_valid(p2.x, p2.y) || !is_valid(p3.x, p3.y) || !is_valid(p4.x, p4.y)) return false;\n    if (has_dot[p1.x][p1.y] || !has_dot[p2.x][p2.y] || !has_dot[p3.x][p3.y] || !has_dot[p4.x][p4.y]) return false;\n    \n    // Check perimeter segments\n    if (is_path_used(p1.x, p1.y, p2.x, p2.y) || is_path_used(p2.x, p2.y, p3.x, p3.y) ||\n        is_path_used(p3.x, p3.y, p4.x, p4.y) || is_path_used(p4.x, p4.y, p1.x, p1.y)) return false;\n    \n    // Check dots on perimeter\n    if (!is_path_clear(p1.x, p1.y, p2.x, p2.y, p2, p3, p4) || !is_path_clear(p2.x, p2.y, p3.x, p3.y, p2, p3, p4) ||\n        !is_path_clear(p3.x, p3.y, p4.x, p4.y, p2, p3, p4) || !is_path_clear(p4.x, p4.y, p1.x, p1.y, p2, p3, p4)) return false;\n    \n    return true;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    cin >> N >> M;\n    has_dot.assign(N, vector<bool>(N, false));\n    used_seg.assign(4, vector<vector<bool>>(N + 1, vector<bool>(N + 1, false)));\n    for (int i = 0; i < M; ++i) {\n        int x, y; cin >> x >> y;\n        has_dot[x][y] = true;\n    }\n\n    struct Op { Point p1, p2, p3, p4; };\n    vector<Op> ops;\n\n    while (true) {\n        Op best_op;\n        int max_w = -1;\n        bool found = false;\n\n        for (int x1 = 0; x1 < N; ++x1) {\n            for (int y1 = 0; y1 < N; ++y1) {\n                if (has_dot[x1][y1]) continue;\n                \n                // Parallel\n                for (int x2 = 0; x2 < N; ++x2) {\n                    if (x2 == x1) continue;\n                    for (int y2 = 0; y2 < N; ++y2) {\n                        if (y2 == y1) continue;\n                        Point p2 = {x2, y1}, p4 = {x1, y2}, p3 = {x2, y2};\n                        if (check_rect({x1, y1}, p2, p3, p4)) {\n                            if (weight(x1, y1) > max_w) {\n                                max_w = weight(x1, y1);\n                                best_op = {{x1, y1}, p2, p3, p4};\n                                found = true;\n                            }\n                        }\n                    }\n                }\n                // 45-degree\n                for (int k = -(N - 1); k < N; ++k) {\n                    if (k == 0) continue;\n                    for (int m = -(N - 1); m < N; ++m) {\n                        if (m == 0 || k == m || k == -m) continue;\n                        Point p2 = {x1 + k, y1 + k}, p4 = {x1 - m, y1 + m}, p3 = {x1 + k - m, y1 + k + m};\n                        if (check_rect({x1, y1}, p2, p3, p4)) {\n                            if (weight(x1, y1) > max_w) {\n                                max_w = weight(x1, y1);\n                                best_op = {{x1, y1}, p2, p3, p4};\n                                found = true;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        if (!found) break;\n        \n        has_dot[best_op.p1.x][best_op.p1.y] = true;\n        auto add_seg = [&](Point a, Point b) {\n            int dx = (b.x > a.x) ? 1 : ((b.x < a.x) ? -1 : 0);\n            int dy = (b.y > a.y) ? 1 : ((b.y < a.y) ? -1 : 0);\n            int dist = max(abs(b.x - a.x), abs(b.y - a.y));\n            for (int i = 0; i < dist; ++i) mark_segment(a.x + i * dx, a.y + i * dy, a.x + (i + 1) * dx, a.y + (i + 1) * dy);\n        };\n        add_seg(best_op.p1, best_op.p2); add_seg(best_op.p2, best_op.p3);\n        add_seg(best_op.p3, best_op.p4); add_seg(best_op.p4, best_op.p1);\n        ops.push_back(best_op);\n    }\n\n    cout << ops.size() << endl;\n    for (auto& o : ops) cout << o.p1.x << \" \" << o.p1.y << \" \" << o.p2.x << \" \" << o.p2.y << \" \" << o.p3.x << \" \" << o.p3.y << \" \" << o.p4.x << \" \" << o.p4.y << endl;\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <queue>\n\nusing namespace std;\n\n// Global state for visited to avoid repeated allocation\nint visited[10][10] = {0};\nint cookie = 0;\n\nstruct State {\n    int board[10][10];\n    State() {\n        for (int i = 0; i < 10; ++i)\n            for (int j = 0; j < 10; ++j)\n                board[i][j] = 0;\n    }\n};\n\n// Optimized BFS for calculating sum of squares of connected component sizes\nint calculate_score(const State& s) {\n    cookie++;\n    int total_score = 0;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            if (s.board[r][c] != 0 && visited[r][c] != cookie) {\n                int flavor = s.board[r][c];\n                int size = 0;\n                static pair<int, int> q[100];\n                int head = 0, tail = 0;\n                q[tail++] = {r, c};\n                visited[r][c] = cookie;\n                while(head < tail){\n                    auto [curr_r, curr_c] = q[head++];\n                    size++;\n                    int dr[] = {-1, 1, 0, 0};\n                    int dc[] = {0, 0, -1, 1};\n                    for(int i=0; i<4; ++i){\n                        int nr = curr_r + dr[i];\n                        int nc = curr_c + dc[i];\n                        if(nr >= 0 && nr < 10 && nc >= 0 && nc < 10 && visited[nr][nc] != cookie && s.board[nr][nc] == flavor){\n                            visited[nr][nc] = cookie;\n                            q[tail++] = {nr, nc};\n                        }\n                    }\n                }\n                total_score += size * size;\n            }\n        }\n    }\n    return total_score;\n}\n\n// Applies the tilt operation to the board state\nState apply_tilt(State s, char dir) {\n    if (dir == 'F') { // Move towards top\n        for (int c = 0; c < 10; ++c) {\n            int write_r = 0;\n            for (int r = 0; r < 10; ++r) {\n                if (s.board[r][c] != 0) {\n                    int flavor = s.board[r][c];\n                    s.board[r][c] = 0;\n                    s.board[write_r][c] = flavor;\n                    write_r++;\n                }\n            }\n        }\n    } else if (dir == 'B') { // Move towards bottom\n        for (int c = 0; c < 10; ++c) {\n            int write_r = 9;\n            for (int r = 9; r >= 0; --r) {\n                if (s.board[r][c] != 0) {\n                    int flavor = s.board[r][c];\n                    s.board[r][c] = 0;\n                    s.board[write_r][c] = flavor;\n                    write_r--;\n                }\n            }\n        }\n    } else if (dir == 'L') { // Move towards left\n        for (int r = 0; r < 10; ++r) {\n            int write_c = 0;\n            for (int c = 0; c < 10; ++c) {\n                if (s.board[r][c] != 0) {\n                    int flavor = s.board[r][c];\n                    s.board[r][c] = 0;\n                    s.board[r][write_c] = flavor;\n                    write_c++;\n                }\n            }\n        }\n    } else if (dir == 'R') { // Move towards right\n        for (int r = 0; r < 10; ++r) {\n            int write_c = 9;\n            for (int c = 9; c >= 0; --c) {\n                if (s.board[r][c] != 0) {\n                    int flavor = s.board[r][c];\n                    s.board[r][c] = 0;\n                    s.board[r][write_c] = flavor;\n                    write_c--;\n                }\n            }\n        }\n    }\n    return s;\n}\n\n// Finds all empty cells in the board\nvector<int> get_empty_cells(const State& s) {\n    vector<int> empty_cells;\n    empty_cells.reserve(100);\n    for (int r = 0; r < 10; ++r)\n        for (int c = 0; c < 10; ++c)\n            if (s.board[r][c] == 0)\n                empty_cells.push_back(r * 10 + c);\n    return empty_cells;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    vector<int> f(100);\n    for (int i = 0; i < 100; ++i) cin >> f[i];\n\n    State current_state;\n    mt19937 rng(12345);\n\n    // Loop through each of the 100 turns\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        cin >> p;\n        vector<int> empty_cells = get_empty_cells(current_state);\n        int cell = empty_cells[p - 1];\n        current_state.board[cell / 10][cell % 10] = f[t];\n\n        if (t == 99) break; // No tilt needed for the last candy\n\n        char directions[] = {'F', 'B', 'L', 'R'};\n        double best_score = -1.0;\n        char best_dir = 'F';\n\n        // Choose best direction by looking ahead using rollouts\n        for (char dir : directions) {\n            State next_state = apply_tilt(current_state, dir);\n            \n            double total_sim_score = 0;\n            int num_rollouts = 30; // Number of simulations per direction\n            for (int r = 0; r < num_rollouts; ++r) {\n                State sim_state = next_state;\n                for (int sim_t = t + 1; sim_t < 100; ++sim_t) {\n                    vector<int> sim_empty = get_empty_cells(sim_state);\n                    uniform_int_distribution<int> dist(0, (int)sim_empty.size() - 1);\n                    int sim_p = sim_empty[dist(rng)];\n                    sim_state.board[sim_p / 10][sim_p % 10] = f[sim_t];\n                    \n                    uniform_int_distribution<int> dir_dist(0, 3);\n                    char sim_dir = directions[dir_dist(rng)];\n                    sim_state = apply_tilt(sim_state, sim_dir);\n                }\n                total_sim_score += calculate_score(sim_state);\n            }\n            if (total_sim_score > best_score) {\n                best_score = total_sim_score;\n                best_dir = dir;\n            }\n        }\n        cout << best_dir << endl;\n        current_state = apply_tilt(current_state, best_dir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Structure to hold graph information\nstruct Graph {\n    int id;\n    int clique_size;\n    vector<int> degree_seq;\n    string edges;\n};\n\nint main() {\n    // Optimization for speed\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n\n    // Determine N. N should be at least M, but also >= 4 and >= 20 for robustness.\n    // N <= 100.\n    int N = max({4, M, 20});\n    if (N > 100) N = 100;\n\n    cout << N << endl;\n\n    vector<Graph> graphs(M);\n    for (int k = 0; k < M; ++k) {\n        graphs[k].id = k;\n        \n        // We choose clique sizes spread between 1 and N.\n        // For M=1, clique size is 1.\n        // For M>1, spread them linearly from 1 to N.\n        if (M == 1) {\n            graphs[k].clique_size = 1;\n        } else {\n            graphs[k].clique_size = 1 + (int)((double)k * (N - 1) / (M - 1));\n        }\n\n        int c = graphs[k].clique_size;\n        \n        // Generate edge string and degree sequence\n        string s = \"\";\n        vector<int> deg(N, 0);\n        for (int i = 0; i < N - 1; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                // Clique of size c: edges only exist between vertices < c\n                if (i < c && j < c) {\n                    s += '1';\n                    deg[i]++;\n                    deg[j]++;\n                } else {\n                    s += '0';\n                }\n            }\n        }\n        graphs[k].edges = s;\n        sort(deg.begin(), deg.end());\n        graphs[k].degree_seq = deg;\n    }\n\n    // Output the generated graphs\n    for (int k = 0; k < M; ++k) {\n        cout << graphs[k].edges << endl;\n    }\n\n    // Process 100 queries\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // Compute degree sequence of H_k\n        vector<int> degH(N, 0);\n        int idx = 0;\n        for (int i = 0; i < N - 1; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (H[idx] == '1') {\n                    degH[i]++;\n                    degH[j]++;\n                }\n                idx++;\n            }\n        }\n        sort(degH.begin(), degH.end());\n\n        // Find the graph whose degree sequence is closest to H_k's\n        int best_k = 0;\n        long long min_dist = -1;\n        for (int k = 0; k < M; ++k) {\n            long long dist = 0;\n            for (int i = 0; i < N; ++i) {\n                long long diff = (long long)graphs[k].degree_seq[i] - degH[i];\n                dist += diff * diff;\n            }\n            if (min_dist == -1 || dist < min_dist) {\n                min_dist = dist;\n                best_k = k;\n            }\n        }\n        cout << best_k << endl;\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent an edge\nstruct Edge {\n    int u, v, w, id;\n};\n\n// Structure for predecessors in shortest path\nstruct Predecessor {\n    int u;\n    int edge_id;\n};\n\nint N, M, D, K;\nvector<vector<pair<int, pair<int, int>>>> adj;\nvector<Edge> edges;\nvector<double> edge_bc;\nvector<double> edge_cost;\n\n// Compute Betweenness Centrality using Brandes' algorithm\nvoid compute_bc() {\n    edge_bc.assign(M, 0.0);\n    for (int s = 0; s < N; ++s) {\n        vector<long long> dist(N + 1, 1e18); // Use 1-indexed for vertices\n        vector<double> sigma(N + 1, 0.0);\n        vector<vector<Predecessor>> predecessors(N + 1);\n        vector<int> order;\n        \n        dist[s + 1] = 0;\n        sigma[s + 1] = 1.0;\n        \n        priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n        pq.push({0, s + 1});\n        \n        while (!pq.empty()) {\n            long long d = pq.top().first;\n            int u = pq.top().second;\n            pq.pop();\n            \n            if (d > dist[u]) continue;\n            order.push_back(u);\n            \n            for (auto& edge : adj[u]) {\n                int v = edge.first;\n                int weight = edge.second.first;\n                int id = edge.second.second;\n                \n                if (dist[v] > dist[u] + weight) {\n                    dist[v] = dist[u] + weight;\n                    sigma[v] = sigma[u];\n                    predecessors[v].clear();\n                    predecessors[v].push_back({u, id});\n                    pq.push({dist[v], v});\n                } else if (dist[v] == dist[u] + weight) {\n                    sigma[v] += sigma[u];\n                    predecessors[v].push_back({u, id});\n                }\n            }\n        }\n        \n        vector<double> delta(N + 1, 0.0);\n        for (int i = order.size() - 1; i >= 0; --i) {\n            int w = order[i];\n            for (auto& pred : predecessors[w]) {\n                int v = pred.u;\n                int edge_id = pred.edge_id;\n                \n                double coeff = (sigma[v] / sigma[w]) * (1.0 + delta[w]);\n                delta[v] += coeff;\n                edge_bc[edge_id] += coeff;\n            }\n        }\n    }\n}\n\nint main() {\n    // Optimize I/O operations\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read input\n    cin >> N >> M >> D >> K;\n    adj.resize(N + 1);\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges[i] = {u, v, w, i};\n        adj[u].push_back({v, {w, i}});\n        adj[v].push_back({u, {w, i}});\n    }\n    \n    // Read coordinates (not used)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    // Compute BC and edge costs\n    compute_bc();\n    edge_cost.resize(M);\n    for (int i = 0; i < M; ++i) {\n        edge_cost[i] = edge_bc[i] * edges[i].w;\n    }\n    \n    // Initial assignment: sort edges by cost and assign round-robin\n    vector<int> edge_indices(M);\n    for (int i = 0; i < M; ++i) edge_indices[i] = i;\n    \n    sort(edge_indices.begin(), edge_indices.end(), [&](int a, int b) {\n        return edge_cost[a] > edge_cost[b];\n    });\n    \n    vector<int> schedule(M);\n    vector<vector<int>> days(D + 1);\n    vector<double> sum_cost(D + 1, 0.0);\n    \n    for (int i = 0; i < M; ++i) {\n        int day = (i % D) + 1;\n        schedule[edge_indices[i]] = day;\n        days[day].push_back(edge_indices[i]);\n        sum_cost[day] += edge_cost[edge_indices[i]];\n    }\n    \n    // Local Search: swap edges to balance costs across days\n    mt19937 rng(42);\n    int iterations = 5000000;\n    for (int iter = 0; iter < iterations; ++iter) {\n        int d1 = (rng() % D) + 1;\n        int d2 = (rng() % D) + 1;\n        if (d1 == d2 || days[d1].empty() || days[d2].empty()) continue;\n        \n        int idx1 = rng() % days[d1].size();\n        int idx2 = rng() % days[d2].size();\n        \n        int e1 = days[d1][idx1];\n        int e2 = days[d2][idx2];\n        \n        double current_var = 0;\n        for(int d=1; d<=D; ++d) current_var += sum_cost[d] * sum_cost[d];\n        \n        double new_sum_cost_d1 = sum_cost[d1] - edge_cost[e1] + edge_cost[e2];\n        double new_sum_cost_d2 = sum_cost[d2] - edge_cost[e2] + edge_cost[e1];\n        \n        double new_var = current_var - sum_cost[d1]*sum_cost[d1] - sum_cost[d2]*sum_cost[d2]\n                        + new_sum_cost_d1*new_sum_cost_d1 + new_sum_cost_d2*new_sum_cost_d2;\n        \n        if (new_var < current_var) {\n            sum_cost[d1] = new_sum_cost_d1;\n            sum_cost[d2] = new_sum_cost_d2;\n            days[d1][idx1] = e2;\n            days[d2][idx2] = e1;\n            schedule[e1] = d2;\n            schedule[e2] = d1;\n        }\n    }\n    \n    // Output the schedule\n    for (int i = 0; i < M; ++i) {\n        cout << schedule[i] << (i == M - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n};\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int D;\n    if (!(cin >> D)) return 0;\n\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for (int i = 0; i < D; ++i) cin >> f1[i];\n    for (int i = 0; i < D; ++i) cin >> r1[i];\n    for (int i = 0; i < D; ++i) cin >> f2[i];\n    for (int i = 0; i < D; ++i) cin >> r2[i];\n\n    // Compute maximum possible objects M1 and M2\n    auto get_max_obj = [&](const vector<string>& f, const vector<string>& r) {\n        vector<vector<vector<int>>> obj(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[z][x] == '1' && r[z][y] == '1') {\n                        obj[x][y][z] = 1;\n                    }\n                }\n            }\n        }\n        return obj;\n    };\n\n    auto M1 = get_max_obj(f1, r1);\n    auto M2 = get_max_obj(f2, r2);\n\n    // Compute intersection I, and unique parts U1, U2\n    vector<vector<vector<int>>> I(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> U1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> U2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n\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 (M1[x][y][z] && M2[x][y][z]) I[x][y][z] = 1;\n                else if (M1[x][y][z]) U1[x][y][z] = 1;\n                else if (M2[x][y][z]) U2[x][y][z] = 1;\n            }\n        }\n    }\n\n    vector<vector<vector<int>>> b1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> b2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n\n    int block_id = 1;\n\n    // BFS to find connected components and assign unique block IDs\n    auto find_components = [&](vector<vector<vector<int>>>& grid, int& id_counter, vector<vector<vector<int>>>& b_map) {\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\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 (grid[x][y][z] && !visited[x][y][z]) {\n                        queue<Point> q;\n                        q.push({x, y, z});\n                        visited[x][y][z] = true;\n                        b_map[x][y][z] = id_counter;\n                        \n                        int dx[] = {1, -1, 0, 0, 0, 0};\n                        int dy[] = {0, 0, 1, -1, 0, 0};\n                        int dz[] = {0, 0, 0, 0, 1, -1};\n                        \n                        while (!q.empty()) {\n                            Point curr = q.front();\n                            q.pop();\n\n                            for (int i = 0; i < 6; ++i) {\n                                int nx = curr.x + dx[i];\n                                int ny = curr.y + dy[i];\n                                int nz = curr.z + dz[i];\n                                if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                    grid[nx][ny][nz] && !visited[nx][ny][nz]) {\n                                    visited[nx][ny][nz] = true;\n                                    b_map[nx][ny][nz] = id_counter;\n                                    q.push({nx, ny, nz});\n                                }\n                            }\n                        }\n                        id_counter++;\n                    }\n                }\n            }\n        }\n    };\n\n    // 1. Process intersection (shared)\n    find_components(I, block_id, b1);\n    for(int x=0; x<D; ++x) for(int y=0; y<D; ++y) for(int z=0; z<D; ++z) b2[x][y][z] = b1[x][y][z];\n    \n    // 2. Process unique parts for object 1\n    find_components(U1, block_id, b1);\n    // 3. Process unique parts for object 2\n    find_components(U2, block_id, b2);\n\n    // Output result\n    cout << block_id - 1 << endl;\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 << b1[x][y][z] << (x == D - 1 && y == D - 1 && z == D - 1 ? \"\" : \" \");\n            }\n        }\n    }\n    cout << endl;\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 << b2[x][y][z] << (x == D - 1 && y == D - 1 && z == D - 1 ? \"\" : \" \");\n            }\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <queue>\n\nusing namespace std;\n\n// Structure for Edge\nstruct Edge {\n    int u, v, w, id;\n};\n\n// Structure for Point\nstruct Point {\n    int x, y;\n};\n\nint N, M, K;\nvector<Point> stations;\nvector<Point> residents;\nvector<Edge> edges;\nvector<vector<pair<int, int>>> adj; // adj[u] = {(v, edge_index), ...}\n\n// Precomputed distances\nvector<vector<double>> station_resident_dist;\n\n// MST structures\nvector<int> parent_node;\nvector<int> parent_edge_idx;\nvector<vector<int>> path_to_root;\n\n// Structure for Cost Result\nstruct CostResult {\n    long long total_cost;\n    vector<int> P;\n    vector<int> B;\n};\n\nvoid build_mst() {\n    vector<int> min_weight(N + 1, 2e9);\n    vector<bool> visited(N + 1, false);\n    parent_node.assign(N + 1, -1);\n    parent_edge_idx.assign(N + 1, -1);\n    \n    min_weight[1] = 0;\n    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n    pq.push({0, 1});\n\n    while (!pq.empty()) {\n        int u = pq.top().second;\n        pq.pop();\n        if (visited[u]) continue;\n        visited[u] = true;\n\n        for (auto& edge : adj[u]) {\n            int v = edge.first;\n            int edge_idx = edge.second;\n            int w = edges[edge_idx].w;\n            if (!visited[v] && w < min_weight[v]) {\n                min_weight[v] = w;\n                parent_node[v] = u;\n                parent_edge_idx[v] = edge_idx;\n                pq.push({w, v});\n            }\n        }\n    }\n    \n    path_to_root.resize(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        int curr = i;\n        while (parent_node[curr] != -1) {\n            path_to_root[i].push_back(parent_edge_idx[curr]);\n            curr = parent_node[curr];\n        }\n    }\n}\n\n// Function to calculate total cost for a given V_active\nCostResult calculate_cost(const vector<bool>& v_active) {\n    vector<int> active_nodes;\n    for (int i = 1; i <= N; ++i) if (v_active[i]) active_nodes.push_back(i);\n    \n    vector<int> assignment(K);\n    vector<int> P(N + 1, 0);\n    \n    // Assign residents to nearest active station\n    for (int k = 0; k < K; ++k) {\n        double min_d = 1e18;\n        int best_node = -1;\n        for (int node : active_nodes) {\n            if (station_resident_dist[node][k] < min_d) {\n                min_d = station_resident_dist[node][k];\n                best_node = node;\n            }\n        }\n        assignment[k] = best_node;\n    }\n    \n    // Calculate required output strength P[i] for each active station\n    for (int k = 0; k < K; ++k) {\n        int node = assignment[k];\n        double d = station_resident_dist[node][k];\n        P[node] = max(P[node], (int)ceil(d));\n    }\n    \n    long long radio_cost = 0;\n    for (int i = 1; i <= N; ++i) {\n        radio_cost += (long long)P[i] * P[i];\n    }\n    \n    vector<int> B(M, 0);\n    long long edge_cost = 0;\n    vector<bool> edge_active(M, false);\n    \n    // Mark edges needed to connect all active stations to 1\n    for (int node : active_nodes) {\n        for (int edge_idx : path_to_root[node]) {\n            if (!edge_active[edge_idx]) {\n                edge_active[edge_idx] = true;\n                edge_cost += edges[edge_idx].w;\n                B[edge_idx] = 1;\n            }\n        }\n    }\n    \n    return {radio_cost + edge_cost, P, B};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N >> M >> K;\n    stations.resize(N + 1);\n    for (int i = 1; i <= N; ++i) cin >> stations[i].x >> stations[i].y;\n    \n    adj.resize(N + 1);\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges[i] = {u, v, w, i};\n        adj[u].push_back({v, i});\n        adj[v].push_back({u, i});\n    }\n    \n    residents.resize(K);\n    for (int k = 0; k < K; ++k) cin >> residents[k].x >> residents[k].y;\n    \n    station_resident_dist.resize(N + 1, vector<double>(K));\n    for (int i = 1; i <= N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            station_resident_dist[i][k] = sqrt(pow(stations[i].x - residents[k].x, 2) + pow(stations[i].y - residents[k].y, 2));\n        }\n    }\n    \n    build_mst();\n    \n    vector<bool> v_active(N + 1, false);\n    // Start with just node 1 as active\n    v_active[1] = true;\n    \n    CostResult current = calculate_cost(v_active);\n    \n    // Greedy search loop\n    while (true) {\n        long long best_cost = current.total_cost;\n        int best_action = -1; // 1000 + v for add, -v for remove\n        \n        // Try adding each inactive node\n        for (int i = 1; i <= N; ++i) {\n            if (!v_active[i]) {\n                v_active[i] = true;\n                CostResult next = calculate_cost(v_active);\n                if (next.total_cost < best_cost) {\n                    best_cost = next.total_cost;\n                    best_action = 1000 + i;\n                }\n                v_active[i] = false;\n            }\n        }\n        \n        // Try removing each active node (except node 1)\n        for (int i = 2; i <= N; ++i) {\n            if (v_active[i]) {\n                v_active[i] = false;\n                CostResult next = calculate_cost(v_active);\n                if (next.total_cost < best_cost) {\n                    best_cost = next.total_cost;\n                    best_action = -i;\n                }\n                v_active[i] = true;\n            }\n        }\n        \n        if (best_action == -1) break;\n        \n        if (best_action >= 1000) {\n            v_active[best_action - 1000] = true;\n        } else {\n            v_active[-best_action] = false;\n        }\n        current = calculate_cost(v_active);\n    }\n    \n    // Output result\n    for (int i = 1; i <= N; ++i) cout << current.P[i] << (i == N ? \"\" : \" \");\n    cout << endl;\n    for (int i = 0; i < M; ++i) cout << current.B[i] << (i == M - 1 ? \"\" : \" \");\n    cout << endl;\n    \n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\n// The number of pyramid tiers is fixed to N=30.\nconstexpr int N = 30;\nint board[N][N];\n\n// Structure to store swap operations\nstruct SwapOp {\n    int x1, y1, x2, y2;\n};\nvector<SwapOp> swap_ops;\n\n// Function to perform and record a swap\nvoid perform_swap(int x1, int y1, int x2, int y2) {\n    swap(board[x1][y1], board[x2][y2]);\n    swap_ops.push_back({x1, y1, x2, y2});\n}\n\nint main() {\n    // Optimize I/O operations\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read the pyramid input\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            cin >> board[i][j];\n        }\n    }\n\n    // Build-Heap algorithm to satisfy the min-heap condition\n    // Start from the last non-leaf level (N-2) and go up to the top (0,0)\n    // For each node, perform a \"sift-down\" operation to maintain the heap property\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            int cur_x = x;\n            int cur_y = y;\n            \n            // Sift-down process\n            while (cur_x < N - 1) {\n                // The children of (cur_x, cur_y) are (cur_x + 1, cur_y) and (cur_x + 1, cur_y + 1)\n                int l_x = cur_x + 1;\n                int l_y = cur_y;\n                int r_x = cur_x + 1;\n                int r_y = cur_y + 1;\n\n                // Identify the smaller of the two children to maintain the min-heap\n                int next_x = l_x;\n                int next_y = l_y;\n                if (board[r_x][r_y] < board[l_x][l_y]) {\n                    next_x = r_x;\n                    next_y = r_y;\n                }\n\n                // If the current node violates the heap property, swap with the smaller child\n                if (board[cur_x][cur_y] > board[next_x][next_y]) {\n                    perform_swap(cur_x, cur_y, next_x, next_y);\n                    cur_x = next_x;\n                    cur_y = next_y;\n                } else {\n                    // Property is satisfied for this branch\n                    break;\n                }\n            }\n        }\n    }\n\n    // Output the number of operations followed by the operations themselves\n    cout << swap_ops.size() << \"\\n\";\n    for (const auto& op : swap_ops) {\n        cout << op.x1 << \" \" << op.y1 << \" \" << op.x2 << \" \" << op.y2 << \"\\n\";\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nconst int D = 9;\nint grid[D][D]; // -2 obstacle, -1 empty, >=0 container label\nbool is_removed[85];\npair<int, int> pos[85];\nint D_dist[D][D]; // BFS distances from (0, 4) in an empty board\n\nint dr[] = {0, 0, 1, -1};\nint dc[] = {1, -1, 0, 0};\n\n// Precompute distances in an empty grid\nvoid precompute_dist() {\n    for (int i = 0; i < D; ++i)\n        for (int j = 0; j < D; ++j)\n            D_dist[i][j] = -1;\n\n    queue<pair<int, int>> q;\n    q.push({0, 4});\n    D_dist[0][4] = 0;\n\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i];\n            int nc = c + dc[i];\n            if (nr >= 0 && nr < D && nc >= 0 && nc < D && D_dist[nr][nc] == -1) {\n                if (grid[nr][nc] != -2) {\n                    D_dist[nr][nc] = D_dist[r][c] + 1;\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n}\n\n// Find path from entrance to (tr, tc), treating other containers as obstacles.\n// Path excludes entrance, includes (tr, tc).\nvector<pair<int, int>> get_path(int tr, int tc) {\n    if (grid[tr][tc] == -2) return {}; \n    if (tr == 0 && tc == 4) return {{0, 4}};\n\n    struct Node {\n        int r, c;\n        vector<pair<int, int>> path;\n    };\n    queue<Node> q;\n    q.push({0, 4, {{0, 4}}});\n\n    bool visited[D][D];\n    for(int i=0; i<D; ++i) for(int j=0; j<D; ++j) visited[i][j] = false;\n    visited[0][4] = true;\n\n    while (!q.empty()) {\n        Node curr = q.front();\n        q.pop();\n\n        if (curr.r == tr && curr.c == tc) return curr.path;\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n\n            if (nr >= 0 && nr < D && nc >= 0 && nc < D && !visited[nr][nc]) {\n                // Passable if empty OR it is the target container\n                if (grid[nr][nc] == -1 || (nr == tr && nc == tc)) {\n                    visited[nr][nc] = true;\n                    vector<pair<int, int>> next_path = curr.path;\n                    next_path.push_back({nr, nc});\n                    q.push({nr, nc, next_path});\n                }\n            }\n        }\n    }\n    return {};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N;\n    cin >> D >> N;\n\n    for (int i = 0; i < D; ++i)\n        for (int j = 0; j < D; ++j)\n            grid[i][j] = -1;\n\n    for (int i = 0; i < N; ++i) {\n        int r, c;\n        cin >> r >> c;\n        grid[r][c] = -2;\n    }\n\n    precompute_dist();\n    int max_dist = 0;\n    for(int i=0; i<D; ++i) for(int j=0; j<D; ++j) if(D_dist[i][j] > max_dist) max_dist = D_dist[i][j];\n\n    int K = D * D - 1 - N;\n    vector<pair<int, int>> removal_order;\n\n    for (int d = 0; d < K; ++d) {\n        int t;\n        cin >> t;\n\n        int best_r = -1, best_c = -1;\n        double min_score = 1e18;\n\n        for (int r = 0; r < D; ++r) {\n            for (int c = 0; c < D; ++c) {\n                if (grid[r][c] == -1) {\n                    if (!get_path(r, c).empty()) {\n                        double target_val = (double)t / (K - 1) * max_dist;\n                        double score = abs(D_dist[r][c] - target_val);\n                        if (score < min_score) {\n                            min_score = score;\n                            best_r = r;\n                            best_c = c;\n                        }\n                    }\n                }\n            }\n        }\n\n        grid[best_r][best_c] = t;\n        pos[t] = {best_r, best_c};\n        cout << best_r << \" \" << best_c << endl;\n    }\n\n    int target = 0;\n    int removed_cnt = 0;\n    for(int i=0; i<85; ++i) is_removed[i] = false;\n\n    while (removed_cnt < K) {\n        if (is_removed[target]) {\n            target++;\n            continue;\n        }\n\n        if (!get_path(pos[target].first, pos[target].second).empty()) {\n            removal_order.push_back(pos[target]);\n            grid[pos[target].first][pos[target].second] = -1;\n            is_removed[target] = true;\n            removed_cnt++;\n        } else {\n            int best_label = -1;\n            pair<int, int> best_pos = {-1, -1};\n            for(int r=0; r<D; ++r) {\n                for(int c=0; c<D; ++c) {\n                    if(grid[r][c] >= 0) {\n                        if (!get_path(r, c).empty()) {\n                            if (grid[r][c] > best_label) {\n                                best_label = grid[r][c];\n                                best_pos = {r, c};\n                            }\n                        }\n                    }\n                }\n            }\n            removal_order.push_back(best_pos);\n            grid[best_pos.first][best_pos.second] = -1;\n            is_removed[best_label] = true;\n            removed_cnt++;\n        }\n    }\n\n    for (auto p : removal_order) {\n        cout << p.first << \" \" << p.second << endl;\n    }\n\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <ctime>\n\nusing namespace std;\n\nconst int MAX_N = 50;\nint N, M;\nint grid[MAX_N][MAX_N];\nbool target_adj[101][101];\nint count_adj[101][101];\nint n_cells[101];\n\nint dr[] = {0, 0, 1, -1};\nint dc[] = {1, -1, 0, 0};\n\nbool is_connected(int c) {\n    if (c == 0) return true;\n    if (n_cells[c] == 0) return true;\n\n    int start_r = -1, start_c = -1;\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            if(grid[i][j] == c) {\n                start_r = i;\n                start_c = j;\n                break;\n            }\n        }\n        if(start_r != -1) break;\n    }\n\n    if(start_r == -1) return true;\n\n    int visited = 0;\n    static int vis[MAX_N][MAX_N];\n    static int vis_gen = 0;\n    vis_gen++;\n\n    queue<pair<int, int>> q;\n    q.push({start_r, start_c});\n    vis[start_r][start_c] = vis_gen;\n    visited++;\n\n    while(!q.empty()){\n        auto [r, c_] = q.front();\n        q.pop();\n\n        for(int i=0; i<4; ++i) {\n            int nr = r + dr[i];\n            int nc = c_ + dc[i];\n            if(nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] == c && vis[nr][nc] != vis_gen){\n                vis[nr][nc] = vis_gen;\n                visited++;\n                q.push({nr, nc});\n            }\n        }\n    }\n    return visited == n_cells[c];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M;\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            cin >> grid[i][j];\n            n_cells[grid[i][j]]++;\n        }\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 + dr[k];\n                int nj = j + dc[k];\n                int nc;\n                if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                else nc = grid[ni][nj];\n                \n                if(grid[i][j] != nc) {\n                    count_adj[grid[i][j]][nc]++;\n                    target_adj[grid[i][j]][nc] = true;\n                }\n            }\n        }\n    }\n\n    mt19937 rng(42);\n    vector<pair<int, int>> squares;\n    for(int i=0; i<N; ++i)\n        for(int j=0; j<N; ++j)\n            squares.push_back({i, j});\n\n    auto start_time = clock();\n    while( (double)(clock() - start_time) / CLOCKS_PER_SEC < 1.8) {\n        shuffle(squares.begin(), squares.end(), rng);\n        for(auto [i, j] : squares) {\n            int old_c = grid[i][j];\n            if(old_c == 0) continue;\n            \n            // To ensure color doesn't disappear\n            if(n_cells[old_c] == 1) continue;\n\n            vector<int> candidates = {0};\n            for(int k=0; k<4; ++k) {\n                int ni = i + dr[k];\n                int nj = j + dc[k];\n                if(ni >= 0 && ni < N && nj >= 0 && nj < N)\n                    candidates.push_back(grid[ni][nj]);\n            }\n            shuffle(candidates.begin(), candidates.end(), rng);\n\n            for(int new_c : candidates) {\n                if(new_c == old_c) continue;\n                \n                int temp_count_adj[101][101];\n                for(int r=0; r<=M; ++r) for(int c=0; c<=M; ++c) temp_count_adj[r][c] = count_adj[r][c];\n\n                for(int k=0; k<4; ++k) {\n                    int ni = i + dr[k];\n                    int nj = j + dc[k];\n                    int nc;\n                    if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                    else nc = grid[ni][nj];\n                    \n                    temp_count_adj[old_c][nc]--;\n                    temp_count_adj[nc][old_c]--;\n                    temp_count_adj[new_c][nc]++;\n                    temp_count_adj[nc][new_c]++;\n                }\n                \n                bool adj_ok = true;\n                for(int c=0; c<=M; ++c) {\n                    if(target_adj[old_c][c] && temp_count_adj[old_c][c] == 0) {\n                        adj_ok = false; break;\n                    }\n                    if(c != old_c && c != new_c && !target_adj[new_c][c] && temp_count_adj[new_c][c] > 0) {\n                        adj_ok = false; break;\n                    }\n                }\n                if(!adj_ok) continue;\n\n                grid[i][j] = new_c;\n                n_cells[old_c]--;\n                n_cells[new_c]++;\n                \n                if(!is_connected(old_c) || !is_connected(new_c)) {\n                    grid[i][j] = old_c;\n                    n_cells[old_c]++;\n                    n_cells[new_c]--;\n                    continue;\n                }\n                \n                for(int r=0; r<=M; ++r) for(int c=0; c<=M; ++c) count_adj[r][c] = temp_count_adj[r][c];\n                break; \n            }\n        }\n    }\n\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            cout << grid[i][j] << (j == N-1 ? \"\" : \" \");\n        }\n        cout << \"\\n\";\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <string>\n#include <numeric>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <iomanip>\n\nusing namespace std;\n\n// The Solver class encapsulates the logic for the problem\nstruct Solver {\n    int N, D, Q;\n    vector<double> weights; // Estimated weights of items\n    mt19937 rng;\n\n    Solver() : rng(1337) {}\n\n    void solve() {\n        // Read N, D, Q\n        if (!(cin >> N >> D >> Q)) return;\n        \n        // Initialize weights to a base value\n        weights.assign(N, 1000.0);\n\n        // Perform queries\n        for (int q = 0; q < Q; ++q) {\n            // Select L and R sets with random sizes (at least 1, at most N/2)\n            int nL = uniform_int_distribution<int>(1, N / 2)(rng);\n            int nR = uniform_int_distribution<int>(1, N / 2)(rng);\n            \n            vector<int> items(N);\n            iota(items.begin(), items.end(), 0);\n            shuffle(items.begin(), items.end(), rng);\n            \n            vector<int> L(items.begin(), items.begin() + nL);\n            vector<int> R(items.begin() + nL, items.begin() + nL + nR);\n            \n            // Output query\n            cout << L.size() << \" \" << R.size();\n            for (int i : L) cout << \" \" << i;\n            for (int i : R) cout << \" \" << i;\n            cout << endl;\n            \n            // Read result\n            string res;\n            cin >> res;\n            \n            // Update weights based on result\n            double sumL = 0;\n            for (int i : L) sumL += weights[i];\n            double sumR = 0;\n            for (int i : R) sumR += weights[i];\n            \n            // Decay learning rate alpha from 0.1 to 0.01\n            double alpha = 0.1 * (1.0 - 0.9 * (double)q / Q);\n            \n            // If sumL < sumR, diff > 0. If sumL > sumR, diff < 0.\n            // Adjust weights to minimize the difference in future queries.\n            double diff = 0;\n            if (res == \"<\") {\n                diff = sumR - sumL; // Target L to increase, R to decrease\n            } else if (res == \">\") {\n                diff = sumL - sumR; // Target L to decrease, R to increase\n                diff = -diff;\n            } else {\n                diff = sumL - sumR; // Target to zero\n                diff = -diff;\n            }\n            \n            for (int i : L) weights[i] += alpha * diff / L.size();\n            for (int i : R) weights[i] -= alpha * diff / R.size();\n            \n            // Keep weights positive\n            for (double& w : weights) w = max(1.0, w);\n        }\n        \n        // Final partition\n        vector<int> assignment(N);\n        vector<double> bucket_weights(D, 0.0);\n        \n        // Greedy assignment based on estimated weights (LPT)\n        vector<int> sorted_items(N);\n        iota(sorted_items.begin(), sorted_items.end(), 0);\n        sort(sorted_items.begin(), sorted_items.end(), [&](int a, int b) {\n            return weights[a] > weights[b];\n        });\n        \n        for (int i : sorted_items) {\n            int best_bucket = 0;\n            for (int d = 1; d < D; ++d) {\n                if (bucket_weights[d] < bucket_weights[best_bucket]) {\n                    best_bucket = d;\n                }\n            }\n            assignment[i] = best_bucket;\n            bucket_weights[best_bucket] += weights[i];\n        }\n        \n        // Local search to refine the partition\n        // 100,000 iterations is well within the 2-second limit\n        for (int iter = 0; iter < 100000; ++iter) {\n            int b1 = uniform_int_distribution<int>(0, D - 1)(rng);\n            int b2 = uniform_int_distribution<int>(0, D - 1)(rng);\n            if (b1 == b2) continue;\n            \n            // Find items in buckets b1 and b2\n            vector<int> items1, items2;\n            for (int i = 0; i < N; ++i) {\n                if (assignment[i] == b1) items1.push_back(i);\n                else if (assignment[i] == b2) items2.push_back(i);\n            }\n            if (items1.empty() || items2.empty()) continue;\n            \n            int i1 = items1[uniform_int_distribution<int>(0, items1.size() - 1)(rng)];\n            int i2 = items2[uniform_int_distribution<int>(0, items2.size() - 1)(rng)];\n            \n            // Calculate current sum of squares (proportional to variance)\n            double old_sum_sq = 0;\n            for (double w : bucket_weights) old_sum_sq += w * w;\n            \n            // Calculate new sum of squares if we swap i1 and i2\n            double new_bw1 = bucket_weights[b1] - weights[i1] + weights[i2];\n            double new_bw2 = bucket_weights[b2] - weights[i2] + weights[i1];\n            \n            double new_sum_sq = old_sum_sq \n                                - bucket_weights[b1]*bucket_weights[b1] - bucket_weights[b2]*bucket_weights[b2]\n                                + new_bw1 * new_bw1 + new_bw2 * new_bw2;\n                           \n            // If swap improves variance (decreases sum of squares), accept it\n            if (new_sum_sq < old_sum_sq) {\n                assignment[i1] = b2;\n                assignment[i2] = b1;\n                bucket_weights[b1] = new_bw1;\n                bucket_weights[b2] = new_bw2;\n            }\n        }\n        \n        // Output the final partition\n        for (int i = 0; i < N; ++i) cout << assignment[i] << (i == N - 1 ? \"\" : \" \");\n        cout << endl;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    Solver s;\n    s.solve();\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\n// Configuration\nint N, M;\nvector<vector<int>> stacks;\nvector<int> box_to_stack;\nvector<int> box_to_pos;\n\n// Find the stack containing a specific target box\nint find_stack(int target) {\n    return box_to_stack[target];\n}\n\n// Find the best destination stack for moving boxes\n// Criteria: prefer empty stacks, otherwise pick the one with the largest top box\nint find_best_dest(int s) {\n    int best_d = -1;\n    int max_top = -2;\n    for (int d = 0; d < M; ++d) {\n        if (d == s) continue;\n        if (stacks[d].empty()) return d;\n        if (stacks[d].back() > max_top) {\n            max_top = stacks[d].back();\n            best_d = d;\n        }\n    }\n    return best_d;\n}\n\n// Move the block of boxes above the target box to another stack d\nvoid move_block(int s, int pos, int d) {\n    // The target box is at `pos`. The boxes above it are at indices `pos + 1` to `end`.\n    int block_start_idx = pos + 1;\n    \n    // Update stack_ids and positions for the moved boxes\n    for (int i = block_start_idx; i < (int)stacks[s].size(); ++i) {\n        int b = stacks[s][i];\n        stacks[d].push_back(b);\n        box_to_stack[b] = d;\n        box_to_pos[b] = (int)stacks[d].size() - 1;\n    }\n    \n    // Remove the moved boxes from the original stack\n    stacks[s].erase(stacks[s].begin() + block_start_idx, stacks[s].end());\n}\n\nint main() {\n    // Optimize I/O\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read N and M\n    cin >> N >> M;\n    stacks.resize(M);\n    box_to_stack.resize(N + 1);\n    box_to_pos.resize(N + 1);\n\n    // Read the initial stack configuration\n    for (int i = 0; i < M; ++i) {\n        for (int j = 0; j < N / M; ++j) {\n            int b;\n            cin >> b;\n            stacks[i].push_back(b);\n            box_to_stack[b] = i;\n            box_to_pos[b] = (int)stacks[i].size() - 1;\n        }\n    }\n\n    int target = 1;\n    int ops = 0;\n    \n    // Process until all boxes are removed\n    while (target <= N && ops < 5000) {\n        int s = find_stack(target);\n        int pos = box_to_pos[target];\n        \n        // If target is at the top of its stack, remove it\n        if (pos == (int)stacks[s].size() - 1) {\n            cout << target << \" 0\" << endl;\n            stacks[s].pop_back();\n            target++;\n            ops++;\n        } else {\n            // Otherwise, move the block above the target to another stack\n            // The box directly above target is stacks[s][pos + 1]\n            int v_prime = stacks[s][pos + 1];\n            int d = find_best_dest(s);\n            \n            // Output the move operation (v, i+1)\n            cout << v_prime << \" \" << (d + 1) << endl;\n            \n            // Perform the move\n            move_block(s, pos, d);\n            ops++;\n        }\n    }\n\n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <set>\n#include <ctime>\n\nusing namespace std;\n\n// Function to get index from (r, c)\nint id(int r, int c, int N) {\n    return r * N + c;\n}\n\n// Function to get (r, c) from index\npair<int, int> pos(int idx, int N) {\n    return {idx / N, idx % N};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> h(N - 1), v(N);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    for (int i = 0; i < N; ++i) cin >> v[i];\n    vector<vector<int>> d(N, vector<int>(N));\n    vector<int> d_flat(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n            d_flat[id(i, j, N)] = d[i][j];\n        }\n    }\n\n    // Graph adjacency\n    vector<vector<int>> adj(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (i + 1 < N && h[i][j] == '0') {\n                adj[id(i, j, N)].push_back(id(i + 1, j, N));\n                adj[id(i + 1, j, N)].push_back(id(i, j, N));\n            }\n            if (j + 1 < N && v[i][j] == '0') {\n                adj[id(i, j, N)].push_back(id(i, j + 1, N));\n                adj[id(i, j + 1, N)].push_back(id(i, j, N));\n            }\n        }\n    }\n\n    // Prim's algorithm for initial MST\n    vector<int> deg(N * N, 0);\n    vector<vector<int>> tree_adj(N * N);\n    vector<bool> in_tree(N * N, false);\n    vector<pair<int, int>> edges_in_tree;\n    vector<pair<int, int>> edges_not_in_tree;\n\n    vector<int> min_edge(N * N, 1e9);\n    vector<int> parent(N * N, -1);\n    in_tree[0] = true;\n    for (int neighbor : adj[0]) {\n        min_edge[neighbor] = -(d[0][0] + d[pos(neighbor, N).first][pos(neighbor, N).second]);\n        parent[neighbor] = 0;\n    }\n\n    for (int i = 1; i < N * N; ++i) {\n        int u = -1;\n        for (int v = 0; v < N * N; ++v) {\n            if (!in_tree[v] && parent[v] != -1) {\n                if (u == -1 || min_edge[v] < min_edge[u]) u = v;\n            }\n        }\n        in_tree[u] = true;\n        int p = parent[u];\n        tree_adj[u].push_back(p);\n        tree_adj[p].push_back(u);\n        deg[u]++;\n        deg[p]++;\n        edges_in_tree.push_back({min(u, p), max(u, p)});\n\n        for (int neighbor : adj[u]) {\n            if (!in_tree[neighbor]) {\n                int weight = -(d[pos(u, N).first][pos(u, N).second] + d[pos(neighbor, N).first][pos(neighbor, N).second]);\n                if (weight < min_edge[neighbor]) {\n                    min_edge[neighbor] = weight;\n                    parent[neighbor] = u;\n                }\n            }\n        }\n    }\n\n    // Identify edges not in tree\n    vector<vector<bool>> is_in_tree(N * N, vector<bool>(N * N, false));\n    for (auto& edge : edges_in_tree) {\n        is_in_tree[edge.first][edge.second] = true;\n        is_in_tree[edge.second][edge.first] = true;\n    }\n\n    for (int u = 0; u < N * N; ++u) {\n        for (int neighbor : adj[u]) {\n            if (u < neighbor && !is_in_tree[u][neighbor]) {\n                edges_not_in_tree.push_back({u, neighbor});\n            }\n        }\n    }\n\n    // Hill Climbing\n    mt19937 rng(42);\n    auto start_time = clock();\n    while ((double)(clock() - start_time) / CLOCKS_PER_SEC < 1.8) {\n        int idx = rng() % edges_not_in_tree.size();\n        int x = edges_not_in_tree[idx].first;\n        int y = edges_not_in_tree[idx].second;\n\n        vector<int> path_parent(N * N, -1);\n        vector<int> q;\n        q.push_back(x);\n        vector<bool> visited(N * N, false);\n        visited[x] = true;\n        int head = 0;\n        while(head < (int)q.size()){\n            int u = q[head++];\n            if (u == y) break;\n            for(int neighbor : tree_adj[u]){\n                if(!visited[neighbor]){\n                    visited[neighbor] = true;\n                    path_parent[neighbor] = u;\n                    q.push_back(neighbor);\n                }\n            }\n        }\n        \n        vector<pair<int, int>> path_edges;\n        int curr = y;\n        while(curr != x){\n            int p = path_parent[curr];\n            path_edges.push_back({min(curr, p), max(curr, p)});\n            curr = p;\n        }\n\n        double best_delta = 0;\n        pair<int, int> best_swap_edge = {-1, -1};\n\n        for(auto& e : path_edges){\n            int a = e.first;\n            int b = e.second;\n            double old_c = (double)d_flat[a]/pow(deg[a], 2) + (double)d_flat[b]/pow(deg[b], 2) + \n                           (double)d_flat[x]/pow(deg[x], 2) + (double)d_flat[y]/pow(deg[y], 2);\n            double new_c = (double)d_flat[a]/pow(deg[a]-1, 2) + (double)d_flat[b]/pow(deg[b]-1, 2) + \n                           (double)d_flat[x]/pow(deg[x]+1, 2) + (double)d_flat[y]/pow(deg[y]+1, 2);\n            if (new_c - old_c < best_delta) {\n                best_delta = new_c - old_c;\n                best_swap_edge = e;\n            }\n        }\n\n        if (best_swap_edge.first != -1) {\n            int a = best_swap_edge.first;\n            int b = best_swap_edge.second;\n            \n            is_in_tree[a][b] = is_in_tree[b][a] = false;\n            is_in_tree[x][y] = is_in_tree[y][x] = true;\n            \n            for(int i=0; i<(int)tree_adj[a].size(); ++i) if(tree_adj[a][i] == b) { tree_adj[a].erase(tree_adj[a].begin()+i); break; }\n            for(int i=0; i<(int)tree_adj[b].size(); ++i) if(tree_adj[b][i] == a) { tree_adj[b].erase(tree_adj[b].begin()+i); break; }\n            tree_adj[x].push_back(y);\n            tree_adj[y].push_back(x);\n            \n            deg[a]--; deg[b]--; deg[x]++; deg[y]++;\n            \n            edges_not_in_tree[idx] = {a, b};\n        }\n    }\n\n    vector<vector<int>> children(N * N);\n    vector<int> parent_node(N * N, -1);\n    vector<int> q;\n    q.push_back(0);\n    vector<bool> visited(N * N, false);\n    visited[0] = true;\n    int head = 0;\n    while(head < (int)q.size()){\n        int u = q[head++];\n        for(int neighbor : tree_adj[u]){\n            if(!visited[neighbor]){\n                visited[neighbor] = true;\n                parent_node[neighbor] = u;\n                children[u].push_back(neighbor);\n                q.push_back(neighbor);\n            }\n        }\n    }\n\n    vector<long long> subtree_d(N * N, 0);\n    for(int i = N * N - 1; i >= 0; --i){\n        int u = q[i];\n        subtree_d[u] += d_flat[u];\n        if(parent_node[u] != -1) subtree_d[parent_node[u]] += subtree_d[u];\n    }\n    \n    for(int i=0; i<N*N; ++i){\n        sort(children[i].begin(), children[i].end(), [&](int a, int b){\n            return subtree_d[a] > subtree_d[b];\n        });\n    }\n\n    string path_str = \"\";\n    auto get_dir = [&](int u, int v) {\n        pair<int, int> p1 = pos(u, N), p2 = pos(v, N);\n        if (p2.first == p1.first + 1) return 'D';\n        if (p2.first == p1.first - 1) return 'U';\n        if (p2.second == p1.second + 1) return 'R';\n        if (p2.second == p1.second - 1) return 'L';\n        return ' ';\n    };\n\n    auto dfs = [&](auto self, int u, int p) -> void {\n        for(int neighbor : children[u]){\n            path_str += get_dir(u, neighbor);\n            self(self, neighbor, u);\n            path_str += get_dir(neighbor, u);\n        }\n    };\n    \n    dfs(dfs, 0, -1);\n    \n    string final_path = \"\";\n    while((int)final_path.length() + (int)path_str.length() <= 100000){\n        final_path += path_str;\n    }\n    \n    cout << final_path << endl;\n\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Structure to hold grid coordinates\nstruct Pos {\n    int r, c;\n};\n\n// Function to calculate the cost of moving between two squares.\n// The problem states the cost is |r1-r2| + |c1-c2| + 1.\nint dist(Pos p1, Pos p2) {\n    return abs(p1.r - p2.r) + abs(p1.c - p2.c) + 1;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n\n    // Store grid positions for each letter\n    vector<string> grid(N);\n    vector<vector<Pos>> pos(26);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n        for (int j = 0; j < N; ++j) {\n            pos[grid[i][j] - 'A'].push_back({i, j});\n        }\n    }\n\n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) cin >> t[i];\n\n    // Precompute overlaps between all pairs of strings\n    // overlap[i][j] is the length of the longest suffix of t[i] \n    // that is a prefix of t[j].\n    vector<vector<int>> overlap(M, vector<int>(M));\n    for (int i = 0; i < M; ++i) {\n        for (int j = 0; j < M; ++j) {\n            if (i == j) continue;\n            for (int len = 5; len >= 0; --len) {\n                if (t[i].substr(5 - len) == t[j].substr(0, len)) {\n                    overlap[i][j] = len;\n                    break;\n                }\n            }\n        }\n    }\n\n    long long best_total_cost = 1e18;\n    vector<Pos> best_path;\n\n    // Try starting the superstring with each of the M strings to find the best ordering\n    for (int start_node = 0; start_node < M; ++start_node) {\n        vector<int> order;\n        vector<bool> used(M, false);\n        order.push_back(start_node);\n        used[start_node] = true;\n        \n        string current_s = t[start_node];\n\n        // Greedy construction of the superstring\n        while (order.size() < M) {\n            int last = order.back();\n            int best_next = -1;\n            int max_o = -1;\n            for (int i = 0; i < M; ++i) {\n                if (!used[i]) {\n                    if (overlap[last][i] > max_o) {\n                        max_o = overlap[last][i];\n                        best_next = i;\n                    }\n                }\n            }\n            order.push_back(best_next);\n            used[best_next] = true;\n            current_s += t[best_next].substr(max_o);\n        }\n\n        // DP to find the minimum cost to type current_s on the grid\n        int L = current_s.length();\n        \n        // Initial DP table for the first character\n        int start_char = current_s[0] - 'A';\n        vector<long long> dp(pos[start_char].size());\n        vector<int> parent(pos[start_char].size(), -1);\n        \n        Pos start_pos = {si, sj};\n        for (size_t i = 0; i < pos[start_char].size(); ++i) {\n            dp[i] = dist(start_pos, pos[start_char][i]);\n        }\n\n        // parent_path[k][i] stores the parent index for the i-th occurrence of character at step k\n        vector<vector<int>> parent_path(L);\n        parent_path[0] = parent;\n\n        for (int k = 1; k < L; ++k) {\n            int curr_char = current_s[k] - 'A';\n            int prev_char = current_s[k-1] - 'A';\n            \n            vector<long long> next_dp(pos[curr_char].size(), 1e18);\n            vector<int> next_parent(pos[curr_char].size(), -1);\n            \n            for (size_t i = 0; i < pos[curr_char].size(); ++i) {\n                for (size_t j = 0; j < pos[prev_char].size(); ++j) {\n                    long long cost = dp[j] + dist(pos[prev_char][j], pos[curr_char][i]);\n                    if (cost < next_dp[i]) {\n                        next_dp[i] = cost;\n                        next_parent[i] = (int)j;\n                    }\n                }\n            }\n            dp = next_dp;\n            parent_path[k] = next_parent;\n        }\n\n        // Find min cost for the last character\n        long long min_cost = 1e18;\n        int last_pos_idx = -1;\n        int last_char = current_s[L-1] - 'A';\n        for (size_t i = 0; i < pos[last_char].size(); ++i) {\n            if (dp[i] < min_cost) {\n                min_cost = dp[i];\n                last_pos_idx = (int)i;\n            }\n        }\n\n        // Keep track of the best result\n        if (min_cost < best_total_cost) {\n            best_total_cost = min_cost;\n            \n            // Reconstruct path\n            best_path.resize(L);\n            int curr_pos_idx = last_pos_idx;\n            for (int k = L - 1; k >= 0; --k) {\n                int char_idx = current_s[k] - 'A';\n                best_path[k] = pos[char_idx][curr_pos_idx];\n                if (k > 0) {\n                    curr_pos_idx = parent_path[k][curr_pos_idx];\n                }\n            }\n        }\n    }\n\n    // Output the optimal path\n    for (const auto& p : best_path) {\n        cout << p.r << \" \" << p.c << \"\\n\";\n    }\n\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <iomanip>\n\nusing namespace std;\n\n// Structure to represent a point on the island\nstruct Point {\n    int r, c;\n};\n\n// Structure to represent an oil field\nstruct Field {\n    vector<Point> shape;\n    int max_dr, max_dc;\n};\n\nint N, M;\ndouble eps;\nvector<Field> fields;\n\n// Global vector for precomputed is_oil: [k][r][c][i][j]\n// Using uint8_t to save memory\nvector<uint8_t> is_oil; \n\ninline bool get_is_oil(int k, int r, int c, int i, int j) {\n    if (i < r || j < c || i >= r + fields[k].max_dr + 1 || j >= c + fields[k].max_dc + 1) return false;\n    return is_oil[((((k * N + r) * N + c) * N + i) * N + j)];\n}\n\nstruct Config {\n    vector<Point> offsets;\n    double log_weight;\n};\n\nvector<Config> particles;\nconst int NUM_PARTICLES = 250;\n\nvoid init_particles() {\n    particles.clear();\n    mt19937 rng(12345);\n    for (int i = 0; i < NUM_PARTICLES; ++i) {\n        Config c;\n        for (int k = 0; k < M; ++k) {\n            uniform_int_distribution<int> dist_r(0, N - 1 - fields[k].max_dr);\n            uniform_int_distribution<int> dist_c(0, N - 1 - fields[k].max_dc);\n            c.offsets.push_back({dist_r(rng), dist_c(rng)});\n        }\n        c.log_weight = -log((double)NUM_PARTICLES);\n        particles.push_back(c);\n    }\n}\n\nint compute_v_S(const Config& c, const vector<Point>& S) {\n    int v_S = 0;\n    for (const auto& p : S) {\n        for (int k = 0; k < M; ++k) {\n            if (get_is_oil(k, c.offsets[k].r, c.offsets[k].c, p.r, p.c)) {\n                v_S++;\n            }\n        }\n    }\n    return v_S;\n}\n\nvoid update_weights(const vector<Point>& S, double obs) {\n    int k = S.size();\n    double sigma2 = (double)k * eps * (1.0 - eps);\n    double max_log_w = -1e18;\n\n    for (auto& c : particles) {\n        int v_S = compute_v_S(c, S);\n        double mu = (double)(k - v_S) * eps + (double)v_S * (1.0 - eps);\n        double log_likelihood = -0.5 * pow(obs - mu, 2) / sigma2;\n        c.log_weight += log_likelihood;\n        if (c.log_weight > max_log_w) max_log_w = c.log_weight;\n    }\n\n    double sum_w = 0;\n    for (auto& c : particles) {\n        c.log_weight -= max_log_w;\n        sum_w += exp(c.log_weight);\n    }\n    for (auto& c : particles) {\n        c.log_weight = log(exp(c.log_weight) / sum_w);\n    }\n}\n\nvoid resample() {\n    double sum_sq_w = 0;\n    for (auto& c : particles) sum_sq_w += exp(2.0 * c.log_weight);\n    if (1.0 / sum_sq_w < NUM_PARTICLES / 3.0) {\n        vector<Config> new_particles;\n        vector<double> weights;\n        for (auto& c : particles) weights.push_back(exp(c.log_weight));\n        discrete_distribution<int> dist(weights.begin(), weights.end());\n        mt19937 rng(45678);\n        for (int i = 0; i < NUM_PARTICLES; ++i) {\n            new_particles.push_back(particles[dist(rng)]);\n            new_particles.back().log_weight = -log((double)NUM_PARTICLES);\n        }\n        particles = new_particles;\n    }\n}\n\nvoid rejuvenate() {\n    double min_w = 1e18;\n    for (auto& c : particles) min_w = min(min_w, c.log_weight);\n    \n    mt19937 rng(999);\n    for (auto& c : particles) {\n        if (c.log_weight < min_w + 1e-4) {\n            for (int k = 0; k < M; ++k) {\n                c.offsets[k].r = uniform_int_distribution<int>(0, N - 1 - fields[k].max_dr)(rng);\n                c.offsets[k].c = uniform_int_distribution<int>(0, N - 1 - fields[k].max_dc)(rng);\n            }\n            c.log_weight = -log((double)NUM_PARTICLES);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    cin >> N >> M >> eps;\n    fields.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int d; cin >> d;\n        int max_dr = 0, max_dc = 0;\n        for (int i = 0; i < d; ++i) {\n            int r, c; cin >> r >> c;\n            fields[k].shape.push_back({r, c});\n            max_dr = max(max_dr, r);\n            max_dc = max(max_dc, c);\n        }\n        fields[k].max_dr = max_dr;\n        fields[k].max_dc = max_dc;\n    }\n\n    is_oil.assign(M * N * N * N * N, 0);\n    for (int k = 0; k < M; ++k) {\n        for (int r = 0; r <= N - 1 - fields[k].max_dr; ++r) {\n            for (int c = 0; c <= N - 1 - fields[k].max_dc; ++c) {\n                for (const auto& p : fields[k].shape) {\n                    is_oil[((((k * N + r) * N + c) * N + (r + p.r)) * N + (c + p.c))] = 1;\n                }\n            }\n        }\n    }\n\n    init_particles();\n    mt19937 rng(42);\n    int query_count = 0;\n    while (query_count < 2 * N * N) {\n        vector<vector<Point>> candidates;\n        for (int i = 0; i < 50; ++i) {\n            int k = uniform_int_distribution<int>(1, N * N / 2)(rng);\n            vector<Point> S;\n            for (int j = 0; j < k; ++j) S.push_back({uniform_int_distribution<int>(0, N - 1)(rng), uniform_int_distribution<int>(0, N - 1)(rng)});\n            candidates.push_back(S);\n        }\n\n        int best_idx = -1;\n        double best_var = -1.0;\n        for (int i = 0; i < candidates.size(); ++i) {\n            double mean = 0;\n            vector<int> v_Ss;\n            for (auto& c : particles) {\n                int v_S = compute_v_S(c, candidates[i]);\n                v_Ss.push_back(v_S);\n                mean += exp(c.log_weight) * v_S;\n            }\n            double var = 0;\n            for (int j = 0; j < particles.size(); ++j) var += exp(particles[j].log_weight) * pow(v_Ss[j] - mean, 2);\n            double score = var * sqrt((double)candidates[i].size());\n            if (score > best_var) { best_var = score; best_idx = i; }\n        }\n\n        cout << \"q \" << candidates[best_idx].size();\n        for (auto& p : candidates[best_idx]) cout << \" \" << p.r << \" \" << p.c;\n        cout << endl;\n        double obs; cin >> obs;\n        update_weights(candidates[best_idx], obs);\n        resample();\n        rejuvenate();\n        query_count++;\n\n        // Guess\n        vector<Point> guess_set;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                double prob = 0;\n                for (auto& c : particles) {\n                    bool oil = false;\n                    for (int k = 0; k < M; ++k) if (get_is_oil(k, c.offsets[k].r, c.offsets[k].c, i, j)) { oil = true; break; }\n                    if (oil) prob += exp(c.log_weight);\n                }\n                if (prob > 0.5) guess_set.push_back({i, j});\n            }\n        }\n\n        cout << \"a \" << guess_set.size();\n        for (auto& p : guess_set) cout << \" \" << p.r << \" \" << p.c;\n        cout << endl;\n        int resp; cin >> resp;\n        if (resp == 1) return 0;\n    }\n    return 0;\n}","ahc031":"/*\n * Problem: Minimize total cost of rental area deficiency and partition movement.\n * Approach: Partition the W x W grid into N horizontal strips.\n * Use coordinate descent to optimize the vertical positions of the N-1 internal partition lines.\n */\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n    // Optimize I/O operations\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\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    // y[d][k] is the vertical position of the partition between reservation k-1 and k.\n    // y[d][0] = 0, y[d][N] = W.\n    // Initialization: evenly spaced partitions.\n    vector<vector<int>> y(D, vector<int>(N + 1));\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k <= N; ++k) {\n            y[d][k] = k * W / N;\n        }\n    }\n\n    // Function to calculate area cost for a given strip height\n    auto get_area_cost = [&](int d, int k, int h) {\n        long long area = (long long)W * h;\n        if (a[d][k] > area) return 100LL * (a[d][k] - area);\n        return 0LL;\n    };\n\n    // Coordinate descent to minimize the total cost\n    // 100 iterations is generally sufficient for convergence\n    for (int iter = 0; iter < 100; ++iter) {\n        bool changed = false;\n        for (int d = 0; d < D; ++d) {\n            for (int k = 1; k < N; ++k) {\n                int best_y = y[d][k];\n                long long min_cost = -1;\n\n                // The valid range for y[d][k] ensures each strip has at least height 1\n                int low = y[d][k - 1] + 1;\n                int high = y[d][k + 1] - 1;\n\n                // Find the best y[d][k] in the range [low, high]\n                for (int cur_y = low; cur_y <= high; ++cur_y) {\n                    long long cost = 0;\n                    // Area cost for reservation k-1 and k\n                    cost += get_area_cost(d, k - 1, cur_y - y[d][k - 1]);\n                    cost += get_area_cost(d, k, y[d][k + 1] - cur_y);\n                    \n                    // Movement cost:\n                    // Only for d > 0, compare with day d-1\n                    if (d > 0) cost += (long long)W * abs(cur_y - y[d - 1][k]);\n                    // Only for d < D-1, compare with day d+1\n                    if (d < D - 1) cost += (long long)W * abs(y[d + 1][k] - cur_y);\n                    \n                    if (min_cost == -1 || cost < min_cost) {\n                        min_cost = cost;\n                        best_y = cur_y;\n                    }\n                }\n                \n                if (y[d][k] != best_y) {\n                    y[d][k] = best_y;\n                    changed = true;\n                }\n            }\n        }\n        if (!changed) break;\n    }\n\n    // Output the resulting rectangles: top-left (i0, j0) and bottom-right (i1, j1)\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            // Rectangle is from row y[d][k] to y[d][k+1] and col 0 to W\n            cout << y[d][k] << \" \" << 0 << \" \" << y[d][k + 1] << \" \" << W << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\n// Standard library includes and types\nconst int MOD = 998244353;\n\nstruct Op {\n    int m, p, q;\n};\n\nint N, M, K;\nvector<vector<int>> A;\nvector<vector<vector<int>>> S;\n\n// Function to calculate the total score: sum(b_{i,j} % MOD)\nlong long calc_score(const vector<vector<long long>>& board) {\n    long long score = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            score += (board[i][j] % MOD);\n        }\n    }\n    return score;\n}\n\n// Function to apply a stamp\nvoid apply(vector<vector<long long>>& board, const Op& op) {\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            board[op.p + i][op.q + j] += S[op.m][i][j];\n        }\n    }\n}\n\n// Function to undo a stamp\nvoid undo(vector<vector<long long>>& board, const Op& op) {\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            board[op.p + i][op.q + j] -= S[op.m][i][j];\n        }\n    }\n}\n\nint main() {\n    // Faster I/O\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read Input\n    cin >> N >> M >> K;\n    A.resize(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    S.resize(M, vector<vector<int>>(3, vector<int>(3)));\n    for (int m = 0; m < M; ++m)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> S[m][i][j];\n\n    // Initial board\n    vector<vector<long long>> board(N, vector<long long>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            board[i][j] = A[i][j];\n\n    // Initial Greedy Approach\n    vector<Op> ops;\n    for (int k = 0; k < K; ++k) {\n        long long best_gain = -1;\n        Op best_op = {-1, -1, -1};\n\n        // Try every possible stamp and position to find the best gain\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    long long gain = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            gain -= (board[p + i][q + j] % MOD);\n                            gain += ((board[p + i][q + j] + S[m][i][j]) % MOD);\n                        }\n                    }\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        best_op = {m, p, q};\n                    }\n                }\n            }\n        }\n        \n        // If we found a beneficial operation, apply it\n        if (best_gain > 0) {\n            apply(board, best_op);\n            ops.push_back(best_op);\n        } else {\n            break;\n        }\n    }\n\n    // Local Search (Simulated Annealing)\n    mt19937 rng(1337);\n    auto start_time = chrono::steady_clock::now();\n    double time_limit = 1.8; // Seconds\n    long long current_score = calc_score(board);\n    \n    double start_temp = 1e6;\n    double end_temp = 100.0;\n\n    while (true) {\n        auto current_time = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(current_time - start_time).count();\n        if (elapsed > time_limit) break;\n\n        double progress = elapsed / time_limit;\n        double temp = start_temp * pow(end_temp / start_temp, progress);\n\n        int move_type = rng() % 3; // 0: modify, 1: add, 2: remove\n        \n        // Ensure valid move_type\n        if (ops.empty()) move_type = 1; // If empty, must add\n        if (ops.size() == K && move_type == 1) move_type = 0; // If full, can't add\n\n        if (move_type == 0 && !ops.empty()) { // Modify\n            int idx = rng() % ops.size();\n            Op old_op = ops[idx];\n            Op new_op = { (int)(rng() % M), (int)(rng() % (N - 2)), (int)(rng() % (N - 2)) };\n            \n            undo(board, old_op);\n            apply(board, new_op);\n            long long new_score = calc_score(board);\n            \n            double delta = (double)new_score - current_score;\n            if (delta > 0 || exp(delta / temp) > (double)rng() / rng.max()) {\n                current_score = new_score;\n                ops[idx] = new_op;\n            } else {\n                undo(board, new_op);\n                apply(board, old_op);\n            }\n        } else if (move_type == 1 && ops.size() < K) { // Add\n            Op new_op = { (int)(rng() % M), (int)(rng() % (N - 2)), (int)(rng() % (N - 2)) };\n            apply(board, new_op);\n            long long new_score = calc_score(board);\n            \n            double delta = (double)new_score - current_score;\n            if (delta > 0 || exp(delta / temp) > (double)rng() / rng.max()) {\n                current_score = new_score;\n                ops.push_back(new_op);\n            } else {\n                undo(board, new_op);\n            }\n        } else if (move_type == 2 && !ops.empty()) { // Remove\n            int idx = rng() % ops.size();\n            Op old_op = ops[idx];\n            \n            undo(board, old_op);\n            long long new_score = calc_score(board);\n            \n            double delta = (double)new_score - current_score;\n            if (delta > 0 || exp(delta / temp) > (double)rng() / rng.max()) {\n                current_score = new_score;\n                ops.erase(ops.begin() + idx);\n            } else {\n                apply(board, old_op);\n            }\n        }\n    }\n\n    // Output\n    cout << ops.size() << endl;\n    for (const auto& op : ops) {\n        cout << op.m << \" \" << op.p << \" \" << op.q << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cstring>\n\nusing namespace std;\n\nconst int N = 5;\n\nstruct Pos {\n    int r, c;\n    bool operator==(const Pos& other) const { return r == other.r && c == other.c; }\n    bool operator!=(const Pos& other) const { return !(*this == other); }\n};\n\nstruct Crane {\n    int id;\n    Pos pos;\n    int holding; \n    bool is_large;\n    string moves;\n};\n\nint grid[N][N];\nCrane cranes[N];\nint incoming[N][N];\nint incoming_ptr[N];\nint expected_container[N];\n\n// BFS to find the next step\nPos get_next_move(int crane_idx, Pos target) {\n    if (cranes[crane_idx].pos == target) return target;\n    \n    queue<pair<Pos, Pos>> q;\n    q.push({cranes[crane_idx].pos, {-1, -1}});\n    \n    bool visited[N][N];\n    memset(visited, false, sizeof(visited));\n    visited[cranes[crane_idx].pos.r][cranes[crane_idx].pos.c] = true;\n    \n    // Parent array to reconstruct the path\n    Pos parent[N][N];\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    \n    while (!q.empty()) {\n        Pos curr = q.front().first;\n        Pos p = q.front().second;\n        q.pop();\n        \n        if (curr == target) {\n            // Reconstruct the first step\n            Pos prev = curr;\n            while (p != cranes[crane_idx].pos) {\n                prev = p;\n                p = parent[p.r][p.c];\n            }\n            return prev;\n        }\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n            \n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && !visited[nr][nc]) {\n                // Check if another crane is there\n                bool crane_blocked = false;\n                for (int j = 0; j < N; ++j) {\n                    if (j != crane_idx && cranes[j].pos.r == nr && cranes[j].pos.c == nc) {\n                        crane_blocked = true;\n                        break;\n                    }\n                }\n                if (crane_blocked) continue;\n                \n                // Small crane with container cannot move to a square with a container\n                if (!cranes[crane_idx].is_large && cranes[crane_idx].holding != -1 && grid[nr][nc] != -1) continue;\n                \n                visited[nr][nc] = true;\n                parent[nr][nc] = curr;\n                q.push({{nr, nc}, curr});\n            }\n        }\n    }\n    return cranes[crane_idx].pos; // Cannot move\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n_in;\n    cin >> n_in;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) cin >> incoming[i][j];\n        incoming_ptr[i] = 0;\n        expected_container[i] = N * i;\n    }\n\n    memset(grid, -1, sizeof(grid));\n    for (int i = 0; i < N; ++i) {\n        cranes[i] = {i, {i, 0}, -1, (i == 0), \"\"};\n    }\n\n    for (int turn = 0; turn < 10000; ++turn) {\n        // 1. Receive\n        for (int i = 0; i < N; ++i) {\n            if (incoming_ptr[i] < N && grid[i][0] == -1) {\n                bool crane_at_gate = false;\n                for(int k=0; k<N; ++k) if(cranes[k].pos.r == i && cranes[k].pos.c == 0) crane_at_gate = true;\n                if (!crane_at_gate) {\n                    grid[i][0] = incoming[i][incoming_ptr[i]++];\n                }\n            }\n        }\n\n        // 2. Actions\n        vector<char> turn_actions(N, '.');\n        for (int i = 0; i < N; ++i) {\n            Crane &c = cranes[i];\n            if (c.holding != -1) {\n                // Moving to target\n                int target_row = c.holding / N;\n                Pos target = {target_row, N - 1};\n                if (c.pos == target) {\n                    if (c.holding == expected_container[target_row]) turn_actions[i] = 'Q';\n                    else {\n                        // Move to storage\n                        Pos storage = {target_row, 0}; // Simple storage\n                        Pos next = get_next_move(i, storage);\n                        if (next != c.pos) turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                        else turn_actions[i] = '.';\n                    }\n                } else {\n                    Pos next = get_next_move(i, target);\n                    if (next != c.pos) turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                    else turn_actions[i] = '.';\n                }\n            } else {\n                // Find a container to pick\n                Pos best_container = {-1, -1};\n                for (int r = 0; r < N; ++r) {\n                    for (int col = 0; col < N; ++col) {\n                        if (grid[r][col] != -1) {\n                            best_container = {r, col};\n                            break;\n                        }\n                    }\n                    if (best_container.r != -1) break;\n                }\n                if (best_container.r != -1) {\n                    if (c.pos == best_container) turn_actions[i] = 'P';\n                    else {\n                        Pos next = get_next_move(i, best_container);\n                        if (next != c.pos) turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                        else turn_actions[i] = '.';\n                    }\n                } else turn_actions[i] = '.';\n            }\n        }\n\n        // Apply actions\n        for (int i = 0; i < N; ++i) {\n            char a = turn_actions[i];\n            cranes[i].moves += a;\n            if (a == 'P') {\n                cranes[i].holding = grid[cranes[i].pos.r][cranes[i].pos.c];\n                grid[cranes[i].pos.r][cranes[i].pos.c] = -1;\n            } else if (a == 'Q') {\n                grid[cranes[i].pos.r][cranes[i].pos.c] = cranes[i].holding;\n                cranes[i].holding = -1;\n            } else if (a != '.' && a != 'B') {\n                if (a == 'U') cranes[i].pos.r--;\n                else if (a == 'D') cranes[i].pos.r++;\n                else if (a == 'L') cranes[i].pos.c--;\n                else if (a == 'R') cranes[i].pos.c++;\n            }\n        }\n\n        // 3. Dispatch\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][N-1] == expected_container[i]) {\n                grid[i][N-1] = -1;\n                expected_container[i]++;\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) cout << cranes[i].moves << \"\\n\";\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 20;\nint H[N][N];\nint curr_r = 0, curr_c = 0;\nint current_load = 0;\n\nstruct Pos {\n    int r, c;\n};\n\n// Function to find the nearest cell with a certain property\n// want_surplus: true if we look for surplus (H > 0), false if deficit (H < 0)\nPos find_nearest(bool want_surplus) {\n    queue<pair<int, int>> q;\n    q.push({curr_r, curr_c});\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    \n    // Check if current cell satisfies the condition\n    if (want_surplus) {\n        if (H[curr_r][curr_c] > 0) return {curr_r, curr_c};\n    } else {\n        if (H[curr_r][curr_c] < 0) return {curr_r, curr_c};\n    }\n    visited[curr_r][curr_c] = true;\n\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n\n        int dr[] = {-1, 1, 0, 0};\n        int dc[] = {0, 0, -1, 1};\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i], nc = c + dc[i];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && !visited[nr][nc]) {\n                if (want_surplus) {\n                    if (H[nr][nc] > 0) return {nr, nc};\n                } else {\n                    if (H[nr][nc] < 0) return {nr, nc};\n                }\n                visited[nr][nc] = true;\n                q.push({nr, nc});\n            }\n        }\n    }\n    return {-1, -1};\n}\n\n// Get shortest path from curr to target\nvector<Pos> get_path(Pos target) {\n    queue<pair<int, int>> q;\n    q.push({curr_r, curr_c});\n    vector<vector<Pos>> parent(N, vector<Pos>(N, {-1, -1}));\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    visited[curr_r][curr_c] = true;\n\n    bool found = false;\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n        if (r == target.r && c == target.c) {\n            found = true;\n            break;\n        }\n\n        int dr[] = {-1, 1, 0, 0};\n        int dc[] = {0, 0, -1, 1};\n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i], nc = c + dc[i];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && !visited[nr][nc]) {\n                visited[nr][nc] = true;\n                parent[nr][nc] = {r, c};\n                q.push({nr, nc});\n            }\n        }\n    }\n\n    vector<Pos> path;\n    if (found) {\n        Pos p = target;\n        while (p.r != curr_r || p.c != curr_c) {\n            path.push_back(p);\n            p = parent[p.r][p.c];\n        }\n        reverse(path.begin(), path.end());\n    }\n    return path;\n}\n\nvoid move_to(int nr, int nc) {\n    if (nr == curr_r - 1) cout << \"U\" << endl;\n    else if (nr == curr_r + 1) cout << \"D\" << endl;\n    else if (nc == curr_c - 1) cout << \"L\" << endl;\n    else if (nc == curr_c + 1) cout << \"R\" << endl;\n    curr_r = nr;\n    curr_c = nc;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n;\n    cin >> n;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> H[i][j];\n        }\n    }\n\n    while (true) {\n        Pos target;\n        // Search for nearest relevant cell\n        if (current_load == 0) {\n            target = find_nearest(true);\n        } else {\n            target = find_nearest(false);\n        }\n\n        if (target.r == -1) break; // All heights are 0\n\n        vector<Pos> path = get_path(target);\n        for (Pos p : path) {\n            move_to(p.r, p.c);\n            // Process the cell we just moved to\n            if (H[p.r][p.c] > 0) {\n                int d = H[p.r][p.c];\n                cout << \"+\" << d << endl;\n                current_load += d;\n                H[p.r][p.c] = 0;\n            } else if (H[p.r][p.c] < 0 && current_load > 0) {\n                int d = min(current_load, -H[p.r][p.c]);\n                cout << \"-\" << d << endl;\n                current_load -= d;\n                H[p.r][p.c] += d;\n            }\n        }\n\n        // If path was empty, target is the current cell\n        if (path.empty()) {\n            if (H[target.r][target.c] > 0) {\n                int d = H[target.r][target.c];\n                cout << \"+\" << d << endl;\n                current_load += d;\n                H[target.r][target.c] = 0;\n            } else if (H[target.r][target.c] < 0 && current_load > 0) {\n                int d = min(current_load, -H[target.r][target.c]);\n                cout << \"-\" << d << endl;\n                current_load -= d;\n                H[target.r][target.c] += d;\n            }\n        }\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Function to calculate the total potential score of the grid arrangement\n// The potential of a pair (A, B) is sum(max(A_l, B_l)) for all criteria l.\nlong long calculate_total_cost(const vector<vector<int>>& grid_seeds, const vector<vector<int>>& neighbors, int M) {\n    long long total_cost = 0;\n    int n = grid_seeds.size();\n    for (int i = 0; i < n; ++i) {\n        for (int neighbor_idx : neighbors[i]) {\n            if (i < neighbor_idx) { // Only count each edge once\n                const vector<int>& s1 = grid_seeds[i];\n                const vector<int>& s2 = grid_seeds[neighbor_idx];\n                for (int l = 0; l < M; ++l) {\n                    total_cost += max(s1[l], s2[l]);\n                }\n            }\n        }\n    }\n    return total_cost;\n}\n\nint main() {\n    // Optimize I/O operations\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> seeds(seed_count, vector<int>(M));\n\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i][j];\n        }\n    }\n\n    // Precompute neighbors for each grid position to speed up cost calculation\n    int grid_size = N * N;\n    vector<vector<int>> neighbors(grid_size);\n    for (int i = 0; i < grid_size; ++i) {\n        int r = i / N;\n        int c = i % N;\n        if (r > 0) neighbors[i].push_back((r - 1) * N + c);\n        if (r < N - 1) neighbors[i].push_back((r + 1) * N + c);\n        if (c > 0) neighbors[i].push_back(r * N + c - 1);\n        if (c < N - 1) neighbors[i].push_back(r * N + c + 1);\n    }\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    for (int t = 0; t < T; t++) {\n        // 1. Selection: Top 30 + 6 random seeds\n        vector<pair<long long, int>> seed_scores(seed_count);\n        for (int i = 0; i < seed_count; ++i) {\n            long long val = 0;\n            for (int l = 0; l < M; ++l) val += seeds[i][l];\n            seed_scores[i] = {val, i};\n        }\n        sort(seed_scores.rbegin(), seed_scores.rend());\n\n        vector<int> selected_seed_indices;\n        for (int i = 0; i < 30; ++i) selected_seed_indices.push_back(seed_scores[i].second);\n        \n        vector<int> remaining_seeds;\n        for (int i = 30; i < seed_count; ++i) remaining_seeds.push_back(seed_scores[i].second);\n        shuffle(remaining_seeds.begin(), remaining_seeds.end(), rng);\n        for (int i = 0; i < 6; ++i) selected_seed_indices.push_back(remaining_seeds[i]);\n\n        // 2. Hill climbing to optimize arrangement\n        vector<int> current_grid_seed_indices(grid_size);\n        iota(current_grid_seed_indices.begin(), current_grid_seed_indices.end(), 0);\n        shuffle(current_grid_seed_indices.begin(), current_grid_seed_indices.end(), rng);\n\n        vector<vector<int>> current_grid_seeds(grid_size);\n        for(int i = 0; i < grid_size; ++i) current_grid_seeds[i] = seeds[selected_seed_indices[current_grid_seed_indices[i]]];\n\n        long long current_cost = calculate_total_cost(current_grid_seeds, neighbors, M);\n        \n        // Hill climbing optimization\n        for (int iter = 0; iter < 50000; ++iter) {\n            int p1 = uniform_int_distribution<int>(0, grid_size - 1)(rng);\n            int p2 = uniform_int_distribution<int>(0, grid_size - 1)(rng);\n            if (p1 == p2) continue;\n\n            swap(current_grid_seeds[p1], current_grid_seeds[p2]);\n            swap(current_grid_seed_indices[p1], current_grid_seed_indices[p2]);\n            \n            long long new_cost = calculate_total_cost(current_grid_seeds, neighbors, M);\n            \n            if (new_cost >= current_cost) {\n                current_cost = new_cost;\n            } else {\n                // Revert swap\n                swap(current_grid_seeds[p1], current_grid_seeds[p2]);\n                swap(current_grid_seed_indices[p1], current_grid_seed_indices[p2]);\n            }\n        }\n\n        // 3. Output the arrangement\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << selected_seed_indices[current_grid_seed_indices[i * N + j]];\n                if (j < N - 1) cout << \" \";\n            }\n            cout << \"\\n\";\n        }\n        cout.flush();\n\n        // 4. Read new seeds\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> seeds[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Coordinate structure\nstruct Point {\n    int x, y;\n};\n\n// Robot vertex structure\nstruct Vertex {\n    int id;\n    int parent;\n    int L;\n    int dir; // 0=R, 1=D, 2=L, 3=U\n    bool holding;\n};\n\nint N, M, V_avail;\nvector<vector<int>> s, t; // s=takoyaki (1 if present), t=target (1 if target)\nint rx, ry;\nvector<Vertex> robot;\n\n// Directions: R, D, L, U (0, 1, 2, 3)\nint DX[] = {0, 1, 0, -1};\nint DY[] = {1, 0, -1, 0};\nchar DIRS[] = {'R', 'D', 'L', 'U'};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    cin >> N >> M >> V_avail;\n    s.resize(N, vector<int>(N));\n    t.resize(N, vector<int>(N));\n    \n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) s[i][j] = row[j] - '0';\n    }\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) t[i][j] = row[j] - '0';\n    }\n\n    // Design robot: star graph\n    // Root is 0, children 1 to V-1\n    int V_prime = V_avail;\n    robot.resize(V_prime);\n    robot[0] = {0, -1, 0, 0, false};\n    for (int i = 1; i < V_prime; ++i) {\n        // Distribute edge lengths to cover different radii\n        robot[i] = {i, 0, (i - 1) % (N - 1) + 1, 0, false};\n    }\n\n    cout << V_prime << endl;\n    for (int i = 1; i < V_prime; ++i) {\n        cout << robot[i].parent << \" \" << robot[i].L << endl;\n    }\n    rx = N / 2;\n    ry = N / 2;\n    cout << rx << \" \" << ry << endl;\n\n    // Simulation\n    for (int turn = 0; turn < 100000; ++turn) {\n        // Check if finished\n        int current_m = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (s[i][j] && t[i][j]) current_m++;\n            }\n        }\n        if (current_m == M) break;\n\n        // 1. Identify targets for each fingertip\n        vector<Point> fingertip_target(V_prime, {-1, -1});\n        for (int i = 1; i < V_prime; ++i) {\n            int min_dist = 1000000;\n            if (robot[i].holding) {\n                // Find nearest empty target square\n                for (int r = 0; r < N; ++r) {\n                    for (int c = 0; c < N; ++c) {\n                        if (t[r][c] && !s[r][c]) {\n                            int d = abs(r - rx) + abs(c - ry); \n                            if (d < min_dist) {\n                                min_dist = d;\n                                fingertip_target[i] = {r, c};\n                            }\n                        }\n                    }\n                }\n            } else {\n                // Find nearest takoyaki (that is not on target)\n                for (int r = 0; r < N; ++r) {\n                    for (int c = 0; c < N; ++c) {\n                        if (s[r][c] && !t[r][c]) {\n                            int d = abs(r - rx) + abs(c - ry);\n                            if (d < min_dist) {\n                                min_dist = d;\n                                fingertip_target[i] = {r, c};\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        // 2. Choose best root move and rotations\n        int best_move = -1; // 0=U, 1=D, 2=L, 3=R, 4=.\n        vector<int> best_rots(V_prime, 0); // 0=., 1=L, 2=R\n        long long min_total_dist = 1e18;\n\n        int move_dx[] = {-1, 1, 0, 0, 0};\n        int move_dy[] = {0, 0, -1, 1, 0};\n        char move_char[] = {'U', 'D', 'L', 'R', '.'};\n\n        for (int m = 0; m < 5; ++m) {\n            int nrx = rx + move_dx[m];\n            int nry = ry + move_dy[m];\n            \n            // Root must be within grid\n            if (nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n\n            long long current_total_dist = 0;\n            vector<int> current_rots(V_prime, 0);\n\n            for (int i = 1; i < V_prime; ++i) {\n                if (fingertip_target[i].x == -1) continue;\n\n                int best_r = -1;\n                int best_d = 1000000;\n                \n                // Try 3 rotations for each subtree\n                for (int r = 0; r < 3; ++r) {\n                    int ndir = robot[i].dir;\n                    if (r == 1) ndir = (ndir + 3) % 4; // CCW\n                    else if (r == 2) ndir = (ndir + 1) % 4; // CW\n                    \n                    int fx = nrx + DX[ndir] * robot[i].L;\n                    int fy = nry + DY[ndir] * robot[i].L;\n                    int d = abs(fx - fingertip_target[i].x) + abs(fy - fingertip_target[i].y);\n                    if (d < best_d) {\n                        best_d = d;\n                        best_r = r;\n                    }\n                }\n                current_total_dist += best_d;\n                current_rots[i] = best_r;\n            }\n            if (current_total_dist < min_total_dist) {\n                min_total_dist = current_total_dist;\n                best_move = m;\n                best_rots = current_rots;\n            }\n        }\n\n        // Apply best move\n        if (best_move == -1) best_move = 4; // Stay\n        rx += move_dx[best_move];\n        ry += move_dy[best_move];\n        \n        string S = \"\";\n        S += move_char[best_move];\n        for (int i = 1; i < V_prime; ++i) {\n            int r = best_rots[i];\n            if (r == 0) S += '.';\n            else if (r == 1) { S += 'L'; robot[i].dir = (robot[i].dir + 3) % 4; }\n            else { S += 'R'; robot[i].dir = (robot[i].dir + 1) % 4; }\n        }\n\n        // 3. Actions\n        string actions = \"\";\n        actions += '.'; // root does nothing\n        for (int i = 1; i < V_prime; ++i) {\n            int fx = rx + DX[robot[i].dir] * robot[i].L;\n            int fy = ry + DY[robot[i].dir] * robot[i].L;\n            \n            bool action = false;\n            if (fx >= 0 && fx < N && fy >= 0 && fy < N) {\n                if (robot[i].holding) {\n                    // Try to drop\n                    if (t[fx][fy] == 1 && s[fx][fy] == 0) {\n                        robot[i].holding = false;\n                        s[fx][fy] = 1;\n                        action = true;\n                    }\n                } else {\n                    // Try to pick\n                    if (s[fx][fy] == 1 && t[fx][fy] == 0) {\n                        robot[i].holding = true;\n                        s[fx][fy] = 0;\n                        action = true;\n                    }\n                }\n            }\n            if (action) actions += 'P';\n            else actions += '.';\n        }\n        cout << S << actions << endl;\n    }\n\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\n// Configuration\nconst int GRID_SIZE = 256;\nconst int MAX_COORD = 100000;\nconst int NUM_ITERATIONS = 100000;\n\nstruct Point {\n    int x, y;\n};\n\n// Global Data\nint grid_score[GRID_SIZE][GRID_SIZE];\nbool is_inside[GRID_SIZE][GRID_SIZE];\nvector<Point> polygon;\nint current_score = 0;\n\n// Utility to convert coordinates to grid indices\nint get_grid_idx(int c) { return max(0, min(GRID_SIZE - 1, (c * GRID_SIZE) / (MAX_COORD + 1))); }\n\n// Ray-casting for point-in-polygon\nbool ray_casting(int cx, int cy, const vector<Point>& poly) {\n    int count = 0;\n    double x = (cx + 0.5) * (MAX_COORD + 1.0) / GRID_SIZE;\n    double y = (cy + 0.5) * (MAX_COORD + 1.0) / GRID_SIZE;\n    for (size_t i = 0; i < poly.size(); ++i) {\n        Point p1 = poly[i];\n        Point p2 = poly[(i + 1) % poly.size()];\n        if (p1.y == p2.y) continue; // Horizontal edge\n        int min_y = min(p1.y, p2.y);\n        int max_y = max(p1.y, p2.y);\n        if (y >= min_y && y < max_y) {\n            if (p1.x > x) count++;\n        }\n    }\n    return (count % 2 == 1);\n}\n\n// Intersection check for non-adjacent edges\nbool intersect_segments(Point a, Point b, Point c, Point d) {\n    long long min_x1 = min(a.x, b.x), max_x1 = max(a.x, b.x);\n    long long min_y1 = min(a.y, b.y), max_y1 = max(a.y, b.y);\n    long long min_x2 = min(c.x, d.x), max_x2 = max(c.x, d.x);\n    long long min_y2 = min(c.y, d.y), max_y2 = max(c.y, d.y);\n    \n    // Check collinear\n    if (min_y1 == max_y1 && min_y2 == max_y2) {\n        if (min_y1 != min_y2) return false;\n        return max(min_x1, min_x2) <= min(max_x1, max_x2);\n    }\n    if (min_x1 == max_x1 && min_x2 == max_x2) {\n        if (min_x1 != min_x2) return false;\n        return max(min_y1, min_y2) <= min(max_y1, max_y2);\n    }\n    // Cross\n    if (min_y1 == max_y1 && min_x2 == max_x2) return (min_x1 <= min_x2 && min_x2 <= max_x1 && min_y2 <= min_y1 && min_y1 <= max_y2);\n    if (min_x1 == max_x1 && min_y2 == max_y2) return (min_x2 <= min_x1 && min_x1 <= max_x2 && min_y1 <= min_y2 && min_y2 <= max_y1);\n    return false;\n}\n\nbool is_valid_polygon(const vector<Point>& poly) {\n    size_t m = poly.size();\n    for (size_t i = 0; i < m; ++i) {\n        Point p1 = poly[i], p2 = poly[(i + 1) % m];\n        for (size_t j = i + 1; j < m; ++j) {\n            if (j == i + 1 || (i == 0 && j == m - 1)) continue;\n            Point p3 = poly[j], p4 = poly[(j + 1) % m];\n            if (intersect_segments(p1, p2, p3, p4)) return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    int N; cin >> N;\n    vector<Point> mackerels(N), sardines(N);\n    for (int i = 0; i < N; ++i) { cin >> mackerels[i].x >> mackerels[i].y; grid_score[get_grid_idx(mackerels[i].x)][get_grid_idx(mackerels[i].y)]++; }\n    for (int i = 0; i < N; ++i) { cin >> sardines[i].x >> sardines[i].y; grid_score[get_grid_idx(sardines[i].x)][get_grid_idx(sardines[i].y)]--; }\n\n    polygon = {{40000, 40000}, {60000, 40000}, {60000, 60000}, {40000, 60000}};\n    for (int i = 0; i < GRID_SIZE; ++i)\n        for (int j = 0; j < GRID_SIZE; ++j)\n            is_inside[i][j] = ray_casting(i, j, polygon);\n\n    for (int i = 0; i < GRID_SIZE; ++i)\n        for (int j = 0; j < GRID_SIZE; ++j)\n            if (is_inside[i][j]) current_score += grid_score[i][j];\n\n    mt19937 rng(42);\n    double temp = 100.0, final_temp = 0.1;\n    for (int iter = 0; iter < NUM_ITERATIONS; ++iter) {\n        double t = (double)iter / NUM_ITERATIONS;\n        double current_temp = temp * pow(final_temp / temp, t);\n        \n        // Random move\n        int type = rng() % 3;\n        vector<Point> next_poly = polygon;\n        int delta_score = 0;\n        \n        if (type == 0 && polygon.size() < 1000) { // Add\n            int i = rng() % polygon.size();\n            Point p1 = polygon[i], p2 = polygon[(i + 1) % polygon.size()];\n            if (p1.x == p2.x) { // Vertical\n                int mid_y = (p1.y + p2.y) / 2;\n                next_poly.insert(next_poly.begin() + i + 1, {p1.x + 100, mid_y});\n                next_poly.insert(next_poly.begin() + i + 1, {p1.x + 100, mid_y}); // Simplistic\n            } else { // Horizontal\n                int mid_x = (p1.x + p2.x) / 2;\n                next_poly.insert(next_poly.begin() + i + 1, {mid_x, p1.y + 100});\n                next_poly.insert(next_poly.begin() + i + 1, {mid_x, p1.y + 100});\n            }\n        } else if (type == 1 && polygon.size() > 4) { // Remove\n            int i = rng() % polygon.size();\n            next_poly.erase(next_poly.begin() + i);\n            next_poly.erase(next_poly.begin() + i % next_poly.size());\n        } else { // Move edge\n            int i = rng() % polygon.size();\n            int move = (rng() % 2001) - 1000;\n            if (polygon[i].x == polygon[(i + 1) % polygon.size()].x) { // Vertical\n                next_poly[i].x += move; next_poly[(i + 1) % polygon.size()].x += move;\n            } else { // Horizontal\n                next_poly[i].y += move; next_poly[(i + 1) % polygon.size()].y += move;\n            }\n        }\n\n        if (is_valid_polygon(next_poly)) {\n            // Calculate delta_score by observing changes\n            int new_score = 0;\n            for (int i = 0; i < GRID_SIZE; ++i)\n                for (int j = 0; j < GRID_SIZE; ++j) {\n                    bool in = ray_casting(i, j, next_poly);\n                    if (in) new_score += grid_score[i][j];\n                }\n            \n            if (new_score > current_score || exp((new_score - current_score) / current_temp) > (double)rng() / rng.max()) {\n                current_score = new_score;\n                polygon = next_poly;\n            }\n        }\n    }\n\n    cout << polygon.size() << endl;\n    for (const auto& p : polygon) cout << p.x << \" \" << p.y << endl;\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <ctime>\n\nusing namespace std;\n\n// Configuration choice for each rectangle\nstruct Choice {\n    int r, d, b; // r: rotation (0 or 1), d: direction (0=U, 1=L), b: reference rectangle (-1 or 0..i-1)\n};\n\nint N, T;\ndouble sigma;\n// Since the judge uses true widths/heights, we don't strictly need to track them,\n// but we do need the count for the loop.\n\nint main() {\n    // Fast I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read initial data\n    if (!(cin >> N >> T >> sigma)) return 0;\n    // Consume the individual width/height estimates (not strictly needed for the strategy)\n    for (int i = 0; i < N; ++i) {\n        int w_tmp, h_tmp;\n        cin >> w_tmp >> h_tmp;\n    }\n\n    // Initialize the best sequence randomly\n    mt19937 rng(12345);\n    vector<Choice> best_seq(N);\n    for (int i = 0; i < N; ++i) {\n        best_seq[i].r = rng() % 2;\n        best_seq[i].d = rng() % 2;\n        best_seq[i].b = (i == 0) ? -1 : (int)(rng() % (i + 1)) - 1;\n    }\n\n    long long best_score = 4e18; // Initialize with a very large value\n\n    // Perform T turns of refinement\n    for (int t = 0; t < T; ++t) {\n        vector<Choice> candidate_seq = best_seq;\n        \n        // Mutate the candidate sequence: higher mutation rate early on, lower later\n        int num_mutations = max(1, (int)(N * (0.5 - 0.4 * (double)t / T)));\n        for (int m = 0; m < num_mutations; ++m) {\n            int i = rng() % N;\n            candidate_seq[i].r = rng() % 2;\n            candidate_seq[i].d = rng() % 2;\n            candidate_seq[i].b = (i == 0) ? -1 : (int)(rng() % (i + 1)) - 1;\n        }\n\n        // Output the configuration\n        cout << N << endl;\n        for (int i = 0; i < N; ++i) {\n            cout << i << \" \" << candidate_seq[i].r << \" \" \n                 << (candidate_seq[i].d == 0 ? 'U' : 'L') << \" \" \n                 << candidate_seq[i].b << endl;\n        }\n        cout.flush();\n\n        // Read the results from the judge\n        long long W_obs, H_obs;\n        if (!(cin >> W_obs >> H_obs)) break;\n        long long current_score = W_obs + H_obs;\n\n        // If the current result is better, update the best sequence\n        if (current_score < best_score) {\n            best_score = current_score;\n            best_seq = candidate_seq;\n        }\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <ctime>\n#include <chrono>\n\nusing namespace std;\n\n// Struct to represent an edge in the priority queue\nstruct Item {\n    int priority;\n    int u; // parent node\n    int v; // child node\n    bool operator<(const Item& other) const {\n        return priority < other.priority;\n    }\n};\n\nvoid solve() {\n    int N, M, H;\n    if (!(cin >> N >> M >> H)) return;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    // Skip coordinates as they are not used in the greedy logic\n    int x, y;\n    for (int i = 0; i < N; ++i) cin >> x >> y;\n\n    vector<int> best_p(N, -1);\n    long long best_score = -1;\n\n    // Time limit handling\n    clock_t start_time = clock();\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist(80, 120);\n    \n    // For root selection order\n    vector<int> nodes(N);\n    for(int i=0; i<N; ++i) nodes[i] = i;\n\n    int iter = 0;\n    while (true) {\n        // Periodically check time\n        if (iter % 10 == 0) {\n            if ((double)(clock() - start_time) / CLOCKS_PER_SEC > 1.8) break;\n        }\n        iter++;\n        \n        vector<int> p(N, -1);\n        vector<int> depth(N, 0);\n        vector<bool> visited(N, false);\n        \n        // Root selection heuristic to explore different configurations\n        if (iter % 3 == 0) {\n            sort(nodes.begin(), nodes.end(), [&](int a, int b){ return A[a] < A[b]; });\n        } else if (iter % 3 == 1) {\n            sort(nodes.begin(), nodes.end(), [&](int a, int b){ return A[a] > A[b]; });\n        } else {\n            shuffle(nodes.begin(), nodes.end(), rng);\n        }\n        \n        priority_queue<Item> pq;\n        int unvisited_count = N;\n        int order_idx = 0;\n        \n        // Build the forest\n        while (unvisited_count > 0) {\n            // Find next unvisited node to be a potential root\n            while (order_idx < N && visited[nodes[order_idx]]) {\n                order_idx++;\n            }\n            \n            if (pq.empty()) {\n                if (order_idx < N) {\n                    int r = nodes[order_idx];\n                    visited[r] = true;\n                    p[r] = -1;\n                    depth[r] = 0;\n                    unvisited_count--;\n                    \n                    // Add neighbors to PQ\n                    for (int neighbor : adj[r]) {\n                        if (!visited[neighbor]) {\n                            int gain = (depth[r] + 2) * A[neighbor];\n                            int randomized_gain = gain * dist(rng) / 100;\n                            pq.push({randomized_gain, r, neighbor});\n                        }\n                    }\n                }\n            } else {\n                Item top = pq.top();\n                pq.pop();\n                \n                if (visited[top.v]) continue;\n                // Constraint check: must not exceed depth H\n                if (depth[top.u] >= H) continue;\n                \n                visited[top.v] = true;\n                p[top.v] = top.u;\n                depth[top.v] = depth[top.u] + 1;\n                unvisited_count--;\n                \n                // Add neighbors to PQ\n                for (int neighbor : adj[top.v]) {\n                    if (!visited[neighbor]) {\n                        int gain = (depth[top.v] + 2) * A[neighbor];\n                        int randomized_gain = gain * dist(rng) / 100;\n                        pq.push({randomized_gain, top.v, neighbor});\n                    }\n                }\n            }\n        }\n        \n        // Calculate score\n        long long current_score = 0;\n        for (int j = 0; j < N; ++j) {\n            current_score += (long long)(depth[j] + 1) * A[j];\n        }\n        \n        // Keep the best solution\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_p = p;\n        }\n    }\n    \n    // Output final solution\n    for (int i = 0; i < N; ++i) {\n        cout << best_p[i] << (i == N - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    solve();\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n// Global variables for board size and state\nint N;\nvector<string> board;\n\n// Structure to store move information\nstruct Move {\n    char dir;\n    int p;\n};\n\n// Check if it's safe to remove an Oni at (r, c) by moving it Up\nbool is_removable_up(int r, int c) {\n    for (int i = 0; i < r; ++i) {\n        if (board[i][c] == 'o') return false;\n    }\n    return true;\n}\n\n// Check if it's safe to remove an Oni at (r, c) by moving it Down\nbool is_removable_down(int r, int c) {\n    for (int i = r + 1; i < N; ++i) {\n        if (board[i][c] == 'o') return false;\n    }\n    return true;\n}\n\n// Check if it's safe to remove an Oni at (r, c) by moving it Left\nbool is_removable_left(int r, int c) {\n    for (int j = 0; j < c; ++j) {\n        if (board[r][j] == 'o') return false;\n    }\n    return true;\n}\n\n// Check if it's safe to remove an Oni at (r, c) by moving it Right\nbool is_removable_right(int r, int c) {\n    for (int j = c + 1; j < N; ++j) {\n        if (board[r][j] == 'o') return false;\n    }\n    return true;\n}\n\n// Apply a single shift operation\nvoid apply_move(char dir, int p) {\n    if (dir == 'U') {\n        for (int i = 0; i < N - 1; ++i) board[i][p] = board[i+1][p];\n        board[N-1][p] = '.';\n    } else if (dir == 'D') {\n        for (int i = N - 1; i > 0; --i) board[i][p] = board[i-1][p];\n        board[0][p] = '.';\n    } else if (dir == 'L') {\n        for (int j = 0; j < N - 1; ++j) board[p][j] = board[p][j+1];\n        board[p][N-1] = '.';\n    } else if (dir == 'R') {\n        for (int j = N - 1; j > 0; --j) board[p][j] = board[p][j-1];\n        board[p][0] = '.';\n    }\n}\n\nint main() {\n    // Faster I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    cin >> N;\n    board.resize(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    vector<Move> ans;\n    // Main loop: greedily remove the easiest Oni\n    while (true) {\n        int best_r = -1, best_c = -1;\n        char best_dir = ' ';\n        int min_cost = 10000;\n        bool oni_exists = false;\n\n        // Find all removable Oni and pick the one with the smallest cost\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (board[r][c] == 'x') {\n                    oni_exists = true;\n                    // Check Up\n                    if (is_removable_up(r, c)) {\n                        if (r + 1 < min_cost) {\n                            min_cost = r + 1;\n                            best_r = r; best_c = c; best_dir = 'U';\n                        }\n                    }\n                    // Check Down\n                    if (is_removable_down(r, c)) {\n                        if (N - r < min_cost) {\n                            min_cost = N - r;\n                            best_r = r; best_c = c; best_dir = 'D';\n                        }\n                    }\n                    // Check Left\n                    if (is_removable_left(r, c)) {\n                        if (c + 1 < min_cost) {\n                            min_cost = c + 1;\n                            best_r = r; best_c = c; best_dir = 'L';\n                        }\n                    }\n                    // Check Right\n                    if (is_removable_right(r, c)) {\n                        if (N - c < min_cost) {\n                            min_cost = N - c;\n                            best_r = r; best_c = c; best_dir = 'R';\n                        }\n                    }\n                }\n            }\n        }\n\n        // If no Oni are left, terminate\n        if (!oni_exists) break;\n        // If no valid move is found, break (should not happen given problem guarantees)\n        if (best_dir == ' ') break;\n\n        // Perform one move for the chosen Oni\n        int p = (best_dir == 'U' || best_dir == 'D') ? best_c : best_r;\n        apply_move(best_dir, p);\n        ans.push_back({best_dir, p});\n    }\n\n    // Output all operations\n    for (const auto& m : ans) {\n        cout << m.dir << \" \" << m.p << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <numeric>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Global variables for problem constraints\nint N, L;\nvector<int> T;\n\n// Function to calculate the L1 error for a given configuration of transitions\nlong long calculate_error(const vector<int>& a, const vector<int>& b) {\n    // counts[i] stores the number of times employee i has cleaned so far\n    vector<int> counts(N, 0);\n    \n    // First week: employee 0 cleans\n    int current = 0;\n    counts[0] = 1;\n    \n    // Simulate from week 2 to L\n    // In each step, determine the next cleaner based on parity of counts[current]\n    for (int i = 1; i < L; ++i) {\n        // If counts[current] is odd, use a[current], else use b[current]\n        int next = (counts[current] % 2 != 0) ? a[current] : b[current];\n        current = next;\n        counts[current]++;\n    }\n    \n    long long error = 0;\n    for (int i = 0; i < N; ++i) {\n        error += abs(counts[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    // Optimize I/O operations\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    // Read N, L, and T_i values\n    if (!(cin >> N >> L)) return 0;\n    T.resize(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n    \n    // Random number generator\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    // Initial State: random assignment\n    vector<int> a(N), b(N);\n    for (int i = 0; i < N; ++i) {\n        a[i] = rng() % N;\n        b[i] = rng() % N;\n    }\n    \n    long long current_error = calculate_error(a, b);\n    \n    // Simulated Annealing parameters\n    auto start_time = chrono::steady_clock::now();\n    double temp = 10000.0;\n    double min_temp = 0.01;\n    \n    // SA iteration tracker\n    long long iter = 0;\n    \n    // Main SA loop\n    while (true) {\n        iter++;\n        // Check time limit every 1024 iterations\n        if ((iter & 1023) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1850) {\n                break;\n            }\n        }\n        \n        // Randomly select employee i and which pointer to change (a or b)\n        int i = rng() % N;\n        int old_val;\n        bool is_a = (rng() & 1);\n        \n        if (is_a) {\n            old_val = a[i];\n            a[i] = rng() % N;\n        } else {\n            old_val = b[i];\n            b[i] = rng() % N;\n        }\n        \n        long long new_error = calculate_error(a, b);\n        \n        // Metropolis acceptance criterion\n        if (new_error < current_error) {\n            current_error = new_error;\n        } else {\n            // Accept worse solutions with a probability that decreases over time\n            double diff = (double)(current_error - new_error);\n            if (exp(diff / temp) > (double)(rng() % 1000000) / 1000000.0) {\n                current_error = new_error;\n            } else {\n                // Revert change\n                if (is_a) a[i] = old_val;\n                else b[i] = old_val;\n            }\n        }\n        \n        // Cooling schedule\n        temp = max(min_temp, temp * 0.999999);\n    }\n    \n    // Output the optimized transitions\n    for (int i = 0; i < N; ++i) {\n        cout << a[i] << \" \" << b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <iomanip>\n\nusing namespace std;\n\n// Structure to represent a city\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double x, y; // Estimated coordinates\n};\n\n// Function to calculate distance squared\nlong long distSq(double x1, double y1, double x2, double y2) {\n    long long dx = (long long)round(x1 - x2);\n    long long dy = (long long)round(y1 - y2);\n    return dx * dx + dy * dy;\n}\n\n// Function to calculate distance rounded down\nlong long distInt(double x1, double y1, double x2, double y2) {\n    return (long long)floor(sqrt(distSq(x1, y1, x2, y2)));\n}\n\n// Function to perform a query\nvector<pair<int, int>> query(const vector<int>& c) {\n    if (c.size() < 2) return {};\n    cout << \"? \" << c.size();\n    for (int city_id : c) cout << \" \" << city_id;\n    cout << endl;\n    \n    vector<pair<int, int>> edges;\n    for (int i = 0; i < (int)c.size() - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        edges.push_back({u, v});\n    }\n    return edges;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    vector<City> cities(N);\n    for (int i = 0; i < N; ++i) {\n        cities[i].id = 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.0;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2.0;\n    }\n\n    // Sort cities for initial partitioning\n    vector<City> sorted_cities = cities;\n    sort(sorted_cities.begin(), sorted_cities.end(), [](const City& a, const City& b) {\n        if (a.x != b.x) return a.x < b.x;\n        return a.y < b.y;\n    });\n    \n    vector<vector<int>> groups(M);\n    int start_idx = 0;\n    for(int i=0; i<M; ++i) {\n        for(int j=0; j<G[i]; ++j) {\n            groups[i].push_back(sorted_cities[start_idx++].id);\n        }\n    }\n\n    // Querying\n    vector<vector<pair<int, int>>> query_edges(M);\n    int queries_left = Q;\n    \n    // For each group, determine number of queries\n    vector<int> q_per_group(M, 0);\n    int total_needed = N - M;\n    if (total_needed == 0) total_needed = 1;\n    \n    for(int i=0; i<M; ++i) {\n        if (G[i] > 1) {\n            q_per_group[i] = (int)((long long)Q * (G[i] - 1) / total_needed);\n            if (q_per_group[i] == 0 && queries_left > 0) q_per_group[i] = 1;\n        }\n    }\n    \n    // Perform queries\n    mt19937 rng(42);\n    for(int i=0; i<M; ++i) {\n        for(int q=0; q<q_per_group[i] && queries_left > 0; ++q) {\n            if (groups[i].size() < 2) continue;\n            \n            // Pick subset\n            int sz = min((int)groups[i].size(), L);\n            \n            // Heuristic: pick a random city from the group, then find sz-1 nearest neighbors in the group\n            int start_node_idx = rng() % groups[i].size();\n            int start_node = groups[i][start_node_idx];\n            \n            vector<pair<double, int>> neighbors;\n            for(int city_id : groups[i]) {\n                double d = (cities[city_id].x - cities[start_node].x) * (cities[city_id].x - cities[start_node].x) +\n                           (cities[city_id].y - cities[start_node].y) * (cities[city_id].y - cities[start_node].y);\n                neighbors.push_back({d, city_id});\n            }\n            sort(neighbors.begin(), neighbors.end());\n            \n            vector<int> subset;\n            for(int j=0; j<sz; ++j) {\n                subset.push_back(neighbors[j].second);\n            }\n            \n            auto edges = query(subset);\n            for(auto& e : edges) {\n                query_edges[i].push_back(e);\n            }\n            queries_left--;\n        }\n    }\n    \n    // Output MST construction\n    cout << \"!\" << endl;\n    for(int i=0; i<M; ++i) {\n        // Output cities\n        for(int j=0; j<G[i]; ++j) {\n            cout << groups[i][j] << (j == G[i]-1 ? \"\" : \" \");\n        }\n        cout << endl;\n        \n        // Build MST\n        struct Edge { int u, v; long long w; };\n        vector<Edge> all_edges;\n        \n        // Add query edges (weight 0 to ensure priority)\n        for(auto& e : query_edges[i]) {\n            all_edges.push_back({e.first, e.second, 0});\n        }\n        \n        // Add potential edges\n        for(size_t u=0; u<groups[i].size(); ++u) {\n            for(size_t v=u+1; v<groups[i].size(); ++v) {\n                int city_u = groups[i][u];\n                int city_v = groups[i][v];\n                long long d = distInt(cities[city_u].x, cities[city_u].y, cities[city_v].x, cities[city_v].y);\n                all_edges.push_back({city_u, city_v, d});\n            }\n        }\n        \n        sort(all_edges.begin(), all_edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        \n        // DSU\n        vector<int> parent(N);\n        for(int j=0; j<N; ++j) parent[j] = j;\n        \n        auto find = [&](auto self, int node) -> int {\n            return parent[node] == node ? node : parent[node] = self(self, parent[node]);\n        };\n        \n        vector<pair<int, int>> mst_edges;\n        for(auto& e : all_edges) {\n            int root_u = find(find, e.u);\n            int root_v = find(find, e.v);\n            if(root_u != root_v) {\n                parent[root_u] = root_v;\n                mst_edges.push_back({e.u, e.v});\n            }\n        }\n        \n        for(auto& e : mst_edges) {\n            cout << e.first << \" \" << e.second << endl;\n        }\n    }\n    \n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <tuple>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Constants\nconst int N = 20;\n\n// Directions: U, D, L, R\nconst int DR[] = {-1, 1, 0, 0};\nconst int DC[] = {0, 0, -1, 1};\nconst char D_CHAR[] = {'U', 'D', 'L', 'R'};\n\nstruct State {\n    int r, c, dist;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\n// Function to simulate sliding and find the stopping position\npair<int, int> get_stop_pos(int r, int c, int dr, int dc, const vector<vector<int>>& grid) {\n    int nr = r, nc = c;\n    while (true) {\n        int next_r = nr + dr;\n        int next_c = nc + dc;\n        // Blocks are at the edges, so sliding always stops\n        if (next_r < 0 || next_r >= N || next_c < 0 || next_c >= N || grid[next_r][next_c] == 1) {\n            return {nr, nc};\n        }\n        nr = next_r;\n        nc = next_c;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n, m;\n    cin >> n >> m;\n    int r0, c0;\n    cin >> r0 >> c0;\n    vector<pair<int, int>> targets(m);\n    for (int i = 0; i < m; ++i) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n\n    vector<vector<int>> grid(N, vector<int>(N, 0));\n    int curr_r = r0, curr_c = c0;\n\n    for (int t = 0; t < m; ++t) {\n        int tr = targets[t].first;\n        int tc = targets[t].second;\n\n        // Dijkstra to find shortest path to (tr, tc)\n        vector<vector<int>> dist(N, vector<int>(N, 1e9));\n        vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n        vector<vector<string>> action_path(N, vector<string>(N, \"\"));\n        \n        priority_queue<State, vector<State>, greater<State>> pq;\n        dist[curr_r][curr_c] = 0;\n        pq.push({curr_r, curr_c, 0});\n        \n        while (!pq.empty()) {\n            State top = pq.top();\n            pq.pop();\n            \n            if (top.dist > dist[top.r][top.c]) continue;\n            if (top.r == tr && top.c == tc) break;\n            \n            for (int i = 0; i < 4; ++i) {\n                // Move action\n                int nr = top.r + DR[i];\n                int nc = top.c + DC[i];\n                if (nr >= 0 && nr < N && nc >= 0 && nc < N) {\n                    int cost = (grid[nr][nc] == 1) ? 2 : 1;\n                    string actions = \"\";\n                    if (grid[nr][nc] == 1) actions += string(\"A \") + D_CHAR[i] + \"\\n\";\n                    actions += string(\"M \") + D_CHAR[i] + \"\\n\";\n                    \n                    if (dist[top.r][top.c] + cost < dist[nr][nc]) {\n                        dist[nr][nc] = dist[top.r][top.c] + cost;\n                        parent[nr][nc] = {top.r, top.c};\n                        action_path[nr][nc] = actions;\n                        pq.push({nr, nc, dist[nr][nc]});\n                    }\n                }\n                \n                // Slide action\n                pair<int, int> stop = get_stop_pos(top.r, top.c, DR[i], DC[i], grid);\n                int sr = stop.first, sc = stop.second;\n                int br = sr + DR[i], bc = sc + DC[i];\n                \n                // Check if we need to add a block to stop at (sr, sc)\n                bool need_block = (br >= 0 && br < N && bc >= 0 && bc < N && grid[br][bc] == 0);\n                int cost = need_block ? 2 : 1;\n                \n                string actions = \"\";\n                if (need_block) actions += string(\"A \") + D_CHAR[i] + \"\\n\";\n                actions += string(\"S \") + D_CHAR[i] + \"\\n\";\n                \n                if (dist[top.r][top.c] + cost < dist[sr][sc]) {\n                    dist[sr][sc] = dist[top.r][top.c] + cost;\n                    parent[sr][sc] = {top.r, top.c};\n                    action_path[sr][sc] = actions;\n                    pq.push({sr, sc, dist[sr][sc]});\n                }\n            }\n        }\n        \n        // Reconstruct and execute path\n        vector<string> path_actions;\n        int curr_r2 = tr, curr_c2 = tc;\n        while (curr_r2 != curr_r || curr_c2 != curr_c) {\n            path_actions.push_back(action_path[curr_r2][curr_c2]);\n            pair<int, int> p = parent[curr_r2][curr_c2];\n            curr_r2 = p.first;\n            curr_c2 = p.second;\n        }\n        reverse(path_actions.begin(), path_actions.end());\n        \n        for (const string& s : path_actions) {\n            cout << s;\n            size_t pos = 0;\n            while(pos < s.length()){\n                size_t next_line = s.find('\\n', pos);\n                string line = s.substr(pos, next_line - pos);\n                pos = next_line + 1;\n                if(line.empty()) continue;\n                \n                char act = line[0], dir = line[2];\n                int dr = 0, dc = 0;\n                if(dir == 'U') dr = -1; else if(dir == 'D') dr = 1; else if(dir == 'L') dc = -1; else if(dir == 'R') dc = 1;\n                \n                if(act == 'A'){\n                    int nr = curr_r + dr;\n                    int nc = curr_c + dc;\n                    grid[nr][nc] = 1 - grid[nr][nc];\n                } else if(act == 'M'){\n                    curr_r += dr;\n                    curr_c += dc;\n                } else if(act == 'S'){\n                    pair<int, int> stop = get_stop_pos(curr_r, curr_c, dr, dc, grid);\n                    curr_r = stop.first;\n                    curr_c = stop.second;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}"},"2":{"ahc001":"#include <iostream>\n#include <vector>\n#include <random>\n#include <chrono>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Structure to represent an axis-aligned rectangle\nstruct Rect {\n    int x1, y1, x2, y2;\n};\n\nint N;\nvector<int> X, Y, R;\nvector<Rect> rects;\nvector<Rect> best_rects;\ndouble current_total_score = 0;\ndouble best_total_score = 0;\n\n// Calculate satisfaction p_i = 1 - (1 - min/max)^2 = 2x - x^2\ndouble get_p(int i, int s) {\n    double r = R[i];\n    double x = min(r, (double)s) / max(r, (double)s);\n    return 2.0 * x - x * x;\n}\n\n// Calculate the total satisfaction score for the current layout\ndouble get_total_score(const vector<Rect>& current_rects) {\n    double total = 0;\n    for (int i = 0; i < N; ++i) {\n        int s = (current_rects[i].x2 - current_rects[i].x1) * (current_rects[i].y2 - current_rects[i].y1);\n        total += get_p(i, s);\n    }\n    return total;\n}\n\n// Check if rectangle 'r' overlaps with any other rectangle\nbool check_overlap(int i, const Rect& r, const vector<Rect>& current_rects) {\n    for (int j = 0; j < N; ++j) {\n        if (i == j) continue;\n        if (r.x1 < current_rects[j].x2 && r.x2 > current_rects[j].x1 &&\n            r.y1 < current_rects[j].y2 && r.y2 > current_rects[j].y1) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    // Fast I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N)) return 0;\n    X.resize(N);\n    Y.resize(N);\n    R.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> X[i] >> Y[i] >> R[i];\n    }\n\n    // Initial state: Each rectangle is 1x1 at its target location\n    rects.resize(N);\n    for (int i = 0; i < N; ++i) {\n        rects[i] = {X[i], Y[i], X[i] + 1, Y[i] + 1};\n    }\n    best_rects = rects;\n\n    current_total_score = get_total_score(rects);\n    best_total_score = current_total_score;\n\n    mt19937 rng(1337);\n    auto start_time = chrono::steady_clock::now();\n\n    // Simulated Annealing parameters\n    double T_start = 0.1;\n    double T_end = 0.00001;\n    long long max_iterations = 5000000;\n    \n    // Main Simulated Annealing loop\n    for (long long iteration = 0; iteration < max_iterations; ++iteration) {\n        // Check time periodically\n        if ((iteration & 2047) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 4800) break;\n        }\n\n        int i = uniform_int_distribution<int>(0, N - 1)(rng);\n        int side = uniform_int_distribution<int>(0, 3)(rng);\n        \n        // Temperature scheduling\n        double progress = (double)iteration / max_iterations;\n        double T = T_start * pow(T_end / T_start, progress);\n        \n        // Adjust delta based on temperature to focus search\n        int delta_range = max(1.0, 100.0 * T / T_start);\n        int delta = uniform_int_distribution<int>(-delta_range, delta_range)(rng);\n\n        Rect next_rect = rects[i];\n        // Move one side, respecting constraints (must cover X[i], Y[i])\n        if (side == 0) { // x1\n            next_rect.x1 = max(0, min(X[i], next_rect.x1 + delta));\n        } else if (side == 1) { // x2\n            next_rect.x2 = max(X[i] + 1, min(10000, next_rect.x2 + delta));\n        } else if (side == 2) { // y1\n            next_rect.y1 = max(0, min(Y[i], next_rect.y1 + delta));\n        } else { // y2\n            next_rect.y2 = max(Y[i] + 1, min(10000, next_rect.y2 + delta));\n        }\n\n        // Validity check\n        if (next_rect.x1 == next_rect.x2 || next_rect.y1 == next_rect.y2) continue;\n        if (check_overlap(i, next_rect, rects)) continue;\n\n        // Calculate score change\n        int old_s = (rects[i].x2 - rects[i].x1) * (rects[i].y2 - rects[i].y1);\n        int new_s = (next_rect.x2 - next_rect.x1) * (next_rect.y2 - next_rect.y1);\n        \n        double delta_score = get_p(i, new_s) - get_p(i, old_s);\n\n        // Accept move based on Metropolis criterion\n        if (delta_score > 0 || (T > 0 && exp(delta_score / T) > uniform_real_distribution<double>(0, 1)(rng))) {\n            rects[i] = next_rect;\n            current_total_score += delta_score;\n            if (current_total_score > best_total_score) {\n                best_total_score = current_total_score;\n                best_rects = rects;\n            }\n        }\n    }\n\n    // Output final results\n    for (int i = 0; i < N; ++i) {\n        cout << best_rects[i].x1 << \" \" << best_rects[i].y1 << \" \" << best_rects[i].x2 << \" \" << best_rects[i].y2 << \"\\n\";\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\n// Global variables\nint si, sj;\nint t[50][50];\nint p[50][50];\nint M = 0;\nvector<int> tile_neighbors[2500];\nbool is_visited_tile[2500];\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dchar[] = {'U', 'D', 'L', 'R'};\n\n// Function to count unvisited neighbors of a given tile\nint count_unvisited_neighbors(int tile_id) {\n    int count = 0;\n    for (int neighbor : tile_neighbors[tile_id]) {\n        if (!is_visited_tile[neighbor]) {\n            count++;\n        }\n    }\n    return count;\n}\n\nint main() {\n    // Faster I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read input\n    if (!(cin >> si >> sj)) return 0;\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> t[i][j];\n            M = max(M, t[i][j] + 1);\n        }\n    }\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> p[i][j];\n        }\n    }\n\n    // Precompute tile adjacency\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            int current_tile = t[i][j];\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dr[k];\n                int nj = j + dc[k];\n                if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n                    int neighbor_tile = t[ni][nj];\n                    if (current_tile != neighbor_tile) {\n                        tile_neighbors[current_tile].push_back(neighbor_tile);\n                    }\n                }\n            }\n        }\n    }\n    // Remove duplicates from neighbor lists\n    for (int i = 0; i < M; ++i) {\n        sort(tile_neighbors[i].begin(), tile_neighbors[i].end());\n        tile_neighbors[i].erase(unique(tile_neighbors[i].begin(), tile_neighbors[i].end()), tile_neighbors[i].end());\n    }\n\n    string best_path = \"\";\n    int max_total_score = -1;\n\n    auto start_time = chrono::high_resolution_clock::now();\n    mt19937 rng(12345);\n\n    // Randomized greedy loop\n    while (true) {\n        auto current_time = chrono::high_resolution_clock::now();\n        // Time limit check (safer margin at 1.8s)\n        if (chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count() > 1800) {\n            break;\n        }\n\n        // Reset state for this iteration\n        memset(is_visited_tile, 0, sizeof(is_visited_tile));\n        \n        string current_path = \"\";\n        int current_total_score = 0;\n        \n        int curr_r = si;\n        int curr_c = sj;\n        int curr_t = t[si][sj];\n        \n        is_visited_tile[curr_t] = true;\n        current_total_score += p[curr_r][curr_c];\n        \n        // Randomization parameter for heuristic (different alpha per iteration)\n        int alpha = rng() % 20;\n\n        while (true) {\n            struct Candidate {\n                int r, c, dir_idx;\n                double score;\n            };\n            vector<Candidate> candidates;\n            \n            // Explore adjacent moves\n            for (int k = 0; k < 4; ++k) {\n                int nr = curr_r + dr[k];\n                int nc = curr_c + dc[k];\n                \n                if (nr >= 0 && nr < 50 && nc >= 0 && nc < 50) {\n                    int next_t = t[nr][nc];\n                    \n                    // Corrected constraint: Must move to a different tile, and that tile must not have been visited.\n                    if (next_t != curr_t && !is_visited_tile[next_t]) {\n                        // Heuristic: prioritize high point tiles + connectivity\n                        double score = (double)p[nr][nc] + (double)alpha * count_unvisited_neighbors(next_t);\n                        // Add randomness to explore different potential paths\n                        score += (rng() % 100) / 10.0;\n                        candidates.push_back({nr, nc, k, score});\n                    }\n                }\n            }\n            \n            if (candidates.empty()) break;\n            \n            // Choose the best candidate based on heuristic\n            int best_idx = 0;\n            for(size_t i = 1; i < candidates.size(); ++i) {\n                if (candidates[i].score > candidates[best_idx].score) best_idx = i;\n            }\n            \n            // Execute move\n            curr_r = candidates[best_idx].r;\n            curr_c = candidates[best_idx].c;\n            int dir = candidates[best_idx].dir_idx;\n            current_path += dchar[dir];\n            \n            curr_t = t[curr_r][curr_c];\n            is_visited_tile[curr_t] = true;\n            current_total_score += p[curr_r][curr_c];\n        }\n        \n        // Keep track of the best path found\n        if (current_total_score > max_total_score) {\n            max_total_score = current_total_score;\n            best_path = current_path;\n        }\n    }\n    \n    cout << best_path << endl;\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Grid dimensions\nconst int R = 30;\nconst int C = 30;\n\n// Edge weights and visit counts\ndouble hor[R][C - 1];\ndouble ver[R - 1][C];\nint cnt_hor[R][C - 1];\nint cnt_ver[R - 1][C];\n\nstruct Node {\n    int r, c;\n    double f; // f = g + h\n    double g; // actual cost so far\n    bool operator>(const Node& other) const {\n        return f > other.f;\n    }\n};\n\n// Heuristic: Manhattan distance * min_possible_edge_weight\n// Since min weight is ~1000, this heuristic is admissible (never overestimates).\ndouble heuristic(int r, int c, int tr, int tc) {\n    return (abs(r - tr) + abs(c - tc)) * 1000.0;\n}\n\n// Function to compute the shortest path using A*\nstring get_path(int sr, int sc, int tr, int tc) {\n    static double dist[R][C];\n    static pair<int, int> parent[R][C];\n    static char dir[R][C];\n    \n    for(int i=0; i<R; ++i) {\n        for(int j=0; j<C; ++j) {\n            dist[i][j] = 1e18;\n            parent[i][j] = {-1, -1};\n            dir[i][j] = ' ';\n        }\n    }\n    \n    priority_queue<Node, vector<Node>, greater<Node>> pq;\n    \n    dist[sr][sc] = 0;\n    pq.push({sr, sc, heuristic(sr, sc, tr, tc), 0});\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    char dchar[] = {'U', 'D', 'L', 'R'};\n    \n    while (!pq.empty()) {\n        Node current = pq.top();\n        pq.pop();\n        \n        int r = current.r;\n        int c = current.c;\n        \n        if (current.g > dist[r][c]) continue;\n        if (r == tr && c == tc) break;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i];\n            int nc = c + dc[i];\n            \n            if (nr >= 0 && nr < R && nc >= 0 && nc < C) {\n                double weight = 0;\n                if (i == 0) weight = ver[r - 1][c]; // U\n                else if (i == 1) weight = ver[r][c]; // D\n                else if (i == 2) weight = hor[r][c - 1]; // L\n                else if (i == 3) weight = hor[r][c]; // R\n                \n                if (dist[nr][nc] > dist[r][c] + weight) {\n                    dist[nr][nc] = dist[r][c] + weight;\n                    parent[nr][nc] = {r, c};\n                    dir[nr][nc] = dchar[i];\n                    pq.push({nr, nc, dist[nr][nc] + heuristic(nr, nc, tr, tc), dist[nr][nc]});\n                }\n            }\n        }\n    }\n    \n    // Reconstruct the path\n    string path = \"\";\n    int curr_r = tr;\n    int curr_c = tc;\n    while (curr_r != sr || curr_c != sc) {\n        char d = dir[curr_r][curr_c];\n        path += d;\n        pair<int, int> p = parent[curr_r][curr_c];\n        curr_r = p.first;\n        curr_c = p.second;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    // Initialize weights to a neutral middle value 5000.0\n    for (int i = 0; i < R; ++i)\n        for (int j = 0; j < C - 1; ++j) { hor[i][j] = 5000.0; cnt_hor[i][j] = 0; }\n    for (int i = 0; i < R - 1; ++i)\n        for (int j = 0; j < C; ++j) { ver[i][j] = 5000.0; cnt_ver[i][j] = 0; }\n    \n    for (int k = 0; k < 1000; ++k) {\n        int sr, sc, tr, tc;\n        cin >> sr >> sc >> tr >> tc;\n        \n        string path = get_path(sr, sc, tr, tc);\n        cout << path << endl; // Flushes output\n        \n        int measured_len;\n        cin >> measured_len;\n        \n        // Calculate predicted path length\n        double path_len = 0;\n        int curr_r = sr;\n        int curr_c = sc;\n        \n        for (char d : path) {\n            if (d == 'U') path_len += ver[curr_r - 1][curr_c];\n            else if (d == 'D') path_len += ver[curr_r][curr_c];\n            else if (d == 'L') path_len += hor[curr_r][curr_c - 1];\n            else if (d == 'R') path_len += hor[curr_r][curr_c];\n            \n            if (d == 'U') curr_r--;\n            else if (d == 'D') curr_r++;\n            else if (d == 'L') curr_c--;\n            else if (d == 'R') curr_c++;\n        }\n        \n        // Calculate ratio and clamp it to avoid wild swings\n        double ratio = (double)measured_len / (path_len + 1e-9);\n        if (ratio < 0.5) ratio = 0.5;\n        if (ratio > 2.0) ratio = 2.0;\n        \n        // Update weights\n        curr_r = sr;\n        curr_c = sc;\n        for (char d : path) {\n            double* w_ptr = nullptr;\n            int* cnt_ptr = nullptr;\n            \n            if (d == 'U') { w_ptr = &ver[curr_r - 1][curr_c]; cnt_ptr = &cnt_ver[curr_r - 1][curr_c]; }\n            else if (d == 'D') { w_ptr = &ver[curr_r][curr_c]; cnt_ptr = &cnt_ver[curr_r][curr_c]; }\n            else if (d == 'L') { w_ptr = &hor[curr_r][curr_c - 1]; cnt_ptr = &cnt_hor[curr_r][curr_c - 1]; }\n            else if (d == 'R') { w_ptr = &hor[curr_r][curr_c]; cnt_ptr = &cnt_hor[curr_r][curr_c]; }\n            \n            // Dynamic learning rate based on visit count\n            (*cnt_ptr)++;\n            double alpha = 0.3 / (1.0 + 0.1 * (*cnt_ptr));\n            \n            *w_ptr *= (1.0 + alpha * (ratio - 1.0));\n            \n            // Constraint check\n            if (*w_ptr < 100) *w_ptr = 100;\n            if (*w_ptr > 10000) *w_ptr = 10000;\n            \n            if (d == 'U') curr_r--;\n            else if (d == 'D') curr_r++;\n            else if (d == 'L') curr_c--;\n            else if (d == 'R') curr_c++;\n        }\n    }\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 20;\nint M;\nvector<string> S;\nint grid[N][N]; // 0-7: A-H, 8: .\nint mismatches[800][800];\nint num_valid[800]; // Number of valid placements for each string\nint count_c;\nint count_d; // Number of '.' cells\n\nstruct Placement {\n    int s_idx;\n    int p_idx;\n};\nvector<Placement> affected[N][N];\n\nstruct PlacementInfo {\n    int line_idx;\n    int start_pos;\n    string s;\n};\nvector<PlacementInfo> all_placements[800];\n\nint get_char_idx(char c) {\n    if (c == '.') return 8;\n    return c - 'A';\n}\n\nchar get_char(int idx) {\n    if (idx == 8) return '.';\n    return idx + 'A';\n}\n\nvoid init() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = 8; // '.'\n        }\n    }\n    count_c = 0;\n    count_d = N * N;\n\n    for (int i = 0; i < M; ++i) {\n        string s = S[i];\n        int len = s.length();\n        // 40 lines: 0-19 rows, 20-39 cols\n        for (int line = 0; line < 2 * N; ++line) {\n            for (int start = 0; start < N; ++start) {\n                int p_idx = line * N + start;\n                all_placements[i].push_back({line, start, s});\n                \n                // Mismatches initially len because grid is '.'\n                mismatches[i][p_idx] = len;\n                \n                for (int k = 0; k < len; ++k) {\n                    int r, c;\n                    if (line < N) {\n                        r = line;\n                        c = (start + k) % N;\n                    } else {\n                        r = (start + k) % N;\n                        c = line - N;\n                    }\n                    affected[r][c].push_back({i, p_idx});\n                }\n            }\n        }\n        num_valid[i] = 0;\n    }\n}\n\nvoid update_grid(int r, int c, int new_val) {\n    int old_val = grid[r][c];\n    if (old_val == new_val) return;\n\n    if (old_val == 8 && new_val != 8) count_d--;\n    else if (old_val != 8 && new_val == 8) count_d++;\n\n    grid[r][c] = new_val;\n\n    for (auto& p : affected[r][c]) {\n        int s_idx = p.s_idx;\n        int p_idx = p.p_idx;\n        \n        bool was_valid = (mismatches[s_idx][p_idx] == 0);\n        \n        PlacementInfo& pi = all_placements[s_idx][p_idx];\n        int len = pi.s.length();\n        int k = -1;\n        \n        if (pi.line_idx < N) {\n            k = (c - pi.start_pos + N) % N;\n        } else {\n            k = (r - pi.start_pos + N) % N;\n        }\n        \n        // Target character at this position\n        int target_idx = get_char_idx(pi.s[k]);\n        \n        auto matches = [&](int cell_val, int target) {\n            return cell_val == target;\n        };\n        \n        bool old_match = matches(old_val, target_idx);\n        bool new_match = matches(new_val, target_idx);\n        \n        if (!old_match && new_match) mismatches[s_idx][p_idx]--;\n        else if (old_match && !new_match) mismatches[s_idx][p_idx]++;\n        \n        bool is_valid = (mismatches[s_idx][p_idx] == 0);\n        \n        if (was_valid && !is_valid) {\n            num_valid[s_idx]--;\n            if (num_valid[s_idx] == 0) count_c--;\n        } else if (!was_valid && is_valid) {\n            if (num_valid[s_idx] == 0) count_c++;\n            num_valid[s_idx]++;\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in; cin >> N_in;\n    cin >> M;\n    S.resize(M);\n    for (int i = 0; i < M; ++i) cin >> S[i];\n\n    init();\n    \n    // Greedy initialization\n    vector<int> p(M);\n    for(int i=0; i<M; ++i) p[i] = i;\n    mt19937 rng(1337);\n    shuffle(p.begin(), p.end(), rng);\n    \n    for(int i : p) {\n        if (num_valid[i] > 0) continue;\n        int p_idx = rng() % all_placements[i].size();\n        PlacementInfo& pi = all_placements[i][p_idx];\n        \n        for (int k = 0; k < (int)pi.s.length(); ++k) {\n            int r, c;\n            if (pi.line_idx < N) {\n                r = pi.line_idx;\n                c = (pi.start_pos + k) % N;\n            } else {\n                r = (pi.start_pos + k) % N;\n                c = pi.line_idx - N;\n            }\n            if (grid[r][c] == 8) {\n                update_grid(r, c, get_char_idx(pi.s[k]));\n            }\n        }\n    }\n\n    // SA\n    double T = 1000.0;\n    double T_min = 0.1;\n    int iterations = 200000;\n    \n    auto get_score = [&]() {\n        if (count_c < M) return (long long)count_c * 10000;\n        return (long long)M * 10000 + count_d;\n    };\n    \n    long long current_score = get_score();\n    \n    for (int i = 0; i < iterations; ++i) {\n        int r = rng() % N;\n        int c = rng() % N;\n        int old_val = grid[r][c];\n        int new_val = rng() % 9; \n        \n        if (old_val == new_val) continue;\n        \n        update_grid(r, c, new_val);\n        long long next_score = get_score();\n        \n        double prob = exp((double)(next_score - current_score) / T);\n        if (next_score >= current_score || (rng() % 10000) / 10000.0 < prob) {\n            current_score = next_score;\n        } else {\n            update_grid(r, c, old_val);\n        }\n        T *= pow(T_min / 1000.0, 1.0 / iterations);\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << get_char(grid[i][j]);\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\n// Structure to represent a point on the grid\nstruct Point {\n    int r, c;\n    bool operator==(const Point& other) const {\n        return r == other.r && c == other.c;\n    }\n    bool operator!=(const Point& other) const {\n        return !(*this == other);\n    }\n};\n\nint N;\nint si, sj;\nvector<string> grid;\nvector<vector<int>> weights;\nvector<vector<vector<Point>>> visible_from;\nvector<Point> all_road_squares;\n\n// Helper to check if a square is a road\nbool is_road(int r, int c) {\n    return r >= 0 && r < N && c >= 0 && c < N && grid[r][c] != '#';\n}\n\n// Precompute visibility for all road squares\nvoid precompute_visibility() {\n    visible_from.resize(N, vector<vector<Point>>(N));\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            if (!is_road(r, c)) continue;\n            \n            // The square itself is visible\n            visible_from[r][c].push_back({r, c});\n            \n            // Horizontal and Vertical visibility\n            for (int nc = c + 1; nc < N && is_road(r, nc); ++nc) visible_from[r][c].push_back({r, nc});\n            for (int nc = c - 1; nc >= 0 && is_road(r, nc); --nc) visible_from[r][c].push_back({r, nc});\n            for (int nr = r + 1; nr < N && is_road(nr, c); ++nr) visible_from[r][c].push_back({nr, c});\n            for (int nr = r - 1; nr >= 0 && is_road(nr, c); --nr) visible_from[r][c].push_back({nr, c});\n        }\n    }\n}\n\n// BFS to find shortest paths and distances\nstruct BFSResult {\n    vector<vector<int>> dist;\n    vector<vector<Point>> parent;\n};\n\nBFSResult bfs(Point start) {\n    BFSResult res;\n    res.dist.assign(N, vector<int>(N, 1e9));\n    res.parent.assign(N, vector<Point>(N, {-1, -1}));\n    \n    queue<Point> q;\n    res.dist[start.r][start.c] = 0;\n    q.push(start);\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    \n    while (!q.empty()) {\n        Point curr = q.front();\n        q.pop();\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n            \n            if (is_road(nr, nc)) {\n                int cost = weights[nr][nc];\n                if (res.dist[nr][nc] > res.dist[curr.r][curr.c] + cost) {\n                    res.dist[nr][nc] = res.dist[curr.r][curr.c] + cost;\n                    res.parent[nr][nc] = curr;\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n    return res;\n}\n\n// Reconstruct path from start to end using BFS parent pointers\nstring get_moves(Point start, Point end, const vector<vector<Point>>& parent) {\n    string moves = \"\";\n    Point curr = end;\n    while (curr != start) {\n        Point p = parent[curr.r][curr.c];\n        if (curr.r == p.r - 1) moves += 'U';\n        else if (curr.r == p.r + 1) moves += 'D';\n        else if (curr.c == p.c - 1) moves += 'L';\n        else if (curr.c == p.c + 1) moves += 'R';\n        curr = p;\n    }\n    reverse(moves.begin(), moves.end());\n    return moves;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N >> si >> sj;\n    grid.resize(N);\n    weights.resize(N, vector<int>(N));\n    \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                weights[i][j] = grid[i][j] - '0';\n                all_road_squares.push_back({i, j});\n            }\n        }\n    }\n    \n    precompute_visibility();\n    \n    // Greedy set cover to find necessary squares to visit\n    vector<Point> must_visit;\n    must_visit.push_back({si, sj});\n    \n    vector<vector<bool>> covered(N, vector<bool>(N, false));\n    int uncovered_count = 0;\n    \n    auto mark_covered = [&](Point p) {\n        int count = 0;\n        for (auto& v : visible_from[p.r][p.c]) {\n            if (!covered[v.r][v.c]) {\n                covered[v.r][v.c] = true;\n                count++;\n            }\n        }\n        return count;\n    };\n    \n    uncovered_count = all_road_squares.size() - mark_covered({si, sj});\n    \n    while (uncovered_count > 0) {\n        Point best_p = {-1, -1};\n        int best_cover = -1;\n        \n        for (auto& p : all_road_squares) {\n            int current_cover = 0;\n            for (auto& v : visible_from[p.r][p.c]) {\n                if (!covered[v.r][v.c]) current_cover++;\n            }\n            if (current_cover > best_cover) {\n                best_cover = current_cover;\n                best_p = p;\n            }\n        }\n        \n        if (best_cover <= 0) break;\n        \n        must_visit.push_back(best_p);\n        uncovered_count -= mark_covered(best_p);\n    }\n    \n    // TSP: Nearest Neighbor heuristic\n    vector<Point> tour;\n    tour.push_back({si, sj});\n    \n    vector<bool> visited(must_visit.size(), false);\n    visited[0] = true;\n    \n    Point curr = {si, sj};\n    while (tour.size() < must_visit.size()) {\n        int best_idx = -1;\n        int min_dist = 1e9;\n        \n        BFSResult bfs_res = bfs(curr);\n        \n        for (int i = 0; i < must_visit.size(); ++i) {\n            if (!visited[i]) {\n                if (bfs_res.dist[must_visit[i].r][must_visit[i].c] < min_dist) {\n                    min_dist = bfs_res.dist[must_visit[i].r][must_visit[i].c];\n                    best_idx = i;\n                }\n            }\n        }\n        \n        tour.push_back(must_visit[best_idx]);\n        visited[best_idx] = true;\n        curr = must_visit[best_idx];\n    }\n    \n    // Return to start\n    tour.push_back({si, sj});\n    \n    // Build final path\n    string final_path = \"\";\n    for (int i = 0; i < tour.size() - 1; ++i) {\n        BFSResult bfs_res = bfs(tour[i]);\n        final_path += get_moves(tour[i], tour[i+1], bfs_res.parent);\n    }\n    \n    cout << final_path << endl;\n    \n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\n// Global variables to store problem state\nint N, M, K, R;\nvector<vector<int>> task_difficulty;\nvector<vector<int>> adj;\nvector<int> in_degree;\nvector<int> task_status; // -1: not started, 0: in progress, 1: completed\nvector<int> member_status; // -1: free, >=0: task_id\nvector<int> start_day;\nvector<vector<double>> s; // Skills estimation\nvector<int> H; // Task criticality (longest dependency chain)\n\n// Function to calculate predicted completion time for a task by a member\ndouble predict_t(int task_id, int member_id) {\n    double w = 0;\n    for (int k = 0; k < K; ++k) {\n        w += max(0, task_difficulty[task_id][k] - (int)s[member_id][k]);\n    }\n    // If w=0, completion time is 1. Otherwise, w is a good estimate.\n    if (w == 0) return 1.0;\n    return max(1.0, w);\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read input\n    cin >> N >> M >> K >> R;\n    task_difficulty.resize(N, vector<int>(K));\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            cin >> task_difficulty[i][k];\n        }\n    }\n    adj.resize(N);\n    in_degree.resize(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        adj[u].push_back(v);\n        in_degree[v]++;\n    }\n\n    // Precompute H (criticality/longest path in DAG)\n    H.resize(N, 1);\n    for (int i = N - 1; i >= 0; --i) {\n        for (int v : adj[i]) {\n            H[i] = max(H[i], 1 + H[v]);\n        }\n    }\n\n    // Initialization\n    task_status.assign(N, -1);\n    member_status.assign(M, -1);\n    start_day.assign(N, -1);\n    s.assign(M, vector<double>(K, 30.0)); // Initial skill guess\n    vector<int> ready_tasks;\n    for (int i = 0; i < N; ++i) {\n        if (in_degree[i] == 0) {\n            ready_tasks.push_back(i);\n        }\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n\n        // 1. Assign tasks\n        // Sort ready_tasks by criticality (H)\n        sort(ready_tasks.begin(), ready_tasks.end(), [&](int a, int b) {\n            return H[a] > H[b];\n        });\n\n        vector<pair<int, int>> assignments;\n        vector<int> free_members;\n        for (int j = 0; j < M; ++j) {\n            if (member_status[j] == -1) {\n                free_members.push_back(j);\n            }\n        }\n\n        // Greedy matching of ready tasks to free members\n        vector<bool> task_assigned(ready_tasks.size(), false);\n        vector<bool> member_assigned(free_members.size(), false);\n        \n        for (int i = 0; i < (int)ready_tasks.size(); ++i) {\n            int task_id = ready_tasks[i];\n            \n            // Find best free member for this task\n            int best_member_idx = -1;\n            double min_t = 1e18;\n            for (int j = 0; j < (int)free_members.size(); ++j) {\n                if (member_assigned[j]) continue;\n                double t = predict_t(task_id, free_members[j]);\n                if (t < min_t) {\n                    min_t = t;\n                    best_member_idx = j;\n                }\n            }\n\n            if (best_member_idx != -1) {\n                int member_id = free_members[best_member_idx];\n                assignments.push_back({member_id + 1, task_id + 1});\n                member_status[member_id] = task_id;\n                task_status[task_id] = 0;\n                start_day[task_id] = day;\n                member_assigned[best_member_idx] = true;\n                task_assigned[i] = true;\n            }\n        }\n\n        // Update ready_tasks: remove assigned ones\n        vector<int> next_ready_tasks;\n        for (int i = 0; i < (int)ready_tasks.size(); ++i) {\n            if (!task_assigned[i]) {\n                next_ready_tasks.push_back(ready_tasks[i]);\n            }\n        }\n        ready_tasks = next_ready_tasks;\n\n        // Output assignments and flush\n        cout << assignments.size();\n        for (auto& p : assignments) {\n            cout << \" \" << p.first << \" \" << p.second;\n        }\n        cout << endl;\n\n        // 2. Read completed tasks\n        int n_completed;\n        cin >> n_completed;\n        if (n_completed == -1) break;\n        \n        for (int i = 0; i < n_completed; ++i) {\n            int member_id;\n            cin >> member_id;\n            --member_id;\n            int task_id = member_status[member_id];\n            \n            // Update skill estimations\n            int actual_t = day - start_day[task_id] + 1;\n            double w = 0;\n            for (int k = 0; k < K; ++k) {\n                w += max(0, task_difficulty[task_id][k] - (int)s[member_id][k]);\n            }\n            double error = actual_t - (w == 0 ? 1.0 : w);\n            double learning_rate = 0.1;\n            for (int k = 0; k < K; ++k) {\n                if (task_difficulty[task_id][k] > s[member_id][k]) {\n                    // Update skill s[member_id][k]\n                    s[member_id][k] -= learning_rate * error;\n                    s[member_id][k] = max(0.0, min(100.0, s[member_id][k]));\n                }\n            }\n\n            task_status[task_id] = 1;\n            member_status[member_id] = -1;\n\n            // Update in_degree and ready_tasks\n            for (int next_task : adj[task_id]) {\n                in_degree[next_task]--;\n                if (in_degree[next_task] == 0) {\n                    ready_tasks.push_back(next_task);\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Order structure\nstruct Order {\n    int id;\n    int ax, ay, cx, cy;\n    double dist_from_office;\n};\n\n// Node structure for the route\nstruct Node {\n    int order_id;\n    bool is_pickup;\n    int x, y;\n};\n\n// Manhattan distance\nint dist(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Calculate total route distance\nint calculate_total_dist(const vector<Node>& route) {\n    int d = 0;\n    int cx = 400, cy = 400;\n    for (const auto& node : route) {\n        d += dist(cx, cy, node.x, node.y);\n        cx = node.x;\n        cy = node.y;\n    }\n    d += dist(cx, cy, 400, 400);\n    return d;\n}\n\n// Check if route satisfies precedence constraints\nbool is_valid(const vector<Node>& route, const vector<int>& selected_orders) {\n    vector<int> p_pos(1001, -1);\n    vector<int> d_pos(1001, -1);\n    for (int i = 0; i < route.size(); ++i) {\n        if (route[i].is_pickup) p_pos[route[i].order_id] = i;\n        else d_pos[route[i].order_id] = i;\n    }\n    for (int id : selected_orders) {\n        if (p_pos[id] > d_pos[id]) return false;\n    }\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // Read all orders\n    vector<Order> all_orders(1000);\n    for (int i = 0; i < 1000; ++i) {\n        all_orders[i].id = i + 1;\n        cin >> all_orders[i].ax >> all_orders[i].ay >> all_orders[i].cx >> all_orders[i].cy;\n        all_orders[i].dist_from_office = dist(400, 400, all_orders[i].ax, all_orders[i].ay) +\n                                         dist(all_orders[i].ax, all_orders[i].ay, all_orders[i].cx, all_orders[i].cy) +\n                                         dist(all_orders[i].cx, all_orders[i].cy, 400, 400);\n    }\n\n    // Sort orders by distance and pick top 50\n    vector<Order> sorted_orders = all_orders;\n    sort(sorted_orders.begin(), sorted_orders.end(), [](const Order& a, const Order& b) {\n        return a.dist_from_office < b.dist_from_office;\n    });\n\n    vector<int> selected_orders;\n    for (int i = 0; i < 50; ++i) {\n        selected_orders.push_back(sorted_orders[i].id);\n    }\n\n    // Greedy Initial Route Construction\n    vector<Node> route;\n    vector<bool> p_visited(1001, false);\n    vector<bool> d_visited(1001, false);\n    int cx = 400, cy = 400;\n    \n    while (route.size() < 100) {\n        int best_idx = -1;\n        bool best_is_pickup = false;\n        int min_d = 2000000000;\n        \n        for (int id : selected_orders) {\n            if (!p_visited[id]) {\n                int d = dist(cx, cy, all_orders[id - 1].ax, all_orders[id - 1].ay);\n                if (d < min_d) {\n                    min_d = d;\n                    best_idx = id;\n                    best_is_pickup = true;\n                }\n            }\n            if (p_visited[id] && !d_visited[id]) {\n                int d = dist(cx, cy, all_orders[id - 1].cx, all_orders[id - 1].cy);\n                if (d < min_d) {\n                    min_d = d;\n                    best_idx = id;\n                    best_is_pickup = false;\n                }\n            }\n        }\n        \n        if (best_is_pickup) {\n            route.push_back({best_idx, true, all_orders[best_idx - 1].ax, all_orders[best_idx - 1].ay});\n            p_visited[best_idx] = true;\n            cx = all_orders[best_idx - 1].ax;\n            cy = all_orders[best_idx - 1].ay;\n        } else {\n            route.push_back({best_idx, false, all_orders[best_idx - 1].cx, all_orders[best_idx - 1].cy});\n            d_visited[best_idx] = true;\n            cx = all_orders[best_idx - 1].cx;\n            cy = all_orders[best_idx - 1].cy;\n        }\n    }\n\n    // Refine with local search (Hill Climbing / 2-opt)\n    auto start_time = chrono::steady_clock::now();\n    mt19937 rng(42);\n    int best_dist = calculate_total_dist(route);\n    int iter = 0;\n    \n    while (true) {\n        if ((iter++ & 1023) == 0) { // Check time every 1024 iterations\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1900) break;\n        }\n        \n        int i = rng() % 100;\n        int j = rng() % 100;\n        if (i > j) swap(i, j);\n        if (i == j) continue;\n        \n        // Try reversing the segment [i, j]\n        vector<Node> next_route = route;\n        reverse(next_route.begin() + i, next_route.begin() + j + 1);\n        \n        if (is_valid(next_route, selected_orders)) {\n            int d = calculate_total_dist(next_route);\n            if (d < best_dist) {\n                best_dist = d;\n                route = next_route;\n            }\n        }\n    }\n\n    // Output results\n    cout << 50;\n    for (int id : selected_orders) cout << \" \" << id;\n    cout << endl;\n    \n    cout << 102; // Start, 100 points, End\n    cout << \" 400 400\";\n    for (const auto& node : route) cout << \" \" << node.x << \" \" << node.y;\n    cout << \" 400 400\" << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\n// DSU structure for connectivity checking\nstruct DSU {\n    vector<int> parent;\n    DSU(int n) {\n        parent.resize(n);\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int i) {\n        if (parent[i] == i)\n            return i;\n        return parent[i] = find(parent[i]);\n    }\n    void unite(int i, int j) {\n        int root_i = find(i);\n        int root_j = find(j);\n        if (root_i != root_j) {\n            parent[root_i] = root_j;\n        }\n    }\n    bool same(int i, int j) {\n        return find(i) == find(j);\n    }\n};\n\nstruct Edge {\n    int u, v, d, id;\n};\n\nint main() {\n    // Faster I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Problem constraints: N=400, M=1995 are fixed.\n    const int N = 400;\n    const int M = 1995;\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<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        int dx = coords[edges[i].u].first - coords[edges[i].v].first;\n        int dy = coords[edges[i].u].second - coords[edges[i].v].second;\n        // Euclidean distance rounded to nearest integer\n        edges[i].d = (int)round(sqrt((double)dx * dx + (double)dy * dy));\n        edges[i].id = i;\n    }\n\n    vector<bool> adopted(M, false);\n    \n    // Process each edge as it arrives\n    for (int i = 0; i < M; ++i) {\n        int l_i;\n        cin >> l_i;\n\n        // Adaptive parameter k:\n        // k starts at 1.0 (optimistic, minimum possible cost) and increases to 2.0 (neutral, expected cost).\n        // This forces the algorithm to be more conservative (avoiding expensive edges) when there are many \n        // opportunities left, and more aggressive (taking edges) as we approach the end to ensure connectivity.\n        double k = 1.0 + 1.0 * ((double)i / M);\n\n        // 1. Initialize DSU with all already adopted edges\n        DSU dsu(N);\n        for (int j = 0; j < i; ++j) {\n            if (adopted[j]) {\n                dsu.unite(edges[j].u, edges[j].v);\n            }\n        }\n\n        // 2. Prepare candidates: the current edge (cost l_i) and all future edges (estimated cost k*d)\n        struct Candidate {\n            double cost;\n            int id;\n            int u, v;\n        };\n        vector<Candidate> candidates;\n        candidates.reserve(M - i);\n        \n        candidates.push_back({(double)l_i, i, edges[i].u, edges[i].v});\n        \n        for (int j = i + 1; j < M; ++j) {\n            candidates.push_back({k * edges[j].d, j, edges[j].u, edges[j].v});\n        }\n        \n        // Sort candidates by cost to run Kruskal's algorithm\n        sort(candidates.begin(), candidates.end(), [](const Candidate& a, const Candidate& b) {\n            return a.cost < b.cost;\n        });\n        \n        // 3. Run Kruskal's to see if the current edge i is part of the MST\n        bool take_edge = false;\n        for (const auto& cand : candidates) {\n            if (!dsu.same(cand.u, cand.v)) {\n                dsu.unite(cand.u, cand.v);\n                if (cand.id == i) {\n                    take_edge = true;\n                    break;\n                }\n            }\n        }\n        \n        // Output decision and flush\n        if (take_edge) {\n            cout << 1 << endl;\n            adopted[i] = true;\n        } else {\n            cout << 0 << endl;\n            adopted[i] = false;\n        }\n    }\n    \n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int r, c;\n    bool operator==(const Point& other) const { return r == other.r && c == other.c; }\n};\n\nint N, M;\nvector<Point> pets;\nvector<int> pet_types;\nvector<Point> humans;\nbool impassable[30][30];\n\n// Check if a coordinate is within bounds\nbool is_valid(int r, int c) {\n    return r >= 0 && r < 30 && c >= 0 && c < 30;\n}\n\n// Check if a square can be made impassable\nbool can_build(int r, int c) {\n    if (!is_valid(r, c) || impassable[r][c]) return false;\n    // Cannot build if a pet or human is currently at (r, c)\n    for (const auto& p : pets) if (p.r == r && p.c == c) return false;\n    for (const auto& h : humans) if (h.r == r && h.c == c) return false;\n    \n    // Cannot build if an adjacent square contains a pet\n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    for (int i = 0; i < 4; ++i) {\n        int nr = r + dr[i];\n        int nc = c + dc[i];\n        if (is_valid(nr, nc)) {\n            for (const auto& p : pets) {\n                if (p.r == nr && p.c == nc) return false;\n            }\n        }\n    }\n    return true;\n}\n\n// Find the index of the nearest pet\nint get_nearest_pet(Point h) {\n    int min_dist = 1000;\n    int target = -1;\n    for (int i = 0; i < N; ++i) {\n        int d = abs(h.r - pets[i].r) + abs(h.c - pets[i].c);\n        if (d < min_dist) {\n            min_dist = d;\n            target = i;\n        }\n    }\n    return target;\n}\n\n// BFS to find the next move towards the target\nPoint get_next_move(Point start, Point target) {\n    if (start.r == target.r && start.c == target.c) return start;\n    \n    queue<pair<Point, Point>> q; // {current, first_step}\n    bool visited[30][30] = {false};\n    \n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    \n    // Check initial neighbors\n    for (int i = 0; i < 4; ++i) {\n        int nr = start.r + dr[i];\n        int nc = start.c + dc[i];\n        if (is_valid(nr, nc) && !impassable[nr][nc]) {\n            bool occupied = false;\n            for(auto& h : humans) if(h.r == nr && h.c == nc) occupied = true;\n            if(!occupied) {\n                q.push({{nr, nc}, {nr, nc}});\n                visited[nr][nc] = true;\n            }\n        }\n    }\n    \n    while (!q.empty()) {\n        auto [curr, first] = q.front();\n        q.pop();\n        \n        if (curr.r == target.r && curr.c == target.c) return first;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n            if (is_valid(nr, nc) && !impassable[nr][nc] && !visited[nr][nc]) {\n                bool occupied = false;\n                for(auto& h : humans) if(h.r == nr && h.c == nc) occupied = true;\n                if(!occupied) {\n                    visited[nr][nc] = true;\n                    q.push({{nr, nc}, first});\n                }\n            }\n        }\n    }\n    return start; // No path found\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N;\n    pets.resize(N);\n    pet_types.resize(N);\n    for (int i = 0; i < N; ++i) cin >> pets[i].r >> pets[i].c >> pet_types[i];\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) cin >> humans[i].r >> humans[i].c;\n    \n    for (int i = 0; i < 30; ++i) for (int j = 0; j < 30; ++j) impassable[i][j] = false;\n    \n    for (int turn = 0; turn < 300; ++turn) {\n        vector<string> actions(M, \".\");\n        \n        for (int i = 0; i < M; ++i) {\n            int target_idx = get_nearest_pet(humans[i]);\n            if (target_idx == -1) continue;\n            \n            Point pet = pets[target_idx];\n            bool built = false;\n            int dr[] = {0, 0, 1, -1};\n            int dc[] = {1, -1, 0, 0};\n            char wall_chars[] = {'r', 'l', 'd', 'u'};\n            \n            // Try to build a wall near the target pet to trap it\n            for (int k = 0; k < 4; ++k) {\n                int nr = humans[i].r + dr[k];\n                int nc = humans[i].c + dc[k];\n                \n                if (abs(nr - pet.r) + abs(nc - pet.c) <= 2) {\n                    if (can_build(nr, nc)) {\n                        string s(1, wall_chars[k]);\n                        actions[i] = s;\n                        impassable[nr][nc] = true;\n                        built = true;\n                        break;\n                    }\n                }\n            }\n            \n            // If not building, move towards the pet\n            if (!built) {\n                Point next = get_next_move(humans[i], pet);\n                if (!(next == humans[i])) {\n                    if (next.r < humans[i].r) actions[i] = \"U\";\n                    else if (next.r > humans[i].r) actions[i] = \"D\";\n                    else if (next.c < humans[i].c) actions[i] = \"L\";\n                    else if (next.c > humans[i].c) actions[i] = \"R\";\n                    humans[i] = next;\n                }\n            }\n        }\n        \n        // Output actions for this turn\n        for (int i = 0; i < M; ++i) cout << actions[i];\n        cout << endl;\n        \n        // Update pets' positions based on their movements\n        for (int i = 0; i < N; ++i) {\n            string move;\n            cin >> move;\n            for (char c : move) {\n                if (c == 'U') pets[i].r--;\n                else if (c == 'D') pets[i].r++;\n                else if (c == 'L') pets[i].c--;\n                else if (c == 'R') pets[i].c++;\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <string>\n#include <array>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n\nusing namespace std;\n\n// State structure for Beam Search\nstruct State {\n    string path;\n    array<array<double, 20>, 20> dist;\n    double reward;\n    double prob_reached;\n    double heuristic; // Lower is better\n};\n\nint Si, Sj, Ti, Tj;\ndouble P;\nvector<string> H, V;\narray<array<int, 20>, 20> min_dist_to_office;\n\n// Function to compute shortest path distances to the office using BFS\nvoid compute_min_dist() {\n    for (int i = 0; i < 20; ++i) {\n        for (int j = 0; j < 20; ++j) {\n            min_dist_to_office[i][j] = 1000;\n        }\n    }\n    queue<pair<int, int>> q;\n    q.push({Ti, Tj});\n    min_dist_to_office[Ti][Tj] = 0;\n\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n\n        // Check U, D, L, R\n        // U: (r-1, c) -> (r, c) - Wall is V[r-1][c]\n        if (r > 0 && V[r - 1][c] == '0' && min_dist_to_office[r - 1][c] == 1000) {\n            min_dist_to_office[r - 1][c] = min_dist_to_office[r][c] + 1;\n            q.push({r - 1, c});\n        }\n        // D: (r+1, c) -> (r, c) - Wall is V[r][c]\n        if (r < 19 && V[r][c] == '0' && min_dist_to_office[r + 1][c] == 1000) {\n            min_dist_to_office[r + 1][c] = min_dist_to_office[r][c] + 1;\n            q.push({r + 1, c});\n        }\n        // L: (r, c-1) -> (r, c) - Wall is H[r][c-1]\n        if (c > 0 && H[r][c - 1] == '0' && min_dist_to_office[r][c - 1] == 1000) {\n            min_dist_to_office[r][c - 1] = min_dist_to_office[r][c] + 1;\n            q.push({r, c - 1});\n        }\n        // R: (r, c+1) -> (r, c) - Wall is H[r][c]\n        if (c < 19 && H[r][c] == '0' && min_dist_to_office[r][c + 1] == 1000) {\n            min_dist_to_office[r][c + 1] = min_dist_to_office[r][c] + 1;\n            q.push({r, c + 1});\n        }\n    }\n}\n\n// Check if a move is possible in the given direction\nbool can_move(int r, int c, char dir) {\n    if (dir == 'U') return r > 0 && V[r - 1][c] == '0';\n    if (dir == 'D') return r < 19 && V[r][c] == '0';\n    if (dir == 'L') return c > 0 && H[r][c - 1] == '0';\n    if (dir == 'R') return c < 19 && H[r][c] == '0';\n    return false;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> Si >> Sj >> Ti >> Tj >> P)) return 0;\n    H.resize(20);\n    for (int i = 0; i < 20; ++i) cin >> H[i];\n    V.resize(19);\n    for (int i = 0; i < 19; ++i) cin >> V[i];\n\n    compute_min_dist();\n\n    // Beam search initialization\n    vector<State> beam;\n    State initial;\n    initial.path = \"\";\n    for (int i = 0; i < 20; ++i)\n        for (int j = 0; j < 20; ++j)\n            initial.dist[i][j] = 0.0;\n    initial.dist[Si][Sj] = 1.0;\n    initial.reward = 0.0;\n    initial.prob_reached = 0.0;\n    initial.heuristic = (double)min_dist_to_office[Si][Sj];\n    beam.push_back(initial);\n\n    int K = 400; // Beam width\n    for (int t = 1; t <= 200; ++t) {\n        vector<State> next_beam;\n        next_beam.reserve(beam.size() * 4);\n        for (const auto& s : beam) {\n            for (char dir : {'U', 'D', 'L', 'R'}) {\n                State next_s;\n                next_s.path = s.path + dir;\n                next_s.prob_reached = s.prob_reached;\n                next_s.reward = s.reward;\n                \n                double prob_reach_at_t = 0.0;\n                for (int i = 0; i < 20; ++i)\n                    for (int j = 0; j < 20; ++j)\n                        next_s.dist[i][j] = 0.0;\n\n                // Propagate probability distribution\n                for (int r = 0; r < 20; ++r) {\n                    for (int c = 0; c < 20; ++c) {\n                        if (s.dist[r][c] == 0) continue;\n                        \n                        // Forgetting: agent stays\n                        next_s.dist[r][c] += s.dist[r][c] * P;\n                        \n                        // Moving: attempts to move\n                        if (can_move(r, c, dir)) {\n                            int nr = r, nc = c;\n                            if (dir == 'U') nr--;\n                            else if (dir == 'D') nr++;\n                            else if (dir == 'L') nc--;\n                            else if (dir == 'R') nc++;\n                            \n                            // Check if reached office\n                            if (nr == Ti && nc == Tj) {\n                                prob_reach_at_t += s.dist[r][c] * (1.0 - P);\n                            } else {\n                                next_s.dist[nr][nc] += s.dist[r][c] * (1.0 - P);\n                            }\n                        } else {\n                            // Wall, stay\n                            next_s.dist[r][c] += s.dist[r][c] * (1.0 - P);\n                        }\n                    }\n                }\n                \n                next_s.prob_reached += prob_reach_at_t;\n                next_s.reward += prob_reach_at_t * (401.0 - t);\n                \n                // Heuristic: sum of dist[r][c] * min_dist_to_office[r][c]\n                double h = 0.0;\n                for (int r = 0; r < 20; ++r) {\n                    for (int c = 0; c < 20; ++c) {\n                        h += next_s.dist[r][c] * min_dist_to_office[r][c];\n                    }\n                }\n                next_s.heuristic = h;\n                \n                next_beam.push_back(next_s);\n            }\n        }\n        \n        // Keep top K sequences\n        sort(next_beam.begin(), next_beam.end(), [](const State& a, const State& b) {\n            if (abs(a.reward - b.reward) > 1e-9) return a.reward > b.reward;\n            if (abs(a.prob_reached - b.prob_reached) > 1e-9) return a.prob_reached > b.prob_reached;\n            return a.heuristic < b.heuristic;\n        });\n        \n        if (next_beam.size() > (size_t)K) {\n            next_beam.resize(K);\n        }\n        beam = next_beam;\n    }\n    \n    cout << beam[0].path << endl;\n    \n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <cstring>\n\nusing namespace std;\n\n// Tile connections for each tile type 0-7 at orientation 0\n// Directions: 0: Left, 1: Up, 2: Right, 3: Down\nint base_to[8][4] = {\n    {1, 0, -1, -1}, // Tile 0: Left <-> Up\n    {3, -1, -1, 0}, // Tile 1: Left <-> Down\n    {-1, -1, 3, 2}, // Tile 2: Right <-> Down\n    {-1, 2, 1, -1}, // Tile 3: Right <-> Up\n    {1, 0, 3, 2},   // Tile 4: Left <-> Up, Right <-> Down\n    {3, 2, 1, 0},   // Tile 5: Left <-> Down, Up <-> Right\n    {2, -1, 0, -1}, // Tile 6: Left <-> Right\n    {-1, 3, -1, 1}, // Tile 7: Up <-> Down\n};\n\n// Map direction based on tile rotation r (0, 1, 2, 3 rotations 90 deg CCW)\ninline int get_to(int type, int r, int d_new) {\n    int d_old = (d_new + r) % 4;\n    int d_old_exit = base_to[type][d_old];\n    if (d_old_exit == -1) return -1;\n    // Map back to the new coordinate system\n    return (d_old_exit - r + 4) % 4;\n}\n\nint N = 30;\nint tiles[30][30];\nint r[30][30];\nint di[4] = {0, -1, 0, 1}; // Left, Up, Right, Down\nint dj[4] = {-1, 0, 1, 0};\n\n// Visited array for cycle finding\nint visited[30][30][4];\n\nlong long calculate_score() {\n    memset(visited, 0, sizeof(visited));\n    vector<int> cycle_lengths;\n    \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                if (visited[i][j][d]) continue;\n                \n                int curr_i = i;\n                int curr_j = j;\n                int curr_d = d;\n                int length = 0;\n                bool closed = false;\n                \n                int path_i = curr_i;\n                int path_j = curr_j;\n                int path_d = curr_d;\n                \n                // Traverse the path\n                while (true) {\n                    int next_d = get_to(tiles[path_i][path_j], r[path_i][path_j], path_d);\n                    if (next_d == -1) break;\n                    \n                    visited[path_i][path_j][path_d] = 1;\n                    \n                    path_i += di[next_d];\n                    path_j += dj[next_d];\n                    \n                    if (path_i < 0 || path_i >= N || path_j < 0 || path_j >= N) break;\n                    \n                    path_d = (next_d + 2) % 4;\n                    length++;\n                    \n                    if (path_i == i && path_j == j && path_d == d) {\n                        closed = true;\n                        break;\n                    }\n                    if (visited[path_i][path_j][path_d]) break;\n                }\n                \n                if (closed) {\n                    cycle_lengths.push_back(length);\n                }\n            }\n        }\n    }\n    \n    if (cycle_lengths.size() < 2) return 0;\n    sort(cycle_lengths.rbegin(), cycle_lengths.rend());\n    return (long long)cycle_lengths[0] * cycle_lengths[1];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    for (int i = 0; i < N; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; ++j) {\n            tiles[i][j] = s[j] - '0';\n            r[i][j] = 0; \n        }\n    }\n    \n    long long current_score = calculate_score();\n    int best_r[30][30];\n    memcpy(best_r, r, sizeof(r));\n    long long best_score = current_score;\n    \n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    double time_limit = 1.95; \n    \n    int iterations = 0;\n    \n    // Simulated Annealing\n    while (true) {\n        if ((iterations & 1023) == 0) {\n            if (chrono::duration<double>(chrono::steady_clock::now() - start_time).count() > time_limit) break;\n        }\n        iterations++;\n        \n        int i = rng() % N;\n        int j = rng() % N;\n        int old_r = r[i][j];\n        r[i][j] = rng() % 4;\n        \n        long long new_score = calculate_score();\n        \n        // Simple cooling schedule\n        double T = 1000.0 * (1.0 - (double)iterations / 2000000.0);\n        double prob = (new_score > current_score) ? 1.0 : exp((double)(new_score - current_score) / (T + 1e-9));\n        \n        if (prob > (double)rng() / rng.max()) {\n            current_score = new_score;\n            if (current_score > best_score) {\n                best_score = current_score;\n                memcpy(best_r, r, sizeof(r));\n            }\n        } else {\n            r[i][j] = old_r;\n        }\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << best_r[i][j];\n        }\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Structure to represent the board\nstruct Board {\n    int N;\n    vector<int> tiles;\n    int empty_r, empty_c;\n\n    Board(int n, const vector<int>& t) : N(n), tiles(t) {\n        for (int i = 0; i < N * N; ++i) {\n            if (tiles[i] == 0) {\n                empty_r = i / N;\n                empty_c = i % N;\n            }\n        }\n    }\n\n    // Apply a sliding move\n    bool apply(char move) {\n        int r = empty_r, c = empty_c;\n        if (move == 'U') r++;\n        else if (move == 'D') r--;\n        else if (move == 'L') c++;\n        else if (move == 'R') c--;\n        else return false;\n\n        if (r < 0 || r >= N || c < 0 || c >= N) return false;\n\n        swap(tiles[empty_r * N + empty_c], tiles[r * N + c]);\n        empty_r = r;\n        empty_c = c;\n        return true;\n    }\n};\n\n// DSU to manage components and check for trees\nstruct DSU {\n    vector<int> parent;\n    vector<int> nodes;\n    vector<int> edges;\n\n    DSU(int n) {\n        parent.resize(n);\n        nodes.resize(n, 1);\n        edges.resize(n, 0);\n        for (int i = 0; i < n; ++i) parent[i] = i;\n    }\n\n    int find(int i) {\n        if (parent[i] == i) return i;\n        return parent[i] = find(parent[i]);\n    }\n\n    void unite(int i, int j) {\n        int root_i = find(i);\n        int root_j = find(j);\n        if (root_i != root_j) {\n            parent[root_j] = root_i;\n            nodes[root_i] += nodes[root_j];\n            edges[root_i] += edges[root_j] + 1;\n        } else {\n            edges[root_i]++;\n        }\n    }\n};\n\n// Calculate the size of the largest tree component\nint calculate_score(const Board& b) {\n    int N = b.N;\n    DSU dsu(N * N);\n    \n    // Set nodes to 0 for empty square (not part of the tree)\n    for (int i = 0; i < N * N; ++i) {\n        if (b.tiles[i] == 0) dsu.nodes[i] = 0;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int u = i * N + j;\n            if (b.tiles[u] == 0) continue;\n\n            // Check rightward connection\n            if (j + 1 < N && b.tiles[i * N + j + 1] != 0) {\n                if ((b.tiles[u] & 4) && (b.tiles[i * N + j + 1] & 1)) {\n                    dsu.unite(u, i * N + j + 1);\n                }\n            }\n            // Check downward connection\n            if (i + 1 < N && b.tiles[(i + 1) * N + j] != 0) {\n                if ((b.tiles[u] & 8) && (b.tiles[(i + 1) * N + j] & 2)) {\n                    dsu.unite(u, (i + 1) * N + j);\n                }\n            }\n        }\n    }\n\n    int max_s = 0;\n    for (int i = 0; i < N * N; ++i) {\n        if (dsu.parent[i] == i) {\n            // A component is a tree if it has V vertices and V-1 edges\n            if (dsu.edges[i] == dsu.nodes[i] - 1) {\n                max_s = max(max_s, dsu.nodes[i]);\n            }\n        }\n    }\n    return max_s;\n}\n\nint hex_to_int(char c) {\n    if (c >= '0' && c <= '9') return c - '0';\n    return c - 'a' + 10;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, T;\n    cin >> N >> T;\n    vector<int> tiles(N * N);\n    for (int i = 0; i < N; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; ++j) {\n            tiles[i * N + j] = hex_to_int(s[j]);\n        }\n    }\n\n    Board initial_board(N, tiles);\n    string best_moves = \"\";\n    int best_S = 0;\n\n    auto start_time = chrono::steady_clock::now();\n    mt19937 rng(42);\n    \n    // Hill Climbing with Random Restarts\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 2500) {\n        Board current_board = initial_board;\n        string current_moves = \"\";\n        int current_S = calculate_score(current_board);\n        \n        for (int i = 0; i < T; ++i) {\n            vector<char> moves = {'U', 'D', 'L', 'R'};\n            shuffle(moves.begin(), moves.end(), rng);\n            \n            bool found_improvement = false;\n            char best_move = ' ';\n            int best_next_S = -1;\n\n            for (char move : moves) {\n                // Prevent reversing the last move\n                if (!current_moves.empty()) {\n                    char last = current_moves.back();\n                    if ((move == 'U' && last == 'D') || (move == 'D' && last == 'U') ||\n                        (move == 'L' && last == 'R') || (move == 'R' && last == 'L')) continue;\n                }\n                \n                Board next_board = current_board;\n                if (!next_board.apply(move)) continue;\n                \n                int next_S = calculate_score(next_board);\n                if (next_S > current_S) {\n                    current_S = next_S;\n                    current_board = next_board;\n                    current_moves += move;\n                    found_improvement = true;\n                    break; // Greedy: take first improvement\n                }\n                if (next_S > best_next_S) {\n                    best_next_S = next_S;\n                    best_move = move;\n                }\n            }\n            \n            if (current_S == N * N - 1) break;\n            \n            if (!found_improvement) {\n                // If no improvement, pick the best move or a random move\n                if (best_next_S != -1) {\n                    current_board.apply(best_move);\n                    current_moves += best_move;\n                    current_S = best_next_S;\n                } else {\n                    char move = moves[rng() % 4];\n                    Board next_board = current_board;\n                    if (next_board.apply(move)) {\n                        current_board = next_board;\n                        current_moves += move;\n                        current_S = calculate_score(current_board);\n                    }\n                }\n            }\n        }\n        \n        if (current_S > best_S) {\n            best_S = current_S;\n            best_moves = current_moves;\n        }\n        \n        if (best_S == N * N - 1) break;\n    }\n    \n    cout << best_moves << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent a point\nstruct Point {\n    long long x, y;\n};\n\n// Structure to represent a line: ax + by + c = 0\nstruct Line {\n    long long a, b, c;\n    Point p1, p2;\n};\n\n// Global data\nint N, K;\nvector<int> a(11);\nvector<Point> strawberries;\nmt19937 rng(1337);\n\n// Function to calculate the score: sum(min(a_d, b_d))\nint calculate_score(const vector<int>& piece_counts) {\n    vector<int> b(11, 0);\n    for (int count : piece_counts) {\n        if (count >= 1 && count <= 10) {\n            b[count]++;\n        }\n    }\n    int score = 0;\n    for (int d = 1; d <= 10; ++d) {\n        score += min(a[d], b[d]);\n    }\n    return score;\n}\n\n// Generate a random line that intersects the cake\nLine generate_random_line() {\n    // Generate points within [-20000, 20000] to cover the cake radius of 10000\n    uniform_int_distribution<long long> dist(-20000, 20000);\n    while (true) {\n        Point p1 = {dist(rng), dist(rng)};\n        Point p2 = {dist(rng), dist(rng)};\n        if (p1.x == p2.x && p1.y == p2.y) continue;\n\n        // Line equation: (y1 - y2)x + (x2 - x1)y + (x1y2 - x2y1) = 0\n        long long a = p1.y - p2.y;\n        long long b = p2.x - p1.x;\n        long long c = -a * p1.x - b * p1.y;\n\n        // Check if the line cuts the cake (distance from origin < 10000)\n        __int128 c2 = (__int128)c * c;\n        __int128 dist2 = (__int128)a * a + (__int128)b * b;\n        if (c2 < (__int128)100000000 * dist2) {\n            return {a, b, c, p1, p2};\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N >> K)) return 0;\n    for (int i = 1; i <= 10; ++i) cin >> a[i];\n    strawberries.resize(N);\n    for (int i = 0; i < N; ++i) cin >> strawberries[i].x >> strawberries[i].y;\n\n    // current_piece_id[i] stores the ID of the piece that strawberry i belongs to\n    vector<int> current_piece_id(N, 0);\n    int num_pieces = 1;\n    vector<Line> lines;\n\n    for (int k = 0; k < K; ++k) {\n        int best_score = -1;\n        Line best_line;\n        bool found = false;\n\n        // Try 1000 random lines and pick the best one\n        for (int trial = 0; trial < 1000; ++trial) {\n            Line line = generate_random_line();\n            \n            // Piece split: how many strawberries in each piece fall on the left/right side\n            // piece_split[p_id].first = count on left, .second = count on right\n            vector<pair<int, int>> piece_split(num_pieces, {0, 0});\n            for (int i = 0; i < N; ++i) {\n                if (current_piece_id[i] == -1) continue;\n                long long val = line.a * strawberries[i].x + line.b * strawberries[i].y + line.c;\n                if (val > 0) piece_split[current_piece_id[i]].second++;\n                else if (val < 0) piece_split[current_piece_id[i]].first++;\n                // val == 0 means the strawberry is on the line (removed)\n            }\n\n            vector<int> next_piece_counts;\n            for (int p = 0; p < num_pieces; ++p) {\n                if (piece_split[p].first > 0) next_piece_counts.push_back(piece_split[p].first);\n                if (piece_split[p].second > 0) next_piece_counts.push_back(piece_split[p].second);\n            }\n\n            int score = calculate_score(next_piece_counts);\n            if (score > best_score) {\n                best_score = score;\n                best_line = line;\n                found = true;\n            }\n        }\n        \n        if (found) {\n            lines.push_back(best_line);\n            \n            // Update current_piece_id mapping for all strawberries\n            vector<int> next_piece_id(N, -1);\n            // new_id_map[old_piece_id][side] -> new_piece_id\n            vector<vector<int>> new_id_map(num_pieces, vector<int>(2, -1));\n            int next_num_pieces = 0;\n\n            for (int i = 0; i < N; ++i) {\n                if (current_piece_id[i] == -1) continue;\n                long long val = best_line.a * strawberries[i].x + best_line.b * strawberries[i].y + best_line.c;\n                if (val == 0) continue; // Strawberry removed\n                \n                int side = (val > 0) ? 1 : 0;\n                int p = current_piece_id[i];\n                \n                if (new_id_map[p][side] == -1) {\n                    new_id_map[p][side] = next_num_pieces++;\n                }\n                next_piece_id[i] = new_id_map[p][side];\n            }\n            current_piece_id = next_piece_id;\n            num_pieces = next_num_pieces;\n        } else {\n            // No improvement found, stop cutting\n            break;\n        }\n    }\n\n    // Output the result\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line.p1.x << \" \" << line.p1.y << \" \" << line.p2.x << \" \" << line.p2.y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nint N, M;\nvector<vector<bool>> has_dot;\nvector<vector<vector<bool>>> used_seg; // 0: horiz, 1: vert, 2: diag1, 3: diag2\n\nint weight(int x, int y) {\n    int cx = (N - 1) / 2;\n    int cy = (N - 1) / 2;\n    return (x - cx) * (x - cx) + (y - cy) * (y - cy) + 1;\n}\n\nbool is_valid(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool is_segment_used(int x1, int y1, int x2, int y2) {\n    int dx = x2 - x1;\n    int dy = y2 - y1;\n    if (dy == 0) { // horiz\n        int x = min(x1, x2);\n        return used_seg[0][x][y1];\n    } else if (dx == 0) { // vert\n        int y = min(y1, y2);\n        return used_seg[1][x1][y];\n    } else if (dx == dy) { // diag1 (slope 1)\n        int x = min(x1, x2);\n        int y = min(y1, y2);\n        return used_seg[2][x][y];\n    } else { // diag2 (slope -1)\n        int x = min(x1, x2);\n        int y = max(y1, y2);\n        return used_seg[3][x][y - 1];\n    }\n}\n\nvoid mark_segment(int x1, int y1, int x2, int y2) {\n    int dx = x2 - x1;\n    int dy = y2 - y1;\n    if (dy == 0) {\n        int x = min(x1, x2);\n        used_seg[0][x][y1] = true;\n    } else if (dx == 0) {\n        int y = min(y1, y2);\n        used_seg[1][x1][y] = true;\n    } else if (dx == dy) {\n        int x = min(x1, x2);\n        int y = min(y1, y2);\n        used_seg[2][x][y] = true;\n    } else {\n        int x = min(x1, x2);\n        int y = max(y1, y2);\n        used_seg[3][x][y - 1] = true;\n    }\n}\n\n// Checks if any unit segment on the line between p1 and p2 is used\nbool is_path_used(int x1, int y1, int x2, int y2) {\n    int dx = (x2 > x1) ? 1 : ((x2 < x1) ? -1 : 0);\n    int dy = (y2 > y1) ? 1 : ((y2 < y1) ? -1 : 0);\n    int dist = max(abs(x2 - x1), abs(y2 - y1));\n    for (int i = 0; i < dist; ++i) {\n        if (is_segment_used(x1 + i * dx, y1 + i * dy, x1 + (i + 1) * dx, y1 + (i + 1) * dy)) return true;\n    }\n    return false;\n}\n\n// Checks if any dot exists on the path between p1 and p2 (excluding endpoints)\nbool is_path_clear(int x1, int y1, int x2, int y2, const Point& p_ex1, const Point& p_ex2, const Point& p_ex3) {\n    int dx = (x2 > x1) ? 1 : ((x2 < x1) ? -1 : 0);\n    int dy = (y2 > y1) ? 1 : ((y2 < y1) ? -1 : 0);\n    int dist = max(abs(x2 - x1), abs(y2 - y1));\n    for (int i = 1; i < dist; ++i) {\n        int cx = x1 + i * dx, cy = y1 + i * dy;\n        if ((cx == p_ex1.x && cy == p_ex1.y) || (cx == p_ex2.x && cy == p_ex2.y) || (cx == p_ex3.x && cy == p_ex3.y)) continue;\n        if (has_dot[cx][cy]) return false;\n    }\n    return true;\n}\n\nbool check_rect(Point p1, Point p2, Point p3, Point p4) {\n    if (!is_valid(p1.x, p1.y) || !is_valid(p2.x, p2.y) || !is_valid(p3.x, p3.y) || !is_valid(p4.x, p4.y)) return false;\n    if (has_dot[p1.x][p1.y] || !has_dot[p2.x][p2.y] || !has_dot[p3.x][p3.y] || !has_dot[p4.x][p4.y]) return false;\n    \n    // Check perimeter segments\n    if (is_path_used(p1.x, p1.y, p2.x, p2.y) || is_path_used(p2.x, p2.y, p3.x, p3.y) ||\n        is_path_used(p3.x, p3.y, p4.x, p4.y) || is_path_used(p4.x, p4.y, p1.x, p1.y)) return false;\n    \n    // Check dots on perimeter\n    if (!is_path_clear(p1.x, p1.y, p2.x, p2.y, p2, p3, p4) || !is_path_clear(p2.x, p2.y, p3.x, p3.y, p2, p3, p4) ||\n        !is_path_clear(p3.x, p3.y, p4.x, p4.y, p2, p3, p4) || !is_path_clear(p4.x, p4.y, p1.x, p1.y, p2, p3, p4)) return false;\n    \n    return true;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    cin >> N >> M;\n    has_dot.assign(N, vector<bool>(N, false));\n    used_seg.assign(4, vector<vector<bool>>(N + 1, vector<bool>(N + 1, false)));\n    for (int i = 0; i < M; ++i) {\n        int x, y; cin >> x >> y;\n        has_dot[x][y] = true;\n    }\n\n    struct Op { Point p1, p2, p3, p4; };\n    vector<Op> ops;\n\n    while (true) {\n        Op best_op;\n        int max_w = -1;\n        bool found = false;\n\n        for (int x1 = 0; x1 < N; ++x1) {\n            for (int y1 = 0; y1 < N; ++y1) {\n                if (has_dot[x1][y1]) continue;\n                \n                // Parallel\n                for (int x2 = 0; x2 < N; ++x2) {\n                    if (x2 == x1) continue;\n                    for (int y2 = 0; y2 < N; ++y2) {\n                        if (y2 == y1) continue;\n                        Point p2 = {x2, y1}, p4 = {x1, y2}, p3 = {x2, y2};\n                        if (check_rect({x1, y1}, p2, p3, p4)) {\n                            if (weight(x1, y1) > max_w) {\n                                max_w = weight(x1, y1);\n                                best_op = {{x1, y1}, p2, p3, p4};\n                                found = true;\n                            }\n                        }\n                    }\n                }\n                // 45-degree\n                for (int k = -(N - 1); k < N; ++k) {\n                    if (k == 0) continue;\n                    for (int m = -(N - 1); m < N; ++m) {\n                        if (m == 0 || k == m || k == -m) continue;\n                        Point p2 = {x1 + k, y1 + k}, p4 = {x1 - m, y1 + m}, p3 = {x1 + k - m, y1 + k + m};\n                        if (check_rect({x1, y1}, p2, p3, p4)) {\n                            if (weight(x1, y1) > max_w) {\n                                max_w = weight(x1, y1);\n                                best_op = {{x1, y1}, p2, p3, p4};\n                                found = true;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        if (!found) break;\n        \n        has_dot[best_op.p1.x][best_op.p1.y] = true;\n        auto add_seg = [&](Point a, Point b) {\n            int dx = (b.x > a.x) ? 1 : ((b.x < a.x) ? -1 : 0);\n            int dy = (b.y > a.y) ? 1 : ((b.y < a.y) ? -1 : 0);\n            int dist = max(abs(b.x - a.x), abs(b.y - a.y));\n            for (int i = 0; i < dist; ++i) mark_segment(a.x + i * dx, a.y + i * dy, a.x + (i + 1) * dx, a.y + (i + 1) * dy);\n        };\n        add_seg(best_op.p1, best_op.p2); add_seg(best_op.p2, best_op.p3);\n        add_seg(best_op.p3, best_op.p4); add_seg(best_op.p4, best_op.p1);\n        ops.push_back(best_op);\n    }\n\n    cout << ops.size() << endl;\n    for (auto& o : ops) cout << o.p1.x << \" \" << o.p1.y << \" \" << o.p2.x << \" \" << o.p2.y << \" \" << o.p3.x << \" \" << o.p3.y << \" \" << o.p4.x << \" \" << o.p4.y << endl;\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <queue>\n\nusing namespace std;\n\n// Global state for visited to avoid repeated allocation\nint visited[10][10] = {0};\nint cookie = 0;\n\nstruct State {\n    int board[10][10];\n    State() {\n        for (int i = 0; i < 10; ++i)\n            for (int j = 0; j < 10; ++j)\n                board[i][j] = 0;\n    }\n};\n\n// Optimized BFS for calculating sum of squares of connected component sizes\nint calculate_score(const State& s) {\n    cookie++;\n    int total_score = 0;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            if (s.board[r][c] != 0 && visited[r][c] != cookie) {\n                int flavor = s.board[r][c];\n                int size = 0;\n                static pair<int, int> q[100];\n                int head = 0, tail = 0;\n                q[tail++] = {r, c};\n                visited[r][c] = cookie;\n                while(head < tail){\n                    auto [curr_r, curr_c] = q[head++];\n                    size++;\n                    int dr[] = {-1, 1, 0, 0};\n                    int dc[] = {0, 0, -1, 1};\n                    for(int i=0; i<4; ++i){\n                        int nr = curr_r + dr[i];\n                        int nc = curr_c + dc[i];\n                        if(nr >= 0 && nr < 10 && nc >= 0 && nc < 10 && visited[nr][nc] != cookie && s.board[nr][nc] == flavor){\n                            visited[nr][nc] = cookie;\n                            q[tail++] = {nr, nc};\n                        }\n                    }\n                }\n                total_score += size * size;\n            }\n        }\n    }\n    return total_score;\n}\n\n// Applies the tilt operation to the board state\nState apply_tilt(State s, char dir) {\n    if (dir == 'F') { // Move towards top\n        for (int c = 0; c < 10; ++c) {\n            int write_r = 0;\n            for (int r = 0; r < 10; ++r) {\n                if (s.board[r][c] != 0) {\n                    int flavor = s.board[r][c];\n                    s.board[r][c] = 0;\n                    s.board[write_r][c] = flavor;\n                    write_r++;\n                }\n            }\n        }\n    } else if (dir == 'B') { // Move towards bottom\n        for (int c = 0; c < 10; ++c) {\n            int write_r = 9;\n            for (int r = 9; r >= 0; --r) {\n                if (s.board[r][c] != 0) {\n                    int flavor = s.board[r][c];\n                    s.board[r][c] = 0;\n                    s.board[write_r][c] = flavor;\n                    write_r--;\n                }\n            }\n        }\n    } else if (dir == 'L') { // Move towards left\n        for (int r = 0; r < 10; ++r) {\n            int write_c = 0;\n            for (int c = 0; c < 10; ++c) {\n                if (s.board[r][c] != 0) {\n                    int flavor = s.board[r][c];\n                    s.board[r][c] = 0;\n                    s.board[r][write_c] = flavor;\n                    write_c++;\n                }\n            }\n        }\n    } else if (dir == 'R') { // Move towards right\n        for (int r = 0; r < 10; ++r) {\n            int write_c = 9;\n            for (int c = 9; c >= 0; --c) {\n                if (s.board[r][c] != 0) {\n                    int flavor = s.board[r][c];\n                    s.board[r][c] = 0;\n                    s.board[r][write_c] = flavor;\n                    write_c--;\n                }\n            }\n        }\n    }\n    return s;\n}\n\n// Finds all empty cells in the board\nvector<int> get_empty_cells(const State& s) {\n    vector<int> empty_cells;\n    empty_cells.reserve(100);\n    for (int r = 0; r < 10; ++r)\n        for (int c = 0; c < 10; ++c)\n            if (s.board[r][c] == 0)\n                empty_cells.push_back(r * 10 + c);\n    return empty_cells;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    vector<int> f(100);\n    for (int i = 0; i < 100; ++i) cin >> f[i];\n\n    State current_state;\n    mt19937 rng(12345);\n\n    // Loop through each of the 100 turns\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        cin >> p;\n        vector<int> empty_cells = get_empty_cells(current_state);\n        int cell = empty_cells[p - 1];\n        current_state.board[cell / 10][cell % 10] = f[t];\n\n        if (t == 99) break; // No tilt needed for the last candy\n\n        char directions[] = {'F', 'B', 'L', 'R'};\n        double best_score = -1.0;\n        char best_dir = 'F';\n\n        // Choose best direction by looking ahead using rollouts\n        for (char dir : directions) {\n            State next_state = apply_tilt(current_state, dir);\n            \n            double total_sim_score = 0;\n            int num_rollouts = 30; // Number of simulations per direction\n            for (int r = 0; r < num_rollouts; ++r) {\n                State sim_state = next_state;\n                for (int sim_t = t + 1; sim_t < 100; ++sim_t) {\n                    vector<int> sim_empty = get_empty_cells(sim_state);\n                    uniform_int_distribution<int> dist(0, (int)sim_empty.size() - 1);\n                    int sim_p = sim_empty[dist(rng)];\n                    sim_state.board[sim_p / 10][sim_p % 10] = f[sim_t];\n                    \n                    uniform_int_distribution<int> dir_dist(0, 3);\n                    char sim_dir = directions[dir_dist(rng)];\n                    sim_state = apply_tilt(sim_state, sim_dir);\n                }\n                total_sim_score += calculate_score(sim_state);\n            }\n            if (total_sim_score > best_score) {\n                best_score = total_sim_score;\n                best_dir = dir;\n            }\n        }\n        cout << best_dir << endl;\n        current_state = apply_tilt(current_state, best_dir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Structure to hold graph information\nstruct Graph {\n    int id;\n    int clique_size;\n    vector<int> degree_seq;\n    string edges;\n};\n\nint main() {\n    // Optimization for speed\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n\n    // Determine N. N should be at least M, but also >= 4 and >= 20 for robustness.\n    // N <= 100.\n    int N = max({4, M, 20});\n    if (N > 100) N = 100;\n\n    cout << N << endl;\n\n    vector<Graph> graphs(M);\n    for (int k = 0; k < M; ++k) {\n        graphs[k].id = k;\n        \n        // We choose clique sizes spread between 1 and N.\n        // For M=1, clique size is 1.\n        // For M>1, spread them linearly from 1 to N.\n        if (M == 1) {\n            graphs[k].clique_size = 1;\n        } else {\n            graphs[k].clique_size = 1 + (int)((double)k * (N - 1) / (M - 1));\n        }\n\n        int c = graphs[k].clique_size;\n        \n        // Generate edge string and degree sequence\n        string s = \"\";\n        vector<int> deg(N, 0);\n        for (int i = 0; i < N - 1; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                // Clique of size c: edges only exist between vertices < c\n                if (i < c && j < c) {\n                    s += '1';\n                    deg[i]++;\n                    deg[j]++;\n                } else {\n                    s += '0';\n                }\n            }\n        }\n        graphs[k].edges = s;\n        sort(deg.begin(), deg.end());\n        graphs[k].degree_seq = deg;\n    }\n\n    // Output the generated graphs\n    for (int k = 0; k < M; ++k) {\n        cout << graphs[k].edges << endl;\n    }\n\n    // Process 100 queries\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // Compute degree sequence of H_k\n        vector<int> degH(N, 0);\n        int idx = 0;\n        for (int i = 0; i < N - 1; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (H[idx] == '1') {\n                    degH[i]++;\n                    degH[j]++;\n                }\n                idx++;\n            }\n        }\n        sort(degH.begin(), degH.end());\n\n        // Find the graph whose degree sequence is closest to H_k's\n        int best_k = 0;\n        long long min_dist = -1;\n        for (int k = 0; k < M; ++k) {\n            long long dist = 0;\n            for (int i = 0; i < N; ++i) {\n                long long diff = (long long)graphs[k].degree_seq[i] - degH[i];\n                dist += diff * diff;\n            }\n            if (min_dist == -1 || dist < min_dist) {\n                min_dist = dist;\n                best_k = k;\n            }\n        }\n        cout << best_k << endl;\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <ctime>\n\nusing namespace std;\n\n// Structure to represent an edge\nstruct Edge {\n    int u, v, w, id;\n};\n\n// Structure for predecessors in shortest path\nstruct Predecessor {\n    int u;\n    int edge_id;\n};\n\nint N, M, D, K;\nvector<vector<pair<int, pair<int, int>>>> adj;\nvector<Edge> edges;\nvector<double> edge_bc;\nvector<double> edge_cost;\n\n// Compute Betweenness Centrality using Brandes' algorithm\n// Suitable for N=1000, M=3000.\nvoid compute_bc() {\n    edge_bc.assign(M, 0.0);\n    for (int s = 0; s < N; ++s) {\n        vector<long long> dist(N + 1, 1e18);\n        vector<double> sigma(N + 1, 0.0);\n        vector<vector<Predecessor>> predecessors(N + 1);\n        vector<int> order;\n        \n        dist[s + 1] = 0;\n        sigma[s + 1] = 1.0;\n        \n        priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n        pq.push({0, s + 1});\n        \n        while (!pq.empty()) {\n            long long d = pq.top().first;\n            int u = pq.top().second;\n            pq.pop();\n            \n            if (d > dist[u]) continue;\n            order.push_back(u);\n            \n            for (auto& edge : adj[u]) {\n                int v = edge.first;\n                int weight = edge.second.first;\n                int id = edge.second.second;\n                \n                if (dist[v] > dist[u] + weight) {\n                    dist[v] = dist[u] + weight;\n                    sigma[v] = sigma[u];\n                    predecessors[v].clear();\n                    predecessors[v].push_back({u, id});\n                    pq.push({dist[v], v});\n                } else if (dist[v] == dist[u] + weight) {\n                    sigma[v] += sigma[u];\n                    predecessors[v].push_back({u, id});\n                }\n            }\n        }\n        \n        vector<double> delta(N + 1, 0.0);\n        for (int i = order.size() - 1; i >= 0; --i) {\n            int w = order[i];\n            for (auto& pred : predecessors[w]) {\n                int v = pred.u;\n                int edge_id = pred.edge_id;\n                \n                double coeff = (sigma[v] / sigma[w]) * (1.0 + delta[w]);\n                delta[v] += coeff;\n                edge_bc[edge_id] += coeff;\n            }\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> D >> K;\n    adj.resize(N + 1);\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges[i] = {u, v, w, i};\n        adj[u].push_back({v, {w, i}});\n        adj[v].push_back({u, {w, i}});\n    }\n    \n    // Read coordinates (not strictly needed for BC, but input format requires it)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    compute_bc();\n    \n    // Define cost: BC * weight balances both edge centrality and edge length\n    edge_cost.resize(M);\n    for (int i = 0; i < M; ++i) {\n        edge_cost[i] = edge_bc[i] * edges[i].w;\n    }\n    \n    // Initial assignment using snake distribution (zig-zagging through days)\n    vector<int> edge_indices(M);\n    for (int i = 0; i < M; ++i) edge_indices[i] = i;\n    \n    sort(edge_indices.begin(), edge_indices.end(), [&](int a, int b) {\n        return edge_cost[a] > edge_cost[b];\n    });\n    \n    vector<int> schedule(M);\n    vector<vector<int>> days(D + 1);\n    vector<double> sum_cost(D + 1, 0.0);\n    \n    for (int i = 0; i < M; ++i) {\n        int day = (i / D) % 2 == 0 ? (i % D) + 1 : D - (i % D);\n        schedule[edge_indices[i]] = day;\n        days[day].push_back(edge_indices[i]);\n        sum_cost[day] += edge_cost[edge_indices[i]];\n    }\n    \n    // Local Search: Greedy Hill Climbing to minimize cost variance\n    mt19937 rng(42);\n    double start_time = clock();\n    double time_limit = 5.5 * CLOCKS_PER_SEC;\n    \n    while (clock() - start_time < time_limit) {\n        int d1 = (rng() % D) + 1;\n        int d2 = (rng() % D) + 1;\n        if (d1 == d2 || days[d1].empty() || days[d2].empty()) continue;\n        \n        int idx1 = rng() % days[d1].size();\n        int idx2 = rng() % days[d2].size();\n        \n        int e1 = days[d1][idx1];\n        int e2 = days[d2][idx2];\n        \n        // Calculate impact on variance\n        double current_sum_sq = 0;\n        for(int d=1; d<=D; ++d) current_sum_sq += sum_cost[d] * sum_cost[d];\n        \n        double new_sum_cost_d1 = sum_cost[d1] - edge_cost[e1] + edge_cost[e2];\n        double new_sum_cost_d2 = sum_cost[d2] - edge_cost[e2] + edge_cost[e1];\n        \n        double new_sum_sq = current_sum_sq - sum_cost[d1]*sum_cost[d1] - sum_cost[d2]*sum_cost[d2]\n                        + new_sum_cost_d1*new_sum_cost_d1 + new_sum_cost_d2*new_sum_cost_d2;\n        \n        // Greedy acceptance if swap improves balance\n        if (new_sum_sq < current_sum_sq) {\n            sum_cost[d1] = new_sum_cost_d1;\n            sum_cost[d2] = new_sum_cost_d2;\n            days[d1][idx1] = e2;\n            days[d2][idx2] = e1;\n            schedule[e1] = d2;\n            schedule[e2] = d1;\n        }\n    }\n    \n    for (int i = 0; i < M; ++i) {\n        cout << schedule[i] << (i == M - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n};\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int D;\n    if (!(cin >> D)) return 0;\n\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for (int i = 0; i < D; ++i) cin >> f1[i];\n    for (int i = 0; i < D; ++i) cin >> r1[i];\n    for (int i = 0; i < D; ++i) cin >> f2[i];\n    for (int i = 0; i < D; ++i) cin >> r2[i];\n\n    // Compute maximum possible objects M1 and M2\n    auto get_max_obj = [&](const vector<string>& f, const vector<string>& r) {\n        vector<vector<vector<int>>> obj(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[z][x] == '1' && r[z][y] == '1') {\n                        obj[x][y][z] = 1;\n                    }\n                }\n            }\n        }\n        return obj;\n    };\n\n    auto M1 = get_max_obj(f1, r1);\n    auto M2 = get_max_obj(f2, r2);\n\n    // Compute intersection I, and unique parts U1, U2\n    vector<vector<vector<int>>> I(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> U1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> U2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n\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 (M1[x][y][z] && M2[x][y][z]) I[x][y][z] = 1;\n                else if (M1[x][y][z]) U1[x][y][z] = 1;\n                else if (M2[x][y][z]) U2[x][y][z] = 1;\n            }\n        }\n    }\n\n    vector<vector<vector<int>>> b1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> b2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n\n    int block_id = 1;\n\n    // BFS to find connected components and assign unique block IDs\n    auto find_components = [&](vector<vector<vector<int>>>& grid, int& id_counter, vector<vector<vector<int>>>& b_map) {\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\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 (grid[x][y][z] && !visited[x][y][z]) {\n                        queue<Point> q;\n                        q.push({x, y, z});\n                        visited[x][y][z] = true;\n                        b_map[x][y][z] = id_counter;\n                        \n                        int dx[] = {1, -1, 0, 0, 0, 0};\n                        int dy[] = {0, 0, 1, -1, 0, 0};\n                        int dz[] = {0, 0, 0, 0, 1, -1};\n                        \n                        while (!q.empty()) {\n                            Point curr = q.front();\n                            q.pop();\n\n                            for (int i = 0; i < 6; ++i) {\n                                int nx = curr.x + dx[i];\n                                int ny = curr.y + dy[i];\n                                int nz = curr.z + dz[i];\n                                if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                    grid[nx][ny][nz] && !visited[nx][ny][nz]) {\n                                    visited[nx][ny][nz] = true;\n                                    b_map[nx][ny][nz] = id_counter;\n                                    q.push({nx, ny, nz});\n                                }\n                            }\n                        }\n                        id_counter++;\n                    }\n                }\n            }\n        }\n    };\n\n    // 1. Process intersection (shared)\n    find_components(I, block_id, b1);\n    for(int x=0; x<D; ++x) for(int y=0; y<D; ++y) for(int z=0; z<D; ++z) b2[x][y][z] = b1[x][y][z];\n    \n    // 2. Process unique parts for object 1\n    find_components(U1, block_id, b1);\n    // 3. Process unique parts for object 2\n    find_components(U2, block_id, b2);\n\n    // Output result\n    cout << block_id - 1 << endl;\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 << b1[x][y][z] << (x == D - 1 && y == D - 1 && z == D - 1 ? \"\" : \" \");\n            }\n        }\n    }\n    cout << endl;\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 << b2[x][y][z] << (x == D - 1 && y == D - 1 && z == D - 1 ? \"\" : \" \");\n            }\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <queue>\n\nusing namespace std;\n\n// Structure for Edge\nstruct Edge {\n    int u, v, w, id;\n};\n\n// Structure for Point\nstruct Point {\n    int x, y;\n};\n\nint N, M, K;\nvector<Point> stations;\nvector<Point> residents;\nvector<Edge> edges;\nvector<vector<pair<int, int>>> adj; // adj[u] = {(v, edge_index), ...}\n\n// Precomputed distances\nvector<vector<double>> station_resident_dist;\n\n// MST structures\nvector<int> parent_node;\nvector<int> parent_edge_idx;\nvector<vector<int>> path_to_root;\n\n// Structure for Cost Result\nstruct CostResult {\n    long long total_cost;\n    vector<int> P;\n    vector<int> B;\n};\n\nvoid build_mst() {\n    vector<int> min_weight(N + 1, 2e9);\n    vector<bool> visited(N + 1, false);\n    parent_node.assign(N + 1, -1);\n    parent_edge_idx.assign(N + 1, -1);\n    \n    min_weight[1] = 0;\n    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n    pq.push({0, 1});\n\n    while (!pq.empty()) {\n        int u = pq.top().second;\n        pq.pop();\n        if (visited[u]) continue;\n        visited[u] = true;\n\n        for (auto& edge : adj[u]) {\n            int v = edge.first;\n            int edge_idx = edge.second;\n            int w = edges[edge_idx].w;\n            if (!visited[v] && w < min_weight[v]) {\n                min_weight[v] = w;\n                parent_node[v] = u;\n                parent_edge_idx[v] = edge_idx;\n                pq.push({w, v});\n            }\n        }\n    }\n    \n    path_to_root.resize(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        int curr = i;\n        while (parent_node[curr] != -1) {\n            path_to_root[i].push_back(parent_edge_idx[curr]);\n            curr = parent_node[curr];\n        }\n    }\n}\n\n// Function to calculate total cost for a given V_active\nCostResult calculate_cost(const vector<bool>& v_active) {\n    vector<int> active_nodes;\n    for (int i = 1; i <= N; ++i) if (v_active[i]) active_nodes.push_back(i);\n    \n    vector<int> assignment(K);\n    vector<int> P(N + 1, 0);\n    \n    // Assign residents to nearest active station\n    for (int k = 0; k < K; ++k) {\n        double min_d = 1e18;\n        int best_node = -1;\n        for (int node : active_nodes) {\n            if (station_resident_dist[node][k] < min_d) {\n                min_d = station_resident_dist[node][k];\n                best_node = node;\n            }\n        }\n        assignment[k] = best_node;\n    }\n    \n    // Calculate required output strength P[i] for each active station\n    for (int k = 0; k < K; ++k) {\n        int node = assignment[k];\n        double d = station_resident_dist[node][k];\n        P[node] = max(P[node], (int)ceil(d));\n    }\n    \n    long long radio_cost = 0;\n    for (int i = 1; i <= N; ++i) {\n        radio_cost += (long long)P[i] * P[i];\n    }\n    \n    vector<int> B(M, 0);\n    long long edge_cost = 0;\n    vector<bool> edge_active(M, false);\n    \n    // Mark edges needed to connect all active stations to 1\n    for (int node : active_nodes) {\n        for (int edge_idx : path_to_root[node]) {\n            if (!edge_active[edge_idx]) {\n                edge_active[edge_idx] = true;\n                edge_cost += edges[edge_idx].w;\n                B[edge_idx] = 1;\n            }\n        }\n    }\n    \n    return {radio_cost + edge_cost, P, B};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N >> M >> K;\n    stations.resize(N + 1);\n    for (int i = 1; i <= N; ++i) cin >> stations[i].x >> stations[i].y;\n    \n    adj.resize(N + 1);\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges[i] = {u, v, w, i};\n        adj[u].push_back({v, i});\n        adj[v].push_back({u, i});\n    }\n    \n    residents.resize(K);\n    for (int k = 0; k < K; ++k) cin >> residents[k].x >> residents[k].y;\n    \n    station_resident_dist.resize(N + 1, vector<double>(K));\n    for (int i = 1; i <= N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            station_resident_dist[i][k] = sqrt(pow(stations[i].x - residents[k].x, 2) + pow(stations[i].y - residents[k].y, 2));\n        }\n    }\n    \n    build_mst();\n    \n    vector<bool> v_active(N + 1, false);\n    // Start with just node 1 as active\n    v_active[1] = true;\n    \n    CostResult current = calculate_cost(v_active);\n    \n    // Greedy search loop\n    while (true) {\n        long long best_cost = current.total_cost;\n        int best_action = -1; // 1000 + v for add, -v for remove\n        \n        // Try adding each inactive node\n        for (int i = 1; i <= N; ++i) {\n            if (!v_active[i]) {\n                v_active[i] = true;\n                CostResult next = calculate_cost(v_active);\n                if (next.total_cost < best_cost) {\n                    best_cost = next.total_cost;\n                    best_action = 1000 + i;\n                }\n                v_active[i] = false;\n            }\n        }\n        \n        // Try removing each active node (except node 1)\n        for (int i = 2; i <= N; ++i) {\n            if (v_active[i]) {\n                v_active[i] = false;\n                CostResult next = calculate_cost(v_active);\n                if (next.total_cost < best_cost) {\n                    best_cost = next.total_cost;\n                    best_action = -i;\n                }\n                v_active[i] = true;\n            }\n        }\n        \n        if (best_action == -1) break;\n        \n        if (best_action >= 1000) {\n            v_active[best_action - 1000] = true;\n        } else {\n            v_active[-best_action] = false;\n        }\n        current = calculate_cost(v_active);\n    }\n    \n    // Output result\n    for (int i = 1; i <= N; ++i) cout << current.P[i] << (i == N ? \"\" : \" \");\n    cout << endl;\n    for (int i = 0; i < M; ++i) cout << current.B[i] << (i == M - 1 ? \"\" : \" \");\n    cout << endl;\n    \n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n\nusing namespace std;\n\n// The number of pyramid tiers is fixed to N=30.\nconstexpr int N = 30;\nint initial_board[N][N];\nint current_board[N][N];\n\n// Structure to store swap operations\nstruct SwapOp {\n    int x1, y1, x2, y2;\n    // Overload == for redundancy check (swaps are symmetric)\n    bool operator==(const SwapOp& other) const {\n        auto p1 = make_pair(x1, y1);\n        auto p2 = make_pair(x2, y2);\n        if (p1 > p2) swap(p1, p2);\n        \n        auto op1 = make_pair(other.x1, other.y1);\n        auto op2 = make_pair(other.x2, other.y2);\n        if (op1 > op2) swap(op1, op2);\n        \n        return p1 == op1 && p2 == op2;\n    }\n};\n\n// Function to perform a swap on the current_board\nvoid perform_swap(int x1, int y1, int x2, int y2, vector<SwapOp>& ops) {\n    swap(current_board[x1][y1], current_board[x2][y2]);\n    ops.push_back({x1, y1, x2, y2});\n}\n\n// Function to build the heap\nint build_heap(vector<SwapOp>& ops, mt19937& rng) {\n    // Reset board\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            current_board[i][j] = initial_board[i][j];\n        }\n    }\n    ops.clear();\n\n    // Build-Heap algorithm (bottom-up)\n    for (int x = N - 2; x >= 0; --x) {\n        // Shuffle the order of y for this tier\n        vector<int> ys(x + 1);\n        iota(ys.begin(), ys.end(), 0);\n        shuffle(ys.begin(), ys.end(), rng);\n\n        for (int y : ys) {\n            int cur_x = x;\n            int cur_y = y;\n            \n            // Sift-down process\n            while (cur_x < N - 1) {\n                int l_x = cur_x + 1;\n                int l_y = cur_y;\n                int r_x = cur_x + 1;\n                int r_y = cur_y + 1;\n\n                int next_x = l_x;\n                int next_y = l_y;\n                // Identify the smaller of the two children\n                if (current_board[r_x][r_y] < current_board[l_x][l_y]) {\n                    next_x = r_x;\n                    next_y = r_y;\n                }\n\n                // If the current node violates the heap property, swap with the smaller child\n                if (current_board[cur_x][cur_y] > current_board[next_x][next_y]) {\n                    perform_swap(cur_x, cur_y, next_x, next_y, ops);\n                    cur_x = next_x;\n                    cur_y = next_y;\n                } else {\n                    break;\n                }\n            }\n        }\n    }\n\n    // Post-process: remove redundant consecutive swaps\n    vector<SwapOp> cleaned_ops;\n    for (const auto& op : ops) {\n        if (!cleaned_ops.empty() && cleaned_ops.back() == op) {\n            cleaned_ops.pop_back();\n        } else {\n            cleaned_ops.push_back(op);\n        }\n    }\n    ops = cleaned_ops;\n    \n    return ops.size();\n}\n\nint main() {\n    // Optimize I/O operations\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read the pyramid input\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            cin >> initial_board[i][j];\n        }\n    }\n\n    int best_K = 20000; // Initialize with a value > 10000\n    vector<SwapOp> best_ops;\n    mt19937 rng(1337);\n\n    // Run multiple iterations with randomized scan orders\n    // The number of iterations is chosen to balance execution time and solution quality\n    for (int i = 0; i < 500; ++i) {\n        vector<SwapOp> current_ops;\n        int K = build_heap(current_ops, rng);\n        \n        if (K < best_K) {\n            best_K = K;\n            best_ops = current_ops;\n        }\n    }\n\n    // Output the number of operations followed by the operations themselves\n    cout << best_ops.size() << \"\\n\";\n    for (const auto& op : best_ops) {\n        cout << op.x1 << \" \" << op.y1 << \" \" << op.x2 << \" \" << op.y2 << \"\\n\";\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nconst int D = 9;\nint grid[D][D]; // -2 obstacle, -1 empty, >=0 container label\nbool is_removed[85];\npair<int, int> pos[85];\nint D_dist[D][D]; // BFS distances from (0, 4) in an empty board\n\nint dr[] = {0, 0, 1, -1};\nint dc[] = {1, -1, 0, 0};\n\n// Precompute distances in an empty grid\nvoid precompute_dist() {\n    for (int i = 0; i < D; ++i)\n        for (int j = 0; j < D; ++j)\n            D_dist[i][j] = -1;\n\n    queue<pair<int, int>> q;\n    q.push({0, 4});\n    D_dist[0][4] = 0;\n\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i];\n            int nc = c + dc[i];\n            if (nr >= 0 && nr < D && nc >= 0 && nc < D && D_dist[nr][nc] == -1) {\n                if (grid[nr][nc] != -2) {\n                    D_dist[nr][nc] = D_dist[r][c] + 1;\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n}\n\n// Find path from entrance to (tr, tc), treating other containers as obstacles.\n// Path excludes entrance, includes (tr, tc).\nvector<pair<int, int>> get_path(int tr, int tc) {\n    if (grid[tr][tc] == -2) return {}; \n    if (tr == 0 && tc == 4) return {{0, 4}};\n\n    struct Node {\n        int r, c;\n        vector<pair<int, int>> path;\n    };\n    queue<Node> q;\n    q.push({0, 4, {{0, 4}}});\n\n    bool visited[D][D];\n    for(int i=0; i<D; ++i) for(int j=0; j<D; ++j) visited[i][j] = false;\n    visited[0][4] = true;\n\n    while (!q.empty()) {\n        Node curr = q.front();\n        q.pop();\n\n        if (curr.r == tr && curr.c == tc) return curr.path;\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n\n            if (nr >= 0 && nr < D && nc >= 0 && nc < D && !visited[nr][nc]) {\n                // Passable if empty OR it is the target container\n                if (grid[nr][nc] == -1 || (nr == tr && nc == tc)) {\n                    visited[nr][nc] = true;\n                    vector<pair<int, int>> next_path = curr.path;\n                    next_path.push_back({nr, nc});\n                    q.push({nr, nc, next_path});\n                }\n            }\n        }\n    }\n    return {};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N;\n    cin >> D >> N;\n\n    for (int i = 0; i < D; ++i)\n        for (int j = 0; j < D; ++j)\n            grid[i][j] = -1;\n\n    for (int i = 0; i < N; ++i) {\n        int r, c;\n        cin >> r >> c;\n        grid[r][c] = -2;\n    }\n\n    precompute_dist();\n    int max_dist = 0;\n    for(int i=0; i<D; ++i) for(int j=0; j<D; ++j) if(D_dist[i][j] > max_dist) max_dist = D_dist[i][j];\n\n    int K = D * D - 1 - N;\n    vector<pair<int, int>> removal_order;\n\n    for (int d = 0; d < K; ++d) {\n        int t;\n        cin >> t;\n\n        int best_r = -1, best_c = -1;\n        double min_score = 1e18;\n\n        for (int r = 0; r < D; ++r) {\n            for (int c = 0; c < D; ++c) {\n                if (grid[r][c] == -1) {\n                    if (!get_path(r, c).empty()) {\n                        double target_val = (double)t / (K - 1) * max_dist;\n                        double score = abs(D_dist[r][c] - target_val);\n                        if (score < min_score) {\n                            min_score = score;\n                            best_r = r;\n                            best_c = c;\n                        }\n                    }\n                }\n            }\n        }\n\n        grid[best_r][best_c] = t;\n        pos[t] = {best_r, best_c};\n        cout << best_r << \" \" << best_c << endl;\n    }\n\n    int target = 0;\n    int removed_cnt = 0;\n    for(int i=0; i<85; ++i) is_removed[i] = false;\n\n    while (removed_cnt < K) {\n        if (is_removed[target]) {\n            target++;\n            continue;\n        }\n\n        if (!get_path(pos[target].first, pos[target].second).empty()) {\n            removal_order.push_back(pos[target]);\n            grid[pos[target].first][pos[target].second] = -1;\n            is_removed[target] = true;\n            removed_cnt++;\n        } else {\n            int best_label = -1;\n            pair<int, int> best_pos = {-1, -1};\n            for(int r=0; r<D; ++r) {\n                for(int c=0; c<D; ++c) {\n                    if(grid[r][c] >= 0) {\n                        if (!get_path(r, c).empty()) {\n                            if (grid[r][c] > best_label) {\n                                best_label = grid[r][c];\n                                best_pos = {r, c};\n                            }\n                        }\n                    }\n                }\n            }\n            removal_order.push_back(best_pos);\n            grid[best_pos.first][best_pos.second] = -1;\n            is_removed[best_label] = true;\n            removed_cnt++;\n        }\n    }\n\n    for (auto p : removal_order) {\n        cout << p.first << \" \" << p.second << endl;\n    }\n\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MAX_N = 50;\nint N, M;\nint grid[MAX_N][MAX_N];\nbool target_adj[101][101];\nint count_adj[101][101];\nint n_cells[101];\n\nint dr[] = {0, 0, 1, -1};\nint dc[] = {1, -1, 0, 0};\n\n// Check if a color c is connected using BFS\nbool is_connected(int c) {\n    if (n_cells[c] <= 1) return true;\n\n    int start_r = -1, start_c = -1;\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            if(grid[i][j] == c) {\n                start_r = i;\n                start_c = j;\n                break;\n            }\n        }\n        if(start_r != -1) break;\n    }\n\n    if(start_r == -1) return true;\n\n    int visited = 0;\n    static int vis[MAX_N][MAX_N];\n    static int vis_gen = 0;\n    vis_gen++;\n\n    queue<pair<int, int>> q;\n    q.push({start_r, start_c});\n    vis[start_r][start_c] = vis_gen;\n    visited++;\n\n    while(!q.empty()){\n        auto [r, c_] = q.front();\n        q.pop();\n\n        for(int i=0; i<4; ++i) {\n            int nr = r + dr[i];\n            int nc = c_ + dc[i];\n            if(nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] == c && vis[nr][nc] != vis_gen){\n                vis[nr][nc] = vis_gen;\n                visited++;\n                q.push({nr, nc});\n            }\n        }\n    }\n    return visited == n_cells[c];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M;\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            cin >> grid[i][j];\n            n_cells[grid[i][j]]++;\n        }\n    }\n\n    // Initialize adjacency counts\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 + dr[k];\n                int nj = j + dc[k];\n                int nc;\n                if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                else nc = grid[ni][nj];\n                \n                if(grid[i][j] != nc) {\n                    count_adj[grid[i][j]][nc]++;\n                }\n            }\n        }\n    }\n\n    // Initialize target adjacencies\n    for(int i=0; i<=M; ++i) {\n        for(int j=0; j<=M; ++j) {\n            if (count_adj[i][j] > 0) target_adj[i][j] = true;\n        }\n    }\n\n    mt19937 rng(42);\n    vector<pair<int, int>> squares;\n    for(int i=0; i<N; ++i)\n        for(int j=0; j<N; ++j)\n            squares.push_back({i, j});\n\n    auto start_time = chrono::steady_clock::now();\n    \n    // Iterative randomized hill climbing\n    while(true) {\n        auto current_time = chrono::steady_clock::now();\n        if(chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count() > 1800) break;\n        \n        shuffle(squares.begin(), squares.end(), rng);\n        \n        for(auto [i, j] : squares) {\n            int old_c = grid[i][j];\n            if(old_c == 0) continue;\n            if(n_cells[old_c] == 1) continue;\n\n            // Check if possible to change to 0\n            bool possible = true;\n            for(int k=0; k<4; ++k) {\n                int ni = i + dr[k];\n                int nj = j + dc[k];\n                int nc;\n                if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                else nc = grid[ni][nj];\n                \n                if (old_c == nc) {\n                    // Gain 0 - old_c edge\n                    if (nc != 0) {\n                        if (count_adj[0][nc] == 0 && !target_adj[0][nc]) {\n                           possible = false; break;\n                        }\n                    }\n                } else {\n                    // Lose old_c - nc, gain 0 - nc\n                    if (count_adj[old_c][nc] == 1 && target_adj[old_c][nc]) {\n                        possible = false; break;\n                    }\n                    if (nc != 0) {\n                        if (count_adj[0][nc] == 0 && !target_adj[0][nc]) {\n                            possible = false; break;\n                        }\n                    }\n                }\n            }\n            \n            if (!possible) continue;\n            \n            // Apply change\n            grid[i][j] = 0;\n            n_cells[old_c]--;\n            n_cells[0]++;\n            \n            // Update counts\n            for(int k=0; k<4; ++k) {\n                int ni = i + dr[k];\n                int nj = j + dc[k];\n                int nc;\n                if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                else nc = grid[ni][nj];\n                \n                if (old_c == nc) {\n                    if (nc != 0) {\n                        count_adj[0][nc]++;\n                        count_adj[nc][0]++;\n                    }\n                } else {\n                    count_adj[old_c][nc]--;\n                    count_adj[nc][old_c]--;\n                    if (nc != 0) {\n                        count_adj[0][nc]++;\n                        count_adj[nc][0]++;\n                    }\n                }\n            }\n            \n            // Verify connectivity\n            if (!is_connected(old_c)) {\n                // Revert if disconnected\n                for(int k=0; k<4; ++k) {\n                    int ni = i + dr[k];\n                    int nj = j + dc[k];\n                    int nc;\n                    if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                    else nc = grid[ni][nj];\n                    \n                    if (old_c == nc) {\n                        if (nc != 0) {\n                            count_adj[0][nc]--;\n                            count_adj[nc][0]--;\n                        }\n                    } else {\n                        count_adj[old_c][nc]++;\n                        count_adj[nc][old_c]++;\n                        if (nc != 0) {\n                            count_adj[0][nc]--;\n                            count_adj[nc][0]--;\n                        }\n                    }\n                }\n                grid[i][j] = old_c;\n                n_cells[old_c]++;\n                n_cells[0]--;\n            }\n        }\n    }\n\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            cout << grid[i][j] << (j == N-1 ? \"\" : \" \");\n        }\n        cout << \"\\n\";\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <string>\n#include <numeric>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <iomanip>\n\nusing namespace std;\n\n// The Solver class encapsulates the logic for the problem\nstruct Solver {\n    int N, D, Q;\n    vector<double> weights; // Estimated weights of items\n    mt19937 rng;\n\n    Solver() : rng(1337) {}\n\n    void solve() {\n        // Read N, D, Q\n        if (!(cin >> N >> D >> Q)) return;\n        \n        // Initialize weights to a base value\n        weights.assign(N, 1000.0);\n\n        // Perform queries\n        for (int q = 0; q < Q; ++q) {\n            // Select L and R sets with random sizes (at least 1, at most N/2)\n            int nL = uniform_int_distribution<int>(1, N / 2)(rng);\n            int nR = uniform_int_distribution<int>(1, N / 2)(rng);\n            \n            vector<int> items(N);\n            iota(items.begin(), items.end(), 0);\n            shuffle(items.begin(), items.end(), rng);\n            \n            vector<int> L(items.begin(), items.begin() + nL);\n            vector<int> R(items.begin() + nL, items.begin() + nL + nR);\n            \n            // Output query\n            cout << L.size() << \" \" << R.size();\n            for (int i : L) cout << \" \" << i;\n            for (int i : R) cout << \" \" << i;\n            cout << endl;\n            \n            // Read result\n            string res;\n            cin >> res;\n            \n            // Update weights based on result\n            double sumL = 0;\n            for (int i : L) sumL += weights[i];\n            double sumR = 0;\n            for (int i : R) sumR += weights[i];\n            \n            // Decay learning rate alpha from 0.1 to 0.01\n            double alpha = 0.1 * (1.0 - 0.9 * (double)q / Q);\n            \n            // If sumL < sumR, diff > 0. If sumL > sumR, diff < 0.\n            // Adjust weights to minimize the difference in future queries.\n            double diff = 0;\n            if (res == \"<\") {\n                diff = sumR - sumL; // Target L to increase, R to decrease\n            } else if (res == \">\") {\n                diff = sumL - sumR; // Target L to decrease, R to increase\n                diff = -diff;\n            } else {\n                diff = sumL - sumR; // Target to zero\n                diff = -diff;\n            }\n            \n            for (int i : L) weights[i] += alpha * diff / L.size();\n            for (int i : R) weights[i] -= alpha * diff / R.size();\n            \n            // Keep weights positive\n            for (double& w : weights) w = max(1.0, w);\n        }\n        \n        // Final partition\n        vector<int> assignment(N);\n        vector<double> bucket_weights(D, 0.0);\n        \n        // Greedy assignment based on estimated weights (LPT)\n        vector<int> sorted_items(N);\n        iota(sorted_items.begin(), sorted_items.end(), 0);\n        sort(sorted_items.begin(), sorted_items.end(), [&](int a, int b) {\n            return weights[a] > weights[b];\n        });\n        \n        for (int i : sorted_items) {\n            int best_bucket = 0;\n            for (int d = 1; d < D; ++d) {\n                if (bucket_weights[d] < bucket_weights[best_bucket]) {\n                    best_bucket = d;\n                }\n            }\n            assignment[i] = best_bucket;\n            bucket_weights[best_bucket] += weights[i];\n        }\n        \n        // Local search to refine the partition\n        // 100,000 iterations is well within the 2-second limit\n        for (int iter = 0; iter < 100000; ++iter) {\n            int b1 = uniform_int_distribution<int>(0, D - 1)(rng);\n            int b2 = uniform_int_distribution<int>(0, D - 1)(rng);\n            if (b1 == b2) continue;\n            \n            // Find items in buckets b1 and b2\n            vector<int> items1, items2;\n            for (int i = 0; i < N; ++i) {\n                if (assignment[i] == b1) items1.push_back(i);\n                else if (assignment[i] == b2) items2.push_back(i);\n            }\n            if (items1.empty() || items2.empty()) continue;\n            \n            int i1 = items1[uniform_int_distribution<int>(0, items1.size() - 1)(rng)];\n            int i2 = items2[uniform_int_distribution<int>(0, items2.size() - 1)(rng)];\n            \n            // Calculate current sum of squares (proportional to variance)\n            double old_sum_sq = 0;\n            for (double w : bucket_weights) old_sum_sq += w * w;\n            \n            // Calculate new sum of squares if we swap i1 and i2\n            double new_bw1 = bucket_weights[b1] - weights[i1] + weights[i2];\n            double new_bw2 = bucket_weights[b2] - weights[i2] + weights[i1];\n            \n            double new_sum_sq = old_sum_sq \n                                - bucket_weights[b1]*bucket_weights[b1] - bucket_weights[b2]*bucket_weights[b2]\n                                + new_bw1 * new_bw1 + new_bw2 * new_bw2;\n                           \n            // If swap improves variance (decreases sum of squares), accept it\n            if (new_sum_sq < old_sum_sq) {\n                assignment[i1] = b2;\n                assignment[i2] = b1;\n                bucket_weights[b1] = new_bw1;\n                bucket_weights[b2] = new_bw2;\n            }\n        }\n        \n        // Output the final partition\n        for (int i = 0; i < N; ++i) cout << assignment[i] << (i == N - 1 ? \"\" : \" \");\n        cout << endl;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    Solver s;\n    s.solve();\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\n// Configuration\nint N, M;\nvector<vector<int>> stacks;\nvector<int> box_to_stack;\nvector<int> box_to_pos;\n\n// Find the stack containing a specific target box\nint find_stack(int target) {\n    return box_to_stack[target];\n}\n\n// Find the best destination stack for moving boxes\n// Criteria: prefer empty stacks, otherwise pick the one with the largest top box\nint find_best_dest(int s) {\n    int best_d = -1;\n    int max_top = -2;\n    for (int d = 0; d < M; ++d) {\n        if (d == s) continue;\n        if (stacks[d].empty()) return d;\n        if (stacks[d].back() > max_top) {\n            max_top = stacks[d].back();\n            best_d = d;\n        }\n    }\n    return best_d;\n}\n\n// Move the block of boxes above the target box to another stack d\nvoid move_block(int s, int pos, int d) {\n    // The target box is at `pos`. The boxes above it are at indices `pos + 1` to `end`.\n    int block_start_idx = pos + 1;\n    \n    // Update stack_ids and positions for the moved boxes\n    for (int i = block_start_idx; i < (int)stacks[s].size(); ++i) {\n        int b = stacks[s][i];\n        stacks[d].push_back(b);\n        box_to_stack[b] = d;\n        box_to_pos[b] = (int)stacks[d].size() - 1;\n    }\n    \n    // Remove the moved boxes from the original stack\n    stacks[s].erase(stacks[s].begin() + block_start_idx, stacks[s].end());\n}\n\nint main() {\n    // Optimize I/O\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read N and M\n    cin >> N >> M;\n    stacks.resize(M);\n    box_to_stack.resize(N + 1);\n    box_to_pos.resize(N + 1);\n\n    // Read the initial stack configuration\n    for (int i = 0; i < M; ++i) {\n        for (int j = 0; j < N / M; ++j) {\n            int b;\n            cin >> b;\n            stacks[i].push_back(b);\n            box_to_stack[b] = i;\n            box_to_pos[b] = (int)stacks[i].size() - 1;\n        }\n    }\n\n    int target = 1;\n    int ops = 0;\n    \n    // Process until all boxes are removed\n    while (target <= N && ops < 5000) {\n        int s = find_stack(target);\n        int pos = box_to_pos[target];\n        \n        // If target is at the top of its stack, remove it\n        if (pos == (int)stacks[s].size() - 1) {\n            cout << target << \" 0\" << endl;\n            stacks[s].pop_back();\n            target++;\n            ops++;\n        } else {\n            // Otherwise, move the block above the target to another stack\n            // The box directly above target is stacks[s][pos + 1]\n            int v_prime = stacks[s][pos + 1];\n            int d = find_best_dest(s);\n            \n            // Output the move operation (v, i+1)\n            cout << v_prime << \" \" << (d + 1) << endl;\n            \n            // Perform the move\n            move_block(s, pos, d);\n            ops++;\n        }\n    }\n\n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <set>\n#include <ctime>\n\nusing namespace std;\n\n// Function to get index from (r, c)\nint id(int r, int c, int N) {\n    return r * N + c;\n}\n\n// Function to get (r, c) from index\npair<int, int> pos(int idx, int N) {\n    return {idx / N, idx % N};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> h(N - 1), v(N);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    for (int i = 0; i < N; ++i) cin >> v[i];\n    vector<vector<int>> d(N, vector<int>(N));\n    vector<int> d_flat(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n            d_flat[id(i, j, N)] = d[i][j];\n        }\n    }\n\n    // Graph adjacency\n    vector<vector<int>> adj(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (i + 1 < N && h[i][j] == '0') {\n                adj[id(i, j, N)].push_back(id(i + 1, j, N));\n                adj[id(i + 1, j, N)].push_back(id(i, j, N));\n            }\n            if (j + 1 < N && v[i][j] == '0') {\n                adj[id(i, j, N)].push_back(id(i, j + 1, N));\n                adj[id(i, j + 1, N)].push_back(id(i, j, N));\n            }\n        }\n    }\n\n    // Prim's algorithm for initial MST\n    vector<int> deg(N * N, 0);\n    vector<vector<int>> tree_adj(N * N);\n    vector<bool> in_tree(N * N, false);\n    vector<pair<int, int>> edges_in_tree;\n    vector<pair<int, int>> edges_not_in_tree;\n\n    vector<int> min_edge(N * N, 1e9);\n    vector<int> parent(N * N, -1);\n    in_tree[0] = true;\n    for (int neighbor : adj[0]) {\n        min_edge[neighbor] = -(d[0][0] + d[pos(neighbor, N).first][pos(neighbor, N).second]);\n        parent[neighbor] = 0;\n    }\n\n    for (int i = 1; i < N * N; ++i) {\n        int u = -1;\n        for (int v = 0; v < N * N; ++v) {\n            if (!in_tree[v] && parent[v] != -1) {\n                if (u == -1 || min_edge[v] < min_edge[u]) u = v;\n            }\n        }\n        in_tree[u] = true;\n        int p = parent[u];\n        tree_adj[u].push_back(p);\n        tree_adj[p].push_back(u);\n        deg[u]++;\n        deg[p]++;\n        edges_in_tree.push_back({min(u, p), max(u, p)});\n\n        for (int neighbor : adj[u]) {\n            if (!in_tree[neighbor]) {\n                int weight = -(d[pos(u, N).first][pos(u, N).second] + d[pos(neighbor, N).first][pos(neighbor, N).second]);\n                if (weight < min_edge[neighbor]) {\n                    min_edge[neighbor] = weight;\n                    parent[neighbor] = u;\n                }\n            }\n        }\n    }\n\n    // Identify edges not in tree\n    vector<vector<bool>> is_in_tree(N * N, vector<bool>(N * N, false));\n    for (auto& edge : edges_in_tree) {\n        is_in_tree[edge.first][edge.second] = true;\n        is_in_tree[edge.second][edge.first] = true;\n    }\n\n    for (int u = 0; u < N * N; ++u) {\n        for (int neighbor : adj[u]) {\n            if (u < neighbor && !is_in_tree[u][neighbor]) {\n                edges_not_in_tree.push_back({u, neighbor});\n            }\n        }\n    }\n\n    // Hill Climbing\n    mt19937 rng(42);\n    auto start_time = clock();\n    while ((double)(clock() - start_time) / CLOCKS_PER_SEC < 1.8) {\n        int idx = rng() % edges_not_in_tree.size();\n        int x = edges_not_in_tree[idx].first;\n        int y = edges_not_in_tree[idx].second;\n\n        vector<int> path_parent(N * N, -1);\n        vector<int> q;\n        q.push_back(x);\n        vector<bool> visited(N * N, false);\n        visited[x] = true;\n        int head = 0;\n        while(head < (int)q.size()){\n            int u = q[head++];\n            if (u == y) break;\n            for(int neighbor : tree_adj[u]){\n                if(!visited[neighbor]){\n                    visited[neighbor] = true;\n                    path_parent[neighbor] = u;\n                    q.push_back(neighbor);\n                }\n            }\n        }\n        \n        vector<pair<int, int>> path_edges;\n        int curr = y;\n        while(curr != x){\n            int p = path_parent[curr];\n            path_edges.push_back({min(curr, p), max(curr, p)});\n            curr = p;\n        }\n\n        double best_delta = 0;\n        pair<int, int> best_swap_edge = {-1, -1};\n\n        for(auto& e : path_edges){\n            int a = e.first;\n            int b = e.second;\n            double old_c = (double)d_flat[a]/pow(deg[a], 2) + (double)d_flat[b]/pow(deg[b], 2) + \n                           (double)d_flat[x]/pow(deg[x], 2) + (double)d_flat[y]/pow(deg[y], 2);\n            double new_c = (double)d_flat[a]/pow(deg[a]-1, 2) + (double)d_flat[b]/pow(deg[b]-1, 2) + \n                           (double)d_flat[x]/pow(deg[x]+1, 2) + (double)d_flat[y]/pow(deg[y]+1, 2);\n            if (new_c - old_c < best_delta) {\n                best_delta = new_c - old_c;\n                best_swap_edge = e;\n            }\n        }\n\n        if (best_swap_edge.first != -1) {\n            int a = best_swap_edge.first;\n            int b = best_swap_edge.second;\n            \n            is_in_tree[a][b] = is_in_tree[b][a] = false;\n            is_in_tree[x][y] = is_in_tree[y][x] = true;\n            \n            for(int i=0; i<(int)tree_adj[a].size(); ++i) if(tree_adj[a][i] == b) { tree_adj[a].erase(tree_adj[a].begin()+i); break; }\n            for(int i=0; i<(int)tree_adj[b].size(); ++i) if(tree_adj[b][i] == a) { tree_adj[b].erase(tree_adj[b].begin()+i); break; }\n            tree_adj[x].push_back(y);\n            tree_adj[y].push_back(x);\n            \n            deg[a]--; deg[b]--; deg[x]++; deg[y]++;\n            \n            edges_not_in_tree[idx] = {a, b};\n        }\n    }\n\n    vector<vector<int>> children(N * N);\n    vector<int> parent_node(N * N, -1);\n    vector<int> q;\n    q.push_back(0);\n    vector<bool> visited(N * N, false);\n    visited[0] = true;\n    int head = 0;\n    while(head < (int)q.size()){\n        int u = q[head++];\n        for(int neighbor : tree_adj[u]){\n            if(!visited[neighbor]){\n                visited[neighbor] = true;\n                parent_node[neighbor] = u;\n                children[u].push_back(neighbor);\n                q.push_back(neighbor);\n            }\n        }\n    }\n\n    vector<long long> subtree_d(N * N, 0);\n    for(int i = N * N - 1; i >= 0; --i){\n        int u = q[i];\n        subtree_d[u] += d_flat[u];\n        if(parent_node[u] != -1) subtree_d[parent_node[u]] += subtree_d[u];\n    }\n    \n    for(int i=0; i<N*N; ++i){\n        sort(children[i].begin(), children[i].end(), [&](int a, int b){\n            return subtree_d[a] > subtree_d[b];\n        });\n    }\n\n    string path_str = \"\";\n    auto get_dir = [&](int u, int v) {\n        pair<int, int> p1 = pos(u, N), p2 = pos(v, N);\n        if (p2.first == p1.first + 1) return 'D';\n        if (p2.first == p1.first - 1) return 'U';\n        if (p2.second == p1.second + 1) return 'R';\n        if (p2.second == p1.second - 1) return 'L';\n        return ' ';\n    };\n\n    auto dfs = [&](auto self, int u, int p) -> void {\n        for(int neighbor : children[u]){\n            path_str += get_dir(u, neighbor);\n            self(self, neighbor, u);\n            path_str += get_dir(neighbor, u);\n        }\n    };\n    \n    dfs(dfs, 0, -1);\n    \n    string final_path = \"\";\n    while((int)final_path.length() + (int)path_str.length() <= 100000){\n        final_path += path_str;\n    }\n    \n    cout << final_path << endl;\n\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Structure to hold grid coordinates\nstruct Pos {\n    int r, c;\n};\n\n// Function to calculate the cost of moving between two squares.\n// The problem states the cost is |r1-r2| + |c1-c2| + 1.\nint dist(Pos p1, Pos p2) {\n    return abs(p1.r - p2.r) + abs(p1.c - p2.c) + 1;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n\n    // Store grid positions for each letter\n    vector<string> grid(N);\n    vector<vector<Pos>> pos(26);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n        for (int j = 0; j < N; ++j) {\n            pos[grid[i][j] - 'A'].push_back({i, j});\n        }\n    }\n\n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) cin >> t[i];\n\n    // Precompute overlaps between all pairs of strings\n    // overlap[i][j] is the length of the longest suffix of t[i] \n    // that is a prefix of t[j].\n    vector<vector<int>> overlap(M, vector<int>(M));\n    for (int i = 0; i < M; ++i) {\n        for (int j = 0; j < M; ++j) {\n            if (i == j) continue;\n            for (int len = 5; len >= 0; --len) {\n                if (t[i].substr(5 - len) == t[j].substr(0, len)) {\n                    overlap[i][j] = len;\n                    break;\n                }\n            }\n        }\n    }\n\n    long long best_total_cost = 1e18;\n    vector<Pos> best_path;\n\n    // Try starting the superstring with each of the M strings to find the best ordering\n    for (int start_node = 0; start_node < M; ++start_node) {\n        vector<int> order;\n        vector<bool> used(M, false);\n        order.push_back(start_node);\n        used[start_node] = true;\n        \n        string current_s = t[start_node];\n\n        // Greedy construction of the superstring\n        while (order.size() < M) {\n            int last = order.back();\n            int best_next = -1;\n            int max_o = -1;\n            for (int i = 0; i < M; ++i) {\n                if (!used[i]) {\n                    if (overlap[last][i] > max_o) {\n                        max_o = overlap[last][i];\n                        best_next = i;\n                    }\n                }\n            }\n            order.push_back(best_next);\n            used[best_next] = true;\n            current_s += t[best_next].substr(max_o);\n        }\n\n        // DP to find the minimum cost to type current_s on the grid\n        int L = current_s.length();\n        \n        // Initial DP table for the first character\n        int start_char = current_s[0] - 'A';\n        vector<long long> dp(pos[start_char].size());\n        vector<int> parent(pos[start_char].size(), -1);\n        \n        Pos start_pos = {si, sj};\n        for (size_t i = 0; i < pos[start_char].size(); ++i) {\n            dp[i] = dist(start_pos, pos[start_char][i]);\n        }\n\n        // parent_path[k][i] stores the parent index for the i-th occurrence of character at step k\n        vector<vector<int>> parent_path(L);\n        parent_path[0] = parent;\n\n        for (int k = 1; k < L; ++k) {\n            int curr_char = current_s[k] - 'A';\n            int prev_char = current_s[k-1] - 'A';\n            \n            vector<long long> next_dp(pos[curr_char].size(), 1e18);\n            vector<int> next_parent(pos[curr_char].size(), -1);\n            \n            for (size_t i = 0; i < pos[curr_char].size(); ++i) {\n                for (size_t j = 0; j < pos[prev_char].size(); ++j) {\n                    long long cost = dp[j] + dist(pos[prev_char][j], pos[curr_char][i]);\n                    if (cost < next_dp[i]) {\n                        next_dp[i] = cost;\n                        next_parent[i] = (int)j;\n                    }\n                }\n            }\n            dp = next_dp;\n            parent_path[k] = next_parent;\n        }\n\n        // Find min cost for the last character\n        long long min_cost = 1e18;\n        int last_pos_idx = -1;\n        int last_char = current_s[L-1] - 'A';\n        for (size_t i = 0; i < pos[last_char].size(); ++i) {\n            if (dp[i] < min_cost) {\n                min_cost = dp[i];\n                last_pos_idx = (int)i;\n            }\n        }\n\n        // Keep track of the best result\n        if (min_cost < best_total_cost) {\n            best_total_cost = min_cost;\n            \n            // Reconstruct path\n            best_path.resize(L);\n            int curr_pos_idx = last_pos_idx;\n            for (int k = L - 1; k >= 0; --k) {\n                int char_idx = current_s[k] - 'A';\n                best_path[k] = pos[char_idx][curr_pos_idx];\n                if (k > 0) {\n                    curr_pos_idx = parent_path[k][curr_pos_idx];\n                }\n            }\n        }\n    }\n\n    // Output the optimal path\n    for (const auto& p : best_path) {\n        cout << p.r << \" \" << p.c << \"\\n\";\n    }\n\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <iomanip>\n\nusing namespace std;\n\n// Structure to represent a point on the island\nstruct Point {\n    int r, c;\n};\n\n// Structure to represent an oil field\nstruct Field {\n    vector<Point> shape;\n    int max_dr, max_dc;\n};\n\nint N, M;\ndouble eps;\nvector<Field> fields;\n\n// Global vector for precomputed is_oil: [k][r][c][i][j]\n// Using uint8_t to save memory\nvector<uint8_t> is_oil; \n\ninline bool get_is_oil(int k, int r, int c, int i, int j) {\n    if (i < r || j < c || i >= r + fields[k].max_dr + 1 || j >= c + fields[k].max_dc + 1) return false;\n    return is_oil[((((k * N + r) * N + c) * N + i) * N + j)];\n}\n\nstruct Config {\n    vector<Point> offsets;\n    double log_weight;\n};\n\nvector<Config> particles;\nconst int NUM_PARTICLES = 250;\n\nvoid init_particles() {\n    particles.clear();\n    mt19937 rng(12345);\n    for (int i = 0; i < NUM_PARTICLES; ++i) {\n        Config c;\n        for (int k = 0; k < M; ++k) {\n            uniform_int_distribution<int> dist_r(0, N - 1 - fields[k].max_dr);\n            uniform_int_distribution<int> dist_c(0, N - 1 - fields[k].max_dc);\n            c.offsets.push_back({dist_r(rng), dist_c(rng)});\n        }\n        c.log_weight = -log((double)NUM_PARTICLES);\n        particles.push_back(c);\n    }\n}\n\nint compute_v_S(const Config& c, const vector<Point>& S) {\n    int v_S = 0;\n    for (const auto& p : S) {\n        for (int k = 0; k < M; ++k) {\n            if (get_is_oil(k, c.offsets[k].r, c.offsets[k].c, p.r, p.c)) {\n                v_S++;\n            }\n        }\n    }\n    return v_S;\n}\n\nvoid update_weights(const vector<Point>& S, double obs) {\n    int k = S.size();\n    double sigma2 = (double)k * eps * (1.0 - eps);\n    double max_log_w = -1e18;\n\n    for (auto& c : particles) {\n        int v_S = compute_v_S(c, S);\n        double mu = (double)(k - v_S) * eps + (double)v_S * (1.0 - eps);\n        double log_likelihood = -0.5 * pow(obs - mu, 2) / sigma2;\n        c.log_weight += log_likelihood;\n        if (c.log_weight > max_log_w) max_log_w = c.log_weight;\n    }\n\n    double sum_w = 0;\n    for (auto& c : particles) {\n        c.log_weight -= max_log_w;\n        sum_w += exp(c.log_weight);\n    }\n    for (auto& c : particles) {\n        c.log_weight = log(exp(c.log_weight) / sum_w);\n    }\n}\n\nvoid resample() {\n    double sum_sq_w = 0;\n    for (auto& c : particles) sum_sq_w += exp(2.0 * c.log_weight);\n    if (1.0 / sum_sq_w < NUM_PARTICLES / 3.0) {\n        vector<Config> new_particles;\n        vector<double> weights;\n        for (auto& c : particles) weights.push_back(exp(c.log_weight));\n        discrete_distribution<int> dist(weights.begin(), weights.end());\n        mt19937 rng(45678);\n        for (int i = 0; i < NUM_PARTICLES; ++i) {\n            new_particles.push_back(particles[dist(rng)]);\n            new_particles.back().log_weight = -log((double)NUM_PARTICLES);\n        }\n        particles = new_particles;\n    }\n}\n\nvoid rejuvenate() {\n    double min_w = 1e18;\n    for (auto& c : particles) min_w = min(min_w, c.log_weight);\n    \n    mt19937 rng(999);\n    for (auto& c : particles) {\n        if (c.log_weight < min_w + 1e-4) {\n            for (int k = 0; k < M; ++k) {\n                c.offsets[k].r = uniform_int_distribution<int>(0, N - 1 - fields[k].max_dr)(rng);\n                c.offsets[k].c = uniform_int_distribution<int>(0, N - 1 - fields[k].max_dc)(rng);\n            }\n            c.log_weight = -log((double)NUM_PARTICLES);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    cin >> N >> M >> eps;\n    fields.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int d; cin >> d;\n        int max_dr = 0, max_dc = 0;\n        for (int i = 0; i < d; ++i) {\n            int r, c; cin >> r >> c;\n            fields[k].shape.push_back({r, c});\n            max_dr = max(max_dr, r);\n            max_dc = max(max_dc, c);\n        }\n        fields[k].max_dr = max_dr;\n        fields[k].max_dc = max_dc;\n    }\n\n    is_oil.assign(M * N * N * N * N, 0);\n    for (int k = 0; k < M; ++k) {\n        for (int r = 0; r <= N - 1 - fields[k].max_dr; ++r) {\n            for (int c = 0; c <= N - 1 - fields[k].max_dc; ++c) {\n                for (const auto& p : fields[k].shape) {\n                    is_oil[((((k * N + r) * N + c) * N + (r + p.r)) * N + (c + p.c))] = 1;\n                }\n            }\n        }\n    }\n\n    init_particles();\n    mt19937 rng(42);\n    int query_count = 0;\n    while (query_count < 2 * N * N) {\n        vector<vector<Point>> candidates;\n        for (int i = 0; i < 50; ++i) {\n            int k = uniform_int_distribution<int>(1, N * N / 2)(rng);\n            vector<Point> S;\n            for (int j = 0; j < k; ++j) S.push_back({uniform_int_distribution<int>(0, N - 1)(rng), uniform_int_distribution<int>(0, N - 1)(rng)});\n            candidates.push_back(S);\n        }\n\n        int best_idx = -1;\n        double best_var = -1.0;\n        for (int i = 0; i < candidates.size(); ++i) {\n            double mean = 0;\n            vector<int> v_Ss;\n            for (auto& c : particles) {\n                int v_S = compute_v_S(c, candidates[i]);\n                v_Ss.push_back(v_S);\n                mean += exp(c.log_weight) * v_S;\n            }\n            double var = 0;\n            for (int j = 0; j < particles.size(); ++j) var += exp(particles[j].log_weight) * pow(v_Ss[j] - mean, 2);\n            double score = var * sqrt((double)candidates[i].size());\n            if (score > best_var) { best_var = score; best_idx = i; }\n        }\n\n        cout << \"q \" << candidates[best_idx].size();\n        for (auto& p : candidates[best_idx]) cout << \" \" << p.r << \" \" << p.c;\n        cout << endl;\n        double obs; cin >> obs;\n        update_weights(candidates[best_idx], obs);\n        resample();\n        rejuvenate();\n        query_count++;\n\n        // Guess\n        vector<Point> guess_set;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                double prob = 0;\n                for (auto& c : particles) {\n                    bool oil = false;\n                    for (int k = 0; k < M; ++k) if (get_is_oil(k, c.offsets[k].r, c.offsets[k].c, i, j)) { oil = true; break; }\n                    if (oil) prob += exp(c.log_weight);\n                }\n                if (prob > 0.5) guess_set.push_back({i, j});\n            }\n        }\n\n        cout << \"a \" << guess_set.size();\n        for (auto& p : guess_set) cout << \" \" << p.r << \" \" << p.c;\n        cout << endl;\n        int resp; cin >> resp;\n        if (resp == 1) return 0;\n    }\n    return 0;\n}","ahc031":"/*\n * Problem: Minimize total cost of rental area deficiency and partition movement.\n * Approach: Partition the W x W grid into N horizontal strips.\n * Use coordinate descent to optimize the positions of the N-1 internal partition lines.\n * The initialization is based on the required areas to provide a better starting point.\n */\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Function to calculate area cost for a given strip height\nlong long get_area_cost(int W, int a_val, int height) {\n    long long area = (long long)W * height;\n    if (a_val > area) return 100LL * (a_val - area);\n    return 0LL;\n}\n\nint main() {\n    // Optimize I/O operations\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\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    // lines[d][k] is the position of the k-th partition on day d.\n    // k goes from 0 to N. lines[d][0] = 0, lines[d][N] = W.\n    vector<vector<int>> lines(D, vector<int>(N + 1));\n    \n    // Better initialization: try to match the desired area\n    for (int d = 0; d < D; ++d) {\n        lines[d][0] = 0;\n        lines[d][N] = W;\n        int current_pos = 0;\n        for (int k = 0; k < N - 1; ++k) {\n            // Estimate height needed: ceil(a/W)\n            int needed_height = (a[d][k] + W - 1) / W;\n            current_pos += max(1, needed_height);\n            lines[d][k + 1] = current_pos;\n        }\n        \n        // Ensure strictly increasing and within [0, W]\n        for (int k = 1; k < N; ++k) {\n            lines[d][k] = max(lines[d][k - 1] + 1, min(lines[d][k], W - (N - k)));\n        }\n    }\n\n    // Coordinate descent to minimize the total cost\n    for (int iter = 0; iter < 200; ++iter) {\n        bool changed = false;\n        for (int d = 0; d < D; ++d) {\n            for (int k = 1; k < N; ++k) {\n                int best_pos = lines[d][k];\n                long long min_cost = -1;\n\n                // The valid range for lines[d][k] ensures each strip has at least height 1\n                int low = lines[d][k - 1] + 1;\n                int high = lines[d][k + 1] - 1;\n\n                // Find the best position for this partition\n                for (int pos = low; pos <= high; ++pos) {\n                    long long cost = 0;\n                    \n                    // Area cost\n                    cost += get_area_cost(W, a[d][k - 1], pos - lines[d][k - 1]);\n                    cost += get_area_cost(W, a[d][k], lines[d][k + 1] - pos);\n                    \n                    // Movement cost\n                    if (d > 0) cost += (long long)W * abs(pos - lines[d - 1][k]);\n                    if (d < D - 1) cost += (long long)W * abs(lines[d + 1][k] - pos);\n                    \n                    if (min_cost == -1 || cost < min_cost) {\n                        min_cost = cost;\n                        best_pos = pos;\n                    }\n                }\n                \n                if (lines[d][k] != best_pos) {\n                    lines[d][k] = best_pos;\n                    changed = true;\n                }\n            }\n        }\n        if (!changed) break;\n    }\n\n    // Output the resulting rectangles: top-left (i0, j0) and bottom-right (i1, j1)\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            // Rectangle spans vertical range [lines[d][k], lines[d][k+1]] and horizontal range [0, W]\n            cout << lines[d][k] << \" \" << 0 << \" \" << lines[d][k + 1] << \" \" << W << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\n// Standard library includes and types\nconst int MOD = 998244353;\n\nstruct Op {\n    int m, p, q;\n};\n\nint N, M, K;\nvector<vector<int>> A;\nvector<vector<vector<int>>> S;\n\n// Function to calculate the total score: sum(b_{i,j} % MOD)\nlong long calc_score(const vector<vector<long long>>& board) {\n    long long score = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            score += (board[i][j] % MOD);\n        }\n    }\n    return score;\n}\n\n// Function to apply a stamp\nvoid apply(vector<vector<long long>>& board, const Op& op) {\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            board[op.p + i][op.q + j] += S[op.m][i][j];\n        }\n    }\n}\n\n// Function to undo a stamp\nvoid undo(vector<vector<long long>>& board, const Op& op) {\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            board[op.p + i][op.q + j] -= S[op.m][i][j];\n        }\n    }\n}\n\nint main() {\n    // Faster I/O\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read Input\n    cin >> N >> M >> K;\n    A.resize(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    S.resize(M, vector<vector<int>>(3, vector<int>(3)));\n    for (int m = 0; m < M; ++m)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> S[m][i][j];\n\n    // Initial board\n    vector<vector<long long>> board(N, vector<long long>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            board[i][j] = A[i][j];\n\n    // Initial Greedy Approach\n    vector<Op> ops;\n    for (int k = 0; k < K; ++k) {\n        long long best_gain = -1;\n        Op best_op = {-1, -1, -1};\n\n        // Try every possible stamp and position to find the best gain\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    long long gain = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            gain -= (board[p + i][q + j] % MOD);\n                            gain += ((board[p + i][q + j] + S[m][i][j]) % MOD);\n                        }\n                    }\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        best_op = {m, p, q};\n                    }\n                }\n            }\n        }\n        \n        // If we found a beneficial operation, apply it\n        if (best_gain > 0) {\n            apply(board, best_op);\n            ops.push_back(best_op);\n        } else {\n            break;\n        }\n    }\n\n    // Local Search (Simulated Annealing)\n    mt19937 rng(1337);\n    auto start_time = chrono::steady_clock::now();\n    double time_limit = 1.8; // Seconds\n    long long current_score = calc_score(board);\n    \n    double start_temp = 1e6;\n    double end_temp = 100.0;\n\n    while (true) {\n        auto current_time = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(current_time - start_time).count();\n        if (elapsed > time_limit) break;\n\n        double progress = elapsed / time_limit;\n        double temp = start_temp * pow(end_temp / start_temp, progress);\n\n        int move_type = rng() % 3; // 0: modify, 1: add, 2: remove\n        \n        // Ensure valid move_type\n        if (ops.empty()) move_type = 1; // If empty, must add\n        if (ops.size() == K && move_type == 1) move_type = 0; // If full, can't add\n\n        if (move_type == 0 && !ops.empty()) { // Modify\n            int idx = rng() % ops.size();\n            Op old_op = ops[idx];\n            Op new_op = { (int)(rng() % M), (int)(rng() % (N - 2)), (int)(rng() % (N - 2)) };\n            \n            undo(board, old_op);\n            apply(board, new_op);\n            long long new_score = calc_score(board);\n            \n            double delta = (double)new_score - current_score;\n            if (delta > 0 || exp(delta / temp) > (double)rng() / rng.max()) {\n                current_score = new_score;\n                ops[idx] = new_op;\n            } else {\n                undo(board, new_op);\n                apply(board, old_op);\n            }\n        } else if (move_type == 1 && ops.size() < K) { // Add\n            Op new_op = { (int)(rng() % M), (int)(rng() % (N - 2)), (int)(rng() % (N - 2)) };\n            apply(board, new_op);\n            long long new_score = calc_score(board);\n            \n            double delta = (double)new_score - current_score;\n            if (delta > 0 || exp(delta / temp) > (double)rng() / rng.max()) {\n                current_score = new_score;\n                ops.push_back(new_op);\n            } else {\n                undo(board, new_op);\n            }\n        } else if (move_type == 2 && !ops.empty()) { // Remove\n            int idx = rng() % ops.size();\n            Op old_op = ops[idx];\n            \n            undo(board, old_op);\n            long long new_score = calc_score(board);\n            \n            double delta = (double)new_score - current_score;\n            if (delta > 0 || exp(delta / temp) > (double)rng() / rng.max()) {\n                current_score = new_score;\n                ops.erase(ops.begin() + idx);\n            } else {\n                apply(board, old_op);\n            }\n        }\n    }\n\n    // Output\n    cout << ops.size() << endl;\n    for (const auto& op : ops) {\n        cout << op.m << \" \" << op.p << \" \" << op.q << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cstring>\n\nusing namespace std;\n\nconst int N = 5;\n\nstruct Pos {\n    int r, c;\n    bool operator==(const Pos& other) const { return r == other.r && c == other.c; }\n    bool operator!=(const Pos& other) const { return !(*this == other); }\n};\n\nstruct Crane {\n    int id;\n    Pos pos;\n    int holding; \n    bool is_large;\n    string moves;\n};\n\nint grid[N][N];\nCrane cranes[N];\nint incoming[N][N];\nint incoming_ptr[N];\nint expected_container[N];\n\n// BFS to find the next step\nPos get_next_move(int crane_idx, Pos target) {\n    if (cranes[crane_idx].pos == target) return target;\n    \n    queue<pair<Pos, Pos>> q;\n    q.push({cranes[crane_idx].pos, {-1, -1}});\n    \n    bool visited[N][N];\n    memset(visited, false, sizeof(visited));\n    visited[cranes[crane_idx].pos.r][cranes[crane_idx].pos.c] = true;\n    \n    // Parent array to reconstruct the path\n    Pos parent[N][N];\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    \n    while (!q.empty()) {\n        Pos curr = q.front().first;\n        Pos p = q.front().second;\n        q.pop();\n        \n        if (curr == target) {\n            // Reconstruct the first step\n            Pos prev = curr;\n            while (p != cranes[crane_idx].pos) {\n                prev = p;\n                p = parent[p.r][p.c];\n            }\n            return prev;\n        }\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n            \n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && !visited[nr][nc]) {\n                // Check if another crane is there\n                bool crane_blocked = false;\n                for (int j = 0; j < N; ++j) {\n                    if (j != crane_idx && cranes[j].pos.r == nr && cranes[j].pos.c == nc) {\n                        crane_blocked = true;\n                        break;\n                    }\n                }\n                if (crane_blocked) continue;\n                \n                // Small crane with container cannot move to a square with a container\n                if (!cranes[crane_idx].is_large && cranes[crane_idx].holding != -1 && grid[nr][nc] != -1) continue;\n                \n                visited[nr][nc] = true;\n                parent[nr][nc] = curr;\n                q.push({{nr, nc}, curr});\n            }\n        }\n    }\n    return cranes[crane_idx].pos; // Cannot move\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n_in;\n    cin >> n_in;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) cin >> incoming[i][j];\n        incoming_ptr[i] = 0;\n        expected_container[i] = N * i;\n    }\n\n    memset(grid, -1, sizeof(grid));\n    for (int i = 0; i < N; ++i) {\n        cranes[i] = {i, {i, 0}, -1, (i == 0), \"\"};\n    }\n\n    for (int turn = 0; turn < 10000; ++turn) {\n        // 1. Receive\n        for (int i = 0; i < N; ++i) {\n            if (incoming_ptr[i] < N && grid[i][0] == -1) {\n                bool crane_at_gate = false;\n                for(int k=0; k<N; ++k) if(cranes[k].pos.r == i && cranes[k].pos.c == 0) crane_at_gate = true;\n                if (!crane_at_gate) {\n                    grid[i][0] = incoming[i][incoming_ptr[i]++];\n                }\n            }\n        }\n\n        // 2. Actions\n        vector<char> turn_actions(N, '.');\n        for (int i = 0; i < N; ++i) {\n            Crane &c = cranes[i];\n            if (c.holding != -1) {\n                // Moving to target\n                int target_row = c.holding / N;\n                Pos target = {target_row, N - 1};\n                if (c.pos == target) {\n                    if (c.holding == expected_container[target_row]) turn_actions[i] = 'Q';\n                    else {\n                        // Move to storage\n                        Pos storage = {target_row, 0}; // Simple storage\n                        Pos next = get_next_move(i, storage);\n                        if (next != c.pos) turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                        else turn_actions[i] = '.';\n                    }\n                } else {\n                    Pos next = get_next_move(i, target);\n                    if (next != c.pos) turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                    else turn_actions[i] = '.';\n                }\n            } else {\n                // Find a container to pick\n                Pos best_container = {-1, -1};\n                for (int r = 0; r < N; ++r) {\n                    for (int col = 0; col < N; ++col) {\n                        if (grid[r][col] != -1) {\n                            best_container = {r, col};\n                            break;\n                        }\n                    }\n                    if (best_container.r != -1) break;\n                }\n                if (best_container.r != -1) {\n                    if (c.pos == best_container) turn_actions[i] = 'P';\n                    else {\n                        Pos next = get_next_move(i, best_container);\n                        if (next != c.pos) turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                        else turn_actions[i] = '.';\n                    }\n                } else turn_actions[i] = '.';\n            }\n        }\n\n        // Apply actions\n        for (int i = 0; i < N; ++i) {\n            char a = turn_actions[i];\n            cranes[i].moves += a;\n            if (a == 'P') {\n                cranes[i].holding = grid[cranes[i].pos.r][cranes[i].pos.c];\n                grid[cranes[i].pos.r][cranes[i].pos.c] = -1;\n            } else if (a == 'Q') {\n                grid[cranes[i].pos.r][cranes[i].pos.c] = cranes[i].holding;\n                cranes[i].holding = -1;\n            } else if (a != '.' && a != 'B') {\n                if (a == 'U') cranes[i].pos.r--;\n                else if (a == 'D') cranes[i].pos.r++;\n                else if (a == 'L') cranes[i].pos.c--;\n                else if (a == 'R') cranes[i].pos.c++;\n            }\n        }\n\n        // 3. Dispatch\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][N-1] == expected_container[i]) {\n                grid[i][N-1] = -1;\n                expected_container[i]++;\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) cout << cranes[i].moves << \"\\n\";\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 20;\nint H[N][N];\nint curr_r = 0, curr_c = 0;\nint current_load = 0;\n\nstruct Pos {\n    int r, c;\n};\n\n// Function to find the nearest cell with a certain property\n// want_surplus: true if we look for surplus (H > 0), false if deficit (H < 0)\nPos find_nearest(bool want_surplus) {\n    queue<pair<int, int>> q;\n    q.push({curr_r, curr_c});\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    \n    // Check if current cell satisfies the condition\n    if (want_surplus) {\n        if (H[curr_r][curr_c] > 0) return {curr_r, curr_c};\n    } else {\n        if (H[curr_r][curr_c] < 0) return {curr_r, curr_c};\n    }\n    visited[curr_r][curr_c] = true;\n\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n\n        int dr[] = {-1, 1, 0, 0};\n        int dc[] = {0, 0, -1, 1};\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i], nc = c + dc[i];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && !visited[nr][nc]) {\n                if (want_surplus) {\n                    if (H[nr][nc] > 0) return {nr, nc};\n                } else {\n                    if (H[nr][nc] < 0) return {nr, nc};\n                }\n                visited[nr][nc] = true;\n                q.push({nr, nc});\n            }\n        }\n    }\n    return {-1, -1};\n}\n\n// Get shortest path from curr to target\nvector<Pos> get_path(Pos target) {\n    queue<pair<int, int>> q;\n    q.push({curr_r, curr_c});\n    vector<vector<Pos>> parent(N, vector<Pos>(N, {-1, -1}));\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    visited[curr_r][curr_c] = true;\n\n    bool found = false;\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n        if (r == target.r && c == target.c) {\n            found = true;\n            break;\n        }\n\n        int dr[] = {-1, 1, 0, 0};\n        int dc[] = {0, 0, -1, 1};\n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i], nc = c + dc[i];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && !visited[nr][nc]) {\n                visited[nr][nc] = true;\n                parent[nr][nc] = {r, c};\n                q.push({nr, nc});\n            }\n        }\n    }\n\n    vector<Pos> path;\n    if (found) {\n        Pos p = target;\n        while (p.r != curr_r || p.c != curr_c) {\n            path.push_back(p);\n            p = parent[p.r][p.c];\n        }\n        reverse(path.begin(), path.end());\n    }\n    return path;\n}\n\nvoid move_to(int nr, int nc) {\n    if (nr == curr_r - 1) cout << \"U\" << endl;\n    else if (nr == curr_r + 1) cout << \"D\" << endl;\n    else if (nc == curr_c - 1) cout << \"L\" << endl;\n    else if (nc == curr_c + 1) cout << \"R\" << endl;\n    curr_r = nr;\n    curr_c = nc;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n;\n    cin >> n;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> H[i][j];\n        }\n    }\n\n    while (true) {\n        Pos target;\n        // Search for nearest relevant cell\n        if (current_load == 0) {\n            target = find_nearest(true);\n        } else {\n            target = find_nearest(false);\n        }\n\n        if (target.r == -1) break; // All heights are 0\n\n        vector<Pos> path = get_path(target);\n        for (Pos p : path) {\n            move_to(p.r, p.c);\n            // Process the cell we just moved to\n            if (H[p.r][p.c] > 0) {\n                int d = H[p.r][p.c];\n                cout << \"+\" << d << endl;\n                current_load += d;\n                H[p.r][p.c] = 0;\n            } else if (H[p.r][p.c] < 0 && current_load > 0) {\n                int d = min(current_load, -H[p.r][p.c]);\n                cout << \"-\" << d << endl;\n                current_load -= d;\n                H[p.r][p.c] += d;\n            }\n        }\n\n        // If path was empty, target is the current cell\n        if (path.empty()) {\n            if (H[target.r][target.c] > 0) {\n                int d = H[target.r][target.c];\n                cout << \"+\" << d << endl;\n                current_load += d;\n                H[target.r][target.c] = 0;\n            } else if (H[target.r][target.c] < 0 && current_load > 0) {\n                int d = min(current_load, -H[target.r][target.c]);\n                cout << \"-\" << d << endl;\n                current_load -= d;\n                H[target.r][target.c] += d;\n            }\n        }\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\n// Potential of a pair (A, B) is sum(max(A_l, B_l)) for all criteria l.\n// This is a strong heuristic for the potential of a pair to produce high-value offspring.\nlong long calculate_edge_cost(const vector<int>& s1, const vector<int>& s2, int M) {\n    long long cost = 0;\n    for (int l = 0; l < M; ++l) {\n        cost += max(s1[l], s2[l]);\n    }\n    return cost;\n}\n\nint main() {\n    // Optimize I/O operations\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> seeds(seed_count, vector<int>(M));\n\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i][j];\n        }\n    }\n\n    // Precompute neighbors for each grid position to speed up cost calculation\n    int grid_size = N * N;\n    vector<vector<int>> neighbors(grid_size);\n    for (int i = 0; i < grid_size; ++i) {\n        int r = i / N;\n        int c = i % N;\n        if (r > 0) neighbors[i].push_back((r - 1) * N + c);\n        if (r < N - 1) neighbors[i].push_back((r + 1) * N + c);\n        if (c > 0) neighbors[i].push_back(r * N + c - 1);\n        if (c < N - 1) neighbors[i].push_back(r * N + c + 1);\n    }\n\n    mt19937 rng(1337); \n\n    for (int t = 0; t < T; t++) {\n        // 1. Selection: Top 30 + 6 random seeds\n        vector<pair<long long, int>> seed_scores(seed_count);\n        for (int i = 0; i < seed_count; ++i) {\n            long long val = 0;\n            for (int l = 0; l < M; ++l) val += seeds[i][l];\n            seed_scores[i] = {val, i};\n        }\n        sort(seed_scores.rbegin(), seed_scores.rend());\n\n        vector<int> selected_indices;\n        for (int i = 0; i < 30; ++i) selected_indices.push_back(seed_scores[i].second);\n        vector<int> remaining;\n        for (int i = 30; i < seed_count; ++i) remaining.push_back(seed_scores[i].second);\n        shuffle(remaining.begin(), remaining.end(), rng);\n        for (int i = 0; i < 6; ++i) selected_indices.push_back(remaining[i]);\n\n        // 2. Simulated Annealing for arrangement\n        // current_grid_seeds[i] stores the seed index at grid position i\n        vector<int> grid_perm(grid_size);\n        iota(grid_perm.begin(), grid_perm.end(), 0);\n        shuffle(grid_perm.begin(), grid_perm.end(), rng);\n\n        vector<int> current_grid_seeds(grid_size);\n        for(int i = 0; i < grid_size; ++i) current_grid_seeds[i] = selected_indices[grid_perm[i]];\n\n        // Initial total cost calculation\n        long long current_total_cost = 0;\n        for (int i = 0; i < grid_size; ++i) {\n            for (int neighbor : neighbors[i]) {\n                if (i < neighbor) {\n                    current_total_cost += calculate_edge_cost(seeds[current_grid_seeds[i]], seeds[current_grid_seeds[neighbor]], M);\n                }\n            }\n        }\n\n        double temp = 1000.0;\n        double cooling = 0.99995;\n        int iterations = 400000;\n\n        for (int iter = 0; iter < iterations; ++iter) {\n            int p1 = uniform_int_distribution<int>(0, grid_size - 1)(rng);\n            int p2 = uniform_int_distribution<int>(0, grid_size - 1)(rng);\n            if (p1 == p2) continue;\n\n            // Collect unique affected edges to calculate delta\n            vector<pair<int, int>> all_edges;\n            auto add_edges = [&](int p) {\n                for (int n : neighbors[p]) {\n                    all_edges.push_back({min(p, n), max(p, n)});\n                }\n            };\n            add_edges(p1);\n            add_edges(p2);\n            sort(all_edges.begin(), all_edges.end());\n            all_edges.erase(unique(all_edges.begin(), all_edges.end()), all_edges.end());\n\n            long long old_partial_cost = 0;\n            for (auto& edge : all_edges) {\n                old_partial_cost += calculate_edge_cost(seeds[current_grid_seeds[edge.first]], seeds[current_grid_seeds[edge.second]], M);\n            }\n\n            // Swap and evaluate\n            swap(current_grid_seeds[p1], current_grid_seeds[p2]);\n\n            long long new_partial_cost = 0;\n            for (auto& edge : all_edges) {\n                new_partial_cost += calculate_edge_cost(seeds[current_grid_seeds[edge.first]], seeds[current_grid_seeds[edge.second]], M);\n            }\n\n            long long delta = new_partial_cost - old_partial_cost;\n            if (delta > 0 || exp(delta / temp) > uniform_real_distribution<double>(0, 1)(rng)) {\n                current_total_cost += delta;\n            } else {\n                swap(current_grid_seeds[p1], current_grid_seeds[p2]);\n            }\n            temp *= cooling;\n        }\n\n        // 3. Output the arrangement\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << current_grid_seeds[i * N + j];\n                if (j < N - 1) cout << \" \";\n            }\n            cout << \"\\n\";\n        }\n        cout.flush();\n\n        // 4. Read new seeds\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> seeds[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Coordinate structure\nstruct Point {\n    int x, y;\n};\n\n// Robot vertex structure\nstruct Vertex {\n    int id;\n    int parent;\n    int L;\n    int dir; // 0=R, 1=D, 2=L, 3=U\n    bool holding;\n    Point target; // Target square\n};\n\nint N, M, V_avail;\nvector<vector<int>> s, t; // s=takoyaki (1 present), t=target (1 present)\nint rx, ry;\nvector<Vertex> robot;\n\n// Directions: R, D, L, U (0, 1, 2, 3)\nint DX[] = {0, 1, 0, -1};\nint DY[] = {1, 0, -1, 0};\nchar DIRS[] = {'R', 'D', 'L', 'U'};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M >> V_avail)) return 0;\n    s.resize(N, vector<int>(N));\n    t.resize(N, vector<int>(N));\n    \n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) s[i][j] = row[j] - '0';\n    }\n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) t[i][j] = row[j] - '0';\n    }\n\n    // Design robot: star graph\n    int V_prime = V_avail;\n    robot.resize(V_prime);\n    robot[0] = {0, -1, 0, 0, false, {-1, -1}};\n    for (int i = 1; i < V_prime; ++i) {\n        // Distribute edge lengths\n        robot[i] = {i, 0, (i - 1) % (N - 1) + 1, 0, false, {-1, -1}};\n    }\n\n    cout << V_prime << endl;\n    for (int i = 1; i < V_prime; ++i) {\n        cout << robot[i].parent << \" \" << robot[i].L << endl;\n    }\n    rx = N / 2;\n    ry = N / 2;\n    cout << rx << \" \" << ry << endl;\n\n    // Simulation\n    for (int turn = 0; turn < 100000; ++turn) {\n        // Check if finished\n        int current_m = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (s[i][j] && t[i][j]) current_m++;\n            }\n        }\n        if (current_m == M) break;\n\n        // 1. Identify/Update targets for each fingertip\n        for (int i = 1; i < V_prime; ++i) {\n            // Validate existing target\n            if (robot[i].target.x >= 0) {\n                int tx = robot[i].target.x, ty = robot[i].target.y;\n                bool valid = false;\n                if (robot[i].holding) {\n                    if (t[tx][ty] == 1 && s[tx][ty] == 0) valid = true;\n                } else {\n                    if (s[tx][ty] == 1 && t[tx][ty] == 0) valid = true;\n                }\n                if (!valid) robot[i].target = {-1, -1};\n            }\n\n            // Assign new target if needed\n            if (robot[i].target.x == -1) {\n                int best_dist = 1e9;\n                Point best_p = {-2, -2}; // -2 means no target found\n                if (robot[i].holding) {\n                    for (int r = 0; r < N; ++r) {\n                        for (int c = 0; c < N; ++c) {\n                            if (t[r][c] && !s[r][c]) {\n                                int dist = abs(r - rx) + abs(c - ry); \n                                if (dist < best_dist) { best_dist = dist; best_p = {r, c}; }\n                            }\n                        }\n                    }\n                } else {\n                    for (int r = 0; r < N; ++r) {\n                        for (int c = 0; c < N; ++c) {\n                            if (s[r][c] && !t[r][c]) {\n                                int dist = abs(r - rx) + abs(c - ry);\n                                if (dist < best_dist) { best_dist = dist; best_p = {r, c}; }\n                            }\n                        }\n                    }\n                }\n                robot[i].target = best_p;\n            }\n        }\n\n        // 2. Choose best root move and rotations\n        int best_move = 4; // Stay\n        long long min_total_dist = 1e18;\n        vector<int> best_rots(V_prime, 0);\n\n        int move_dx[] = {-1, 1, 0, 0, 0}; // U, D, L, R, .\n        int move_dy[] = {0, 0, -1, 1, 0};\n        char move_char[] = {'U', 'D', 'L', 'R', '.'};\n\n        for (int m = 0; m < 5; ++m) {\n            int nrx = rx + move_dx[m];\n            int nry = ry + move_dy[m];\n            \n            if (nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n\n            long long current_total_dist = 0;\n            vector<int> current_rots(V_prime, 0);\n\n            for (int i = 1; i < V_prime; ++i) {\n                if (robot[i].target.x < 0) continue;\n\n                int best_r = -1;\n                int best_d = 1000000;\n                \n                // Try 3 rotations: current (0), CCW (1), CW (2)\n                for (int r = 0; r < 3; ++r) {\n                    int ndir = robot[i].dir;\n                    if (r == 1) ndir = (ndir + 3) % 4; // CCW\n                    else if (r == 2) ndir = (ndir + 1) % 4; // CW\n                    \n                    int fx = nrx + DX[ndir] * robot[i].L;\n                    int fy = nry + DY[ndir] * robot[i].L;\n                    int d = abs(fx - robot[i].target.x) + abs(fy - robot[i].target.y);\n                    if (d < best_d) {\n                        best_d = d;\n                        best_r = r;\n                    }\n                }\n                current_total_dist += best_d;\n                current_rots[i] = best_r;\n            }\n            if (current_total_dist < min_total_dist) {\n                min_total_dist = current_total_dist;\n                best_move = m;\n                best_rots = current_rots;\n            }\n        }\n\n        // Apply best move\n        rx += move_dx[best_move];\n        ry += move_dy[best_move];\n        \n        string S = \"\";\n        S += move_char[best_move];\n        for (int i = 1; i < V_prime; ++i) {\n            int r = best_rots[i];\n            if (r == 1) { S += 'L'; robot[i].dir = (robot[i].dir + 3) % 4; }\n            else if (r == 2) { S += 'R'; robot[i].dir = (robot[i].dir + 1) % 4; }\n            else S += '.';\n        }\n\n        // 3. Actions\n        string actions = \"\";\n        actions += '.'; // root does nothing\n        for (int i = 1; i < V_prime; ++i) {\n            int fx = rx + DX[robot[i].dir] * robot[i].L;\n            int fy = ry + DY[robot[i].dir] * robot[i].L;\n            \n            bool action = false;\n            if (fx >= 0 && fx < N && fy >= 0 && fy < N) {\n                if (robot[i].holding) {\n                    // Try to drop\n                    if (t[fx][fy] == 1 && s[fx][fy] == 0) {\n                        robot[i].holding = false;\n                        s[fx][fy] = 1;\n                        action = true;\n                    }\n                } else {\n                    // Try to pick\n                    if (s[fx][fy] == 1 && t[fx][fy] == 0) {\n                        robot[i].holding = true;\n                        s[fx][fy] = 0;\n                        action = true;\n                    }\n                }\n            }\n            actions += (action ? 'P' : '.');\n        }\n        cout << S << actions << endl;\n    }\n\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\n// Using a 64x64 grid to precompute mackerel-sardine density.\n// 64 is a safe size to keep operations under the 13ms-per-case time limit (64^3 = 262,144 ops).\nconst int GRID_SIZE = 64; \nconst int MAX_COORD = 100000;\n\nvoid solve() {\n    int N;\n    if (!(cin >> N)) return;\n\n    // Grid stores (mackerel_count - sardine_count)\n    vector<vector<int>> grid(GRID_SIZE, vector<int>(GRID_SIZE, 0));\n    \n    // Read Mackerels and populate grid\n    for (int i = 0; i < N; ++i) {\n        int x, y; cin >> x >> y;\n        // Map [0, 100000] to [0, 63]\n        int gx = min(x * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1);\n        int gy = min(y * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1);\n        grid[gx][gy]++;\n    }\n    // Read Sardines and populate grid\n    for (int i = 0; i < N; ++i) {\n        int x, y; cin >> x >> y;\n        int gx = min(x * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1);\n        int gy = min(y * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1);\n        grid[gx][gy]--;\n    }\n\n    // 2D Kadane's Algorithm to find the max weight sub-rectangle\n    // This finds the sub-rectangle [best_i1, best_i2] x [best_j1, best_j2] \n    // that maximizes the sum of (mackerels - sardines).\n    int max_sum = 0;\n    int best_i1 = 0, best_j1 = 0, best_i2 = 0, best_j2 = 0;\n\n    for (int i1 = 0; i1 < GRID_SIZE; ++i1) {\n        vector<int> col_sum(GRID_SIZE, 0);\n        for (int i2 = i1; i2 < GRID_SIZE; ++i2) {\n            for (int j = 0; j < GRID_SIZE; ++j) col_sum[j] += grid[i2][j];\n            \n            // 1D Kadane's on col_sum\n            int current_sum = 0, start_j = 0;\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                current_sum += col_sum[j];\n                if (current_sum < 0) {\n                    current_sum = 0;\n                    start_j = j + 1;\n                } else if (current_sum > max_sum) {\n                    max_sum = current_sum;\n                    best_i1 = i1; best_i2 = i2;\n                    best_j1 = start_j; best_j2 = j;\n                }\n            }\n        }\n    }\n\n    // Output the resulting polygon\n    if (max_sum <= 0) {\n        // If no region has a positive score, output a tiny 1x1 polygon\n        cout << 4 << endl;\n        cout << \"0 0\" << endl << \"1 0\" << endl << \"1 1\" << endl << \"0 1\" << endl;\n    } else {\n        // Convert grid indices back to coordinate range [0, 100000]\n        int step = (MAX_COORD + 1) / GRID_SIZE;\n        int x1 = best_i1 * step, y1 = best_j1 * step;\n        int x2 = min(MAX_COORD, (best_i2 + 1) * step), y2 = min(MAX_COORD, (best_j2 + 1) * step);\n        \n        // Output a rectangle (a valid orthogonal polygon with 4 vertices)\n        cout << 4 << endl;\n        cout << x1 << \" \" << y1 << endl;\n        cout << x2 << \" \" << y1 << endl;\n        cout << x2 << \" \" << y2 << endl;\n        cout << x1 << \" \" << y2 << endl;\n    }\n}\n\nint main() {\n    // Faster I/O is crucial for processing 150 test cases efficiently.\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <ctime>\n\nusing namespace std;\n\n// Configuration choice for each rectangle\nstruct Choice {\n    int r, d, b; // r: rotation (0 or 1), d: direction (0=U, 1=L), b: reference rectangle (-1 or 0..i-1)\n};\n\nint N, T;\ndouble sigma;\n// Since the judge uses true widths/heights, we don't strictly need to track them,\n// but we do need the count for the loop.\n\nint main() {\n    // Fast I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read initial data\n    if (!(cin >> N >> T >> sigma)) return 0;\n    // Consume the individual width/height estimates (not strictly needed for the strategy)\n    for (int i = 0; i < N; ++i) {\n        int w_tmp, h_tmp;\n        cin >> w_tmp >> h_tmp;\n    }\n\n    // Initialize the best sequence randomly\n    mt19937 rng(12345);\n    vector<Choice> best_seq(N);\n    for (int i = 0; i < N; ++i) {\n        best_seq[i].r = rng() % 2;\n        best_seq[i].d = rng() % 2;\n        best_seq[i].b = (i == 0) ? -1 : (int)(rng() % (i + 1)) - 1;\n    }\n\n    long long best_score = 4e18; // Initialize with a very large value\n\n    // Perform T turns of refinement\n    for (int t = 0; t < T; ++t) {\n        vector<Choice> candidate_seq = best_seq;\n        \n        // Mutate the candidate sequence: higher mutation rate early on, lower later\n        int num_mutations = max(1, (int)(N * (0.5 - 0.4 * (double)t / T)));\n        for (int m = 0; m < num_mutations; ++m) {\n            int i = rng() % N;\n            candidate_seq[i].r = rng() % 2;\n            candidate_seq[i].d = rng() % 2;\n            candidate_seq[i].b = (i == 0) ? -1 : (int)(rng() % (i + 1)) - 1;\n        }\n\n        // Output the configuration\n        cout << N << endl;\n        for (int i = 0; i < N; ++i) {\n            cout << i << \" \" << candidate_seq[i].r << \" \" \n                 << (candidate_seq[i].d == 0 ? 'U' : 'L') << \" \" \n                 << candidate_seq[i].b << endl;\n        }\n        cout.flush();\n\n        // Read the results from the judge\n        long long W_obs, H_obs;\n        if (!(cin >> W_obs >> H_obs)) break;\n        long long current_score = W_obs + H_obs;\n\n        // If the current result is better, update the best sequence\n        if (current_score < best_score) {\n            best_score = current_score;\n            best_seq = candidate_seq;\n        }\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <ctime>\n#include <chrono>\n\nusing namespace std;\n\n// Struct to represent an edge in the priority queue\nstruct Item {\n    int priority;\n    int u; // parent node\n    int v; // child node\n    bool operator<(const Item& other) const {\n        return priority < other.priority;\n    }\n};\n\nvoid solve() {\n    int N, M, H;\n    if (!(cin >> N >> M >> H)) return;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    // Skip coordinates as they are not used in the greedy logic\n    int x, y;\n    for (int i = 0; i < N; ++i) cin >> x >> y;\n\n    vector<int> best_p(N, -1);\n    long long best_score = -1;\n\n    // Time limit handling\n    clock_t start_time = clock();\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist(80, 120);\n    \n    // For root selection order\n    vector<int> nodes(N);\n    for(int i=0; i<N; ++i) nodes[i] = i;\n\n    int iter = 0;\n    while (true) {\n        // Periodically check time\n        if (iter % 10 == 0) {\n            if ((double)(clock() - start_time) / CLOCKS_PER_SEC > 1.8) break;\n        }\n        iter++;\n        \n        vector<int> p(N, -1);\n        vector<int> depth(N, 0);\n        vector<bool> visited(N, false);\n        \n        // Root selection heuristic to explore different configurations\n        if (iter % 3 == 0) {\n            sort(nodes.begin(), nodes.end(), [&](int a, int b){ return A[a] < A[b]; });\n        } else if (iter % 3 == 1) {\n            sort(nodes.begin(), nodes.end(), [&](int a, int b){ return A[a] > A[b]; });\n        } else {\n            shuffle(nodes.begin(), nodes.end(), rng);\n        }\n        \n        priority_queue<Item> pq;\n        int unvisited_count = N;\n        int order_idx = 0;\n        \n        // Build the forest\n        while (unvisited_count > 0) {\n            // Find next unvisited node to be a potential root\n            while (order_idx < N && visited[nodes[order_idx]]) {\n                order_idx++;\n            }\n            \n            if (pq.empty()) {\n                if (order_idx < N) {\n                    int r = nodes[order_idx];\n                    visited[r] = true;\n                    p[r] = -1;\n                    depth[r] = 0;\n                    unvisited_count--;\n                    \n                    // Add neighbors to PQ\n                    for (int neighbor : adj[r]) {\n                        if (!visited[neighbor]) {\n                            int gain = (depth[r] + 2) * A[neighbor];\n                            int randomized_gain = gain * dist(rng) / 100;\n                            pq.push({randomized_gain, r, neighbor});\n                        }\n                    }\n                }\n            } else {\n                Item top = pq.top();\n                pq.pop();\n                \n                if (visited[top.v]) continue;\n                // Constraint check: must not exceed depth H\n                if (depth[top.u] >= H) continue;\n                \n                visited[top.v] = true;\n                p[top.v] = top.u;\n                depth[top.v] = depth[top.u] + 1;\n                unvisited_count--;\n                \n                // Add neighbors to PQ\n                for (int neighbor : adj[top.v]) {\n                    if (!visited[neighbor]) {\n                        int gain = (depth[top.v] + 2) * A[neighbor];\n                        int randomized_gain = gain * dist(rng) / 100;\n                        pq.push({randomized_gain, top.v, neighbor});\n                    }\n                }\n            }\n        }\n        \n        // Calculate score\n        long long current_score = 0;\n        for (int j = 0; j < N; ++j) {\n            current_score += (long long)(depth[j] + 1) * A[j];\n        }\n        \n        // Keep the best solution\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_p = p;\n        }\n    }\n    \n    // Output final solution\n    for (int i = 0; i < N; ++i) {\n        cout << best_p[i] << (i == N - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    solve();\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n// Global variables for board size and state\nint N;\nvector<string> board;\n\n// Structure to store move information\nstruct Move {\n    char dir;\n    int p;\n};\n\n// Check if it's safe to remove an Oni at (r, c) by moving it Up\nbool is_removable_up(int r, int c) {\n    for (int i = 0; i < r; ++i) {\n        if (board[i][c] == 'o') return false;\n    }\n    return true;\n}\n\n// Check if it's safe to remove an Oni at (r, c) by moving it Down\nbool is_removable_down(int r, int c) {\n    for (int i = r + 1; i < N; ++i) {\n        if (board[i][c] == 'o') return false;\n    }\n    return true;\n}\n\n// Check if it's safe to remove an Oni at (r, c) by moving it Left\nbool is_removable_left(int r, int c) {\n    for (int j = 0; j < c; ++j) {\n        if (board[r][j] == 'o') return false;\n    }\n    return true;\n}\n\n// Check if it's safe to remove an Oni at (r, c) by moving it Right\nbool is_removable_right(int r, int c) {\n    for (int j = c + 1; j < N; ++j) {\n        if (board[r][j] == 'o') return false;\n    }\n    return true;\n}\n\n// Apply a single shift operation\nvoid apply_move(char dir, int p) {\n    if (dir == 'U') {\n        for (int i = 0; i < N - 1; ++i) board[i][p] = board[i+1][p];\n        board[N-1][p] = '.';\n    } else if (dir == 'D') {\n        for (int i = N - 1; i > 0; --i) board[i][p] = board[i-1][p];\n        board[0][p] = '.';\n    } else if (dir == 'L') {\n        for (int j = 0; j < N - 1; ++j) board[p][j] = board[p][j+1];\n        board[p][N-1] = '.';\n    } else if (dir == 'R') {\n        for (int j = N - 1; j > 0; --j) board[p][j] = board[p][j-1];\n        board[p][0] = '.';\n    }\n}\n\nint main() {\n    // Faster I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    cin >> N;\n    board.resize(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    vector<Move> ans;\n    // Main loop: greedily remove the easiest Oni\n    while (true) {\n        int best_r = -1, best_c = -1;\n        char best_dir = ' ';\n        int min_cost = 10000;\n        bool oni_exists = false;\n\n        // Find all removable Oni and pick the one with the smallest cost\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (board[r][c] == 'x') {\n                    oni_exists = true;\n                    // Check Up\n                    if (is_removable_up(r, c)) {\n                        if (r + 1 < min_cost) {\n                            min_cost = r + 1;\n                            best_r = r; best_c = c; best_dir = 'U';\n                        }\n                    }\n                    // Check Down\n                    if (is_removable_down(r, c)) {\n                        if (N - r < min_cost) {\n                            min_cost = N - r;\n                            best_r = r; best_c = c; best_dir = 'D';\n                        }\n                    }\n                    // Check Left\n                    if (is_removable_left(r, c)) {\n                        if (c + 1 < min_cost) {\n                            min_cost = c + 1;\n                            best_r = r; best_c = c; best_dir = 'L';\n                        }\n                    }\n                    // Check Right\n                    if (is_removable_right(r, c)) {\n                        if (N - c < min_cost) {\n                            min_cost = N - c;\n                            best_r = r; best_c = c; best_dir = 'R';\n                        }\n                    }\n                }\n            }\n        }\n\n        // If no Oni are left, terminate\n        if (!oni_exists) break;\n        // If no valid move is found, break (should not happen given problem guarantees)\n        if (best_dir == ' ') break;\n\n        // Perform one move for the chosen Oni\n        int p = (best_dir == 'U' || best_dir == 'D') ? best_c : best_r;\n        apply_move(best_dir, p);\n        ans.push_back({best_dir, p});\n    }\n\n    // Output all operations\n    for (const auto& m : ans) {\n        cout << m.dir << \" \" << m.p << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <numeric>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Global variables for problem constraints\nint N, L;\nvector<int> T;\n\n// Function to calculate the L1 error for a given configuration of transitions\nlong long calculate_error(const vector<int>& a, const vector<int>& b) {\n    // counts[i] stores the number of times employee i has cleaned so far\n    vector<int> counts(N, 0);\n    \n    // First week: employee 0 cleans\n    int current = 0;\n    counts[0] = 1;\n    \n    // Simulate from week 2 to L\n    // In each step, determine the next cleaner based on parity of counts[current]\n    for (int i = 1; i < L; ++i) {\n        // If counts[current] is odd, use a[current], else use b[current]\n        int next = (counts[current] % 2 != 0) ? a[current] : b[current];\n        current = next;\n        counts[current]++;\n    }\n    \n    long long error = 0;\n    for (int i = 0; i < N; ++i) {\n        error += abs(counts[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    // Optimize I/O operations\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    // Read N, L, and T_i values\n    if (!(cin >> N >> L)) return 0;\n    T.resize(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n    \n    // Random number generator\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    // Initial State: random assignment\n    vector<int> a(N), b(N);\n    for (int i = 0; i < N; ++i) {\n        a[i] = rng() % N;\n        b[i] = rng() % N;\n    }\n    \n    long long current_error = calculate_error(a, b);\n    \n    // Simulated Annealing parameters\n    auto start_time = chrono::steady_clock::now();\n    double temp = 10000.0;\n    double min_temp = 0.01;\n    \n    // SA iteration tracker\n    long long iter = 0;\n    \n    // Main SA loop\n    while (true) {\n        iter++;\n        // Check time limit every 1024 iterations\n        if ((iter & 1023) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1850) {\n                break;\n            }\n        }\n        \n        // Randomly select employee i and which pointer to change (a or b)\n        int i = rng() % N;\n        int old_val;\n        bool is_a = (rng() & 1);\n        \n        if (is_a) {\n            old_val = a[i];\n            a[i] = rng() % N;\n        } else {\n            old_val = b[i];\n            b[i] = rng() % N;\n        }\n        \n        long long new_error = calculate_error(a, b);\n        \n        // Metropolis acceptance criterion\n        if (new_error < current_error) {\n            current_error = new_error;\n        } else {\n            // Accept worse solutions with a probability that decreases over time\n            double diff = (double)(current_error - new_error);\n            if (exp(diff / temp) > (double)(rng() % 1000000) / 1000000.0) {\n                current_error = new_error;\n            } else {\n                // Revert change\n                if (is_a) a[i] = old_val;\n                else b[i] = old_val;\n            }\n        }\n        \n        // Cooling schedule\n        temp = max(min_temp, temp * 0.999999);\n    }\n    \n    // Output the optimized transitions\n    for (int i = 0; i < N; ++i) {\n        cout << a[i] << \" \" << b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <iomanip>\n\nusing namespace std;\n\n// Structure to represent a city\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double x, y; // Estimated coordinates\n};\n\n// Function to calculate distance squared\ndouble distSq(double x1, double y1, double x2, double y2) {\n    return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\n}\n\n// Function to calculate distance rounded down\nlong long distInt(double x1, double y1, double x2, double y2) {\n    return (long long)floor(sqrt(distSq(x1, y1, x2, y2)));\n}\n\n// Function to perform a query\nvector<pair<int, int>> query(const vector<int>& c) {\n    if (c.size() < 2) return {};\n    cout << \"? \" << c.size();\n    for (int city_id : c) cout << \" \" << city_id;\n    cout << endl;\n    \n    vector<pair<int, int>> edges;\n    for (int i = 0; i < (int)c.size() - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        edges.push_back({u, v});\n    }\n    return edges;\n}\n\n// Calculate estimated MST cost for a given clustering\n// This helps pick the best initial clustering among different projections\ndouble calculateClusteringCost(const vector<vector<int>>& groups, const vector<City>& cities) {\n    double total_cost = 0;\n    for (const auto& group : groups) {\n        if (group.size() <= 1) continue;\n        int n = group.size();\n        vector<bool> visited(n, false);\n        vector<double> min_dist(n, 1e18);\n        min_dist[0] = 0;\n        for(int i=0; i<n; ++i) {\n            int u = -1;\n            for(int j=0; j<n; ++j) {\n                if(!visited[j] && (u == -1 || min_dist[j] < min_dist[u])) u = j;\n            }\n            if (u == -1 || min_dist[u] == 1e18) break;\n            visited[u] = true;\n            total_cost += min_dist[u];\n            for(int v=0; v<n; ++v) {\n                if(!visited[v]) {\n                    double d = sqrt(distSq(cities[group[u]].x, cities[group[u]].y, \n                                           cities[group[v]].x, cities[group[v]].y));\n                    min_dist[v] = min(min_dist[v], d);\n                }\n            }\n        }\n    }\n    return total_cost;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    vector<City> cities(N);\n    for (int i = 0; i < N; ++i) {\n        cities[i].id = 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.0;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2.0;\n    }\n\n    // Try multiple sorting directions to find the best clustering\n    vector<vector<int>> best_groups;\n    double min_cost = 1e18;\n    int num_angles = 20;\n\n    for (int i = 0; i < num_angles; ++i) {\n        double angle = M_PI * i / num_angles;\n        double cos_a = cos(angle);\n        double sin_a = sin(angle);\n        \n        vector<int> indices(N);\n        for(int j=0; j<N; ++j) indices[j] = j;\n        \n        sort(indices.begin(), indices.end(), [&](int a, int b) {\n            double pos_a = cities[a].x * cos_a + cities[a].y * sin_a;\n            double pos_b = cities[b].x * cos_a + cities[b].y * sin_a;\n            return pos_a < pos_b;\n        });\n        \n        vector<vector<int>> current_groups(M);\n        int start_idx = 0;\n        for(int j=0; j<M; ++j) {\n            for(int k=0; k<G[j]; ++k) {\n                current_groups[j].push_back(indices[start_idx++]);\n            }\n        }\n        \n        double cost = calculateClusteringCost(current_groups, cities);\n        if (cost < min_cost) {\n            min_cost = cost;\n            best_groups = current_groups;\n        }\n    }\n    \n    vector<vector<int>> groups = best_groups;\n\n    // Querying\n    vector<vector<pair<int, int>>> query_edges(M);\n    \n    // Allocate queries proportionally to group size\n    vector<int> q_per_group(M, 0);\n    int total_nodes_with_edges = 0;\n    for (int i = 0; i < M; ++i) {\n        if (G[i] > 1) total_nodes_with_edges += (G[i] - 1);\n    }\n    \n    if (total_nodes_with_edges == 0) total_nodes_with_edges = 1;\n    \n    int queries_used = 0;\n    for(int i=0; i<M; ++i) {\n        if (G[i] > 1) {\n            q_per_group[i] = (int)((long long)Q * (G[i] - 1) / total_nodes_with_edges);\n            queries_used += q_per_group[i];\n        }\n    }\n    \n    // Distribute remaining queries\n    for(int i=0; i<M && queries_used < Q; ++i) {\n        if (G[i] > 1) {\n            q_per_group[i]++;\n            queries_used++;\n        }\n    }\n    \n    mt19937 rng(42);\n    for(int i=0; i<M; ++i) {\n        for(int q=0; q<q_per_group[i]; ++q) {\n            if (groups[i].size() < 2) continue;\n            \n            int sz = min((int)groups[i].size(), L);\n            \n            // Pick a random city, then find sz-1 nearest neighbors\n            int start_node_idx = rng() % groups[i].size();\n            int start_node = groups[i][start_node_idx];\n            \n            vector<pair<double, int>> neighbors;\n            for(int city_id : groups[i]) {\n                double d = distSq(cities[city_id].x, cities[city_id].y, \n                                 cities[start_node].x, cities[start_node].y);\n                neighbors.push_back({d, city_id});\n            }\n            sort(neighbors.begin(), neighbors.end());\n            \n            vector<int> subset;\n            for(int j=0; j<sz; ++j) {\n                subset.push_back(neighbors[j].second);\n            }\n            \n            auto edges = query(subset);\n            for(auto& e : edges) {\n                query_edges[i].push_back(e);\n            }\n        }\n    }\n    \n    // Output MST construction\n    cout << \"!\" << endl;\n    for(int i=0; i<M; ++i) {\n        // Output cities\n        for(int j=0; j<G[i]; ++j) {\n            cout << groups[i][j] << (j == G[i]-1 ? \"\" : \" \");\n        }\n        cout << endl;\n        \n        // Build MST\n        struct Edge { int u, v; long long w; };\n        vector<Edge> all_edges;\n        \n        // Add query edges (weight 0 to ensure priority)\n        for(auto& e : query_edges[i]) {\n            all_edges.push_back({e.first, e.second, 0});\n        }\n        \n        // Add potential edges\n        for(size_t u=0; u<groups[i].size(); ++u) {\n            for(size_t v=u+1; v<groups[i].size(); ++v) {\n                int city_u = groups[i][u];\n                int city_v = groups[i][v];\n                long long d = distInt(cities[city_u].x, cities[city_u].y, cities[city_v].x, cities[city_v].y);\n                all_edges.push_back({city_u, city_v, d});\n            }\n        }\n        \n        sort(all_edges.begin(), all_edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        \n        // DSU\n        vector<int> parent(N);\n        for(int j=0; j<N; ++j) parent[j] = j;\n        \n        auto find = [&](auto self, int node) -> int {\n            return parent[node] == node ? node : parent[node] = self(self, parent[node]);\n        };\n        \n        vector<pair<int, int>> mst_edges;\n        for(auto& e : all_edges) {\n            int root_u = find(find, e.u);\n            int root_v = find(find, e.v);\n            if(root_u != root_v) {\n                parent[root_u] = root_v;\n                mst_edges.push_back({e.u, e.v});\n            }\n        }\n        \n        for(auto& e : mst_edges) {\n            cout << e.first << \" \" << e.second << endl;\n        }\n    }\n    \n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <tuple>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Constants\nconst int N = 20;\n\n// Directions: U, D, L, R\nconst int DR[] = {-1, 1, 0, 0};\nconst int DC[] = {0, 0, -1, 1};\nconst char D_CHAR[] = {'U', 'D', 'L', 'R'};\n\nstruct State {\n    int r, c, dist;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\n// Function to simulate sliding and find the stopping position\npair<int, int> get_stop_pos(int r, int c, int dr, int dc, const vector<vector<int>>& grid) {\n    int nr = r, nc = c;\n    while (true) {\n        int next_r = nr + dr;\n        int next_c = nc + dc;\n        // Blocks are at the edges, so sliding always stops\n        if (next_r < 0 || next_r >= N || next_c < 0 || next_c >= N || grid[next_r][next_c] == 1) {\n            return {nr, nc};\n        }\n        nr = next_r;\n        nc = next_c;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n, m;\n    cin >> n >> m;\n    int r0, c0;\n    cin >> r0 >> c0;\n    vector<pair<int, int>> targets(m);\n    for (int i = 0; i < m; ++i) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n\n    vector<vector<int>> grid(N, vector<int>(N, 0));\n    int curr_r = r0, curr_c = c0;\n\n    for (int t = 0; t < m; ++t) {\n        int tr = targets[t].first;\n        int tc = targets[t].second;\n\n        // Dijkstra to find shortest path to (tr, tc)\n        vector<vector<int>> dist(N, vector<int>(N, 1e9));\n        vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n        vector<vector<string>> action_path(N, vector<string>(N, \"\"));\n        \n        priority_queue<State, vector<State>, greater<State>> pq;\n        dist[curr_r][curr_c] = 0;\n        pq.push({curr_r, curr_c, 0});\n        \n        while (!pq.empty()) {\n            State top = pq.top();\n            pq.pop();\n            \n            if (top.dist > dist[top.r][top.c]) continue;\n            if (top.r == tr && top.c == tc) break;\n            \n            for (int i = 0; i < 4; ++i) {\n                // Move action\n                int nr = top.r + DR[i];\n                int nc = top.c + DC[i];\n                if (nr >= 0 && nr < N && nc >= 0 && nc < N) {\n                    int cost = (grid[nr][nc] == 1) ? 2 : 1;\n                    string actions = \"\";\n                    if (grid[nr][nc] == 1) actions += string(\"A \") + D_CHAR[i] + \"\\n\";\n                    actions += string(\"M \") + D_CHAR[i] + \"\\n\";\n                    \n                    if (dist[top.r][top.c] + cost < dist[nr][nc]) {\n                        dist[nr][nc] = dist[top.r][top.c] + cost;\n                        parent[nr][nc] = {top.r, top.c};\n                        action_path[nr][nc] = actions;\n                        pq.push({nr, nc, dist[nr][nc]});\n                    }\n                }\n                \n                // Slide action\n                pair<int, int> stop = get_stop_pos(top.r, top.c, DR[i], DC[i], grid);\n                int sr = stop.first, sc = stop.second;\n                int br = sr + DR[i], bc = sc + DC[i];\n                \n                // Check if we need to add a block to stop at (sr, sc)\n                bool need_block = (br >= 0 && br < N && bc >= 0 && bc < N && grid[br][bc] == 0);\n                int cost = need_block ? 2 : 1;\n                \n                string actions = \"\";\n                if (need_block) actions += string(\"A \") + D_CHAR[i] + \"\\n\";\n                actions += string(\"S \") + D_CHAR[i] + \"\\n\";\n                \n                if (dist[top.r][top.c] + cost < dist[sr][sc]) {\n                    dist[sr][sc] = dist[top.r][top.c] + cost;\n                    parent[sr][sc] = {top.r, top.c};\n                    action_path[sr][sc] = actions;\n                    pq.push({sr, sc, dist[sr][sc]});\n                }\n            }\n        }\n        \n        // Reconstruct and execute path\n        vector<string> path_actions;\n        int curr_r2 = tr, curr_c2 = tc;\n        while (curr_r2 != curr_r || curr_c2 != curr_c) {\n            path_actions.push_back(action_path[curr_r2][curr_c2]);\n            pair<int, int> p = parent[curr_r2][curr_c2];\n            curr_r2 = p.first;\n            curr_c2 = p.second;\n        }\n        reverse(path_actions.begin(), path_actions.end());\n        \n        for (const string& s : path_actions) {\n            cout << s;\n            size_t pos = 0;\n            while(pos < s.length()){\n                size_t next_line = s.find('\\n', pos);\n                string line = s.substr(pos, next_line - pos);\n                pos = next_line + 1;\n                if(line.empty()) continue;\n                \n                char act = line[0], dir = line[2];\n                int dr = 0, dc = 0;\n                if(dir == 'U') dr = -1; else if(dir == 'D') dr = 1; else if(dir == 'L') dc = -1; else if(dir == 'R') dc = 1;\n                \n                if(act == 'A'){\n                    int nr = curr_r + dr;\n                    int nc = curr_c + dc;\n                    grid[nr][nc] = 1 - grid[nr][nc];\n                } else if(act == 'M'){\n                    curr_r += dr;\n                    curr_c += dc;\n                } else if(act == 'S'){\n                    pair<int, int> stop = get_stop_pos(curr_r, curr_c, dr, dc, grid);\n                    curr_r = stop.first;\n                    curr_c = stop.second;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}"},"4":{"ahc001":"#include <iostream>\n#include <vector>\n#include <chrono>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Structure to represent an axis-aligned rectangle\nstruct Rect {\n    int x1, y1, x2, y2;\n};\n\nint N;\nvector<int> X, Y, R;\nvector<Rect> rects;\nvector<Rect> best_rects;\n\n// Fast Xorshift RNG for performance\nstruct Xorshift {\n    uint32_t x = 123456789, y = 362436069, z = 521288629, w = 88675123;\n    uint32_t next() {\n        uint32_t t = x ^ (x << 11);\n        x = y; y = z; z = w;\n        return w = w ^ (w >> 19) ^ t ^ (t >> 8);\n    }\n    int next_int(int n) { return next() % n; }\n    double next_double() { return (double)next() / 4294967296.0; }\n} rng;\n\n// Objective function: p_i = 1 - (1 - min/max)^2 = 2x - x^2\ninline double get_p(int i, int s) {\n    double r = R[i];\n    double x = min(r, (double)s) / max(r, (double)s);\n    return 2.0 * x - x * x;\n}\n\n// Check if rectangle 'r' overlaps with any other rectangle\n// idx is the index of the rectangle currently being moved\ninline bool check_overlap(int idx, const Rect& r) {\n    for (int i = 0; i < N; ++i) {\n        if (i == idx) continue;\n        // Overlap condition:\n        // rects[i].x1 < r.x2 && rects[i].x2 > r.x1 && rects[i].y1 < r.y2 && rects[i].y2 > r.y1\n        if (r.x1 < rects[i].x2 && r.x2 > rects[i].x1 &&\n            r.y1 < rects[i].y2 && r.y2 > rects[i].y1) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    // Fast I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N)) return 0;\n    X.resize(N);\n    Y.resize(N);\n    R.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> X[i] >> Y[i] >> R[i];\n    }\n\n    // Initial state: Each rectangle is 1x1 at its target location\n    rects.resize(N);\n    for (int i = 0; i < N; ++i) {\n        rects[i] = {X[i], Y[i], X[i] + 1, Y[i] + 1};\n    }\n    best_rects = rects;\n\n    double current_total_score = 0;\n    for (int i = 0; i < N; ++i) {\n        current_total_score += get_p(i, 1);\n    }\n    double best_total_score = current_total_score;\n\n    auto start_time = chrono::steady_clock::now();\n    \n    // SA parameters\n    double T_start = 0.1;\n    double T_end = 0.0001;\n    \n    // Main loop\n    int iter = 0;\n    while (true) {\n        // Check time every 1024 iterations to minimize overhead\n        if ((iter++ & 1023) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 4700) break;\n        }\n\n        // Calculate progress (0.0 to 1.0) and temperature\n        double elapsed_ms = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count();\n        double progress = elapsed_ms / 4700.0;\n        double T = T_start * pow(T_end / T_start, progress);\n\n        // Pick a rectangle to mutate\n        int i = rng.next_int(N);\n\n        // Adaptive delta_range: larger at the start for exploration, smaller at the end for precision\n        int delta_range = max(1, (int)(1000.0 * (1.0 - progress)));\n        int delta = rng.next_int(2 * delta_range + 1) - delta_range;\n\n        Rect next_rect = rects[i];\n        int side = rng.next_int(4);\n\n        // Mutate one side, ensuring target point (X[i], Y[i]) remains inside\n        if (side == 0) { // x1\n            next_rect.x1 = max(0, min(X[i], next_rect.x1 + delta));\n        } else if (side == 1) { // x2\n            next_rect.x2 = max(X[i] + 1, min(10000, next_rect.x2 + delta));\n        } else if (side == 2) { // y1\n            next_rect.y1 = max(0, min(Y[i], next_rect.y1 + delta));\n        } else { // y2\n            next_rect.y2 = max(Y[i] + 1, min(10000, next_rect.y2 + delta));\n        }\n\n        // Validate: skip degenerate rectangles and overlaps\n        if (next_rect.x1 == next_rect.x2 || next_rect.y1 == next_rect.y2) continue;\n        if (check_overlap(i, next_rect)) continue;\n\n        // Calculate score change\n        int old_s = (rects[i].x2 - rects[i].x1) * (rects[i].y2 - rects[i].y1);\n        int new_s = (next_rect.x2 - next_rect.x1) * (next_rect.y2 - next_rect.y1);\n        double delta_score = get_p(i, new_s) - get_p(i, old_s);\n\n        // Metropolis criterion: accept if better or with probability based on T\n        if (delta_score > 0 || (T > 1e-9 && exp(delta_score / T) > rng.next_double())) {\n            rects[i] = next_rect;\n            current_total_score += delta_score;\n            if (current_total_score > best_total_score) {\n                best_total_score = current_total_score;\n                best_rects = rects;\n            }\n        }\n    }\n\n    // Output best result found\n    for (int i = 0; i < N; ++i) {\n        cout << best_rects[i].x1 << \" \" << best_rects[i].y1 << \" \" << best_rects[i].x2 << \" \" << best_rects[i].y2 << \"\\n\";\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cstring>\n#include <numeric>\n\nusing namespace std;\n\n// Global variables\nint si, sj;\nint t[50][50];\nint p[50][50];\nint M = 0;\nvector<int> tile_neighbors[2500];\nint tile_values[2500];\nint degree[2500];\nbool is_visited_tile[2500];\n\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dchar[] = {'U', 'D', 'L', 'R'};\n\nint main() {\n    // Faster I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read input\n    if (!(cin >> si >> sj)) return 0;\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> t[i][j];\n            M = max(M, t[i][j] + 1);\n        }\n    }\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> p[i][j];\n            tile_values[t[i][j]] += p[i][j];\n        }\n    }\n\n    // Precompute tile adjacency\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            int current_tile = t[i][j];\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dr[k];\n                int nj = j + dc[k];\n                if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n                    int neighbor_tile = t[ni][nj];\n                    if (current_tile != neighbor_tile) {\n                        tile_neighbors[current_tile].push_back(neighbor_tile);\n                    }\n                }\n            }\n        }\n    }\n    // Remove duplicates from neighbor lists\n    for (int i = 0; i < M; ++i) {\n        sort(tile_neighbors[i].begin(), tile_neighbors[i].end());\n        tile_neighbors[i].erase(unique(tile_neighbors[i].begin(), tile_neighbors[i].end()), tile_neighbors[i].end());\n    }\n\n    string best_path = \"\";\n    int max_total_score = -1;\n\n    auto start_time = chrono::high_resolution_clock::now();\n    mt19937 rng(12345);\n\n    // Randomized greedy loop with weighted selection\n    while (true) {\n        auto current_time = chrono::high_resolution_clock::now();\n        // Time limit check (safety margin at 1.9s)\n        if (chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count() > 1900) {\n            break;\n        }\n\n        // Reset state\n        memset(is_visited_tile, 0, sizeof(is_visited_tile));\n        for(int i = 0; i < M; ++i) degree[i] = tile_neighbors[i].size();\n\n        string current_path = \"\";\n        int current_total_score = 0;\n        int curr_r = si;\n        int curr_c = sj;\n        int curr_t = t[si][sj];\n        \n        is_visited_tile[curr_t] = true;\n        // Update neighbors\n        for(int neighbor : tile_neighbors[curr_t]) degree[neighbor]--;\n        current_total_score += p[curr_r][curr_c];\n        \n        // Randomize alpha parameter per iteration for search diversity\n        int alpha = rng() % 30;\n\n        while (true) {\n            struct Candidate {\n                int r, c, dir_idx;\n                double score;\n            };\n            vector<Candidate> candidates;\n            \n            // Explore valid neighbors\n            for (int k = 0; k < 4; ++k) {\n                int nr = curr_r + dr[k];\n                int nc = curr_c + dc[k];\n                if (nr >= 0 && nr < 50 && nc >= 0 && nc < 50) {\n                    int next_t = t[nr][nc];\n                    // Constraint: Must be unvisited tile\n                    if (next_t != curr_t && !is_visited_tile[next_t]) {\n                        double score = (double)tile_values[next_t] + (double)alpha * degree[next_t];\n                        candidates.push_back({nr, nc, k, score});\n                    }\n                }\n            }\n            \n            if (candidates.empty()) break;\n            \n            // Use weighted random selection to pick the next step\n            vector<double> weights;\n            for(auto& cand : candidates) weights.push_back(max(0.1, cand.score));\n            \n            discrete_distribution<int> dist(weights.begin(), weights.end());\n            int best_idx = dist(rng);\n            \n            // Execute move\n            curr_r = candidates[best_idx].r;\n            curr_c = candidates[best_idx].c;\n            int dir = candidates[best_idx].dir_idx;\n            current_path += dchar[dir];\n            \n            curr_t = t[curr_r][curr_c];\n            is_visited_tile[curr_t] = true;\n            for(int neighbor : tile_neighbors[curr_t]) degree[neighbor]--;\n            current_total_score += p[curr_r][curr_c];\n        }\n        \n        // Update best path if better found\n        if (current_total_score > max_total_score) {\n            max_total_score = current_total_score;\n            best_path = current_path;\n        }\n    }\n    \n    cout << best_path << endl;\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Grid dimensions (30x30)\nconst int R = 30;\nconst int C = 30;\n\n// Edge weights and visit counts\ndouble hor[R][C - 1];\ndouble ver[R - 1][C];\nint cnt_hor[R][C - 1];\nint cnt_ver[R - 1][C];\n\nstruct Node {\n    int r, c;\n    double f; // f = g + h\n    double g; // actual cost so far\n    bool operator>(const Node& other) const {\n        return f > other.f;\n    }\n};\n\n// Heuristic: Manhattan distance * min_possible_edge_weight\n// Min possible weight = 1000.\ninline double heuristic(int r, int c, int tr, int tc) {\n    return (abs(r - tr) + abs(c - tc)) * 1000.0;\n}\n\n// Function to compute the shortest path using A*\nstring get_path(int sr, int sc, int tr, int tc) {\n    static double dist[R][C];\n    static pair<int, int> parent[R][C];\n    static char dir[R][C];\n    \n    for(int i = 0; i < R; ++i) {\n        for(int j = 0; j < C; ++j) {\n            dist[i][j] = 1e18;\n            parent[i][j] = {-1, -1};\n            dir[i][j] = ' ';\n        }\n    }\n    \n    priority_queue<Node, vector<Node>, greater<Node>> pq;\n    \n    dist[sr][sc] = 0;\n    pq.push({sr, sc, heuristic(sr, sc, tr, tc), 0});\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    char dchar[] = {'U', 'D', 'L', 'R'};\n    \n    while (!pq.empty()) {\n        Node current = pq.top();\n        pq.pop();\n        \n        int r = current.r;\n        int c = current.c;\n        \n        if (current.g > dist[r][c]) continue;\n        if (r == tr && c == tc) break;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i];\n            int nc = c + dc[i];\n            \n            if (nr >= 0 && nr < R && nc >= 0 && nc < C) {\n                double weight = 0;\n                if (i == 0) weight = ver[r - 1][c]; // U\n                else if (i == 1) weight = ver[r][c]; // D\n                else if (i == 2) weight = hor[r][c - 1]; // L\n                else if (i == 3) weight = hor[r][c]; // R\n                \n                if (dist[nr][nc] > dist[r][c] + weight) {\n                    dist[nr][nc] = dist[r][c] + weight;\n                    parent[nr][nc] = {r, c};\n                    dir[nr][nc] = dchar[i];\n                    pq.push({nr, nc, dist[nr][nc] + heuristic(nr, nc, tr, tc), dist[nr][nc]});\n                }\n            }\n        }\n    }\n    \n    // Reconstruct the path\n    string path = \"\";\n    int curr_r = tr;\n    int curr_c = tc;\n    while (curr_r != sr || curr_c != sc) {\n        char d = dir[curr_r][curr_c];\n        path += d;\n        pair<int, int> p = parent[curr_r][curr_c];\n        curr_r = p.first;\n        curr_c = p.second;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    // Initialize weights to a neutral middle value 5000.0\n    for (int i = 0; i < R; ++i)\n        for (int j = 0; j < C - 1; ++j) { hor[i][j] = 5000.0; cnt_hor[i][j] = 0; }\n    for (int i = 0; i < R - 1; ++i)\n        for (int j = 0; j < C; ++j) { ver[i][j] = 5000.0; cnt_ver[i][j] = 0; }\n    \n    for (int k = 0; k < 1000; ++k) {\n        int sr, sc, tr, tc;\n        cin >> sr >> sc >> tr >> tc;\n        \n        string path = get_path(sr, sc, tr, tc);\n        cout << path << endl; // Flushes output\n        \n        int measured_len;\n        cin >> measured_len;\n        \n        // Calculate predicted path length based on current estimates\n        double path_len = 0;\n        int curr_r = sr;\n        int curr_c = sc;\n        \n        for (char d : path) {\n            if (d == 'U') path_len += ver[curr_r - 1][curr_c];\n            else if (d == 'D') path_len += ver[curr_r][curr_c];\n            else if (d == 'L') path_len += hor[curr_r][curr_c - 1];\n            else if (d == 'R') path_len += hor[curr_r][curr_c];\n            \n            if (d == 'U') curr_r--;\n            else if (d == 'D') curr_r++;\n            else if (d == 'L') curr_c--;\n            else if (d == 'R') curr_c++;\n        }\n        \n        // Calculate ratio and clamp it to avoid wild swings\n        double ratio = (double)measured_len / (path_len + 1e-9);\n        if (ratio < 0.5) ratio = 0.5;\n        if (ratio > 2.0) ratio = 2.0;\n        \n        // Update weights\n        curr_r = sr;\n        curr_c = sc;\n        for (char d : path) {\n            double* w_ptr = nullptr;\n            int* cnt_ptr = nullptr;\n            \n            if (d == 'U') { w_ptr = &ver[curr_r - 1][curr_c]; cnt_ptr = &cnt_ver[curr_r - 1][curr_c]; }\n            else if (d == 'D') { w_ptr = &ver[curr_r][curr_c]; cnt_ptr = &cnt_ver[curr_r][curr_c]; }\n            else if (d == 'L') { w_ptr = &hor[curr_r][curr_c - 1]; cnt_ptr = &cnt_hor[curr_r][curr_c - 1]; }\n            else if (d == 'R') { w_ptr = &hor[curr_r][curr_c]; cnt_ptr = &cnt_hor[curr_r][curr_c]; }\n            \n            // Dynamic learning rate\n            (*cnt_ptr)++;\n            double alpha = 0.5 / (1.0 + 0.05 * (*cnt_ptr));\n            \n            *w_ptr *= (1.0 + alpha * (ratio - 1.0));\n            \n            // Constraint check\n            if (*w_ptr < 100) *w_ptr = 100;\n            if (*w_ptr > 10000) *w_ptr = 10000;\n            \n            if (d == 'U') curr_r--;\n            else if (d == 'D') curr_r++;\n            else if (d == 'L') curr_c--;\n            else if (d == 'R') curr_c++;\n        }\n    }\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 20;\nint M;\nvector<string> S;\nint grid[N][N]; // 0-7: A-H, 8: .\nint mismatches[800][800];\nint num_valid[800]; // Number of valid placements for each string\nint count_c;\nint count_d; // Number of '.' cells\n\nstruct Placement {\n    int s_idx;\n    int p_idx;\n};\nvector<Placement> affected[N][N];\n\nstruct PlacementInfo {\n    int line_idx;\n    int start_pos;\n    string s;\n};\nvector<PlacementInfo> all_placements[800];\n\nint get_char_idx(char c) {\n    if (c == '.') return 8;\n    return c - 'A';\n}\n\nchar get_char(int idx) {\n    if (idx == 8) return '.';\n    return idx + 'A';\n}\n\nvoid init() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = 8; // '.'\n        }\n    }\n    count_c = 0;\n    count_d = N * N;\n\n    for (int i = 0; i < M; ++i) {\n        string s = S[i];\n        int len = s.length();\n        // 40 lines: 0-19 rows, 20-39 cols\n        for (int line = 0; line < 2 * N; ++line) {\n            for (int start = 0; start < N; ++start) {\n                int p_idx = line * N + start;\n                all_placements[i].push_back({line, start, s});\n                \n                // Mismatches initially len because grid is '.'\n                mismatches[i][p_idx] = len;\n                \n                for (int k = 0; k < len; ++k) {\n                    int r, c;\n                    if (line < N) {\n                        r = line;\n                        c = (start + k) % N;\n                    } else {\n                        r = (start + k) % N;\n                        c = line - N;\n                    }\n                    affected[r][c].push_back({i, p_idx});\n                }\n            }\n        }\n        num_valid[i] = 0;\n    }\n}\n\nvoid update_grid(int r, int c, int new_val) {\n    int old_val = grid[r][c];\n    if (old_val == new_val) return;\n\n    if (old_val == 8 && new_val != 8) count_d--;\n    else if (old_val != 8 && new_val == 8) count_d++;\n\n    grid[r][c] = new_val;\n\n    for (auto& p : affected[r][c]) {\n        int s_idx = p.s_idx;\n        int p_idx = p.p_idx;\n        \n        bool was_valid = (mismatches[s_idx][p_idx] == 0);\n        \n        PlacementInfo& pi = all_placements[s_idx][p_idx];\n        int len = pi.s.length();\n        int k = -1;\n        \n        if (pi.line_idx < N) {\n            k = (c - pi.start_pos + N) % N;\n        } else {\n            k = (r - pi.start_pos + N) % N;\n        }\n        \n        // Target character at this position\n        int target_idx = get_char_idx(pi.s[k]);\n        \n        auto matches = [&](int cell_val, int target) {\n            return cell_val == target;\n        };\n        \n        bool old_match = matches(old_val, target_idx);\n        bool new_match = matches(new_val, target_idx);\n        \n        if (!old_match && new_match) mismatches[s_idx][p_idx]--;\n        else if (old_match && !new_match) mismatches[s_idx][p_idx]++;\n        \n        bool is_valid = (mismatches[s_idx][p_idx] == 0);\n        \n        if (was_valid && !is_valid) {\n            num_valid[s_idx]--;\n            if (num_valid[s_idx] == 0) count_c--;\n        } else if (!was_valid && is_valid) {\n            if (num_valid[s_idx] == 0) count_c++;\n            num_valid[s_idx]++;\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_in; cin >> N_in;\n    cin >> M;\n    S.resize(M);\n    for (int i = 0; i < M; ++i) cin >> S[i];\n\n    init();\n    \n    // Greedy initialization\n    vector<int> p(M);\n    for(int i=0; i<M; ++i) p[i] = i;\n    mt19937 rng(1337);\n    shuffle(p.begin(), p.end(), rng);\n    \n    for(int i : p) {\n        if (num_valid[i] > 0) continue;\n        int p_idx = rng() % all_placements[i].size();\n        PlacementInfo& pi = all_placements[i][p_idx];\n        \n        for (int k = 0; k < (int)pi.s.length(); ++k) {\n            int r, c;\n            if (pi.line_idx < N) {\n                r = pi.line_idx;\n                c = (pi.start_pos + k) % N;\n            } else {\n                r = (pi.start_pos + k) % N;\n                c = pi.line_idx - N;\n            }\n            if (grid[r][c] == 8) {\n                update_grid(r, c, get_char_idx(pi.s[k]));\n            }\n        }\n    }\n\n    // SA\n    double T = 1000.0;\n    double T_min = 0.1;\n    int iterations = 200000;\n    \n    auto get_score = [&]() {\n        if (count_c < M) return (long long)count_c * 10000;\n        return (long long)M * 10000 + count_d;\n    };\n    \n    long long current_score = get_score();\n    \n    for (int i = 0; i < iterations; ++i) {\n        int r = rng() % N;\n        int c = rng() % N;\n        int old_val = grid[r][c];\n        int new_val = rng() % 9; \n        \n        if (old_val == new_val) continue;\n        \n        update_grid(r, c, new_val);\n        long long next_score = get_score();\n        \n        double prob = exp((double)(next_score - current_score) / T);\n        if (next_score >= current_score || (rng() % 10000) / 10000.0 < prob) {\n            current_score = next_score;\n        } else {\n            update_grid(r, c, old_val);\n        }\n        T *= pow(T_min / 1000.0, 1.0 / iterations);\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << get_char(grid[i][j]);\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\n// Structure to represent a point on the grid\nstruct Point {\n    int r, c;\n    bool operator==(const Point& other) const {\n        return r == other.r && c == other.c;\n    }\n    bool operator!=(const Point& other) const {\n        return !(*this == other);\n    }\n};\n\nint N;\nint si, sj;\nvector<string> grid;\nvector<vector<int>> weights;\nvector<vector<vector<Point>>> visible_from;\nvector<Point> all_road_squares;\n\n// Helper to check if a square is a road\nbool is_road(int r, int c) {\n    return r >= 0 && r < N && c >= 0 && c < N && grid[r][c] != '#';\n}\n\n// Precompute visibility for all road squares\nvoid precompute_visibility() {\n    visible_from.resize(N, vector<vector<Point>>(N));\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            if (!is_road(r, c)) continue;\n            \n            // The square itself is visible\n            visible_from[r][c].push_back({r, c});\n            \n            // Horizontal and Vertical visibility\n            for (int nc = c + 1; nc < N && is_road(r, nc); ++nc) visible_from[r][c].push_back({r, nc});\n            for (int nc = c - 1; nc >= 0 && is_road(r, nc); --nc) visible_from[r][c].push_back({r, nc});\n            for (int nr = r + 1; nr < N && is_road(nr, c); ++nr) visible_from[r][c].push_back({nr, c});\n            for (int nr = r - 1; nr >= 0 && is_road(nr, c); --nr) visible_from[r][c].push_back({nr, c});\n        }\n    }\n}\n\n// BFS to find shortest paths and distances\nstruct BFSResult {\n    vector<vector<int>> dist;\n    vector<vector<Point>> parent;\n};\n\nBFSResult bfs(Point start) {\n    BFSResult res;\n    res.dist.assign(N, vector<int>(N, 1e9));\n    res.parent.assign(N, vector<Point>(N, {-1, -1}));\n    \n    queue<Point> q;\n    res.dist[start.r][start.c] = 0;\n    q.push(start);\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    \n    while (!q.empty()) {\n        Point curr = q.front();\n        q.pop();\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n            \n            if (is_road(nr, nc)) {\n                int cost = weights[nr][nc];\n                if (res.dist[nr][nc] > res.dist[curr.r][curr.c] + cost) {\n                    res.dist[nr][nc] = res.dist[curr.r][curr.c] + cost;\n                    res.parent[nr][nc] = curr;\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n    return res;\n}\n\n// Reconstruct path from start to end using BFS parent pointers\nstring get_moves(Point start, Point end, const vector<vector<Point>>& parent) {\n    string moves = \"\";\n    Point curr = end;\n    while (curr != start) {\n        Point p = parent[curr.r][curr.c];\n        if (curr.r == p.r - 1) moves += 'U';\n        else if (curr.r == p.r + 1) moves += 'D';\n        else if (curr.c == p.c - 1) moves += 'L';\n        else if (curr.c == p.c + 1) moves += 'R';\n        curr = p;\n    }\n    reverse(moves.begin(), moves.end());\n    return moves;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N >> si >> sj;\n    grid.resize(N);\n    weights.resize(N, vector<int>(N));\n    \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                weights[i][j] = grid[i][j] - '0';\n                all_road_squares.push_back({i, j});\n            }\n        }\n    }\n    \n    precompute_visibility();\n    \n    // Greedy set cover to find necessary squares to visit\n    vector<Point> must_visit;\n    must_visit.push_back({si, sj});\n    \n    vector<vector<bool>> covered(N, vector<bool>(N, false));\n    int uncovered_count = 0;\n    \n    auto mark_covered = [&](Point p) {\n        int count = 0;\n        for (auto& v : visible_from[p.r][p.c]) {\n            if (!covered[v.r][v.c]) {\n                covered[v.r][v.c] = true;\n                count++;\n            }\n        }\n        return count;\n    };\n    \n    uncovered_count = all_road_squares.size() - mark_covered({si, sj});\n    \n    while (uncovered_count > 0) {\n        Point best_p = {-1, -1};\n        int best_cover = -1;\n        \n        for (auto& p : all_road_squares) {\n            int current_cover = 0;\n            for (auto& v : visible_from[p.r][p.c]) {\n                if (!covered[v.r][v.c]) current_cover++;\n            }\n            if (current_cover > best_cover) {\n                best_cover = current_cover;\n                best_p = p;\n            }\n        }\n        \n        if (best_cover <= 0) break;\n        \n        must_visit.push_back(best_p);\n        uncovered_count -= mark_covered(best_p);\n    }\n    \n    // TSP: Nearest Neighbor heuristic\n    vector<Point> tour;\n    tour.push_back({si, sj});\n    \n    vector<bool> visited(must_visit.size(), false);\n    visited[0] = true;\n    \n    Point curr = {si, sj};\n    while (tour.size() < must_visit.size()) {\n        int best_idx = -1;\n        int min_dist = 1e9;\n        \n        BFSResult bfs_res = bfs(curr);\n        \n        for (int i = 0; i < must_visit.size(); ++i) {\n            if (!visited[i]) {\n                if (bfs_res.dist[must_visit[i].r][must_visit[i].c] < min_dist) {\n                    min_dist = bfs_res.dist[must_visit[i].r][must_visit[i].c];\n                    best_idx = i;\n                }\n            }\n        }\n        \n        tour.push_back(must_visit[best_idx]);\n        visited[best_idx] = true;\n        curr = must_visit[best_idx];\n    }\n    \n    // Return to start\n    tour.push_back({si, sj});\n    \n    // Build final path\n    string final_path = \"\";\n    for (int i = 0; i < tour.size() - 1; ++i) {\n        BFSResult bfs_res = bfs(tour[i]);\n        final_path += get_moves(tour[i], tour[i+1], bfs_res.parent);\n    }\n    \n    cout << final_path << endl;\n    \n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <bitset>\n\nusing namespace std;\n\n// Global problem variables\nint N, M, K, R;\nvector<vector<int>> task_difficulty;\nvector<vector<int>> adj; \nvector<int> in_degree;\nvector<int> member_status; // -1: free, >=0: task_id\nvector<int> start_day;\nvector<vector<double>> s; // Skills estimation (member x skill_dim)\nvector<int> H; // Task height (longest chain)\nvector<int> D; // Descendants count\nvector<int> visit_count; // Number of tasks completed by each member\n\n// Function to calculate predicted completion time for a task by a member\ndouble predict_t(int task_id, int member_id) {\n    double w = 0;\n    for (int k = 0; k < K; ++k) {\n        w += max(0.0, (double)task_difficulty[task_id][k] - s[member_id][k]);\n    }\n    return max(1.0, w);\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read input\n    if (!(cin >> N >> M >> K >> R)) return 0;\n    task_difficulty.resize(N, vector<int>(K));\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            cin >> task_difficulty[i][k];\n        }\n    }\n    adj.resize(N);\n    in_degree.resize(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        adj[u].push_back(v);\n        in_degree[v]++;\n    }\n\n    // Precompute H (Height) - Longest path in DAG\n    H.resize(N, 1);\n    for (int i = N - 1; i >= 0; --i) {\n        for (int v : adj[i]) {\n            H[i] = max(H[i], 1 + H[v]);\n        }\n    }\n\n    // Precompute D (Descendants count)\n    vector<bitset<1000>> reachable(N);\n    for (int i = N - 1; i >= 0; --i) {\n        reachable[i].set(i);\n        for (int v : adj[i]) {\n            reachable[i] |= reachable[v];\n        }\n    }\n    D.resize(N);\n    for(int i=0; i<N; ++i) D[i] = (int)reachable[i].count() - 1;\n\n    // Precompute estimated average difficulty for prioritization\n    vector<double> task_avg_dur(N);\n    for(int i=0; i<N; ++i) {\n        double dur = 0;\n        for(int k=0; k<K; ++k) dur += max(0.0, (double)task_difficulty[i][k] - 30.0);\n        task_avg_dur[i] = dur;\n    }\n\n    // Initialization\n    member_status.assign(M, -1);\n    start_day.assign(N, -1);\n    visit_count.assign(M, 0);\n    s.assign(M, vector<double>(K, 30.0)); \n    vector<int> ready_tasks;\n    for (int i = 0; i < N; ++i) {\n        if (in_degree[i] == 0) ready_tasks.push_back(i);\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n\n        // 1. Assign tasks\n        // Prioritize: H (Criticality) * 20000 + D + estimated_duration\n        sort(ready_tasks.begin(), ready_tasks.end(), [&](int a, int b) {\n            double score_a = (double)H[a] * 20000 + D[a] * 10.0 + task_avg_dur[a];\n            double score_b = (double)H[b] * 20000 + D[b] * 10.0 + task_avg_dur[b];\n            return score_a > score_b;\n        });\n\n        vector<pair<int, int>> assignments;\n        vector<int> free_members;\n        for (int j = 0; j < M; ++j) {\n            if (member_status[j] == -1) free_members.push_back(j);\n        }\n\n        vector<bool> task_assigned(ready_tasks.size(), false);\n        vector<bool> member_assigned(free_members.size(), false);\n\n        // Greedy matching: Task-first, then best member\n        for (int i = 0; i < (int)ready_tasks.size(); ++i) {\n            int task_id = ready_tasks[i];\n            \n            int best_member_idx = -1;\n            double min_t = 1e18;\n\n            for (int j = 0; j < (int)free_members.size(); ++j) {\n                if (member_assigned[j]) continue;\n                double t = predict_t(task_id, free_members[j]);\n                if (t < min_t) {\n                    min_t = t;\n                    best_member_idx = j;\n                }\n            }\n\n            if (best_member_idx != -1) {\n                int member_id = free_members[best_member_idx];\n                assignments.push_back({member_id + 1, task_id + 1});\n                member_status[member_id] = task_id;\n                start_day[task_id] = day;\n                member_assigned[best_member_idx] = true;\n                task_assigned[i] = true;\n            }\n        }\n\n        // Update ready_tasks: remove assigned\n        vector<int> next_ready_tasks;\n        for (int i = 0; i < (int)ready_tasks.size(); ++i) {\n            if (!task_assigned[i]) next_ready_tasks.push_back(ready_tasks[i]);\n        }\n        ready_tasks = next_ready_tasks;\n\n        // Output and flush\n        cout << assignments.size();\n        for (auto& p : assignments) cout << \" \" << p.first << \" \" << p.second;\n        cout << endl;\n\n        // 2. Read completed\n        int n_completed;\n        cin >> n_completed;\n        if (n_completed == -1) break;\n\n        for (int i = 0; i < n_completed; ++i) {\n            int member_id;\n            cin >> member_id;\n            --member_id;\n            int task_id = member_status[member_id];\n            \n            // Skill learning update\n            int actual_t = day - start_day[task_id] + 1;\n            double w_pred = 0;\n            vector<int> bottlenecks;\n            for (int k = 0; k < K; ++k) {\n                double diff = (double)task_difficulty[task_id][k] - s[member_id][k];\n                if (diff > 0) {\n                    w_pred += diff;\n                    bottlenecks.push_back(k);\n                }\n            }\n            \n            // Adaptive learning rate based on how many tasks the member has completed\n            double lr = 0.2 / (1.0 + 0.05 * visit_count[member_id]);\n            visit_count[member_id]++;\n\n            double error = (double)actual_t - max(1.0, w_pred);\n            if (abs(error) > 1e-9) {\n                if (!bottlenecks.empty()) {\n                    for(int k : bottlenecks) {\n                        s[member_id][k] -= (error / bottlenecks.size()) * lr;\n                        s[member_id][k] = max(0.0, min(100.0, s[member_id][k]));\n                    }\n                } else {\n                    // Update all if no bottlenecks (error indicates optimistic skill estimate)\n                    for(int k = 0; k < K; ++k) {\n                        s[member_id][k] -= (error / K) * lr;\n                        s[member_id][k] = max(0.0, min(100.0, s[member_id][k]));\n                    }\n                }\n            }\n\n            member_status[member_id] = -1;\n\n            // Unlock dependencies\n            for (int next_task : adj[task_id]) {\n                in_degree[next_task]--;\n                if (in_degree[next_task] == 0) ready_tasks.push_back(next_task);\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Order structure\nstruct Order {\n    int id;\n    int ax, ay, cx, cy;\n    double dist_from_office;\n};\n\n// Node structure for the route\nstruct Node {\n    int order_id;\n    bool is_pickup;\n    int x, y;\n};\n\n// Manhattan distance\nint dist(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Calculate total route distance\nint calculate_total_dist(const vector<Node>& route) {\n    int d = 0;\n    int cx = 400, cy = 400;\n    for (const auto& node : route) {\n        d += dist(cx, cy, node.x, node.y);\n        cx = node.x;\n        cy = node.y;\n    }\n    d += dist(cx, cy, 400, 400);\n    return d;\n}\n\n// Check if route satisfies precedence constraints\nbool is_valid(const vector<Node>& route, const vector<int>& selected_orders) {\n    vector<int> p_pos(1001, -1);\n    vector<int> d_pos(1001, -1);\n    for (int i = 0; i < route.size(); ++i) {\n        if (route[i].is_pickup) p_pos[route[i].order_id] = i;\n        else d_pos[route[i].order_id] = i;\n    }\n    for (int id : selected_orders) {\n        if (p_pos[id] > d_pos[id]) return false;\n    }\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // Read all orders\n    vector<Order> all_orders(1000);\n    for (int i = 0; i < 1000; ++i) {\n        all_orders[i].id = i + 1;\n        cin >> all_orders[i].ax >> all_orders[i].ay >> all_orders[i].cx >> all_orders[i].cy;\n        all_orders[i].dist_from_office = dist(400, 400, all_orders[i].ax, all_orders[i].ay) +\n                                         dist(all_orders[i].ax, all_orders[i].ay, all_orders[i].cx, all_orders[i].cy) +\n                                         dist(all_orders[i].cx, all_orders[i].cy, 400, 400);\n    }\n\n    // Sort orders by distance and pick top 50\n    vector<Order> sorted_orders = all_orders;\n    sort(sorted_orders.begin(), sorted_orders.end(), [](const Order& a, const Order& b) {\n        return a.dist_from_office < b.dist_from_office;\n    });\n\n    vector<int> selected_orders;\n    for (int i = 0; i < 50; ++i) {\n        selected_orders.push_back(sorted_orders[i].id);\n    }\n\n    // Greedy Initial Route Construction\n    vector<Node> route;\n    vector<bool> p_visited(1001, false);\n    vector<bool> d_visited(1001, false);\n    int cx = 400, cy = 400;\n    \n    while (route.size() < 100) {\n        int best_idx = -1;\n        bool best_is_pickup = false;\n        int min_d = 2000000000;\n        \n        for (int id : selected_orders) {\n            if (!p_visited[id]) {\n                int d = dist(cx, cy, all_orders[id - 1].ax, all_orders[id - 1].ay);\n                if (d < min_d) {\n                    min_d = d;\n                    best_idx = id;\n                    best_is_pickup = true;\n                }\n            }\n            if (p_visited[id] && !d_visited[id]) {\n                int d = dist(cx, cy, all_orders[id - 1].cx, all_orders[id - 1].cy);\n                if (d < min_d) {\n                    min_d = d;\n                    best_idx = id;\n                    best_is_pickup = false;\n                }\n            }\n        }\n        \n        if (best_is_pickup) {\n            route.push_back({best_idx, true, all_orders[best_idx - 1].ax, all_orders[best_idx - 1].ay});\n            p_visited[best_idx] = true;\n            cx = all_orders[best_idx - 1].ax;\n            cy = all_orders[best_idx - 1].ay;\n        } else {\n            route.push_back({best_idx, false, all_orders[best_idx - 1].cx, all_orders[best_idx - 1].cy});\n            d_visited[best_idx] = true;\n            cx = all_orders[best_idx - 1].cx;\n            cy = all_orders[best_idx - 1].cy;\n        }\n    }\n\n    // Refine with local search (Hill Climbing / 2-opt)\n    auto start_time = chrono::steady_clock::now();\n    mt19937 rng(42);\n    int best_dist = calculate_total_dist(route);\n    int iter = 0;\n    \n    while (true) {\n        if ((iter++ & 1023) == 0) { // Check time every 1024 iterations\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1900) break;\n        }\n        \n        int i = rng() % 100;\n        int j = rng() % 100;\n        if (i > j) swap(i, j);\n        if (i == j) continue;\n        \n        // Try reversing the segment [i, j]\n        vector<Node> next_route = route;\n        reverse(next_route.begin() + i, next_route.begin() + j + 1);\n        \n        if (is_valid(next_route, selected_orders)) {\n            int d = calculate_total_dist(next_route);\n            if (d < best_dist) {\n                best_dist = d;\n                route = next_route;\n            }\n        }\n    }\n\n    // Output results\n    cout << 50;\n    for (int id : selected_orders) cout << \" \" << id;\n    cout << endl;\n    \n    cout << 102; // Start, 100 points, End\n    cout << \" 400 400\";\n    for (const auto& node : route) cout << \" \" << node.x << \" \" << node.y;\n    cout << \" 400 400\" << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\n// DSU structure for connectivity checking\nstruct DSU {\n    vector<int> parent;\n    int num_components;\n    DSU(int n) : num_components(n) {\n        parent.resize(n);\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int i) {\n        if (parent[i] == i)\n            return i;\n        return parent[i] = find(parent[i]);\n    }\n    // unite returns true if it actually merged two components\n    bool unite(int i, int j) {\n        int root_i = find(i);\n        int root_j = find(j);\n        if (root_i != root_j) {\n            parent[root_i] = root_j;\n            num_components--;\n            return true;\n        }\n        return false;\n    }\n    bool same(int i, int j) {\n        return find(i) == find(j);\n    }\n};\n\nstruct Edge {\n    int u, v, d, id;\n};\n\nint main() {\n    // Faster I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Problem constraints\n    const int N = 400;\n    const int M = 1995;\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<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        int dx = coords[edges[i].u].first - coords[edges[i].v].first;\n        int dy = coords[edges[i].u].second - coords[edges[i].v].second;\n        // Euclidean distance rounded to nearest integer\n        edges[i].d = (int)round(sqrt((double)dx * dx + (double)dy * dy));\n        edges[i].id = i;\n    }\n\n    vector<bool> adopted(M, false);\n    \n    // Process each edge as it arrives\n    for (int i = 0; i < M; ++i) {\n        int l_i;\n        cin >> l_i;\n\n        // 1. Initialize DSU with all already adopted edges\n        DSU dsu(N);\n        for (int j = 0; j < i; ++j) {\n            if (adopted[j]) {\n                dsu.unite(edges[j].u, edges[j].v);\n            }\n        }\n        \n        // Calculate needed edge count\n        // We need to connect num_components components, so we need num_components - 1 more edges.\n        int num_needed = dsu.num_components - 1;\n        int num_remaining = M - i;\n\n        // Adaptive parameter k:\n        // k_base increases from 1.0 to 2.5 over time.\n        // Boost factor increases as we get desperate (num_needed close to num_remaining).\n        double k_base = 1.0 + 1.5 * ((double)i / M);\n        // The boost ensures we prioritize connectivity when edges are running out.\n        double boost = 0.5 * ((double)num_needed / (num_remaining));\n        double k = k_base + boost;\n\n        // 2. Prepare candidates: the current edge (cost l_i) and all future edges (estimated cost k*d)\n        struct Candidate {\n            double cost;\n            int id;\n            int u, v;\n        };\n        vector<Candidate> candidates;\n        candidates.reserve(M - i);\n        \n        candidates.push_back({(double)l_i, i, edges[i].u, edges[i].v});\n        \n        for (int j = i + 1; j < M; ++j) {\n            candidates.push_back({k * edges[j].d, j, edges[j].u, edges[j].v});\n        }\n        \n        // Sort candidates by cost to run Kruskal's algorithm\n        sort(candidates.begin(), candidates.end(), [](const Candidate& a, const Candidate& b) {\n            return a.cost < b.cost;\n        });\n        \n        // 3. Run Kruskal's to see if the current edge i is part of the MST\n        bool take_edge = false;\n        for (const auto& cand : candidates) {\n            if (!dsu.same(cand.u, cand.v)) {\n                dsu.unite(cand.u, cand.v);\n                if (cand.id == i) {\n                    take_edge = true;\n                    break;\n                }\n            }\n        }\n        \n        // Output decision and flush\n        if (take_edge) {\n            cout << 1 << endl;\n            adopted[i] = true;\n        } else {\n            cout << 0 << endl;\n            adopted[i] = false;\n        }\n    }\n    \n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int r, c;\n    bool operator==(const Point& other) const { return r == other.r && c == other.c; }\n};\n\nint N, M;\nvector<Point> pets;\nvector<int> pet_types;\nvector<Point> humans;\nbool impassable[30][30];\n\n// Check if a coordinate is within bounds\nbool is_valid(int r, int c) {\n    return r >= 0 && r < 30 && c >= 0 && c < 30;\n}\n\n// Check if a square can be made impassable\nbool can_build(int r, int c) {\n    if (!is_valid(r, c) || impassable[r][c]) return false;\n    // Cannot build if a pet or human is currently at (r, c)\n    for (const auto& p : pets) if (p.r == r && p.c == c) return false;\n    for (const auto& h : humans) if (h.r == r && h.c == c) return false;\n    \n    // Cannot build if an adjacent square contains a pet\n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    for (int i = 0; i < 4; ++i) {\n        int nr = r + dr[i];\n        int nc = c + dc[i];\n        if (is_valid(nr, nc)) {\n            for (const auto& p : pets) {\n                if (p.r == nr && p.c == nc) return false;\n            }\n        }\n    }\n    return true;\n}\n\n// Find the index of the nearest pet\nint get_nearest_pet(Point h) {\n    int min_dist = 1000;\n    int target = -1;\n    for (int i = 0; i < N; ++i) {\n        int d = abs(h.r - pets[i].r) + abs(h.c - pets[i].c);\n        if (d < min_dist) {\n            min_dist = d;\n            target = i;\n        }\n    }\n    return target;\n}\n\n// BFS to find the next move towards the target\nPoint get_next_move(Point start, Point target) {\n    if (start.r == target.r && start.c == target.c) return start;\n    \n    queue<pair<Point, Point>> q; // {current, first_step}\n    bool visited[30][30] = {false};\n    \n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    \n    // Check initial neighbors\n    for (int i = 0; i < 4; ++i) {\n        int nr = start.r + dr[i];\n        int nc = start.c + dc[i];\n        if (is_valid(nr, nc) && !impassable[nr][nc]) {\n            bool occupied = false;\n            for(auto& h : humans) if(h.r == nr && h.c == nc) occupied = true;\n            if(!occupied) {\n                q.push({{nr, nc}, {nr, nc}});\n                visited[nr][nc] = true;\n            }\n        }\n    }\n    \n    while (!q.empty()) {\n        auto [curr, first] = q.front();\n        q.pop();\n        \n        if (curr.r == target.r && curr.c == target.c) return first;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n            if (is_valid(nr, nc) && !impassable[nr][nc] && !visited[nr][nc]) {\n                bool occupied = false;\n                for(auto& h : humans) if(h.r == nr && h.c == nc) occupied = true;\n                if(!occupied) {\n                    visited[nr][nc] = true;\n                    q.push({{nr, nc}, first});\n                }\n            }\n        }\n    }\n    return start; // No path found\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N;\n    pets.resize(N);\n    pet_types.resize(N);\n    for (int i = 0; i < N; ++i) cin >> pets[i].r >> pets[i].c >> pet_types[i];\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) cin >> humans[i].r >> humans[i].c;\n    \n    for (int i = 0; i < 30; ++i) for (int j = 0; j < 30; ++j) impassable[i][j] = false;\n    \n    for (int turn = 0; turn < 300; ++turn) {\n        vector<string> actions(M, \".\");\n        \n        for (int i = 0; i < M; ++i) {\n            int target_idx = get_nearest_pet(humans[i]);\n            if (target_idx == -1) continue;\n            \n            Point pet = pets[target_idx];\n            bool built = false;\n            int dr[] = {0, 0, 1, -1};\n            int dc[] = {1, -1, 0, 0};\n            char wall_chars[] = {'r', 'l', 'd', 'u'};\n            \n            // Try to build a wall near the target pet to trap it\n            for (int k = 0; k < 4; ++k) {\n                int nr = humans[i].r + dr[k];\n                int nc = humans[i].c + dc[k];\n                \n                if (abs(nr - pet.r) + abs(nc - pet.c) <= 2) {\n                    if (can_build(nr, nc)) {\n                        string s(1, wall_chars[k]);\n                        actions[i] = s;\n                        impassable[nr][nc] = true;\n                        built = true;\n                        break;\n                    }\n                }\n            }\n            \n            // If not building, move towards the pet\n            if (!built) {\n                Point next = get_next_move(humans[i], pet);\n                if (!(next == humans[i])) {\n                    if (next.r < humans[i].r) actions[i] = \"U\";\n                    else if (next.r > humans[i].r) actions[i] = \"D\";\n                    else if (next.c < humans[i].c) actions[i] = \"L\";\n                    else if (next.c > humans[i].c) actions[i] = \"R\";\n                    humans[i] = next;\n                }\n            }\n        }\n        \n        // Output actions for this turn\n        for (int i = 0; i < M; ++i) cout << actions[i];\n        cout << endl;\n        \n        // Update pets' positions based on their movements\n        for (int i = 0; i < N; ++i) {\n            string move;\n            cin >> move;\n            for (char c : move) {\n                if (c == 'U') pets[i].r--;\n                else if (c == 'D') pets[i].r++;\n                else if (c == 'L') pets[i].c--;\n                else if (c == 'R') pets[i].c++;\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Node for path reconstruction\nstruct Node {\n    int parent;\n    char move;\n};\n\n// Fixed-size State for Beam Search to minimize allocation overhead\nstruct BeamState {\n    int node_idx;\n    double dist[400]; // Probabilities for each cell\n    double reward;\n    double prob_reached;\n    double expected_total_reward;\n    bool finished; // Optimization: stop propagating if reached\n};\n\nint Si, Sj, Ti, Tj;\ndouble P;\nvector<string> H, V;\nint min_dist_to_office[400];\n\n// Compute shortest path distance using BFS\nvoid compute_min_dist() {\n    for (int i = 0; i < 400; ++i) min_dist_to_office[i] = 1000;\n    queue<int> q;\n    q.push(Ti * 20 + Tj);\n    min_dist_to_office[Ti * 20 + Tj] = 0;\n\n    while (!q.empty()) {\n        int curr = q.front();\n        q.pop();\n        int r = curr / 20;\n        int c = curr % 20;\n\n        if (r > 0 && V[r - 1][c] == '0' && min_dist_to_office[(r - 1) * 20 + c] == 1000) {\n            min_dist_to_office[(r - 1) * 20 + c] = min_dist_to_office[curr] + 1;\n            q.push((r - 1) * 20 + c);\n        }\n        if (r < 19 && V[r][c] == '0' && min_dist_to_office[(r + 1) * 20 + c] == 1000) {\n            min_dist_to_office[(r + 1) * 20 + c] = min_dist_to_office[curr] + 1;\n            q.push((r + 1) * 20 + c);\n        }\n        if (c > 0 && H[r][c - 1] == '0' && min_dist_to_office[r * 20 + c - 1] == 1000) {\n            min_dist_to_office[r * 20 + c - 1] = min_dist_to_office[curr] + 1;\n            q.push(r * 20 + c - 1);\n        }\n        if (c < 19 && H[r][c] == '0' && min_dist_to_office[r * 20 + c + 1] == 1000) {\n            min_dist_to_office[r * 20 + c + 1] = min_dist_to_office[curr] + 1;\n            q.push(r * 20 + c + 1);\n        }\n    }\n}\n\ninline bool can_move(int r, int c, char dir) {\n    if (dir == 'U') return r > 0 && V[r - 1][c] == '0';\n    if (dir == 'D') return r < 19 && V[r][c] == '0';\n    if (dir == 'L') return c > 0 && H[r][c - 1] == '0';\n    if (dir == 'R') return c < 19 && H[r][c] == '0';\n    return false;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> Si >> Sj >> Ti >> Tj >> P)) return 0;\n    H.resize(20);\n    for (int i = 0; i < 20; ++i) cin >> H[i];\n    V.resize(19);\n    for (int i = 0; i < 19; ++i) cin >> V[i];\n\n    compute_min_dist();\n\n    vector<Node> all_nodes;\n    all_nodes.reserve(300000);\n    all_nodes.push_back({-1, ' '}); // Dummy root\n\n    vector<BeamState> beam;\n    beam.reserve(1200);\n    BeamState initial;\n    initial.node_idx = 0;\n    for (int i = 0; i < 400; ++i) initial.dist[i] = 0.0;\n    initial.dist[Si * 20 + Sj] = 1.0;\n    initial.reward = 0.0;\n    initial.prob_reached = 0.0;\n    initial.finished = false;\n    double h = (double)min_dist_to_office[Si * 20 + Sj];\n    initial.expected_total_reward = 0.0 + (1.0 - 0.0) * max(0.0, 401.0 - h);\n    beam.push_back(initial);\n\n    int K = 1000; // Increased beam width\n    for (int t = 1; t <= 200; ++t) {\n        vector<BeamState> next_beam;\n        next_beam.reserve(beam.size() * 4);\n        for (const auto& s : beam) {\n            if (s.finished) {\n                next_beam.push_back(s);\n                continue;\n            }\n\n            for (char dir : {'U', 'D', 'L', 'R'}) {\n                BeamState next_s;\n                next_s.prob_reached = s.prob_reached;\n                next_s.reward = s.reward;\n                next_s.finished = false;\n                for (int i = 0; i < 400; ++i) next_s.dist[i] = 0.0;\n\n                double prob_reach_at_t = 0.0;\n\n                for (int curr = 0; curr < 400; ++curr) {\n                    if (s.dist[curr] < 1e-9) continue; // Threshold\n                    \n                    int r = curr / 20;\n                    int c = curr % 20;\n                    \n                    // Forgetting: agent stays\n                    next_s.dist[curr] += s.dist[curr] * P;\n                    \n                    // Moving: attempts to move\n                    if (can_move(r, c, dir)) {\n                        int nr = r, nc = c;\n                        if (dir == 'U') nr--;\n                        else if (dir == 'D') nr++;\n                        else if (dir == 'L') nc--;\n                        else if (dir == 'R') nc++;\n                        \n                        if (nr == Ti && nc == Tj) {\n                            prob_reach_at_t += s.dist[curr] * (1.0 - P);\n                        } else {\n                            next_s.dist[nr * 20 + nc] += s.dist[curr] * (1.0 - P);\n                        }\n                    } else {\n                        // Wall, stay\n                        next_s.dist[curr] += s.dist[curr] * (1.0 - P);\n                    }\n                }\n                \n                next_s.prob_reached += prob_reach_at_t;\n                next_s.reward += prob_reach_at_t * (401.0 - t);\n                \n                if (next_s.prob_reached >= 1.0 - 1e-12) {\n                    next_s.finished = true;\n                }\n                \n                double h_val = 0.0;\n                for (int i = 0; i < 400; ++i) {\n                    if (next_s.dist[i] > 1e-9)\n                        h_val += next_s.dist[i] * min_dist_to_office[i];\n                }\n                \n                double remaining_time = 401.0 - t - h_val;\n                if (remaining_time < 0) remaining_time = 0;\n                next_s.expected_total_reward = next_s.reward + (1.0 - next_s.prob_reached) * remaining_time;\n                \n                next_s.node_idx = all_nodes.size();\n                all_nodes.push_back({s.node_idx, dir});\n                next_beam.push_back(next_s);\n            }\n        }\n        \n        if (next_beam.size() > (size_t)K) {\n            nth_element(next_beam.begin(), next_beam.begin() + K, next_beam.end(), [](const BeamState& a, const BeamState& b) {\n                return a.expected_total_reward > b.expected_total_reward;\n            });\n            next_beam.resize(K);\n        }\n        beam = next_beam;\n    }\n    \n    sort(beam.begin(), beam.end(), [](const BeamState& a, const BeamState& b) {\n        return a.expected_total_reward > b.expected_total_reward;\n    });\n    \n    string path = \"\";\n    int curr_node = beam[0].node_idx;\n    while (all_nodes[curr_node].parent != -1) {\n        path += all_nodes[curr_node].move;\n        curr_node = all_nodes[curr_node].parent;\n    }\n    reverse(path.begin(), path.end());\n    cout << path << endl;\n    \n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <cstring>\n\nusing namespace std;\n\n// Precomputed connectivity: conn[type][rotation][in_direction] = out_direction\n// Directions: 0: Left, 1: Up, 2: Right, 3: Down\nint conn[8][4][4];\n\nvoid precompute_conn() {\n    int base_to[8][4] = {\n        {1, 0, -1, -1}, // Tile 0: Left <-> Up\n        {3, -1, -1, 0}, // Tile 1: Left <-> Down\n        {-1, -1, 3, 2}, // Tile 2: Right <-> Down\n        {-1, 2, 1, -1}, // Tile 3: Right <-> Up\n        {1, 0, 3, 2},   // Tile 4: Left <-> Up, Right <-> Down\n        {3, 2, 1, 0},   // Tile 5: Left <-> Down, Up <-> Right\n        {2, -1, 0, -1}, // Tile 6: Left <-> Right\n        {-1, 3, -1, 1}, // Tile 7: Up <-> Down\n    };\n    \n    for (int t = 0; t < 8; ++t) {\n        for (int r = 0; r < 4; ++r) {\n            for (int d = 0; d < 4; ++d) {\n                int d_old = (d + r) % 4;\n                int d_old_exit = base_to[t][d_old];\n                if (d_old_exit == -1) {\n                    conn[t][r][d] = -1;\n                } else {\n                    conn[t][r][d] = (d_old_exit - r + 4) % 4;\n                }\n            }\n        }\n    }\n}\n\nint N = 30;\nint tiles[30][30];\nint r[30][30];\nint di[4] = {0, -1, 0, 1}; // Left, Up, Right, Down\nint dj[4] = {-1, 0, 1, 0};\n\n// Visited tracking to avoid frequent memset/allocation\nint visited[30][30][4];\nint visit_gen = 0;\n\n// Highly optimized score calculation\nlong long calculate_score() {\n    visit_gen++;\n    if (visit_gen >= 2000000000) {\n        memset(visited, 0, sizeof(visited));\n        visit_gen = 1;\n    }\n    \n    int max1 = 0, max2 = 0;\n    \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                if (visited[i][j][d] == visit_gen) continue;\n                \n                int curr_i = i;\n                int curr_j = j;\n                int curr_d = d;\n                int length = 0;\n                bool closed = false;\n                \n                int path_i = curr_i;\n                int path_j = curr_j;\n                int path_d = curr_d;\n                \n                while (true) {\n                    if (visited[path_i][path_j][path_d] == visit_gen) break;\n                    visited[path_i][path_j][path_d] = visit_gen;\n                    \n                    int next_d = conn[tiles[path_i][path_j]][r[path_i][path_j]][path_d];\n                    if (next_d == -1) break;\n                    \n                    path_i += di[next_d];\n                    path_j += dj[next_d];\n                    \n                    if (path_i < 0 || path_i >= N || path_j < 0 || path_j >= N) break;\n                    \n                    path_d = (next_d + 2) % 4;\n                    length++;\n                    \n                    if (path_i == i && path_j == j && path_d == d) {\n                        closed = true;\n                        break;\n                    }\n                }\n                \n                if (closed) {\n                    if (length > max1) {\n                        max2 = max1;\n                        max1 = length;\n                    } else if (length > max2) {\n                        max2 = length;\n                    }\n                }\n            }\n        }\n    }\n    return (long long)max1 * max2;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    precompute_conn();\n    \n    for (int i = 0; i < N; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; ++j) {\n            tiles[i][j] = s[j] - '0';\n            r[i][j] = 0; \n        }\n    }\n    \n    int best_r[30][30];\n    memcpy(best_r, r, sizeof(r));\n    long long best_score = calculate_score();\n    long long current_score = best_score;\n    \n    mt19937 rng(1337);\n    auto start_time = chrono::steady_clock::now();\n    double time_limit = 1.90; \n    \n    int iterations = 0;\n    \n    // Simulated Annealing\n    while (true) {\n        if ((iterations & 1023) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration<double>(now - start_time).count() > time_limit) break;\n        }\n        iterations++;\n        \n        int i = rng() % N;\n        int j = rng() % N;\n        int old_r = r[i][j];\n        r[i][j] = rng() % 4;\n        \n        long long new_score = calculate_score();\n        \n        double progress = (double)iterations / 1000000.0;\n        double T = 1000.0 * pow(0.001, progress); \n        \n        double prob = (new_score >= current_score) ? 1.0 : exp((double)(new_score - current_score) / (T + 1e-9));\n        \n        if (new_score > best_score) {\n            best_score = new_score;\n            memcpy(best_r, r, sizeof(r));\n        }\n        \n        if (prob > (double)rng() / rng.max()) {\n            current_score = new_score;\n        } else {\n            r[i][j] = old_r;\n        }\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << best_r[i][j];\n        }\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <chrono>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent the board\nstruct Board {\n    int N;\n    vector<int> tiles;\n    int empty_r, empty_c;\n\n    Board(int n, const vector<int>& t) : N(n), tiles(t) {\n        for (int i = 0; i < N * N; ++i) {\n            if (tiles[i] == 0) {\n                empty_r = i / N;\n                empty_c = i % N;\n            }\n        }\n    }\n\n    // Apply a move by moving the empty square.\n    // 'U': Empty square moves up (row index decreases)\n    // 'D': Empty square moves down (row index increases)\n    // 'L': Empty square moves left (col index decreases)\n    // 'R': Empty square moves right (col index increases)\n    bool apply(char move) {\n        int nr = empty_r, nc = empty_c;\n        if (move == 'U') nr--;\n        else if (move == 'D') nr++;\n        else if (move == 'L') nc--;\n        else if (move == 'R') nc++;\n        else return false;\n\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n\n        swap(tiles[empty_r * N + empty_c], tiles[nr * N + nc]);\n        empty_r = nr;\n        empty_c = nc;\n        return true;\n    }\n};\n\n// DSU to manage components and check for tree structure\nstruct DSU {\n    vector<int> parent;\n    vector<int> nodes;\n    vector<int> edges;\n\n    DSU(int n) {\n        parent.resize(n);\n        nodes.resize(n, 1);\n        edges.resize(n, 0);\n        for (int i = 0; i < n; ++i) parent[i] = i;\n    }\n\n    int find(int i) {\n        if (parent[i] == i) return i;\n        return parent[i] = find(parent[i]);\n    }\n\n    void unite(int i, int j) {\n        int root_i = find(i);\n        int root_j = find(j);\n        if (root_i != root_j) {\n            parent[root_j] = root_i;\n            nodes[root_i] += nodes[root_j];\n            edges[root_i] += edges[root_j] + 1;\n        } else {\n            edges[root_i]++;\n        }\n    }\n};\n\nint calculate_score(const Board& b) {\n    int N = b.N;\n    DSU dsu(N * N);\n    \n    for (int i = 0; i < N * N; ++i) {\n        if (b.tiles[i] == 0) dsu.nodes[i] = 0;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int u = i * N + j;\n            if (b.tiles[u] == 0) continue;\n\n            // Check rightward connection (bit 2 is 4)\n            if (j + 1 < N && b.tiles[i * N + j + 1] != 0) {\n                if ((b.tiles[u] & 4) && (b.tiles[i * N + j + 1] & 1)) { // 4 is right, 1 is left\n                    dsu.unite(u, i * N + j + 1);\n                }\n            }\n            // Check downward connection (bit 3 is 8)\n            if (i + 1 < N && b.tiles[(i + 1) * N + j] != 0) {\n                if ((b.tiles[u] & 8) && (b.tiles[(i + 1) * N + j] & 2)) { // 8 is down, 2 is up\n                    dsu.unite(u, (i + 1) * N + j);\n                }\n            }\n        }\n    }\n\n    int max_s = 0;\n    for (int i = 0; i < N * N; ++i) {\n        if (dsu.parent[i] == i && dsu.nodes[i] > 0) {\n            // A tree has edges == nodes - 1\n            if (dsu.edges[i] == dsu.nodes[i] - 1) {\n                max_s = max(max_s, dsu.nodes[i]);\n            }\n        }\n    }\n    return max_s;\n}\n\nint hex_to_int(char c) {\n    if (c >= '0' && c <= '9') return c - '0';\n    return c - 'a' + 10;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, T;\n    cin >> N >> T;\n    vector<int> tiles(N * N);\n    string s;\n    for (int i = 0; i < N; ++i) {\n        cin >> s;\n        for (int j = 0; j < N; ++j) {\n            tiles[i * N + j] = hex_to_int(s[j]);\n        }\n    }\n\n    Board initial_board(N, tiles);\n    string best_moves = \"\";\n    int best_S = calculate_score(initial_board);\n\n    auto start_time = chrono::steady_clock::now();\n    mt19937 rng(42);\n    \n    // Hill Climbing with random restarts\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 2800) {\n        Board current_board = initial_board;\n        string current_moves = \"\";\n        int current_S = calculate_score(current_board);\n        \n        for (int i = 0; i < T; ++i) {\n            if (current_S == N * N - 1) break;\n\n            vector<char> moves = {'U', 'D', 'L', 'R'};\n            shuffle(moves.begin(), moves.end(), rng);\n            \n            char best_move = ' ';\n            int best_move_S = -1;\n\n            // Greedy step: choose the move that maximizes the current score\n            for (char move : moves) {\n                Board next_board = current_board;\n                if (next_board.apply(move)) {\n                    int next_S = calculate_score(next_board);\n                    if (next_S > best_move_S) {\n                        best_move_S = next_S;\n                        best_move = move;\n                    }\n                }\n            }\n            \n            if (best_move == ' ') break; \n            \n            current_board.apply(best_move);\n            current_moves += best_move;\n            current_S = best_move_S;\n            \n            if (current_S > best_S) {\n                best_S = current_S;\n                best_moves = current_moves;\n            }\n        }\n        \n        if (best_S == N * N - 1) break;\n    }\n    \n    cout << best_moves << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent a point\nstruct Point {\n    long long x, y;\n};\n\n// Structure to represent a line: ax + by + c = 0\nstruct Line {\n    long long a, b, c;\n    Point p1, p2;\n};\n\n// Global data\nint N, K;\nvector<int> a(11);\nvector<Point> strawberries;\nmt19937 rng(1337);\n\n// Function to calculate the score: sum(min(a_d, b_d))\nint calculate_score(const vector<int>& piece_counts) {\n    vector<int> b(11, 0);\n    for (int count : piece_counts) {\n        if (count >= 1 && count <= 10) {\n            b[count]++;\n        }\n    }\n    int score = 0;\n    for (int d = 1; d <= 10; ++d) {\n        score += min(a[d], b[d]);\n    }\n    return score;\n}\n\n// Generate a random line that intersects the cake\nLine generate_random_line() {\n    // Generate points within [-20000, 20000] to cover the cake radius of 10000\n    uniform_int_distribution<long long> dist(-20000, 20000);\n    while (true) {\n        Point p1 = {dist(rng), dist(rng)};\n        Point p2 = {dist(rng), dist(rng)};\n        if (p1.x == p2.x && p1.y == p2.y) continue;\n\n        // Line equation: (y1 - y2)x + (x2 - x1)y + (x1y2 - x2y1) = 0\n        long long a = p1.y - p2.y;\n        long long b = p2.x - p1.x;\n        long long c = -a * p1.x - b * p1.y;\n\n        // Check if the line cuts the cake (distance from origin < 10000)\n        __int128 c2 = (__int128)c * c;\n        __int128 dist2 = (__int128)a * a + (__int128)b * b;\n        if (c2 < (__int128)100000000 * dist2) {\n            return {a, b, c, p1, p2};\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N >> K)) return 0;\n    for (int i = 1; i <= 10; ++i) cin >> a[i];\n    strawberries.resize(N);\n    for (int i = 0; i < N; ++i) cin >> strawberries[i].x >> strawberries[i].y;\n\n    // current_piece_id[i] stores the ID of the piece that strawberry i belongs to\n    vector<int> current_piece_id(N, 0);\n    int num_pieces = 1;\n    vector<Line> lines;\n\n    for (int k = 0; k < K; ++k) {\n        int best_score = -1;\n        Line best_line;\n        bool found = false;\n\n        // Try 1000 random lines and pick the best one\n        for (int trial = 0; trial < 1000; ++trial) {\n            Line line = generate_random_line();\n            \n            // Piece split: how many strawberries in each piece fall on the left/right side\n            // piece_split[p_id].first = count on left, .second = count on right\n            vector<pair<int, int>> piece_split(num_pieces, {0, 0});\n            for (int i = 0; i < N; ++i) {\n                if (current_piece_id[i] == -1) continue;\n                long long val = line.a * strawberries[i].x + line.b * strawberries[i].y + line.c;\n                if (val > 0) piece_split[current_piece_id[i]].second++;\n                else if (val < 0) piece_split[current_piece_id[i]].first++;\n                // val == 0 means the strawberry is on the line (removed)\n            }\n\n            vector<int> next_piece_counts;\n            for (int p = 0; p < num_pieces; ++p) {\n                if (piece_split[p].first > 0) next_piece_counts.push_back(piece_split[p].first);\n                if (piece_split[p].second > 0) next_piece_counts.push_back(piece_split[p].second);\n            }\n\n            int score = calculate_score(next_piece_counts);\n            if (score > best_score) {\n                best_score = score;\n                best_line = line;\n                found = true;\n            }\n        }\n        \n        if (found) {\n            lines.push_back(best_line);\n            \n            // Update current_piece_id mapping for all strawberries\n            vector<int> next_piece_id(N, -1);\n            // new_id_map[old_piece_id][side] -> new_piece_id\n            vector<vector<int>> new_id_map(num_pieces, vector<int>(2, -1));\n            int next_num_pieces = 0;\n\n            for (int i = 0; i < N; ++i) {\n                if (current_piece_id[i] == -1) continue;\n                long long val = best_line.a * strawberries[i].x + best_line.b * strawberries[i].y + best_line.c;\n                if (val == 0) continue; // Strawberry removed\n                \n                int side = (val > 0) ? 1 : 0;\n                int p = current_piece_id[i];\n                \n                if (new_id_map[p][side] == -1) {\n                    new_id_map[p][side] = next_num_pieces++;\n                }\n                next_piece_id[i] = new_id_map[p][side];\n            }\n            current_piece_id = next_piece_id;\n            num_pieces = next_num_pieces;\n        } else {\n            // No improvement found, stop cutting\n            break;\n        }\n    }\n\n    // Output the result\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line.p1.x << \" \" << line.p1.y << \" \" << line.p2.x << \" \" << line.p2.y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <queue>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nstruct Rectangle {\n    Point p[4];\n};\n\nint N, M;\nvector<vector<bool>> has_dot;\nvector<Rectangle> all_rects;\nvector<vector<int>> potential_rects;\nvector<int> occupied_count;\nvector<bool> is_used_rect;\n\n// Segment status arrays\nbool used_h[65][65];\nbool used_v[65][65];\nbool used_d1[130][65]; // diag1: y-x+N. length = dx\nbool used_d2[130][65]; // diag2: y+x. length = dx\n\nbool is_valid_coord(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nvoid add_rect(Point p1, Point p2, Point p3, Point p4) {\n    if (is_valid_coord(p1.x, p1.y) && is_valid_coord(p2.x, p2.y) && is_valid_coord(p3.x, p3.y) && is_valid_coord(p4.x, p4.y)) {\n        all_rects.push_back({{p1, p2, p3, p4}});\n        int id = (int)all_rects.size() - 1;\n        potential_rects[p1.x * N + p1.y].push_back(id);\n        potential_rects[p2.x * N + p2.y].push_back(id);\n        potential_rects[p3.x * N + p3.y].push_back(id);\n        potential_rects[p4.x * N + p4.y].push_back(id);\n    }\n}\n\nint weight(int x, int y) {\n    int cx = (N - 1) / 2;\n    int cy = (N - 1) / 2;\n    return (x - cx) * (x - cx) + (y - cy) * (y - cy) + 1;\n}\n\nstruct Segment {\n    int type; // 0: h, 1: v, 2: d1, 3: d2\n    int x, y;\n};\n\nvector<Segment> get_segments(const Rectangle& r) {\n    vector<Segment> segs;\n    auto add_seg = [&](Point a, Point b) {\n        int dx = b.x - a.x, dy = b.y - a.y;\n        int dist = max(abs(dx), abs(dy));\n        int sx = (dist == 0) ? 0 : dx / dist;\n        int sy = (dist == 0) ? 0 : dy / dist;\n        for (int i = 0; i < dist; ++i) {\n            int x1 = a.x + i * sx, y1 = a.y + i * sy;\n            int x2 = x1 + sx, y2 = y1 + sy;\n            if (sy == 0) segs.push_back({0, min(x1, x2), y1});\n            else if (sx == 0) segs.push_back({1, x1, min(y1, y2)});\n            else if (sx == sy) segs.push_back({2, y1 - x1 + N, min(x1, x2)});\n            else segs.push_back({3, y1 + x1, min(x1, x2)});\n        }\n    };\n    add_seg(r.p[0], r.p[1]); add_seg(r.p[1], r.p[2]);\n    add_seg(r.p[2], r.p[3]); add_seg(r.p[3], r.p[0]);\n    return segs;\n}\n\nbool check_rect_validity(int rect_id) {\n    const auto& r = all_rects[rect_id];\n    for (const auto& seg : get_segments(r)) {\n        if (seg.type == 0 && used_h[seg.x][seg.y]) return false;\n        if (seg.type == 1 && used_v[seg.x][seg.y]) return false;\n        if (seg.type == 2 && used_d1[seg.x][seg.y]) return false;\n        if (seg.type == 3 && used_d2[seg.x][seg.y]) return false;\n    }\n    auto add_pts = [&](Point a, Point b) {\n        int dx = b.x - a.x, dy = b.y - a.y;\n        int dist = max(abs(dx), abs(dy));\n        int sx = (dist == 0) ? 0 : dx / dist;\n        int sy = (dist == 0) ? 0 : dy / dist;\n        for (int i = 1; i < dist; ++i) {\n            if (has_dot[a.x + i * sx][a.y + i * sy]) return true;\n        }\n        return false;\n    };\n    if (add_pts(r.p[0], r.p[1])) return false;\n    if (add_pts(r.p[1], r.p[2])) return false;\n    if (add_pts(r.p[2], r.p[3])) return false;\n    if (add_pts(r.p[3], r.p[0])) return false;\n    return true;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n    cin >> N >> M;\n    has_dot.assign(N, vector<bool>(N, false));\n    potential_rects.assign(N * N, vector<int>());\n    for (int i = 0; i < M; ++i) {\n        int x, y; cin >> x >> y;\n        has_dot[x][y] = true;\n    }\n\n    for (int x1 = 0; x1 < N; ++x1)\n        for (int x2 = x1 + 1; x2 < N; ++x2)\n            for (int y1 = 0; y1 < N; ++y1)\n                for (int y2 = y1 + 1; y2 < N; ++y2)\n                    add_rect({x1, y1}, {x2, y1}, {x2, y2}, {x1, y2});\n\n    for (int x = 0; x < N; ++x)\n        for (int y = 0; y < N; ++y)\n            for (int d = 1; d < N; ++d)\n                for (int k = 1; k < N; ++k)\n                    add_rect({x, y}, {x + d, y + d}, {x + d + k, y + d - k}, {x + k, y - k});\n\n    occupied_count.assign(all_rects.size(), 0);\n    is_used_rect.assign(all_rects.size(), false);\n    priority_queue<pair<int, int>> pq;\n\n    for (int i = 0; i < (int)all_rects.size(); ++i) {\n        for (int j = 0; j < 4; ++j)\n            if (has_dot[all_rects[i].p[j].x][all_rects[i].p[j].y]) occupied_count[i]++;\n        if (occupied_count[i] == 3) {\n            int empty_idx = -1;\n            for(int j=0; j<4; ++j) if(!has_dot[all_rects[i].p[j].x][all_rects[i].p[j].y]) empty_idx = j;\n            if(empty_idx != -1)\n                pq.push({weight(all_rects[i].p[empty_idx].x, all_rects[i].p[empty_idx].y), i});\n        }\n    }\n\n    struct Op { int rect_id; int p_new_idx; };\n    vector<Op> final_ops;\n\n    while (!pq.empty()) {\n        auto [w, id] = pq.top(); pq.pop();\n        if (is_used_rect[id] || occupied_count[id] != 3 || !check_rect_validity(id)) continue;\n\n        int empty_idx = -1;\n        for (int j = 0; j < 4; ++j)\n            if (!has_dot[all_rects[id].p[j].x][all_rects[id].p[j].y]) { empty_idx = j; break; }\n        \n        has_dot[all_rects[id].p[empty_idx].x][all_rects[id].p[empty_idx].y] = true;\n        is_used_rect[id] = true;\n        final_ops.push_back({id, empty_idx});\n\n        for (const auto& seg : get_segments(all_rects[id])) {\n            if (seg.type == 0) used_h[seg.x][seg.y] = true;\n            else if (seg.type == 1) used_v[seg.x][seg.y] = true;\n            else if (seg.type == 2) used_d1[seg.x][seg.y] = true;\n            else if (seg.type == 3) used_d2[seg.x][seg.y] = true;\n        }\n\n        int new_x = all_rects[id].p[empty_idx].x;\n        int new_y = all_rects[id].p[empty_idx].y;\n        for (int rect_id : potential_rects[new_x * N + new_y]) {\n            occupied_count[rect_id]++;\n            if (occupied_count[rect_id] == 3) {\n                int e_idx = -1;\n                for(int j=0; j<4; ++j) if(!has_dot[all_rects[rect_id].p[j].x][all_rects[rect_id].p[j].y]) e_idx = j;\n                if (e_idx != -1)\n                    pq.push({weight(all_rects[rect_id].p[e_idx].x, all_rects[rect_id].p[e_idx].y), rect_id});\n            }\n        }\n    }\n\n    cout << final_ops.size() << endl;\n    for (const auto& op : final_ops) {\n        const auto& r = all_rects[op.rect_id];\n        int idx = op.p_new_idx;\n        cout << r.p[idx].x << \" \" << r.p[idx].y << \" \" \n             << r.p[(idx + 1) % 4].x << \" \" << r.p[(idx + 1) % 4].y << \" \"\n             << r.p[(idx + 2) % 4].x << \" \" << r.p[(idx + 2) % 4].y << \" \"\n             << r.p[(idx + 3) % 4].x << \" \" << r.p[(idx + 3) % 4].y << endl;\n    }\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <cstring>\n#include <algorithm>\n\nusing namespace std;\n\n// Fast PRNG to speed up simulation\nstruct XorShift {\n    uint32_t x = 123456789, y = 362436069, z = 521288629, w = 88675123;\n    uint32_t next() {\n        uint32_t t = x ^ (x << 11);\n        x = y; y = z; z = w;\n        return w = w ^ (w >> 19) ^ t ^ (t >> 8);\n    }\n    int nextInt(int n) { return next() % n; }\n} rng;\n\nstruct Board {\n    int cell[100];\n};\n\n// Optimized board tilting\nvoid apply_tilt(Board& b, char dir) {\n    if (dir == 'F') {\n        for (int c = 0; c < 10; ++c) {\n            int write = 0;\n            for (int r = 0; r < 10; ++r) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[write * 10 + c] = v;\n                    write++;\n                }\n            }\n        }\n    } else if (dir == 'B') {\n        for (int c = 0; c < 10; ++c) {\n            int write = 9;\n            for (int r = 9; r >= 0; --r) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[write * 10 + c] = v;\n                    write--;\n                }\n            }\n        }\n    } else if (dir == 'L') {\n        for (int r = 0; r < 10; ++r) {\n            int write = 0;\n            for (int c = 0; c < 10; ++c) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[r * 10 + write] = v;\n                    write++;\n                }\n            }\n        }\n    } else if (dir == 'R') {\n        for (int r = 0; r < 10; ++r) {\n            int write = 9;\n            for (int c = 9; c >= 0; --c) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[r * 10 + write] = v;\n                    write--;\n                }\n            }\n        }\n    }\n}\n\n// Optimized BFS for scoring\nint calculate_score(const Board& b) {\n    int score = 0;\n    bool visited[100] = {false};\n    for (int i = 0; i < 100; ++i) {\n        if (b.cell[i] == 0 || visited[i]) continue;\n        int flavor = b.cell[i];\n        int count = 0;\n        int q[100];\n        int head = 0, tail = 0;\n        q[tail++] = i;\n        visited[i] = true;\n        while (head < tail) {\n            int curr = q[head++];\n            count++;\n            int r = curr / 10;\n            int c = curr % 10;\n            if (r > 0 && !visited[curr - 10] && b.cell[curr - 10] == flavor) {\n                visited[curr - 10] = true;\n                q[tail++] = curr - 10;\n            }\n            if (r < 9 && !visited[curr + 10] && b.cell[curr + 10] == flavor) {\n                visited[curr + 10] = true;\n                q[tail++] = curr + 10;\n            }\n            if (c > 0 && !visited[curr - 1] && b.cell[curr - 1] == flavor) {\n                visited[curr - 1] = true;\n                q[tail++] = curr - 1;\n            }\n            if (c < 9 && !visited[curr + 1] && b.cell[curr + 1] == flavor) {\n                visited[curr + 1] = true;\n                q[tail++] = curr + 1;\n            }\n        }\n        score += count * count;\n    }\n    return score;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    vector<int> f(100);\n    for (int i = 0; i < 100; ++i) cin >> f[i];\n\n    Board b;\n    memset(b.cell, 0, sizeof(b.cell));\n    char directions[] = {'F', 'B', 'L', 'R'};\n\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        cin >> p;\n        // Place candy\n        int count = 0;\n        for (int i = 0; i < 100; ++i) {\n            if (b.cell[i] == 0) {\n                count++;\n                if (count == p) {\n                    b.cell[i] = f[t];\n                    break;\n                }\n            }\n        }\n\n        if (t == 99) break;\n\n        // Perform simulations with fixed budget to avoid TLE\n        int num_rollouts = 300; \n        double max_score = -1.0;\n        char best_dir = 'F';\n\n        for (char d : directions) {\n            double total_score = 0;\n            for (int r = 0; r < num_rollouts; ++r) {\n                Board sim_b = b;\n                apply_tilt(sim_b, d);\n                \n                // Rollout\n                for (int st = t + 1; st < 100; ++st) {\n                    // Optimized empty cell finding\n                    int next_pos = rng.nextInt(100);\n                    while (sim_b.cell[next_pos] != 0) {\n                        next_pos++;\n                        if (next_pos == 100) next_pos = 0;\n                    }\n                    sim_b.cell[next_pos] = f[st];\n                    \n                    char sim_dir = directions[rng.nextInt(4)];\n                    apply_tilt(sim_b, sim_dir);\n                }\n                total_score += calculate_score(sim_b);\n            }\n            if (total_score > max_score) {\n                max_score = total_score;\n                best_dir = d;\n            }\n        }\n\n        cout << best_dir << endl;\n        apply_tilt(b, best_dir);\n    }\n\n    return 0;\n}","ahc016":"/*\n * Refined Approach:\n * 1. Optimized Adaptive N:\n *    - N = max(M, 4 + (int)(epsilon * 200))\n *    - Cap N at 100.\n *    - This strategy significantly reduces N for low epsilon, maximizing the 1/N \n *      scoring component while maintaining enough vertices for high-noise cases.\n * 2. Robust Encoding:\n *    - Clique-based graphs with sizes spread uniformly in [1, N].\n *    - Degree sequences provide distinct signatures that are invariant under vertex shuffling.\n * 3. Classification:\n *    - Euclidean distance on sorted degree sequences.\n */\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Structure to hold graph information\nstruct Graph {\n    int id;\n    int clique_size;\n    vector<int> degree_seq;\n    string edges;\n};\n\n// Helper to compute degree sequence from edges string\nvector<int> compute_degree_seq(int N, const string& edges) {\n    vector<int> deg(N, 0);\n    int idx = 0;\n    for (int i = 0; i < N - 1; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (edges[idx] == '1') {\n                deg[i]++;\n                deg[j]++;\n            }\n            idx++;\n        }\n    }\n    sort(deg.begin(), deg.end());\n    return deg;\n}\n\nint main() {\n    // Optimization for I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n\n    // Optimized Adaptive N calculation:\n    // - N >= M is required to encode M distinct graphs.\n    // - N >= 4 is a problem constraint.\n    // - We use 4 + eps * 200 to scale N with noise. This keeps N minimal \n    //   for low noise (improving 1/N score) and provides sufficient \n    //   vertices for high noise.\n    int N = (int)(4 + eps * 200);\n    if (N < M) N = M;\n    if (N > 100) N = 100;\n    if (N < 4) N = 4;\n\n    cout << N << endl;\n\n    vector<Graph> graphs(M);\n    for (int k = 0; k < M; ++k) {\n        graphs[k].id = k;\n        \n        // Distribute clique sizes uniformly in [1, N]\n        // This ensures distinct degree sequences for each graph.\n        if (M == 1) {\n            graphs[k].clique_size = 2; \n        } else {\n            graphs[k].clique_size = 1 + (int)((double)k * (N - 1) / (M - 1));\n        }\n\n        int c = graphs[k].clique_size;\n        \n        // Generate edge string\n        // A clique of size c has edges between all pairs (i, j) where i, j < c.\n        string s = \"\";\n        s.reserve(N * (N - 1) / 2);\n        for (int i = 0; i < N - 1; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (i < c && j < c) {\n                    s += '1';\n                } else {\n                    s += '0';\n                }\n            }\n        }\n        graphs[k].edges = s;\n        graphs[k].degree_seq = compute_degree_seq(N, s);\n    }\n\n    // Output the generated graphs\n    for (int k = 0; k < M; ++k) {\n        cout << graphs[k].edges << endl;\n    }\n\n    // Process 100 queries\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // Compute degree sequence of received graph\n        vector<int> degH = compute_degree_seq(N, H);\n\n        // Find the graph whose degree sequence is closest to H's\n        int best_k = 0;\n        long long min_dist = -1;\n\n        for (int k = 0; k < M; ++k) {\n            long long dist = 0;\n            const vector<int>& degG = graphs[k].degree_seq;\n            // The degree sequence is always length N\n            for (int i = 0; i < N; ++i) {\n                long long diff = (long long)degG[i] - degH[i];\n                dist += diff * diff;\n            }\n            if (min_dist == -1 || dist < min_dist) {\n                min_dist = dist;\n                best_k = k;\n            }\n        }\n        cout << best_k << endl;\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <ctime>\n\nusing namespace std;\n\n// Structure to represent an edge\nstruct Edge {\n    int u, v, w, id;\n};\n\n// Structure for predecessors in shortest path\nstruct Predecessor {\n    int u;\n    int edge_id;\n};\n\nint N, M, D, K;\nvector<vector<pair<int, pair<int, int>>>> adj;\nvector<Edge> edges;\nvector<double> edge_bc;\nvector<double> edge_cost;\n\n// Compute Betweenness Centrality using Brandes' algorithm\n// Suitable for N=1000, M=3000.\nvoid compute_bc() {\n    edge_bc.assign(M, 0.0);\n    for (int s = 0; s < N; ++s) {\n        vector<long long> dist(N + 1, 1e18);\n        vector<double> sigma(N + 1, 0.0);\n        vector<vector<Predecessor>> predecessors(N + 1);\n        vector<int> order;\n        \n        dist[s + 1] = 0;\n        sigma[s + 1] = 1.0;\n        \n        priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n        pq.push({0, s + 1});\n        \n        while (!pq.empty()) {\n            long long d = pq.top().first;\n            int u = pq.top().second;\n            pq.pop();\n            \n            if (d > dist[u]) continue;\n            order.push_back(u);\n            \n            for (auto& edge : adj[u]) {\n                int v = edge.first;\n                int weight = edge.second.first;\n                int id = edge.second.second;\n                \n                if (dist[v] > dist[u] + weight) {\n                    dist[v] = dist[u] + weight;\n                    sigma[v] = sigma[u];\n                    predecessors[v].clear();\n                    predecessors[v].push_back({u, id});\n                    pq.push({dist[v], v});\n                } else if (dist[v] == dist[u] + weight) {\n                    sigma[v] += sigma[u];\n                    predecessors[v].push_back({u, id});\n                }\n            }\n        }\n        \n        vector<double> delta(N + 1, 0.0);\n        for (int i = (int)order.size() - 1; i >= 0; --i) {\n            int w = order[i];\n            for (auto& pred : predecessors[w]) {\n                int v = pred.u;\n                int edge_id = pred.edge_id;\n                \n                double coeff = (sigma[v] / sigma[w]) * (1.0 + delta[w]);\n                delta[v] += coeff;\n                edge_bc[edge_id] += coeff;\n            }\n        }\n    }\n}\n\nint main() {\n    // Optimize I/O\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    if (!(cin >> N >> M >> D >> K)) return 0;\n    adj.resize(N + 1);\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges[i] = {u, v, w, i};\n        adj[u].push_back({v, {w, i}});\n        adj[v].push_back({u, {w, i}});\n    }\n    \n    // Read coordinates (not strictly needed, but format requires reading)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    compute_bc();\n    \n    edge_cost.resize(M);\n    for (int i = 0; i < M; ++i) {\n        edge_cost[i] = edge_bc[i] * (double)edges[i].w;\n    }\n    \n    // Initial assignment: Snake distribution for balanced initial counts and costs\n    vector<int> edge_indices(M);\n    for (int i = 0; i < M; ++i) edge_indices[i] = i;\n    \n    sort(edge_indices.begin(), edge_indices.end(), [&](int a, int b) {\n        return edge_cost[a] > edge_cost[b];\n    });\n    \n    vector<int> schedule(M);\n    vector<vector<int>> days(D + 1);\n    vector<double> sum_cost(D + 1, 0.0);\n    \n    for (int i = 0; i < M; ++i) {\n        int day = (i / D) % 2 == 0 ? (i % D) + 1 : D - (i % D);\n        schedule[edge_indices[i]] = day;\n        days[day].push_back(edge_indices[i]);\n        sum_cost[day] += edge_cost[edge_indices[i]];\n    }\n    \n    // Local Search with targeted and random swaps\n    mt19937 rng(42);\n    double start_time = clock();\n    double time_limit = 5.5 * CLOCKS_PER_SEC;\n    \n    while (clock() - start_time < time_limit) {\n        // Strategy 1: Periodic targeted swap between max/min sum days\n        int d1 = (rng() % D) + 1;\n        int d2 = (rng() % D) + 1;\n        \n        if (rng() % 5 == 0) {\n            d1 = 1; d2 = 1;\n            for (int d = 1; d <= D; ++d) {\n                if (sum_cost[d] > sum_cost[d1]) d1 = d;\n                if (sum_cost[d] < sum_cost[d2]) d2 = d;\n            }\n        }\n        \n        if (d1 == d2 || days[d1].empty() || days[d2].empty()) continue;\n        \n        int idx1 = rng() % days[d1].size();\n        int idx2 = rng() % days[d2].size();\n        \n        int e1 = days[d1][idx1];\n        int e2 = days[d2][idx2];\n        \n        double delta_cost_1 = edge_cost[e2] - edge_cost[e1];\n        double delta_cost_2 = edge_cost[e1] - edge_cost[e2];\n        \n        // Calculate the change in sum of squares of daily costs\n        // We want to minimize sum(sum_cost_d^2), which is variance minimization\n        double new_sum_cost_d1 = sum_cost[d1] + delta_cost_1;\n        double new_sum_cost_d2 = sum_cost[d2] + delta_cost_2;\n        \n        // Only accept swap if it reduces the variance\n        if (new_sum_cost_d1 * new_sum_cost_d1 + new_sum_cost_d2 * new_sum_cost_d2 < \n            sum_cost[d1] * sum_cost[d1] + sum_cost[d2] * sum_cost[d2]) {\n            \n            sum_cost[d1] = new_sum_cost_d1;\n            sum_cost[d2] = new_sum_cost_d2;\n            days[d1][idx1] = e2;\n            days[d2][idx2] = e1;\n            schedule[e1] = d2;\n            schedule[e2] = d1;\n        }\n    }\n    \n    // Output schedule\n    for (int i = 0; i < M; ++i) {\n        cout << schedule[i] << (i == M - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n};\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int D;\n    if (!(cin >> D)) return 0;\n\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for (int i = 0; i < D; ++i) cin >> f1[i];\n    for (int i = 0; i < D; ++i) cin >> r1[i];\n    for (int i = 0; i < D; ++i) cin >> f2[i];\n    for (int i = 0; i < D; ++i) cin >> r2[i];\n\n    // Compute maximum possible objects M1 and M2\n    auto get_max_obj = [&](const vector<string>& f, const vector<string>& r) {\n        vector<vector<vector<int>>> obj(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[z][x] == '1' && r[z][y] == '1') {\n                        obj[x][y][z] = 1;\n                    }\n                }\n            }\n        }\n        return obj;\n    };\n\n    auto M1 = get_max_obj(f1, r1);\n    auto M2 = get_max_obj(f2, r2);\n\n    // Compute intersection I, and unique parts U1, U2\n    vector<vector<vector<int>>> I(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> U1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> U2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n\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 (M1[x][y][z] && M2[x][y][z]) I[x][y][z] = 1;\n                else if (M1[x][y][z]) U1[x][y][z] = 1;\n                else if (M2[x][y][z]) U2[x][y][z] = 1;\n            }\n        }\n    }\n\n    vector<vector<vector<int>>> b1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> b2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n\n    int block_id = 1;\n\n    // BFS to find connected components and assign unique block IDs\n    auto find_components = [&](vector<vector<vector<int>>>& grid, int& id_counter, vector<vector<vector<int>>>& b_map) {\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\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 (grid[x][y][z] && !visited[x][y][z]) {\n                        queue<Point> q;\n                        q.push({x, y, z});\n                        visited[x][y][z] = true;\n                        b_map[x][y][z] = id_counter;\n                        \n                        int dx[] = {1, -1, 0, 0, 0, 0};\n                        int dy[] = {0, 0, 1, -1, 0, 0};\n                        int dz[] = {0, 0, 0, 0, 1, -1};\n                        \n                        while (!q.empty()) {\n                            Point curr = q.front();\n                            q.pop();\n\n                            for (int i = 0; i < 6; ++i) {\n                                int nx = curr.x + dx[i];\n                                int ny = curr.y + dy[i];\n                                int nz = curr.z + dz[i];\n                                if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                    grid[nx][ny][nz] && !visited[nx][ny][nz]) {\n                                    visited[nx][ny][nz] = true;\n                                    b_map[nx][ny][nz] = id_counter;\n                                    q.push({nx, ny, nz});\n                                }\n                            }\n                        }\n                        id_counter++;\n                    }\n                }\n            }\n        }\n    };\n\n    // 1. Process intersection (shared)\n    find_components(I, block_id, b1);\n    for(int x=0; x<D; ++x) for(int y=0; y<D; ++y) for(int z=0; z<D; ++z) b2[x][y][z] = b1[x][y][z];\n    \n    // 2. Process unique parts for object 1\n    find_components(U1, block_id, b1);\n    // 3. Process unique parts for object 2\n    find_components(U2, block_id, b2);\n\n    // Output result\n    cout << block_id - 1 << endl;\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 << b1[x][y][z] << (x == D - 1 && y == D - 1 && z == D - 1 ? \"\" : \" \");\n            }\n        }\n    }\n    cout << endl;\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 << b2[x][y][z] << (x == D - 1 && y == D - 1 && z == D - 1 ? \"\" : \" \");\n            }\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <queue>\n\nusing namespace std;\n\n// Structure for Edge\nstruct Edge {\n    int u, v, w, id;\n};\n\n// Structure for Point\nstruct Point {\n    int x, y;\n};\n\nint N, M, K;\nvector<Point> stations;\nvector<Point> residents;\nvector<Edge> edges;\nvector<vector<pair<int, int>>> adj; \n\n// Precomputed distances\nvector<vector<double>> station_resident_dist;\nvector<vector<pair<double, int>>> sorted_stations; // sorted_stations[k] = {(dist, station_id), ...}\n\n// MST structures\nvector<int> parent_node;\nvector<int> parent_edge_idx;\nvector<vector<int>> path_to_root;\n\n// Optimization structures\nvector<bool> active;\nvector<int> resident_to_rank; // Current index in sorted_stations\nvector<int> resident_to_station;\nvector<int> station_P;\nvector<int> edge_usage;\n\nvoid build_mst() {\n    vector<int> min_weight(N + 1, 2e9);\n    vector<bool> visited(N + 1, false);\n    parent_node.assign(N + 1, -1);\n    parent_edge_idx.assign(N + 1, -1);\n    \n    min_weight[1] = 0;\n    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n    pq.push({0, 1});\n\n    while (!pq.empty()) {\n        int u = pq.top().second;\n        pq.pop();\n        if (visited[u]) continue;\n        visited[u] = true;\n\n        for (auto& edge : adj[u]) {\n            int v = edge.first;\n            int edge_idx = edge.second;\n            int w = edges[edge_idx].w;\n            if (!visited[v] && w < min_weight[v]) {\n                min_weight[v] = w;\n                parent_node[v] = u;\n                parent_edge_idx[v] = edge_idx;\n                pq.push({w, v});\n            }\n        }\n    }\n    \n    path_to_root.resize(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        int curr = i;\n        while (parent_node[curr] != -1) {\n            path_to_root[i].push_back(parent_edge_idx[curr]);\n            curr = parent_node[curr];\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N >> M >> K;\n    stations.resize(N + 1);\n    for (int i = 1; i <= N; ++i) cin >> stations[i].x >> stations[i].y;\n    \n    adj.resize(N + 1);\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges[i] = {u, v, w, i};\n        adj[u].push_back({v, i});\n        adj[v].push_back({u, i});\n    }\n    \n    residents.resize(K);\n    for (int k = 0; k < K; ++k) cin >> residents[k].x >> residents[k].y;\n    \n    station_resident_dist.resize(N + 1, vector<double>(K));\n    sorted_stations.resize(K);\n    for (int k = 0; k < K; ++k) {\n        for (int i = 1; i <= N; ++i) {\n            double d = sqrt(pow(stations[i].x - residents[k].x, 2) + pow(stations[i].y - residents[k].y, 2));\n            station_resident_dist[i][k] = d;\n            sorted_stations[k].push_back({d, i});\n        }\n        sort(sorted_stations[k].begin(), sorted_stations[k].end());\n    }\n    \n    build_mst();\n    \n    active.assign(N + 1, true);\n    resident_to_rank.assign(K, 0);\n    resident_to_station.assign(K, 0);\n    station_P.assign(N + 1, 0);\n    edge_usage.assign(M, 0);\n    \n    long long total_edge_cost = 0;\n    long long total_radio_cost = 0;\n    \n    for (int k = 0; k < K; ++k) {\n        while (!active[sorted_stations[k][resident_to_rank[k]].second]) {\n            resident_to_rank[k]++;\n        }\n        int s = sorted_stations[k][resident_to_rank[k]].second;\n        resident_to_station[k] = s;\n        station_P[s] = max(station_P[s], (int)ceil(sorted_stations[k][resident_to_rank[k]].first));\n    }\n    \n    for (int i = 1; i <= N; ++i) {\n        if (active[i]) {\n            for (int edge_idx : path_to_root[i]) {\n                if (edge_usage[edge_idx] == 0) total_edge_cost += edges[edge_idx].w;\n                edge_usage[edge_idx]++;\n            }\n        }\n    }\n    \n    for (int i = 1; i <= N; ++i) total_radio_cost += (long long)station_P[i] * station_P[i];\n    \n    while (true) {\n        int best_u = -1;\n        long long best_total_cost = total_edge_cost + total_radio_cost;\n        \n        for (int u = 2; u <= N; ++u) {\n            if (!active[u]) continue;\n            \n            bool possible = true;\n            long long delta_radio = 0;\n            long long delta_edge = 0;\n            \n            vector<pair<int, int>> reassignments; \n            for (int k = 0; k < K; ++k) {\n                if (resident_to_station[k] == u) {\n                    int r = resident_to_rank[k] + 1;\n                    while (r < N && !active[sorted_stations[k][r].second]) r++;\n                    \n                    if (r == N || sorted_stations[k][r].first > 5000) {\n                        possible = false;\n                        break;\n                    }\n                    reassignments.push_back({k, r});\n                }\n            }\n            \n            if (!possible) continue;\n            \n            for (int edge_idx : path_to_root[u]) {\n                if (edge_usage[edge_idx] == 1) delta_edge -= edges[edge_idx].w;\n            }\n            \n            delta_radio -= (long long)station_P[u] * station_P[u];\n            vector<int> temp_P = station_P;\n            temp_P[u] = 0;\n            for (auto& p : reassignments) {\n                int k = p.first;\n                int r = p.second;\n                int new_s = sorted_stations[k][r].second;\n                int new_dist = (int)ceil(sorted_stations[k][r].first);\n                if (new_dist > temp_P[new_s]) {\n                    delta_radio += (long long)new_dist * new_dist - (long long)temp_P[new_s] * temp_P[new_s];\n                    temp_P[new_s] = new_dist;\n                }\n            }\n            \n            if (total_edge_cost + delta_edge + total_radio_cost + delta_radio < best_total_cost) {\n                best_total_cost = total_edge_cost + delta_edge + total_radio_cost + delta_radio;\n                best_u = u;\n            }\n        }\n        \n        if (best_u != -1) {\n            int u = best_u;\n            active[u] = false;\n            for (int edge_idx : path_to_root[u]) {\n                if (edge_usage[edge_idx] == 1) total_edge_cost -= edges[edge_idx].w;\n                edge_usage[edge_idx]--;\n            }\n            total_radio_cost -= (long long)station_P[u] * station_P[u];\n            station_P[u] = 0;\n            for (int k = 0; k < K; ++k) {\n                if (resident_to_station[k] == u) {\n                    while (!active[sorted_stations[k][resident_to_rank[k]].second]) {\n                        resident_to_rank[k]++;\n                    }\n                    int new_s = sorted_stations[k][resident_to_rank[k]].second;\n                    int new_dist = (int)ceil(sorted_stations[k][resident_to_rank[k]].first);\n                    if (new_dist > station_P[new_s]) {\n                        total_radio_cost += (long long)new_dist * new_dist - (long long)station_P[new_s] * station_P[new_s];\n                        station_P[new_s] = new_dist;\n                    }\n                    resident_to_station[k] = new_s;\n                }\n            }\n        } else {\n            break;\n        }\n    }\n    \n    for (int i = 1; i <= N; ++i) cout << station_P[i] << (i == N ? \"\" : \" \");\n    cout << endl;\n    for (int i = 0; i < M; ++i) cout << (edge_usage[i] > 0 ? 1 : 0) << (i == M - 1 ? \"\" : \" \");\n    cout << endl;\n    \n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <chrono>\n\nusing namespace std;\n\n// The number of pyramid tiers is fixed to N=30.\nconstexpr int N = 30;\nint initial_board[N][N];\nint current_board[N][N];\n\n// Structure to store swap operations\nstruct SwapOp {\n    int x1, y1, x2, y2;\n    \n    // Overload == for redundancy check (swaps are symmetric)\n    // We use a canonical representation (smaller coordinate first) to compare swaps\n    bool operator==(const SwapOp& other) const {\n        int p1_val = x1 * N + y1;\n        int p2_val = x2 * N + y2;\n        if (p1_val > p2_val) swap(p1_val, p2_val);\n\n        int o1_val = other.x1 * N + other.y1;\n        int o2_val = other.x2 * N + other.y2;\n        if (o1_val > o2_val) swap(o1_val, o2_val);\n\n        return p1_val == o1_val && p2_val == o2_val;\n    }\n};\n\n// Function to perform a swap on the current_board\ninline void perform_swap(int x1, int y1, int x2, int y2, vector<SwapOp>& ops) {\n    swap(current_board[x1][y1], current_board[x2][y2]);\n    ops.push_back({x1, y1, x2, y2});\n}\n\n// Function to build the heap using a randomized node order\n// Returns the number of operations used\nint build_heap(vector<SwapOp>& ops, mt19937& rng) {\n    // Reset board\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            current_board[i][j] = initial_board[i][j];\n        }\n    }\n    ops.clear();\n\n    // Build-Heap algorithm (bottom-up)\n    // We iterate from the last tier up to the top.\n    // For each tier, we randomize the processing order of nodes to explore different heap paths.\n    for (int x = N - 2; x >= 0; --x) {\n        vector<int> ys(x + 1);\n        iota(ys.begin(), ys.end(), 0);\n        shuffle(ys.begin(), ys.end(), rng);\n\n        for (int y : ys) {\n            int cur_x = x;\n            int cur_y = y;\n            \n            // Sift-down process to satisfy min-heap condition\n            while (cur_x < N - 1) {\n                int l_x = cur_x + 1;\n                int l_y = cur_y;\n                int r_x = cur_x + 1;\n                int r_y = cur_y + 1;\n\n                // Identify the smaller of the two children to maintain min-heap\n                int next_x = l_x;\n                int next_y = l_y;\n                if (current_board[r_x][r_y] < current_board[l_x][l_y]) {\n                    next_x = r_x;\n                    next_y = r_y;\n                }\n\n                // If the current node violates the heap property, swap with the smaller child\n                if (current_board[cur_x][cur_y] > current_board[next_x][next_y]) {\n                    perform_swap(cur_x, cur_y, next_x, next_y, ops);\n                    cur_x = next_x;\n                    cur_y = next_y;\n                } else {\n                    break;\n                }\n            }\n        }\n    }\n\n    // Post-process: remove redundant consecutive swaps (e.g., A-B then B-A)\n    if (ops.size() > 1) {\n        vector<SwapOp> cleaned_ops;\n        cleaned_ops.reserve(ops.size());\n        for (const auto& op : ops) {\n            if (!cleaned_ops.empty() && cleaned_ops.back() == op) {\n                cleaned_ops.pop_back();\n            } else {\n                cleaned_ops.push_back(op);\n            }\n        }\n        ops = std::move(cleaned_ops);\n    }\n    \n    return ops.size();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read the pyramid input\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            cin >> initial_board[i][j];\n        }\n    }\n\n    int best_K = 20000; \n    vector<SwapOp> best_ops;\n    best_ops.reserve(10000);\n    \n    mt19937 rng(1337); // Fixed seed for reproducibility\n\n    auto start_time = chrono::steady_clock::now();\n    int iterations = 0;\n\n    // Pre-allocate to avoid allocations inside the loop\n    vector<SwapOp> current_ops;\n    current_ops.reserve(10000);\n\n    // Run as many iterations as possible within 1.9 seconds\n    while (true) {\n        iterations++;\n        // Check time roughly every 64 iterations\n        if ((iterations & 63) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1900) {\n                break;\n            }\n        }\n\n        int K = build_heap(current_ops, rng);\n        \n        if (K < best_K) {\n            best_K = K;\n            best_ops = current_ops;\n        }\n    }\n\n    // Output the result\n    cout << best_ops.size() << \"\\n\";\n    for (const auto& op : best_ops) {\n        cout << op.x1 << \" \" << op.y1 << \" \" << op.x2 << \" \" << op.y2 << \"\\n\";\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nconst int D = 9;\nint grid[D][D]; // -2 obstacle, -1 empty, >=0 container label\nbool is_removed[85];\npair<int, int> pos[85];\nint D_dist[D][D]; // BFS distances from (0, 4) in an empty board\n\nint dr[] = {0, 0, 1, -1};\nint dc[] = {1, -1, 0, 0};\n\n// Precompute distances in an empty grid\nvoid precompute_dist() {\n    for (int i = 0; i < D; ++i)\n        for (int j = 0; j < D; ++j)\n            D_dist[i][j] = -1;\n\n    queue<pair<int, int>> q;\n    q.push({0, 4});\n    D_dist[0][4] = 0;\n\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i];\n            int nc = c + dc[i];\n            if (nr >= 0 && nr < D && nc >= 0 && nc < D && D_dist[nr][nc] == -1) {\n                if (grid[nr][nc] != -2) {\n                    D_dist[nr][nc] = D_dist[r][c] + 1;\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n}\n\n// Find path from entrance to (tr, tc), treating other containers as obstacles.\n// Path excludes entrance, includes (tr, tc).\nvector<pair<int, int>> get_path(int tr, int tc) {\n    if (grid[tr][tc] == -2) return {}; \n    if (tr == 0 && tc == 4) return {{0, 4}};\n\n    struct Node {\n        int r, c;\n        vector<pair<int, int>> path;\n    };\n    queue<Node> q;\n    q.push({0, 4, {{0, 4}}});\n\n    bool visited[D][D];\n    for(int i=0; i<D; ++i) for(int j=0; j<D; ++j) visited[i][j] = false;\n    visited[0][4] = true;\n\n    while (!q.empty()) {\n        Node curr = q.front();\n        q.pop();\n\n        if (curr.r == tr && curr.c == tc) return curr.path;\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n\n            if (nr >= 0 && nr < D && nc >= 0 && nc < D && !visited[nr][nc]) {\n                // Passable if empty OR it is the target container\n                if (grid[nr][nc] == -1 || (nr == tr && nc == tc)) {\n                    visited[nr][nc] = true;\n                    vector<pair<int, int>> next_path = curr.path;\n                    next_path.push_back({nr, nc});\n                    q.push({nr, nc, next_path});\n                }\n            }\n        }\n    }\n    return {};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N;\n    cin >> D >> N;\n\n    for (int i = 0; i < D; ++i)\n        for (int j = 0; j < D; ++j)\n            grid[i][j] = -1;\n\n    for (int i = 0; i < N; ++i) {\n        int r, c;\n        cin >> r >> c;\n        grid[r][c] = -2;\n    }\n\n    precompute_dist();\n    int max_dist = 0;\n    for(int i=0; i<D; ++i) for(int j=0; j<D; ++j) if(D_dist[i][j] > max_dist) max_dist = D_dist[i][j];\n\n    int K = D * D - 1 - N;\n    vector<pair<int, int>> removal_order;\n\n    for (int d = 0; d < K; ++d) {\n        int t;\n        cin >> t;\n\n        int best_r = -1, best_c = -1;\n        double min_score = 1e18;\n\n        for (int r = 0; r < D; ++r) {\n            for (int c = 0; c < D; ++c) {\n                if (grid[r][c] == -1) {\n                    if (!get_path(r, c).empty()) {\n                        double target_val = (double)t / (K - 1) * max_dist;\n                        double score = abs(D_dist[r][c] - target_val);\n                        if (score < min_score) {\n                            min_score = score;\n                            best_r = r;\n                            best_c = c;\n                        }\n                    }\n                }\n            }\n        }\n\n        grid[best_r][best_c] = t;\n        pos[t] = {best_r, best_c};\n        cout << best_r << \" \" << best_c << endl;\n    }\n\n    int target = 0;\n    int removed_cnt = 0;\n    for(int i=0; i<85; ++i) is_removed[i] = false;\n\n    while (removed_cnt < K) {\n        if (is_removed[target]) {\n            target++;\n            continue;\n        }\n\n        if (!get_path(pos[target].first, pos[target].second).empty()) {\n            removal_order.push_back(pos[target]);\n            grid[pos[target].first][pos[target].second] = -1;\n            is_removed[target] = true;\n            removed_cnt++;\n        } else {\n            int best_label = -1;\n            pair<int, int> best_pos = {-1, -1};\n            for(int r=0; r<D; ++r) {\n                for(int c=0; c<D; ++c) {\n                    if(grid[r][c] >= 0) {\n                        if (!get_path(r, c).empty()) {\n                            if (grid[r][c] > best_label) {\n                                best_label = grid[r][c];\n                                best_pos = {r, c};\n                            }\n                        }\n                    }\n                }\n            }\n            removal_order.push_back(best_pos);\n            grid[best_pos.first][best_pos.second] = -1;\n            is_removed[best_label] = true;\n            removed_cnt++;\n        }\n    }\n\n    for (auto p : removal_order) {\n        cout << p.first << \" \" << p.second << endl;\n    }\n\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MAX_N = 50;\nint N, M;\nint grid[MAX_N][MAX_N];\nbool target_adj[101][101];\nint count_adj[101][101];\nint n_cells[101];\n\nint dr[] = {0, 0, 1, -1};\nint dc[] = {1, -1, 0, 0};\n\n// Check if a color c is connected using BFS\nbool is_connected(int c) {\n    if (n_cells[c] <= 1) return true;\n\n    int start_r = -1, start_c = -1;\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            if(grid[i][j] == c) {\n                start_r = i;\n                start_c = j;\n                break;\n            }\n        }\n        if(start_r != -1) break;\n    }\n\n    if(start_r == -1) return true;\n\n    int visited = 0;\n    static int vis[MAX_N][MAX_N];\n    static int vis_gen = 0;\n    vis_gen++;\n\n    queue<pair<int, int>> q;\n    q.push({start_r, start_c});\n    vis[start_r][start_c] = vis_gen;\n    visited++;\n\n    while(!q.empty()){\n        auto [r, c_] = q.front();\n        q.pop();\n\n        for(int i=0; i<4; ++i) {\n            int nr = r + dr[i];\n            int nc = c_ + dc[i];\n            if(nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] == c && vis[nr][nc] != vis_gen){\n                vis[nr][nc] = vis_gen;\n                visited++;\n                q.push({nr, nc});\n            }\n        }\n    }\n    return visited == n_cells[c];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M;\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            cin >> grid[i][j];\n            n_cells[grid[i][j]]++;\n        }\n    }\n\n    // Initialize adjacency counts\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 + dr[k];\n                int nj = j + dc[k];\n                int nc;\n                if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                else nc = grid[ni][nj];\n                \n                if(grid[i][j] != nc) {\n                    count_adj[grid[i][j]][nc]++;\n                }\n            }\n        }\n    }\n\n    // Initialize target adjacencies\n    for(int i=0; i<=M; ++i) {\n        for(int j=0; j<=M; ++j) {\n            if (count_adj[i][j] > 0) target_adj[i][j] = true;\n        }\n    }\n\n    mt19937 rng(42);\n    vector<pair<int, int>> squares;\n    for(int i=0; i<N; ++i)\n        for(int j=0; j<N; ++j)\n            squares.push_back({i, j});\n\n    auto start_time = chrono::steady_clock::now();\n    \n    // Iterative randomized hill climbing\n    while(true) {\n        auto current_time = chrono::steady_clock::now();\n        if(chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count() > 1800) break;\n        \n        shuffle(squares.begin(), squares.end(), rng);\n        \n        for(auto [i, j] : squares) {\n            int old_c = grid[i][j];\n            if(old_c == 0) continue;\n            if(n_cells[old_c] == 1) continue;\n\n            // Check if possible to change to 0\n            bool possible = true;\n            for(int k=0; k<4; ++k) {\n                int ni = i + dr[k];\n                int nj = j + dc[k];\n                int nc;\n                if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                else nc = grid[ni][nj];\n                \n                if (old_c == nc) {\n                    // Gain 0 - old_c edge\n                    if (nc != 0) {\n                        if (count_adj[0][nc] == 0 && !target_adj[0][nc]) {\n                           possible = false; break;\n                        }\n                    }\n                } else {\n                    // Lose old_c - nc, gain 0 - nc\n                    if (count_adj[old_c][nc] == 1 && target_adj[old_c][nc]) {\n                        possible = false; break;\n                    }\n                    if (nc != 0) {\n                        if (count_adj[0][nc] == 0 && !target_adj[0][nc]) {\n                            possible = false; break;\n                        }\n                    }\n                }\n            }\n            \n            if (!possible) continue;\n            \n            // Apply change\n            grid[i][j] = 0;\n            n_cells[old_c]--;\n            n_cells[0]++;\n            \n            // Update counts\n            for(int k=0; k<4; ++k) {\n                int ni = i + dr[k];\n                int nj = j + dc[k];\n                int nc;\n                if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                else nc = grid[ni][nj];\n                \n                if (old_c == nc) {\n                    if (nc != 0) {\n                        count_adj[0][nc]++;\n                        count_adj[nc][0]++;\n                    }\n                } else {\n                    count_adj[old_c][nc]--;\n                    count_adj[nc][old_c]--;\n                    if (nc != 0) {\n                        count_adj[0][nc]++;\n                        count_adj[nc][0]++;\n                    }\n                }\n            }\n            \n            // Verify connectivity\n            if (!is_connected(old_c)) {\n                // Revert if disconnected\n                for(int k=0; k<4; ++k) {\n                    int ni = i + dr[k];\n                    int nj = j + dc[k];\n                    int nc;\n                    if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                    else nc = grid[ni][nj];\n                    \n                    if (old_c == nc) {\n                        if (nc != 0) {\n                            count_adj[0][nc]--;\n                            count_adj[nc][0]--;\n                        }\n                    } else {\n                        count_adj[old_c][nc]++;\n                        count_adj[nc][old_c]++;\n                        if (nc != 0) {\n                            count_adj[0][nc]--;\n                            count_adj[nc][0]--;\n                        }\n                    }\n                }\n                grid[i][j] = old_c;\n                n_cells[old_c]++;\n                n_cells[0]--;\n            }\n        }\n    }\n\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            cout << grid[i][j] << (j == N-1 ? \"\" : \" \");\n        }\n        cout << \"\\n\";\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <string>\n#include <numeric>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <iomanip>\n\nusing namespace std;\n\n// The Solver class encapsulates the logic for the problem\nstruct Solver {\n    int N, D, Q;\n    vector<double> weights; // Estimated weights of items\n    mt19937 rng;\n\n    Solver() : rng(1337) {}\n\n    void solve() {\n        // Read N, D, Q\n        if (!(cin >> N >> D >> Q)) return;\n        \n        // Initialize weights to a base value\n        weights.assign(N, 1000.0);\n\n        // Perform queries\n        for (int q = 0; q < Q; ++q) {\n            // Select L and R sets with random sizes (at least 1, at most N/2)\n            int nL = uniform_int_distribution<int>(1, N / 2)(rng);\n            int nR = uniform_int_distribution<int>(1, N / 2)(rng);\n            \n            vector<int> items(N);\n            iota(items.begin(), items.end(), 0);\n            shuffle(items.begin(), items.end(), rng);\n            \n            vector<int> L(items.begin(), items.begin() + nL);\n            vector<int> R(items.begin() + nL, items.begin() + nL + nR);\n            \n            // Output query\n            cout << L.size() << \" \" << R.size();\n            for (int i : L) cout << \" \" << i;\n            for (int i : R) cout << \" \" << i;\n            cout << endl;\n            \n            // Read result\n            string res;\n            cin >> res;\n            \n            // Update weights based on result\n            double sumL = 0;\n            for (int i : L) sumL += weights[i];\n            double sumR = 0;\n            for (int i : R) sumR += weights[i];\n            \n            // Decay learning rate alpha from 0.1 to 0.01\n            double alpha = 0.1 * (1.0 - 0.9 * (double)q / Q);\n            \n            // If sumL < sumR, diff > 0. If sumL > sumR, diff < 0.\n            // Adjust weights to minimize the difference in future queries.\n            double diff = 0;\n            if (res == \"<\") {\n                diff = sumR - sumL; // Target L to increase, R to decrease\n            } else if (res == \">\") {\n                diff = sumL - sumR; // Target L to decrease, R to increase\n                diff = -diff;\n            } else {\n                diff = sumL - sumR; // Target to zero\n                diff = -diff;\n            }\n            \n            for (int i : L) weights[i] += alpha * diff / L.size();\n            for (int i : R) weights[i] -= alpha * diff / R.size();\n            \n            // Keep weights positive\n            for (double& w : weights) w = max(1.0, w);\n        }\n        \n        // Final partition\n        vector<int> assignment(N);\n        vector<double> bucket_weights(D, 0.0);\n        \n        // Greedy assignment based on estimated weights (LPT)\n        vector<int> sorted_items(N);\n        iota(sorted_items.begin(), sorted_items.end(), 0);\n        sort(sorted_items.begin(), sorted_items.end(), [&](int a, int b) {\n            return weights[a] > weights[b];\n        });\n        \n        for (int i : sorted_items) {\n            int best_bucket = 0;\n            for (int d = 1; d < D; ++d) {\n                if (bucket_weights[d] < bucket_weights[best_bucket]) {\n                    best_bucket = d;\n                }\n            }\n            assignment[i] = best_bucket;\n            bucket_weights[best_bucket] += weights[i];\n        }\n        \n        // Local search to refine the partition\n        // 100,000 iterations is well within the 2-second limit\n        for (int iter = 0; iter < 100000; ++iter) {\n            int b1 = uniform_int_distribution<int>(0, D - 1)(rng);\n            int b2 = uniform_int_distribution<int>(0, D - 1)(rng);\n            if (b1 == b2) continue;\n            \n            // Find items in buckets b1 and b2\n            vector<int> items1, items2;\n            for (int i = 0; i < N; ++i) {\n                if (assignment[i] == b1) items1.push_back(i);\n                else if (assignment[i] == b2) items2.push_back(i);\n            }\n            if (items1.empty() || items2.empty()) continue;\n            \n            int i1 = items1[uniform_int_distribution<int>(0, items1.size() - 1)(rng)];\n            int i2 = items2[uniform_int_distribution<int>(0, items2.size() - 1)(rng)];\n            \n            // Calculate current sum of squares (proportional to variance)\n            double old_sum_sq = 0;\n            for (double w : bucket_weights) old_sum_sq += w * w;\n            \n            // Calculate new sum of squares if we swap i1 and i2\n            double new_bw1 = bucket_weights[b1] - weights[i1] + weights[i2];\n            double new_bw2 = bucket_weights[b2] - weights[i2] + weights[i1];\n            \n            double new_sum_sq = old_sum_sq \n                                - bucket_weights[b1]*bucket_weights[b1] - bucket_weights[b2]*bucket_weights[b2]\n                                + new_bw1 * new_bw1 + new_bw2 * new_bw2;\n                           \n            // If swap improves variance (decreases sum of squares), accept it\n            if (new_sum_sq < old_sum_sq) {\n                assignment[i1] = b2;\n                assignment[i2] = b1;\n                bucket_weights[b1] = new_bw1;\n                bucket_weights[b2] = new_bw2;\n            }\n        }\n        \n        // Output the final partition\n        for (int i = 0; i < N; ++i) cout << assignment[i] << (i == N - 1 ? \"\" : \" \");\n        cout << endl;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    Solver s;\n    s.solve();\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\n// Global Configuration\nint N, M;\nvector<vector<int>> stacks;\nvector<int> box_to_stack;\nvector<int> box_to_pos;\n\n// Find the stack containing a specific target box\nint find_stack(int target) {\n    return box_to_stack[target];\n}\n\n// Helper to find the minimum box number in a stack.\n// This represents the \"deadline\" for the stack: we must process this box \n// before or at the time we process any box larger than it. \n// Burying a stack with a large minimum is safe because we don't need those boxes soon.\nint get_min_box(const vector<int>& stack) {\n    if (stack.empty()) return 1000000; // Large value for empty stack\n    int min_b = 1000000;\n    for (int b : stack) {\n        if (b < min_b) min_b = b;\n    }\n    return min_b;\n}\n\n// Find the best destination stack for moving blocks of boxes.\n// Criteria:\n// 1. Prefer empty stacks (represented by min_box = 1000000).\n// 2. Otherwise, pick the stack with the largest min_box (least urgent).\n// 3. Tie-breaker: smaller stack size (keeps the stacks more balanced).\nint find_best_dest(int s) {\n    int best_d = -1;\n    int max_min_box = -1;\n    int min_size = 1000000;\n\n    for (int d = 0; d < M; ++d) {\n        if (d == s) continue; // Cannot move to the current stack\n        \n        int current_min_box = get_min_box(stacks[d]);\n        \n        // We want to maximize the minimum box number (least urgent stack)\n        if (current_min_box > max_min_box) {\n            max_min_box = current_min_box;\n            best_d = d;\n            min_size = stacks[d].size();\n        } else if (current_min_box == max_min_box) {\n            // Tie-breaker: smaller stack size\n            if ((int)stacks[d].size() < min_size) {\n                min_size = stacks[d].size();\n                best_d = d;\n            }\n        }\n    }\n    return best_d;\n}\n\n// Move the block of boxes above the target box to another stack d\nvoid move_block(int s, int pos, int d) {\n    int block_start_idx = pos + 1;\n    \n    // Update stack_ids and positions for the moved boxes\n    for (int i = block_start_idx; i < (int)stacks[s].size(); ++i) {\n        int b = stacks[s][i];\n        stacks[d].push_back(b);\n        box_to_stack[b] = d;\n        box_to_pos[b] = (int)stacks[d].size() - 1;\n    }\n    \n    // Remove the moved boxes from the original stack\n    stacks[s].erase(stacks[s].begin() + block_start_idx, stacks[s].end());\n}\n\nint main() {\n    // Optimize I/O\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M)) return 0;\n    \n    stacks.resize(M);\n    box_to_stack.resize(N + 1);\n    box_to_pos.resize(N + 1);\n\n    // Read the initial stack configuration\n    for (int i = 0; i < M; ++i) {\n        for (int j = 0; j < N / M; ++j) {\n            int b;\n            cin >> b;\n            stacks[i].push_back(b);\n            box_to_stack[b] = i;\n            box_to_pos[b] = (int)stacks[i].size() - 1;\n        }\n    }\n\n    int target = 1;\n    int ops = 0;\n    \n    // Process until all boxes are removed\n    while (target <= N && ops < 5000) {\n        int s = find_stack(target);\n        int pos = box_to_pos[target];\n        \n        // If target is at the top of its stack, remove it\n        if (pos == (int)stacks[s].size() - 1) {\n            cout << target << \" 0\" << endl;\n            stacks[s].pop_back();\n            target++;\n            ops++;\n        } else {\n            // Need to move the block\n            int d = find_best_dest(s);\n            int v_prime = stacks[s][pos + 1];\n            \n            // Output the move operation (v, i+1)\n            cout << v_prime << \" \" << (d + 1) << endl;\n            \n            // Perform the move\n            move_block(s, pos, d);\n            ops++;\n        }\n    }\n\n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <queue>\n#include <ctime>\n\nusing namespace std;\n\n// Helper to map 2D coordinates to 1D\nint id(int r, int c, int N) {\n    return r * N + c;\n}\n\n// Helper to map 1D index to 2D coordinates\npair<int, int> pos(int idx, int N) {\n    return {idx / N, idx % N};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> h(N - 1), v(N);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    for (int i = 0; i < N; ++i) cin >> v[i];\n    vector<vector<int>> d(N, vector<int>(N));\n    vector<int> d_flat(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n            d_flat[id(i, j, N)] = d[i][j];\n        }\n    }\n\n    // Build the grid graph\n    vector<vector<int>> adj(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (i + 1 < N && h[i][j] == '0') {\n                adj[id(i, j, N)].push_back(id(i + 1, j, N));\n                adj[id(i + 1, j, N)].push_back(id(i, j, N));\n            }\n            if (j + 1 < N && v[i][j] == '0') {\n                adj[id(i, j, N)].push_back(id(i, j + 1, N));\n                adj[id(i, j + 1, N)].push_back(id(i, j, N));\n            }\n        }\n    }\n\n    // Prim's algorithm for an initial spanning tree\n    vector<int> deg(N * N, 0);\n    vector<vector<int>> tree_adj(N * N);\n    vector<vector<bool>> is_in_tree(N * N, vector<bool>(N * N, false));\n    vector<int> parent(N * N, -1);\n    vector<bool> visited(N * N, false);\n    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n    pq.push({0, 0});\n    vector<int> min_edge_w(N * N, 1e9);\n    min_edge_w[0] = 0;\n    \n    while(!pq.empty()){\n        int u = pq.top().second;\n        pq.pop();\n        if(visited[u]) continue;\n        visited[u] = true;\n        \n        if(parent[u] != -1){\n            int p = parent[u];\n            tree_adj[u].push_back(p);\n            tree_adj[p].push_back(u);\n            is_in_tree[u][p] = is_in_tree[p][u] = true;\n            deg[u]++;\n            deg[p]++;\n        }\n        \n        for(int neighbor : adj[u]){\n            if(!visited[neighbor]){\n                // Heuristic: connect higher dirt regions\n                int weight = -(d_flat[u] + d_flat[neighbor]);\n                if(weight < min_edge_w[neighbor]){\n                    min_edge_w[neighbor] = weight;\n                    parent[neighbor] = u;\n                    pq.push({weight, neighbor});\n                }\n            }\n        }\n    }\n\n    auto get_cost = [&](int u) -> double {\n        return (double)d_flat[u] / deg[u];\n    };\n\n    // Simulated Annealing to optimize tree\n    mt19937 rng(42);\n    auto start_time = clock();\n    double T = 1.0;\n    \n    vector<pair<int, int>> non_tree_edges;\n    for(int u = 0; u < N * N; ++u) {\n        for(int v : adj[u]) {\n            if (u < v && !is_in_tree[u][v]) {\n                non_tree_edges.push_back({u, v});\n            }\n        }\n    }\n\n    while ((double)(clock() - start_time) / CLOCKS_PER_SEC < 1.8) {\n        int idx = rng() % non_tree_edges.size();\n        int u = non_tree_edges[idx].first;\n        int v = non_tree_edges[idx].second;\n        \n        vector<int> path_parent(N * N, -1);\n        vector<int> q;\n        q.push_back(u);\n        vector<bool> v_visited(N * N, false);\n        v_visited[u] = true;\n        int head = 0;\n        bool found = false;\n        while(head < (int)q.size()){\n            int curr = q[head++];\n            if(curr == v) { found = true; break; }\n            for(int neighbor : tree_adj[curr]){\n                if(!v_visited[neighbor]){\n                    v_visited[neighbor] = true;\n                    path_parent[neighbor] = curr;\n                    q.push_back(neighbor);\n                }\n            }\n        }\n        \n        if(!found) continue;\n\n        vector<pair<int, int>> path_edges;\n        int curr = v;\n        while(curr != u){\n            int p = path_parent[curr];\n            path_edges.push_back({curr, p});\n            curr = p;\n        }\n\n        for(auto& e : path_edges){\n            int a = e.first;\n            int b = e.second;\n            \n            double old_c = get_cost(a) + get_cost(b) + get_cost(u) + get_cost(v);\n            double new_c = (double)d_flat[a] / (deg[a]-1) + (double)d_flat[b] / (deg[b]-1) + (double)d_flat[u] / (deg[u]+1) + (double)d_flat[v] / (deg[v]+1);\n            \n            double delta = new_c - old_c;\n            \n            if (delta < 0 || exp(-delta / T) > (double)rng() / rng.max()) {\n                is_in_tree[a][b] = is_in_tree[b][a] = false;\n                is_in_tree[u][v] = is_in_tree[v][u] = true;\n                \n                for(int i=0; i<(int)tree_adj[a].size(); ++i) if(tree_adj[a][i] == b) { tree_adj[a].erase(tree_adj[a].begin()+i); break; }\n                for(int i=0; i<(int)tree_adj[b].size(); ++i) if(tree_adj[b][i] == a) { tree_adj[b].erase(tree_adj[b].begin()+i); break; }\n                tree_adj[u].push_back(v);\n                tree_adj[v].push_back(u);\n                \n                deg[a]--; deg[b]--; deg[u]++; deg[v]++;\n                non_tree_edges[idx] = {a, b};\n                break;\n            }\n        }\n        T *= 0.99999;\n    }\n\n    // Build DFS path\n    vector<vector<int>> children(N * N);\n    vector<int> q; q.push_back(0);\n    vector<bool> visited_node(N * N, false);\n    visited_node[0] = true;\n    int head = 0;\n    while(head < (int)q.size()){\n        int u = q[head++];\n        for(int neighbor : tree_adj[u]){\n            if(!visited_node[neighbor]){\n                visited_node[neighbor] = true;\n                children[u].push_back(neighbor);\n                q.push_back(neighbor);\n            }\n        }\n    }\n    vector<int> parent_node(N * N, -1);\n    for(int i = 0; i < N * N; ++i) for(int child : children[i]) parent_node[child] = i;\n    vector<long long> subtree_d(N * N, 0);\n    for(int i = N * N - 1; i >= 0; --i){\n        int u = q[i];\n        subtree_d[u] += d_flat[u];\n        if(parent_node[u] != -1) subtree_d[parent_node[u]] += subtree_d[u];\n    }\n    for(int i=0; i<N*N; ++i) sort(children[i].begin(), children[i].end(), [&](int a, int b){ return subtree_d[a] > subtree_d[b]; });\n\n    string path_str = \"\";\n    auto get_dir = [&](int u, int v) {\n        pair<int, int> p1 = pos(u, N), p2 = pos(v, N);\n        if (p2.first == p1.first + 1) return 'D';\n        if (p2.first == p1.first - 1) return 'U';\n        if (p2.second == p1.second + 1) return 'R';\n        if (p2.second == p1.second - 1) return 'L';\n        return ' ';\n    };\n\n    auto dfs = [&](auto self, int u) -> void {\n        for(int neighbor : children[u]){\n            path_str += get_dir(u, neighbor);\n            self(self, neighbor);\n            path_str += get_dir(neighbor, u);\n        }\n    };\n    dfs(dfs, 0);\n    \n    string final_path = \"\";\n    while((int)final_path.length() + (int)path_str.length() <= 100000) final_path += path_str;\n    cout << final_path << endl;\n\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <ctime>\n\nusing namespace std;\n\n// Structure to hold grid coordinates\nstruct Pos {\n    int r, c;\n};\n\n// Function to calculate the cost of moving between two squares.\n// The cost is |r1-r2| + |c1-c2| + 1.\ninline int dist(Pos p1, Pos p2) {\n    return abs(p1.r - p2.r) + abs(p1.c - p2.c) + 1;\n}\n\n// Global variables\nint N, M;\nint si, sj;\nvector<vector<Pos>> pos_map(26);\nvector<string> t;\nvector<vector<int>> overlap;\n\n// DP function to calculate ONLY the minimum travel cost for a given superstring.\nlong long get_min_cost(const string& s) {\n    int L = s.length();\n    if (L == 0) return 0;\n\n    const auto& start_chars = pos_map[s[0] - 'A'];\n    vector<long long> dp(start_chars.size());\n    \n    Pos start_pos = {si, sj};\n    for (size_t i = 0; i < start_chars.size(); ++i) {\n        dp[i] = dist(start_pos, start_chars[i]);\n    }\n\n    for (int k = 1; k < L; ++k) {\n        const auto& curr_chars = pos_map[s[k] - 'A'];\n        const auto& prev_chars = pos_map[s[k-1] - 'A'];\n        \n        vector<long long> next_dp(curr_chars.size(), 1e18);\n        \n        for (size_t i = 0; i < curr_chars.size(); ++i) {\n            for (size_t j = 0; j < prev_chars.size(); ++j) {\n                long long d = dp[j] + dist(prev_chars[j], curr_chars[i]);\n                if (d < next_dp[i]) {\n                    next_dp[i] = d;\n                }\n            }\n        }\n        dp = next_dp;\n    }\n\n    long long min_cost = 1e18;\n    for (long long val : dp) {\n        if (val < min_cost) min_cost = val;\n    }\n    return min_cost;\n}\n\n// DP function to calculate the cost AND the path for final reconstruction.\npair<long long, vector<Pos>> solve_dp(const string& s) {\n    int L = s.length();\n    const auto& start_chars = pos_map[s[0] - 'A'];\n    vector<long long> dp(start_chars.size());\n    vector<vector<int>> parent_path(L);\n    \n    Pos start_pos = {si, sj};\n    for (size_t i = 0; i < start_chars.size(); ++i) {\n        dp[i] = dist(start_pos, start_chars[i]);\n    }\n\n    for (int k = 1; k < L; ++k) {\n        const auto& curr_chars = pos_map[s[k] - 'A'];\n        const auto& prev_chars = pos_map[s[k-1] - 'A'];\n        \n        vector<long long> next_dp(curr_chars.size(), 1e18);\n        vector<int> next_parent(curr_chars.size(), -1);\n        \n        for (size_t i = 0; i < curr_chars.size(); ++i) {\n            for (size_t j = 0; j < prev_chars.size(); ++j) {\n                long long d = dp[j] + dist(prev_chars[j], curr_chars[i]);\n                if (d < next_dp[i]) {\n                    next_dp[i] = d;\n                    next_parent[i] = (int)j;\n                }\n            }\n        }\n        dp = next_dp;\n        parent_path[k] = next_parent;\n    }\n\n    long long min_cost = 1e18;\n    int last_idx = -1;\n    for (size_t i = 0; i < dp.size(); ++i) {\n        if (dp[i] < min_cost) {\n            min_cost = dp[i];\n            last_idx = (int)i;\n        }\n    }\n\n    vector<Pos> path(L);\n    int curr_idx = last_idx;\n    for (int k = L - 1; k >= 0; --k) {\n        path[k] = pos_map[s[k] - 'A'][curr_idx];\n        if (k > 0) {\n            curr_idx = parent_path[k][curr_idx];\n        }\n    }\n    return {min_cost, path};\n}\n\nstring build_superstring(const vector<int>& p) {\n    string res = t[p[0]];\n    for (size_t i = 1; i < p.size(); ++i) {\n        res += t[p[i]].substr(overlap[p[i-1]][p[i]]);\n    }\n    return res;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M)) return 0;\n    cin >> si >> sj;\n\n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) {\n            pos_map[row[j] - 'A'].push_back({i, j});\n        }\n    }\n\n    t.resize(M);\n    for (int i = 0; i < M; ++i) cin >> t[i];\n\n    overlap.assign(M, vector<int>(M));\n    for (int i = 0; i < M; ++i) {\n        for (int j = 0; j < M; ++j) {\n            if (i == j) continue;\n            for (int len = 5; len >= 0; --len) {\n                if (t[i].substr(5 - len) == t[j].substr(0, len)) {\n                    overlap[i][j] = len;\n                    break;\n                }\n            }\n        }\n    }\n\n    // 1. Generate M greedy initial candidates\n    vector<vector<int>> candidates;\n    for (int start_node = 0; start_node < M; ++start_node) {\n        vector<int> p;\n        p.reserve(M);\n        p.push_back(start_node);\n        vector<bool> used(M, false);\n        used[start_node] = true;\n        \n        for (int i = 1; i < M; ++i) {\n            int last = p.back();\n            int best_next = -1;\n            int max_o = -1;\n            for (int j = 0; j < M; ++j) {\n                if (!used[j] && overlap[last][j] > max_o) {\n                    max_o = overlap[last][j];\n                    best_next = j;\n                }\n            }\n            p.push_back(best_next);\n            used[best_next] = true;\n        }\n        candidates.push_back(p);\n    }\n\n    // 2. Perform Hill Climbing / Local Search\n    long long best_total_cost = 2e18;\n    vector<int> best_p;\n    \n    // Find initial best\n    for(const auto& p : candidates) {\n        long long c = get_min_cost(build_superstring(p));\n        if(c < best_total_cost) {\n            best_total_cost = c;\n            best_p = p;\n        }\n    }\n\n    mt19937 rng(1337);\n    auto start_time = clock();\n    \n    int cand_idx = 0;\n    while ((double)(clock() - start_time) / CLOCKS_PER_SEC < 1.7) {\n        vector<int> p = candidates[cand_idx % M];\n        \n        // Hill climbing: 2-opt moves\n        for(int iter = 0; iter < 10; ++iter) {\n            int i = rng() % (M - 1);\n            int j = i + 1 + rng() % (M - 1 - i);\n            \n            vector<int> next_p = p;\n            reverse(next_p.begin() + i, next_p.begin() + j + 1);\n            \n            long long current_cost = get_min_cost(build_superstring(p));\n            long long next_cost = get_min_cost(build_superstring(next_p));\n            \n            if (next_cost < current_cost) {\n                p = next_p;\n                \n                // Keep track of the best global permutation found\n                if (next_cost < best_total_cost) {\n                    best_total_cost = next_cost;\n                    best_p = next_p;\n                }\n            }\n        }\n        cand_idx++;\n    }\n\n    // 3. Final path reconstruction\n    pair<long long, vector<Pos>> final_result = solve_dp(build_superstring(best_p));\n    for (const auto& pos : final_result.second) {\n        cout << pos.r << \" \" << pos.c << \"\\n\";\n    }\n\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <iomanip>\n\nusing namespace std;\n\n// Structure to represent a point on the island\nstruct Point {\n    int r, c;\n};\n\n// Structure to represent an oil field\nstruct Field {\n    vector<Point> shape;\n    int max_dr, max_dc;\n};\n\nint N, M;\ndouble eps;\nvector<Field> fields;\n\n// Global vector for precomputed is_oil: [k][r][c][i][j]\n// Using uint8_t to save memory\nvector<uint8_t> is_oil; \n\ninline bool get_is_oil(int k, int r, int c, int i, int j) {\n    if (i < r || j < c || i >= r + fields[k].max_dr + 1 || j >= c + fields[k].max_dc + 1) return false;\n    return is_oil[((((k * N + r) * N + c) * N + i) * N + j)];\n}\n\nstruct Config {\n    vector<Point> offsets;\n    double log_weight;\n};\n\nvector<Config> particles;\nconst int NUM_PARTICLES = 250;\n\nvoid init_particles() {\n    particles.clear();\n    mt19937 rng(12345);\n    for (int i = 0; i < NUM_PARTICLES; ++i) {\n        Config c;\n        for (int k = 0; k < M; ++k) {\n            uniform_int_distribution<int> dist_r(0, N - 1 - fields[k].max_dr);\n            uniform_int_distribution<int> dist_c(0, N - 1 - fields[k].max_dc);\n            c.offsets.push_back({dist_r(rng), dist_c(rng)});\n        }\n        c.log_weight = -log((double)NUM_PARTICLES);\n        particles.push_back(c);\n    }\n}\n\nint compute_v_S(const Config& c, const vector<Point>& S) {\n    int v_S = 0;\n    for (const auto& p : S) {\n        for (int k = 0; k < M; ++k) {\n            if (get_is_oil(k, c.offsets[k].r, c.offsets[k].c, p.r, p.c)) {\n                v_S++;\n            }\n        }\n    }\n    return v_S;\n}\n\nvoid update_weights(const vector<Point>& S, double obs) {\n    int k = S.size();\n    double sigma2 = (double)k * eps * (1.0 - eps);\n    double max_log_w = -1e18;\n\n    for (auto& c : particles) {\n        int v_S = compute_v_S(c, S);\n        double mu = (double)(k - v_S) * eps + (double)v_S * (1.0 - eps);\n        double log_likelihood = -0.5 * pow(obs - mu, 2) / sigma2;\n        c.log_weight += log_likelihood;\n        if (c.log_weight > max_log_w) max_log_w = c.log_weight;\n    }\n\n    double sum_w = 0;\n    for (auto& c : particles) {\n        c.log_weight -= max_log_w;\n        sum_w += exp(c.log_weight);\n    }\n    for (auto& c : particles) {\n        c.log_weight = log(exp(c.log_weight) / sum_w);\n    }\n}\n\nvoid resample() {\n    double sum_sq_w = 0;\n    for (auto& c : particles) sum_sq_w += exp(2.0 * c.log_weight);\n    if (1.0 / sum_sq_w < NUM_PARTICLES / 3.0) {\n        vector<Config> new_particles;\n        vector<double> weights;\n        for (auto& c : particles) weights.push_back(exp(c.log_weight));\n        discrete_distribution<int> dist(weights.begin(), weights.end());\n        mt19937 rng(45678);\n        for (int i = 0; i < NUM_PARTICLES; ++i) {\n            new_particles.push_back(particles[dist(rng)]);\n            new_particles.back().log_weight = -log((double)NUM_PARTICLES);\n        }\n        particles = new_particles;\n    }\n}\n\nvoid rejuvenate() {\n    double min_w = 1e18;\n    for (auto& c : particles) min_w = min(min_w, c.log_weight);\n    \n    mt19937 rng(999);\n    for (auto& c : particles) {\n        if (c.log_weight < min_w + 1e-4) {\n            for (int k = 0; k < M; ++k) {\n                c.offsets[k].r = uniform_int_distribution<int>(0, N - 1 - fields[k].max_dr)(rng);\n                c.offsets[k].c = uniform_int_distribution<int>(0, N - 1 - fields[k].max_dc)(rng);\n            }\n            c.log_weight = -log((double)NUM_PARTICLES);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    cin >> N >> M >> eps;\n    fields.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int d; cin >> d;\n        int max_dr = 0, max_dc = 0;\n        for (int i = 0; i < d; ++i) {\n            int r, c; cin >> r >> c;\n            fields[k].shape.push_back({r, c});\n            max_dr = max(max_dr, r);\n            max_dc = max(max_dc, c);\n        }\n        fields[k].max_dr = max_dr;\n        fields[k].max_dc = max_dc;\n    }\n\n    is_oil.assign(M * N * N * N * N, 0);\n    for (int k = 0; k < M; ++k) {\n        for (int r = 0; r <= N - 1 - fields[k].max_dr; ++r) {\n            for (int c = 0; c <= N - 1 - fields[k].max_dc; ++c) {\n                for (const auto& p : fields[k].shape) {\n                    is_oil[((((k * N + r) * N + c) * N + (r + p.r)) * N + (c + p.c))] = 1;\n                }\n            }\n        }\n    }\n\n    init_particles();\n    mt19937 rng(42);\n    int query_count = 0;\n    while (query_count < 2 * N * N) {\n        vector<vector<Point>> candidates;\n        for (int i = 0; i < 50; ++i) {\n            int k = uniform_int_distribution<int>(1, N * N / 2)(rng);\n            vector<Point> S;\n            for (int j = 0; j < k; ++j) S.push_back({uniform_int_distribution<int>(0, N - 1)(rng), uniform_int_distribution<int>(0, N - 1)(rng)});\n            candidates.push_back(S);\n        }\n\n        int best_idx = -1;\n        double best_var = -1.0;\n        for (int i = 0; i < candidates.size(); ++i) {\n            double mean = 0;\n            vector<int> v_Ss;\n            for (auto& c : particles) {\n                int v_S = compute_v_S(c, candidates[i]);\n                v_Ss.push_back(v_S);\n                mean += exp(c.log_weight) * v_S;\n            }\n            double var = 0;\n            for (int j = 0; j < particles.size(); ++j) var += exp(particles[j].log_weight) * pow(v_Ss[j] - mean, 2);\n            double score = var * sqrt((double)candidates[i].size());\n            if (score > best_var) { best_var = score; best_idx = i; }\n        }\n\n        cout << \"q \" << candidates[best_idx].size();\n        for (auto& p : candidates[best_idx]) cout << \" \" << p.r << \" \" << p.c;\n        cout << endl;\n        double obs; cin >> obs;\n        update_weights(candidates[best_idx], obs);\n        resample();\n        rejuvenate();\n        query_count++;\n\n        // Guess\n        vector<Point> guess_set;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                double prob = 0;\n                for (auto& c : particles) {\n                    bool oil = false;\n                    for (int k = 0; k < M; ++k) if (get_is_oil(k, c.offsets[k].r, c.offsets[k].c, i, j)) { oil = true; break; }\n                    if (oil) prob += exp(c.log_weight);\n                }\n                if (prob > 0.5) guess_set.push_back({i, j});\n            }\n        }\n\n        cout << \"a \" << guess_set.size();\n        for (auto& p : guess_set) cout << \" \" << p.r << \" \" << p.c;\n        cout << endl;\n        int resp; cin >> resp;\n        if (resp == 1) return 0;\n    }\n    return 0;\n}","ahc031":"/*\n * Problem: Minimize total cost of rental area deficiency and partition movement.\n * Approach: Partition the W x W grid into N horizontal strips.\n * Use Coordinate Descent (Hill Climbing) followed by Simulated Annealing to optimize\n * the vertical positions of the N-1 internal partition lines.\n */\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Function to calculate area cost for a given strip height\nlong long get_area_cost(int W, int a_val, int height) {\n    if (height <= 0) return 1e15; // Prevents invalid partition configurations\n    long long area = (long long)W * height;\n    if (a_val > area) return 100LL * (a_val - area);\n    return 0LL;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\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    // lines[d][k] is the vertical position of the partition between strip k-1 and k.\n    vector<vector<int>> lines(D, vector<int>(N + 1));\n    for (int d = 0; d < D; ++d) {\n        lines[d][0] = 0;\n        lines[d][N] = W;\n        int current_pos = 0;\n        for (int k = 0; k < N - 1; ++k) {\n            int needed_height = (a[d][k] + W - 1) / W;\n            current_pos += max(1, needed_height);\n            lines[d][k + 1] = current_pos;\n        }\n        for (int k = 1; k < N; ++k) {\n            lines[d][k] = max(lines[d][k - 1] + 1, min(lines[d][k], W - (N - k)));\n        }\n    }\n\n    // Stage 1: Coordinate Descent (Hill Climbing)\n    for (int iter = 0; iter < 50; ++iter) {\n        bool changed = false;\n        for (int d = 0; d < D; ++d) {\n            for (int k = 1; k < N; ++k) {\n                int best_pos = lines[d][k];\n                long long min_cost = -1;\n                int low = lines[d][k - 1] + 1;\n                int high = lines[d][k + 1] - 1;\n                for (int pos = low; pos <= high; ++pos) {\n                    long long cost = 0;\n                    cost += get_area_cost(W, a[d][k - 1], pos - lines[d][k - 1]);\n                    cost += get_area_cost(W, a[d][k], lines[d][k + 1] - pos);\n                    if (d > 0 && pos != lines[d - 1][k]) cost += 2LL * W;\n                    if (d < D - 1 && pos != lines[d + 1][k]) cost += 2LL * W;\n                    if (min_cost == -1 || cost < min_cost) {\n                        min_cost = cost;\n                        best_pos = pos;\n                    }\n                }\n                if (lines[d][k] != best_pos) {\n                    lines[d][k] = best_pos;\n                    changed = true;\n                }\n            }\n        }\n        if (!changed) break;\n    }\n\n    // Stage 2: Simulated Annealing\n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    double temp = 1000.0;\n    double min_temp = 1.0;\n    int iter = 0;\n\n    while (true) {\n        if ((iter & 2047) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 2800) break;\n        }\n        iter++;\n\n        int d = uniform_int_distribution<int>(0, D - 1)(rng);\n        int k = uniform_int_distribution<int>(1, N - 1)(rng);\n\n        int old_pos = lines[d][k];\n        int low = lines[d][k - 1] + 1;\n        int high = lines[d][k + 1] - 1;\n        if (low > high) continue;\n\n        int new_pos = uniform_int_distribution<int>(low, high)(rng);\n        if (new_pos == old_pos) continue;\n\n        long long delta = 0;\n        delta -= get_area_cost(W, a[d][k - 1], old_pos - lines[d][k - 1]);\n        delta -= get_area_cost(W, a[d][k], lines[d][k + 1] - old_pos);\n        delta += get_area_cost(W, a[d][k - 1], new_pos - lines[d][k - 1]);\n        delta += get_area_cost(W, a[d][k], lines[d][k + 1] - new_pos);\n\n        if (d > 0) {\n            if (old_pos != lines[d - 1][k]) delta -= 2 * W;\n            if (new_pos != lines[d - 1][k]) delta += 2 * W;\n        }\n        if (d < D - 1) {\n            if (old_pos != lines[d + 1][k]) delta -= 2 * W;\n            if (new_pos != lines[d + 1][k]) delta += 2 * W;\n        }\n\n        double acceptance = exp(-delta / temp);\n        if (delta < 0 || uniform_real_distribution<double>(0, 1)(rng) < acceptance) {\n            lines[d][k] = new_pos;\n        }\n\n        temp = max(min_temp, temp * 0.9999995);\n    }\n\n    // Output\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << lines[d][k] << \" \" << 0 << \" \" << lines[d][k + 1] << \" \" << W << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\n// Standard library includes and types\nconst int MOD = 998244353;\n\nstruct Op {\n    int m, p, q;\n};\n\nint N, M, K;\nvector<vector<int>> A;\nvector<vector<vector<int>>> S;\n\n// Function to calculate the total score: sum(b_{i,j} % MOD)\nlong long calc_score(const vector<vector<long long>>& board) {\n    long long score = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            score += (board[i][j] % MOD);\n        }\n    }\n    return score;\n}\n\n// Function to apply a stamp\nvoid apply(vector<vector<long long>>& board, const Op& op) {\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            board[op.p + i][op.q + j] += S[op.m][i][j];\n        }\n    }\n}\n\n// Function to undo a stamp\nvoid undo(vector<vector<long long>>& board, const Op& op) {\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            board[op.p + i][op.q + j] -= S[op.m][i][j];\n        }\n    }\n}\n\nint main() {\n    // Faster I/O\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read Input\n    cin >> N >> M >> K;\n    A.resize(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    S.resize(M, vector<vector<int>>(3, vector<int>(3)));\n    for (int m = 0; m < M; ++m)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> S[m][i][j];\n\n    // Initial board\n    vector<vector<long long>> board(N, vector<long long>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            board[i][j] = A[i][j];\n\n    // Initial Greedy Approach\n    vector<Op> ops;\n    for (int k = 0; k < K; ++k) {\n        long long best_gain = -1;\n        Op best_op = {-1, -1, -1};\n\n        // Try every possible stamp and position to find the best gain\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    long long gain = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            gain -= (board[p + i][q + j] % MOD);\n                            gain += ((board[p + i][q + j] + S[m][i][j]) % MOD);\n                        }\n                    }\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        best_op = {m, p, q};\n                    }\n                }\n            }\n        }\n        \n        // If we found a beneficial operation, apply it\n        if (best_gain > 0) {\n            apply(board, best_op);\n            ops.push_back(best_op);\n        } else {\n            break;\n        }\n    }\n\n    // Local Search (Simulated Annealing)\n    mt19937 rng(1337);\n    auto start_time = chrono::steady_clock::now();\n    double time_limit = 1.8; // Seconds\n    long long current_score = calc_score(board);\n    \n    double start_temp = 1e6;\n    double end_temp = 100.0;\n\n    while (true) {\n        auto current_time = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(current_time - start_time).count();\n        if (elapsed > time_limit) break;\n\n        double progress = elapsed / time_limit;\n        double temp = start_temp * pow(end_temp / start_temp, progress);\n\n        int move_type = rng() % 3; // 0: modify, 1: add, 2: remove\n        \n        // Ensure valid move_type\n        if (ops.empty()) move_type = 1; // If empty, must add\n        if (ops.size() == K && move_type == 1) move_type = 0; // If full, can't add\n\n        if (move_type == 0 && !ops.empty()) { // Modify\n            int idx = rng() % ops.size();\n            Op old_op = ops[idx];\n            Op new_op = { (int)(rng() % M), (int)(rng() % (N - 2)), (int)(rng() % (N - 2)) };\n            \n            undo(board, old_op);\n            apply(board, new_op);\n            long long new_score = calc_score(board);\n            \n            double delta = (double)new_score - current_score;\n            if (delta > 0 || exp(delta / temp) > (double)rng() / rng.max()) {\n                current_score = new_score;\n                ops[idx] = new_op;\n            } else {\n                undo(board, new_op);\n                apply(board, old_op);\n            }\n        } else if (move_type == 1 && ops.size() < K) { // Add\n            Op new_op = { (int)(rng() % M), (int)(rng() % (N - 2)), (int)(rng() % (N - 2)) };\n            apply(board, new_op);\n            long long new_score = calc_score(board);\n            \n            double delta = (double)new_score - current_score;\n            if (delta > 0 || exp(delta / temp) > (double)rng() / rng.max()) {\n                current_score = new_score;\n                ops.push_back(new_op);\n            } else {\n                undo(board, new_op);\n            }\n        } else if (move_type == 2 && !ops.empty()) { // Remove\n            int idx = rng() % ops.size();\n            Op old_op = ops[idx];\n            \n            undo(board, old_op);\n            long long new_score = calc_score(board);\n            \n            double delta = (double)new_score - current_score;\n            if (delta > 0 || exp(delta / temp) > (double)rng() / rng.max()) {\n                current_score = new_score;\n                ops.erase(ops.begin() + idx);\n            } else {\n                apply(board, old_op);\n            }\n        }\n    }\n\n    // Output\n    cout << ops.size() << endl;\n    for (const auto& op : ops) {\n        cout << op.m << \" \" << op.p << \" \" << op.q << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cstring>\n\nusing namespace std;\n\nconst int N = 5;\n\nstruct Pos {\n    int r, c;\n    bool operator==(const Pos& other) const { return r == other.r && c == other.c; }\n    bool operator!=(const Pos& other) const { return !(*this == other); }\n};\n\nstruct Crane {\n    int id;\n    Pos pos;\n    int holding;\n    bool is_large;\n    string moves;\n};\n\nint grid[N][N];\nCrane cranes[N];\nint incoming[N][N];\nint incoming_ptr[N];\nint expected_container[N];\n\n// BFS to find the next step for a crane to reach a target\nPos get_next_move(int crane_idx, Pos target) {\n    if (cranes[crane_idx].pos == target) return target;\n\n    queue<pair<Pos, Pos>> q; // {current_pos, parent_pos}\n    q.push({cranes[crane_idx].pos, {-1, -1}});\n\n    Pos parent[N][N];\n    for(int i=0; i<N; ++i) for(int j=0; j<N; ++j) parent[i][j] = {-2, -2};\n    parent[cranes[crane_idx].pos.r][cranes[crane_idx].pos.c] = {-1, -1};\n\n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n\n    bool found = false;\n    Pos last = {-1, -1};\n\n    while (!q.empty()) {\n        Pos curr = q.front().first;\n        q.pop();\n\n        if (curr == target) {\n            found = true;\n            last = curr;\n            break;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && parent[nr][nc].r == -2) {\n                // Check if another crane is already occupying the square\n                bool crane_blocked = false;\n                for (int j = 0; j < N; ++j) {\n                    if (j != crane_idx && cranes[j].pos.r == nr && cranes[j].pos.c == nc) {\n                        crane_blocked = true;\n                        break;\n                    }\n                }\n                if (crane_blocked) continue;\n\n                // Special rule:\n                // Small cranes cannot move to a square with a container IF they are carrying a container\n                // Large cranes can always move to a square with a container\n                if (!cranes[crane_idx].is_large && cranes[crane_idx].holding != -1 && grid[nr][nc] != -1) {\n                    continue; \n                }\n\n                parent[nr][nc] = curr;\n                q.push({{nr, nc}, curr});\n            }\n        }\n        if (found) break;\n    }\n\n    if (!found) return cranes[crane_idx].pos;\n\n    // Backtrack to find the first move from the start\n    Pos curr = last;\n    while (parent[curr.r][curr.c] != cranes[crane_idx].pos) {\n        curr = parent[curr.r][curr.c];\n    }\n    return curr;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n_in;\n    cin >> n_in;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) cin >> incoming[i][j];\n        incoming_ptr[i] = 0;\n        expected_container[i] = N * i;\n    }\n\n    memset(grid, -1, sizeof(grid));\n    for (int i = 0; i < N; ++i) {\n        cranes[i] = {i, {i, 0}, -1, (i == 0), \"\"};\n    }\n\n    for (int turn = 0; turn < 10000; ++turn) {\n        // 1. Receive\n        for (int i = 0; i < N; ++i) {\n            if (incoming_ptr[i] < N && grid[i][0] == -1) {\n                bool crane_at_gate = false;\n                for(int k=0; k<N; ++k) if(cranes[k].pos.r == i && cranes[k].pos.c == 0) crane_at_gate = true;\n                if (!crane_at_gate) {\n                    grid[i][0] = incoming[i][incoming_ptr[i]++];\n                }\n            }\n        }\n\n        // 2. Action planning\n        vector<char> turn_actions(N, '.');\n        vector<Pos> next_positions(N);\n        for(int i=0; i<N; ++i) next_positions[i] = cranes[i].pos;\n\n        for (int i = 0; i < N; ++i) {\n            Crane &c = cranes[i];\n            \n            if (c.holding != -1) {\n                int target_row = c.holding / N;\n                Pos target = {target_row, N - 1};\n                \n                if (c.pos == target) {\n                    turn_actions[i] = 'Q';\n                } else {\n                    Pos next = get_next_move(i, target);\n                    if (next != c.pos) {\n                        next_positions[i] = next;\n                        turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                    } else turn_actions[i] = '.';\n                }\n            } else {\n                Pos target = {-1, -1};\n                \n                // Priority 1: Clear wrong container at dispatch gate\n                for (int r = 0; r < N; ++r) {\n                    if (grid[r][N-1] != -1 && grid[r][N-1] != expected_container[r]) {\n                        target = {r, N-1};\n                        break;\n                    }\n                }\n                \n                // Priority 2: Pick up expected container for this crane's row (or any expected container for the large crane)\n                if (target.r == -1) {\n                    for (int r = 0; r < N; ++r) {\n                        for (int col = 0; col < N; ++col) {\n                            if (grid[r][col] == expected_container[r]) {\n                                // Large crane handles any, small crane only handles its own row\n                                if (i == 0 || r == i) {\n                                    target = {r, col};\n                                    goto found;\n                                }\n                            }\n                        }\n                    }\n                }\n                found:;\n                \n                // Priority 3: Move to home position\n                if (target.r == -1) {\n                    target = {i, 1};\n                }\n\n                if (c.pos == target) {\n                    // If we are at target and there is a container, P it\n                    if (grid[target.r][target.c] != -1) {\n                        turn_actions[i] = 'P';\n                    } else {\n                        turn_actions[i] = '.';\n                    }\n                } else {\n                    Pos next = get_next_move(i, target);\n                    if (next != c.pos) {\n                        next_positions[i] = next;\n                        turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                    } else turn_actions[i] = '.';\n                }\n            }\n        }\n\n        // Conflict Resolution\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (turn_actions[i] != '.' && turn_actions[j] != '.' && \n                    turn_actions[i] != 'P' && turn_actions[j] != 'P' &&\n                    turn_actions[i] != 'Q' && turn_actions[j] != 'Q' &&\n                    next_positions[i] == next_positions[j]) {\n                    turn_actions[j] = '.';\n                    next_positions[j] = cranes[j].pos;\n                }\n            }\n        }\n\n        // Apply actions\n        for (int i = 0; i < N; ++i) {\n            char a = turn_actions[i];\n            cranes[i].moves += a;\n            if (a == 'P') {\n                cranes[i].holding = grid[cranes[i].pos.r][cranes[i].pos.c];\n                grid[cranes[i].pos.r][cranes[i].pos.c] = -1;\n            } else if (a == 'Q') {\n                grid[cranes[i].pos.r][cranes[i].pos.c] = cranes[i].holding;\n                cranes[i].holding = -1;\n            } else if (a != '.' && a != 'B') {\n                cranes[i].pos = next_positions[i];\n            }\n        }\n\n        // Dispatch\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][N-1] == expected_container[i]) {\n                grid[i][N-1] = -1;\n                expected_container[i]++;\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) cout << cranes[i].moves << \"\\n\";\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 20;\nint H[N][N];\nint curr_r = 0, curr_c = 0;\nint current_load = 0;\n\nstruct Pos {\n    int r, c;\n};\n\n// Function to find the nearest cell with a certain property\n// want_surplus: true if we look for surplus (H > 0), false if deficit (H < 0)\nPos find_nearest(bool want_surplus) {\n    queue<pair<int, int>> q;\n    q.push({curr_r, curr_c});\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    \n    // Check if current cell satisfies the condition\n    if (want_surplus) {\n        if (H[curr_r][curr_c] > 0) return {curr_r, curr_c};\n    } else {\n        if (H[curr_r][curr_c] < 0) return {curr_r, curr_c};\n    }\n    visited[curr_r][curr_c] = true;\n\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n\n        int dr[] = {-1, 1, 0, 0};\n        int dc[] = {0, 0, -1, 1};\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i], nc = c + dc[i];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && !visited[nr][nc]) {\n                if (want_surplus) {\n                    if (H[nr][nc] > 0) return {nr, nc};\n                } else {\n                    if (H[nr][nc] < 0) return {nr, nc};\n                }\n                visited[nr][nc] = true;\n                q.push({nr, nc});\n            }\n        }\n    }\n    return {-1, -1};\n}\n\n// Get shortest path from curr to target\nvector<Pos> get_path(Pos target) {\n    queue<pair<int, int>> q;\n    q.push({curr_r, curr_c});\n    vector<vector<Pos>> parent(N, vector<Pos>(N, {-1, -1}));\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    visited[curr_r][curr_c] = true;\n\n    bool found = false;\n    while (!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n        if (r == target.r && c == target.c) {\n            found = true;\n            break;\n        }\n\n        int dr[] = {-1, 1, 0, 0};\n        int dc[] = {0, 0, -1, 1};\n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i], nc = c + dc[i];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && !visited[nr][nc]) {\n                visited[nr][nc] = true;\n                parent[nr][nc] = {r, c};\n                q.push({nr, nc});\n            }\n        }\n    }\n\n    vector<Pos> path;\n    if (found) {\n        Pos p = target;\n        while (p.r != curr_r || p.c != curr_c) {\n            path.push_back(p);\n            p = parent[p.r][p.c];\n        }\n        reverse(path.begin(), path.end());\n    }\n    return path;\n}\n\nvoid move_to(int nr, int nc) {\n    if (nr == curr_r - 1) cout << \"U\" << endl;\n    else if (nr == curr_r + 1) cout << \"D\" << endl;\n    else if (nc == curr_c - 1) cout << \"L\" << endl;\n    else if (nc == curr_c + 1) cout << \"R\" << endl;\n    curr_r = nr;\n    curr_c = nc;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n;\n    cin >> n;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> H[i][j];\n        }\n    }\n\n    while (true) {\n        Pos target;\n        // Search for nearest relevant cell\n        if (current_load == 0) {\n            target = find_nearest(true);\n        } else {\n            target = find_nearest(false);\n        }\n\n        if (target.r == -1) break; // All heights are 0\n\n        vector<Pos> path = get_path(target);\n        for (Pos p : path) {\n            move_to(p.r, p.c);\n            // Process the cell we just moved to\n            if (H[p.r][p.c] > 0) {\n                int d = H[p.r][p.c];\n                cout << \"+\" << d << endl;\n                current_load += d;\n                H[p.r][p.c] = 0;\n            } else if (H[p.r][p.c] < 0 && current_load > 0) {\n                int d = min(current_load, -H[p.r][p.c]);\n                cout << \"-\" << d << endl;\n                current_load -= d;\n                H[p.r][p.c] += d;\n            }\n        }\n\n        // If path was empty, target is the current cell\n        if (path.empty()) {\n            if (H[target.r][target.c] > 0) {\n                int d = H[target.r][target.c];\n                cout << \"+\" << d << endl;\n                current_load += d;\n                H[target.r][target.c] = 0;\n            } else if (H[target.r][target.c] < 0 && current_load > 0) {\n                int d = min(current_load, -H[target.r][target.c]);\n                cout << \"-\" << d << endl;\n                current_load -= d;\n                H[target.r][target.c] += d;\n            }\n        }\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\n// Potential of a pair (A, B) is sum(max(A_l, B_l)) for all criteria l.\n// This is a heuristic for the potential of a pair to produce high-value offspring.\ninline long long calculate_edge_cost(const vector<int>& s1, const vector<int>& s2, int M) {\n    long long cost = 0;\n    for (int l = 0; l < M; ++l) {\n        cost += max(s1[l], s2[l]);\n    }\n    return cost;\n}\n\nint main() {\n    // Optimize I/O operations\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seed_count = 2 * N * (N - 1); // 60\n    int grid_size = N * N; // 36\n    vector<vector<int>> seeds(seed_count, vector<int>(M));\n\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i][j];\n        }\n    }\n\n    // Precompute neighbors for each grid position\n    vector<vector<int>> neighbors(grid_size);\n    for (int i = 0; i < grid_size; ++i) {\n        int r = i / N;\n        int c = i % N;\n        if (r > 0) neighbors[i].push_back((r - 1) * N + c);\n        if (r < N - 1) neighbors[i].push_back((r + 1) * N + c);\n        if (c > 0) neighbors[i].push_back(r * N + c - 1);\n        if (c < N - 1) neighbors[i].push_back(r * N + c + 1);\n    }\n\n    mt19937 rng(1337); \n\n    vector<int> grid_indices(grid_size);\n    vector<int> unused_indices(seed_count - grid_size);\n    vector<bool> is_on_grid(seed_count, false);\n\n    for (int t = 0; t < T; t++) {\n        // Selection: Top 30 + 6 random seeds as a starting point\n        vector<pair<long long, int>> seed_scores(seed_count);\n        for (int i = 0; i < seed_count; ++i) {\n            long long val = 0;\n            for (int l = 0; l < M; ++l) val += seeds[i][l];\n            seed_scores[i] = {val, i};\n        }\n        sort(seed_scores.rbegin(), seed_scores.rend());\n\n        fill(is_on_grid.begin(), is_on_grid.end(), false);\n        for (int i = 0; i < 30; ++i) {\n            grid_indices[i] = seed_scores[i].second;\n            is_on_grid[grid_indices[i]] = true;\n        }\n        vector<int> remaining;\n        for (int i = 30; i < seed_count; ++i) remaining.push_back(seed_scores[i].second);\n        shuffle(remaining.begin(), remaining.end(), rng);\n        for (int i = 0; i < 6; ++i) {\n            grid_indices[30 + i] = remaining[i];\n            is_on_grid[remaining[i]] = true;\n        }\n        \n        int u_idx = 0;\n        for (int i = 0; i < seed_count; ++i) {\n            if (!is_on_grid[i]) {\n                unused_indices[u_idx++] = i;\n            }\n        }\n\n        // Simulated Annealing optimizing BOTH arrangement and selection\n        long long current_total_cost = 0;\n        for (int i = 0; i < grid_size; ++i) {\n            for (int neighbor : neighbors[i]) {\n                if (i < neighbor) {\n                    current_total_cost += calculate_edge_cost(seeds[grid_indices[i]], seeds[grid_indices[neighbor]], M);\n                }\n            }\n        }\n\n        double temp = 500.0;\n        double cooling = 0.99995;\n        int iterations = 400000;\n\n        for (int iter = 0; iter < iterations; ++iter) {\n            int type = (uniform_int_distribution<int>(0, 1)(rng));\n            int p1 = uniform_int_distribution<int>(0, grid_size - 1)(rng);\n            int p2;\n            bool is_grid_grid = false;\n\n            if (type == 0) { // Swap grid-grid (rearrangement)\n                p2 = uniform_int_distribution<int>(0, grid_size - 1)(rng);\n                if (p1 == p2) continue;\n                is_grid_grid = true;\n            } else { // Swap grid-unused (selection optimization)\n                p2 = uniform_int_distribution<int>(0, unused_indices.size() - 1)(rng);\n                is_grid_grid = false;\n            }\n\n            // Incremental cost update\n            vector<pair<int, int>> all_edges;\n            auto add_edges = [&](int p) {\n                for (int n : neighbors[p]) {\n                    all_edges.push_back({min(p, n), max(p, n)});\n                }\n            };\n            \n            add_edges(p1);\n            if (is_grid_grid) add_edges(p2);\n            sort(all_edges.begin(), all_edges.end());\n            all_edges.erase(unique(all_edges.begin(), all_edges.end()), all_edges.end());\n\n            long long old_partial_cost = 0;\n            for (auto& edge : all_edges) {\n                old_partial_cost += calculate_edge_cost(seeds[grid_indices[edge.first]], seeds[grid_indices[edge.second]], M);\n            }\n\n            int seed1 = grid_indices[p1];\n            int seed2;\n            if (is_grid_grid) {\n                seed2 = grid_indices[p2];\n                swap(grid_indices[p1], grid_indices[p2]);\n            } else {\n                seed2 = unused_indices[p2];\n                grid_indices[p1] = seed2;\n                unused_indices[p2] = seed1;\n            }\n\n            long long new_partial_cost = 0;\n            for (auto& edge : all_edges) {\n                new_partial_cost += calculate_edge_cost(seeds[grid_indices[edge.first]], seeds[grid_indices[edge.second]], M);\n            }\n\n            long long delta = new_partial_cost - old_partial_cost;\n            if (delta > 0 || exp(delta / temp) > uniform_real_distribution<double>(0, 1)(rng)) {\n                current_total_cost += delta;\n            } else {\n                // Revert\n                if (is_grid_grid) {\n                    swap(grid_indices[p1], grid_indices[p2]);\n                } else {\n                    grid_indices[p1] = seed1;\n                    unused_indices[p2] = seed2;\n                }\n            }\n            temp *= cooling;\n        }\n\n        // Output the grid arrangement\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << grid_indices[i * N + j];\n                if (j < N - 1) cout << \" \";\n            }\n            cout << \"\\n\";\n        }\n        cout.flush();\n\n        // Read the new generation of seeds\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> seeds[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Coordinate structure\nstruct Point {\n    int x, y;\n};\n\n// Robot vertex structure\nstruct Vertex {\n    int id;\n    int parent;\n    int L;\n    int dir; // 0=R, 1=D, 2=L, 3=U\n    bool holding;\n    Point target;\n};\n\nint N, M, V_avail;\nvector<vector<int>> s, t; // s=takoyaki (1 present), t=target (1 present)\nint rx, ry;\nvector<Vertex> robot;\n\n// Directions: R, D, L, U (0, 1, 2, 3)\nint DX[] = {0, 1, 0, -1};\nint DY[] = {1, 0, -1, 0};\nchar DIRS[] = {'R', 'D', 'L', 'U'};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M >> V_avail)) return 0;\n    s.resize(N, vector<int>(N));\n    t.resize(N, vector<int>(N));\n    \n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) s[i][j] = row[j] - '0';\n    }\n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) t[i][j] = row[j] - '0';\n    }\n\n    // Design robot: star graph with varying edge lengths\n    int V_prime = V_avail;\n    robot.resize(V_prime);\n    robot[0] = {0, -1, 0, 0, false, {-1, -1}};\n    for (int i = 1; i < V_prime; ++i) {\n        // Distribute edge lengths more diversely to cover the grid\n        int len = (i - 1) % min(N - 1, 7) + 1;\n        robot[i] = {i, 0, len, 0, false, {-1, -1}};\n    }\n\n    cout << V_prime << endl;\n    for (int i = 1; i < V_prime; ++i) {\n        cout << robot[i].parent << \" \" << robot[i].L << endl;\n    }\n    rx = N / 2;\n    ry = N / 2;\n    cout << rx << \" \" << ry << endl;\n\n    // Simulation\n    for (int turn = 0; turn < 100000; ++turn) {\n        // 1. Identify/Update targets\n        int current_m = 0;\n        vector<Point> takoyaki_squares;\n        vector<Point> target_squares;\n        for(int i=0; i<N; ++i) {\n            for(int j=0; j<N; ++j) {\n                if (s[i][j] && t[i][j]) current_m++;\n                if (s[i][j] && !t[i][j]) takoyaki_squares.push_back({i, j});\n                if (t[i][j] && !s[i][j]) target_squares.push_back({i, j});\n            }\n        }\n        if (current_m == M) break;\n\n        for (int i = 1; i < V_prime; ++i) {\n            if (robot[i].target.x >= 0) {\n                bool valid = false;\n                if (robot[i].holding) {\n                    if (t[robot[i].target.x][robot[i].target.y] == 1 && s[robot[i].target.x][robot[i].target.y] == 0) valid = true;\n                } else {\n                    if (s[robot[i].target.x][robot[i].target.y] == 1 && t[robot[i].target.x][robot[i].target.y] == 0) valid = true;\n                }\n                if (!valid) robot[i].target = {-1, -1};\n            }\n\n            if (robot[i].target.x == -1) {\n                int min_dist = 1e9;\n                Point best_p = {-1, -1};\n                if (robot[i].holding) {\n                    for (auto& p : target_squares) {\n                        int dist = abs(p.x - rx) + abs(p.y - ry);\n                        if (dist < min_dist) { min_dist = dist; best_p = p; }\n                    }\n                } else {\n                    for (auto& p : takoyaki_squares) {\n                        int dist = abs(p.x - rx) + abs(p.y - ry);\n                        if (dist < min_dist) { min_dist = dist; best_p = p; }\n                    }\n                }\n                robot[i].target = best_p;\n            }\n        }\n\n        // 2. Choose best root move and rotations\n        int best_move = 4; // Stay\n        double min_cost = 1e18;\n        vector<int> best_rots(V_prime, 0);\n\n        int move_dx[] = {-1, 1, 0, 0, 0}; // U, D, L, R, .\n        int move_dy[] = {0, 0, -1, 1, 0};\n        char move_char[] = {'U', 'D', 'L', 'R', '.'};\n\n        for (int m = 0; m < 5; ++m) {\n            int nrx = rx + move_dx[m];\n            int nry = ry + move_dy[m];\n            if (nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n\n            double cost = 0;\n            vector<int> current_rots(V_prime, 0);\n\n            for (int i = 1; i < V_prime; ++i) {\n                double best_d = 1e9;\n                int best_r = 0;\n                \n                for (int r = 0; r < 3; ++r) {\n                    int ndir = robot[i].dir;\n                    if (r == 1) ndir = (ndir + 3) % 4;\n                    else if (r == 2) ndir = (ndir + 1) % 4;\n                    int fx = nrx + DX[ndir] * robot[i].L;\n                    int fy = nry + DY[ndir] * robot[i].L;\n                    \n                    double d;\n                    if (robot[i].target.x >= 0) {\n                        d = abs(fx - robot[i].target.x) + abs(fy - robot[i].target.y);\n                        // Heuristic: If holding, prioritize dropping.\n                        if (robot[i].holding) d *= 1.5; \n                    } else {\n                        // Heuristic: Move to center if idle (resting position)\n                        d = abs(fx - N/2) + abs(fy - N/2);\n                        d *= 0.1; // Lower priority than active tasks\n                    }\n                    if (d < best_d) { best_d = d; best_r = r; }\n                }\n                cost += best_d;\n                current_rots[i] = best_r;\n            }\n            if (cost < min_cost) {\n                min_cost = cost;\n                best_move = m;\n                best_rots = current_rots;\n            }\n        }\n\n        // Apply best move\n        rx += move_dx[best_move];\n        ry += move_dy[best_move];\n        \n        string S = \"\";\n        S += move_char[best_move];\n        for (int i = 1; i < V_prime; ++i) {\n            if (best_rots[i] == 1) { S += 'L'; robot[i].dir = (robot[i].dir + 3) % 4; }\n            else if (best_rots[i] == 2) { S += 'R'; robot[i].dir = (robot[i].dir + 1) % 4; }\n            else S += '.';\n        }\n\n        // 3. Actions\n        string actions = \".\";\n        for (int i = 1; i < V_prime; ++i) {\n            int fx = rx + DX[robot[i].dir] * robot[i].L;\n            int fy = ry + DY[robot[i].dir] * robot[i].L;\n            bool action = false;\n            if (fx >= 0 && fx < N && fy >= 0 && fy < N) {\n                if (robot[i].holding) {\n                    if (t[fx][fy] == 1 && s[fx][fy] == 0) {\n                        robot[i].holding = false;\n                        s[fx][fy] = 1;\n                        action = true;\n                    }\n                } else {\n                    if (s[fx][fy] == 1 && t[fx][fy] == 0) {\n                        robot[i].holding = true;\n                        s[fx][fy] = 0;\n                        action = true;\n                    }\n                }\n            }\n            actions += (action ? 'P' : '.');\n        }\n        cout << S << actions << endl;\n    }\n\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\n// Using a 128x128 grid for a good balance between resolution and speed.\n// 128^3 = 2,097,152 operations per test case. \n// Total operations for 150 cases ~315M, well within the 2.0s limit.\nconst int GRID_SIZE = 128;\nconst int MAX_COORD = 100000;\n\nvoid solve() {\n    int N;\n    if (!(cin >> N)) return;\n\n    // grid stores the net catch (mackerel - sardine) for each cell\n    vector<vector<int>> grid(GRID_SIZE, vector<int>(GRID_SIZE, 0));\n    \n    // Read Mackerels and populate grid\n    for (int i = 0; i < N; ++i) {\n        int x, y; cin >> x >> y;\n        int gx = min(x * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1);\n        int gy = min(y * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1);\n        grid[gx][gy]++;\n    }\n    // Read Sardines and populate grid\n    for (int i = 0; i < N; ++i) {\n        int x, y; cin >> x >> y;\n        int gx = min(x * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1);\n        int gy = min(y * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1);\n        grid[gx][gy]--;\n    }\n\n    // 2D Kadane's Algorithm to find the max weight sub-rectangle\n    // This finds the sub-rectangle [best_i1, best_i2] x [best_j1, best_j2] \n    // that maximizes the sum of (mackerels - sardines).\n    int max_sum = 0;\n    int best_i1 = 0, best_j1 = 0, best_i2 = 0, best_j2 = 0;\n\n    for (int i1 = 0; i1 < GRID_SIZE; ++i1) {\n        vector<int> col_sum(GRID_SIZE, 0);\n        for (int i2 = i1; i2 < GRID_SIZE; ++i2) {\n            // Update column sums\n            for (int j = 0; j < GRID_SIZE; ++j) col_sum[j] += grid[i2][j];\n            \n            // 1D Kadane's on col_sum\n            int current_sum = 0, start_j = 0;\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                current_sum += col_sum[j];\n                \n                // Update max if we find a better region\n                if (current_sum > max_sum) {\n                    max_sum = current_sum;\n                    best_i1 = i1; best_i2 = i2;\n                    best_j1 = start_j; best_j2 = j;\n                }\n                \n                // Reset if sum goes negative\n                if (current_sum < 0) {\n                    current_sum = 0;\n                    start_j = j + 1;\n                }\n            }\n        }\n    }\n\n    // Output result\n    if (max_sum <= 0) {\n        // If no region has a positive score, output a tiny 1x1 polygon\n        cout << 4 << endl;\n        cout << \"0 0\" << endl << \"1 0\" << endl << \"1 1\" << endl << \"0 1\" << endl;\n    } else {\n        // Convert grid indices back to coordinate range [0, 100000]\n        double step = (double)(MAX_COORD + 1) / GRID_SIZE;\n        int x1 = (int)(best_i1 * step);\n        int y1 = (int)(best_j1 * step);\n        int x2 = (int)((best_i2 + 1) * step);\n        int y2 = (int)((best_j2 + 1) * step);\n        \n        // Ensure constraints [0, 100000]\n        x1 = max(0, min(MAX_COORD, x1));\n        y1 = max(0, min(MAX_COORD, y1));\n        x2 = max(0, min(MAX_COORD, x2));\n        y2 = max(0, min(MAX_COORD, y2));\n        \n        // Output rectangle (a valid orthogonal polygon with 4 vertices)\n        cout << 4 << endl;\n        cout << x1 << \" \" << y1 << endl;\n        cout << x2 << \" \" << y1 << endl;\n        cout << x2 << \" \" << y2 << endl;\n        cout << x1 << \" \" << y2 << endl;\n    }\n}\n\nint main() {\n    // Fast I/O is crucial for 150 test cases\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\n// Configuration for a single rectangle's placement\nstruct Placement {\n    int id;\n    int r;           // Rotation (0 or 1)\n    char d;          // Direction ('U' or 'L')\n    int b;           // Reference rectangle index (-1 for origin)\n    bool included;   // Whether it's included in the packing\n};\n\n// Global variables\nint N, T;\ndouble sigma;\nlong long W_obs_all[105], H_obs_all[105];\n\n// Rectangles data for simulation\nstruct Rect {\n    long long x, y, w, h;\n};\nRect placed_rects[105];\n\n// Efficient simulation using static arrays\nlong long simulate(const vector<Placement>& config, long long& W, long long& H) {\n    W = 0;\n    H = 0;\n    long long current_cost = 0;\n\n    for (int i = 0; i < N; ++i) {\n        if (!config[i].included) {\n            current_cost += (W_obs_all[i] + H_obs_all[i]);\n            continue;\n        }\n\n        int idx = config[i].id;\n        long long cur_w = (config[i].r == 0) ? W_obs_all[idx] : H_obs_all[idx];\n        long long cur_h = (config[i].r == 0) ? H_obs_all[idx] : W_obs_all[idx];\n\n        long long x, y;\n        int ref = config[i].b;\n        // If reference is not included, treat it as -1 (origin)\n        if (ref != -1 && !config[ref].included) ref = -1;\n\n        if (config[i].d == 'U') {\n            x = (ref == -1) ? 0 : (placed_rects[ref].x + placed_rects[ref].w);\n            y = 0;\n            for (int j = 0; j < i; ++j) {\n                if (config[j].included) {\n                    const Rect& r = placed_rects[config[j].id];\n                    // Overlap check in X: [x, x+cur_w) overlaps [r.x, r.x+r.w)\n                    if (x < r.x + r.w && x + cur_w > r.x) {\n                        if (r.y + r.h > y) y = r.y + r.h;\n                    }\n                }\n            }\n        } else {\n            y = (ref == -1) ? 0 : (placed_rects[ref].y + placed_rects[ref].h);\n            x = 0;\n            for (int j = 0; j < i; ++j) {\n                if (config[j].included) {\n                    const Rect& r = placed_rects[config[j].id];\n                    // Overlap check in Y: [y, y+cur_h) overlaps [r.y, r.y+r.h)\n                    if (y < r.y + r.h && y + cur_h > r.y) {\n                        if (r.x + r.w > x) x = r.x + r.w;\n                    }\n                }\n            }\n        }\n        \n        placed_rects[idx] = {x, y, cur_w, cur_h};\n        if (x + cur_w > W) W = x + cur_w;\n        if (y + cur_h > H) H = y + cur_h;\n    }\n    return W + H + current_cost;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> T >> sigma)) return 0;\n    for (int i = 0; i < N; ++i) cin >> W_obs_all[i] >> H_obs_all[i];\n\n    mt19937 rng(12345);\n    vector<Placement> best_config(N);\n    for (int i = 0; i < N; ++i) best_config[i] = {i, 0, 'U', -1, true};\n\n    long long W, H;\n    long long best_sim_score = simulate(best_config, W, H);\n\n    for (int t = 0; t < T; ++t) {\n        vector<Placement> current_config = best_config;\n        \n        // Fixed iteration count ensures we stay under time limit\n        const int iterations = 250; \n        for (int iter = 0; iter < iterations; ++iter) {\n            int idx = rng() % N;\n            Placement old = current_config[idx];\n            \n            int mutation = rng() % 4;\n            if (mutation == 0) current_config[idx].r = 1 - current_config[idx].r;\n            else if (mutation == 1) current_config[idx].d = (current_config[idx].d == 'U' ? 'L' : 'U');\n            else if (mutation == 2) {\n                if (rng() % 3 == 0) current_config[idx].b = -1;\n                else if (idx > 0) current_config[idx].b = rng() % idx;\n            }\n            else current_config[idx].included = !current_config[idx].included;\n\n            long long new_W, new_H;\n            long long new_score = simulate(current_config, new_W, new_H);\n            \n            if (new_score < best_sim_score) {\n                best_sim_score = new_score;\n                best_config = current_config;\n            } else {\n                current_config[idx] = old; // Backtrack\n            }\n        }\n\n        // Output current best\n        int count = 0;\n        for (const auto& p : best_config) if (p.included) count++;\n        \n        cout << count << endl;\n        for (const auto& p : best_config) {\n            if (p.included)\n                cout << p.id << \" \" << p.r << \" \" << p.d << \" \" << p.b << endl;\n        }\n        cout.flush();\n\n        long long W_obs, H_obs;\n        if (!(cin >> W_obs >> H_obs)) break;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <ctime>\n#include <chrono>\n\nusing namespace std;\n\n// Struct to represent an edge in the priority queue\nstruct Item {\n    int priority;\n    int u; // parent node\n    int v; // child node\n    bool operator<(const Item& other) const {\n        return priority < other.priority;\n    }\n};\n\nvoid solve() {\n    int N, M, H;\n    if (!(cin >> N >> M >> H)) return;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    // Skip coordinates as they are not used in the greedy logic\n    int x, y;\n    for (int i = 0; i < N; ++i) cin >> x >> y;\n\n    vector<int> best_p(N, -1);\n    long long best_score = -1;\n\n    // Time limit handling\n    clock_t start_time = clock();\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist(80, 120);\n    \n    // For root selection order\n    vector<int> nodes(N);\n    for(int i=0; i<N; ++i) nodes[i] = i;\n\n    int iter = 0;\n    while (true) {\n        // Periodically check time\n        if (iter % 10 == 0) {\n            if ((double)(clock() - start_time) / CLOCKS_PER_SEC > 1.8) break;\n        }\n        iter++;\n        \n        vector<int> p(N, -1);\n        vector<int> depth(N, 0);\n        vector<bool> visited(N, false);\n        \n        // Root selection heuristic to explore different configurations\n        if (iter % 3 == 0) {\n            sort(nodes.begin(), nodes.end(), [&](int a, int b){ return A[a] < A[b]; });\n        } else if (iter % 3 == 1) {\n            sort(nodes.begin(), nodes.end(), [&](int a, int b){ return A[a] > A[b]; });\n        } else {\n            shuffle(nodes.begin(), nodes.end(), rng);\n        }\n        \n        priority_queue<Item> pq;\n        int unvisited_count = N;\n        int order_idx = 0;\n        \n        // Build the forest\n        while (unvisited_count > 0) {\n            // Find next unvisited node to be a potential root\n            while (order_idx < N && visited[nodes[order_idx]]) {\n                order_idx++;\n            }\n            \n            if (pq.empty()) {\n                if (order_idx < N) {\n                    int r = nodes[order_idx];\n                    visited[r] = true;\n                    p[r] = -1;\n                    depth[r] = 0;\n                    unvisited_count--;\n                    \n                    // Add neighbors to PQ\n                    for (int neighbor : adj[r]) {\n                        if (!visited[neighbor]) {\n                            int gain = (depth[r] + 2) * A[neighbor];\n                            int randomized_gain = gain * dist(rng) / 100;\n                            pq.push({randomized_gain, r, neighbor});\n                        }\n                    }\n                }\n            } else {\n                Item top = pq.top();\n                pq.pop();\n                \n                if (visited[top.v]) continue;\n                // Constraint check: must not exceed depth H\n                if (depth[top.u] >= H) continue;\n                \n                visited[top.v] = true;\n                p[top.v] = top.u;\n                depth[top.v] = depth[top.u] + 1;\n                unvisited_count--;\n                \n                // Add neighbors to PQ\n                for (int neighbor : adj[top.v]) {\n                    if (!visited[neighbor]) {\n                        int gain = (depth[top.v] + 2) * A[neighbor];\n                        int randomized_gain = gain * dist(rng) / 100;\n                        pq.push({randomized_gain, top.v, neighbor});\n                    }\n                }\n            }\n        }\n        \n        // Calculate score\n        long long current_score = 0;\n        for (int j = 0; j < N; ++j) {\n            current_score += (long long)(depth[j] + 1) * A[j];\n        }\n        \n        // Keep the best solution\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_p = p;\n        }\n    }\n    \n    // Output final solution\n    for (int i = 0; i < N; ++i) {\n        cout << best_p[i] << (i == N - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    solve();\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n// Global variables\nint N;\nchar board[20][20];\n// Pre-calculate safety using prefix sums\n// row_fuku[r][c] = number of Fukunokami in row r in columns 0 to c-1\nint row_fuku[20][21]; \nint col_fuku[20][21]; \n\n// Update prefix sums after a board change\nvoid update_fuku_prefix() {\n    for (int i = 0; i < N; ++i) {\n        row_fuku[i][0] = 0;\n        for (int j = 0; j < N; ++j) {\n            row_fuku[i][j+1] = row_fuku[i][j] + (board[i][j] == 'o' ? 1 : 0);\n        }\n    }\n    for (int j = 0; j < N; ++j) {\n        col_fuku[j][0] = 0;\n        for (int i = 0; i < N; ++i) {\n            col_fuku[j][i+1] = col_fuku[j][i] + (board[i][j] == 'o' ? 1 : 0);\n        }\n    }\n}\n\n// O(1) safety check using prefix sums\nbool is_safe_fast(int r, int c, char dir) {\n    if (dir == 'U') {\n        // No Fukunokami in col c, rows 0 to r-1\n        return (col_fuku[c][r] - col_fuku[c][0]) == 0;\n    } else if (dir == 'D') {\n        // No Fukunokami in col c, rows r+1 to N-1\n        return (col_fuku[c][N] - col_fuku[c][r+1]) == 0;\n    } else if (dir == 'L') {\n        // No Fukunokami in row r, cols 0 to c-1\n        return (row_fuku[r][c] - row_fuku[r][0]) == 0;\n    } else if (dir == 'R') {\n        // No Fukunokami in row r, cols c+1 to N-1\n        return (row_fuku[r][N] - row_fuku[r][c+1]) == 0;\n    }\n    return true;\n}\n\n// Perform the shift\nvoid apply_move(char dir, int p) {\n    if (dir == 'U') {\n        for (int i = 0; i < N - 1; ++i) board[i][p] = board[i+1][p];\n        board[N-1][p] = '.';\n    } else if (dir == 'D') {\n        for (int i = N - 1; i > 0; --i) board[i][p] = board[i-1][p];\n        board[0][p] = '.';\n    } else if (dir == 'L') {\n        for (int j = 0; j < N - 1; ++j) board[p][j] = board[p][j+1];\n        board[p][N-1] = '.';\n    } else if (dir == 'R') {\n        for (int j = N - 1; j > 0; --j) board[p][j] = board[p][j-1];\n        board[p][0] = '.';\n    }\n    update_fuku_prefix();\n}\n\nstruct Move {\n    char dir;\n    int p;\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N)) return 0;\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) board[i][j] = row[j];\n    }\n    update_fuku_prefix();\n\n    vector<Move> ans;\n    // Iterate up to the max possible moves 4N^2\n    for (int iter = 0; iter < 4 * N * N; ++iter) {\n        int best_r = -1, best_c = -1;\n        char best_dir = ' ';\n        int best_score = -1;\n        bool oni_found = false;\n\n        // Greedy search: find the best safe move\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (board[r][c] == 'x') {\n                    oni_found = true;\n                    char dirs[] = {'U', 'D', 'L', 'R'};\n                    for (char d : dirs) {\n                        if (is_safe_fast(r, c, d)) {\n                            // Check if this move removes the Oni immediately\n                            bool immediate = false;\n                            if (d == 'U' && r == 0) immediate = true;\n                            else if (d == 'D' && r == N - 1) immediate = true;\n                            else if (d == 'L' && c == 0) immediate = true;\n                            else if (d == 'R' && c == N - 1) immediate = true;\n\n                            // Score: Priority to immediate removals\n                            int score = immediate ? 2 : 1;\n                            if (score > best_score) {\n                                best_score = score;\n                                best_dir = d;\n                                best_r = r;\n                                best_c = c;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        if (!oni_found) break; // All Oni removed\n        if (best_dir == ' ') break; // Should not happen based on problem constraints\n\n        int p = (best_dir == 'U' || best_dir == 'D') ? best_c : best_r;\n        apply_move(best_dir, p);\n        ans.push_back({best_dir, p});\n    }\n\n    for (const auto& m : ans) {\n        cout << m.dir << \" \" << m.p << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\n// Problem constants\nconst int MAX_N = 100;\nint N, L;\nint T[MAX_N];\nint a[MAX_N], b[MAX_N];\nint counts[MAX_N];\n\n// Fast simulation function\n// Returns the L1 error of the cleaning plan\ninline long long calculate_error(const int* a_ptr, const int* b_ptr) {\n    // Reset counts using memset for performance\n    memset(counts, 0, sizeof(int) * N);\n    \n    int current = 0;\n    counts[0] = 1;\n    \n    // Simulate L weeks\n    for (int i = 1; i < L; ++i) {\n        // parity: counts[current] % 2\n        // If parity is odd, use a[current], otherwise use b[current]\n        int next = (counts[current] & 1) ? a_ptr[current] : b_ptr[current];\n        current = next;\n        counts[current]++;\n    }\n    \n    // Calculate L1 error\n    long long error = 0;\n    for (int i = 0; i < N; ++i) {\n        error += abs(counts[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    // Read Input\n    if (!(cin >> N >> L)) return 0;\n    for (int i = 0; i < N; ++i) cin >> T[i];\n    \n    // Random number generator\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    // Initial state: random assignment\n    for (int i = 0; i < N; ++i) {\n        a[i] = rng() % N;\n        b[i] = rng() % N;\n    }\n    \n    long long current_error = calculate_error(a, b);\n    \n    // Keep track of the best solution found\n    long long best_error = current_error;\n    int best_a[MAX_N], best_b[MAX_N];\n    memcpy(best_a, a, sizeof(int) * N);\n    memcpy(best_b, b, sizeof(int) * N);\n    \n    auto start_time = chrono::steady_clock::now();\n    \n    // Simulated Annealing parameters\n    double initial_temp = 2000.0;\n    double final_temp = 0.5;\n    const int MAX_ITER = 300000;\n    \n    for (int iter = 0; iter < MAX_ITER; ++iter) {\n        // Check time every 64 iterations\n        if ((iter & 63) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1850) {\n                break;\n            }\n        }\n        \n        // Tournament selection for choosing the node i to modify\n        int i = rng() % N;\n        for(int k = 0; k < 4; ++k) {\n            int cand = rng() % N;\n            if (abs(counts[cand] - T[cand]) > abs(counts[i] - T[i])) {\n                i = cand;\n            }\n        }\n        \n        // Pick which transition to modify\n        bool is_a = (rng() & 1);\n        int old_val = is_a ? a[i] : b[i];\n        \n        // Biased choice for new_val\n        int new_val;\n        // 70% of the time, try to pick a node that needs more visits\n        if (rng() % 10 < 7) { \n            int target_i = rng() % N;\n            long long max_under_visited = -2000000; // Look for under-visited node\n            for(int k = 0; k < 5; ++k) {\n                int cand = rng() % N;\n                long long diff = T[cand] - counts[cand]; // Positive if under-visited\n                if(diff > max_under_visited) {\n                    max_under_visited = diff;\n                    target_i = cand;\n                }\n            }\n            new_val = target_i;\n        } else {\n            new_val = rng() % N;\n        }\n        \n        // Apply change\n        if (is_a) a[i] = new_val;\n        else b[i] = new_val;\n        \n        long long new_error = calculate_error(a, b);\n        \n        // Metropolis acceptance\n        double temp = initial_temp + (final_temp - initial_temp) * (double)iter / MAX_ITER;\n        bool accept = false;\n        \n        if (new_error < current_error) {\n            accept = true;\n        } else {\n            double prob = exp((current_error - new_error) / temp);\n            if ((double)rng() / rng.max() < prob) {\n                accept = true;\n            }\n        }\n        \n        if (accept) {\n            current_error = new_error;\n            if (current_error < best_error) {\n                best_error = current_error;\n                memcpy(best_a, a, sizeof(int) * N);\n                memcpy(best_b, b, sizeof(int) * N);\n            }\n        } else {\n            // Revert changes\n            if (is_a) a[i] = old_val;\n            else b[i] = old_val;\n        }\n    }\n    \n    // Output the best solution\n    for (int i = 0; i < N; ++i) {\n        cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent a city\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double x, y; // Estimated coordinates\n};\n\n// Structure for an edge\nstruct Edge {\n    int u, v;\n    long long w;\n    int group_id;\n};\n\n// Function to calculate distance squared\ndouble distSq(double x1, double y1, double x2, double y2) {\n    return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\n}\n\n// Function to calculate distance rounded down\nlong long distInt(double x1, double y1, double x2, double y2) {\n    return (long long)floor(sqrt(distSq(x1, y1, x2, y2)));\n}\n\n// Function to perform a query\nvector<pair<int, int>> query(const vector<int>& c) {\n    if (c.size() < 2) return {};\n    cout << \"? \" << c.size();\n    for (int city_id : c) cout << \" \" << city_id;\n    cout << endl;\n    \n    vector<pair<int, int>> edges;\n    for (int i = 0; i < (int)c.size() - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        edges.push_back({u, v});\n    }\n    return edges;\n}\n\n// Calculate MST cost for a single group\ndouble calculateGroupMST(const vector<int>& group, const vector<City>& cities) {\n    if (group.size() <= 1) return 0;\n    int n = group.size();\n    vector<bool> visited(n, false);\n    vector<double> min_dist(n, 1e18);\n    min_dist[0] = 0;\n    double cost = 0;\n    for(int i=0; i<n; ++i) {\n        int u = -1;\n        for(int j=0; j<n; ++j) {\n            if(!visited[j] && (u == -1 || min_dist[j] < min_dist[u])) u = j;\n        }\n        if (u == -1 || min_dist[u] == 1e18) break;\n        visited[u] = true;\n        cost += min_dist[u];\n        for(int v=0; v<n; ++v) {\n            if(!visited[v]) {\n                double d = sqrt(distSq(cities[group[u]].x, cities[group[u]].y, \n                                       cities[group[v]].x, cities[group[v]].y));\n                min_dist[v] = min(min_dist[v], d);\n            }\n        }\n    }\n    return cost;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    vector<City> cities(N);\n    for (int i = 0; i < N; ++i) {\n        cities[i].id = 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.0;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2.0;\n    }\n\n    // 1. Multi-angle Clustering\n    vector<vector<int>> best_groups;\n    double min_cost = 1e18;\n    int num_angles = 100;\n\n    for (int i = 0; i < num_angles; ++i) {\n        double angle = M_PI * i / num_angles;\n        double cos_a = cos(angle);\n        double sin_a = sin(angle);\n        \n        vector<int> indices(N);\n        for(int j=0; j<N; ++j) indices[j] = j;\n        \n        sort(indices.begin(), indices.end(), [&](int a, int b) {\n            double pos_a = cities[a].x * cos_a + cities[a].y * sin_a;\n            double pos_b = cities[b].x * cos_a + cities[b].y * sin_a;\n            return pos_a < pos_b;\n        });\n        \n        vector<vector<int>> current_groups(M);\n        int start_idx = 0;\n        for(int j=0; j<M; ++j) {\n            for(int k=0; k<G[j]; ++k) {\n                current_groups[j].push_back(indices[start_idx++]);\n            }\n        }\n        \n        double cost = 0;\n        for (const auto& group : current_groups) cost += calculateGroupMST(group, cities);\n        if (cost < min_cost) {\n            min_cost = cost;\n            best_groups = current_groups;\n        }\n    }\n    \n    vector<vector<int>> groups = best_groups;\n\n    // 2. Identify expensive edges to query\n    vector<Edge> all_expensive_edges;\n    for(int i=0; i<M; ++i) {\n        if (groups[i].size() <= 1) continue;\n        \n        vector<Edge> group_edges;\n        for(size_t u=0; u<groups[i].size(); ++u) {\n            for(size_t v=u+1; v<groups[i].size(); ++v) {\n                int city_u = groups[i][u];\n                int city_v = groups[i][v];\n                group_edges.push_back({city_u, city_v, distInt(cities[city_u].x, cities[city_u].y, cities[city_v].x, cities[city_v].y), i});\n            }\n        }\n        sort(group_edges.begin(), group_edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        \n        vector<int> parent(N);\n        for(int j=0; j<N; ++j) parent[j] = j;\n        auto find = [&](auto self, int node) -> int {\n            return parent[node] == node ? node : parent[node] = self(self, parent[node]);\n        };\n        \n        for(const auto& e : group_edges) {\n            int root_u = find(find, e.u);\n            int root_v = find(find, e.v);\n            if(root_u != root_v) {\n                parent[root_u] = root_v;\n                all_expensive_edges.push_back(e);\n            }\n        }\n    }\n    \n    // Sort all MST edges by weight descending to prioritize expensive edges\n    sort(all_expensive_edges.begin(), all_expensive_edges.end(), [](const Edge& a, const Edge& b) {\n        return a.w > b.w;\n    });\n\n    // 3. Querying\n    vector<vector<pair<int, int>>> query_edges(M);\n    int queries_left = Q;\n    \n    for(const auto& e : all_expensive_edges) {\n        if (queries_left <= 0) break;\n        \n        int gid = e.group_id;\n        if (groups[gid].size() < 2) continue;\n        \n        // Pick u, v and find L-2 nearest neighbors to the midpoint of u and v\n        int u = e.u;\n        int v = e.v;\n        double mid_x = (cities[u].x + cities[v].x) / 2.0;\n        double mid_y = (cities[u].y + cities[v].y) / 2.0;\n        \n        vector<pair<double, int>> neighbors;\n        for(int city_id : groups[gid]) {\n            if (city_id == u || city_id == v) continue;\n            double d = distSq(cities[city_id].x, cities[city_id].y, mid_x, mid_y);\n            neighbors.push_back({d, city_id});\n        }\n        sort(neighbors.begin(), neighbors.end());\n        \n        vector<int> subset = {u, v};\n        int num_neighbors = min((int)neighbors.size(), L - 2);\n        for(int i=0; i<num_neighbors; ++i) subset.push_back(neighbors[i].second);\n        \n        auto edges = query(subset);\n        for(auto& edge : edges) {\n            query_edges[gid].push_back(edge);\n        }\n        queries_left--;\n    }\n    \n    // 4. Output MST construction\n    cout << \"!\" << endl;\n    for(int i=0; i<M; ++i) {\n        // Output cities\n        for(int j=0; j<G[i]; ++j) {\n            cout << groups[i][j] << (j == G[i]-1 ? \"\" : \" \");\n        }\n        cout << endl;\n        \n        // Build final MST\n        vector<Edge> final_edges;\n        \n        // Add query edges (weight 0 to ensure priority)\n        for(auto& edge : query_edges[i]) {\n            final_edges.push_back({edge.first, edge.second, 0, i});\n        }\n        \n        // Add all other edges (weight = estimated Euclidean distance)\n        for(size_t u=0; u<groups[i].size(); ++u) {\n            for(size_t v=u+1; v<groups[i].size(); ++v) {\n                int city_u = groups[i][u];\n                int city_v = groups[i][v];\n                long long d = distInt(cities[city_u].x, cities[city_u].y, cities[city_v].x, cities[city_v].y);\n                final_edges.push_back({city_u, city_v, d, i});\n            }\n        }\n        \n        sort(final_edges.begin(), final_edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        \n        // DSU\n        vector<int> parent(N);\n        for(int j=0; j<N; ++j) parent[j] = j;\n        \n        auto find = [&](auto self, int node) -> int {\n            return parent[node] == node ? node : parent[node] = self(self, parent[node]);\n        };\n        \n        vector<pair<int, int>> mst_edges;\n        for(auto& e : final_edges) {\n            int root_u = find(find, e.u);\n            int root_v = find(find, e.v);\n            if(root_u != root_v) {\n                parent[root_u] = root_v;\n                mst_edges.push_back({e.u, e.v});\n            }\n        }\n        \n        for(auto& e : mst_edges) {\n            cout << e.first << \" \" << e.second << endl;\n        }\n    }\n    \n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <tuple>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Constants\nconst int N = 20;\n\n// Directions: U, D, L, R\nconst int DR[] = {-1, 1, 0, 0};\nconst int DC[] = {0, 0, -1, 1};\nconst char D_CHAR[] = {'U', 'D', 'L', 'R'};\n\nstruct State {\n    int r, c, dist;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\n// Function to simulate sliding and find the stopping position\npair<int, int> get_stop_pos(int r, int c, int dr, int dc, const vector<vector<int>>& grid) {\n    int nr = r, nc = c;\n    while (true) {\n        int next_r = nr + dr;\n        int next_c = nc + dc;\n        // Blocks are at the edges, so sliding always stops\n        if (next_r < 0 || next_r >= N || next_c < 0 || next_c >= N || grid[next_r][next_c] == 1) {\n            return {nr, nc};\n        }\n        nr = next_r;\n        nc = next_c;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n, m;\n    cin >> n >> m;\n    int r0, c0;\n    cin >> r0 >> c0;\n    vector<pair<int, int>> targets(m);\n    for (int i = 0; i < m; ++i) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n\n    vector<vector<int>> grid(N, vector<int>(N, 0));\n    int curr_r = r0, curr_c = c0;\n\n    for (int t = 0; t < m; ++t) {\n        int tr = targets[t].first;\n        int tc = targets[t].second;\n\n        // Dijkstra to find shortest path to (tr, tc)\n        vector<vector<int>> dist(N, vector<int>(N, 1e9));\n        vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n        vector<vector<string>> action_path(N, vector<string>(N, \"\"));\n        \n        priority_queue<State, vector<State>, greater<State>> pq;\n        dist[curr_r][curr_c] = 0;\n        pq.push({curr_r, curr_c, 0});\n        \n        while (!pq.empty()) {\n            State top = pq.top();\n            pq.pop();\n            \n            if (top.dist > dist[top.r][top.c]) continue;\n            if (top.r == tr && top.c == tc) break;\n            \n            for (int i = 0; i < 4; ++i) {\n                // Move action\n                int nr = top.r + DR[i];\n                int nc = top.c + DC[i];\n                if (nr >= 0 && nr < N && nc >= 0 && nc < N) {\n                    int cost = (grid[nr][nc] == 1) ? 2 : 1;\n                    string actions = \"\";\n                    if (grid[nr][nc] == 1) actions += string(\"A \") + D_CHAR[i] + \"\\n\";\n                    actions += string(\"M \") + D_CHAR[i] + \"\\n\";\n                    \n                    if (dist[top.r][top.c] + cost < dist[nr][nc]) {\n                        dist[nr][nc] = dist[top.r][top.c] + cost;\n                        parent[nr][nc] = {top.r, top.c};\n                        action_path[nr][nc] = actions;\n                        pq.push({nr, nc, dist[nr][nc]});\n                    }\n                }\n                \n                // Slide action\n                pair<int, int> stop = get_stop_pos(top.r, top.c, DR[i], DC[i], grid);\n                int sr = stop.first, sc = stop.second;\n                int br = sr + DR[i], bc = sc + DC[i];\n                \n                // Check if we need to add a block to stop at (sr, sc)\n                bool need_block = (br >= 0 && br < N && bc >= 0 && bc < N && grid[br][bc] == 0);\n                int cost = need_block ? 2 : 1;\n                \n                string actions = \"\";\n                if (need_block) actions += string(\"A \") + D_CHAR[i] + \"\\n\";\n                actions += string(\"S \") + D_CHAR[i] + \"\\n\";\n                \n                if (dist[top.r][top.c] + cost < dist[sr][sc]) {\n                    dist[sr][sc] = dist[top.r][top.c] + cost;\n                    parent[sr][sc] = {top.r, top.c};\n                    action_path[sr][sc] = actions;\n                    pq.push({sr, sc, dist[sr][sc]});\n                }\n            }\n        }\n        \n        // Reconstruct and execute path\n        vector<string> path_actions;\n        int curr_r2 = tr, curr_c2 = tc;\n        while (curr_r2 != curr_r || curr_c2 != curr_c) {\n            path_actions.push_back(action_path[curr_r2][curr_c2]);\n            pair<int, int> p = parent[curr_r2][curr_c2];\n            curr_r2 = p.first;\n            curr_c2 = p.second;\n        }\n        reverse(path_actions.begin(), path_actions.end());\n        \n        for (const string& s : path_actions) {\n            cout << s;\n            size_t pos = 0;\n            while(pos < s.length()){\n                size_t next_line = s.find('\\n', pos);\n                string line = s.substr(pos, next_line - pos);\n                pos = next_line + 1;\n                if(line.empty()) continue;\n                \n                char act = line[0], dir = line[2];\n                int dr = 0, dc = 0;\n                if(dir == 'U') dr = -1; else if(dir == 'D') dr = 1; else if(dir == 'L') dc = -1; else if(dir == 'R') dc = 1;\n                \n                if(act == 'A'){\n                    int nr = curr_r + dr;\n                    int nc = curr_c + dc;\n                    grid[nr][nc] = 1 - grid[nr][nc];\n                } else if(act == 'M'){\n                    curr_r += dr;\n                    curr_c += dc;\n                } else if(act == 'S'){\n                    pair<int, int> stop = get_stop_pos(curr_r, curr_c, dr, dc, grid);\n                    curr_r = stop.first;\n                    curr_c = stop.second;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}"},"8":{"ahc001":"#include <iostream>\n#include <vector>\n#include <chrono>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Structure to represent an axis-aligned rectangle\nstruct Rect {\n    int x1, y1, x2, y2;\n};\n\nint N;\nvector<int> X, Y, R;\nvector<Rect> rects;\nvector<Rect> best_rects;\n\n// Fast Xorshift RNG for performance\nstruct Xorshift {\n    uint32_t x = 123456789, y = 362436069, z = 521288629, w = 88675123;\n    uint32_t next() {\n        uint32_t t = x ^ (x << 11);\n        x = y; y = z; z = w;\n        return w = w ^ (w >> 19) ^ t ^ (t >> 8);\n    }\n    int next_int(int n) { return next() % n; }\n    double next_double() { return (double)next() / 4294967296.0; }\n} rng;\n\n// Objective function: p_i = 1 - (1 - min/max)^2 = 2x - x^2\ninline double get_p(int i, int s) {\n    double r = R[i];\n    double x = min(r, (double)s) / max(r, (double)s);\n    return 2.0 * x - x * x;\n}\n\n// Check if rectangle 'r' overlaps with any other rectangle\n// idx is the index of the rectangle currently being moved\ninline bool check_overlap(int idx, const Rect& r) {\n    for (int i = 0; i < N; ++i) {\n        if (i == idx) continue;\n        // Overlap condition:\n        // rects[i].x1 < r.x2 && rects[i].x2 > r.x1 && rects[i].y1 < r.y2 && rects[i].y2 > r.y1\n        if (r.x1 < rects[i].x2 && r.x2 > rects[i].x1 &&\n            r.y1 < rects[i].y2 && r.y2 > rects[i].y1) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    // Fast I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N)) return 0;\n    X.resize(N);\n    Y.resize(N);\n    R.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> X[i] >> Y[i] >> R[i];\n    }\n\n    // Initial state: Each rectangle is 1x1 at its target location\n    rects.resize(N);\n    for (int i = 0; i < N; ++i) {\n        rects[i] = {X[i], Y[i], X[i] + 1, Y[i] + 1};\n    }\n    best_rects = rects;\n\n    double current_total_score = 0;\n    for (int i = 0; i < N; ++i) {\n        current_total_score += get_p(i, 1);\n    }\n    double best_total_score = current_total_score;\n\n    auto start_time = chrono::steady_clock::now();\n    \n    // SA parameters\n    double T_start = 0.1;\n    double T_end = 0.0001;\n    \n    // Main loop\n    int iter = 0;\n    while (true) {\n        // Check time every 1024 iterations to minimize overhead\n        if ((iter++ & 1023) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 4700) break;\n        }\n\n        // Calculate progress (0.0 to 1.0) and temperature\n        double elapsed_ms = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count();\n        double progress = elapsed_ms / 4700.0;\n        double T = T_start * pow(T_end / T_start, progress);\n\n        // Pick a rectangle to mutate\n        int i = rng.next_int(N);\n\n        // Adaptive delta_range: larger at the start for exploration, smaller at the end for precision\n        int delta_range = max(1, (int)(1000.0 * (1.0 - progress)));\n        int delta = rng.next_int(2 * delta_range + 1) - delta_range;\n\n        Rect next_rect = rects[i];\n        int side = rng.next_int(4);\n\n        // Mutate one side, ensuring target point (X[i], Y[i]) remains inside\n        if (side == 0) { // x1\n            next_rect.x1 = max(0, min(X[i], next_rect.x1 + delta));\n        } else if (side == 1) { // x2\n            next_rect.x2 = max(X[i] + 1, min(10000, next_rect.x2 + delta));\n        } else if (side == 2) { // y1\n            next_rect.y1 = max(0, min(Y[i], next_rect.y1 + delta));\n        } else { // y2\n            next_rect.y2 = max(Y[i] + 1, min(10000, next_rect.y2 + delta));\n        }\n\n        // Validate: skip degenerate rectangles and overlaps\n        if (next_rect.x1 == next_rect.x2 || next_rect.y1 == next_rect.y2) continue;\n        if (check_overlap(i, next_rect)) continue;\n\n        // Calculate score change\n        int old_s = (rects[i].x2 - rects[i].x1) * (rects[i].y2 - rects[i].y1);\n        int new_s = (next_rect.x2 - next_rect.x1) * (next_rect.y2 - next_rect.y1);\n        double delta_score = get_p(i, new_s) - get_p(i, old_s);\n\n        // Metropolis criterion: accept if better or with probability based on T\n        if (delta_score > 0 || (T > 1e-9 && exp(delta_score / T) > rng.next_double())) {\n            rects[i] = next_rect;\n            current_total_score += delta_score;\n            if (current_total_score > best_total_score) {\n                best_total_score = current_total_score;\n                best_rects = rects;\n            }\n        }\n    }\n\n    // Output best result found\n    for (int i = 0; i < N; ++i) {\n        cout << best_rects[i].x1 << \" \" << best_rects[i].y1 << \" \" << best_rects[i].x2 << \" \" << best_rects[i].y2 << \"\\n\";\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cstring>\n#include <cmath>\n\nusing namespace std;\n\n// Global variables to store problem data\nint si, sj;\nint t[50][50];\nint p[50][50];\nint M = 0;\nvector<int> tile_neighbors[2500];\nint initial_degree[2500];\nint degree[2500];\nbool is_visited_tile[2500];\n\n// Movement directions: Up, Down, Left, Right\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dchar[] = {'U', 'D', 'L', 'R'};\n\nint main() {\n    // Faster I/O for performance\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read input\n    if (!(cin >> si >> sj)) return 0;\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> t[i][j];\n            M = max(M, t[i][j] + 1);\n        }\n    }\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> p[i][j];\n        }\n    }\n\n    // Precompute tile adjacency\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            int current_tile = t[i][j];\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dr[k];\n                int nj = j + dc[k];\n                if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n                    int neighbor_tile = t[ni][nj];\n                    if (current_tile != neighbor_tile) {\n                        tile_neighbors[current_tile].push_back(neighbor_tile);\n                    }\n                }\n            }\n        }\n    }\n    // Remove duplicates from neighbor lists and calculate initial degree\n    for (int i = 0; i < M; ++i) {\n        sort(tile_neighbors[i].begin(), tile_neighbors[i].end());\n        tile_neighbors[i].erase(unique(tile_neighbors[i].begin(), tile_neighbors[i].end()), tile_neighbors[i].end());\n        initial_degree[i] = tile_neighbors[i].size();\n    }\n\n    string best_path = \"\";\n    int max_total_score = -1;\n\n    auto start_time = chrono::high_resolution_clock::now();\n    mt19937 rng(12345);\n\n    // Randomized search loop\n    while (true) {\n        auto current_time = chrono::high_resolution_clock::now();\n        // Time limit check (safer margin at 1.9s)\n        if (chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count() > 1900) {\n            break;\n        }\n\n        // Reset state efficiently\n        memset(is_visited_tile, 0, sizeof(bool) * M);\n        memcpy(degree, initial_degree, sizeof(int) * M);\n        \n        string current_path = \"\";\n        int current_total_score = 0;\n        int curr_r = si;\n        int curr_c = sj;\n        int curr_t = t[si][sj];\n        \n        is_visited_tile[curr_t] = true;\n        for(int neighbor : tile_neighbors[curr_t]) degree[neighbor]--;\n        current_total_score += p[curr_r][curr_c];\n        \n        // Random alpha to balance point greed and connectivity\n        int alpha = (rng() % 31) - 15;\n\n        while (true) {\n            struct Candidate { int r, c, dir, next_t; double score; };\n            Candidate candidates[4];\n            int num_candidates = 0;\n            \n            // Explore valid neighbor tiles\n            for (int k = 0; k < 4; ++k) {\n                int nr = curr_r + dr[k];\n                int nc = curr_c + dc[k];\n                if (nr >= 0 && nr < 50 && nc >= 0 && nc < 50) {\n                    int next_t = t[nr][nc];\n                    // Constraint: Must move to a different, unvisited tile\n                    if (next_t != curr_t && !is_visited_tile[next_t]) {\n                        // Heuristic: Immediate reward + connectivity (Warnsdorff's rule)\n                        double score = (double)p[nr][nc] + (double)alpha * degree[next_t];\n                        candidates[num_candidates++] = {nr, nc, k, next_t, score};\n                    }\n                }\n            }\n            \n            if (num_candidates == 0) break;\n            \n            // Sharpen weighting to favor high-heuristic moves\n            double min_score = candidates[0].score;\n            for(int i = 1; i < num_candidates; ++i) min_score = min(min_score, candidates[i].score);\n            \n            double weights[4];\n            double sum_weights = 0;\n            for(int i = 0; i < num_candidates; ++i) {\n                // Normalize and sharpen weights\n                double s = candidates[i].score - min_score + 1.0;\n                weights[i] = s * s; \n                sum_weights += weights[i];\n            }\n            \n            uniform_real_distribution<double> dist(0, sum_weights);\n            double r = dist(rng);\n            int best_idx = 0;\n            double cumulative = 0;\n            for(int i = 0; i < num_candidates; ++i) {\n                cumulative += weights[i];\n                if (r < cumulative) {\n                    best_idx = i;\n                    break;\n                }\n            }\n            \n            // Execute move\n            curr_r = candidates[best_idx].r;\n            curr_c = candidates[best_idx].c;\n            current_path += dchar[candidates[best_idx].dir];\n            \n            curr_t = candidates[best_idx].next_t;\n            is_visited_tile[curr_t] = true;\n            for(int neighbor : tile_neighbors[curr_t]) degree[neighbor]--;\n            current_total_score += p[curr_r][curr_c];\n        }\n        \n        // Keep track of the best path found\n        if (current_total_score > max_total_score) {\n            max_total_score = current_total_score;\n            best_path = current_path;\n        }\n    }\n    \n    cout << best_path << endl;\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Grid dimensions (30x30)\nconst int R = 30;\nconst int C = 30;\n\n// Edge weights and visit counts\ndouble hor[R][C - 1];\ndouble ver[R - 1][C];\nint cnt_hor[R][C - 1];\nint cnt_ver[R - 1][C];\n\nstruct Node {\n    int r, c;\n    double f; // f = g + h\n    double g; // actual cost so far\n    bool operator>(const Node& other) const {\n        return f > other.f;\n    }\n};\n\n// Heuristic: Manhattan distance * min_possible_edge_weight\n// Min possible weight is 1000.\ninline double heuristic(int r, int c, int tr, int tc) {\n    return (abs(r - tr) + abs(c - tc)) * 1000.0;\n}\n\n// Function to compute the shortest path using A*\nstring get_path(int sr, int sc, int tr, int tc) {\n    static double dist[R][C];\n    static pair<int, int> parent[R][C];\n    static char dir[R][C];\n    \n    for(int i = 0; i < R; ++i) {\n        for(int j = 0; j < C; ++j) {\n            dist[i][j] = 1e18;\n            parent[i][j] = {-1, -1};\n            dir[i][j] = ' ';\n        }\n    }\n    \n    priority_queue<Node, vector<Node>, greater<Node>> pq;\n    \n    dist[sr][sc] = 0;\n    pq.push({sr, sc, heuristic(sr, sc, tr, tc), 0});\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    char dchar[] = {'U', 'D', 'L', 'R'};\n    \n    while (!pq.empty()) {\n        Node current = pq.top();\n        pq.pop();\n        \n        int r = current.r;\n        int c = current.c;\n        \n        if (current.g > dist[r][c]) continue;\n        if (r == tr && c == tc) break;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i];\n            int nc = c + dc[i];\n            \n            if (nr >= 0 && nr < R && nc >= 0 && nc < C) {\n                double weight = 0;\n                if (i == 0) weight = ver[r - 1][c]; // U\n                else if (i == 1) weight = ver[r][c]; // D\n                else if (i == 2) weight = hor[r][c - 1]; // L\n                else if (i == 3) weight = hor[r][c]; // R\n                \n                if (dist[nr][nc] > dist[r][c] + weight) {\n                    dist[nr][nc] = dist[r][c] + weight;\n                    parent[nr][nc] = {r, c};\n                    dir[nr][nc] = dchar[i];\n                    pq.push({nr, nc, dist[nr][nc] + heuristic(nr, nc, tr, tc), dist[nr][nc]});\n                }\n            }\n        }\n    }\n    \n    // Reconstruct the path\n    string path = \"\";\n    int curr_r = tr;\n    int curr_c = tc;\n    while (curr_r != sr || curr_c != sc) {\n        char d = dir[curr_r][curr_c];\n        path += d;\n        pair<int, int> p = parent[curr_r][curr_c];\n        curr_r = p.first;\n        curr_c = p.second;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    // Initialize weights to a neutral middle value 5000.0\n    for (int i = 0; i < R; ++i)\n        for (int j = 0; j < C - 1; ++j) { hor[i][j] = 5000.0; cnt_hor[i][j] = 0; }\n    for (int i = 0; i < R - 1; ++i)\n        for (int j = 0; j < C; ++j) { ver[i][j] = 5000.0; cnt_ver[i][j] = 0; }\n    \n    for (int k = 0; k < 1000; ++k) {\n        int sr, sc, tr, tc;\n        cin >> sr >> sc >> tr >> tc;\n        \n        string path = get_path(sr, sc, tr, tc);\n        cout << path << endl; // Flushes output\n        \n        int measured_len;\n        cin >> measured_len;\n        \n        // Calculate predicted path length based on current estimates\n        double path_len = 0;\n        int curr_r = sr;\n        int curr_c = sc;\n        \n        for (char d : path) {\n            if (d == 'U') path_len += ver[curr_r - 1][curr_c];\n            else if (d == 'D') path_len += ver[curr_r][curr_c];\n            else if (d == 'L') path_len += hor[curr_r][curr_c - 1];\n            else if (d == 'R') path_len += hor[curr_r][curr_c];\n            \n            if (d == 'U') curr_r--;\n            else if (d == 'D') curr_r++;\n            else if (d == 'L') curr_c--;\n            else if (d == 'R') curr_c++;\n        }\n        \n        // Calculate ratio and clamp it to allow robust correction\n        double ratio = (double)measured_len / (path_len + 1e-9);\n        if (ratio < 0.4) ratio = 0.4;\n        if (ratio > 2.5) ratio = 2.5;\n        \n        // Update weights\n        curr_r = sr;\n        curr_c = sc;\n        for (char d : path) {\n            double* w_ptr = nullptr;\n            int* cnt_ptr = nullptr;\n            \n            if (d == 'U') { w_ptr = &ver[curr_r - 1][curr_c]; cnt_ptr = &cnt_ver[curr_r - 1][curr_c]; }\n            else if (d == 'D') { w_ptr = &ver[curr_r][curr_c]; cnt_ptr = &cnt_ver[curr_r][curr_c]; }\n            else if (d == 'L') { w_ptr = &hor[curr_r][curr_c - 1]; cnt_ptr = &cnt_hor[curr_r][curr_c - 1]; }\n            else if (d == 'R') { w_ptr = &hor[curr_r][curr_c]; cnt_ptr = &cnt_hor[curr_r][curr_c]; }\n            \n            // Dynamic learning rate tuned with a floor to ensure sustained adaptivity\n            (*cnt_ptr)++;\n            double alpha = 0.6 / (1.0 + 0.02 * (*cnt_ptr));\n            if (alpha < 0.05) alpha = 0.05;\n            \n            *w_ptr *= (1.0 + alpha * (ratio - 1.0));\n            \n            // Constraint check\n            if (*w_ptr < 100) *w_ptr = 100;\n            if (*w_ptr > 15000) *w_ptr = 15000;\n            \n            if (d == 'U') curr_r--;\n            else if (d == 'D') curr_r++;\n            else if (d == 'L') curr_c--;\n            else if (d == 'R') curr_c++;\n        }\n    }\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\n// Constants\nconst int N = 20;\nint M;\nstring S[800];\nint8_t grid[N][N];\nint8_t best_grid[N][N];\nlong long best_overall_score = -1;\n\nint16_t mismatches[800][800];\nint16_t num_valid[800];\nint count_c;\nint count_dot;\n\nstruct AffectedItem {\n    int16_t s_idx;\n    int16_t p_idx;\n    int8_t k;\n};\n\n// Flattened affected structures for cache locality\nAffectedItem affected[N][N][2000];\nint affected_size[N][N];\n\nstruct PlacementInfo {\n    int16_t line_idx;\n    int16_t start_pos;\n    int8_t len;\n    int8_t target_chars[12];\n};\nPlacementInfo all_placements[800][800];\n\n// Unsatisfied string tracking\nvector<int> unsatisfied;\nint pos_in_unsatisfied[800]; // To store position in unsatisfied vector\n\nvoid update_unsatisfied(int s_idx, bool is_now_satisfied) {\n    if (is_now_satisfied) {\n        if (pos_in_unsatisfied[s_idx] != -1) {\n            int pos = pos_in_unsatisfied[s_idx];\n            int last_s = unsatisfied.back();\n            unsatisfied[pos] = last_s;\n            pos_in_unsatisfied[last_s] = pos;\n            unsatisfied.pop_back();\n            pos_in_unsatisfied[s_idx] = -1;\n        }\n    } else {\n        if (pos_in_unsatisfied[s_idx] == -1) {\n            pos_in_unsatisfied[s_idx] = unsatisfied.size();\n            unsatisfied.push_back(s_idx);\n        }\n    }\n}\n\nvoid precompute() {\n    memset(affected_size, 0, sizeof(affected_size));\n    for (int i = 0; i < M; ++i) {\n        int len = S[i].length();\n        for (int line = 0; line < 2 * N; ++line) {\n            for (int start = 0; start < N; ++start) {\n                int p_idx = line * N + start;\n                all_placements[i][p_idx] = {(int16_t)line, (int16_t)start, (int8_t)len};\n                for (int k = 0; k < len; ++k) all_placements[i][p_idx].target_chars[k] = S[i][k] - 'A';\n                for (int k = 0; k < len; ++k) {\n                    int r, c;\n                    if (line < N) {\n                        r = line;\n                        c = (start + k) % N;\n                    } else {\n                        r = (start + k) % N;\n                        c = line - N;\n                    }\n                    if (affected_size[r][c] < 2000) {\n                        affected[r][c][affected_size[r][c]++] = {(int16_t)i, (int16_t)p_idx, (int8_t)k};\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid reset_state() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) grid[i][j] = 8; // '.'\n    }\n    count_c = 0;\n    count_dot = N * N;\n    unsatisfied.clear();\n    for (int i = 0; i < M; ++i) {\n        num_valid[i] = 0;\n        pos_in_unsatisfied[i] = -1;\n        update_unsatisfied(i, false);\n        int len = S[i].length();\n        for (int p = 0; p < 2 * N * N; ++p) {\n            mismatches[i][p] = len;\n        }\n    }\n}\n\ninline void update_grid(int r, int c, int new_val) {\n    int old_val = grid[r][c];\n    if (old_val == new_val) return;\n    if (old_val == 8 && new_val != 8) count_dot--;\n    else if (old_val != 8 && new_val == 8) count_dot++;\n    grid[r][c] = new_val;\n\n    int sz = affected_size[r][c];\n    for (int i = 0; i < sz; ++i) {\n        AffectedItem& p = affected[r][c][i];\n        bool was_valid = (mismatches[p.s_idx][p.p_idx] == 0);\n        int target = all_placements[p.s_idx][p.p_idx].target_chars[p.k];\n        \n        if (old_val == target) mismatches[p.s_idx][p.p_idx]++;\n        if (new_val == target) mismatches[p.s_idx][p.p_idx]--;\n        \n        bool is_valid = (mismatches[p.s_idx][p.p_idx] == 0);\n        if (was_valid && !is_valid) {\n            num_valid[p.s_idx]--;\n            if (num_valid[p.s_idx] == 0) {\n                count_c--;\n                update_unsatisfied(p.s_idx, false);\n            }\n        } else if (!was_valid && is_valid) {\n            if (num_valid[p.s_idx] == 0) {\n                count_c++;\n                update_unsatisfied(p.s_idx, true);\n            }\n            num_valid[p.s_idx]++;\n        }\n    }\n}\n\nlong long get_score() {\n    return (long long)count_c * 1000000 + count_dot;\n}\n\nvoid solve(mt19937& rng, chrono::steady_clock::time_point start_time) {\n    reset_state();\n\n    // Initial greedy\n    vector<int> p(M);\n    for(int i=0; i<M; ++i) p[i] = i;\n    shuffle(p.begin(), p.end(), rng);\n    for(int i : p) {\n        if (num_valid[i] > 0) continue;\n        int p_idx = rng() % (2 * N * N);\n        int len = all_placements[i][p_idx].len;\n        for (int k = 0; k < len; ++k) {\n            int line = all_placements[i][p_idx].line_idx;\n            int start = all_placements[i][p_idx].start_pos;\n            int r, c;\n            if (line < N) { r = line; c = (start + k) % N; }\n            else { r = (start + k) % N; c = line - N; }\n            if (grid[r][c] == 8) update_grid(r, c, all_placements[i][p_idx].target_chars[k]);\n        }\n    }\n\n    long long current_score = get_score();\n    long long best_local_score = current_score;\n    \n    double T_start = 1e6;\n    double T_end = 1e1;\n    const int iterations = 1000000;\n    \n    for (int i = 0; i < iterations; ++i) {\n        if ((i & 1023) == 0) {\n            if (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() > 2800) break;\n        }\n        \n        int r, c, val;\n        \n        if (!unsatisfied.empty() && (rng() % 100 < 80)) {\n            int s_idx = unsatisfied[rng() % unsatisfied.size()];\n            int best_p = -1;\n            int min_m = 999;\n            for (int p_idx = 0; p_idx < 2 * N * N; ++p_idx) {\n                if (mismatches[s_idx][p_idx] < min_m) {\n                    min_m = mismatches[s_idx][p_idx];\n                    best_p = p_idx;\n                }\n            }\n            int target_k = rng() % all_placements[s_idx][best_p].len;\n            int line = all_placements[s_idx][best_p].line_idx;\n            int start = all_placements[s_idx][best_p].start_pos;\n            if (line < N) { r = line; c = (start + target_k) % N; }\n            else { r = (start + target_k) % N; c = line - N; }\n            val = all_placements[s_idx][best_p].target_chars[target_k];\n        } else {\n            r = rng() % N;\n            c = rng() % N;\n            val = rng() % 9;\n        }\n        \n        int old_val = grid[r][c];\n        if (old_val == val) continue;\n        \n        update_grid(r, c, val);\n        long long next_score = get_score();\n        \n        double progress = (double)i / iterations;\n        double T = T_start * exp(log(T_end / T_start) * progress);\n        \n        if (next_score >= current_score || (rng() % 10000) / 10000.0 < exp((double)(next_score - current_score) / T)) {\n            current_score = next_score;\n            if (current_score > best_local_score) {\n                best_local_score = current_score;\n                if (best_local_score > best_overall_score) {\n                    best_overall_score = best_local_score;\n                    memcpy(best_grid, grid, sizeof(grid));\n                }\n            }\n        } else {\n            update_grid(r, c, old_val);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    int N_in; cin >> N_in >> M;\n    for (int i = 0; i < M; ++i) cin >> S[i];\n    \n    precompute();\n    \n    mt19937 rng(1337);\n    auto start_time = chrono::steady_clock::now();\n    \n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 2800) {\n        solve(rng, start_time);\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) cout << (best_grid[i][j] == 8 ? '.' : (char)(best_grid[i][j] + 'A'));\n        cout << \"\\n\";\n    }\n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <chrono>\n#include <random>\n#include <functional>\n#include <cmath>\n\nusing namespace std;\n\n// Structure for grid coordinates\nstruct Point {\n    int r, c;\n    bool operator==(const Point& other) const { return r == other.r && c == other.c; }\n    bool operator!=(const Point& other) const { return !(*this == other); }\n};\n\n// State for Dijkstra priority queue\nstruct State {\n    int dist;\n    Point p;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\nint N;\nint si, sj;\nvector<string> grid;\nvector<vector<int>> weights;\nvector<vector<vector<Point>>> visible_from;\nvector<Point> all_road_squares;\n\n// Precompute which squares are visible from each road square\nvoid precompute_visibility() {\n    visible_from.assign(N, vector<vector<Point>>(N));\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            if (grid[r][c] == '#') continue;\n            \n            // The square itself is visible\n            visible_from[r][c].push_back({r, c});\n            \n            // Horizontal\n            for (int nc = c + 1; nc < N && grid[r][nc] != '#'; ++nc) \n                visible_from[r][c].push_back({r, nc});\n            for (int nc = c - 1; nc >= 0 && grid[r][nc] != '#'; --nc) \n                visible_from[r][c].push_back({r, nc});\n            \n            // Vertical\n            for (int nr = r + 1; nr < N && grid[nr][c] != '#'; ++nr) \n                visible_from[r][c].push_back({nr, c});\n            for (int nr = r - 1; nr >= 0 && grid[nr][c] != '#'; --nr) \n                visible_from[r][c].push_back({nr, c});\n        }\n    }\n}\n\n// Dijkstra for shortest path calculation\nstruct DijkstraResult {\n    vector<vector<int>> dist;\n    vector<vector<Point>> parent;\n};\n\nDijkstraResult dijkstra(Point start) {\n    DijkstraResult res;\n    res.dist.assign(N, vector<int>(N, 1e9));\n    res.parent.assign(N, vector<Point>(N, {-1, -1}));\n    \n    priority_queue<State, vector<State>, greater<State>> pq;\n    \n    res.dist[start.r][start.c] = 0;\n    pq.push({0, start});\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    \n    while (!pq.empty()) {\n        State top = pq.top();\n        pq.pop();\n        int d = top.dist;\n        Point u = top.p;\n        \n        if (d > res.dist[u.r][u.c]) continue;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = u.r + dr[i];\n            int nc = u.c + dc[i];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] != '#') {\n                int cost = weights[nr][nc];\n                if (res.dist[nr][nc] > d + cost) {\n                    res.dist[nr][nc] = d + cost;\n                    res.parent[nr][nc] = u;\n                    pq.push({res.dist[nr][nc], {nr, nc}});\n                }\n            }\n        }\n    }\n    return res;\n}\n\n// Reconstruct path\nstring get_path_string(Point start, Point end, const vector<vector<Point>>& parent) {\n    string path = \"\";\n    Point curr = end;\n    while (curr != start) {\n        Point p = parent[curr.r][curr.c];\n        if (curr.r == p.r - 1) path += 'U';\n        else if (curr.r == p.r + 1) path += 'D';\n        else if (curr.c == p.c - 1) path += 'L';\n        else if (curr.c == p.c + 1) path += 'R';\n        curr = p;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N >> si >> sj;\n    grid.resize(N);\n    weights.resize(N, vector<int>(N));\n    \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                weights[i][j] = grid[i][j] - '0';\n                all_road_squares.push_back({i, j});\n            }\n        }\n    }\n    \n    precompute_visibility();\n    \n    auto start_time = chrono::steady_clock::now();\n    mt19937 rng(42);\n    \n    string best_full_path;\n    int min_total_cost = 2e9;\n    \n    // Randomized greedy construction with iteration\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 2500) {\n        vector<vector<bool>> covered(N, vector<bool>(N, false));\n        int total_covered = 0;\n        int target = all_road_squares.size();\n        \n        Point curr = {si, sj};\n        vector<Point> path_nodes = {curr};\n        \n        auto mark = [&](Point p) {\n            for (auto& v : visible_from[p.r][p.c]) {\n                if (!covered[v.r][v.c]) {\n                    covered[v.r][v.c] = true;\n                    total_covered++;\n                }\n            }\n        };\n        mark(curr);\n        \n        while (total_covered < target) {\n            auto bfs_res = dijkstra(curr);\n            \n            struct Candidate { Point p; double score; int dist; };\n            vector<Candidate> candidates;\n            \n            for (auto& p : all_road_squares) {\n                int gain = 0;\n                for (auto& v : visible_from[p.r][p.c]) {\n                    if (!covered[v.r][v.c]) gain++;\n                }\n                if (gain > 0) {\n                    double dist = (double)bfs_res.dist[p.r][p.c];\n                    double score = (double)gain / (pow(dist, 1.2) + 1.0);\n                    candidates.push_back({p, score, (int)dist});\n                }\n            }\n            \n            if (candidates.empty()) break;\n            \n            sort(candidates.begin(), candidates.end(), [](const Candidate& a, const Candidate& b) {\n                return a.score > b.score;\n            });\n            \n            int k = min((int)candidates.size(), 5);\n            uniform_int_distribution<int> dist_k(0, k - 1);\n            int idx = dist_k(rng);\n            \n            curr = candidates[idx].p;\n            path_nodes.push_back(curr);\n            mark(curr);\n        }\n        \n        path_nodes.push_back({si, sj});\n        \n        // Multi-pass Pruning\n        for(int pass = 0; pass < 5; ++pass) {\n            vector<vector<int>> cov_cnt(N, vector<int>(N, 0));\n            for (auto& p : path_nodes) {\n                for (auto& v : visible_from[p.r][p.c]) {\n                    cov_cnt[v.r][v.c]++;\n                }\n            }\n            \n            bool changed = false;\n            for (int i = 1; i < (int)path_nodes.size() - 1; ) {\n                Point p = path_nodes[i];\n                bool can_remove = true;\n                for (auto& v : visible_from[p.r][p.c]) {\n                    if (cov_cnt[v.r][v.c] <= 1) {\n                        can_remove = false;\n                        break;\n                    }\n                }\n                \n                if (can_remove) {\n                    for (auto& v : visible_from[p.r][p.c]) {\n                        cov_cnt[v.r][v.c]--;\n                    }\n                    path_nodes.erase(path_nodes.begin() + i);\n                    changed = true;\n                } else {\n                    i++;\n                }\n            }\n            if (!changed) break;\n        }\n        \n        // Build final path from pruned waypoints\n        string current_path = \"\";\n        int current_total_cost = 0;\n        for (int i = 0; i < (int)path_nodes.size() - 1; ++i) {\n            auto bfs_res = dijkstra(path_nodes[i]);\n            current_total_cost += bfs_res.dist[path_nodes[i+1].r][path_nodes[i+1].c];\n            current_path += get_path_string(path_nodes[i], path_nodes[i+1], bfs_res.parent);\n        }\n        \n        if (current_total_cost < min_total_cost) {\n            min_total_cost = current_total_cost;\n            best_full_path = current_path;\n        }\n    }\n    \n    cout << best_full_path << endl;\n    \n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <bitset>\n\nusing namespace std;\n\n// Global problem variables\nint N, M, K, R;\nvector<vector<int>> task_difficulty;\nvector<vector<int>> adj; \nvector<int> in_degree;\nvector<int> member_status; // -1: free, >=0: task_id\nvector<int> start_day;\nvector<vector<double>> s; // Skills estimation (member x skill_dim)\nvector<int> H; // Task height (longest chain)\nvector<int> D; // Descendants count\nvector<int> visit_count; // Number of tasks completed by each member\n\n// Function to calculate predicted completion time for a task by a member\ndouble predict_t(int task_id, int member_id) {\n    double w = 0;\n    for (int k = 0; k < K; ++k) {\n        w += max(0.0, (double)task_difficulty[task_id][k] - s[member_id][k]);\n    }\n    return max(1.0, w);\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read input\n    if (!(cin >> N >> M >> K >> R)) return 0;\n    task_difficulty.resize(N, vector<int>(K));\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            cin >> task_difficulty[i][k];\n        }\n    }\n    adj.resize(N);\n    in_degree.resize(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        adj[u].push_back(v);\n        in_degree[v]++;\n    }\n\n    // Precompute H (Height) - Longest path in DAG\n    H.resize(N, 1);\n    for (int i = N - 1; i >= 0; --i) {\n        for (int v : adj[i]) {\n            H[i] = max(H[i], 1 + H[v]);\n        }\n    }\n\n    // Precompute D (Descendants count)\n    vector<bitset<1000>> reachable(N);\n    for (int i = N - 1; i >= 0; --i) {\n        reachable[i].set(i);\n        for (int v : adj[i]) {\n            reachable[i] |= reachable[v];\n        }\n    }\n    D.resize(N);\n    for(int i=0; i<N; ++i) D[i] = (int)reachable[i].count() - 1;\n\n    // Precompute estimated average difficulty for prioritization\n    vector<double> task_avg_dur(N);\n    for(int i=0; i<N; ++i) {\n        double dur = 0;\n        for(int k=0; k<K; ++k) dur += max(0.0, (double)task_difficulty[i][k] - 30.0);\n        task_avg_dur[i] = dur;\n    }\n\n    // Initialization\n    member_status.assign(M, -1);\n    start_day.assign(N, -1);\n    visit_count.assign(M, 0);\n    s.assign(M, vector<double>(K, 30.0)); \n    vector<int> ready_tasks;\n    for (int i = 0; i < N; ++i) {\n        if (in_degree[i] == 0) ready_tasks.push_back(i);\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n\n        // 1. Assign tasks\n        // Prioritize: H (Criticality) * 20000 + D + estimated_duration\n        sort(ready_tasks.begin(), ready_tasks.end(), [&](int a, int b) {\n            double score_a = (double)H[a] * 20000 + D[a] * 10.0 + task_avg_dur[a];\n            double score_b = (double)H[b] * 20000 + D[b] * 10.0 + task_avg_dur[b];\n            return score_a > score_b;\n        });\n\n        vector<pair<int, int>> assignments;\n        vector<int> free_members;\n        for (int j = 0; j < M; ++j) {\n            if (member_status[j] == -1) free_members.push_back(j);\n        }\n\n        vector<bool> task_assigned(ready_tasks.size(), false);\n        vector<bool> member_assigned(free_members.size(), false);\n\n        // Greedy matching: Task-first, then best member\n        for (int i = 0; i < (int)ready_tasks.size(); ++i) {\n            int task_id = ready_tasks[i];\n            \n            int best_member_idx = -1;\n            double min_t = 1e18;\n\n            for (int j = 0; j < (int)free_members.size(); ++j) {\n                if (member_assigned[j]) continue;\n                double t = predict_t(task_id, free_members[j]);\n                if (t < min_t) {\n                    min_t = t;\n                    best_member_idx = j;\n                }\n            }\n\n            if (best_member_idx != -1) {\n                int member_id = free_members[best_member_idx];\n                assignments.push_back({member_id + 1, task_id + 1});\n                member_status[member_id] = task_id;\n                start_day[task_id] = day;\n                member_assigned[best_member_idx] = true;\n                task_assigned[i] = true;\n            }\n        }\n\n        // Update ready_tasks: remove assigned\n        vector<int> next_ready_tasks;\n        for (int i = 0; i < (int)ready_tasks.size(); ++i) {\n            if (!task_assigned[i]) next_ready_tasks.push_back(ready_tasks[i]);\n        }\n        ready_tasks = next_ready_tasks;\n\n        // Output and flush\n        cout << assignments.size();\n        for (auto& p : assignments) cout << \" \" << p.first << \" \" << p.second;\n        cout << endl;\n\n        // 2. Read completed\n        int n_completed;\n        cin >> n_completed;\n        if (n_completed == -1) break;\n\n        for (int i = 0; i < n_completed; ++i) {\n            int member_id;\n            cin >> member_id;\n            --member_id;\n            int task_id = member_status[member_id];\n            \n            // Skill learning update\n            int actual_t = day - start_day[task_id] + 1;\n            double w_pred = 0;\n            vector<int> bottlenecks;\n            for (int k = 0; k < K; ++k) {\n                double diff = (double)task_difficulty[task_id][k] - s[member_id][k];\n                if (diff > 0) {\n                    w_pred += diff;\n                    bottlenecks.push_back(k);\n                }\n            }\n            \n            // Adaptive learning rate based on how many tasks the member has completed\n            double lr = 0.2 / (1.0 + 0.05 * visit_count[member_id]);\n            visit_count[member_id]++;\n\n            double error = (double)actual_t - max(1.0, w_pred);\n            if (abs(error) > 1e-9) {\n                if (!bottlenecks.empty()) {\n                    for(int k : bottlenecks) {\n                        s[member_id][k] -= (error / bottlenecks.size()) * lr;\n                        s[member_id][k] = max(0.0, min(100.0, s[member_id][k]));\n                    }\n                } else {\n                    // Update all if no bottlenecks (error indicates optimistic skill estimate)\n                    for(int k = 0; k < K; ++k) {\n                        s[member_id][k] -= (error / K) * lr;\n                        s[member_id][k] = max(0.0, min(100.0, s[member_id][k]));\n                    }\n                }\n            }\n\n            member_status[member_id] = -1;\n\n            // Unlock dependencies\n            for (int next_task : adj[task_id]) {\n                in_degree[next_task]--;\n                if (in_degree[next_task] == 0) ready_tasks.push_back(next_task);\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Structure to hold order information\nstruct Order {\n    int id;\n    int ax, ay, cx, cy;\n};\n\n// Node structure for the route (pickup or delivery)\nstruct Node {\n    int order_id;\n    bool is_pickup;\n    int x, y;\n};\n\n// Global lookup\nOrder orders_by_id[1001];\n\n// Inline distance function for performance\ninline int dist(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Calculate the total route distance\nint calculate_total_dist(const vector<Node>& route) {\n    int d = dist(400, 400, route[0].x, route[0].y);\n    for (size_t i = 0; i < route.size() - 1; ++i) {\n        d += dist(route[i].x, route[i].y, route[i + 1].x, route[i + 1].y);\n    }\n    d += dist(route.back().x, route.back().y, 400, 400);\n    return d;\n}\n\n// Efficiently check if a route satisfies precedence constraints\nbool is_valid(const vector<Node>& route, const vector<int>& selected_orders) {\n    static int p_pos[1001], d_pos[1001];\n    for (int id : selected_orders) {\n        p_pos[id] = -1;\n        d_pos[id] = -1;\n    }\n    \n    for (int i = 0; i < (int)route.size(); ++i) {\n        if (route[i].is_pickup) p_pos[route[i].order_id] = i;\n        else d_pos[route[i].order_id] = i;\n    }\n    \n    for (int id : selected_orders) {\n        if (p_pos[id] == -1 || d_pos[id] == -1 || p_pos[id] > d_pos[id]) return false;\n    }\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // Read orders\n    vector<int> all_indices(1000);\n    for (int i = 0; i < 1000; ++i) {\n        orders_by_id[i + 1].id = i + 1;\n        cin >> orders_by_id[i + 1].ax >> orders_by_id[i + 1].ay \n            >> orders_by_id[i + 1].cx >> orders_by_id[i + 1].cy;\n        all_indices[i] = i + 1;\n    }\n\n    // Heuristic selection: sort by total trip cost\n    sort(all_indices.begin(), all_indices.end(), [](int i, int j) {\n        auto cost = [](int idx) {\n            return dist(400, 400, orders_by_id[idx].ax, orders_by_id[idx].ay) + \n                   dist(orders_by_id[idx].ax, orders_by_id[idx].ay, orders_by_id[idx].cx, orders_by_id[idx].cy) +\n                   dist(orders_by_id[idx].cx, orders_by_id[idx].cy, 400, 400);\n        };\n        return cost(i) < cost(j);\n    });\n\n    vector<int> selected_orders;\n    for (int i = 0; i < 50; ++i) selected_orders.push_back(all_indices[i]);\n\n    // Randomized Greedy Initial Construction\n    mt19937 rng(42);\n    vector<Node> route;\n    vector<bool> p_visited(1001, false), d_visited(1001, false);\n    int cx = 400, cy = 400;\n    \n    while (route.size() < 100) {\n        vector<pair<int, int>> candidates; // {dist, id*2 + (is_pickup ? 0 : 1)}\n        for (int id : selected_orders) {\n            if (!p_visited[id]) {\n                candidates.push_back({dist(cx, cy, orders_by_id[id].ax, orders_by_id[id].ay), id * 2});\n            } else if (p_visited[id] && !d_visited[id]) {\n                candidates.push_back({dist(cx, cy, orders_by_id[id].cx, orders_by_id[id].cy), id * 2 + 1});\n            }\n        }\n        \n        sort(candidates.begin(), candidates.end());\n        \n        // Pick from top 3 candidates to diversify\n        int pick_idx = 0;\n        if (candidates.size() > 1) pick_idx = rng() % min((int)candidates.size(), 3);\n        \n        int val = candidates[pick_idx].second;\n        int id = val / 2;\n        bool is_pickup = (val % 2 == 0);\n        \n        if (is_pickup) {\n            route.push_back({id, true, orders_by_id[id].ax, orders_by_id[id].ay});\n            p_visited[id] = true;\n            cx = orders_by_id[id].ax; cy = orders_by_id[id].ay;\n        } else {\n            route.push_back({id, false, orders_by_id[id].cx, orders_by_id[id].cy});\n            d_visited[id] = true;\n            cx = orders_by_id[id].cx; cy = orders_by_id[id].cy;\n        }\n    }\n\n    // Simulated Annealing\n    auto start_time = chrono::steady_clock::now();\n    int current_dist = calculate_total_dist(route);\n    double temp = 1000.0;\n    int iter = 0;\n    \n    while (true) {\n        if ((++iter & 1023) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1900) break;\n        }\n\n        vector<Node> next_route = route;\n        int type = rng() % 3; // 0: 2-opt, 1: Relocate, 2: Swap\n        \n        if (type == 0) { // 2-opt\n            int i = rng() % 100, j = rng() % 100;\n            if (i > j) swap(i, j);\n            reverse(next_route.begin() + i, next_route.begin() + j + 1);\n        } else if (type == 1) { // Relocate\n            int i = rng() % 100, j = rng() % 100;\n            Node n = next_route[i];\n            next_route.erase(next_route.begin() + i);\n            next_route.insert(next_route.begin() + j, n);\n        } else { // Swap\n            int i = rng() % 100, j = rng() % 100;\n            swap(next_route[i], next_route[j]);\n        }\n\n        if (is_valid(next_route, selected_orders)) {\n            int next_dist = calculate_total_dist(next_route);\n            if (next_dist < current_dist || (rng() % 10000) / 10000.0 < exp((current_dist - next_dist) / temp)) {\n                route = next_route;\n                current_dist = next_dist;\n            }\n        }\n        temp *= 0.999999;\n    }\n\n    // Output results\n    cout << 50;\n    for (int id : selected_orders) cout << \" \" << id;\n    cout << endl << 102 << \" 400 400\";\n    for (const auto& node : route) cout << \" \" << node.x << \" \" << node.y;\n    cout << \" 400 400\" << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\n// DSU structure for connectivity checking\nstruct DSU {\n    vector<int> parent;\n    int num_components;\n    DSU(int n) : num_components(n) {\n        parent.resize(n);\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int i) {\n        if (parent[i] == i)\n            return i;\n        return parent[i] = find(parent[i]);\n    }\n    // unite returns true if it actually merged two components\n    bool unite(int i, int j) {\n        int root_i = find(i);\n        int root_j = find(j);\n        if (root_i != root_j) {\n            parent[root_i] = root_j;\n            num_components--;\n            return true;\n        }\n        return false;\n    }\n    bool same(int i, int j) {\n        return find(i) == find(j);\n    }\n};\n\nstruct Edge {\n    int u, v, d, id;\n};\n\nint main() {\n    // Faster I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Problem constraints\n    const int N = 400;\n    const int M = 1995;\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<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        int dx = coords[edges[i].u].first - coords[edges[i].v].first;\n        int dy = coords[edges[i].u].second - coords[edges[i].v].second;\n        // Euclidean distance rounded to nearest integer\n        edges[i].d = (int)round(sqrt((double)dx * dx + (double)dy * dy));\n        edges[i].id = i;\n    }\n\n    vector<bool> adopted(M, false);\n    \n    // Process each edge as it arrives\n    for (int i = 0; i < M; ++i) {\n        int l_i;\n        cin >> l_i;\n\n        // Initialize DSU with all already adopted edges\n        DSU dsu(N);\n        for (int j = 0; j < i; ++j) {\n            if (adopted[j]) {\n                dsu.unite(edges[j].u, edges[j].v);\n            }\n        }\n        \n        // Calculate needed edge count\n        // We need to connect num_components components, so we need num_components - 1 more edges.\n        int num_needed = dsu.num_components - 1;\n        int num_remaining = M - i;\n\n        // Adaptive parameter k:\n        // k_base increases from 1.5 to 2.0 over time.\n        // Boost factor increases as we get desperate (num_needed close to num_remaining).\n        // This keeps our estimation centered around 2.0 (the expected value).\n        double k = 1.5 + 0.5 * ((double)i / M) + 0.5 * ((double)num_needed / num_remaining);\n\n        // Prepare candidates: the current edge (cost l_i) and all future edges (estimated cost k*d)\n        struct Candidate {\n            double cost;\n            int id;\n            int u, v;\n        };\n        vector<Candidate> candidates;\n        candidates.reserve(M - i);\n        \n        candidates.push_back({(double)l_i, i, edges[i].u, edges[i].v});\n        \n        for (int j = i + 1; j < M; ++j) {\n            candidates.push_back({k * edges[j].d, j, edges[j].u, edges[j].v});\n        }\n        \n        // Sort candidates by cost to run Kruskal's algorithm\n        sort(candidates.begin(), candidates.end(), [](const Candidate& a, const Candidate& b) {\n            return a.cost < b.cost;\n        });\n        \n        // Run Kruskal's to see if the current edge i is part of the MST\n        bool take_edge = false;\n        for (const auto& cand : candidates) {\n            if (!dsu.same(cand.u, cand.v)) {\n                dsu.unite(cand.u, cand.v);\n                if (cand.id == i) {\n                    take_edge = true;\n                    break;\n                }\n            }\n        }\n        \n        // Output decision and flush\n        if (take_edge) {\n            cout << 1 << endl;\n            adopted[i] = true;\n        } else {\n            cout << 0 << endl;\n            adopted[i] = false;\n        }\n    }\n    \n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int r, c;\n    bool operator==(const Point& other) const { return r == other.r && c == other.c; }\n};\n\nint N, M;\nvector<Point> pets;\nvector<int> pet_types;\nvector<Point> humans;\nbool impassable[30][30];\n\n// Check if a coordinate is within bounds\nbool is_valid(int r, int c) {\n    return r >= 0 && r < 30 && c >= 0 && c < 30;\n}\n\n// Check if a square can be made impassable\nbool can_build(int r, int c) {\n    if (!is_valid(r, c) || impassable[r][c]) return false;\n    // Cannot build if a pet or human is currently at (r, c)\n    for (const auto& p : pets) if (p.r == r && p.c == c) return false;\n    for (const auto& h : humans) if (h.r == r && h.c == c) return false;\n    \n    // Cannot build if an adjacent square contains a pet\n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    for (int i = 0; i < 4; ++i) {\n        int nr = r + dr[i];\n        int nc = c + dc[i];\n        if (is_valid(nr, nc)) {\n            for (const auto& p : pets) {\n                if (p.r == nr && p.c == nc) return false;\n            }\n        }\n    }\n    return true;\n}\n\n// Find the index of the nearest pet\nint get_nearest_pet(Point h) {\n    int min_dist = 1000;\n    int target = -1;\n    for (int i = 0; i < N; ++i) {\n        int d = abs(h.r - pets[i].r) + abs(h.c - pets[i].c);\n        if (d < min_dist) {\n            min_dist = d;\n            target = i;\n        }\n    }\n    return target;\n}\n\n// BFS to find the next move towards the target\nPoint get_next_move(Point start, Point target) {\n    if (start.r == target.r && start.c == target.c) return start;\n    \n    queue<pair<Point, Point>> q; // {current, first_step}\n    bool visited[30][30] = {false};\n    \n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    \n    // Check initial neighbors\n    for (int i = 0; i < 4; ++i) {\n        int nr = start.r + dr[i];\n        int nc = start.c + dc[i];\n        if (is_valid(nr, nc) && !impassable[nr][nc]) {\n            bool occupied = false;\n            for(auto& h : humans) if(h.r == nr && h.c == nc) occupied = true;\n            if(!occupied) {\n                q.push({{nr, nc}, {nr, nc}});\n                visited[nr][nc] = true;\n            }\n        }\n    }\n    \n    while (!q.empty()) {\n        auto [curr, first] = q.front();\n        q.pop();\n        \n        if (curr.r == target.r && curr.c == target.c) return first;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n            if (is_valid(nr, nc) && !impassable[nr][nc] && !visited[nr][nc]) {\n                bool occupied = false;\n                for(auto& h : humans) if(h.r == nr && h.c == nc) occupied = true;\n                if(!occupied) {\n                    visited[nr][nc] = true;\n                    q.push({{nr, nc}, first});\n                }\n            }\n        }\n    }\n    return start; // No path found\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N;\n    pets.resize(N);\n    pet_types.resize(N);\n    for (int i = 0; i < N; ++i) cin >> pets[i].r >> pets[i].c >> pet_types[i];\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) cin >> humans[i].r >> humans[i].c;\n    \n    for (int i = 0; i < 30; ++i) for (int j = 0; j < 30; ++j) impassable[i][j] = false;\n    \n    for (int turn = 0; turn < 300; ++turn) {\n        vector<string> actions(M, \".\");\n        \n        for (int i = 0; i < M; ++i) {\n            int target_idx = get_nearest_pet(humans[i]);\n            if (target_idx == -1) continue;\n            \n            Point pet = pets[target_idx];\n            bool built = false;\n            int dr[] = {0, 0, 1, -1};\n            int dc[] = {1, -1, 0, 0};\n            char wall_chars[] = {'r', 'l', 'd', 'u'};\n            \n            // Try to build a wall near the target pet to trap it\n            for (int k = 0; k < 4; ++k) {\n                int nr = humans[i].r + dr[k];\n                int nc = humans[i].c + dc[k];\n                \n                if (abs(nr - pet.r) + abs(nc - pet.c) <= 2) {\n                    if (can_build(nr, nc)) {\n                        string s(1, wall_chars[k]);\n                        actions[i] = s;\n                        impassable[nr][nc] = true;\n                        built = true;\n                        break;\n                    }\n                }\n            }\n            \n            // If not building, move towards the pet\n            if (!built) {\n                Point next = get_next_move(humans[i], pet);\n                if (!(next == humans[i])) {\n                    if (next.r < humans[i].r) actions[i] = \"U\";\n                    else if (next.r > humans[i].r) actions[i] = \"D\";\n                    else if (next.c < humans[i].c) actions[i] = \"L\";\n                    else if (next.c > humans[i].c) actions[i] = \"R\";\n                    humans[i] = next;\n                }\n            }\n        }\n        \n        // Output actions for this turn\n        for (int i = 0; i < M; ++i) cout << actions[i];\n        cout << endl;\n        \n        // Update pets' positions based on their movements\n        for (int i = 0; i < N; ++i) {\n            string move;\n            cin >> move;\n            for (char c : move) {\n                if (c == 'U') pets[i].r--;\n                else if (c == 'D') pets[i].r++;\n                else if (c == 'L') pets[i].c--;\n                else if (c == 'R') pets[i].c++;\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Node for path reconstruction\nstruct Node {\n    int parent;\n    char move;\n};\n\n// Fixed-size State for Beam Search to minimize allocation overhead\nstruct BeamState {\n    int node_idx;\n    double dist[400]; // Probabilities for each cell\n    double reward;\n    double prob_reached;\n    double expected_total_reward;\n    bool finished; // Optimization: stop propagating if reached\n};\n\nint Si, Sj, Ti, Tj;\ndouble P;\nvector<string> H, V;\nint min_dist_to_office[400];\n\n// Compute shortest path distance using BFS\nvoid compute_min_dist() {\n    for (int i = 0; i < 400; ++i) min_dist_to_office[i] = 1000;\n    queue<int> q;\n    q.push(Ti * 20 + Tj);\n    min_dist_to_office[Ti * 20 + Tj] = 0;\n\n    while (!q.empty()) {\n        int curr = q.front();\n        q.pop();\n        int r = curr / 20;\n        int c = curr % 20;\n\n        if (r > 0 && V[r - 1][c] == '0' && min_dist_to_office[(r - 1) * 20 + c] == 1000) {\n            min_dist_to_office[(r - 1) * 20 + c] = min_dist_to_office[curr] + 1;\n            q.push((r - 1) * 20 + c);\n        }\n        if (r < 19 && V[r][c] == '0' && min_dist_to_office[(r + 1) * 20 + c] == 1000) {\n            min_dist_to_office[(r + 1) * 20 + c] = min_dist_to_office[curr] + 1;\n            q.push((r + 1) * 20 + c);\n        }\n        if (c > 0 && H[r][c - 1] == '0' && min_dist_to_office[r * 20 + c - 1] == 1000) {\n            min_dist_to_office[r * 20 + c - 1] = min_dist_to_office[curr] + 1;\n            q.push(r * 20 + c - 1);\n        }\n        if (c < 19 && H[r][c] == '0' && min_dist_to_office[r * 20 + c + 1] == 1000) {\n            min_dist_to_office[r * 20 + c + 1] = min_dist_to_office[curr] + 1;\n            q.push(r * 20 + c + 1);\n        }\n    }\n}\n\ninline bool can_move(int r, int c, char dir) {\n    if (dir == 'U') return r > 0 && V[r - 1][c] == '0';\n    if (dir == 'D') return r < 19 && V[r][c] == '0';\n    if (dir == 'L') return c > 0 && H[r][c - 1] == '0';\n    if (dir == 'R') return c < 19 && H[r][c] == '0';\n    return false;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> Si >> Sj >> Ti >> Tj >> P)) return 0;\n    H.resize(20);\n    for (int i = 0; i < 20; ++i) cin >> H[i];\n    V.resize(19);\n    for (int i = 0; i < 19; ++i) cin >> V[i];\n\n    compute_min_dist();\n\n    vector<Node> all_nodes;\n    all_nodes.reserve(300000);\n    all_nodes.push_back({-1, ' '}); // Dummy root\n\n    vector<BeamState> beam;\n    beam.reserve(1200);\n    BeamState initial;\n    initial.node_idx = 0;\n    for (int i = 0; i < 400; ++i) initial.dist[i] = 0.0;\n    initial.dist[Si * 20 + Sj] = 1.0;\n    initial.reward = 0.0;\n    initial.prob_reached = 0.0;\n    initial.finished = false;\n    double h = (double)min_dist_to_office[Si * 20 + Sj];\n    initial.expected_total_reward = 0.0 + (1.0 - 0.0) * max(0.0, 401.0 - h);\n    beam.push_back(initial);\n\n    int K = 1000; // Increased beam width\n    for (int t = 1; t <= 200; ++t) {\n        vector<BeamState> next_beam;\n        next_beam.reserve(beam.size() * 4);\n        for (const auto& s : beam) {\n            if (s.finished) {\n                next_beam.push_back(s);\n                continue;\n            }\n\n            for (char dir : {'U', 'D', 'L', 'R'}) {\n                BeamState next_s;\n                next_s.prob_reached = s.prob_reached;\n                next_s.reward = s.reward;\n                next_s.finished = false;\n                for (int i = 0; i < 400; ++i) next_s.dist[i] = 0.0;\n\n                double prob_reach_at_t = 0.0;\n\n                for (int curr = 0; curr < 400; ++curr) {\n                    if (s.dist[curr] < 1e-9) continue; // Threshold\n                    \n                    int r = curr / 20;\n                    int c = curr % 20;\n                    \n                    // Forgetting: agent stays\n                    next_s.dist[curr] += s.dist[curr] * P;\n                    \n                    // Moving: attempts to move\n                    if (can_move(r, c, dir)) {\n                        int nr = r, nc = c;\n                        if (dir == 'U') nr--;\n                        else if (dir == 'D') nr++;\n                        else if (dir == 'L') nc--;\n                        else if (dir == 'R') nc++;\n                        \n                        if (nr == Ti && nc == Tj) {\n                            prob_reach_at_t += s.dist[curr] * (1.0 - P);\n                        } else {\n                            next_s.dist[nr * 20 + nc] += s.dist[curr] * (1.0 - P);\n                        }\n                    } else {\n                        // Wall, stay\n                        next_s.dist[curr] += s.dist[curr] * (1.0 - P);\n                    }\n                }\n                \n                next_s.prob_reached += prob_reach_at_t;\n                next_s.reward += prob_reach_at_t * (401.0 - t);\n                \n                if (next_s.prob_reached >= 1.0 - 1e-12) {\n                    next_s.finished = true;\n                }\n                \n                double h_val = 0.0;\n                for (int i = 0; i < 400; ++i) {\n                    if (next_s.dist[i] > 1e-9)\n                        h_val += next_s.dist[i] * min_dist_to_office[i];\n                }\n                \n                double remaining_time = 401.0 - t - h_val;\n                if (remaining_time < 0) remaining_time = 0;\n                next_s.expected_total_reward = next_s.reward + (1.0 - next_s.prob_reached) * remaining_time;\n                \n                next_s.node_idx = all_nodes.size();\n                all_nodes.push_back({s.node_idx, dir});\n                next_beam.push_back(next_s);\n            }\n        }\n        \n        if (next_beam.size() > (size_t)K) {\n            nth_element(next_beam.begin(), next_beam.begin() + K, next_beam.end(), [](const BeamState& a, const BeamState& b) {\n                return a.expected_total_reward > b.expected_total_reward;\n            });\n            next_beam.resize(K);\n        }\n        beam = next_beam;\n    }\n    \n    sort(beam.begin(), beam.end(), [](const BeamState& a, const BeamState& b) {\n        return a.expected_total_reward > b.expected_total_reward;\n    });\n    \n    string path = \"\";\n    int curr_node = beam[0].node_idx;\n    while (all_nodes[curr_node].parent != -1) {\n        path += all_nodes[curr_node].move;\n        curr_node = all_nodes[curr_node].parent;\n    }\n    reverse(path.begin(), path.end());\n    cout << path << endl;\n    \n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <cstring>\n\nusing namespace std;\n\n// Precomputed connectivity: conn[type][rotation][in_direction] = out_direction\n// Directions: 0: Left, 1: Up, 2: Right, 3: Down\nint conn[8][4][4];\n\nvoid precompute_conn() {\n    int base_to[8][4] = {\n        {1, 0, -1, -1}, {3, -1, -1, 0}, {-1, -1, 3, 2}, {-1, 2, 1, -1},\n        {1, 0, 3, 2},   {3, 2, 1, 0},   {2, -1, 0, -1}, {-1, 3, -1, 1}\n    };\n    for (int t = 0; t < 8; ++t) {\n        for (int r = 0; r < 4; ++r) {\n            for (int d = 0; d < 4; ++d) {\n                int d_old = (d + r) % 4;\n                int d_old_exit = base_to[t][d_old];\n                conn[t][r][d] = (d_old_exit == -1) ? -1 : (d_old_exit - r + 4) % 4;\n            }\n        }\n    }\n}\n\nint N = 30;\nint tiles[30][30];\nint r[30][30];\n\n// Use a flat 1D array for visited to optimize access\nint visited[3600]; \nint visit_gen = 0;\n\n// Highly optimized score calculation\ninline long long calculate_score() {\n    visit_gen++;\n    if (visit_gen > 1000000000) {\n        memset(visited, 0, sizeof(visited));\n        visit_gen = 1;\n    }\n    \n    int max1 = 0, max2 = 0;\n    \n    for (int i = 0; i < 900; ++i) {\n        int r_i = i / 30;\n        int c_i = i % 30;\n        for (int d = 0; d < 4; ++d) {\n            int v_idx = (i << 2) + d;\n            if (visited[v_idx] == visit_gen) continue;\n            \n            int curr_idx = i;\n            int curr_d = d;\n            int length = 0;\n            int start_idx = curr_idx;\n            int start_d = curr_d;\n            bool closed = false;\n            \n            while (true) {\n                int v_curr = (curr_idx << 2) + curr_d;\n                if (visited[v_curr] == visit_gen) break;\n                visited[v_curr] = visit_gen;\n                \n                int curr_r = curr_idx / 30;\n                int curr_c = curr_idx % 30;\n                \n                int next_d = conn[tiles[curr_r][curr_c]][r[curr_r][curr_c]][curr_d];\n                if (next_d == -1) break;\n                \n                int next_idx = curr_idx;\n                if (next_d == 0) next_idx -= 1;\n                else if (next_d == 1) next_idx -= 30;\n                else if (next_d == 2) next_idx += 1;\n                else if (next_d == 3) next_idx += 30;\n                \n                int next_r = next_idx / 30;\n                int next_c = next_idx % 30;\n                \n                // Manual boundary check\n                if (next_r < 0 || next_r >= 30 || next_c < 0 || next_c >= 30) break;\n                \n                curr_idx = next_idx;\n                curr_d = (next_d + 2) % 4;\n                length++;\n                \n                if (curr_idx == start_idx && curr_d == start_d) {\n                    closed = true;\n                    break;\n                }\n            }\n            \n            if (closed) {\n                if (length > max1) { max2 = max1; max1 = length; }\n                else if (length > max2) { max2 = length; }\n            }\n        }\n    }\n    return (long long)max1 * max2;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    precompute_conn();\n    for (int i = 0; i < N; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; ++j) {\n            tiles[i][j] = s[j] - '0';\n            r[i][j] = 0; \n        }\n    }\n    \n    int best_r[30][30];\n    memcpy(best_r, r, sizeof(r));\n    long long best_score = calculate_score();\n    \n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    double time_limit = 1.85; \n    \n    int num_restarts = 3;\n    for (int restart = 0; restart < num_restarts; ++restart) {\n        if (restart > 0) {\n            for(int i=0; i<N; ++i) for(int j=0; j<N; ++j) r[i][j] = rng() % 4;\n        }\n        \n        long long current_score = calculate_score();\n        int iterations = 0;\n        while (true) {\n            if ((iterations & 511) == 0) {\n                if (chrono::duration<double>(chrono::steady_clock::now() - start_time).count() > time_limit) goto end_loops;\n            }\n            iterations++;\n            \n            int i = rng() % 900;\n            int old_r = r[i / 30][i % 30];\n            r[i / 30][i % 30] = rng() % 4;\n            \n            long long new_score = calculate_score();\n            \n            double progress = chrono::duration<double>(chrono::steady_clock::now() - start_time).count() / time_limit;\n            double T = 1000.0 * pow(0.001, progress); \n            double prob = (new_score >= current_score) ? 1.0 : exp((double)(new_score - current_score) / (T + 1e-9));\n            \n            if (new_score > best_score) {\n                best_score = new_score;\n                memcpy(best_r, r, sizeof(r));\n            }\n            \n            if (prob > (double)rng() / rng.max()) current_score = new_score;\n            else r[i / 30][i % 30] = old_r;\n        }\n    }\n    \n    end_loops:\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) cout << best_r[i][j];\n    }\n    cout << endl;\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <chrono>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent the board\nstruct Board {\n    int N;\n    vector<int> tiles;\n    int empty_r, empty_c;\n\n    Board(int n, const vector<int>& t) : N(n), tiles(t) {\n        for (int i = 0; i < N * N; ++i) {\n            if (tiles[i] == 0) {\n                empty_r = i / N;\n                empty_c = i % N;\n            }\n        }\n    }\n\n    bool apply(char move) {\n        int nr = empty_r, nc = empty_c;\n        if (move == 'U') nr--;\n        else if (move == 'D') nr++;\n        else if (move == 'L') nc--;\n        else if (move == 'R') nc++;\n        else return false;\n\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n\n        swap(tiles[empty_r * N + empty_c], tiles[nr * N + nc]);\n        empty_r = nr;\n        empty_c = nc;\n        return true;\n    }\n};\n\nchar reverse_move(char m) {\n    if (m == 'U') return 'D';\n    if (m == 'D') return 'U';\n    if (m == 'L') return 'R';\n    if (m == 'R') return 'L';\n    return ' ';\n}\n\n// DSU structure for tree connectivity checking\nstruct DSU {\n    vector<int> parent;\n    vector<int> nodes;\n    vector<int> edges;\n\n    DSU(int n) {\n        parent.resize(n);\n        nodes.resize(n, 1);\n        edges.resize(n, 0);\n        for (int i = 0; i < n; ++i) parent[i] = i;\n    }\n\n    int find(int i) {\n        if (parent[i] == i) return i;\n        return parent[i] = find(parent[i]);\n    }\n\n    void unite(int i, int j) {\n        int root_i = find(i);\n        int root_j = find(j);\n        if (root_i != root_j) {\n            parent[root_j] = root_i;\n            nodes[root_i] += nodes[root_j];\n            edges[root_i] += edges[root_j] + 1;\n        } else {\n            edges[root_i]++;\n        }\n    }\n};\n\nint calculate_score(const Board& b) {\n    int N = b.N;\n    DSU dsu(N * N);\n    \n    for (int i = 0; i < N * N; ++i) {\n        if (b.tiles[i] == 0) dsu.nodes[i] = 0;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int u = i * N + j;\n            if (b.tiles[u] == 0) continue;\n\n            if (j + 1 < N && b.tiles[i * N + j + 1] != 0) {\n                if ((b.tiles[u] & 4) && (b.tiles[i * N + j + 1] & 1)) {\n                    dsu.unite(u, i * N + j + 1);\n                }\n            }\n            if (i + 1 < N && b.tiles[(i + 1) * N + j] != 0) {\n                if ((b.tiles[u] & 8) && (b.tiles[(i + 1) * N + j] & 2)) {\n                    dsu.unite(u, (i + 1) * N + j);\n                }\n            }\n        }\n    }\n\n    int max_s = 0;\n    for (int i = 0; i < N * N; ++i) {\n        if (dsu.parent[i] == i && dsu.nodes[i] > 0) {\n            if (dsu.edges[i] == dsu.nodes[i] - 1) {\n                max_s = max(max_s, dsu.nodes[i]);\n            }\n        }\n    }\n    return max_s;\n}\n\nint hex_to_int(char c) {\n    if (c >= '0' && c <= '9') return c - '0';\n    return c - 'a' + 10;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, T;\n    cin >> N >> T;\n    vector<int> tiles(N * N);\n    string s;\n    for (int i = 0; i < N; ++i) {\n        cin >> s;\n        for (int j = 0; j < N; ++j) {\n            tiles[i * N + j] = hex_to_int(s[j]);\n        }\n    }\n\n    Board initial_board(N, tiles);\n    string best_moves = \"\";\n    int best_S = calculate_score(initial_board);\n\n    auto start_time = chrono::steady_clock::now();\n    mt19937 rng(42);\n    \n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 2800) {\n        Board current_board = initial_board;\n        string current_moves = \"\";\n        int current_S = calculate_score(current_board);\n        \n        for (int i = 0; i < T; ++i) {\n            if (best_S == N * N - 1 && current_moves.size() >= best_moves.size() && !best_moves.empty()) break;\n\n            vector<char> moves = {'U', 'D', 'L', 'R'};\n            shuffle(moves.begin(), moves.end(), rng);\n            \n            char best_move = ' ';\n            int best_move_S = -1;\n\n            for (char move : moves) {\n                Board next_board = current_board;\n                if (next_board.apply(move)) {\n                    int next_S = calculate_score(next_board);\n                    if (next_S > best_move_S) {\n                        best_move_S = next_S;\n                        best_move = move;\n                    }\n                }\n            }\n            \n            if (best_move != ' ' && best_move_S >= current_S) {\n                current_board.apply(best_move);\n                current_moves += best_move;\n                current_S = best_move_S;\n                if (current_S > best_S) {\n                    best_S = current_S;\n                    best_moves = current_moves;\n                } else if (current_S == best_S && best_S == N * N - 1) {\n                    if (best_moves.empty() || current_moves.size() < best_moves.size()) {\n                        best_moves = current_moves;\n                    }\n                }\n            } else {\n                int walk_len = 8;\n                char last_move = ' ';\n                for(int k = 0; k < walk_len; ++k) {\n                    shuffle(moves.begin(), moves.end(), rng);\n                    bool moved = false;\n                    for(char move : moves) {\n                        if (move == reverse_move(last_move)) continue;\n                        if(current_board.apply(move)) {\n                            current_moves += move;\n                            current_S = calculate_score(current_board);\n                            last_move = move;\n                            moved = true;\n                            break;\n                        }\n                    }\n                    if (!moved) break;\n                }\n            }\n            \n            if (current_moves.size() >= T) break;\n        }\n    }\n    \n    cout << best_moves << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent a point\nstruct Point {\n    long long x, y;\n};\n\n// Structure to represent a line: ax + by + c = 0\nstruct Line {\n    long long a, b, c;\n    Point p1, p2;\n};\n\n// Global data\nint N, K;\nvector<int> a(11);\nvector<Point> strawberries;\nmt19937 rng(1337);\n\n// Function to calculate the score: sum(min(a_d, b_d))\nint calculate_score(const vector<int>& piece_counts) {\n    vector<int> b(11, 0);\n    for (int count : piece_counts) {\n        if (count >= 1 && count <= 10) {\n            b[count]++;\n        }\n    }\n    int score = 0;\n    for (int d = 1; d <= 10; ++d) {\n        score += min(a[d], b[d]);\n    }\n    return score;\n}\n\n// Generate a random line that intersects the cake\nLine generate_random_line() {\n    // Generate points within [-20000, 20000] to cover the cake radius of 10000\n    uniform_int_distribution<long long> dist(-20000, 20000);\n    while (true) {\n        Point p1 = {dist(rng), dist(rng)};\n        Point p2 = {dist(rng), dist(rng)};\n        if (p1.x == p2.x && p1.y == p2.y) continue;\n\n        // Line equation: (y1 - y2)x + (x2 - x1)y + (x1y2 - x2y1) = 0\n        long long a = p1.y - p2.y;\n        long long b = p2.x - p1.x;\n        long long c = -a * p1.x - b * p1.y;\n\n        // Check if the line cuts the cake (distance from origin < 10000)\n        __int128 c2 = (__int128)c * c;\n        __int128 dist2 = (__int128)a * a + (__int128)b * b;\n        if (c2 < (__int128)100000000 * dist2) {\n            return {a, b, c, p1, p2};\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N >> K)) return 0;\n    for (int i = 1; i <= 10; ++i) cin >> a[i];\n    strawberries.resize(N);\n    for (int i = 0; i < N; ++i) cin >> strawberries[i].x >> strawberries[i].y;\n\n    // current_piece_id[i] stores the ID of the piece that strawberry i belongs to\n    vector<int> current_piece_id(N, 0);\n    int num_pieces = 1;\n    vector<Line> lines;\n\n    for (int k = 0; k < K; ++k) {\n        int best_score = -1;\n        Line best_line;\n        bool found = false;\n\n        // Try 1000 random lines and pick the best one\n        for (int trial = 0; trial < 1000; ++trial) {\n            Line line = generate_random_line();\n            \n            // Piece split: how many strawberries in each piece fall on the left/right side\n            // piece_split[p_id].first = count on left, .second = count on right\n            vector<pair<int, int>> piece_split(num_pieces, {0, 0});\n            for (int i = 0; i < N; ++i) {\n                if (current_piece_id[i] == -1) continue;\n                long long val = line.a * strawberries[i].x + line.b * strawberries[i].y + line.c;\n                if (val > 0) piece_split[current_piece_id[i]].second++;\n                else if (val < 0) piece_split[current_piece_id[i]].first++;\n                // val == 0 means the strawberry is on the line (removed)\n            }\n\n            vector<int> next_piece_counts;\n            for (int p = 0; p < num_pieces; ++p) {\n                if (piece_split[p].first > 0) next_piece_counts.push_back(piece_split[p].first);\n                if (piece_split[p].second > 0) next_piece_counts.push_back(piece_split[p].second);\n            }\n\n            int score = calculate_score(next_piece_counts);\n            if (score > best_score) {\n                best_score = score;\n                best_line = line;\n                found = true;\n            }\n        }\n        \n        if (found) {\n            lines.push_back(best_line);\n            \n            // Update current_piece_id mapping for all strawberries\n            vector<int> next_piece_id(N, -1);\n            // new_id_map[old_piece_id][side] -> new_piece_id\n            vector<vector<int>> new_id_map(num_pieces, vector<int>(2, -1));\n            int next_num_pieces = 0;\n\n            for (int i = 0; i < N; ++i) {\n                if (current_piece_id[i] == -1) continue;\n                long long val = best_line.a * strawberries[i].x + best_line.b * strawberries[i].y + best_line.c;\n                if (val == 0) continue; // Strawberry removed\n                \n                int side = (val > 0) ? 1 : 0;\n                int p = current_piece_id[i];\n                \n                if (new_id_map[p][side] == -1) {\n                    new_id_map[p][side] = next_num_pieces++;\n                }\n                next_piece_id[i] = new_id_map[p][side];\n            }\n            current_piece_id = next_piece_id;\n            num_pieces = next_num_pieces;\n        } else {\n            // No improvement found, stop cutting\n            break;\n        }\n    }\n\n    // Output the result\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line.p1.x << \" \" << line.p1.y << \" \" << line.p2.x << \" \" << line.p2.y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <queue>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nstruct Rectangle {\n    Point p[4];\n};\n\nint N, M;\nvector<vector<bool>> has_dot;\nvector<Rectangle> all_rects;\nvector<vector<int>> potential_rects;\nvector<int> occupied_count;\nvector<bool> is_used_rect;\n\n// Segment status arrays\nbool used_h[65][65];\nbool used_v[65][65];\nbool used_d1[130][65]; // diag1: y-x+N. length = dx\nbool used_d2[130][65]; // diag2: y+x. length = dx\n\nbool is_valid_coord(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nvoid add_rect(Point p1, Point p2, Point p3, Point p4) {\n    if (is_valid_coord(p1.x, p1.y) && is_valid_coord(p2.x, p2.y) && is_valid_coord(p3.x, p3.y) && is_valid_coord(p4.x, p4.y)) {\n        all_rects.push_back({{p1, p2, p3, p4}});\n        int id = (int)all_rects.size() - 1;\n        potential_rects[p1.x * N + p1.y].push_back(id);\n        potential_rects[p2.x * N + p2.y].push_back(id);\n        potential_rects[p3.x * N + p3.y].push_back(id);\n        potential_rects[p4.x * N + p4.y].push_back(id);\n    }\n}\n\nint weight(int x, int y) {\n    int cx = (N - 1) / 2;\n    int cy = (N - 1) / 2;\n    return (x - cx) * (x - cx) + (y - cy) * (y - cy) + 1;\n}\n\nstruct Segment {\n    int type; // 0: h, 1: v, 2: d1, 3: d2\n    int x, y;\n};\n\nvector<Segment> get_segments(const Rectangle& r) {\n    vector<Segment> segs;\n    auto add_seg = [&](Point a, Point b) {\n        int dx = b.x - a.x, dy = b.y - a.y;\n        int dist = max(abs(dx), abs(dy));\n        int sx = (dist == 0) ? 0 : dx / dist;\n        int sy = (dist == 0) ? 0 : dy / dist;\n        for (int i = 0; i < dist; ++i) {\n            int x1 = a.x + i * sx, y1 = a.y + i * sy;\n            int x2 = x1 + sx, y2 = y1 + sy;\n            if (sy == 0) segs.push_back({0, min(x1, x2), y1});\n            else if (sx == 0) segs.push_back({1, x1, min(y1, y2)});\n            else if (sx == sy) segs.push_back({2, y1 - x1 + N, min(x1, x2)});\n            else segs.push_back({3, y1 + x1, min(x1, x2)});\n        }\n    };\n    add_seg(r.p[0], r.p[1]); add_seg(r.p[1], r.p[2]);\n    add_seg(r.p[2], r.p[3]); add_seg(r.p[3], r.p[0]);\n    return segs;\n}\n\nbool check_rect_validity(int rect_id) {\n    const auto& r = all_rects[rect_id];\n    for (const auto& seg : get_segments(r)) {\n        if (seg.type == 0 && used_h[seg.x][seg.y]) return false;\n        if (seg.type == 1 && used_v[seg.x][seg.y]) return false;\n        if (seg.type == 2 && used_d1[seg.x][seg.y]) return false;\n        if (seg.type == 3 && used_d2[seg.x][seg.y]) return false;\n    }\n    auto add_pts = [&](Point a, Point b) {\n        int dx = b.x - a.x, dy = b.y - a.y;\n        int dist = max(abs(dx), abs(dy));\n        int sx = (dist == 0) ? 0 : dx / dist;\n        int sy = (dist == 0) ? 0 : dy / dist;\n        for (int i = 1; i < dist; ++i) {\n            if (has_dot[a.x + i * sx][a.y + i * sy]) return true;\n        }\n        return false;\n    };\n    if (add_pts(r.p[0], r.p[1])) return false;\n    if (add_pts(r.p[1], r.p[2])) return false;\n    if (add_pts(r.p[2], r.p[3])) return false;\n    if (add_pts(r.p[3], r.p[0])) return false;\n    return true;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n    cin >> N >> M;\n    has_dot.assign(N, vector<bool>(N, false));\n    potential_rects.assign(N * N, vector<int>());\n    for (int i = 0; i < M; ++i) {\n        int x, y; cin >> x >> y;\n        has_dot[x][y] = true;\n    }\n\n    for (int x1 = 0; x1 < N; ++x1)\n        for (int x2 = x1 + 1; x2 < N; ++x2)\n            for (int y1 = 0; y1 < N; ++y1)\n                for (int y2 = y1 + 1; y2 < N; ++y2)\n                    add_rect({x1, y1}, {x2, y1}, {x2, y2}, {x1, y2});\n\n    for (int x = 0; x < N; ++x)\n        for (int y = 0; y < N; ++y)\n            for (int d = 1; d < N; ++d)\n                for (int k = 1; k < N; ++k)\n                    add_rect({x, y}, {x + d, y + d}, {x + d + k, y + d - k}, {x + k, y - k});\n\n    occupied_count.assign(all_rects.size(), 0);\n    is_used_rect.assign(all_rects.size(), false);\n    priority_queue<pair<int, int>> pq;\n\n    for (int i = 0; i < (int)all_rects.size(); ++i) {\n        for (int j = 0; j < 4; ++j)\n            if (has_dot[all_rects[i].p[j].x][all_rects[i].p[j].y]) occupied_count[i]++;\n        if (occupied_count[i] == 3) {\n            int empty_idx = -1;\n            for(int j=0; j<4; ++j) if(!has_dot[all_rects[i].p[j].x][all_rects[i].p[j].y]) empty_idx = j;\n            if(empty_idx != -1)\n                pq.push({weight(all_rects[i].p[empty_idx].x, all_rects[i].p[empty_idx].y), i});\n        }\n    }\n\n    struct Op { int rect_id; int p_new_idx; };\n    vector<Op> final_ops;\n\n    while (!pq.empty()) {\n        auto [w, id] = pq.top(); pq.pop();\n        if (is_used_rect[id] || occupied_count[id] != 3 || !check_rect_validity(id)) continue;\n\n        int empty_idx = -1;\n        for (int j = 0; j < 4; ++j)\n            if (!has_dot[all_rects[id].p[j].x][all_rects[id].p[j].y]) { empty_idx = j; break; }\n        \n        has_dot[all_rects[id].p[empty_idx].x][all_rects[id].p[empty_idx].y] = true;\n        is_used_rect[id] = true;\n        final_ops.push_back({id, empty_idx});\n\n        for (const auto& seg : get_segments(all_rects[id])) {\n            if (seg.type == 0) used_h[seg.x][seg.y] = true;\n            else if (seg.type == 1) used_v[seg.x][seg.y] = true;\n            else if (seg.type == 2) used_d1[seg.x][seg.y] = true;\n            else if (seg.type == 3) used_d2[seg.x][seg.y] = true;\n        }\n\n        int new_x = all_rects[id].p[empty_idx].x;\n        int new_y = all_rects[id].p[empty_idx].y;\n        for (int rect_id : potential_rects[new_x * N + new_y]) {\n            occupied_count[rect_id]++;\n            if (occupied_count[rect_id] == 3) {\n                int e_idx = -1;\n                for(int j=0; j<4; ++j) if(!has_dot[all_rects[rect_id].p[j].x][all_rects[rect_id].p[j].y]) e_idx = j;\n                if (e_idx != -1)\n                    pq.push({weight(all_rects[rect_id].p[e_idx].x, all_rects[rect_id].p[e_idx].y), rect_id});\n            }\n        }\n    }\n\n    cout << final_ops.size() << endl;\n    for (const auto& op : final_ops) {\n        const auto& r = all_rects[op.rect_id];\n        int idx = op.p_new_idx;\n        cout << r.p[idx].x << \" \" << r.p[idx].y << \" \" \n             << r.p[(idx + 1) % 4].x << \" \" << r.p[(idx + 1) % 4].y << \" \"\n             << r.p[(idx + 2) % 4].x << \" \" << r.p[(idx + 2) % 4].y << \" \"\n             << r.p[(idx + 3) % 4].x << \" \" << r.p[(idx + 3) % 4].y << endl;\n    }\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <cstring>\n#include <algorithm>\n\nusing namespace std;\n\n// Fast PRNG to speed up simulation\nstruct XorShift {\n    uint32_t x = 123456789, y = 362436069, z = 521288629, w = 88675123;\n    uint32_t next() {\n        uint32_t t = x ^ (x << 11);\n        x = y; y = z; z = w;\n        return w = w ^ (w >> 19) ^ t ^ (t >> 8);\n    }\n    int nextInt(int n) { return next() % n; }\n} rng;\n\nstruct Board {\n    int cell[100];\n};\n\n// Optimized board tilting\nvoid apply_tilt(Board& b, char dir) {\n    if (dir == 'F') {\n        for (int c = 0; c < 10; ++c) {\n            int write = 0;\n            for (int r = 0; r < 10; ++r) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[write * 10 + c] = v;\n                    write++;\n                }\n            }\n        }\n    } else if (dir == 'B') {\n        for (int c = 0; c < 10; ++c) {\n            int write = 9;\n            for (int r = 9; r >= 0; --r) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[write * 10 + c] = v;\n                    write--;\n                }\n            }\n        }\n    } else if (dir == 'L') {\n        for (int r = 0; r < 10; ++r) {\n            int write = 0;\n            for (int c = 0; c < 10; ++c) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[r * 10 + write] = v;\n                    write++;\n                }\n            }\n        }\n    } else if (dir == 'R') {\n        for (int r = 0; r < 10; ++r) {\n            int write = 9;\n            for (int c = 9; c >= 0; --c) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[r * 10 + write] = v;\n                    write--;\n                }\n            }\n        }\n    }\n}\n\n// Optimized BFS for scoring\nint calculate_score(const Board& b) {\n    int score = 0;\n    bool visited[100] = {false};\n    for (int i = 0; i < 100; ++i) {\n        if (b.cell[i] == 0 || visited[i]) continue;\n        int flavor = b.cell[i];\n        int count = 0;\n        int q[100];\n        int head = 0, tail = 0;\n        q[tail++] = i;\n        visited[i] = true;\n        while (head < tail) {\n            int curr = q[head++];\n            count++;\n            int r = curr / 10;\n            int c = curr % 10;\n            if (r > 0 && !visited[curr - 10] && b.cell[curr - 10] == flavor) {\n                visited[curr - 10] = true;\n                q[tail++] = curr - 10;\n            }\n            if (r < 9 && !visited[curr + 10] && b.cell[curr + 10] == flavor) {\n                visited[curr + 10] = true;\n                q[tail++] = curr + 10;\n            }\n            if (c > 0 && !visited[curr - 1] && b.cell[curr - 1] == flavor) {\n                visited[curr - 1] = true;\n                q[tail++] = curr - 1;\n            }\n            if (c < 9 && !visited[curr + 1] && b.cell[curr + 1] == flavor) {\n                visited[curr + 1] = true;\n                q[tail++] = curr + 1;\n            }\n        }\n        score += count * count;\n    }\n    return score;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    vector<int> f(100);\n    for (int i = 0; i < 100; ++i) cin >> f[i];\n\n    Board b;\n    memset(b.cell, 0, sizeof(b.cell));\n    char directions[] = {'F', 'B', 'L', 'R'};\n\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        cin >> p;\n        // Place candy\n        int count = 0;\n        for (int i = 0; i < 100; ++i) {\n            if (b.cell[i] == 0) {\n                count++;\n                if (count == p) {\n                    b.cell[i] = f[t];\n                    break;\n                }\n            }\n        }\n\n        if (t == 99) break;\n\n        // Perform simulations with fixed budget to avoid TLE\n        int num_rollouts = 300; \n        double max_score = -1.0;\n        char best_dir = 'F';\n\n        for (char d : directions) {\n            double total_score = 0;\n            for (int r = 0; r < num_rollouts; ++r) {\n                Board sim_b = b;\n                apply_tilt(sim_b, d);\n                \n                // Rollout\n                for (int st = t + 1; st < 100; ++st) {\n                    // Optimized empty cell finding\n                    int next_pos = rng.nextInt(100);\n                    while (sim_b.cell[next_pos] != 0) {\n                        next_pos++;\n                        if (next_pos == 100) next_pos = 0;\n                    }\n                    sim_b.cell[next_pos] = f[st];\n                    \n                    char sim_dir = directions[rng.nextInt(4)];\n                    apply_tilt(sim_b, sim_dir);\n                }\n                total_score += calculate_score(sim_b);\n            }\n            if (total_score > max_score) {\n                max_score = total_score;\n                best_dir = d;\n            }\n        }\n\n        cout << best_dir << endl;\n        apply_tilt(b, best_dir);\n    }\n\n    return 0;\n}","ahc016":"/*\n * Refined Approach:\n * 1. Optimized Adaptive N:\n *    - N = max(M, 4 + (int)(epsilon * 200))\n *    - Cap N at 100.\n *    - This strategy significantly reduces N for low epsilon, maximizing the 1/N \n *      scoring component while maintaining enough vertices for high-noise cases.\n * 2. Robust Encoding:\n *    - Clique-based graphs with sizes spread uniformly in [1, N].\n *    - Degree sequences provide distinct signatures that are invariant under vertex shuffling.\n * 3. Classification:\n *    - Euclidean distance on sorted degree sequences.\n */\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Structure to hold graph information\nstruct Graph {\n    int id;\n    int clique_size;\n    vector<int> degree_seq;\n    string edges;\n};\n\n// Helper to compute degree sequence from edges string\nvector<int> compute_degree_seq(int N, const string& edges) {\n    vector<int> deg(N, 0);\n    int idx = 0;\n    for (int i = 0; i < N - 1; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (edges[idx] == '1') {\n                deg[i]++;\n                deg[j]++;\n            }\n            idx++;\n        }\n    }\n    sort(deg.begin(), deg.end());\n    return deg;\n}\n\nint main() {\n    // Optimization for I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n\n    // Optimized Adaptive N calculation:\n    // - N >= M is required to encode M distinct graphs.\n    // - N >= 4 is a problem constraint.\n    // - We use 4 + eps * 200 to scale N with noise. This keeps N minimal \n    //   for low noise (improving 1/N score) and provides sufficient \n    //   vertices for high noise.\n    int N = (int)(4 + eps * 200);\n    if (N < M) N = M;\n    if (N > 100) N = 100;\n    if (N < 4) N = 4;\n\n    cout << N << endl;\n\n    vector<Graph> graphs(M);\n    for (int k = 0; k < M; ++k) {\n        graphs[k].id = k;\n        \n        // Distribute clique sizes uniformly in [1, N]\n        // This ensures distinct degree sequences for each graph.\n        if (M == 1) {\n            graphs[k].clique_size = 2; \n        } else {\n            graphs[k].clique_size = 1 + (int)((double)k * (N - 1) / (M - 1));\n        }\n\n        int c = graphs[k].clique_size;\n        \n        // Generate edge string\n        // A clique of size c has edges between all pairs (i, j) where i, j < c.\n        string s = \"\";\n        s.reserve(N * (N - 1) / 2);\n        for (int i = 0; i < N - 1; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (i < c && j < c) {\n                    s += '1';\n                } else {\n                    s += '0';\n                }\n            }\n        }\n        graphs[k].edges = s;\n        graphs[k].degree_seq = compute_degree_seq(N, s);\n    }\n\n    // Output the generated graphs\n    for (int k = 0; k < M; ++k) {\n        cout << graphs[k].edges << endl;\n    }\n\n    // Process 100 queries\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // Compute degree sequence of received graph\n        vector<int> degH = compute_degree_seq(N, H);\n\n        // Find the graph whose degree sequence is closest to H's\n        int best_k = 0;\n        long long min_dist = -1;\n\n        for (int k = 0; k < M; ++k) {\n            long long dist = 0;\n            const vector<int>& degG = graphs[k].degree_seq;\n            // The degree sequence is always length N\n            for (int i = 0; i < N; ++i) {\n                long long diff = (long long)degG[i] - degH[i];\n                dist += diff * diff;\n            }\n            if (min_dist == -1 || dist < min_dist) {\n                min_dist = dist;\n                best_k = k;\n            }\n        }\n        cout << best_k << endl;\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <ctime>\n\nusing namespace std;\n\n// Structure to represent an edge\nstruct Edge {\n    int u, v, w, id;\n};\n\n// Structure for predecessors in shortest path\nstruct Predecessor {\n    int u;\n    int edge_id;\n};\n\nint N, M, D, K;\nvector<vector<pair<int, pair<int, int>>>> adj;\nvector<Edge> edges;\nvector<double> edge_bc;\nvector<double> edge_cost;\n\n// Compute Betweenness Centrality using Brandes' algorithm\n// Suitable for N=1000, M=3000.\nvoid compute_bc() {\n    edge_bc.assign(M, 0.0);\n    for (int s = 0; s < N; ++s) {\n        vector<long long> dist(N + 1, 1e18);\n        vector<double> sigma(N + 1, 0.0);\n        vector<vector<Predecessor>> predecessors(N + 1);\n        vector<int> order;\n        \n        dist[s + 1] = 0;\n        sigma[s + 1] = 1.0;\n        \n        priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n        pq.push({0, s + 1});\n        \n        while (!pq.empty()) {\n            long long d = pq.top().first;\n            int u = pq.top().second;\n            pq.pop();\n            \n            if (d > dist[u]) continue;\n            order.push_back(u);\n            \n            for (auto& edge : adj[u]) {\n                int v = edge.first;\n                int weight = edge.second.first;\n                int id = edge.second.second;\n                \n                if (dist[v] > dist[u] + weight) {\n                    dist[v] = dist[u] + weight;\n                    sigma[v] = sigma[u];\n                    predecessors[v].clear();\n                    predecessors[v].push_back({u, id});\n                    pq.push({dist[v], v});\n                } else if (dist[v] == dist[u] + weight) {\n                    sigma[v] += sigma[u];\n                    predecessors[v].push_back({u, id});\n                }\n            }\n        }\n        \n        vector<double> delta(N + 1, 0.0);\n        for (int i = (int)order.size() - 1; i >= 0; --i) {\n            int w = order[i];\n            for (auto& pred : predecessors[w]) {\n                int v = pred.u;\n                int edge_id = pred.edge_id;\n                \n                double coeff = (sigma[v] / sigma[w]) * (1.0 + delta[w]);\n                delta[v] += coeff;\n                edge_bc[edge_id] += coeff;\n            }\n        }\n    }\n}\n\nint main() {\n    // Optimize I/O\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    if (!(cin >> N >> M >> D >> K)) return 0;\n    adj.resize(N + 1);\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges[i] = {u, v, w, i};\n        adj[u].push_back({v, {w, i}});\n        adj[v].push_back({u, {w, i}});\n    }\n    \n    // Read coordinates (not strictly needed, but format requires reading)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    compute_bc();\n    \n    edge_cost.resize(M);\n    for (int i = 0; i < M; ++i) {\n        edge_cost[i] = edge_bc[i] * (double)edges[i].w;\n    }\n    \n    // Initial assignment: Snake distribution for balanced initial counts and costs\n    vector<int> edge_indices(M);\n    for (int i = 0; i < M; ++i) edge_indices[i] = i;\n    \n    sort(edge_indices.begin(), edge_indices.end(), [&](int a, int b) {\n        return edge_cost[a] > edge_cost[b];\n    });\n    \n    vector<int> schedule(M);\n    vector<vector<int>> days(D + 1);\n    vector<double> sum_cost(D + 1, 0.0);\n    \n    for (int i = 0; i < M; ++i) {\n        int day = (i / D) % 2 == 0 ? (i % D) + 1 : D - (i % D);\n        schedule[edge_indices[i]] = day;\n        days[day].push_back(edge_indices[i]);\n        sum_cost[day] += edge_cost[edge_indices[i]];\n    }\n    \n    // Local Search with targeted and random swaps\n    mt19937 rng(42);\n    double start_time = clock();\n    double time_limit = 5.5 * CLOCKS_PER_SEC;\n    \n    while (clock() - start_time < time_limit) {\n        // Strategy 1: Periodic targeted swap between max/min sum days\n        int d1 = (rng() % D) + 1;\n        int d2 = (rng() % D) + 1;\n        \n        if (rng() % 5 == 0) {\n            d1 = 1; d2 = 1;\n            for (int d = 1; d <= D; ++d) {\n                if (sum_cost[d] > sum_cost[d1]) d1 = d;\n                if (sum_cost[d] < sum_cost[d2]) d2 = d;\n            }\n        }\n        \n        if (d1 == d2 || days[d1].empty() || days[d2].empty()) continue;\n        \n        int idx1 = rng() % days[d1].size();\n        int idx2 = rng() % days[d2].size();\n        \n        int e1 = days[d1][idx1];\n        int e2 = days[d2][idx2];\n        \n        double delta_cost_1 = edge_cost[e2] - edge_cost[e1];\n        double delta_cost_2 = edge_cost[e1] - edge_cost[e2];\n        \n        // Calculate the change in sum of squares of daily costs\n        // We want to minimize sum(sum_cost_d^2), which is variance minimization\n        double new_sum_cost_d1 = sum_cost[d1] + delta_cost_1;\n        double new_sum_cost_d2 = sum_cost[d2] + delta_cost_2;\n        \n        // Only accept swap if it reduces the variance\n        if (new_sum_cost_d1 * new_sum_cost_d1 + new_sum_cost_d2 * new_sum_cost_d2 < \n            sum_cost[d1] * sum_cost[d1] + sum_cost[d2] * sum_cost[d2]) {\n            \n            sum_cost[d1] = new_sum_cost_d1;\n            sum_cost[d2] = new_sum_cost_d2;\n            days[d1][idx1] = e2;\n            days[d2][idx2] = e1;\n            schedule[e1] = d2;\n            schedule[e2] = d1;\n        }\n    }\n    \n    // Output schedule\n    for (int i = 0; i < M; ++i) {\n        cout << schedule[i] << (i == M - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n};\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int D;\n    if (!(cin >> D)) return 0;\n\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for (int i = 0; i < D; ++i) cin >> f1[i];\n    for (int i = 0; i < D; ++i) cin >> r1[i];\n    for (int i = 0; i < D; ++i) cin >> f2[i];\n    for (int i = 0; i < D; ++i) cin >> r2[i];\n\n    // Compute maximum possible objects M1 and M2\n    auto get_max_obj = [&](const vector<string>& f, const vector<string>& r) {\n        vector<vector<vector<int>>> obj(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[z][x] == '1' && r[z][y] == '1') {\n                        obj[x][y][z] = 1;\n                    }\n                }\n            }\n        }\n        return obj;\n    };\n\n    auto M1 = get_max_obj(f1, r1);\n    auto M2 = get_max_obj(f2, r2);\n\n    // Compute intersection I, and unique parts U1, U2\n    vector<vector<vector<int>>> I(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> U1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> U2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n\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 (M1[x][y][z] && M2[x][y][z]) I[x][y][z] = 1;\n                else if (M1[x][y][z]) U1[x][y][z] = 1;\n                else if (M2[x][y][z]) U2[x][y][z] = 1;\n            }\n        }\n    }\n\n    vector<vector<vector<int>>> b1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> b2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n\n    int block_id = 1;\n\n    // BFS to find connected components and assign unique block IDs\n    auto find_components = [&](vector<vector<vector<int>>>& grid, int& id_counter, vector<vector<vector<int>>>& b_map) {\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\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 (grid[x][y][z] && !visited[x][y][z]) {\n                        queue<Point> q;\n                        q.push({x, y, z});\n                        visited[x][y][z] = true;\n                        b_map[x][y][z] = id_counter;\n                        \n                        int dx[] = {1, -1, 0, 0, 0, 0};\n                        int dy[] = {0, 0, 1, -1, 0, 0};\n                        int dz[] = {0, 0, 0, 0, 1, -1};\n                        \n                        while (!q.empty()) {\n                            Point curr = q.front();\n                            q.pop();\n\n                            for (int i = 0; i < 6; ++i) {\n                                int nx = curr.x + dx[i];\n                                int ny = curr.y + dy[i];\n                                int nz = curr.z + dz[i];\n                                if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                    grid[nx][ny][nz] && !visited[nx][ny][nz]) {\n                                    visited[nx][ny][nz] = true;\n                                    b_map[nx][ny][nz] = id_counter;\n                                    q.push({nx, ny, nz});\n                                }\n                            }\n                        }\n                        id_counter++;\n                    }\n                }\n            }\n        }\n    };\n\n    // 1. Process intersection (shared)\n    find_components(I, block_id, b1);\n    for(int x=0; x<D; ++x) for(int y=0; y<D; ++y) for(int z=0; z<D; ++z) b2[x][y][z] = b1[x][y][z];\n    \n    // 2. Process unique parts for object 1\n    find_components(U1, block_id, b1);\n    // 3. Process unique parts for object 2\n    find_components(U2, block_id, b2);\n\n    // Output result\n    cout << block_id - 1 << endl;\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 << b1[x][y][z] << (x == D - 1 && y == D - 1 && z == D - 1 ? \"\" : \" \");\n            }\n        }\n    }\n    cout << endl;\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 << b2[x][y][z] << (x == D - 1 && y == D - 1 && z == D - 1 ? \"\" : \" \");\n            }\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <queue>\n#include <ctime>\n#include <random>\n#include <numeric>\n\nusing namespace std;\n\nstruct Edge { int u, v, w, id; };\nstruct Point { int x, y; };\n\nint N, M, K;\nvector<Point> stations;\nvector<Point> residents;\nvector<Edge> edges;\nvector<vector<pair<int, int>>> adj;\nvector<vector<pair<double, int>>> sorted_stations;\nvector<vector<int>> path_to_root;\nvector<bool> active;\nvector<int> P;\nvector<int> edge_usage;\nlong long total_edge_cost = 0;\nlong long total_radio_cost = 0;\n\n// Reusable buffers to avoid allocation overhead\nvector<int> next_P;\nvector<int> next_edge_usage;\n\nvoid build_mst() {\n    vector<int> min_weight(N + 1, 2e9);\n    vector<bool> visited(N + 1, false);\n    vector<int> parent_node(N + 1, -1);\n    vector<int> parent_edge_idx(N + 1, -1);\n    min_weight[1] = 0;\n    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n    pq.push({0, 1});\n    while (!pq.empty()) {\n        int u = pq.top().second;\n        pq.pop();\n        if (visited[u]) continue;\n        visited[u] = true;\n        for (auto& edge : adj[u]) {\n            int v = edge.first, idx = edge.second;\n            if (!visited[v] && edges[idx].w < min_weight[v]) {\n                min_weight[v] = edges[idx].w;\n                parent_node[v] = u;\n                parent_edge_idx[v] = idx;\n                pq.push({min_weight[v], v});\n            }\n        }\n    }\n    path_to_root.resize(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        int curr = i;\n        while (parent_node[curr] != -1) {\n            path_to_root[i].push_back(parent_edge_idx[curr]);\n            curr = parent_node[curr];\n        }\n    }\n}\n\n// Attempts to toggle a station status with Simulated Annealing acceptance\nlong long try_toggle(int u, double T, mt19937& rng) {\n    if (u == 1) return -1;\n    \n    active[u] = !active[u];\n    \n    // Check coverage and find best stations\n    bool possible = true;\n    fill(next_P.begin(), next_P.end(), 0);\n    \n    for (int k = 0; k < K; ++k) {\n        int r = 0;\n        // Find best active station for resident k\n        while (r < N && !active[sorted_stations[k][r].second]) r++;\n        \n        if (r == N || sorted_stations[k][r].first > 5000.0) {\n            possible = false; \n            break;\n        }\n        \n        int s = sorted_stations[k][r].second;\n        int d = (int)ceil(sorted_stations[k][r].first);\n        if (d > next_P[s]) next_P[s] = d;\n    }\n    \n    if (!possible) {\n        active[u] = !active[u]; \n        return -1;\n    }\n    \n    // Calculate new costs\n    fill(next_edge_usage.begin(), next_edge_usage.end(), 0);\n    long long next_edge_cost = 0;\n    \n    for (int i = 1; i <= N; ++i) {\n        if (active[i]) {\n            for (int e : path_to_root[i]) {\n                if (next_edge_usage[e] == 0) next_edge_cost += edges[e].w;\n                next_edge_usage[e]++;\n            }\n        }\n    }\n    \n    long long next_radio_cost = 0;\n    for (int i = 1; i <= N; ++i) next_radio_cost += (long long)next_P[i] * next_P[i];\n    \n    long long new_cost = next_radio_cost + next_edge_cost;\n    long long old_cost = total_radio_cost + total_edge_cost;\n    \n    // Accept logic (SA)\n    if (new_cost < old_cost || (T > 1e-9 && exp((double)(old_cost - new_cost) / T) > (double)rng() / rng.max())) {\n        total_radio_cost = next_radio_cost;\n        total_edge_cost = next_edge_cost;\n        P = next_P;\n        edge_usage = next_edge_usage;\n        return new_cost;\n    } else {\n        active[u] = !active[u];\n        return -1;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n    cin >> N >> M >> K;\n    stations.resize(N + 1);\n    for (int i = 1; i <= N; ++i) cin >> stations[i].x >> stations[i].y;\n    adj.resize(N + 1); edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w; cin >> u >> v >> w;\n        edges[i] = {u, v, w, i};\n        adj[u].push_back({v, i});\n        adj[v].push_back({u, i});\n    }\n    residents.resize(K);\n    for (int k = 0; k < K; ++k) cin >> residents[k].x >> residents[k].y;\n    \n    sorted_stations.resize(K);\n    for (int k = 0; k < K; ++k) {\n        for (int i = 1; i <= N; ++i) {\n            double d = sqrt(pow(stations[i].x - residents[k].x, 2) + pow(stations[i].y - residents[k].y, 2));\n            sorted_stations[k].push_back({d, i});\n        }\n        sort(sorted_stations[k].begin(), sorted_stations[k].end());\n    }\n    \n    build_mst();\n    \n    next_P.resize(N + 1);\n    next_edge_usage.resize(M);\n    \n    vector<int> best_P(N + 1, 0);\n    vector<int> best_edge_usage(M, 0);\n    long long best_total_cost = 4e18;\n    \n    mt19937 rng(1337);\n    clock_t start = clock();\n    \n    while ((double)(clock() - start) / CLOCKS_PER_SEC < 1.8) {\n        active.assign(N + 1, true); \n        P.assign(N + 1, 0);\n        edge_usage.assign(M, 0);\n        total_edge_cost = 0;\n        total_radio_cost = 0;\n        \n        for (int k = 0; k < K; ++k) P[sorted_stations[k][0].second] = max(P[sorted_stations[k][0].second], (int)ceil(sorted_stations[k][0].first));\n        for (int i = 1; i <= N; ++i) {\n            total_radio_cost += (long long)P[i] * P[i];\n            for (int e : path_to_root[i]) {\n                if (edge_usage[e] == 0) total_edge_cost += edges[e].w;\n                edge_usage[e]++;\n            }\n        }\n        \n        double T_start = 1e7, T_end = 1e2;\n        int iterations = 1000;\n        for (int iter = 0; iter < iterations; ++iter) {\n            double T = T_start * pow(T_end / T_start, (double)iter / iterations);\n            int u = (rng() % (N - 1)) + 2;\n            long long new_cost = try_toggle(u, T, rng);\n            if (new_cost != -1 && new_cost < best_total_cost) {\n                best_total_cost = new_cost;\n                best_P = P;\n                best_edge_usage = edge_usage;\n            }\n        }\n    }\n    \n    for (int i = 1; i <= N; ++i) cout << best_P[i] << (i == N ? \"\" : \" \");\n    cout << endl;\n    for (int i = 0; i < M; ++i) cout << (best_edge_usage[i] > 0 ? 1 : 0) << (i == M - 1 ? \"\" : \" \");\n    cout << endl;\n    \n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\n// The number of pyramid tiers is fixed to N=30.\nconstexpr int N = 30;\nint initial_board[N][N];\nint current_board[N][N];\n\n// Structure to store swap operations\nstruct SwapOp {\n    int x1, y1, x2, y2;\n    \n    // Overload == for redundancy check (swaps are symmetric)\n    bool operator==(const SwapOp& other) const {\n        int p1_val = x1 * N + y1;\n        int p2_val = x2 * N + y2;\n        if (p1_val > p2_val) swap(p1_val, p2_val);\n\n        int o1_val = other.x1 * N + other.y1;\n        int o2_val = other.x2 * N + other.y2;\n        if (o1_val > o2_val) swap(o1_val, o2_val);\n\n        return p1_val == o1_val && p2_val == o2_val;\n    }\n};\n\n// Function to perform a swap on the current_board\ninline void perform_swap(int x1, int y1, int x2, int y2, vector<SwapOp>& ops) {\n    swap(current_board[x1][y1], current_board[x2][y2]);\n    ops.push_back({x1, y1, x2, y2});\n}\n\n// Function to build the heap using a randomized node order\nint build_heap(vector<SwapOp>& ops, mt19937& rng, vector<int>& ys_buffer) {\n    // Reset board to initial state using memcpy for speed\n    memcpy(current_board, initial_board, sizeof(initial_board));\n    ops.clear();\n\n    // Build-Heap algorithm (bottom-up)\n    for (int x = N - 2; x >= 0; --x) {\n        int sz = x + 1;\n        // Fill and shuffle the pre-allocated buffer for this layer\n        for(int i = 0; i < sz; ++i) ys_buffer[i] = i;\n        shuffle(ys_buffer.begin(), ys_buffer.begin() + sz, rng);\n\n        for (int i = 0; i < sz; ++i) {\n            int y = ys_buffer[i];\n            int cur_x = x;\n            int cur_y = y;\n            \n            // Sift-down process to satisfy min-heap condition\n            while (cur_x < N - 1) {\n                int l_x = cur_x + 1;\n                int l_y = cur_y;\n                int r_x = cur_x + 1;\n                int r_y = cur_y + 1;\n\n                int next_x = l_x;\n                int next_y = l_y;\n                \n                // Identify the smaller of the two children to maintain min-heap property\n                if (current_board[r_x][r_y] < current_board[l_x][l_y]) {\n                    next_x = r_x;\n                    next_y = r_y;\n                }\n\n                // If the current node violates the heap property, swap with the smaller child\n                if (current_board[cur_x][cur_y] > current_board[next_x][next_y]) {\n                    perform_swap(cur_x, cur_y, next_x, next_y, ops);\n                    cur_x = next_x;\n                    cur_y = next_y;\n                } else {\n                    break;\n                }\n            }\n        }\n    }\n\n    // Post-process: remove redundant consecutive swaps\n    if (ops.size() > 1) {\n        vector<SwapOp> cleaned_ops;\n        cleaned_ops.reserve(ops.size());\n        for (const auto& op : ops) {\n            if (!cleaned_ops.empty() && cleaned_ops.back() == op) {\n                cleaned_ops.pop_back();\n            } else {\n                cleaned_ops.push_back(op);\n            }\n        }\n        ops = std::move(cleaned_ops);\n    }\n    \n    return ops.size();\n}\n\nint main() {\n    // Optimize I/O operations\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read the pyramid input\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            cin >> initial_board[i][j];\n        }\n    }\n\n    int best_K = 20000; \n    vector<SwapOp> best_ops;\n    best_ops.reserve(10000);\n    \n    // Seed the RNG\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    // Pre-allocated buffer for node shuffling\n    vector<int> ys_buffer(N);\n\n    auto start_time = chrono::steady_clock::now();\n    int iterations = 0;\n\n    vector<SwapOp> current_ops;\n    current_ops.reserve(10000);\n\n    // Run as many iterations as possible within 1.9 seconds\n    while (true) {\n        iterations++;\n        // Check time roughly every 64 iterations\n        if ((iterations & 63) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1900) {\n                break;\n            }\n        }\n\n        int K = build_heap(current_ops, rng, ys_buffer);\n        \n        if (K < best_K) {\n            best_K = K;\n            best_ops = current_ops;\n        }\n    }\n\n    // Output the result\n    cout << best_ops.size() << \"\\n\";\n    for (const auto& op : best_ops) {\n        cout << op.x1 << \" \" << op.y1 << \" \" << op.x2 << \" \" << op.y2 << \"\\n\";\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\n// Grid size is fixed at 9, but using variables for generality.\nint D; \nint grid[10][10]; \nstruct Point { int r, c, dist; };\nint dist_map[10][10]; \nbool is_removed[100];\nstruct ContainerPos { int r, c; };\nContainerPos pos[100];\n\nint dr[] = {0, 0, 1, -1};\nint dc[] = {1, -1, 0, 0};\n\n// Precompute BFS distance from the entrance (0, (D-1)/2) on an empty grid.\nvoid precompute_dist() {\n    for (int i = 0; i < D; ++i)\n        for (int j = 0; j < D; ++j)\n            dist_map[i][j] = 1000;\n    \n    int er = 0;\n    int ec = (D - 1) / 2;\n    queue<pair<int, int>> q;\n    q.push({er, ec});\n    dist_map[er][ec] = 0;\n    \n    while(!q.empty()){\n        pair<int, int> curr = q.front();\n        q.pop();\n        \n        for(int i=0; i<4; ++i){\n            int nr = curr.first + dr[i];\n            int nc = curr.second + dc[i];\n            if(nr >= 0 && nr < D && nc >= 0 && nc < D && dist_map[nr][nc] == 1000){\n                if(grid[nr][nc] != -2) { // Skip obstacles\n                    dist_map[nr][nc] = dist_map[curr.first][curr.second] + 1;\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n}\n\n// Perform BFS to find all currently reachable empty squares (-1).\nvector<Point> get_reachable_empty() {\n    vector<Point> reachable;\n    bool visited[10][10] = {false};\n    queue<pair<int, int>> q;\n    \n    int er = 0;\n    int ec = (D - 1) / 2;\n    q.push({er, ec});\n    visited[er][ec] = true;\n    \n    while(!q.empty()){\n        pair<int, int> curr = q.front();\n        q.pop();\n        \n        for(int i=0; i<4; ++i){\n            int nr = curr.first + dr[i];\n            int nc = curr.second + dc[i];\n            if(nr >= 0 && nr < D && nc >= 0 && nc < D && !visited[nr][nc]){\n                // Passable if empty (-1).\n                if(grid[nr][nc] == -1){ \n                    visited[nr][nc] = true;\n                    reachable.push_back({nr, nc, dist_map[nr][nc]});\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n    return reachable;\n}\n\n// Check if a container is reachable from the entrance.\nbool is_reachable(int tr, int tc) {\n    if(grid[tr][tc] < 0) return false;\n    \n    bool visited[10][10] = {false};\n    queue<pair<int, int>> q;\n    \n    int er = 0;\n    int ec = (D - 1) / 2;\n    q.push({er, ec});\n    visited[er][ec] = true;\n    \n    while(!q.empty()){\n        pair<int, int> curr = q.front();\n        q.pop();\n        \n        if(curr.first == tr && curr.second == tc) return true;\n        \n        for(int i=0; i<4; ++i){\n            int nr = curr.first + dr[i];\n            int nc = curr.second + dc[i];\n            if(nr >= 0 && nr < D && nc >= 0 && nc < D && !visited[nr][nc]){\n                // Passable if empty (-1) or the target container.\n                if(grid[nr][nc] == -1 || (nr == tr && nc == tc)){\n                    visited[nr][nc] = true;\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n    return false;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int N;\n    if (!(cin >> D >> N)) return 0;\n    \n    for(int i=0; i<D; ++i)\n        for(int j=0; j<D; ++j)\n            grid[i][j] = -1;\n            \n    for(int i=0; i<N; ++i){\n        int r, c;\n        cin >> r >> c;\n        grid[r][c] = -2;\n    }\n    \n    precompute_dist();\n    int K = D * D - 1 - N;\n\n    // Storage Phase\n    for(int d=0; d<K; ++d){\n        int t;\n        cin >> t;\n        \n        vector<Point> reachable = get_reachable_empty();\n        \n        // Sort reachable squares by distance descending (farthest first).\n        sort(reachable.begin(), reachable.end(), [](const Point& a, const Point& b) {\n            return a.dist > b.dist;\n        });\n        \n        Point best = reachable[0];\n        \n        grid[best.r][best.c] = t;\n        pos[t] = {best.r, best.c};\n        cout << best.r << \" \" << best.c << endl;\n    }\n    \n    // Retrieval Phase\n    int target = 0;\n    int removed_cnt = 0;\n    for(int i=0; i<100; ++i) is_removed[i] = false;\n    \n    while(removed_cnt < K){\n        if(is_removed[target]){\n            target++;\n            continue;\n        }\n        \n        if(is_reachable(pos[target].r, pos[target].c)){\n            cout << pos[target].r << \" \" << pos[target].c << endl;\n            grid[pos[target].r][pos[target].c] = -1;\n            is_removed[target] = true;\n            removed_cnt++;\n        } else {\n            // Find reachable blocker with largest label\n            int best_label = -1;\n            pair<int, int> best_pos = {-1, -1};\n            \n            for(int r=0; r<D; ++r){\n                for(int c=0; c<D; ++c){\n                    if(grid[r][c] >= 0){\n                        if(is_reachable(r, c)){\n                            if(grid[r][c] > best_label){\n                                best_label = grid[r][c];\n                                best_pos = {r, c};\n                            }\n                        }\n                    }\n                }\n            }\n            \n            if(best_pos.first != -1){\n                cout << best_pos.first << \" \" << best_pos.second << endl;\n                grid[best_pos.first][best_pos.second] = -1;\n                is_removed[best_label] = true;\n                removed_cnt++;\n            } else {\n                break; // Should not happen.\n            }\n        }\n    }\n    \n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <chrono>\n#include <random>\n\nusing namespace std;\n\nconst int MAX_N = 50;\nint N, M;\nint grid[MAX_N][MAX_N];\nbool target_adj[101][101]; // Required adjacencies\nint count_adj[101][101];   // Current adjacencies\nint n_cells[101];\n\nint dr[] = {0, 0, 1, -1};\nint dc[] = {1, -1, 0, 0};\n\nint vis[MAX_N][MAX_N];\nint vis_gen = 0;\n\n// Checks if all cells of color c are in a single connected component\nbool is_connected(int c) {\n    if (n_cells[c] <= 1) return true;\n    \n    vis_gen++;\n    queue<pair<int, int>> q;\n\n    int start_r = -1, start_c = -1;\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            if(grid[i][j] == c) {\n                start_r = i; start_c = j; break;\n            }\n        }\n        if(start_r != -1) break;\n    }\n    if(start_r == -1) return true; \n\n    vis[start_r][start_c] = vis_gen;\n    q.push({start_r, start_c});\n\n    int visited = 0;\n    while(!q.empty()){\n        auto [r, c_val] = q.front();\n        q.pop();\n        visited++;\n\n        for(int i=0; i<4; ++i) {\n            int nr = r + dr[i];\n            int nc = c_val + dc[i];\n            if(nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] == c && vis[nr][nc] != vis_gen){\n                vis[nr][nc] = vis_gen;\n                q.push({nr, nc});\n            }\n        }\n    }\n    return visited == n_cells[c];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M;\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            cin >> grid[i][j];\n            n_cells[grid[i][j]]++;\n        }\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 + dr[k];\n                int nj = j + dc[k];\n                int nc;\n                if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                else nc = grid[ni][nj];\n                \n                if(grid[i][j] != nc) {\n                    count_adj[grid[i][j]][nc]++;\n                }\n            }\n        }\n    }\n\n    for(int i=0; i<=M; ++i) {\n        for(int j=0; j<=M; ++j) {\n            if (count_adj[i][j] > 0) target_adj[i][j] = true;\n        }\n    }\n\n    static int delta_adj[101][101];\n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    \n    while(true) {\n        auto current_time = chrono::steady_clock::now();\n        if(chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count() > 1800) break;\n        \n        int r = rng() % N;\n        int c = rng() % N;\n        int old_c = grid[r][c];\n        \n        vector<int> candidates = {0};\n        for(int k=0; k<4; ++k) {\n            int nr = r + dr[k];\n            int nc = c + dc[k];\n            if(nr >= 0 && nr < N && nc >= 0 && nc < N) {\n                candidates.push_back(grid[nr][nc]);\n            }\n        }\n        \n        shuffle(candidates.begin(), candidates.end(), rng);\n        \n        for(int new_c : candidates) {\n            if (new_c == old_c) continue;\n            \n            vector<pair<int, int>> affected;\n            for(int k=0; k<4; ++k) {\n                int nr = r + dr[k];\n                int nc = c + dc[k];\n                int neighbor_c = (nr < 0 || nr >= N || nc < 0 || nc >= N) ? 0 : grid[nr][nc];\n                \n                if (old_c != neighbor_c) {\n                    int u = min(old_c, neighbor_c);\n                    int v = max(old_c, neighbor_c);\n                    if (delta_adj[u][v] == 0) affected.push_back({u, v});\n                    delta_adj[u][v]--;\n                }\n                if (new_c != neighbor_c) {\n                    int u = min(new_c, neighbor_c);\n                    int v = max(new_c, neighbor_c);\n                    if (delta_adj[u][v] == 0) affected.push_back({u, v});\n                    delta_adj[u][v]++;\n                }\n            }\n            \n            sort(affected.begin(), affected.end());\n            affected.erase(unique(affected.begin(), affected.end()), affected.end());\n            \n            bool adj_ok = true;\n            for(auto p : affected) {\n                int u = p.first, v = p.second;\n                int new_count = count_adj[u][v] + delta_adj[u][v];\n                if (target_adj[u][v] && new_count == 0) { adj_ok = false; break; }\n                if (!target_adj[u][v] && new_count > 0) { adj_ok = false; break; }\n            }\n            \n            if (!adj_ok) {\n                for(auto p : affected) delta_adj[p.first][p.second] = 0;\n                continue;\n            }\n            \n            grid[r][c] = new_c;\n            n_cells[old_c]--;\n            n_cells[new_c]++;\n            \n            if (!is_connected(old_c)) {\n                grid[r][c] = old_c;\n                n_cells[old_c]++;\n                n_cells[new_c]--;\n                for(auto p : affected) delta_adj[p.first][p.second] = 0;\n            } else {\n                for(auto p : affected) {\n                    count_adj[p.first][p.second] += delta_adj[p.first][p.second];\n                    count_adj[p.second][p.first] += delta_adj[p.first][p.second];\n                    delta_adj[p.first][p.second] = 0;\n                }\n                break;\n            }\n        }\n    }\n\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            cout << grid[i][j] << (j == N-1 ? \"\" : \" \");\n        }\n        cout << \"\\n\";\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <string>\n#include <numeric>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <iomanip>\n#include <chrono>\n\nusing namespace std;\n\nstruct Solver {\n    int N, D, Q;\n    vector<double> weights;\n    mt19937 rng;\n\n    Solver() : rng(1337) {}\n\n    // Faster random selection\n    inline int get_rand(int n) {\n        return (int)(rng() % n);\n    }\n\n    // Active query selection: optimized to avoid repeated heavy allocations\n    pair<vector<int>, vector<int>> select_query() {\n        double min_diff = 1e18;\n        vector<int> best_L, best_R;\n        int candidates = 20; \n        \n        static vector<int> all_items(100);\n        if(all_items.size() != (size_t)N) {\n            all_items.resize(N);\n            iota(all_items.begin(), all_items.end(), 0);\n        }\n\n        for(int k = 0; k < candidates; ++k) {\n            int nL = 1 + get_rand(N / 2);\n            int nR = 1 + get_rand(N - nL);\n            \n            shuffle(all_items.begin(), all_items.end(), rng);\n            \n            vector<int> L(all_items.begin(), all_items.begin() + nL);\n            vector<int> R(all_items.begin() + nL, all_items.begin() + nL + nR);\n            \n            double sumL = 0;\n            for(int i : L) sumL += weights[i];\n            double sumR = 0;\n            for(int i : R) sumR += weights[i];\n            \n            double diff = abs(sumL - sumR);\n            if(diff < min_diff) {\n                min_diff = diff;\n                best_L = std::move(L);\n                best_R = std::move(R);\n            }\n        }\n        return {best_L, best_R};\n    }\n\n    void solve() {\n        if (!(cin >> N >> D >> Q)) return;\n        weights.assign(N, 1000.0);\n\n        for (int q = 0; q < Q; ++q) {\n            auto [L, R] = select_query();\n            \n            cout << L.size() << \" \" << R.size();\n            for (int i : L) cout << \" \" << i;\n            for (int i : R) cout << \" \" << i;\n            cout << endl;\n            \n            string res;\n            cin >> res;\n            \n            double sumL = 0;\n            for (int i : L) sumL += weights[i];\n            double sumR = 0;\n            for (int i : R) sumR += weights[i];\n            \n            double diff = (res == \"<\") ? (sumR - sumL) : ((res == \">\") ? (sumL - sumR) : 0);\n            \n            double alpha = 0.1 * (1.0 - 0.5 * (double)q / Q);\n            for (int i : L) weights[i] += alpha * diff / L.size();\n            for (int i : R) weights[i] -= alpha * diff / R.size();\n            \n            for (double& w : weights) w = max(1.0, w);\n        }\n        \n        // Initial Assignment (LPT)\n        vector<int> assignment(N);\n        vector<double> bucket_weights(D, 0.0);\n        vector<vector<int>> bucket_items(D);\n        vector<int> item_pos_in_bucket(N); \n        \n        vector<int> sorted_items(N);\n        iota(sorted_items.begin(), sorted_items.end(), 0);\n        sort(sorted_items.begin(), sorted_items.end(), [&](int a, int b) {\n            return weights[a] > weights[b];\n        });\n        \n        for (int i : sorted_items) {\n            int best_bucket = 0;\n            for (int d = 1; d < D; ++d) {\n                if (bucket_weights[d] < bucket_weights[best_bucket]) best_bucket = d;\n            }\n            assignment[i] = best_bucket;\n            bucket_weights[best_bucket] += weights[i];\n            item_pos_in_bucket[i] = (int)bucket_items[best_bucket].size();\n            bucket_items[best_bucket].push_back(i);\n        }\n        \n        // Simulated Annealing\n        auto start_time = chrono::steady_clock::now();\n        double T_start = 100.0;\n        double T_end = 0.01;\n        \n        for(int iter = 0; ; ++iter) {\n            // Check time every 8191 iterations to reduce overhead\n            if ((iter & 8191) == 0) {\n                auto now = chrono::steady_clock::now();\n                if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1700) break;\n            }\n            \n            double progress = min(1.0, (double)iter / 1000000.0); \n            double temp = T_start * pow(T_end / T_start, progress);\n            \n            int op = get_rand(2); // 0 swap, 1 move\n            \n            if (op == 0) { // swap\n                int b1 = get_rand(D);\n                int b2 = get_rand(D);\n                if (b1 == b2 || bucket_items[b1].empty() || bucket_items[b2].empty()) continue;\n                \n                int i1 = bucket_items[b1][get_rand((int)bucket_items[b1].size())];\n                int i2 = bucket_items[b2][get_rand((int)bucket_items[b2].size())];\n                \n                double new_bw1 = bucket_weights[b1] - weights[i1] + weights[i2];\n                double new_bw2 = bucket_weights[b2] - weights[i2] + weights[i1];\n                \n                double delta = (new_bw1*new_bw1 + new_bw2*new_bw2) - (bucket_weights[b1]*bucket_weights[b1] + bucket_weights[b2]*bucket_weights[b2]);\n                \n                if (delta < 0 || exp(-delta / temp) > (double)rng() / 4294967295.0) {\n                    assignment[i1] = b2;\n                    assignment[i2] = b1;\n                    bucket_weights[b1] = new_bw1;\n                    bucket_weights[b2] = new_bw2;\n                    \n                    int pos1 = item_pos_in_bucket[i1];\n                    int last1 = bucket_items[b1].back();\n                    bucket_items[b1][pos1] = last1;\n                    item_pos_in_bucket[last1] = pos1;\n                    bucket_items[b1].pop_back();\n                    \n                    int pos2 = item_pos_in_bucket[i2];\n                    int last2 = bucket_items[b2].back();\n                    bucket_items[b2][pos2] = last2;\n                    item_pos_in_bucket[last2] = pos2;\n                    bucket_items[b2].pop_back();\n                    \n                    item_pos_in_bucket[i1] = (int)bucket_items[b2].size();\n                    bucket_items[b2].push_back(i1);\n                    item_pos_in_bucket[i2] = (int)bucket_items[b1].size();\n                    bucket_items[b1].push_back(i2);\n                }\n            } else { // move\n                int b1 = get_rand(D);\n                int b2 = get_rand(D);\n                if (b1 == b2 || bucket_items[b1].empty()) continue;\n                \n                int i1 = bucket_items[b1][get_rand((int)bucket_items[b1].size())];\n                \n                double new_bw1 = bucket_weights[b1] - weights[i1];\n                double new_bw2 = bucket_weights[b2] + weights[i1];\n                \n                double delta = (new_bw1*new_bw1 + new_bw2*new_bw2) - (bucket_weights[b1]*bucket_weights[b1] + bucket_weights[b2]*bucket_weights[b2]);\n                \n                if (delta < 0 || exp(-delta / temp) > (double)rng() / 4294967295.0) {\n                    assignment[i1] = b2;\n                    bucket_weights[b1] = new_bw1;\n                    bucket_weights[b2] = new_bw2;\n                    \n                    int pos1 = item_pos_in_bucket[i1];\n                    int last1 = bucket_items[b1].back();\n                    bucket_items[b1][pos1] = last1;\n                    item_pos_in_bucket[last1] = pos1;\n                    bucket_items[b1].pop_back();\n                    \n                    item_pos_in_bucket[i1] = (int)bucket_items[b2].size();\n                    bucket_items[b2].push_back(i1);\n                }\n            }\n        }\n        \n        for (int i = 0; i < N; ++i) cout << assignment[i] << (i == N - 1 ? \"\" : \" \");\n        cout << endl;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    Solver s;\n    s.solve();\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\n// Global Configuration\nint N, M;\nvector<vector<int>> stacks;\nvector<int> box_to_stack;\nvector<int> box_to_pos;\n\n// Find the stack containing a specific target box\nint find_stack(int target) {\n    return box_to_stack[target];\n}\n\n// Helper to find the minimum box number in a stack.\n// This represents the \"deadline\" for the stack: we must process this box \n// before or at the time we process any box larger than it. \n// Burying a stack with a large minimum is safe because we don't need those boxes soon.\nint get_min_box(const vector<int>& stack) {\n    if (stack.empty()) return 1000000; // Large value for empty stack\n    int min_b = 1000000;\n    for (int b : stack) {\n        if (b < min_b) min_b = b;\n    }\n    return min_b;\n}\n\n// Find the best destination stack for moving blocks of boxes.\n// Criteria:\n// 1. Prefer empty stacks (represented by min_box = 1000000).\n// 2. Otherwise, pick the stack with the largest min_box (least urgent).\n// 3. Tie-breaker: smaller stack size (keeps the stacks more balanced).\nint find_best_dest(int s) {\n    int best_d = -1;\n    int max_min_box = -1;\n    int min_size = 1000000;\n\n    for (int d = 0; d < M; ++d) {\n        if (d == s) continue; // Cannot move to the current stack\n        \n        int current_min_box = get_min_box(stacks[d]);\n        \n        // We want to maximize the minimum box number (least urgent stack)\n        if (current_min_box > max_min_box) {\n            max_min_box = current_min_box;\n            best_d = d;\n            min_size = stacks[d].size();\n        } else if (current_min_box == max_min_box) {\n            // Tie-breaker: smaller stack size\n            if ((int)stacks[d].size() < min_size) {\n                min_size = stacks[d].size();\n                best_d = d;\n            }\n        }\n    }\n    return best_d;\n}\n\n// Move the block of boxes above the target box to another stack d\nvoid move_block(int s, int pos, int d) {\n    int block_start_idx = pos + 1;\n    \n    // Update stack_ids and positions for the moved boxes\n    for (int i = block_start_idx; i < (int)stacks[s].size(); ++i) {\n        int b = stacks[s][i];\n        stacks[d].push_back(b);\n        box_to_stack[b] = d;\n        box_to_pos[b] = (int)stacks[d].size() - 1;\n    }\n    \n    // Remove the moved boxes from the original stack\n    stacks[s].erase(stacks[s].begin() + block_start_idx, stacks[s].end());\n}\n\nint main() {\n    // Optimize I/O\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M)) return 0;\n    \n    stacks.resize(M);\n    box_to_stack.resize(N + 1);\n    box_to_pos.resize(N + 1);\n\n    // Read the initial stack configuration\n    for (int i = 0; i < M; ++i) {\n        for (int j = 0; j < N / M; ++j) {\n            int b;\n            cin >> b;\n            stacks[i].push_back(b);\n            box_to_stack[b] = i;\n            box_to_pos[b] = (int)stacks[i].size() - 1;\n        }\n    }\n\n    int target = 1;\n    int ops = 0;\n    \n    // Process until all boxes are removed\n    while (target <= N && ops < 5000) {\n        int s = find_stack(target);\n        int pos = box_to_pos[target];\n        \n        // If target is at the top of its stack, remove it\n        if (pos == (int)stacks[s].size() - 1) {\n            cout << target << \" 0\" << endl;\n            stacks[s].pop_back();\n            target++;\n            ops++;\n        } else {\n            // Need to move the block\n            int d = find_best_dest(s);\n            int v_prime = stacks[s][pos + 1];\n            \n            // Output the move operation (v, i+1)\n            cout << v_prime << \" \" << (d + 1) << endl;\n            \n            // Perform the move\n            move_block(s, pos, d);\n            ops++;\n        }\n    }\n\n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <queue>\n#include <ctime>\n\nusing namespace std;\n\n// Helper to map 2D coordinates to 1D\nint id(int r, int c, int N) {\n    return r * N + c;\n}\n\n// Helper to map 1D index to 2D coordinates\npair<int, int> pos(int idx, int N) {\n    return {idx / N, idx % N};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> h(N - 1), v(N);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    for (int i = 0; i < N; ++i) cin >> v[i];\n    vector<vector<int>> d(N, vector<int>(N));\n    vector<int> d_flat(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n            d_flat[id(i, j, N)] = d[i][j];\n        }\n    }\n\n    // Build the grid graph\n    vector<vector<int>> adj(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (i + 1 < N && h[i][j] == '0') {\n                adj[id(i, j, N)].push_back(id(i + 1, j, N));\n                adj[id(i + 1, j, N)].push_back(id(i, j, N));\n            }\n            if (j + 1 < N && v[i][j] == '0') {\n                adj[id(i, j, N)].push_back(id(i, j + 1, N));\n                adj[id(i, j + 1, N)].push_back(id(i, j, N));\n            }\n        }\n    }\n\n    // Prim's algorithm for an initial spanning tree\n    vector<int> deg(N * N, 0);\n    vector<vector<int>> tree_adj(N * N);\n    vector<vector<bool>> is_in_tree(N * N, vector<bool>(N * N, false));\n    vector<int> parent(N * N, -1);\n    vector<bool> visited(N * N, false);\n    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n    pq.push({0, 0});\n    vector<int> min_edge_w(N * N, 1e9);\n    min_edge_w[0] = 0;\n    \n    while(!pq.empty()){\n        int u = pq.top().second;\n        pq.pop();\n        if(visited[u]) continue;\n        visited[u] = true;\n        \n        if(parent[u] != -1){\n            int p = parent[u];\n            tree_adj[u].push_back(p);\n            tree_adj[p].push_back(u);\n            is_in_tree[u][p] = is_in_tree[p][u] = true;\n            deg[u]++;\n            deg[p]++;\n        }\n        \n        for(int neighbor : adj[u]){\n            if(!visited[neighbor]){\n                // Heuristic: connect higher dirt regions\n                int weight = -(d_flat[u] + d_flat[neighbor]);\n                if(weight < min_edge_w[neighbor]){\n                    min_edge_w[neighbor] = weight;\n                    parent[neighbor] = u;\n                    pq.push({weight, neighbor});\n                }\n            }\n        }\n    }\n\n    auto get_cost = [&](int u) -> double {\n        return (double)d_flat[u] / deg[u];\n    };\n\n    // Simulated Annealing to optimize tree\n    mt19937 rng(42);\n    auto start_time = clock();\n    double T = 1.0;\n    \n    vector<pair<int, int>> non_tree_edges;\n    for(int u = 0; u < N * N; ++u) {\n        for(int v : adj[u]) {\n            if (u < v && !is_in_tree[u][v]) {\n                non_tree_edges.push_back({u, v});\n            }\n        }\n    }\n\n    while ((double)(clock() - start_time) / CLOCKS_PER_SEC < 1.8) {\n        int idx = rng() % non_tree_edges.size();\n        int u = non_tree_edges[idx].first;\n        int v = non_tree_edges[idx].second;\n        \n        vector<int> path_parent(N * N, -1);\n        vector<int> q;\n        q.push_back(u);\n        vector<bool> v_visited(N * N, false);\n        v_visited[u] = true;\n        int head = 0;\n        bool found = false;\n        while(head < (int)q.size()){\n            int curr = q[head++];\n            if(curr == v) { found = true; break; }\n            for(int neighbor : tree_adj[curr]){\n                if(!v_visited[neighbor]){\n                    v_visited[neighbor] = true;\n                    path_parent[neighbor] = curr;\n                    q.push_back(neighbor);\n                }\n            }\n        }\n        \n        if(!found) continue;\n\n        vector<pair<int, int>> path_edges;\n        int curr = v;\n        while(curr != u){\n            int p = path_parent[curr];\n            path_edges.push_back({curr, p});\n            curr = p;\n        }\n\n        for(auto& e : path_edges){\n            int a = e.first;\n            int b = e.second;\n            \n            double old_c = get_cost(a) + get_cost(b) + get_cost(u) + get_cost(v);\n            double new_c = (double)d_flat[a] / (deg[a]-1) + (double)d_flat[b] / (deg[b]-1) + (double)d_flat[u] / (deg[u]+1) + (double)d_flat[v] / (deg[v]+1);\n            \n            double delta = new_c - old_c;\n            \n            if (delta < 0 || exp(-delta / T) > (double)rng() / rng.max()) {\n                is_in_tree[a][b] = is_in_tree[b][a] = false;\n                is_in_tree[u][v] = is_in_tree[v][u] = true;\n                \n                for(int i=0; i<(int)tree_adj[a].size(); ++i) if(tree_adj[a][i] == b) { tree_adj[a].erase(tree_adj[a].begin()+i); break; }\n                for(int i=0; i<(int)tree_adj[b].size(); ++i) if(tree_adj[b][i] == a) { tree_adj[b].erase(tree_adj[b].begin()+i); break; }\n                tree_adj[u].push_back(v);\n                tree_adj[v].push_back(u);\n                \n                deg[a]--; deg[b]--; deg[u]++; deg[v]++;\n                non_tree_edges[idx] = {a, b};\n                break;\n            }\n        }\n        T *= 0.99999;\n    }\n\n    // Build DFS path\n    vector<vector<int>> children(N * N);\n    vector<int> q; q.push_back(0);\n    vector<bool> visited_node(N * N, false);\n    visited_node[0] = true;\n    int head = 0;\n    while(head < (int)q.size()){\n        int u = q[head++];\n        for(int neighbor : tree_adj[u]){\n            if(!visited_node[neighbor]){\n                visited_node[neighbor] = true;\n                children[u].push_back(neighbor);\n                q.push_back(neighbor);\n            }\n        }\n    }\n    vector<int> parent_node(N * N, -1);\n    for(int i = 0; i < N * N; ++i) for(int child : children[i]) parent_node[child] = i;\n    vector<long long> subtree_d(N * N, 0);\n    for(int i = N * N - 1; i >= 0; --i){\n        int u = q[i];\n        subtree_d[u] += d_flat[u];\n        if(parent_node[u] != -1) subtree_d[parent_node[u]] += subtree_d[u];\n    }\n    for(int i=0; i<N*N; ++i) sort(children[i].begin(), children[i].end(), [&](int a, int b){ return subtree_d[a] > subtree_d[b]; });\n\n    string path_str = \"\";\n    auto get_dir = [&](int u, int v) {\n        pair<int, int> p1 = pos(u, N), p2 = pos(v, N);\n        if (p2.first == p1.first + 1) return 'D';\n        if (p2.first == p1.first - 1) return 'U';\n        if (p2.second == p1.second + 1) return 'R';\n        if (p2.second == p1.second - 1) return 'L';\n        return ' ';\n    };\n\n    auto dfs = [&](auto self, int u) -> void {\n        for(int neighbor : children[u]){\n            path_str += get_dir(u, neighbor);\n            self(self, neighbor);\n            path_str += get_dir(neighbor, u);\n        }\n    };\n    dfs(dfs, 0);\n    \n    string final_path = \"\";\n    while((int)final_path.length() + (int)path_str.length() <= 100000) final_path += path_str;\n    cout << final_path << endl;\n\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <ctime>\n\nusing namespace std;\n\n// Structure to hold grid coordinates\nstruct Pos {\n    int r, c;\n};\n\n// Function to calculate the cost of moving between two squares.\n// The cost is |r1-r2| + |c1-c2| + 1.\ninline int dist(Pos p1, Pos p2) {\n    return abs(p1.r - p2.r) + abs(p1.c - p2.c) + 1;\n}\n\n// Global variables\nint N, M;\nint si, sj;\nvector<vector<Pos>> pos_map(26);\nvector<string> t;\nvector<vector<int>> overlap;\n\n// DP function to calculate ONLY the minimum travel cost for a given superstring.\nlong long get_min_cost(const string& s) {\n    int L = s.length();\n    if (L == 0) return 0;\n\n    const auto& start_chars = pos_map[s[0] - 'A'];\n    vector<long long> dp(start_chars.size());\n    \n    Pos start_pos = {si, sj};\n    for (size_t i = 0; i < start_chars.size(); ++i) {\n        dp[i] = dist(start_pos, start_chars[i]);\n    }\n\n    for (int k = 1; k < L; ++k) {\n        const auto& curr_chars = pos_map[s[k] - 'A'];\n        const auto& prev_chars = pos_map[s[k-1] - 'A'];\n        \n        vector<long long> next_dp(curr_chars.size(), 1e18);\n        \n        for (size_t i = 0; i < curr_chars.size(); ++i) {\n            for (size_t j = 0; j < prev_chars.size(); ++j) {\n                long long d = dp[j] + dist(prev_chars[j], curr_chars[i]);\n                if (d < next_dp[i]) {\n                    next_dp[i] = d;\n                }\n            }\n        }\n        dp = next_dp;\n    }\n\n    long long min_cost = 1e18;\n    for (long long val : dp) {\n        if (val < min_cost) min_cost = val;\n    }\n    return min_cost;\n}\n\n// DP function to calculate the cost AND the path for final reconstruction.\npair<long long, vector<Pos>> solve_dp(const string& s) {\n    int L = s.length();\n    const auto& start_chars = pos_map[s[0] - 'A'];\n    vector<long long> dp(start_chars.size());\n    vector<vector<int>> parent_path(L);\n    \n    Pos start_pos = {si, sj};\n    for (size_t i = 0; i < start_chars.size(); ++i) {\n        dp[i] = dist(start_pos, start_chars[i]);\n    }\n\n    for (int k = 1; k < L; ++k) {\n        const auto& curr_chars = pos_map[s[k] - 'A'];\n        const auto& prev_chars = pos_map[s[k-1] - 'A'];\n        \n        vector<long long> next_dp(curr_chars.size(), 1e18);\n        vector<int> next_parent(curr_chars.size(), -1);\n        \n        for (size_t i = 0; i < curr_chars.size(); ++i) {\n            for (size_t j = 0; j < prev_chars.size(); ++j) {\n                long long d = dp[j] + dist(prev_chars[j], curr_chars[i]);\n                if (d < next_dp[i]) {\n                    next_dp[i] = d;\n                    next_parent[i] = (int)j;\n                }\n            }\n        }\n        dp = next_dp;\n        parent_path[k] = next_parent;\n    }\n\n    long long min_cost = 1e18;\n    int last_idx = -1;\n    for (size_t i = 0; i < dp.size(); ++i) {\n        if (dp[i] < min_cost) {\n            min_cost = dp[i];\n            last_idx = (int)i;\n        }\n    }\n\n    vector<Pos> path(L);\n    int curr_idx = last_idx;\n    for (int k = L - 1; k >= 0; --k) {\n        path[k] = pos_map[s[k] - 'A'][curr_idx];\n        if (k > 0) {\n            curr_idx = parent_path[k][curr_idx];\n        }\n    }\n    return {min_cost, path};\n}\n\nstring build_superstring(const vector<int>& p) {\n    string res = t[p[0]];\n    for (size_t i = 1; i < p.size(); ++i) {\n        res += t[p[i]].substr(overlap[p[i-1]][p[i]]);\n    }\n    return res;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M)) return 0;\n    cin >> si >> sj;\n\n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) {\n            pos_map[row[j] - 'A'].push_back({i, j});\n        }\n    }\n\n    t.resize(M);\n    for (int i = 0; i < M; ++i) cin >> t[i];\n\n    overlap.assign(M, vector<int>(M));\n    for (int i = 0; i < M; ++i) {\n        for (int j = 0; j < M; ++j) {\n            if (i == j) continue;\n            for (int len = 5; len >= 0; --len) {\n                if (t[i].substr(5 - len) == t[j].substr(0, len)) {\n                    overlap[i][j] = len;\n                    break;\n                }\n            }\n        }\n    }\n\n    // 1. Generate M greedy initial candidates\n    vector<vector<int>> candidates;\n    for (int start_node = 0; start_node < M; ++start_node) {\n        vector<int> p;\n        p.reserve(M);\n        p.push_back(start_node);\n        vector<bool> used(M, false);\n        used[start_node] = true;\n        \n        for (int i = 1; i < M; ++i) {\n            int last = p.back();\n            int best_next = -1;\n            int max_o = -1;\n            for (int j = 0; j < M; ++j) {\n                if (!used[j] && overlap[last][j] > max_o) {\n                    max_o = overlap[last][j];\n                    best_next = j;\n                }\n            }\n            p.push_back(best_next);\n            used[best_next] = true;\n        }\n        candidates.push_back(p);\n    }\n\n    // 2. Perform Hill Climbing / Local Search\n    long long best_total_cost = 2e18;\n    vector<int> best_p;\n    \n    // Find initial best\n    for(const auto& p : candidates) {\n        long long c = get_min_cost(build_superstring(p));\n        if(c < best_total_cost) {\n            best_total_cost = c;\n            best_p = p;\n        }\n    }\n\n    mt19937 rng(1337);\n    auto start_time = clock();\n    \n    int cand_idx = 0;\n    while ((double)(clock() - start_time) / CLOCKS_PER_SEC < 1.7) {\n        vector<int> p = candidates[cand_idx % M];\n        \n        // Hill climbing: 2-opt moves\n        for(int iter = 0; iter < 10; ++iter) {\n            int i = rng() % (M - 1);\n            int j = i + 1 + rng() % (M - 1 - i);\n            \n            vector<int> next_p = p;\n            reverse(next_p.begin() + i, next_p.begin() + j + 1);\n            \n            long long current_cost = get_min_cost(build_superstring(p));\n            long long next_cost = get_min_cost(build_superstring(next_p));\n            \n            if (next_cost < current_cost) {\n                p = next_p;\n                \n                // Keep track of the best global permutation found\n                if (next_cost < best_total_cost) {\n                    best_total_cost = next_cost;\n                    best_p = next_p;\n                }\n            }\n        }\n        cand_idx++;\n    }\n\n    // 3. Final path reconstruction\n    pair<long long, vector<Pos>> final_result = solve_dp(build_superstring(best_p));\n    for (const auto& pos : final_result.second) {\n        cout << pos.r << \" \" << pos.c << \"\\n\";\n    }\n\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <iomanip>\n\nusing namespace std;\n\n// Structure to represent a point on the island\nstruct Point {\n    int r, c;\n};\n\n// Structure to represent an oil field\nstruct Field {\n    vector<Point> shape;\n    int max_dr, max_dc;\n};\n\nint N, M;\ndouble eps;\nvector<Field> fields;\n\n// Global vector for precomputed is_oil: [k][r][c][i][j]\n// Using uint8_t to save memory\nvector<uint8_t> is_oil; \n\ninline bool get_is_oil(int k, int r, int c, int i, int j) {\n    if (i < r || j < c || i >= r + fields[k].max_dr + 1 || j >= c + fields[k].max_dc + 1) return false;\n    return is_oil[((((k * N + r) * N + c) * N + i) * N + j)];\n}\n\nstruct Config {\n    vector<Point> offsets;\n    double log_weight;\n};\n\nvector<Config> particles;\nconst int NUM_PARTICLES = 250;\n\nvoid init_particles() {\n    particles.clear();\n    mt19937 rng(12345);\n    for (int i = 0; i < NUM_PARTICLES; ++i) {\n        Config c;\n        for (int k = 0; k < M; ++k) {\n            uniform_int_distribution<int> dist_r(0, N - 1 - fields[k].max_dr);\n            uniform_int_distribution<int> dist_c(0, N - 1 - fields[k].max_dc);\n            c.offsets.push_back({dist_r(rng), dist_c(rng)});\n        }\n        c.log_weight = -log((double)NUM_PARTICLES);\n        particles.push_back(c);\n    }\n}\n\nint compute_v_S(const Config& c, const vector<Point>& S) {\n    int v_S = 0;\n    for (const auto& p : S) {\n        for (int k = 0; k < M; ++k) {\n            if (get_is_oil(k, c.offsets[k].r, c.offsets[k].c, p.r, p.c)) {\n                v_S++;\n            }\n        }\n    }\n    return v_S;\n}\n\nvoid update_weights(const vector<Point>& S, double obs) {\n    int k = S.size();\n    double sigma2 = (double)k * eps * (1.0 - eps);\n    double max_log_w = -1e18;\n\n    for (auto& c : particles) {\n        int v_S = compute_v_S(c, S);\n        double mu = (double)(k - v_S) * eps + (double)v_S * (1.0 - eps);\n        double log_likelihood = -0.5 * pow(obs - mu, 2) / sigma2;\n        c.log_weight += log_likelihood;\n        if (c.log_weight > max_log_w) max_log_w = c.log_weight;\n    }\n\n    double sum_w = 0;\n    for (auto& c : particles) {\n        c.log_weight -= max_log_w;\n        sum_w += exp(c.log_weight);\n    }\n    for (auto& c : particles) {\n        c.log_weight = log(exp(c.log_weight) / sum_w);\n    }\n}\n\nvoid resample() {\n    double sum_sq_w = 0;\n    for (auto& c : particles) sum_sq_w += exp(2.0 * c.log_weight);\n    if (1.0 / sum_sq_w < NUM_PARTICLES / 3.0) {\n        vector<Config> new_particles;\n        vector<double> weights;\n        for (auto& c : particles) weights.push_back(exp(c.log_weight));\n        discrete_distribution<int> dist(weights.begin(), weights.end());\n        mt19937 rng(45678);\n        for (int i = 0; i < NUM_PARTICLES; ++i) {\n            new_particles.push_back(particles[dist(rng)]);\n            new_particles.back().log_weight = -log((double)NUM_PARTICLES);\n        }\n        particles = new_particles;\n    }\n}\n\nvoid rejuvenate() {\n    double min_w = 1e18;\n    for (auto& c : particles) min_w = min(min_w, c.log_weight);\n    \n    mt19937 rng(999);\n    for (auto& c : particles) {\n        if (c.log_weight < min_w + 1e-4) {\n            for (int k = 0; k < M; ++k) {\n                c.offsets[k].r = uniform_int_distribution<int>(0, N - 1 - fields[k].max_dr)(rng);\n                c.offsets[k].c = uniform_int_distribution<int>(0, N - 1 - fields[k].max_dc)(rng);\n            }\n            c.log_weight = -log((double)NUM_PARTICLES);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    cin >> N >> M >> eps;\n    fields.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int d; cin >> d;\n        int max_dr = 0, max_dc = 0;\n        for (int i = 0; i < d; ++i) {\n            int r, c; cin >> r >> c;\n            fields[k].shape.push_back({r, c});\n            max_dr = max(max_dr, r);\n            max_dc = max(max_dc, c);\n        }\n        fields[k].max_dr = max_dr;\n        fields[k].max_dc = max_dc;\n    }\n\n    is_oil.assign(M * N * N * N * N, 0);\n    for (int k = 0; k < M; ++k) {\n        for (int r = 0; r <= N - 1 - fields[k].max_dr; ++r) {\n            for (int c = 0; c <= N - 1 - fields[k].max_dc; ++c) {\n                for (const auto& p : fields[k].shape) {\n                    is_oil[((((k * N + r) * N + c) * N + (r + p.r)) * N + (c + p.c))] = 1;\n                }\n            }\n        }\n    }\n\n    init_particles();\n    mt19937 rng(42);\n    int query_count = 0;\n    while (query_count < 2 * N * N) {\n        vector<vector<Point>> candidates;\n        for (int i = 0; i < 50; ++i) {\n            int k = uniform_int_distribution<int>(1, N * N / 2)(rng);\n            vector<Point> S;\n            for (int j = 0; j < k; ++j) S.push_back({uniform_int_distribution<int>(0, N - 1)(rng), uniform_int_distribution<int>(0, N - 1)(rng)});\n            candidates.push_back(S);\n        }\n\n        int best_idx = -1;\n        double best_var = -1.0;\n        for (int i = 0; i < candidates.size(); ++i) {\n            double mean = 0;\n            vector<int> v_Ss;\n            for (auto& c : particles) {\n                int v_S = compute_v_S(c, candidates[i]);\n                v_Ss.push_back(v_S);\n                mean += exp(c.log_weight) * v_S;\n            }\n            double var = 0;\n            for (int j = 0; j < particles.size(); ++j) var += exp(particles[j].log_weight) * pow(v_Ss[j] - mean, 2);\n            double score = var * sqrt((double)candidates[i].size());\n            if (score > best_var) { best_var = score; best_idx = i; }\n        }\n\n        cout << \"q \" << candidates[best_idx].size();\n        for (auto& p : candidates[best_idx]) cout << \" \" << p.r << \" \" << p.c;\n        cout << endl;\n        double obs; cin >> obs;\n        update_weights(candidates[best_idx], obs);\n        resample();\n        rejuvenate();\n        query_count++;\n\n        // Guess\n        vector<Point> guess_set;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                double prob = 0;\n                for (auto& c : particles) {\n                    bool oil = false;\n                    for (int k = 0; k < M; ++k) if (get_is_oil(k, c.offsets[k].r, c.offsets[k].c, i, j)) { oil = true; break; }\n                    if (oil) prob += exp(c.log_weight);\n                }\n                if (prob > 0.5) guess_set.push_back({i, j});\n            }\n        }\n\n        cout << \"a \" << guess_set.size();\n        for (auto& p : guess_set) cout << \" \" << p.r << \" \" << p.c;\n        cout << endl;\n        int resp; cin >> resp;\n        if (resp == 1) return 0;\n    }\n    return 0;\n}","ahc031":"/*\n * Problem: Minimize total cost of rental area deficiency and partition movement.\n * Approach: Partition the W x W grid into N horizontal strips.\n * Use Coordinate Descent (Hill Climbing) followed by Simulated Annealing to optimize\n * the vertical positions of the N-1 internal partition lines.\n */\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Function to calculate area cost for a given strip height\nlong long get_area_cost(int W, int a_val, int height) {\n    if (height <= 0) return 1e15; // Prevents invalid partition configurations\n    long long area = (long long)W * height;\n    if (a_val > area) return 100LL * (a_val - area);\n    return 0LL;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\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    // lines[d][k] is the vertical position of the partition between strip k-1 and k.\n    vector<vector<int>> lines(D, vector<int>(N + 1));\n    for (int d = 0; d < D; ++d) {\n        lines[d][0] = 0;\n        lines[d][N] = W;\n        int current_pos = 0;\n        for (int k = 0; k < N - 1; ++k) {\n            int needed_height = (a[d][k] + W - 1) / W;\n            current_pos += max(1, needed_height);\n            lines[d][k + 1] = current_pos;\n        }\n        for (int k = 1; k < N; ++k) {\n            lines[d][k] = max(lines[d][k - 1] + 1, min(lines[d][k], W - (N - k)));\n        }\n    }\n\n    // Stage 1: Coordinate Descent (Hill Climbing)\n    for (int iter = 0; iter < 50; ++iter) {\n        bool changed = false;\n        for (int d = 0; d < D; ++d) {\n            for (int k = 1; k < N; ++k) {\n                int best_pos = lines[d][k];\n                long long min_cost = -1;\n                int low = lines[d][k - 1] + 1;\n                int high = lines[d][k + 1] - 1;\n                for (int pos = low; pos <= high; ++pos) {\n                    long long cost = 0;\n                    cost += get_area_cost(W, a[d][k - 1], pos - lines[d][k - 1]);\n                    cost += get_area_cost(W, a[d][k], lines[d][k + 1] - pos);\n                    if (d > 0 && pos != lines[d - 1][k]) cost += 2LL * W;\n                    if (d < D - 1 && pos != lines[d + 1][k]) cost += 2LL * W;\n                    if (min_cost == -1 || cost < min_cost) {\n                        min_cost = cost;\n                        best_pos = pos;\n                    }\n                }\n                if (lines[d][k] != best_pos) {\n                    lines[d][k] = best_pos;\n                    changed = true;\n                }\n            }\n        }\n        if (!changed) break;\n    }\n\n    // Stage 2: Simulated Annealing\n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    double temp = 1000.0;\n    double min_temp = 1.0;\n    int iter = 0;\n\n    while (true) {\n        if ((iter & 2047) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 2800) break;\n        }\n        iter++;\n\n        int d = uniform_int_distribution<int>(0, D - 1)(rng);\n        int k = uniform_int_distribution<int>(1, N - 1)(rng);\n\n        int old_pos = lines[d][k];\n        int low = lines[d][k - 1] + 1;\n        int high = lines[d][k + 1] - 1;\n        if (low > high) continue;\n\n        int new_pos = uniform_int_distribution<int>(low, high)(rng);\n        if (new_pos == old_pos) continue;\n\n        long long delta = 0;\n        delta -= get_area_cost(W, a[d][k - 1], old_pos - lines[d][k - 1]);\n        delta -= get_area_cost(W, a[d][k], lines[d][k + 1] - old_pos);\n        delta += get_area_cost(W, a[d][k - 1], new_pos - lines[d][k - 1]);\n        delta += get_area_cost(W, a[d][k], lines[d][k + 1] - new_pos);\n\n        if (d > 0) {\n            if (old_pos != lines[d - 1][k]) delta -= 2 * W;\n            if (new_pos != lines[d - 1][k]) delta += 2 * W;\n        }\n        if (d < D - 1) {\n            if (old_pos != lines[d + 1][k]) delta -= 2 * W;\n            if (new_pos != lines[d + 1][k]) delta += 2 * W;\n        }\n\n        double acceptance = exp(-delta / temp);\n        if (delta < 0 || uniform_real_distribution<double>(0, 1)(rng) < acceptance) {\n            lines[d][k] = new_pos;\n        }\n\n        temp = max(min_temp, temp * 0.9999995);\n    }\n\n    // Output\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << lines[d][k] << \" \" << 0 << \" \" << lines[d][k + 1] << \" \" << W << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <algorithm>\n\n#pragma GCC optimize(\"O3\")\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint N, M, K;\nvector<vector<int>> A;\nvector<vector<vector<int>>> S;\nvector<vector<long long>> board;\nlong long current_score = 0;\n\nstruct Op {\n    int m, p, q;\n};\n\n// Apply or undo a stamp operation, updating the score locally\nvoid apply_op(const Op& op, int sign) {\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            int r = op.p + i;\n            int c = op.q + j;\n            current_score -= (board[r][c] % MOD);\n            if (sign == 1) {\n                board[r][c] += S[op.m][i][j];\n            } else {\n                board[r][c] -= S[op.m][i][j];\n            }\n            current_score += (board[r][c] % MOD);\n        }\n    }\n}\n\n// Function to reset the board to the initial state A\nvoid reset_board() {\n    current_score = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            board[i][j] = A[i][j];\n            current_score += (board[i][j] % MOD);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M >> K)) return 0;\n\n    A.assign(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> A[i][j];\n    \n    S.assign(M, vector<vector<int>>(3, vector<int>(3)));\n    for (int m = 0; m < M; ++m)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> S[m][i][j];\n\n    board.assign(N, vector<long long>(N));\n    \n    // Perform multiple randomized greedy trials to find a good starting point\n    vector<Op> best_ops;\n    long long best_total_score = -1;\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto start_time = chrono::steady_clock::now();\n\n    for (int trial = 0; trial < 20; ++trial) {\n        reset_board();\n        vector<Op> ops;\n        for (int k = 0; k < K; ++k) {\n            vector<pair<long long, Op>> candidates;\n            for (int m = 0; m < M; ++m) {\n                for (int p = 0; p <= N - 3; ++p) {\n                    for (int q = 0; q <= N - 3; ++q) {\n                        long long gain = 0;\n                        for (int i = 0; i < 3; ++i) {\n                            for (int j = 0; j < 3; ++j) {\n                                gain -= (board[p + i][q + j] % MOD);\n                                gain += ((board[p + i][q + j] + S[m][i][j]) % MOD);\n                            }\n                        }\n                        if (gain > 0) candidates.push_back({gain, {m, p, q}});\n                    }\n                }\n            }\n            if (candidates.empty()) break;\n            \n            // Randomly pick from top candidates to explore\n            sort(candidates.begin(), candidates.end(), [](const pair<long long, Op>& a, const pair<long long, Op>& b) {\n                return a.first > b.first;\n            });\n            int pick = rng() % min((int)candidates.size(), 3);\n            apply_op(candidates[pick].second, 1);\n            ops.push_back(candidates[pick].second);\n        }\n        \n        if (current_score > best_total_score) {\n            best_total_score = current_score;\n            best_ops = ops;\n        }\n        \n        if (chrono::duration<double>(chrono::steady_clock::now() - start_time).count() > 0.4) break;\n    }\n\n    // Initialize board with the best greedy solution\n    reset_board();\n    vector<Op> ops = best_ops;\n    for (const auto& op : ops) apply_op(op, 1);\n\n    // Simulated Annealing\n    double time_limit = 1.9; \n    double start_temp = 1e6;\n    double end_temp = 1e1;\n    double temp = start_temp;\n\n    int iter = 0;\n    while (true) {\n        if ((iter & 1023) == 0) {\n            auto current_time = chrono::steady_clock::now();\n            double elapsed = chrono::duration<double>(current_time - start_time).count();\n            if (elapsed > time_limit) break;\n            temp = start_temp * pow(end_temp / start_temp, elapsed / time_limit);\n        }\n        iter++;\n\n        // Move distribution: Modify (60%), Swap (30%), Add/Remove (10%)\n        int r = rng() % 100;\n        int move_type = 0;\n        if (r < 60) move_type = 0;      // Modify\n        else if (r < 90) move_type = 3; // Swap\n        else if (r < 95) move_type = 1; // Add\n        else move_type = 2;             // Remove\n\n        if (ops.empty()) move_type = 1;\n        else if ((int)ops.size() == K && move_type == 1) move_type = 0;\n        else if (ops.size() == 0 && move_type == 2) move_type = 1;\n        else if (ops.size() < 2 && move_type == 3) move_type = 0;\n\n        long long prev_score = current_score;\n        Op old_op, new_op;\n        int idx1 = -1, idx2 = -1;\n\n        if (move_type == 0) { // Modify\n            idx1 = rng() % ops.size();\n            old_op = ops[idx1];\n            new_op = { (int)(rng() % M), (int)(rng() % (N - 2)), (int)(rng() % (N - 2)) };\n            apply_op(old_op, -1);\n            apply_op(new_op, 1);\n        } else if (move_type == 1) { // Add\n            new_op = { (int)(rng() % M), (int)(rng() % (N - 2)), (int)(rng() % (N - 2)) };\n            apply_op(new_op, 1);\n        } else if (move_type == 2) { // Remove\n            idx1 = rng() % ops.size();\n            old_op = ops[idx1];\n            apply_op(old_op, -1);\n        } else if (move_type == 3) { // Swap\n            idx1 = rng() % ops.size(); idx2 = rng() % ops.size();\n            apply_op(ops[idx1], -1); apply_op(ops[idx2], -1);\n            swap(ops[idx1], ops[idx2]);\n            apply_op(ops[idx1], 1); apply_op(ops[idx2], 1);\n        }\n\n        if (current_score >= prev_score || (exp((double)(current_score - prev_score) / (temp + 1e-9)) > (double)rng() / rng.max())) {\n            if (move_type == 0) ops[idx1] = new_op;\n            else if (move_type == 1) ops.push_back(new_op);\n            else if (move_type == 2) ops.erase(ops.begin() + idx1);\n        } else {\n            if (move_type == 0) {\n                apply_op(new_op, -1); apply_op(old_op, 1); ops[idx1] = old_op;\n            } else if (move_type == 1) apply_op(new_op, -1);\n            else if (move_type == 2) apply_op(old_op, 1);\n            else if (move_type == 3) {\n                apply_op(ops[idx1], -1); apply_op(ops[idx2], -1);\n                swap(ops[idx1], ops[idx2]);\n                apply_op(ops[idx1], 1); apply_op(ops[idx2], 1);\n            }\n        }\n    }\n\n    cout << ops.size() << endl;\n    for (const auto& op : ops) cout << op.m << \" \" << op.p << \" \" << op.q << endl;\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cstring>\n\nusing namespace std;\n\nconst int N = 5;\n\nstruct Pos {\n    int r, c;\n    bool operator==(const Pos& other) const { return r == other.r && c == other.c; }\n    bool operator!=(const Pos& other) const { return !(*this == other); }\n};\n\nstruct Crane {\n    int id;\n    Pos pos;\n    int holding;\n    bool is_large;\n    string moves;\n};\n\nint grid[N][N];\nCrane cranes[N];\nint incoming[N][N];\nint incoming_ptr[N];\nint expected_container[N];\n\n// BFS to find the next step for a crane to reach a target\nPos get_next_move(int crane_idx, Pos target) {\n    if (cranes[crane_idx].pos == target) return target;\n\n    queue<pair<Pos, Pos>> q; // {current_pos, parent_pos}\n    q.push({cranes[crane_idx].pos, {-1, -1}});\n\n    Pos parent[N][N];\n    for(int i=0; i<N; ++i) for(int j=0; j<N; ++j) parent[i][j] = {-2, -2};\n    parent[cranes[crane_idx].pos.r][cranes[crane_idx].pos.c] = {-1, -1};\n\n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n\n    bool found = false;\n    Pos last = {-1, -1};\n\n    while (!q.empty()) {\n        Pos curr = q.front().first;\n        q.pop();\n\n        if (curr == target) {\n            found = true;\n            last = curr;\n            break;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && parent[nr][nc].r == -2) {\n                // Check if another crane is already occupying the square\n                bool crane_blocked = false;\n                for (int j = 0; j < N; ++j) {\n                    if (j != crane_idx && cranes[j].pos.r == nr && cranes[j].pos.c == nc) {\n                        crane_blocked = true;\n                        break;\n                    }\n                }\n                if (crane_blocked) continue;\n\n                // Special rule:\n                // Small cranes cannot move to a square with a container IF they are carrying a container\n                // Large cranes can always move to a square with a container\n                if (!cranes[crane_idx].is_large && cranes[crane_idx].holding != -1 && grid[nr][nc] != -1) {\n                    continue; \n                }\n\n                parent[nr][nc] = curr;\n                q.push({{nr, nc}, curr});\n            }\n        }\n        if (found) break;\n    }\n\n    if (!found) return cranes[crane_idx].pos;\n\n    // Backtrack to find the first move from the start\n    Pos curr = last;\n    while (parent[curr.r][curr.c] != cranes[crane_idx].pos) {\n        curr = parent[curr.r][curr.c];\n    }\n    return curr;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n_in;\n    cin >> n_in;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) cin >> incoming[i][j];\n        incoming_ptr[i] = 0;\n        expected_container[i] = N * i;\n    }\n\n    memset(grid, -1, sizeof(grid));\n    for (int i = 0; i < N; ++i) {\n        cranes[i] = {i, {i, 0}, -1, (i == 0), \"\"};\n    }\n\n    for (int turn = 0; turn < 10000; ++turn) {\n        // 1. Receive\n        for (int i = 0; i < N; ++i) {\n            if (incoming_ptr[i] < N && grid[i][0] == -1) {\n                bool crane_at_gate = false;\n                for(int k=0; k<N; ++k) if(cranes[k].pos.r == i && cranes[k].pos.c == 0) crane_at_gate = true;\n                if (!crane_at_gate) {\n                    grid[i][0] = incoming[i][incoming_ptr[i]++];\n                }\n            }\n        }\n\n        // 2. Action planning\n        vector<char> turn_actions(N, '.');\n        vector<Pos> next_positions(N);\n        for(int i=0; i<N; ++i) next_positions[i] = cranes[i].pos;\n\n        for (int i = 0; i < N; ++i) {\n            Crane &c = cranes[i];\n            \n            if (c.holding != -1) {\n                int target_row = c.holding / N;\n                Pos target = {target_row, N - 1};\n                \n                if (c.pos == target) {\n                    turn_actions[i] = 'Q';\n                } else {\n                    Pos next = get_next_move(i, target);\n                    if (next != c.pos) {\n                        next_positions[i] = next;\n                        turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                    } else turn_actions[i] = '.';\n                }\n            } else {\n                Pos target = {-1, -1};\n                \n                // Priority 1: Clear wrong container at dispatch gate\n                for (int r = 0; r < N; ++r) {\n                    if (grid[r][N-1] != -1 && grid[r][N-1] != expected_container[r]) {\n                        target = {r, N-1};\n                        break;\n                    }\n                }\n                \n                // Priority 2: Pick up expected container for this crane's row (or any expected container for the large crane)\n                if (target.r == -1) {\n                    for (int r = 0; r < N; ++r) {\n                        for (int col = 0; col < N; ++col) {\n                            if (grid[r][col] == expected_container[r]) {\n                                // Large crane handles any, small crane only handles its own row\n                                if (i == 0 || r == i) {\n                                    target = {r, col};\n                                    goto found;\n                                }\n                            }\n                        }\n                    }\n                }\n                found:;\n                \n                // Priority 3: Move to home position\n                if (target.r == -1) {\n                    target = {i, 1};\n                }\n\n                if (c.pos == target) {\n                    // If we are at target and there is a container, P it\n                    if (grid[target.r][target.c] != -1) {\n                        turn_actions[i] = 'P';\n                    } else {\n                        turn_actions[i] = '.';\n                    }\n                } else {\n                    Pos next = get_next_move(i, target);\n                    if (next != c.pos) {\n                        next_positions[i] = next;\n                        turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                    } else turn_actions[i] = '.';\n                }\n            }\n        }\n\n        // Conflict Resolution\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (turn_actions[i] != '.' && turn_actions[j] != '.' && \n                    turn_actions[i] != 'P' && turn_actions[j] != 'P' &&\n                    turn_actions[i] != 'Q' && turn_actions[j] != 'Q' &&\n                    next_positions[i] == next_positions[j]) {\n                    turn_actions[j] = '.';\n                    next_positions[j] = cranes[j].pos;\n                }\n            }\n        }\n\n        // Apply actions\n        for (int i = 0; i < N; ++i) {\n            char a = turn_actions[i];\n            cranes[i].moves += a;\n            if (a == 'P') {\n                cranes[i].holding = grid[cranes[i].pos.r][cranes[i].pos.c];\n                grid[cranes[i].pos.r][cranes[i].pos.c] = -1;\n            } else if (a == 'Q') {\n                grid[cranes[i].pos.r][cranes[i].pos.c] = cranes[i].holding;\n                cranes[i].holding = -1;\n            } else if (a != '.' && a != 'B') {\n                cranes[i].pos = next_positions[i];\n            }\n        }\n\n        // Dispatch\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][N-1] == expected_container[i]) {\n                grid[i][N-1] = -1;\n                expected_container[i]++;\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) cout << cranes[i].moves << \"\\n\";\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 20;\nint H[N][N];\nint curr_r = 0, curr_c = 0;\nlong long current_load = 0;\n\nstruct Pos {\n    int r, c;\n};\n\n// Process the current cell: pick up surplus if available, and drop off if we have a load and there is a deficit\nvoid process_cell() {\n    // 1. Pick up surplus\n    if (H[curr_r][curr_c] > 0) {\n        int d = H[curr_r][curr_c];\n        cout << \"+\" << d << \"\\n\";\n        current_load += d;\n        H[curr_r][curr_c] = 0;\n    }\n    // 2. Drop off deficit\n    if (current_load > 0 && H[curr_r][curr_c] < 0) {\n        int d = min((long long)current_load, (long long)-H[curr_r][curr_c]);\n        cout << \"-\" << d << \"\\n\";\n        current_load -= d;\n        H[curr_r][curr_c] += d;\n    }\n}\n\n// Move to adjacent cell\nvoid move_to(int nr, int nc) {\n    if (nr == curr_r - 1) cout << \"U\" << \"\\n\";\n    else if (nr == curr_r + 1) cout << \"D\" << \"\\n\";\n    else if (nc == curr_c - 1) cout << \"L\" << \"\\n\";\n    else if (nc == curr_c + 1) cout << \"R\" << \"\\n\";\n    curr_r = nr;\n    curr_c = nc;\n}\n\n// Find the best target cell using a load-aware heuristic\nPos find_best_target() {\n    double max_score = -1.0;\n    Pos best = {-1, -1};\n    \n    for(int i = 0; i < N; ++i) {\n        for(int j = 0; j < N; ++j) {\n            if (H[i][j] == 0) continue;\n            \n            // If empty, skip deficit targets\n            if (H[i][j] < 0 && current_load == 0) continue;\n            \n            int dist = abs(i - curr_r) + abs(j - curr_c);\n            double score;\n            \n            // Score based on magnitude of imbalance and inverse of distance\n            if (H[i][j] > 0) {\n                score = (double)H[i][j] / (dist + 1.0);\n            } else {\n                // Higher multiplier for deficits when carrying more load\n                score = (double)abs(H[i][j]) * (1.0 + (double)current_load / 50.0) / (dist + 1.0);\n            }\n            \n            if (score > max_score) {\n                max_score = score;\n                best = {i, j};\n            }\n        }\n    }\n    return best;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n;\n    cin >> n;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) cin >> H[i][j];\n    }\n\n    // Process initial position\n    process_cell();\n\n    while (true) {\n        Pos target = find_best_target();\n        if (target.r == -1) break;\n\n        // Move towards target step-by-step\n        while (curr_r != target.r || curr_c != target.c) {\n            int nr = curr_r, nc = curr_c;\n            \n            // Prioritize movement in the dimension with larger distance\n            if (abs(curr_r - target.r) >= abs(curr_c - target.c)) {\n                if (curr_r < target.r) nr++;\n                else if (curr_r > target.r) nr--;\n                else if (curr_c < target.c) nc++;\n                else if (curr_c > target.c) nc--;\n            } else {\n                if (curr_c < target.c) nc++;\n                else if (curr_c > target.c) nc--;\n                else if (curr_r < target.r) nr++;\n                else if (curr_r > target.r) nr--;\n            }\n            \n            move_to(nr, nc);\n            process_cell();\n        }\n    }\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\n// Pairwise potential: sum(max(A_l, B_l)) for all criteria l.\nint precomputed_costs[60][60];\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seed_count = 2 * N * (N - 1); // 60\n    int grid_size = N * N; // 36\n    vector<vector<int>> seeds(seed_count, vector<int>(M));\n\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i][j];\n        }\n    }\n\n    // Precompute neighbors\n    vector<vector<int>> adj(grid_size);\n    for (int i = 0; i < grid_size; ++i) {\n        int r = i / N;\n        int c = i % N;\n        if (r > 0) adj[i].push_back((r - 1) * N + c);\n        if (r < N - 1) adj[i].push_back((r + 1) * N + c);\n        if (c > 0) adj[i].push_back(r * N + c - 1);\n        if (c < N - 1) adj[i].push_back(r * N + c + 1);\n    }\n\n    mt19937 rng(1337); \n\n    vector<int> grid_indices(grid_size);\n    vector<int> unused_indices(seed_count - grid_size);\n    \n    // Initial selection\n    vector<pair<long long, int>> seed_scores(seed_count);\n    for (int i = 0; i < seed_count; ++i) {\n        long long sum_val = 0;\n        for (int l = 0; l < M; ++l) sum_val += seeds[i][l];\n        seed_scores[i] = {sum_val, i};\n    }\n    sort(seed_scores.rbegin(), seed_scores.rend());\n    \n    vector<bool> is_on_grid(seed_count, false);\n    for (int i = 0; i < grid_size; ++i) {\n        grid_indices[i] = seed_scores[i].second;\n        is_on_grid[grid_indices[i]] = true;\n    }\n    int u_idx = 0;\n    for (int i = 0; i < seed_count; ++i) {\n        if (!is_on_grid[i]) {\n            unused_indices[u_idx++] = i;\n        }\n    }\n\n    for (int t = 0; t < T; t++) {\n        // Precompute pair costs for this turn\n        for (int i = 0; i < seed_count; ++i) {\n            for (int j = 0; j < seed_count; ++j) {\n                int cost = 0;\n                for (int l = 0; l < M; ++l) {\n                    cost += max(seeds[i][l], seeds[j][l]);\n                }\n                precomputed_costs[i][j] = cost;\n            }\n        }\n\n        // Simulated Annealing\n        int iterations = 2000000;\n        double start_temp = 50.0;\n        double end_temp = 0.05;\n        double temp = start_temp;\n        double cooling = pow(end_temp / start_temp, 1.0 / iterations);\n\n        for (int iter = 0; iter < iterations; ++iter) {\n            int p1 = rng() % grid_size;\n            bool is_grid_grid = (rng() % 2 == 0);\n            int p2;\n            if (is_grid_grid) {\n                p2 = rng() % grid_size;\n                if (p1 == p2) continue;\n            } else {\n                p2 = rng() % (seed_count - grid_size);\n            }\n\n            int v1 = grid_indices[p1];\n            int v2 = is_grid_grid ? grid_indices[p2] : unused_indices[p2];\n\n            long long delta = 0;\n            if (is_grid_grid) {\n                // p1 has v1, p2 has v2. Swapping them.\n                // Correct cost delta calculation:\n                // Sum_old = (Sum over adj[p1] excluding p2: cost(v1, seed_n)) + (Sum over adj[p2] excluding p1: cost(v2, seed_n)) + cost(v1, v2)\n                // Sum_new = (Sum over adj[p1] excluding p2: cost(v2, seed_n)) + (Sum over adj[p2] excluding p1: cost(v1, seed_n)) + cost(v2, v1)\n                long long old_c = 0;\n                for (int n : adj[p1]) if (n != p2) old_c += precomputed_costs[v1][grid_indices[n]];\n                for (int n : adj[p2]) if (n != p1) old_c += precomputed_costs[v2][grid_indices[n]];\n                old_c += precomputed_costs[v1][v2];\n\n                long long new_c = 0;\n                for (int n : adj[p1]) if (n != p2) new_c += precomputed_costs[v2][grid_indices[n]];\n                for (int n : adj[p2]) if (n != p1) new_c += precomputed_costs[v1][grid_indices[n]];\n                new_c += precomputed_costs[v2][v1];\n                \n                delta = new_c - old_c;\n            } else {\n                // p1 has v1, replacing with v2.\n                long long old_c = 0;\n                for (int n : adj[p1]) old_c += precomputed_costs[v1][grid_indices[n]];\n                \n                long long new_c = 0;\n                for (int n : adj[p1]) new_c += precomputed_costs[v2][grid_indices[n]];\n                \n                delta = new_c - old_c;\n            }\n\n            if (delta > 0 || (temp > 1e-9 && exp(delta / temp) > (double)(rng() % 1000000) / 1000000.0)) {\n                if (is_grid_grid) {\n                    swap(grid_indices[p1], grid_indices[p2]);\n                } else {\n                    grid_indices[p1] = v2;\n                    unused_indices[p2] = v1;\n                }\n            }\n            temp *= cooling;\n        }\n\n        // Output\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << grid_indices[i * N + j];\n                if (j < N - 1) cout << \" \";\n            }\n            cout << \"\\n\";\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> seeds[i][j];\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Coordinate structure\nstruct Point {\n    int x, y;\n};\n\n// Robot vertex structure\nstruct Vertex {\n    int id;\n    int parent;\n    int L;\n    int dir; // 0=R, 1=D, 2=L, 3=U\n    bool holding;\n    Point target;\n};\n\nint N, M, V_avail;\nvector<vector<int>> s, t; // s=takoyaki (1 present), t=target (1 present)\nint rx, ry;\nvector<Vertex> robot;\n\n// Directions: R, D, L, U (0, 1, 2, 3)\nint DX[] = {0, 1, 0, -1};\nint DY[] = {1, 0, -1, 0};\nchar DIRS[] = {'R', 'D', 'L', 'U'};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M >> V_avail)) return 0;\n    s.resize(N, vector<int>(N));\n    t.resize(N, vector<int>(N));\n    \n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) s[i][j] = row[j] - '0';\n    }\n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) t[i][j] = row[j] - '0';\n    }\n\n    // Design robot: star graph with varying edge lengths\n    int V_prime = V_avail;\n    robot.resize(V_prime);\n    robot[0] = {0, -1, 0, 0, false, {-1, -1}};\n    for (int i = 1; i < V_prime; ++i) {\n        // Distribute edge lengths more diversely to cover the grid\n        int len = (i - 1) % min(N - 1, 7) + 1;\n        robot[i] = {i, 0, len, 0, false, {-1, -1}};\n    }\n\n    cout << V_prime << endl;\n    for (int i = 1; i < V_prime; ++i) {\n        cout << robot[i].parent << \" \" << robot[i].L << endl;\n    }\n    rx = N / 2;\n    ry = N / 2;\n    cout << rx << \" \" << ry << endl;\n\n    // Simulation\n    for (int turn = 0; turn < 100000; ++turn) {\n        // 1. Identify/Update targets\n        int current_m = 0;\n        vector<Point> takoyaki_squares;\n        vector<Point> target_squares;\n        for(int i=0; i<N; ++i) {\n            for(int j=0; j<N; ++j) {\n                if (s[i][j] && t[i][j]) current_m++;\n                if (s[i][j] && !t[i][j]) takoyaki_squares.push_back({i, j});\n                if (t[i][j] && !s[i][j]) target_squares.push_back({i, j});\n            }\n        }\n        if (current_m == M) break;\n\n        for (int i = 1; i < V_prime; ++i) {\n            if (robot[i].target.x >= 0) {\n                bool valid = false;\n                if (robot[i].holding) {\n                    if (t[robot[i].target.x][robot[i].target.y] == 1 && s[robot[i].target.x][robot[i].target.y] == 0) valid = true;\n                } else {\n                    if (s[robot[i].target.x][robot[i].target.y] == 1 && t[robot[i].target.x][robot[i].target.y] == 0) valid = true;\n                }\n                if (!valid) robot[i].target = {-1, -1};\n            }\n\n            if (robot[i].target.x == -1) {\n                int min_dist = 1e9;\n                Point best_p = {-1, -1};\n                if (robot[i].holding) {\n                    for (auto& p : target_squares) {\n                        int dist = abs(p.x - rx) + abs(p.y - ry);\n                        if (dist < min_dist) { min_dist = dist; best_p = p; }\n                    }\n                } else {\n                    for (auto& p : takoyaki_squares) {\n                        int dist = abs(p.x - rx) + abs(p.y - ry);\n                        if (dist < min_dist) { min_dist = dist; best_p = p; }\n                    }\n                }\n                robot[i].target = best_p;\n            }\n        }\n\n        // 2. Choose best root move and rotations\n        int best_move = 4; // Stay\n        double min_cost = 1e18;\n        vector<int> best_rots(V_prime, 0);\n\n        int move_dx[] = {-1, 1, 0, 0, 0}; // U, D, L, R, .\n        int move_dy[] = {0, 0, -1, 1, 0};\n        char move_char[] = {'U', 'D', 'L', 'R', '.'};\n\n        for (int m = 0; m < 5; ++m) {\n            int nrx = rx + move_dx[m];\n            int nry = ry + move_dy[m];\n            if (nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n\n            double cost = 0;\n            vector<int> current_rots(V_prime, 0);\n\n            for (int i = 1; i < V_prime; ++i) {\n                double best_d = 1e9;\n                int best_r = 0;\n                \n                for (int r = 0; r < 3; ++r) {\n                    int ndir = robot[i].dir;\n                    if (r == 1) ndir = (ndir + 3) % 4;\n                    else if (r == 2) ndir = (ndir + 1) % 4;\n                    int fx = nrx + DX[ndir] * robot[i].L;\n                    int fy = nry + DY[ndir] * robot[i].L;\n                    \n                    double d;\n                    if (robot[i].target.x >= 0) {\n                        d = abs(fx - robot[i].target.x) + abs(fy - robot[i].target.y);\n                        // Heuristic: If holding, prioritize dropping.\n                        if (robot[i].holding) d *= 1.5; \n                    } else {\n                        // Heuristic: Move to center if idle (resting position)\n                        d = abs(fx - N/2) + abs(fy - N/2);\n                        d *= 0.1; // Lower priority than active tasks\n                    }\n                    if (d < best_d) { best_d = d; best_r = r; }\n                }\n                cost += best_d;\n                current_rots[i] = best_r;\n            }\n            if (cost < min_cost) {\n                min_cost = cost;\n                best_move = m;\n                best_rots = current_rots;\n            }\n        }\n\n        // Apply best move\n        rx += move_dx[best_move];\n        ry += move_dy[best_move];\n        \n        string S = \"\";\n        S += move_char[best_move];\n        for (int i = 1; i < V_prime; ++i) {\n            if (best_rots[i] == 1) { S += 'L'; robot[i].dir = (robot[i].dir + 3) % 4; }\n            else if (best_rots[i] == 2) { S += 'R'; robot[i].dir = (robot[i].dir + 1) % 4; }\n            else S += '.';\n        }\n\n        // 3. Actions\n        string actions = \".\";\n        for (int i = 1; i < V_prime; ++i) {\n            int fx = rx + DX[robot[i].dir] * robot[i].L;\n            int fy = ry + DY[robot[i].dir] * robot[i].L;\n            bool action = false;\n            if (fx >= 0 && fx < N && fy >= 0 && fy < N) {\n                if (robot[i].holding) {\n                    if (t[fx][fy] == 1 && s[fx][fy] == 0) {\n                        robot[i].holding = false;\n                        s[fx][fy] = 1;\n                        action = true;\n                    }\n                } else {\n                    if (s[fx][fy] == 1 && t[fx][fy] == 0) {\n                        robot[i].holding = true;\n                        s[fx][fy] = 0;\n                        action = true;\n                    }\n                }\n            }\n            actions += (action ? 'P' : '.');\n        }\n        cout << S << actions << endl;\n    }\n\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Fish {\n    int x, y, type; // 1 for mackerel, -1 for sardine\n};\n\nconst int GRID_SIZE = 128;\nconst int MAX_COORD = 100000;\n\n// Function to calculate the net score (mackerels - sardines) for a rectangle\nint calculate_score(const vector<Fish>& fish, int x1, int y1, int x2, int y2) {\n    if (x1 >= x2 || y1 >= y2) return 0;\n    int score = 0;\n    for (const auto& f : fish) {\n        if (f.x >= x1 && f.x <= x2 && f.y >= y1 && f.y <= y2) {\n            score += f.type;\n        }\n    }\n    return score;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<Fish> fish;\n    fish.reserve(2 * N);\n    \n    // Grid to estimate the best initial rectangle\n    vector<vector<int>> grid(GRID_SIZE, vector<int>(GRID_SIZE, 0));\n    \n    for (int i = 0; i < N; ++i) {\n        int x, y; cin >> x >> y;\n        fish.push_back({x, y, 1});\n        grid[min(x * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1)][min(y * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1)]++;\n    }\n    for (int i = 0; i < N; ++i) {\n        int x, y; cin >> x >> y;\n        fish.push_back({x, y, -1});\n        grid[min(x * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1)][min(y * GRID_SIZE / (MAX_COORD + 1), GRID_SIZE - 1)]--;\n    }\n\n    // 2D Kadane's to find initial optimal rectangle\n    int max_sum = 0;\n    int best_i1 = 0, best_j1 = 0, best_i2 = 0, best_j2 = 0;\n\n    for (int i1 = 0; i1 < GRID_SIZE; ++i1) {\n        vector<int> col_sum(GRID_SIZE, 0);\n        for (int i2 = i1; i2 < GRID_SIZE; ++i2) {\n            for (int j = 0; j < GRID_SIZE; ++j) col_sum[j] += grid[i2][j];\n            int current_sum = 0, start_j = 0;\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                current_sum += col_sum[j];\n                if (current_sum > max_sum) {\n                    max_sum = current_sum;\n                    best_i1 = i1; best_i2 = i2;\n                    best_j1 = start_j; best_j2 = j;\n                }\n                if (current_sum < 0) {\n                    current_sum = 0;\n                    start_j = j + 1;\n                }\n            }\n        }\n    }\n\n    // Convert grid indices to original coordinates\n    double step = (double)(MAX_COORD + 1) / GRID_SIZE;\n    int x1 = max(0, min(MAX_COORD, (int)(best_i1 * step)));\n    int y1 = max(0, min(MAX_COORD, (int)(best_j1 * step)));\n    int x2 = max(0, min(MAX_COORD, (int)((best_i2 + 1) * step)));\n    int y2 = max(0, min(MAX_COORD, (int)((best_j2 + 1) * step)));\n\n    // Hill Climbing Refinement\n    int current_score = calculate_score(fish, x1, y1, x2, y2);\n    int step_size = 2000;\n    while (step_size > 0) {\n        bool improved = false;\n        int* coords[4] = {&x1, &x2, &y1, &y2};\n        \n        for (int i = 0; i < 4; ++i) {\n            int original = *coords[i];\n            for (int delta : {-step_size, step_size}) {\n                int next = original + delta;\n                int cur_x1 = (i == 0) ? next : x1;\n                int cur_x2 = (i == 1) ? next : x2;\n                int cur_y1 = (i == 2) ? next : y1;\n                int cur_y2 = (i == 3) ? next : y2;\n\n                // Validate new rectangle bounds\n                if (cur_x1 >= cur_x2 || cur_y1 >= cur_y2) continue;\n                if (cur_x1 < 0 || cur_x1 > MAX_COORD || cur_x2 < 0 || cur_x2 > MAX_COORD ||\n                    cur_y1 < 0 || cur_y1 > MAX_COORD || cur_y2 < 0 || cur_y2 > MAX_COORD) continue;\n                \n                *coords[i] = next;\n                int s = calculate_score(fish, x1, y1, x2, y2);\n                if (s > current_score) {\n                    current_score = s;\n                    improved = true;\n                } else {\n                    *coords[i] = original; // Backtrack\n                }\n            }\n        }\n        if (!improved) step_size /= 2;\n    }\n\n    // Output the optimized rectangle\n    cout << 4 << endl;\n    cout << x1 << \" \" << y1 << endl;\n    cout << x2 << \" \" << y1 << endl;\n    cout << x2 << \" \" << y2 << endl;\n    cout << x1 << \" \" << y2 << endl;\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\n// Configuration for a single rectangle's placement\nstruct Placement {\n    int id;\n    int r;           // Rotation (0 or 1)\n    char d;          // Direction ('U' or 'L')\n    int b;           // Reference rectangle index (-1 for origin)\n    bool included;   // Whether it's included in the packing\n};\n\nint N, T;\ndouble sigma;\nlong long W_obs_all[105], H_obs_all[105];\n\n// Rectangles data for simulation\nstruct Rect {\n    long long x, y, w, h;\n};\nRect placed_rects[105];\nbool is_included[105];\n\n// Efficient simulation using static arrays\nlong long simulate(const vector<Placement>& config, long long& W, long long& H) {\n    W = 0;\n    H = 0;\n    long long current_cost = 0;\n\n    // Reset status\n    for (int i = 0; i < N; ++i) is_included[i] = false;\n    for (int i = 0; i < N; ++i) if (config[i].included) is_included[config[i].id] = true;\n\n    for (int i = 0; i < N; ++i) {\n        if (!config[i].included) {\n            current_cost += (W_obs_all[config[i].id] + H_obs_all[config[i].id]);\n            continue;\n        }\n\n        int idx = config[i].id;\n        long long cur_w = (config[i].r == 0) ? W_obs_all[idx] : H_obs_all[idx];\n        long long cur_h = (config[i].r == 0) ? H_obs_all[idx] : W_obs_all[idx];\n\n        long long x, y;\n        int ref = config[i].b;\n        if (ref != -1 && !is_included[ref]) ref = -1;\n\n        if (config[i].d == 'U') {\n            x = (ref == -1) ? 0 : (placed_rects[ref].x + placed_rects[ref].w);\n            y = 0;\n            for (int j = 0; j < i; ++j) {\n                if (config[j].included) {\n                    const Rect& r = placed_rects[config[j].id];\n                    if (x < r.x + r.w && x + cur_w > r.x) {\n                        if (r.y + r.h > y) y = r.y + r.h;\n                    }\n                }\n            }\n        } else {\n            y = (ref == -1) ? 0 : (placed_rects[ref].y + placed_rects[ref].h);\n            x = 0;\n            for (int j = 0; j < i; ++j) {\n                if (config[j].included) {\n                    const Rect& r = placed_rects[config[j].id];\n                    if (y < r.y + r.h && y + cur_h > r.y) {\n                        if (r.x + r.w > x) x = r.x + r.w;\n                    }\n                }\n            }\n        }\n        \n        placed_rects[idx] = {x, y, cur_w, cur_h};\n        if (x + cur_w > W) W = x + cur_w;\n        if (y + cur_h > H) H = y + cur_h;\n    }\n    return W + H + current_cost;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> T >> sigma)) return 0;\n    for (int i = 0; i < N; ++i) cin >> W_obs_all[i] >> H_obs_all[i];\n\n    mt19937 rng(12345);\n    vector<Placement> best_config(N);\n    // Initialize config: placing rectangles in index order 0..N-1\n    for (int i = 0; i < N; ++i) best_config[i] = {i, 0, 'U', -1, true};\n\n    long long W, H;\n    long long best_sim_score = simulate(best_config, W, H);\n    double temp = 1000.0; // Initial temperature for SA\n\n    for (int t = 0; t < T; ++t) {\n        vector<Placement> current_config = best_config;\n        long long current_sim_score = best_sim_score;\n        \n        const int iterations = 500; \n        for (int iter = 0; iter < iterations; ++iter) {\n            int idx = rng() % N;\n            Placement old = current_config[idx];\n            \n            int mutation = rng() % 4;\n            if (mutation == 0) current_config[idx].r = 1 - current_config[idx].r;\n            else if (mutation == 1) current_config[idx].d = (current_config[idx].d == 'U' ? 'L' : 'U');\n            else if (mutation == 2) {\n                if (rng() % 3 == 0) current_config[idx].b = -1;\n                else if (idx > 0) {\n                    // Pick from previously placed rectangles\n                    current_config[idx].b = current_config[rng() % idx].id;\n                }\n            }\n            else current_config[idx].included = !current_config[idx].included;\n\n            long long new_W, new_H;\n            long long new_score = simulate(current_config, new_W, new_H);\n            \n            // Acceptance probability for Simulated Annealing\n            double delta = (double)(new_score - current_sim_score);\n            if (delta < 0 || exp(-delta / temp) > (double)(rng() % 10000) / 10000.0) {\n                current_sim_score = new_score;\n                if (new_score < best_sim_score) {\n                    best_sim_score = new_score;\n                    best_config = current_config;\n                }\n            } else {\n                current_config[idx] = old; // Backtrack\n            }\n        }\n        temp *= 0.95; // Cool down\n\n        // Output current best\n        int count = 0;\n        for (const auto& p : best_config) if (p.included) count++;\n        \n        cout << count << endl;\n        for (const auto& p : best_config) {\n            if (p.included)\n                cout << p.id << \" \" << p.r << \" \" << p.d << \" \" << p.b << endl;\n        }\n        cout.flush();\n\n        long long W_obs, H_obs;\n        if (!(cin >> W_obs >> H_obs)) break;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <ctime>\n#include <chrono>\n\nusing namespace std;\n\n// Struct to represent an edge in the priority queue\nstruct Item {\n    int priority;\n    int u; // parent node\n    int v; // child node\n    bool operator<(const Item& other) const {\n        return priority < other.priority;\n    }\n};\n\nvoid solve() {\n    int N, M, H;\n    if (!(cin >> N >> M >> H)) return;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    // Skip coordinates as they are not used in the greedy logic\n    int x, y;\n    for (int i = 0; i < N; ++i) cin >> x >> y;\n\n    vector<int> best_p(N, -1);\n    long long best_score = -1;\n\n    // Time limit handling\n    clock_t start_time = clock();\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist(80, 120);\n    \n    // For root selection order\n    vector<int> nodes(N);\n    for(int i=0; i<N; ++i) nodes[i] = i;\n\n    int iter = 0;\n    while (true) {\n        // Periodically check time\n        if (iter % 10 == 0) {\n            if ((double)(clock() - start_time) / CLOCKS_PER_SEC > 1.8) break;\n        }\n        iter++;\n        \n        vector<int> p(N, -1);\n        vector<int> depth(N, 0);\n        vector<bool> visited(N, false);\n        \n        // Root selection heuristic to explore different configurations\n        if (iter % 3 == 0) {\n            sort(nodes.begin(), nodes.end(), [&](int a, int b){ return A[a] < A[b]; });\n        } else if (iter % 3 == 1) {\n            sort(nodes.begin(), nodes.end(), [&](int a, int b){ return A[a] > A[b]; });\n        } else {\n            shuffle(nodes.begin(), nodes.end(), rng);\n        }\n        \n        priority_queue<Item> pq;\n        int unvisited_count = N;\n        int order_idx = 0;\n        \n        // Build the forest\n        while (unvisited_count > 0) {\n            // Find next unvisited node to be a potential root\n            while (order_idx < N && visited[nodes[order_idx]]) {\n                order_idx++;\n            }\n            \n            if (pq.empty()) {\n                if (order_idx < N) {\n                    int r = nodes[order_idx];\n                    visited[r] = true;\n                    p[r] = -1;\n                    depth[r] = 0;\n                    unvisited_count--;\n                    \n                    // Add neighbors to PQ\n                    for (int neighbor : adj[r]) {\n                        if (!visited[neighbor]) {\n                            int gain = (depth[r] + 2) * A[neighbor];\n                            int randomized_gain = gain * dist(rng) / 100;\n                            pq.push({randomized_gain, r, neighbor});\n                        }\n                    }\n                }\n            } else {\n                Item top = pq.top();\n                pq.pop();\n                \n                if (visited[top.v]) continue;\n                // Constraint check: must not exceed depth H\n                if (depth[top.u] >= H) continue;\n                \n                visited[top.v] = true;\n                p[top.v] = top.u;\n                depth[top.v] = depth[top.u] + 1;\n                unvisited_count--;\n                \n                // Add neighbors to PQ\n                for (int neighbor : adj[top.v]) {\n                    if (!visited[neighbor]) {\n                        int gain = (depth[top.v] + 2) * A[neighbor];\n                        int randomized_gain = gain * dist(rng) / 100;\n                        pq.push({randomized_gain, top.v, neighbor});\n                    }\n                }\n            }\n        }\n        \n        // Calculate score\n        long long current_score = 0;\n        for (int j = 0; j < N; ++j) {\n            current_score += (long long)(depth[j] + 1) * A[j];\n        }\n        \n        // Keep the best solution\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_p = p;\n        }\n    }\n    \n    // Output final solution\n    for (int i = 0; i < N; ++i) {\n        cout << best_p[i] << (i == N - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    solve();\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n// Global variables\nint N;\nchar board[20][20];\n// Pre-calculate safety using prefix sums\n// row_fuku[r][c] = number of Fukunokami in row r in columns 0 to c-1\nint row_fuku[20][21]; \nint col_fuku[20][21]; \n\n// Update prefix sums after a board change\nvoid update_fuku_prefix() {\n    for (int i = 0; i < N; ++i) {\n        row_fuku[i][0] = 0;\n        for (int j = 0; j < N; ++j) {\n            row_fuku[i][j+1] = row_fuku[i][j] + (board[i][j] == 'o' ? 1 : 0);\n        }\n    }\n    for (int j = 0; j < N; ++j) {\n        col_fuku[j][0] = 0;\n        for (int i = 0; i < N; ++i) {\n            col_fuku[j][i+1] = col_fuku[j][i] + (board[i][j] == 'o' ? 1 : 0);\n        }\n    }\n}\n\n// O(1) safety check using prefix sums\nbool is_safe_fast(int r, int c, char dir) {\n    if (dir == 'U') {\n        // No Fukunokami in col c, rows 0 to r-1\n        return (col_fuku[c][r] - col_fuku[c][0]) == 0;\n    } else if (dir == 'D') {\n        // No Fukunokami in col c, rows r+1 to N-1\n        return (col_fuku[c][N] - col_fuku[c][r+1]) == 0;\n    } else if (dir == 'L') {\n        // No Fukunokami in row r, cols 0 to c-1\n        return (row_fuku[r][c] - row_fuku[r][0]) == 0;\n    } else if (dir == 'R') {\n        // No Fukunokami in row r, cols c+1 to N-1\n        return (row_fuku[r][N] - row_fuku[r][c+1]) == 0;\n    }\n    return true;\n}\n\n// Perform the shift\nvoid apply_move(char dir, int p) {\n    if (dir == 'U') {\n        for (int i = 0; i < N - 1; ++i) board[i][p] = board[i+1][p];\n        board[N-1][p] = '.';\n    } else if (dir == 'D') {\n        for (int i = N - 1; i > 0; --i) board[i][p] = board[i-1][p];\n        board[0][p] = '.';\n    } else if (dir == 'L') {\n        for (int j = 0; j < N - 1; ++j) board[p][j] = board[p][j+1];\n        board[p][N-1] = '.';\n    } else if (dir == 'R') {\n        for (int j = N - 1; j > 0; --j) board[p][j] = board[p][j-1];\n        board[p][0] = '.';\n    }\n    update_fuku_prefix();\n}\n\nstruct Move {\n    char dir;\n    int p;\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N)) return 0;\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) board[i][j] = row[j];\n    }\n    update_fuku_prefix();\n\n    vector<Move> ans;\n    // Iterate up to the max possible moves 4N^2\n    for (int iter = 0; iter < 4 * N * N; ++iter) {\n        int best_r = -1, best_c = -1;\n        char best_dir = ' ';\n        int best_score = -1;\n        bool oni_found = false;\n\n        // Greedy search: find the best safe move\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (board[r][c] == 'x') {\n                    oni_found = true;\n                    char dirs[] = {'U', 'D', 'L', 'R'};\n                    for (char d : dirs) {\n                        if (is_safe_fast(r, c, d)) {\n                            // Check if this move removes the Oni immediately\n                            bool immediate = false;\n                            if (d == 'U' && r == 0) immediate = true;\n                            else if (d == 'D' && r == N - 1) immediate = true;\n                            else if (d == 'L' && c == 0) immediate = true;\n                            else if (d == 'R' && c == N - 1) immediate = true;\n\n                            // Score: Priority to immediate removals\n                            int score = immediate ? 2 : 1;\n                            if (score > best_score) {\n                                best_score = score;\n                                best_dir = d;\n                                best_r = r;\n                                best_c = c;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        if (!oni_found) break; // All Oni removed\n        if (best_dir == ' ') break; // Should not happen based on problem constraints\n\n        int p = (best_dir == 'U' || best_dir == 'D') ? best_c : best_r;\n        apply_move(best_dir, p);\n        ans.push_back({best_dir, p});\n    }\n\n    for (const auto& m : ans) {\n        cout << m.dir << \" \" << m.p << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\n// Problem constants\nconst int MAX_N = 100;\nint N, L;\nint T[MAX_N];\nint a[MAX_N], b[MAX_N];\nint counts[MAX_N];\n\n// Fast simulation function\n// Returns the L1 error of the cleaning plan\ninline long long calculate_error(const int* a_ptr, const int* b_ptr) {\n    // Reset counts using memset for performance\n    memset(counts, 0, sizeof(int) * N);\n    \n    int current = 0;\n    counts[0] = 1;\n    \n    // Simulate L weeks\n    for (int i = 1; i < L; ++i) {\n        // parity: counts[current] % 2\n        // If parity is odd, use a[current], otherwise use b[current]\n        int next = (counts[current] & 1) ? a_ptr[current] : b_ptr[current];\n        current = next;\n        counts[current]++;\n    }\n    \n    // Calculate L1 error\n    long long error = 0;\n    for (int i = 0; i < N; ++i) {\n        error += abs(counts[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    // Read Input\n    if (!(cin >> N >> L)) return 0;\n    for (int i = 0; i < N; ++i) cin >> T[i];\n    \n    // Random number generator\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    // Initial state: random assignment\n    for (int i = 0; i < N; ++i) {\n        a[i] = rng() % N;\n        b[i] = rng() % N;\n    }\n    \n    long long current_error = calculate_error(a, b);\n    \n    // Keep track of the best solution found\n    long long best_error = current_error;\n    int best_a[MAX_N], best_b[MAX_N];\n    memcpy(best_a, a, sizeof(int) * N);\n    memcpy(best_b, b, sizeof(int) * N);\n    \n    auto start_time = chrono::steady_clock::now();\n    \n    // Simulated Annealing parameters\n    double initial_temp = 2000.0;\n    double final_temp = 0.5;\n    const int MAX_ITER = 300000;\n    \n    for (int iter = 0; iter < MAX_ITER; ++iter) {\n        // Check time every 64 iterations\n        if ((iter & 63) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1850) {\n                break;\n            }\n        }\n        \n        // Tournament selection for choosing the node i to modify\n        int i = rng() % N;\n        for(int k = 0; k < 4; ++k) {\n            int cand = rng() % N;\n            if (abs(counts[cand] - T[cand]) > abs(counts[i] - T[i])) {\n                i = cand;\n            }\n        }\n        \n        // Pick which transition to modify\n        bool is_a = (rng() & 1);\n        int old_val = is_a ? a[i] : b[i];\n        \n        // Biased choice for new_val\n        int new_val;\n        // 70% of the time, try to pick a node that needs more visits\n        if (rng() % 10 < 7) { \n            int target_i = rng() % N;\n            long long max_under_visited = -2000000; // Look for under-visited node\n            for(int k = 0; k < 5; ++k) {\n                int cand = rng() % N;\n                long long diff = T[cand] - counts[cand]; // Positive if under-visited\n                if(diff > max_under_visited) {\n                    max_under_visited = diff;\n                    target_i = cand;\n                }\n            }\n            new_val = target_i;\n        } else {\n            new_val = rng() % N;\n        }\n        \n        // Apply change\n        if (is_a) a[i] = new_val;\n        else b[i] = new_val;\n        \n        long long new_error = calculate_error(a, b);\n        \n        // Metropolis acceptance\n        double temp = initial_temp + (final_temp - initial_temp) * (double)iter / MAX_ITER;\n        bool accept = false;\n        \n        if (new_error < current_error) {\n            accept = true;\n        } else {\n            double prob = exp((current_error - new_error) / temp);\n            if ((double)rng() / rng.max() < prob) {\n                accept = true;\n            }\n        }\n        \n        if (accept) {\n            current_error = new_error;\n            if (current_error < best_error) {\n                best_error = current_error;\n                memcpy(best_a, a, sizeof(int) * N);\n                memcpy(best_b, b, sizeof(int) * N);\n            }\n        } else {\n            // Revert changes\n            if (is_a) a[i] = old_val;\n            else b[i] = old_val;\n        }\n    }\n    \n    // Output the best solution\n    for (int i = 0; i < N; ++i) {\n        cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent a city\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double x, y; // Estimated coordinates\n};\n\n// Structure for an edge\nstruct Edge {\n    int u, v;\n    long long w;\n    int group_id;\n};\n\n// Function to calculate distance squared\ndouble distSq(double x1, double y1, double x2, double y2) {\n    return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\n}\n\n// Function to calculate distance rounded down\nlong long distInt(double x1, double y1, double x2, double y2) {\n    return (long long)floor(sqrt(distSq(x1, y1, x2, y2)));\n}\n\n// Function to perform a query\nvector<pair<int, int>> query(const vector<int>& c) {\n    if (c.size() < 2) return {};\n    cout << \"? \" << c.size();\n    for (int city_id : c) cout << \" \" << city_id;\n    cout << endl;\n    \n    vector<pair<int, int>> edges;\n    for (int i = 0; i < (int)c.size() - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        edges.push_back({u, v});\n    }\n    return edges;\n}\n\n// Calculate MST cost for a single group\ndouble calculateGroupMST(const vector<int>& group, const vector<City>& cities) {\n    if (group.size() <= 1) return 0;\n    int n = group.size();\n    vector<bool> visited(n, false);\n    vector<double> min_dist(n, 1e18);\n    min_dist[0] = 0;\n    double cost = 0;\n    for(int i=0; i<n; ++i) {\n        int u = -1;\n        for(int j=0; j<n; ++j) {\n            if(!visited[j] && (u == -1 || min_dist[j] < min_dist[u])) u = j;\n        }\n        if (u == -1 || min_dist[u] == 1e18) break;\n        visited[u] = true;\n        cost += min_dist[u];\n        for(int v=0; v<n; ++v) {\n            if(!visited[v]) {\n                double d = sqrt(distSq(cities[group[u]].x, cities[group[u]].y, \n                                       cities[group[v]].x, cities[group[v]].y));\n                min_dist[v] = min(min_dist[v], d);\n            }\n        }\n    }\n    return cost;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    vector<City> cities(N);\n    for (int i = 0; i < N; ++i) {\n        cities[i].id = 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.0;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2.0;\n    }\n\n    // 1. Multi-angle Clustering\n    vector<vector<int>> best_groups;\n    double min_cost = 1e18;\n    int num_angles = 100;\n\n    for (int i = 0; i < num_angles; ++i) {\n        double angle = M_PI * i / num_angles;\n        double cos_a = cos(angle);\n        double sin_a = sin(angle);\n        \n        vector<int> indices(N);\n        for(int j=0; j<N; ++j) indices[j] = j;\n        \n        sort(indices.begin(), indices.end(), [&](int a, int b) {\n            double pos_a = cities[a].x * cos_a + cities[a].y * sin_a;\n            double pos_b = cities[b].x * cos_a + cities[b].y * sin_a;\n            return pos_a < pos_b;\n        });\n        \n        vector<vector<int>> current_groups(M);\n        int start_idx = 0;\n        for(int j=0; j<M; ++j) {\n            for(int k=0; k<G[j]; ++k) {\n                current_groups[j].push_back(indices[start_idx++]);\n            }\n        }\n        \n        double cost = 0;\n        for (const auto& group : current_groups) cost += calculateGroupMST(group, cities);\n        if (cost < min_cost) {\n            min_cost = cost;\n            best_groups = current_groups;\n        }\n    }\n    \n    vector<vector<int>> groups = best_groups;\n\n    // 2. Identify expensive edges to query\n    vector<Edge> all_expensive_edges;\n    for(int i=0; i<M; ++i) {\n        if (groups[i].size() <= 1) continue;\n        \n        vector<Edge> group_edges;\n        for(size_t u=0; u<groups[i].size(); ++u) {\n            for(size_t v=u+1; v<groups[i].size(); ++v) {\n                int city_u = groups[i][u];\n                int city_v = groups[i][v];\n                group_edges.push_back({city_u, city_v, distInt(cities[city_u].x, cities[city_u].y, cities[city_v].x, cities[city_v].y), i});\n            }\n        }\n        sort(group_edges.begin(), group_edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        \n        vector<int> parent(N);\n        for(int j=0; j<N; ++j) parent[j] = j;\n        auto find = [&](auto self, int node) -> int {\n            return parent[node] == node ? node : parent[node] = self(self, parent[node]);\n        };\n        \n        for(const auto& e : group_edges) {\n            int root_u = find(find, e.u);\n            int root_v = find(find, e.v);\n            if(root_u != root_v) {\n                parent[root_u] = root_v;\n                all_expensive_edges.push_back(e);\n            }\n        }\n    }\n    \n    // Sort all MST edges by weight descending to prioritize expensive edges\n    sort(all_expensive_edges.begin(), all_expensive_edges.end(), [](const Edge& a, const Edge& b) {\n        return a.w > b.w;\n    });\n\n    // 3. Querying\n    vector<vector<pair<int, int>>> query_edges(M);\n    int queries_left = Q;\n    \n    for(const auto& e : all_expensive_edges) {\n        if (queries_left <= 0) break;\n        \n        int gid = e.group_id;\n        if (groups[gid].size() < 2) continue;\n        \n        // Pick u, v and find L-2 nearest neighbors to the midpoint of u and v\n        int u = e.u;\n        int v = e.v;\n        double mid_x = (cities[u].x + cities[v].x) / 2.0;\n        double mid_y = (cities[u].y + cities[v].y) / 2.0;\n        \n        vector<pair<double, int>> neighbors;\n        for(int city_id : groups[gid]) {\n            if (city_id == u || city_id == v) continue;\n            double d = distSq(cities[city_id].x, cities[city_id].y, mid_x, mid_y);\n            neighbors.push_back({d, city_id});\n        }\n        sort(neighbors.begin(), neighbors.end());\n        \n        vector<int> subset = {u, v};\n        int num_neighbors = min((int)neighbors.size(), L - 2);\n        for(int i=0; i<num_neighbors; ++i) subset.push_back(neighbors[i].second);\n        \n        auto edges = query(subset);\n        for(auto& edge : edges) {\n            query_edges[gid].push_back(edge);\n        }\n        queries_left--;\n    }\n    \n    // 4. Output MST construction\n    cout << \"!\" << endl;\n    for(int i=0; i<M; ++i) {\n        // Output cities\n        for(int j=0; j<G[i]; ++j) {\n            cout << groups[i][j] << (j == G[i]-1 ? \"\" : \" \");\n        }\n        cout << endl;\n        \n        // Build final MST\n        vector<Edge> final_edges;\n        \n        // Add query edges (weight 0 to ensure priority)\n        for(auto& edge : query_edges[i]) {\n            final_edges.push_back({edge.first, edge.second, 0, i});\n        }\n        \n        // Add all other edges (weight = estimated Euclidean distance)\n        for(size_t u=0; u<groups[i].size(); ++u) {\n            for(size_t v=u+1; v<groups[i].size(); ++v) {\n                int city_u = groups[i][u];\n                int city_v = groups[i][v];\n                long long d = distInt(cities[city_u].x, cities[city_u].y, cities[city_v].x, cities[city_v].y);\n                final_edges.push_back({city_u, city_v, d, i});\n            }\n        }\n        \n        sort(final_edges.begin(), final_edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        \n        // DSU\n        vector<int> parent(N);\n        for(int j=0; j<N; ++j) parent[j] = j;\n        \n        auto find = [&](auto self, int node) -> int {\n            return parent[node] == node ? node : parent[node] = self(self, parent[node]);\n        };\n        \n        vector<pair<int, int>> mst_edges;\n        for(auto& e : final_edges) {\n            int root_u = find(find, e.u);\n            int root_v = find(find, e.v);\n            if(root_u != root_v) {\n                parent[root_u] = root_v;\n                mst_edges.push_back({e.u, e.v});\n            }\n        }\n        \n        for(auto& e : mst_edges) {\n            cout << e.first << \" \" << e.second << endl;\n        }\n    }\n    \n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <tuple>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Constants\nconst int N = 20;\n\n// Directions: U, D, L, R\nconst int DR[] = {-1, 1, 0, 0};\nconst int DC[] = {0, 0, -1, 1};\nconst char D_CHAR[] = {'U', 'D', 'L', 'R'};\n\nstruct State {\n    int r, c, dist;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\n// Function to simulate sliding and find the stopping position\npair<int, int> get_stop_pos(int r, int c, int dr, int dc, const vector<vector<int>>& grid) {\n    int nr = r, nc = c;\n    while (true) {\n        int next_r = nr + dr;\n        int next_c = nc + dc;\n        // Blocks are at the edges, so sliding always stops\n        if (next_r < 0 || next_r >= N || next_c < 0 || next_c >= N || grid[next_r][next_c] == 1) {\n            return {nr, nc};\n        }\n        nr = next_r;\n        nc = next_c;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n, m;\n    cin >> n >> m;\n    int r0, c0;\n    cin >> r0 >> c0;\n    vector<pair<int, int>> targets(m);\n    for (int i = 0; i < m; ++i) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n\n    vector<vector<int>> grid(N, vector<int>(N, 0));\n    int curr_r = r0, curr_c = c0;\n\n    for (int t = 0; t < m; ++t) {\n        int tr = targets[t].first;\n        int tc = targets[t].second;\n\n        // Dijkstra to find shortest path to (tr, tc)\n        vector<vector<int>> dist(N, vector<int>(N, 1e9));\n        vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n        vector<vector<string>> action_path(N, vector<string>(N, \"\"));\n        \n        priority_queue<State, vector<State>, greater<State>> pq;\n        dist[curr_r][curr_c] = 0;\n        pq.push({curr_r, curr_c, 0});\n        \n        while (!pq.empty()) {\n            State top = pq.top();\n            pq.pop();\n            \n            if (top.dist > dist[top.r][top.c]) continue;\n            if (top.r == tr && top.c == tc) break;\n            \n            for (int i = 0; i < 4; ++i) {\n                // Move action\n                int nr = top.r + DR[i];\n                int nc = top.c + DC[i];\n                if (nr >= 0 && nr < N && nc >= 0 && nc < N) {\n                    int cost = (grid[nr][nc] == 1) ? 2 : 1;\n                    string actions = \"\";\n                    if (grid[nr][nc] == 1) actions += string(\"A \") + D_CHAR[i] + \"\\n\";\n                    actions += string(\"M \") + D_CHAR[i] + \"\\n\";\n                    \n                    if (dist[top.r][top.c] + cost < dist[nr][nc]) {\n                        dist[nr][nc] = dist[top.r][top.c] + cost;\n                        parent[nr][nc] = {top.r, top.c};\n                        action_path[nr][nc] = actions;\n                        pq.push({nr, nc, dist[nr][nc]});\n                    }\n                }\n                \n                // Slide action\n                pair<int, int> stop = get_stop_pos(top.r, top.c, DR[i], DC[i], grid);\n                int sr = stop.first, sc = stop.second;\n                int br = sr + DR[i], bc = sc + DC[i];\n                \n                // Check if we need to add a block to stop at (sr, sc)\n                bool need_block = (br >= 0 && br < N && bc >= 0 && bc < N && grid[br][bc] == 0);\n                int cost = need_block ? 2 : 1;\n                \n                string actions = \"\";\n                if (need_block) actions += string(\"A \") + D_CHAR[i] + \"\\n\";\n                actions += string(\"S \") + D_CHAR[i] + \"\\n\";\n                \n                if (dist[top.r][top.c] + cost < dist[sr][sc]) {\n                    dist[sr][sc] = dist[top.r][top.c] + cost;\n                    parent[sr][sc] = {top.r, top.c};\n                    action_path[sr][sc] = actions;\n                    pq.push({sr, sc, dist[sr][sc]});\n                }\n            }\n        }\n        \n        // Reconstruct and execute path\n        vector<string> path_actions;\n        int curr_r2 = tr, curr_c2 = tc;\n        while (curr_r2 != curr_r || curr_c2 != curr_c) {\n            path_actions.push_back(action_path[curr_r2][curr_c2]);\n            pair<int, int> p = parent[curr_r2][curr_c2];\n            curr_r2 = p.first;\n            curr_c2 = p.second;\n        }\n        reverse(path_actions.begin(), path_actions.end());\n        \n        for (const string& s : path_actions) {\n            cout << s;\n            size_t pos = 0;\n            while(pos < s.length()){\n                size_t next_line = s.find('\\n', pos);\n                string line = s.substr(pos, next_line - pos);\n                pos = next_line + 1;\n                if(line.empty()) continue;\n                \n                char act = line[0], dir = line[2];\n                int dr = 0, dc = 0;\n                if(dir == 'U') dr = -1; else if(dir == 'D') dr = 1; else if(dir == 'L') dc = -1; else if(dir == 'R') dc = 1;\n                \n                if(act == 'A'){\n                    int nr = curr_r + dr;\n                    int nc = curr_c + dc;\n                    grid[nr][nc] = 1 - grid[nr][nc];\n                } else if(act == 'M'){\n                    curr_r += dr;\n                    curr_c += dc;\n                } else if(act == 'S'){\n                    pair<int, int> stop = get_stop_pos(curr_r, curr_c, dr, dc, grid);\n                    curr_r = stop.first;\n                    curr_c = stop.second;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}"},"16":{"ahc001":"#include <iostream>\n#include <vector>\n#include <chrono>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Structure to represent an axis-aligned rectangle\nstruct Rect {\n    int x1, y1, x2, y2;\n};\n\nint N;\nvector<int> X, Y, R;\nvector<Rect> rects;\nvector<Rect> best_rects;\n\n// Fast Xorshift RNG for performance\nstruct Xorshift {\n    uint32_t x = 123456789, y = 362436069, z = 521288629, w = 88675123;\n    uint32_t next() {\n        uint32_t t = x ^ (x << 11);\n        x = y; y = z; z = w;\n        return w = w ^ (w >> 19) ^ t ^ (t >> 8);\n    }\n    int next_int(int n) { return next() % n; }\n    double next_double() { return (double)next() / 4294967296.0; }\n} rng;\n\n// Objective function: p_i = 1 - (1 - min/max)^2 = 2x - x^2\ninline double get_p(int i, int s) {\n    double r = R[i];\n    double x = min(r, (double)s) / max(r, (double)s);\n    return 2.0 * x - x * x;\n}\n\n// Check if rectangle 'r' overlaps with any other rectangle\n// idx is the index of the rectangle currently being moved\ninline bool check_overlap(int idx, const Rect& r) {\n    for (int i = 0; i < N; ++i) {\n        if (i == idx) continue;\n        // Overlap condition:\n        // rects[i].x1 < r.x2 && rects[i].x2 > r.x1 && rects[i].y1 < r.y2 && rects[i].y2 > r.y1\n        if (r.x1 < rects[i].x2 && r.x2 > rects[i].x1 &&\n            r.y1 < rects[i].y2 && r.y2 > rects[i].y1) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    // Fast I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N)) return 0;\n    X.resize(N);\n    Y.resize(N);\n    R.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> X[i] >> Y[i] >> R[i];\n    }\n\n    // Initial state: Each rectangle is 1x1 at its target location\n    rects.resize(N);\n    for (int i = 0; i < N; ++i) {\n        rects[i] = {X[i], Y[i], X[i] + 1, Y[i] + 1};\n    }\n    best_rects = rects;\n\n    double current_total_score = 0;\n    for (int i = 0; i < N; ++i) {\n        current_total_score += get_p(i, 1);\n    }\n    double best_total_score = current_total_score;\n\n    auto start_time = chrono::steady_clock::now();\n    \n    // SA parameters\n    double T_start = 0.1;\n    double T_end = 0.0001;\n    \n    // Main loop\n    int iter = 0;\n    while (true) {\n        // Check time every 1024 iterations to minimize overhead\n        if ((iter++ & 1023) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 4700) break;\n        }\n\n        // Calculate progress (0.0 to 1.0) and temperature\n        double elapsed_ms = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count();\n        double progress = elapsed_ms / 4700.0;\n        double T = T_start * pow(T_end / T_start, progress);\n\n        // Pick a rectangle to mutate\n        int i = rng.next_int(N);\n\n        // Adaptive delta_range: larger at the start for exploration, smaller at the end for precision\n        int delta_range = max(1, (int)(1000.0 * (1.0 - progress)));\n        int delta = rng.next_int(2 * delta_range + 1) - delta_range;\n\n        Rect next_rect = rects[i];\n        int side = rng.next_int(4);\n\n        // Mutate one side, ensuring target point (X[i], Y[i]) remains inside\n        if (side == 0) { // x1\n            next_rect.x1 = max(0, min(X[i], next_rect.x1 + delta));\n        } else if (side == 1) { // x2\n            next_rect.x2 = max(X[i] + 1, min(10000, next_rect.x2 + delta));\n        } else if (side == 2) { // y1\n            next_rect.y1 = max(0, min(Y[i], next_rect.y1 + delta));\n        } else { // y2\n            next_rect.y2 = max(Y[i] + 1, min(10000, next_rect.y2 + delta));\n        }\n\n        // Validate: skip degenerate rectangles and overlaps\n        if (next_rect.x1 == next_rect.x2 || next_rect.y1 == next_rect.y2) continue;\n        if (check_overlap(i, next_rect)) continue;\n\n        // Calculate score change\n        int old_s = (rects[i].x2 - rects[i].x1) * (rects[i].y2 - rects[i].y1);\n        int new_s = (next_rect.x2 - next_rect.x1) * (next_rect.y2 - next_rect.y1);\n        double delta_score = get_p(i, new_s) - get_p(i, old_s);\n\n        // Metropolis criterion: accept if better or with probability based on T\n        if (delta_score > 0 || (T > 1e-9 && exp(delta_score / T) > rng.next_double())) {\n            rects[i] = next_rect;\n            current_total_score += delta_score;\n            if (current_total_score > best_total_score) {\n                best_total_score = current_total_score;\n                best_rects = rects;\n            }\n        }\n    }\n\n    // Output best result found\n    for (int i = 0; i < N; ++i) {\n        cout << best_rects[i].x1 << \" \" << best_rects[i].y1 << \" \" << best_rects[i].x2 << \" \" << best_rects[i].y2 << \"\\n\";\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\n// Global variables to store problem data\nint si, sj;\nint t[50][50];\nint p[50][50];\nint M = 0;\nvector<int> tile_neighbors[2500];\nint initial_degree[2500];\nint degree[2500];\nbool is_visited_tile[2500];\n\n// Movement directions: Up, Down, Left, Right\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dchar[] = {'U', 'D', 'L', 'R'};\n\nint main() {\n    // Faster I/O for performance\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read input\n    if (!(cin >> si >> sj)) return 0;\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> t[i][j];\n            M = max(M, t[i][j] + 1);\n        }\n    }\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> p[i][j];\n        }\n    }\n\n    // Precompute tile adjacency\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            int current_tile = t[i][j];\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dr[k];\n                int nj = j + dc[k];\n                if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n                    int neighbor_tile = t[ni][nj];\n                    if (current_tile != neighbor_tile) {\n                        tile_neighbors[current_tile].push_back(neighbor_tile);\n                    }\n                }\n            }\n        }\n    }\n    // Remove duplicates from neighbor lists and calculate initial degree\n    for (int i = 0; i < M; ++i) {\n        sort(tile_neighbors[i].begin(), tile_neighbors[i].end());\n        tile_neighbors[i].erase(unique(tile_neighbors[i].begin(), tile_neighbors[i].end()), tile_neighbors[i].end());\n        initial_degree[i] = tile_neighbors[i].size();\n    }\n\n    string best_path = \"\";\n    int max_total_score = -1;\n\n    auto start_time = chrono::high_resolution_clock::now();\n    mt19937 rng(12345);\n\n    // Randomized search loop\n    while (true) {\n        auto current_time = chrono::high_resolution_clock::now();\n        // Time limit check (safer margin at 1.9s)\n        if (chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count() > 1900) {\n            break;\n        }\n\n        // Reset state efficiently\n        memset(is_visited_tile, 0, sizeof(bool) * M);\n        memcpy(degree, initial_degree, sizeof(int) * M);\n        \n        string current_path = \"\";\n        int current_total_score = 0;\n        int curr_r = si;\n        int curr_c = sj;\n        int curr_t = t[si][sj];\n        \n        is_visited_tile[curr_t] = true;\n        for(int neighbor : tile_neighbors[curr_t]) degree[neighbor]--;\n        current_total_score += p[curr_r][curr_c];\n        \n        // Random alpha focused on balancing points and connectivity\n        int alpha = (rng() % 101) - 60; // Range [-60, 40]\n        // Randomize greediness exponent for adaptive strategy\n        int exponent = (rng() % 4) + 1; // Range [1, 4]\n\n        while (true) {\n            struct Candidate { int r, c, dir, next_t; int score; };\n            Candidate candidates[4];\n            int num_candidates = 0;\n            \n            // Explore valid neighbor tiles\n            for (int k = 0; k < 4; ++k) {\n                int nr = curr_r + dr[k];\n                int nc = curr_c + dc[k];\n                if (nr >= 0 && nr < 50 && nc >= 0 && nc < 50) {\n                    int next_t = t[nr][nc];\n                    // Constraint: Must move to a different, unvisited tile\n                    if (next_t != curr_t && !is_visited_tile[next_t]) {\n                        // Heuristic: Immediate reward + connectivity\n                        int score = p[nr][nc] + alpha * degree[next_t];\n                        candidates[num_candidates++] = {nr, nc, k, next_t, score};\n                    }\n                }\n            }\n            \n            if (num_candidates == 0) break;\n            \n            // Fast weighted selection: Use exponents to favor high-score candidates\n            int min_score = candidates[0].score;\n            for(int i = 1; i < num_candidates; ++i) min_score = min(min_score, candidates[i].score);\n            \n            long long weights[4];\n            long long sum_weights = 0;\n            for(int i = 0; i < num_candidates; ++i) {\n                long long s = (long long)(candidates[i].score - min_score + 1);\n                long long w = s;\n                // Exponent-based weighting\n                for(int e = 1; e < exponent; ++e) w *= s;\n                weights[i] = w;\n                sum_weights += weights[i];\n            }\n            \n            uniform_int_distribution<long long> dist(0, sum_weights - 1);\n            long long r = dist(rng);\n            int best_idx = 0;\n            long long cumulative = 0;\n            for(int i = 0; i < num_candidates; ++i) {\n                cumulative += weights[i];\n                if (r < cumulative) {\n                    best_idx = i;\n                    break;\n                }\n            }\n            \n            // Execute move\n            curr_r = candidates[best_idx].r;\n            curr_c = candidates[best_idx].c;\n            current_path += dchar[candidates[best_idx].dir];\n            \n            curr_t = candidates[best_idx].next_t;\n            is_visited_tile[curr_t] = true;\n            for(int neighbor : tile_neighbors[curr_t]) degree[neighbor]--;\n            current_total_score += p[curr_r][curr_c];\n        }\n        \n        // Track best result\n        if (current_total_score > max_total_score) {\n            max_total_score = current_total_score;\n            best_path = current_path;\n        }\n    }\n    \n    cout << best_path << endl;\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Grid dimensions (30x30)\nconst int R = 30;\nconst int C = 30;\n\n// Edge weights and visit counts\ndouble hor[R][C - 1];\ndouble ver[R - 1][C];\nint cnt_hor[R][C - 1];\nint cnt_ver[R - 1][C];\n\nstruct Node {\n    int r, c;\n    double f; // f = g + h\n    double g; // actual cost so far\n    bool operator>(const Node& other) const {\n        return f > other.f;\n    }\n};\n\n// Heuristic: Manhattan distance * min_possible_edge_weight\n// Min possible weight is 1000.\ninline double heuristic(int r, int c, int tr, int tc) {\n    return (abs(r - tr) + abs(c - tc)) * 1000.0;\n}\n\n// Function to compute the shortest path using A*\nstring get_path(int sr, int sc, int tr, int tc) {\n    static double dist[R][C];\n    static pair<int, int> parent[R][C];\n    static char dir[R][C];\n    \n    for(int i = 0; i < R; ++i) {\n        for(int j = 0; j < C; ++j) {\n            dist[i][j] = 1e18;\n            parent[i][j] = {-1, -1};\n            dir[i][j] = ' ';\n        }\n    }\n    \n    priority_queue<Node, vector<Node>, greater<Node>> pq;\n    \n    dist[sr][sc] = 0;\n    pq.push({sr, sc, heuristic(sr, sc, tr, tc), 0});\n    \n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    char dchar[] = {'U', 'D', 'L', 'R'};\n    \n    while (!pq.empty()) {\n        Node current = pq.top();\n        pq.pop();\n        \n        int r = current.r;\n        int c = current.c;\n        \n        if (current.g > dist[r][c]) continue;\n        if (r == tr && c == tc) break;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = r + dr[i];\n            int nc = c + dc[i];\n            \n            if (nr >= 0 && nr < R && nc >= 0 && nc < C) {\n                double weight = 0;\n                if (i == 0) weight = ver[r - 1][c]; // U\n                else if (i == 1) weight = ver[r][c]; // D\n                else if (i == 2) weight = hor[r][c - 1]; // L\n                else if (i == 3) weight = hor[r][c]; // R\n                \n                if (dist[nr][nc] > dist[r][c] + weight) {\n                    dist[nr][nc] = dist[r][c] + weight;\n                    parent[nr][nc] = {r, c};\n                    dir[nr][nc] = dchar[i];\n                    pq.push({nr, nc, dist[nr][nc] + heuristic(nr, nc, tr, tc), dist[nr][nc]});\n                }\n            }\n        }\n    }\n    \n    // Reconstruct the path\n    string path = \"\";\n    int curr_r = tr;\n    int curr_c = tc;\n    while (curr_r != sr || curr_c != sc) {\n        char d = dir[curr_r][curr_c];\n        path += d;\n        pair<int, int> p = parent[curr_r][curr_c];\n        curr_r = p.first;\n        curr_c = p.second;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    // Initialize weights to a neutral middle value 5000.0\n    for (int i = 0; i < R; ++i)\n        for (int j = 0; j < C - 1; ++j) { hor[i][j] = 5000.0; cnt_hor[i][j] = 0; }\n    for (int i = 0; i < R - 1; ++i)\n        for (int j = 0; j < C; ++j) { ver[i][j] = 5000.0; cnt_ver[i][j] = 0; }\n    \n    for (int k = 0; k < 1000; ++k) {\n        int sr, sc, tr, tc;\n        cin >> sr >> sc >> tr >> tc;\n        \n        string path = get_path(sr, sc, tr, tc);\n        cout << path << endl; // Flushes output\n        \n        int measured_len;\n        cin >> measured_len;\n        \n        // Calculate predicted path length based on current estimates\n        double path_len = 0;\n        int curr_r = sr;\n        int curr_c = sc;\n        \n        for (char d : path) {\n            if (d == 'U') path_len += ver[curr_r - 1][curr_c];\n            else if (d == 'D') path_len += ver[curr_r][curr_c];\n            else if (d == 'L') path_len += hor[curr_r][curr_c - 1];\n            else if (d == 'R') path_len += hor[curr_r][curr_c];\n            \n            if (d == 'U') curr_r--;\n            else if (d == 'D') curr_r++;\n            else if (d == 'L') curr_c--;\n            else if (d == 'R') curr_c++;\n        }\n        \n        // Calculate ratio and clamp it to allow robust correction\n        double ratio = (double)measured_len / (path_len + 1e-9);\n        if (ratio < 0.4) ratio = 0.4;\n        if (ratio > 2.5) ratio = 2.5;\n        \n        // Update weights\n        curr_r = sr;\n        curr_c = sc;\n        for (char d : path) {\n            double* w_ptr = nullptr;\n            int* cnt_ptr = nullptr;\n            \n            if (d == 'U') { w_ptr = &ver[curr_r - 1][curr_c]; cnt_ptr = &cnt_ver[curr_r - 1][curr_c]; }\n            else if (d == 'D') { w_ptr = &ver[curr_r][curr_c]; cnt_ptr = &cnt_ver[curr_r][curr_c]; }\n            else if (d == 'L') { w_ptr = &hor[curr_r][curr_c - 1]; cnt_ptr = &cnt_hor[curr_r][curr_c - 1]; }\n            else if (d == 'R') { w_ptr = &hor[curr_r][curr_c]; cnt_ptr = &cnt_hor[curr_r][curr_c]; }\n            \n            // Dynamic learning rate tuned with a slower decay (0.002) and higher floor (0.15)\n            (*cnt_ptr)++;\n            double alpha = 0.7 / (1.0 + 0.002 * (*cnt_ptr));\n            if (alpha < 0.15) alpha = 0.15;\n            \n            *w_ptr *= (1.0 + alpha * (ratio - 1.0));\n            \n            // Constraint check\n            if (*w_ptr < 100) *w_ptr = 100;\n            if (*w_ptr > 15000) *w_ptr = 15000;\n            \n            if (d == 'U') curr_r--;\n            else if (d == 'D') curr_r++;\n            else if (d == 'L') curr_c--;\n            else if (d == 'R') curr_c++;\n        }\n    }\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\n// Constants\nconst int N = 20;\nint M;\nstring S[800];\nint8_t grid[N][N];\nint8_t best_grid[N][N];\nlong long best_overall_score = -1;\n\nint16_t mismatches[800][800];\nint16_t num_valid[800];\nint count_c;\nint count_dot;\n\nstruct AffectedItem {\n    int16_t s_idx;\n    int16_t p_idx;\n    int8_t k;\n};\n\n// Flattened affected structures for cache locality\nAffectedItem affected[N][N][2000];\nint affected_size[N][N];\n\nstruct PlacementInfo {\n    int16_t line_idx;\n    int16_t start_pos;\n    int8_t len;\n    int8_t target_chars[12];\n};\nPlacementInfo all_placements[800][800];\n\n// Unsatisfied string tracking\nvector<int> unsatisfied;\nint pos_in_unsatisfied[800];\n\nvoid update_unsatisfied(int s_idx, bool is_now_satisfied) {\n    if (is_now_satisfied) {\n        if (pos_in_unsatisfied[s_idx] != -1) {\n            int pos = pos_in_unsatisfied[s_idx];\n            int last_s = unsatisfied.back();\n            unsatisfied[pos] = last_s;\n            pos_in_unsatisfied[last_s] = pos;\n            unsatisfied.pop_back();\n            pos_in_unsatisfied[s_idx] = -1;\n        }\n    } else {\n        if (pos_in_unsatisfied[s_idx] == -1) {\n            pos_in_unsatisfied[s_idx] = (int)unsatisfied.size();\n            unsatisfied.push_back(s_idx);\n        }\n    }\n}\n\nvoid precompute() {\n    memset(affected_size, 0, sizeof(affected_size));\n    for (int i = 0; i < M; ++i) {\n        int len = (int)S[i].length();\n        for (int line = 0; line < 2 * N; ++line) {\n            for (int start = 0; start < N; ++start) {\n                int p_idx = line * N + start;\n                all_placements[i][p_idx] = {(int16_t)line, (int16_t)start, (int8_t)len};\n                for (int k = 0; k < len; ++k) all_placements[i][p_idx].target_chars[k] = S[i][k] - 'A';\n                for (int k = 0; k < len; ++k) {\n                    int r, c;\n                    if (line < N) { r = line; c = (start + k) % N; }\n                    else { r = (start + k) % N; c = line - N; }\n                    if (affected_size[r][c] < 2000) {\n                        affected[r][c][affected_size[r][c]++] = {(int16_t)i, (int16_t)p_idx, (int8_t)k};\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid reset_state() {\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) grid[i][j] = 8;\n    }\n    count_c = 0;\n    count_dot = N * N;\n    unsatisfied.clear();\n    for (int i = 0; i < M; ++i) {\n        num_valid[i] = 0;\n        pos_in_unsatisfied[i] = -1;\n        update_unsatisfied(i, false);\n        int len = (int)S[i].length();\n        for (int p = 0; p < 2 * N * N; ++p) mismatches[i][p] = (int16_t)len;\n    }\n}\n\ninline void update_grid(int r, int c, int new_val) {\n    int old_val = grid[r][c];\n    if (old_val == new_val) return;\n    if (old_val == 8 && new_val != 8) count_dot--;\n    else if (old_val != 8 && new_val == 8) count_dot++;\n    grid[r][c] = (int8_t)new_val;\n\n    int sz = affected_size[r][c];\n    for (int i = 0; i < sz; ++i) {\n        AffectedItem& p = affected[r][c][i];\n        bool was_valid = (mismatches[p.s_idx][p.p_idx] == 0);\n        int target = all_placements[p.s_idx][p.p_idx].target_chars[p.k];\n        \n        if (old_val == target) mismatches[p.s_idx][p.p_idx]++;\n        if (new_val == target) mismatches[p.s_idx][p.p_idx]--;\n        \n        bool is_valid = (mismatches[p.s_idx][p.p_idx] == 0);\n        if (was_valid && !is_valid) {\n            num_valid[p.s_idx]--;\n            if (num_valid[p.s_idx] == 0) { count_c--; update_unsatisfied(p.s_idx, false); }\n        } else if (!was_valid && is_valid) {\n            if (num_valid[p.s_idx] == 0) { count_c++; update_unsatisfied(p.s_idx, true); }\n            num_valid[p.s_idx]++;\n        }\n    }\n}\n\nlong long get_score() { return (long long)count_c * 1000000 + count_dot; }\n\nvoid post_process(mt19937& rng) {\n    if (count_c < M) return;\n    vector<pair<int, int>> cells;\n    cells.reserve(N * N);\n    for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) cells.push_back({i, j});\n    shuffle(cells.begin(), cells.end(), rng);\n    for (auto& p : cells) {\n        int i = p.first, j = p.second;\n        if (grid[i][j] != 8) {\n            int old_val = grid[i][j];\n            update_grid(i, j, 8);\n            if (count_c < M) update_grid(i, j, old_val);\n        }\n    }\n}\n\nvoid solve(mt19937& rng, chrono::steady_clock::time_point start_time) {\n    reset_state();\n\n    vector<int> order(M);\n    for(int i=0; i<M; ++i) order[i] = i;\n    sort(order.begin(), order.end(), [&](int a, int b) { \n        return S[a].length() > S[b].length();\n    });\n    for(int i=0; i<M/10; ++i) swap(order[rng()%M], order[rng()%M]);\n    \n    for(int i : order) {\n        if (num_valid[i] > 0) continue;\n        int p_idx = rng() % (2 * N * N);\n        int len = all_placements[i][p_idx].len;\n        for (int k = 0; k < len; ++k) {\n            int line = all_placements[i][p_idx].line_idx;\n            int start = all_placements[i][p_idx].start_pos;\n            int r, c;\n            if (line < N) { r = line; c = (start + k) % N; }\n            else { r = (start + k) % N; c = line - N; }\n            if (grid[r][c] == 8) update_grid(r, c, all_placements[i][p_idx].target_chars[k]);\n        }\n    }\n\n    long long current_score = get_score();\n    long long best_local_score = current_score;\n    double T_start = 1e6, T_end = 1e1;\n    const int iterations = 1500000;\n    \n    for (int i = 0; i < iterations; ++i) {\n        if ((i & 1023) == 0 && chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() > 2800) break;\n        \n        int r, c, val;\n        int move_type = rng() % 100;\n        \n        if (count_c < M) {\n            // Satisfaction Phase: Fix unsatisfied strings\n            if (!unsatisfied.empty() && (move_type < 90)) {\n                int s_idx = unsatisfied[rng() % unsatisfied.size()];\n                int best_p = -1; int min_m = 999;\n                for (int p_idx = 0; p_idx < 2 * N * N; ++p_idx) {\n                    if (mismatches[s_idx][p_idx] < min_m) { min_m = mismatches[s_idx][p_idx]; best_p = p_idx; }\n                }\n                int target_k = rng() % all_placements[s_idx][best_p].len;\n                int line = all_placements[s_idx][best_p].line_idx;\n                int start = all_placements[s_idx][best_p].start_pos;\n                if (line < N) { r = line; c = (start + target_k) % N; }\n                else { r = (start + target_k) % N; c = line - N; }\n                val = all_placements[s_idx][best_p].target_chars[target_k];\n            } else {\n                r = rng() % N; c = rng() % N; val = rng() % 9;\n            }\n        } else {\n            // Optimization Phase: Maximize '.'\n            if (move_type < 70) {\n                // Try to set random cell to '.'\n                r = rng() % N; c = rng() % N; val = 8;\n            } else {\n                r = rng() % N; c = rng() % N; val = rng() % 9;\n            }\n        }\n        \n        int old_val = grid[r][c];\n        if (old_val == val) continue;\n        update_grid(r, c, val);\n        long long next_score = get_score();\n        \n        double prob = (next_score >= current_score) ? 1.0 : exp((double)(next_score - current_score) / (T_start * exp(log(T_end / T_start) * ((double)i / iterations))));\n        if (prob > (double)(rng() % 10000) / 10000.0) {\n            current_score = next_score;\n            if (current_score > best_local_score) {\n                best_local_score = current_score;\n                post_process(rng);\n                long long final_score = get_score();\n                if (final_score > best_overall_score) {\n                    best_overall_score = final_score;\n                    memcpy(best_grid, grid, sizeof(grid));\n                }\n                current_score = final_score;\n            }\n        } else {\n            update_grid(r, c, old_val);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    int N_in; cin >> N_in >> M;\n    for (int i = 0; i < M; ++i) cin >> S[i];\n    precompute();\n    mt19937 rng(1337);\n    auto start_time = chrono::steady_clock::now();\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 2800) solve(rng, start_time);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) cout << (best_grid[i][j] == 8 ? '.' : (char)(best_grid[i][j] + 'A'));\n        cout << \"\\n\";\n    }\n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <chrono>\n#include <random>\n#include <functional>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int r, c;\n    bool operator==(const Point& other) const { return r == other.r && c == other.c; }\n    bool operator!=(const Point& other) const { return !(*this == other); }\n};\n\nint N;\nint si, sj;\nvector<string> grid;\nvector<int> weights_flat;\nvector<vector<vector<Point>>> visible_from;\nvector<Point> all_road_squares;\nvector<vector<int>> road_id_map;\nvector<vector<int>> all_pairs_dist;\n\nvoid precompute() {\n    visible_from.assign(N, vector<vector<Point>>(N));\n    road_id_map.assign(N, vector<int>(N, -1));\n    weights_flat.assign(N * N, 0);\n    \n    for (int i = 0; i < all_road_squares.size(); ++i) {\n        road_id_map[all_road_squares[i].r][all_road_squares[i].c] = i;\n    }\n    for(int r = 0; r < N; ++r) {\n        for(int c = 0; c < N; ++c) {\n            if(grid[r][c] != '#') weights_flat[r * N + c] = grid[r][c] - '0';\n        }\n    }\n\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            if (grid[r][c] == '#') continue;\n            visible_from[r][c].push_back({r, c});\n            for (int nc = c + 1; nc < N && grid[r][nc] != '#'; ++nc) visible_from[r][c].push_back({r, nc});\n            for (int nc = c - 1; nc >= 0 && grid[r][nc] != '#'; --nc) visible_from[r][c].push_back({r, nc});\n            for (int nr = r + 1; nr < N && grid[nr][c] != '#'; ++nr) visible_from[r][c].push_back({nr, c});\n            for (int nr = r - 1; nr >= 0 && grid[nr][c] != '#'; --nr) visible_from[r][c].push_back({nr, c});\n        }\n    }\n\n    all_pairs_dist.assign(all_road_squares.size(), vector<int>(all_road_squares.size()));\n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n\n    for (int i = 0; i < all_road_squares.size(); ++i) {\n        Point start = all_road_squares[i];\n        vector<int> dist(N * N, 1e9);\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n        dist[start.r * N + start.c] = 0;\n        pq.push({0, start.r * N + start.c});\n        \n        while (!pq.empty()) {\n            int d = pq.top().first;\n            int u = pq.top().second;\n            pq.pop();\n            if (d > dist[u]) continue;\n            int r = u / N, c = u % N;\n            for (int k = 0; k < 4; ++k) {\n                int nr = r + dr[k], nc = c + dc[k];\n                if (nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] != '#') {\n                    if (dist[nr * N + nc] > d + weights_flat[nr * N + nc]) {\n                        dist[nr * N + nc] = d + weights_flat[nr * N + nc];\n                        pq.push({dist[nr * N + nc], nr * N + nc});\n                    }\n                }\n            }\n        }\n        for (int j = 0; j < all_road_squares.size(); ++j) {\n            all_pairs_dist[i][j] = dist[all_road_squares[j].r * N + all_road_squares[j].c];\n        }\n    }\n}\n\nstring get_path(Point start, Point end) {\n    int target_id = end.r * N + end.c;\n    vector<int> dist(N * N, 1e9);\n    vector<int> parent(N * N, -1);\n    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n    dist[start.r * N + start.c] = 0;\n    pq.push({0, start.r * N + start.c});\n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    while (!pq.empty()) {\n        int d = pq.top().first;\n        int u = pq.top().second;\n        pq.pop();\n        if (d > dist[u]) continue;\n        if (u == target_id) break;\n        int r = u / N, c = u % N;\n        for (int k = 0; k < 4; ++k) {\n            int nr = r + dr[k], nc = c + dc[k];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] != '#') {\n                if (dist[nr * N + nc] > d + weights_flat[nr * N + nc]) {\n                    dist[nr * N + nc] = d + weights_flat[nr * N + nc];\n                    parent[nr * N + nc] = u;\n                    pq.push({dist[nr * N + nc], nr * N + nc});\n                }\n            }\n        }\n    }\n    string path = \"\";\n    int curr = target_id;\n    while (curr != start.r * N + start.c) {\n        int p = parent[curr];\n        int r = curr / N, c = curr % N;\n        int pr = p / N, pc = p % N;\n        if (r == pr - 1) path += 'U';\n        else if (r == pr + 1) path += 'D';\n        else if (c == pc - 1) path += 'L';\n        else if (c == pc + 1) path += 'R';\n        curr = p;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n    cin >> N >> si >> sj;\n    grid.resize(N);\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] != '#') all_road_squares.push_back({i, j});\n        }\n    }\n    precompute();\n    \n    auto start_time = chrono::steady_clock::now();\n    mt19937 rng(42);\n    string best_full_path;\n    int min_total_cost = 2e9;\n    \n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 2500) {\n        vector<vector<bool>> covered(N, vector<bool>(N, false));\n        int total_covered = 0, target = all_road_squares.size();\n        int curr_idx = road_id_map[si][sj];\n        vector<int> path_node_indices = {curr_idx};\n        auto mark = [&](int idx) {\n            Point p = all_road_squares[idx];\n            for (auto& v : visible_from[p.r][p.c]) {\n                if (!covered[v.r][v.c]) { covered[v.r][v.c] = true; total_covered++; }\n            }\n        };\n        mark(curr_idx);\n        \n        while (total_covered < target) {\n            struct Candidate { int idx; double score; };\n            vector<Candidate> cands;\n            for (int i = 0; i < (int)all_road_squares.size(); ++i) {\n                int gain = 0;\n                Point p = all_road_squares[i];\n                for (auto& v : visible_from[p.r][p.c]) if (!covered[v.r][v.c]) gain++;\n                if (gain > 0) {\n                    double d = all_pairs_dist[curr_idx][i];\n                    cands.push_back({i, (double)gain / (pow(d, 1.3) + 1.0)});\n                }\n            }\n            if (cands.empty()) break;\n            sort(cands.begin(), cands.end(), [](const Candidate& a, const Candidate& b) { return a.score > b.score; });\n            int k = min((int)cands.size(), 5);\n            vector<double> weights_vec;\n            for(int i = 0; i < k; ++i) weights_vec.push_back(cands[i].score);\n            discrete_distribution<int> dist(weights_vec.begin(), weights_vec.end());\n            curr_idx = cands[dist(rng)].idx;\n            path_node_indices.push_back(curr_idx);\n            mark(curr_idx);\n        }\n        path_node_indices.push_back(road_id_map[si][sj]);\n        \n        for(int pass = 0; pass < 5; ++pass) {\n            vector<vector<int>> cov_cnt(N, vector<int>(N, 0));\n            for (int idx : path_node_indices) {\n                Point p = all_road_squares[idx];\n                for (auto& v : visible_from[p.r][p.c]) cov_cnt[v.r][v.c]++;\n            }\n            bool changed = false;\n            for (int i = 1; i < (int)path_node_indices.size() - 1; ) {\n                Point p = all_road_squares[path_node_indices[i]];\n                bool can_remove = true;\n                for (auto& v : visible_from[p.r][p.c]) if (cov_cnt[v.r][v.c] <= 1) can_remove = false;\n                if (can_remove) {\n                    for (auto& v : visible_from[p.r][p.c]) cov_cnt[v.r][v.c]--;\n                    path_node_indices.erase(path_node_indices.begin() + i);\n                    changed = true;\n                } else i++;\n            }\n            if (!changed) break;\n        }\n        \n        bool improved = true;\n        while(improved) {\n            improved = false;\n            int M = path_node_indices.size();\n            for (int i = 1; i < M - 2; ++i) {\n                for (int j = i + 1; j < M - 1; ++j) {\n                    if (all_pairs_dist[path_node_indices[i-1]][path_node_indices[j]] + all_pairs_dist[path_node_indices[i]][path_node_indices[j+1]] < \n                        all_pairs_dist[path_node_indices[i-1]][path_node_indices[i]] + all_pairs_dist[path_node_indices[j]][path_node_indices[j+1]]) {\n                        reverse(path_node_indices.begin() + i, path_node_indices.begin() + j + 1);\n                        improved = true;\n                    }\n                }\n            }\n        }\n        \n        int total_cost = 0;\n        string current_path = \"\";\n        for (int i = 0; i < (int)path_node_indices.size() - 1; ++i) {\n            total_cost += all_pairs_dist[path_node_indices[i]][path_node_indices[i+1]];\n            current_path += get_path(all_road_squares[path_node_indices[i]], all_road_squares[path_node_indices[i+1]]);\n        }\n        if (total_cost < min_total_cost) { min_total_cost = total_cost; best_full_path = current_path; }\n    }\n    cout << best_full_path << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <bitset>\n\nusing namespace std;\n\n// Global problem variables\nint N, M, K, R;\nvector<vector<int>> task_difficulty;\nvector<vector<int>> adj; \nvector<int> in_degree;\nvector<int> member_status; // -1: free, >=0: task_id\nvector<int> start_day;\nvector<vector<double>> s; // Skills estimation (member x skill_dim)\nvector<int> H; // Task height (longest chain)\nvector<int> D; // Descendants count\nvector<int> visit_count; // Number of tasks completed by each member\n\n// Function to calculate predicted completion time for a task by a member\ndouble predict_t(int task_id, int member_id) {\n    double w = 0;\n    for (int k = 0; k < K; ++k) {\n        w += max(0.0, (double)task_difficulty[task_id][k] - s[member_id][k]);\n    }\n    return max(1.0, w);\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Read input\n    if (!(cin >> N >> M >> K >> R)) return 0;\n    task_difficulty.resize(N, vector<int>(K));\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            cin >> task_difficulty[i][k];\n        }\n    }\n    adj.resize(N);\n    in_degree.resize(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        adj[u].push_back(v);\n        in_degree[v]++;\n    }\n\n    // Precompute H (Height) - Longest path in DAG\n    H.resize(N, 1);\n    for (int i = N - 1; i >= 0; --i) {\n        for (int v : adj[i]) {\n            H[i] = max(H[i], 1 + H[v]);\n        }\n    }\n\n    // Precompute D (Descendants count)\n    vector<bitset<1000>> reachable(N);\n    for (int i = N - 1; i >= 0; --i) {\n        reachable[i].set(i);\n        for (int v : adj[i]) {\n            reachable[i] |= reachable[v];\n        }\n    }\n    D.resize(N);\n    for(int i=0; i<N; ++i) D[i] = (int)reachable[i].count() - 1;\n\n    // Precompute estimated average difficulty for prioritization\n    vector<double> task_avg_dur(N);\n    for(int i=0; i<N; ++i) {\n        double dur = 0;\n        for(int k=0; k<K; ++k) dur += max(0.0, (double)task_difficulty[i][k] - 30.0);\n        task_avg_dur[i] = dur;\n    }\n\n    // Initialization\n    member_status.assign(M, -1);\n    start_day.assign(N, -1);\n    visit_count.assign(M, 0);\n    s.assign(M, vector<double>(K, 30.0)); \n    vector<int> ready_tasks;\n    for (int i = 0; i < N; ++i) {\n        if (in_degree[i] == 0) ready_tasks.push_back(i);\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n\n        // 1. Assign tasks\n        // Prioritize: H (Criticality) * 20000 + D + estimated_duration\n        sort(ready_tasks.begin(), ready_tasks.end(), [&](int a, int b) {\n            double score_a = (double)H[a] * 20000 + D[a] * 10.0 + task_avg_dur[a];\n            double score_b = (double)H[b] * 20000 + D[b] * 10.0 + task_avg_dur[b];\n            return score_a > score_b;\n        });\n\n        vector<pair<int, int>> assignments;\n        vector<int> free_members;\n        for (int j = 0; j < M; ++j) {\n            if (member_status[j] == -1) free_members.push_back(j);\n        }\n\n        vector<bool> task_assigned(ready_tasks.size(), false);\n        vector<bool> member_assigned(free_members.size(), false);\n\n        // Greedy matching: Task-first, then best member\n        for (int i = 0; i < (int)ready_tasks.size(); ++i) {\n            int task_id = ready_tasks[i];\n            \n            int best_member_idx = -1;\n            double min_t = 1e18;\n\n            for (int j = 0; j < (int)free_members.size(); ++j) {\n                if (member_assigned[j]) continue;\n                double t = predict_t(task_id, free_members[j]);\n                if (t < min_t) {\n                    min_t = t;\n                    best_member_idx = j;\n                }\n            }\n\n            if (best_member_idx != -1) {\n                int member_id = free_members[best_member_idx];\n                assignments.push_back({member_id + 1, task_id + 1});\n                member_status[member_id] = task_id;\n                start_day[task_id] = day;\n                member_assigned[best_member_idx] = true;\n                task_assigned[i] = true;\n            }\n        }\n\n        // Update ready_tasks: remove assigned\n        vector<int> next_ready_tasks;\n        for (int i = 0; i < (int)ready_tasks.size(); ++i) {\n            if (!task_assigned[i]) next_ready_tasks.push_back(ready_tasks[i]);\n        }\n        ready_tasks = next_ready_tasks;\n\n        // Output and flush\n        cout << assignments.size();\n        for (auto& p : assignments) cout << \" \" << p.first << \" \" << p.second;\n        cout << endl;\n\n        // 2. Read completed\n        int n_completed;\n        cin >> n_completed;\n        if (n_completed == -1) break;\n\n        for (int i = 0; i < n_completed; ++i) {\n            int member_id;\n            cin >> member_id;\n            --member_id;\n            int task_id = member_status[member_id];\n            \n            // Skill learning update\n            int actual_t = day - start_day[task_id] + 1;\n            double w_pred = 0;\n            vector<int> bottlenecks;\n            for (int k = 0; k < K; ++k) {\n                double diff = (double)task_difficulty[task_id][k] - s[member_id][k];\n                if (diff > 0) {\n                    w_pred += diff;\n                    bottlenecks.push_back(k);\n                }\n            }\n            \n            // Adaptive learning rate based on how many tasks the member has completed\n            double lr = 0.2 / (1.0 + 0.05 * visit_count[member_id]);\n            visit_count[member_id]++;\n\n            double error = (double)actual_t - max(1.0, w_pred);\n            if (abs(error) > 1e-9) {\n                if (!bottlenecks.empty()) {\n                    for(int k : bottlenecks) {\n                        s[member_id][k] -= (error / bottlenecks.size()) * lr;\n                        s[member_id][k] = max(0.0, min(100.0, s[member_id][k]));\n                    }\n                } else {\n                    // Update all if no bottlenecks (error indicates optimistic skill estimate)\n                    for(int k = 0; k < K; ++k) {\n                        s[member_id][k] -= (error / K) * lr;\n                        s[member_id][k] = max(0.0, min(100.0, s[member_id][k]));\n                    }\n                }\n            }\n\n            member_status[member_id] = -1;\n\n            // Unlock dependencies\n            for (int next_task : adj[task_id]) {\n                in_degree[next_task]--;\n                if (in_degree[next_task] == 0) ready_tasks.push_back(next_task);\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Order structure\nstruct Order {\n    int id;\n    int ax, ay, cx, cy;\n};\n\n// Node structure for the route (pickup or delivery)\nstruct Node {\n    int order_id;\n    bool is_pickup;\n    int x, y;\n};\n\n// Global lookup for orders\nOrder orders_by_id[1001];\n\n// Inline distance function for performance\ninline int dist(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// Calculate the total route distance, including return to office\ninline int calculate_total_dist(const vector<Node>& route) {\n    int d = dist(400, 400, route[0].x, route[0].y);\n    for (size_t i = 0; i < route.size() - 1; ++i) {\n        d += dist(route[i].x, route[i].y, route[i + 1].x, route[i + 1].y);\n    }\n    d += dist(route.back().x, route.back().y, 400, 400);\n    return d;\n}\n\n// Efficiently check if a route satisfies precedence constraints\nbool is_valid(const vector<Node>& route, const vector<int>& selected_orders) {\n    static int p_pos[1001], d_pos[1001];\n    for (int id : selected_orders) {\n        p_pos[id] = -1;\n        d_pos[id] = -1;\n    }\n    \n    for (int i = 0; i < (int)route.size(); ++i) {\n        if (route[i].is_pickup) p_pos[route[i].order_id] = i;\n        else d_pos[route[i].order_id] = i;\n    }\n    \n    for (int id : selected_orders) {\n        if (p_pos[id] == -1 || d_pos[id] == -1 || p_pos[id] > d_pos[id]) return false;\n    }\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // Read all orders\n    vector<int> all_indices(1000);\n    for (int i = 0; i < 1000; ++i) {\n        orders_by_id[i + 1].id = i + 1;\n        cin >> orders_by_id[i + 1].ax >> orders_by_id[i + 1].ay \n            >> orders_by_id[i + 1].cx >> orders_by_id[i + 1].cy;\n        all_indices[i] = i + 1;\n    }\n\n    // Heuristic selection: Choose 50 orders with minimal total trip distance\n    sort(all_indices.begin(), all_indices.end(), [](int i, int j) {\n        auto cost = [](int idx) {\n            return dist(400, 400, orders_by_id[idx].ax, orders_by_id[idx].ay) + \n                   dist(orders_by_id[idx].ax, orders_by_id[idx].ay, orders_by_id[idx].cx, orders_by_id[idx].cy) +\n                   dist(orders_by_id[idx].cx, orders_by_id[idx].cy, 400, 400);\n        };\n        return cost(i) < cost(j);\n    });\n\n    vector<int> selected_orders;\n    for (int i = 0; i < 50; ++i) selected_orders.push_back(all_indices[i]);\n\n    // Randomized Greedy Construction\n    mt19937 rng(42);\n    vector<Node> route;\n    vector<bool> p_visited(1001, false), d_visited(1001, false);\n    int cx = 400, cy = 400;\n    \n    while (route.size() < 100) {\n        vector<pair<int, int>> candidates;\n        for (int id : selected_orders) {\n            if (!p_visited[id]) {\n                candidates.push_back({dist(cx, cy, orders_by_id[id].ax, orders_by_id[id].ay), id * 2});\n            } else if (p_visited[id] && !d_visited[id]) {\n                candidates.push_back({dist(cx, cy, orders_by_id[id].cx, orders_by_id[id].cy), id * 2 + 1});\n            }\n        }\n        sort(candidates.begin(), candidates.end());\n        int pick_idx = (candidates.size() > 1) ? (rng() % min((int)candidates.size(), 3)) : 0;\n        int val = candidates[pick_idx].second;\n        int id = val / 2;\n        if (val % 2 == 0) {\n            route.push_back({id, true, orders_by_id[id].ax, orders_by_id[id].ay});\n            p_visited[id] = true;\n            cx = orders_by_id[id].ax; cy = orders_by_id[id].ay;\n        } else {\n            route.push_back({id, false, orders_by_id[id].cx, orders_by_id[id].cy});\n            d_visited[id] = true;\n            cx = orders_by_id[id].cx; cy = orders_by_id[id].cy;\n        }\n    }\n\n    // Simulated Annealing\n    auto start_time = chrono::steady_clock::now();\n    int current_dist = calculate_total_dist(route);\n    double start_temp = 1000.0, end_temp = 1.0;\n    int iter = 0;\n    \n    while (true) {\n        // Time management check\n        if ((++iter & 1023) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1900) break;\n        }\n\n        // Adaptive temperature based on remaining time\n        double time_ratio = (double)chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() / 1900.0;\n        double temp = start_temp * pow(end_temp / start_temp, time_ratio);\n\n        vector<Node> next_route = route;\n        int r = rng() % 100;\n        if (r < 60) { // 2-opt\n            int i = rng() % 100, j = rng() % 100;\n            if (i > j) swap(i, j);\n            reverse(next_route.begin() + i, next_route.begin() + j + 1);\n        } else if (r < 80) { // Relocate\n            int i = rng() % 100, j = rng() % 100;\n            Node n = next_route[i];\n            next_route.erase(next_route.begin() + i);\n            next_route.insert(next_route.begin() + j, n);\n        } else { // Swap\n            int i = rng() % 100, j = rng() % 100;\n            swap(next_route[i], next_route[j]);\n        }\n\n        if (is_valid(next_route, selected_orders)) {\n            int next_dist = calculate_total_dist(next_route);\n            if (next_dist < current_dist || (rng() % 10000) / 10000.0 < exp((current_dist - next_dist) / temp)) {\n                route = next_route;\n                current_dist = next_dist;\n            }\n        }\n    }\n\n    // Output results\n    cout << 50;\n    for (int id : selected_orders) cout << \" \" << id;\n    cout << endl << 102 << \" 400 400\";\n    for (const auto& node : route) cout << \" \" << node.x << \" \" << node.y;\n    cout << \" 400 400\" << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\n// DSU structure for connectivity checking\nstruct DSU {\n    vector<int> parent;\n    int num_components;\n    DSU(int n) : num_components(n) {\n        parent.resize(n);\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int i) {\n        if (parent[i] == i)\n            return i;\n        return parent[i] = find(parent[i]);\n    }\n    // unite returns true if it actually merged two components\n    bool unite(int i, int j) {\n        int root_i = find(i);\n        int root_j = find(j);\n        if (root_i != root_j) {\n            parent[root_i] = root_j;\n            num_components--;\n            return true;\n        }\n        return false;\n    }\n    bool same(int i, int j) {\n        return find(i) == find(j);\n    }\n};\n\nstruct Edge {\n    int u, v, d, id;\n};\n\nint main() {\n    // Faster I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    // Problem constraints\n    const int N = 400;\n    const int M = 1995;\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<Edge> edges(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        int dx = coords[edges[i].u].first - coords[edges[i].v].first;\n        int dy = coords[edges[i].u].second - coords[edges[i].v].second;\n        // Euclidean distance rounded to nearest integer\n        edges[i].d = (int)round(sqrt((double)dx * dx + (double)dy * dy));\n        edges[i].id = i;\n    }\n\n    vector<bool> adopted(M, false);\n    \n    // Process each edge as it arrives\n    for (int i = 0; i < M; ++i) {\n        int l_i;\n        cin >> l_i;\n\n        // Initialize DSU with all already adopted edges\n        DSU dsu(N);\n        for (int j = 0; j < i; ++j) {\n            if (adopted[j]) {\n                dsu.unite(edges[j].u, edges[j].v);\n            }\n        }\n        \n        // Calculate needed edge count\n        // We need to connect num_components components, so we need num_components - 1 more edges.\n        int num_needed = dsu.num_components - 1;\n        int num_remaining = M - i;\n\n        // Adaptive parameter k:\n        // k_base increases from 1.5 to 2.0 over time.\n        // Boost factor increases as we get desperate (num_needed close to num_remaining).\n        // This keeps our estimation centered around 2.0 (the expected value).\n        double k = 1.5 + 0.5 * ((double)i / M) + 0.5 * ((double)num_needed / num_remaining);\n\n        // Prepare candidates: the current edge (cost l_i) and all future edges (estimated cost k*d)\n        struct Candidate {\n            double cost;\n            int id;\n            int u, v;\n        };\n        vector<Candidate> candidates;\n        candidates.reserve(M - i);\n        \n        candidates.push_back({(double)l_i, i, edges[i].u, edges[i].v});\n        \n        for (int j = i + 1; j < M; ++j) {\n            candidates.push_back({k * edges[j].d, j, edges[j].u, edges[j].v});\n        }\n        \n        // Sort candidates by cost to run Kruskal's algorithm\n        sort(candidates.begin(), candidates.end(), [](const Candidate& a, const Candidate& b) {\n            return a.cost < b.cost;\n        });\n        \n        // Run Kruskal's to see if the current edge i is part of the MST\n        bool take_edge = false;\n        for (const auto& cand : candidates) {\n            if (!dsu.same(cand.u, cand.v)) {\n                dsu.unite(cand.u, cand.v);\n                if (cand.id == i) {\n                    take_edge = true;\n                    break;\n                }\n            }\n        }\n        \n        // Output decision and flush\n        if (take_edge) {\n            cout << 1 << endl;\n            adopted[i] = true;\n        } else {\n            cout << 0 << endl;\n            adopted[i] = false;\n        }\n    }\n    \n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int r, c;\n    bool operator==(const Point& other) const { return r == other.r && c == other.c; }\n};\n\nint N, M;\nvector<Point> pets;\nvector<int> pet_types;\nvector<Point> humans;\nbool impassable[30][30];\nbool pet_grid[30][30];\nbool human_grid[30][30];\nbool planned_walls[30][30];\n\n// Check if a coordinate is within the 30x30 grid (0-29)\nbool is_valid(int r, int c) {\n    return r >= 0 && r < 30 && c >= 0 && c < 30;\n}\n\n// Helper to treat boundaries and walls as \"impassable\"\nbool is_impassable_or_boundary(int r, int c) {\n    if (!is_valid(r, c)) return true;\n    return impassable[r][c] || planned_walls[r][c];\n}\n\n// Update grids based on the current positions of pets and humans (start of turn)\nvoid update_grids() {\n    for (int i = 0; i < 30; ++i)\n        for (int j = 0; j < 30; ++j) {\n            pet_grid[i][j] = false;\n            human_grid[i][j] = false;\n        }\n    for (const auto& p : pets) if (is_valid(p.r, p.c)) pet_grid[p.r][p.c] = true;\n    for (const auto& h : humans) if (is_valid(h.r, h.c)) human_grid[h.r][h.c] = true;\n}\n\n// Count how many neighbors are already impassable or boundaries\nint count_adjacent_impassable(int r, int c) {\n    int count = 0;\n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    for (int i = 0; i < 4; ++i) {\n        if (is_impassable_or_boundary(r + dr[i], c + dc[i])) {\n            count++;\n        }\n    }\n    return count;\n}\n\n// Strictly check if a wall can be built legally\nbool can_build(int r, int c) {\n    if (!is_valid(r, c) || impassable[r][c] || planned_walls[r][c]) return false;\n    \n    // Rule: Cannot choose a square that contains pets or humans at the start of the turn.\n    if (pet_grid[r][c] || human_grid[r][c]) return false;\n    \n    // Rule: Cannot choose a square whose adjacent square contains a pet.\n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    for (int i = 0; i < 4; ++i) {\n        int nr = r + dr[i];\n        int nc = c + dc[i];\n        if (is_valid(nr, nc) && pet_grid[nr][nc]) return false;\n    }\n    return true;\n}\n\n// BFS to find the next valid move towards a pet\nPoint get_next_move(Point start, int target_idx) {\n    Point target = pets[target_idx];\n    if (start == target) return start;\n    \n    queue<pair<Point, Point>> q;\n    bool visited[30][30] = {false};\n    \n    int dr[] = {0, 0, 1, -1};\n    int dc[] = {1, -1, 0, 0};\n    \n    for (int i = 0; i < 4; ++i) {\n        int nr = start.r + dr[i];\n        int nc = start.c + dc[i];\n        if (is_valid(nr, nc) && !impassable[nr][nc] && !planned_walls[nr][nc]) {\n            visited[nr][nc] = true;\n            q.push({{nr, nc}, {nr, nc}});\n        }\n    }\n    \n    while (!q.empty()) {\n        auto [curr, first] = q.front();\n        q.pop();\n        \n        if (curr.r == target.r && curr.c == target.c) return first;\n        \n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n            if (is_valid(nr, nc) && !impassable[nr][nc] && !visited[nr][nc] && !planned_walls[nr][nc]) {\n                visited[nr][nc] = true;\n                q.push({{nr, nc}, first});\n            }\n        }\n    }\n    return start;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    cin >> N;\n    pets.resize(N);\n    pet_types.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].r >> pets[i].c >> pet_types[i];\n        pets[i].r--; pets[i].c--;\n    }\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].r >> humans[i].c;\n        humans[i].r--; humans[i].c--;\n    }\n    \n    for (int i = 0; i < 30; ++i) for (int j = 0; j < 30; ++j) impassable[i][j] = false;\n    \n    for (int turn = 0; turn < 300; ++turn) {\n        update_grids();\n        for (int i = 0; i < 30; ++i) for (int j = 0; j < 30; ++j) planned_walls[i][j] = false;\n        \n        // Greedy assignment: distribute humans among pets\n        vector<int> target_for_human(M);\n        vector<int> human_count_per_pet(N, 0);\n        for(int i=0; i<M; ++i) {\n            int best_pet = -1;\n            int min_val = 1e9;\n            for(int j=0; j<N; ++j) {\n                int d = abs(humans[i].r - pets[j].r) + abs(humans[i].c - pets[j].c);\n                int val = d + human_count_per_pet[j] * 10;\n                if(val < min_val) { min_val = val; best_pet = j; }\n            }\n            target_for_human[i] = best_pet;\n            human_count_per_pet[best_pet]++;\n        }\n        \n        vector<string> actions(M, \".\");\n        \n        // Planning phase\n        for (int i = 0; i < M; ++i) {\n            int target_idx = target_for_human[i];\n            \n            int best_r = -1, best_c = -1;\n            int max_score = -1000;\n            int best_k = -1;\n            \n            int dr[] = {0, 0, 1, -1};\n            int dc[] = {1, -1, 0, 0};\n            char wall_chars[] = {'r', 'l', 'd', 'u'};\n            \n            // Build if possible, with a threshold for score\n            for (int k = 0; k < 4; ++k) {\n                int nr = humans[i].r + dr[k];\n                int nc = humans[i].c + dc[k];\n                if (can_build(nr, nc)) {\n                    int score = count_adjacent_impassable(nr, nc) * 8 - (abs(nr - pets[target_idx].r) + abs(nc - pets[target_idx].c));\n                    if (score > max_score) {\n                        max_score = score;\n                        best_r = nr; best_c = nc;\n                        best_k = k;\n                    }\n                }\n            }\n            \n            if (best_r != -1 && max_score > 0) {\n                actions[i] = string(1, wall_chars[best_k]);\n                planned_walls[best_r][best_c] = true;\n            } else {\n                Point next = get_next_move(humans[i], target_idx);\n                if (!(next == humans[i])) {\n                    if (next.r < humans[i].r) actions[i] = \"U\";\n                    else if (next.r > humans[i].r) actions[i] = \"D\";\n                    else if (next.c < humans[i].c) actions[i] = \"L\";\n                    else if (next.c > humans[i].c) actions[i] = \"R\";\n                }\n            }\n        }\n        \n        // Output actions\n        for (int i = 0; i < M; ++i) cout << actions[i];\n        cout << endl;\n        \n        // Execution phase\n        for (int i = 0; i < M; ++i) {\n            if (actions[i].size() == 0 || actions[i] == \".\") continue;\n            char act = actions[i][0];\n            if (act == 'u' || act == 'd' || act == 'l' || act == 'r') {\n                int r = humans[i].r, c = humans[i].c;\n                if (act == 'u') r--; else if (act == 'd') r++; else if (act == 'l') c--; else if (act == 'r') c++;\n                if (is_valid(r, c)) impassable[r][c] = true;\n            } else if (act == 'U' || act == 'D' || act == 'L' || act == 'R') {\n                int r = humans[i].r, c = humans[i].c;\n                if (act == 'U') r--; else if (act == 'D') r++; else if (act == 'L') c--; else if (act == 'R') c++;\n                if (is_valid(r, c)) humans[i] = {r, c};\n            }\n        }\n        \n        // Update pets positions\n        for (int i = 0; i < N; ++i) {\n            string move;\n            cin >> move;\n            for (char c : move) {\n                if (c == 'U') pets[i].r--;\n                else if (c == 'D') pets[i].r++;\n                else if (c == 'L') pets[i].c--;\n                else if (c == 'R') pets[i].c++;\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Node for path reconstruction\nstruct Node {\n    int parent;\n    char move;\n};\n\n// Fixed-size State for Beam Search to minimize allocation overhead\nstruct BeamState {\n    int node_idx;\n    double dist[400]; // Probabilities for each cell\n    double reward;\n    double prob_reached;\n    double expected_total_reward;\n    bool finished; // Optimization: stop propagating if reached\n};\n\nint Si, Sj, Ti, Tj;\ndouble P;\nvector<string> H, V;\nint min_dist_to_office[400];\n\n// Compute shortest path distance using BFS\nvoid compute_min_dist() {\n    for (int i = 0; i < 400; ++i) min_dist_to_office[i] = 1000;\n    queue<int> q;\n    q.push(Ti * 20 + Tj);\n    min_dist_to_office[Ti * 20 + Tj] = 0;\n\n    while (!q.empty()) {\n        int curr = q.front();\n        q.pop();\n        int r = curr / 20;\n        int c = curr % 20;\n\n        if (r > 0 && V[r - 1][c] == '0' && min_dist_to_office[(r - 1) * 20 + c] == 1000) {\n            min_dist_to_office[(r - 1) * 20 + c] = min_dist_to_office[curr] + 1;\n            q.push((r - 1) * 20 + c);\n        }\n        if (r < 19 && V[r][c] == '0' && min_dist_to_office[(r + 1) * 20 + c] == 1000) {\n            min_dist_to_office[(r + 1) * 20 + c] = min_dist_to_office[curr] + 1;\n            q.push((r + 1) * 20 + c);\n        }\n        if (c > 0 && H[r][c - 1] == '0' && min_dist_to_office[r * 20 + c - 1] == 1000) {\n            min_dist_to_office[r * 20 + c - 1] = min_dist_to_office[curr] + 1;\n            q.push(r * 20 + c - 1);\n        }\n        if (c < 19 && H[r][c] == '0' && min_dist_to_office[r * 20 + c + 1] == 1000) {\n            min_dist_to_office[r * 20 + c + 1] = min_dist_to_office[curr] + 1;\n            q.push(r * 20 + c + 1);\n        }\n    }\n}\n\ninline bool can_move(int r, int c, char dir) {\n    if (dir == 'U') return r > 0 && V[r - 1][c] == '0';\n    if (dir == 'D') return r < 19 && V[r][c] == '0';\n    if (dir == 'L') return c > 0 && H[r][c - 1] == '0';\n    if (dir == 'R') return c < 19 && H[r][c] == '0';\n    return false;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> Si >> Sj >> Ti >> Tj >> P)) return 0;\n    H.resize(20);\n    for (int i = 0; i < 20; ++i) cin >> H[i];\n    V.resize(19);\n    for (int i = 0; i < 19; ++i) cin >> V[i];\n\n    compute_min_dist();\n\n    vector<Node> all_nodes;\n    all_nodes.reserve(300000);\n    all_nodes.push_back({-1, ' '}); // Dummy root\n\n    vector<BeamState> beam;\n    beam.reserve(1200);\n    BeamState initial;\n    initial.node_idx = 0;\n    for (int i = 0; i < 400; ++i) initial.dist[i] = 0.0;\n    initial.dist[Si * 20 + Sj] = 1.0;\n    initial.reward = 0.0;\n    initial.prob_reached = 0.0;\n    initial.finished = false;\n    double h = (double)min_dist_to_office[Si * 20 + Sj];\n    initial.expected_total_reward = 0.0 + (1.0 - 0.0) * max(0.0, 401.0 - h);\n    beam.push_back(initial);\n\n    int K = 1000; // Increased beam width\n    for (int t = 1; t <= 200; ++t) {\n        vector<BeamState> next_beam;\n        next_beam.reserve(beam.size() * 4);\n        for (const auto& s : beam) {\n            if (s.finished) {\n                next_beam.push_back(s);\n                continue;\n            }\n\n            for (char dir : {'U', 'D', 'L', 'R'}) {\n                BeamState next_s;\n                next_s.prob_reached = s.prob_reached;\n                next_s.reward = s.reward;\n                next_s.finished = false;\n                for (int i = 0; i < 400; ++i) next_s.dist[i] = 0.0;\n\n                double prob_reach_at_t = 0.0;\n\n                for (int curr = 0; curr < 400; ++curr) {\n                    if (s.dist[curr] < 1e-9) continue; // Threshold\n                    \n                    int r = curr / 20;\n                    int c = curr % 20;\n                    \n                    // Forgetting: agent stays\n                    next_s.dist[curr] += s.dist[curr] * P;\n                    \n                    // Moving: attempts to move\n                    if (can_move(r, c, dir)) {\n                        int nr = r, nc = c;\n                        if (dir == 'U') nr--;\n                        else if (dir == 'D') nr++;\n                        else if (dir == 'L') nc--;\n                        else if (dir == 'R') nc++;\n                        \n                        if (nr == Ti && nc == Tj) {\n                            prob_reach_at_t += s.dist[curr] * (1.0 - P);\n                        } else {\n                            next_s.dist[nr * 20 + nc] += s.dist[curr] * (1.0 - P);\n                        }\n                    } else {\n                        // Wall, stay\n                        next_s.dist[curr] += s.dist[curr] * (1.0 - P);\n                    }\n                }\n                \n                next_s.prob_reached += prob_reach_at_t;\n                next_s.reward += prob_reach_at_t * (401.0 - t);\n                \n                if (next_s.prob_reached >= 1.0 - 1e-12) {\n                    next_s.finished = true;\n                }\n                \n                double h_val = 0.0;\n                for (int i = 0; i < 400; ++i) {\n                    if (next_s.dist[i] > 1e-9)\n                        h_val += next_s.dist[i] * min_dist_to_office[i];\n                }\n                \n                double remaining_time = 401.0 - t - h_val;\n                if (remaining_time < 0) remaining_time = 0;\n                next_s.expected_total_reward = next_s.reward + (1.0 - next_s.prob_reached) * remaining_time;\n                \n                next_s.node_idx = all_nodes.size();\n                all_nodes.push_back({s.node_idx, dir});\n                next_beam.push_back(next_s);\n            }\n        }\n        \n        if (next_beam.size() > (size_t)K) {\n            nth_element(next_beam.begin(), next_beam.begin() + K, next_beam.end(), [](const BeamState& a, const BeamState& b) {\n                return a.expected_total_reward > b.expected_total_reward;\n            });\n            next_beam.resize(K);\n        }\n        beam = next_beam;\n    }\n    \n    sort(beam.begin(), beam.end(), [](const BeamState& a, const BeamState& b) {\n        return a.expected_total_reward > b.expected_total_reward;\n    });\n    \n    string path = \"\";\n    int curr_node = beam[0].node_idx;\n    while (all_nodes[curr_node].parent != -1) {\n        path += all_nodes[curr_node].move;\n        curr_node = all_nodes[curr_node].parent;\n    }\n    reverse(path.begin(), path.end());\n    cout << path << endl;\n    \n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <cstring>\n\nusing namespace std;\n\n// Precomputed connectivity: base_conn[type][rotation][in_direction] = out_direction\nint base_conn[8][4][4];\nint current_conn[900][4];\nint row[900], col[900];\nint d_offset[4] = {-1, -30, 1, 30};\n\nvoid precompute() {\n    int base_to[8][4] = {\n        {1, 0, -1, -1}, {3, -1, -1, 0}, {-1, -1, 3, 2}, {-1, 2, 1, -1},\n        {1, 0, 3, 2},   {3, 2, 1, 0},   {2, -1, 0, -1}, {-1, 3, -1, 1}\n    };\n    for (int t = 0; t < 8; ++t) {\n        for (int r = 0; r < 4; ++r) {\n            for (int d = 0; d < 4; ++d) {\n                int d_old = (d + r) % 4;\n                int d_old_exit = base_to[t][d_old];\n                base_conn[t][r][d] = (d_old_exit == -1) ? -1 : (d_old_exit - r + 4) % 4;\n            }\n        }\n    }\n    for(int i = 0; i < 900; ++i) { \n        row[i] = i / 30; \n        col[i] = i % 30; \n    }\n}\n\nint N = 30;\nint tiles[30][30];\nint r[30][30];\nint visited[3600]; \nint visit_gen = 0;\n\n// Highly optimized score calculation\nstruct ScoreResult {\n    long long internal;\n    long long true_score;\n};\n\ninline ScoreResult get_score() {\n    visit_gen++;\n    if (visit_gen > 1000000000) { memset(visited, 0, sizeof(visited)); visit_gen = 1; }\n    \n    int max1 = 0, max2 = 0;\n    for (int i = 0; i < 900; ++i) {\n        for (int d = 0; d < 4; ++d) {\n            int v_idx = (i << 2) + d;\n            if (visited[v_idx] == visit_gen) continue;\n            \n            int curr_idx = i;\n            int curr_d = d;\n            int length = 0;\n            int start_idx = curr_idx;\n            int start_d = curr_d;\n            bool closed = false;\n            \n            while (true) {\n                int v_curr = (curr_idx << 2) + curr_d;\n                if (visited[v_curr] == visit_gen) break;\n                visited[v_curr] = visit_gen;\n                \n                int next_d = current_conn[curr_idx][curr_d];\n                if (next_d == -1) break;\n                \n                // Boundary check\n                if (next_d == 0 && col[curr_idx] == 0) break;\n                if (next_d == 1 && row[curr_idx] == 0) break;\n                if (next_d == 2 && col[curr_idx] == 29) break;\n                if (next_d == 3 && row[curr_idx] == 29) break;\n                \n                curr_idx += d_offset[next_d];\n                curr_d = (next_d + 2) % 4;\n                length++;\n                \n                if (curr_idx == start_idx && curr_d == start_d) {\n                    closed = true;\n                    break;\n                }\n            }\n            if (closed) {\n                if (length > max1) { max2 = max1; max1 = length; }\n                else if (length > max2) { max2 = length; }\n            }\n        }\n    }\n    long long true_score = (max2 > 0) ? (long long)max1 * max2 : 0;\n    // Internal reward: prioritize finding two loops over just one.\n    long long internal_score = (max2 > 0) ? (true_score + 1000000) : (long long)max1;\n    return {internal_score, true_score};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    precompute();\n    for (int i = 0; i < N; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; ++j) {\n            tiles[i][j] = s[j] - '0';\n            r[i][j] = 0; \n            for (int d = 0; d < 4; ++d) current_conn[i * 30 + j][d] = base_conn[tiles[i][j]][0][d];\n        }\n    }\n    \n    int best_r[30][30];\n    memcpy(best_r, r, sizeof(r));\n    ScoreResult initial_score = get_score();\n    long long best_true_score = initial_score.true_score;\n    \n    auto start_time = chrono::steady_clock::now();\n    double time_limit = 1.95; \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    int num_restarts = 5;\n    \n    for (int restart = 0; restart < num_restarts; ++restart) {\n        if (restart > 0) {\n            for(int i = 0; i < N; ++i) {\n                for(int j = 0; j < N; ++j) {\n                    r[i][j] = rng() % 4;\n                    for(int d = 0; d < 4; ++d) current_conn[i * 30 + j][d] = base_conn[tiles[i][j]][r[i][j]][d];\n                }\n            }\n        }\n        \n        ScoreResult current_res = get_score();\n        long long current_internal = current_res.internal;\n        int iterations = 0;\n        \n        while (true) {\n            if ((iterations & 511) == 0) {\n                if (chrono::duration<double>(chrono::steady_clock::now() - start_time).count() > time_limit) goto end_loops;\n            }\n            iterations++;\n            \n            int i, old_r, new_r;\n            // Occasional perturbation\n            if (iterations % 20000 == 0) {\n                for(int k=0; k<5; ++k) {\n                    i = rng() % 900;\n                    old_r = r[i / 30][i % 30];\n                    new_r = rng() % 4;\n                    r[i / 30][i % 30] = new_r;\n                    for(int d = 0; d < 4; ++d) current_conn[i][d] = base_conn[tiles[i/30][i%30]][new_r][d];\n                }\n            } else {\n                i = rng() % 900;\n                old_r = r[i / 30][i % 30];\n                new_r = rng() % 4;\n                if (old_r == new_r) continue;\n                r[i / 30][i % 30] = new_r;\n                for(int d = 0; d < 4; ++d) current_conn[i][d] = base_conn[tiles[i/30][i%30]][new_r][d];\n            }\n            \n            ScoreResult next_res = get_score();\n            \n            double progress = chrono::duration<double>(chrono::steady_clock::now() - start_time).count() / time_limit;\n            double T = 1000.0 * pow(0.0001, progress); \n            double prob = (next_res.internal >= current_internal) ? 1.0 : exp((double)(next_res.internal - current_internal) / (T + 1e-9));\n            \n            if (next_res.true_score > best_true_score) {\n                best_true_score = next_res.true_score;\n                memcpy(best_r, r, sizeof(r));\n            }\n            \n            if (prob > (double)rng() / rng.max()) {\n                current_internal = next_res.internal;\n            } else {\n                r[i / 30][i % 30] = old_r;\n                for(int d = 0; d < 4; ++d) current_conn[i][d] = base_conn[tiles[i/30][i%30]][old_r][d];\n            }\n        }\n    }\n    \n    end_loops:\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) cout << best_r[i][j];\n    }\n    cout << endl;\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <chrono>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent the board\nstruct Board {\n    int N;\n    vector<int> tiles;\n    int empty_r, empty_c;\n\n    Board(int n, const vector<int>& t) : N(n), tiles(t) {\n        for (int i = 0; i < N * N; ++i) {\n            if (tiles[i] == 0) {\n                empty_r = i / N;\n                empty_c = i % N;\n            }\n        }\n    }\n\n    bool apply(char move) {\n        int nr = empty_r, nc = empty_c;\n        if (move == 'U') nr--;\n        else if (move == 'D') nr++;\n        else if (move == 'L') nc--;\n        else if (move == 'R') nc++;\n        else return false;\n\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n\n        swap(tiles[empty_r * N + empty_c], tiles[nr * N + nc]);\n        empty_r = nr;\n        empty_c = nc;\n        return true;\n    }\n};\n\nchar reverse_move(char m) {\n    if (m == 'U') return 'D';\n    if (m == 'D') return 'U';\n    if (m == 'L') return 'R';\n    if (m == 'R') return 'L';\n    return ' ';\n}\n\n// DSU structure for tree connectivity and counting\nstruct DSU {\n    vector<int> parent, nodes, edges;\n    DSU(int n) : parent(n), nodes(n, 1), edges(n, 0) {}\n    \n    void reset(int n) {\n        for (int i = 0; i < n; ++i) {\n            parent[i] = i;\n            nodes[i] = 1;\n            edges[i] = 0;\n        }\n    }\n\n    int find(int i) {\n        if (parent[i] == i) return i;\n        return parent[i] = find(parent[i]);\n    }\n\n    void unite(int i, int j) {\n        int root_i = find(i);\n        int root_j = find(j);\n        if (root_i != root_j) {\n            parent[root_j] = root_i;\n            nodes[root_i] += nodes[root_j];\n            edges[root_i] += edges[root_j] + 1;\n        } else {\n            edges[root_i]++;\n        }\n    }\n};\n\nint calculate_max_tree_size(const Board& b, DSU& dsu) {\n    int N = b.N;\n    dsu.reset(N * N);\n    for (int i = 0; i < N * N; ++i) if (b.tiles[i] == 0) dsu.nodes[i] = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int u = i * N + j;\n            if (b.tiles[u] == 0) continue;\n            if (j + 1 < N && b.tiles[i * N + j + 1] != 0) {\n                if ((b.tiles[u] & 4) && (b.tiles[i * N + j + 1] & 1)) dsu.unite(u, i * N + j + 1);\n            }\n            if (i + 1 < N && b.tiles[(i + 1) * N + j] != 0) {\n                if ((b.tiles[u] & 8) && (b.tiles[(i + 1) * N + j] & 2)) dsu.unite(u, (i + 1) * N + j);\n            }\n        }\n    }\n    int max_s = 0;\n    for (int i = 0; i < N * N; ++i) {\n        if (dsu.parent[i] == i && dsu.nodes[i] > 0) {\n            if (dsu.edges[i] == dsu.nodes[i] - 1) max_s = max(max_s, dsu.nodes[i]);\n        }\n    }\n    return max_s;\n}\n\nint hex_to_int(char c) {\n    return (c >= '0' && c <= '9') ? (c - '0') : (c - 'a' + 10);\n}\n\n// Incremental pruning: add move to path and cancel inverse\nvoid add_move(string& p, char m) {\n    if (!p.empty() && p.back() == reverse_move(m)) p.pop_back();\n    else p.push_back(m);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int N, T;\n    cin >> N >> T;\n    vector<int> tiles(N * N);\n    string s;\n    for (int i = 0; i < N; ++i) {\n        cin >> s;\n        for (int j = 0; j < N; ++j) tiles[i * N + j] = hex_to_int(s[j]);\n    }\n\n    Board initial_board(N, tiles);\n    DSU dsu(N * N);\n    string best_moves = \"\";\n    int best_S = calculate_max_tree_size(initial_board, dsu);\n\n    auto start_time = chrono::steady_clock::now();\n    mt19937 rng(42);\n\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 2800) {\n        Board current_board = initial_board;\n        string current_moves = \"\";\n        int current_S = calculate_max_tree_size(current_board, dsu);\n        char last_move = ' ';\n        int stuck_count = 0;\n\n        for (int i = 0; i < T; ++i) {\n            if (best_S == N * N - 1 && current_moves.size() >= best_moves.size() && !best_moves.empty()) break;\n\n            vector<char> moves = {'U', 'D', 'L', 'R'};\n            vector<char> best_moves_list;\n            int best_move_S = -1;\n\n            for (char move : moves) {\n                if (move == reverse_move(last_move)) continue;\n                Board next_board = current_board;\n                if (next_board.apply(move)) {\n                    int next_S = calculate_max_tree_size(next_board, dsu);\n                    if (next_S > best_move_S) {\n                        best_move_S = next_S;\n                        best_moves_list.clear();\n                        best_moves_list.push_back(move);\n                    } else if (next_S == best_move_S) {\n                        best_moves_list.push_back(move);\n                    }\n                }\n            }\n\n            if (!best_moves_list.empty() && best_move_S >= current_S) {\n                char move = best_moves_list[rng() % best_moves_list.size()];\n                current_board.apply(move);\n                add_move(current_moves, move);\n                current_S = best_move_S;\n                last_move = move;\n                stuck_count = 0;\n                \n                if (current_S > best_S) {\n                    best_S = current_S;\n                    best_moves = current_moves;\n                } else if (current_S == best_S && best_S == N * N - 1) {\n                    if (best_moves.empty() || current_moves.size() < best_moves.size()) best_moves = current_moves;\n                }\n            } else {\n                stuck_count++;\n                int walk_len = (stuck_count > 20) ? 20 : 8;\n                char walk_last = last_move;\n                bool moved = false;\n                for(int k = 0; k < walk_len; ++k) {\n                    shuffle(moves.begin(), moves.end(), rng);\n                    for(char move : moves) {\n                        if (move == reverse_move(walk_last)) continue;\n                        if(current_board.apply(move)) {\n                            add_move(current_moves, move);\n                            current_S = calculate_max_tree_size(current_board, dsu);\n                            walk_last = move;\n                            moved = true;\n                            break;\n                        }\n                    }\n                }\n                if (!moved) break;\n                last_move = walk_last;\n            }\n            if (current_moves.size() >= T) break;\n        }\n    }\n    cout << best_moves << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent a point\nstruct Point {\n    long long x, y;\n};\n\n// Structure to represent a line: ax + by + c = 0\nstruct Line {\n    long long a, b, c;\n    Point p1, p2;\n};\n\n// Global data\nint N, K;\nvector<int> a(11);\nvector<Point> strawberries;\nmt19937 rng(1337);\n\n// Function to calculate the score: sum(min(a_d, b_d))\nint calculate_score(const vector<int>& piece_counts) {\n    vector<int> b(11, 0);\n    for (int count : piece_counts) {\n        if (count >= 1 && count <= 10) {\n            b[count]++;\n        }\n    }\n    int score = 0;\n    for (int d = 1; d <= 10; ++d) {\n        score += min(a[d], b[d]);\n    }\n    return score;\n}\n\n// Generate a random line that intersects the cake\nLine generate_random_line() {\n    // Generate points within [-20000, 20000] to cover the cake radius of 10000\n    uniform_int_distribution<long long> dist(-20000, 20000);\n    while (true) {\n        Point p1 = {dist(rng), dist(rng)};\n        Point p2 = {dist(rng), dist(rng)};\n        if (p1.x == p2.x && p1.y == p2.y) continue;\n\n        // Line equation: (y1 - y2)x + (x2 - x1)y + (x1y2 - x2y1) = 0\n        long long a = p1.y - p2.y;\n        long long b = p2.x - p1.x;\n        long long c = -a * p1.x - b * p1.y;\n\n        // Check if the line cuts the cake (distance from origin < 10000)\n        __int128 c2 = (__int128)c * c;\n        __int128 dist2 = (__int128)a * a + (__int128)b * b;\n        if (c2 < (__int128)100000000 * dist2) {\n            return {a, b, c, p1, p2};\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> N >> K)) return 0;\n    for (int i = 1; i <= 10; ++i) cin >> a[i];\n    strawberries.resize(N);\n    for (int i = 0; i < N; ++i) cin >> strawberries[i].x >> strawberries[i].y;\n\n    // current_piece_id[i] stores the ID of the piece that strawberry i belongs to\n    vector<int> current_piece_id(N, 0);\n    int num_pieces = 1;\n    vector<Line> lines;\n\n    for (int k = 0; k < K; ++k) {\n        int best_score = -1;\n        Line best_line;\n        bool found = false;\n\n        // Try 1000 random lines and pick the best one\n        for (int trial = 0; trial < 1000; ++trial) {\n            Line line = generate_random_line();\n            \n            // Piece split: how many strawberries in each piece fall on the left/right side\n            // piece_split[p_id].first = count on left, .second = count on right\n            vector<pair<int, int>> piece_split(num_pieces, {0, 0});\n            for (int i = 0; i < N; ++i) {\n                if (current_piece_id[i] == -1) continue;\n                long long val = line.a * strawberries[i].x + line.b * strawberries[i].y + line.c;\n                if (val > 0) piece_split[current_piece_id[i]].second++;\n                else if (val < 0) piece_split[current_piece_id[i]].first++;\n                // val == 0 means the strawberry is on the line (removed)\n            }\n\n            vector<int> next_piece_counts;\n            for (int p = 0; p < num_pieces; ++p) {\n                if (piece_split[p].first > 0) next_piece_counts.push_back(piece_split[p].first);\n                if (piece_split[p].second > 0) next_piece_counts.push_back(piece_split[p].second);\n            }\n\n            int score = calculate_score(next_piece_counts);\n            if (score > best_score) {\n                best_score = score;\n                best_line = line;\n                found = true;\n            }\n        }\n        \n        if (found) {\n            lines.push_back(best_line);\n            \n            // Update current_piece_id mapping for all strawberries\n            vector<int> next_piece_id(N, -1);\n            // new_id_map[old_piece_id][side] -> new_piece_id\n            vector<vector<int>> new_id_map(num_pieces, vector<int>(2, -1));\n            int next_num_pieces = 0;\n\n            for (int i = 0; i < N; ++i) {\n                if (current_piece_id[i] == -1) continue;\n                long long val = best_line.a * strawberries[i].x + best_line.b * strawberries[i].y + best_line.c;\n                if (val == 0) continue; // Strawberry removed\n                \n                int side = (val > 0) ? 1 : 0;\n                int p = current_piece_id[i];\n                \n                if (new_id_map[p][side] == -1) {\n                    new_id_map[p][side] = next_num_pieces++;\n                }\n                next_piece_id[i] = new_id_map[p][side];\n            }\n            current_piece_id = next_piece_id;\n            num_pieces = next_num_pieces;\n        } else {\n            // No improvement found, stop cutting\n            break;\n        }\n    }\n\n    // Output the result\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line.p1.x << \" \" << line.p1.y << \" \" << line.p2.x << \" \" << line.p2.y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <queue>\n#include <random>\n#include <chrono>\n#include <cstring>\n\nusing namespace std;\n\nstruct Point { int x, y; };\nstruct Rectangle { Point p[4]; };\nstruct Op { int rect_id; int p_new_idx; };\nstruct Candidate {\n    int weight, id;\n    bool operator<(const Candidate& other) const {\n        return weight < other.weight;\n    }\n};\n\nint N, M;\nvector<Rectangle> all_rects;\nvector<int> potential_rects_flat;\nvector<int> potential_rects_start;\nbool has_dot_init[70][70];\nbool has_dot[70][70];\n// Using vectors for dynamic sizing based on number of rectangles\nvector<int> occupied_count_init;\nvector<int> occupied_count;\nvector<bool> is_used_rect;\nbool used_h[70][70], used_v[70][70], used_d1[150][70], used_d2[150][70];\n\ninline int get_weight(int x, int y) {\n    int cx = (N - 1) / 2, cy = (N - 1) / 2;\n    return (x - cx) * (x - cx) + (y - cy) * (y - cy) + 1;\n}\n\ninline bool is_valid_coord(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\n\nvoid add_rect(Point p1, Point p2, Point p3, Point p4) {\n    if (is_valid_coord(p1.x, p1.y) && is_valid_coord(p2.x, p2.y) && is_valid_coord(p3.x, p3.y) && is_valid_coord(p4.x, p4.y)) {\n        all_rects.push_back({{p1, p2, p3, p4}});\n    }\n}\n\nbool check_rect_validity(const Rectangle& r) {\n    auto check_seg = [&](Point a, Point b) {\n        int dx = b.x - a.x, dy = b.y - a.y;\n        int dist = max(abs(dx), abs(dy));\n        int sx = (dist == 0) ? 0 : dx / dist, sy = (dist == 0) ? 0 : dy / dist;\n        for (int i = 0; i < dist; ++i) {\n            int x1 = a.x + i * sx, y1 = a.y + i * sy;\n            if (sy == 0) { if (used_h[min(x1, x1 + sx)][y1]) return false; }\n            else if (sx == 0) { if (used_v[x1][min(y1, y1 + sy)]) return false; }\n            else if (sx == sy) { if (used_d1[y1 - x1 + N][min(x1, x1 + sx)]) return false; }\n            else { if (used_d2[y1 + x1][min(x1, x1 + sx)]) return false; }\n        }\n        return true;\n    };\n    if (!check_seg(r.p[0], r.p[1]) || !check_seg(r.p[1], r.p[2]) || !check_seg(r.p[2], r.p[3]) || !check_seg(r.p[3], r.p[0])) return false;\n    auto has_dot_on_seg = [&](Point a, Point b) {\n        int dx = b.x - a.x, dy = b.y - a.y;\n        int dist = max(abs(dx), abs(dy));\n        int sx = (dist == 0) ? 0 : dx / dist, sy = (dist == 0) ? 0 : dy / dist;\n        for (int i = 1; i < dist; ++i) if (has_dot[a.x + i * sx][a.y + i * sy]) return true;\n        return false;\n    };\n    return !(has_dot_on_seg(r.p[0], r.p[1]) || has_dot_on_seg(r.p[1], r.p[2]) || has_dot_on_seg(r.p[2], r.p[3]) || has_dot_on_seg(r.p[3], r.p[0]));\n}\n\nvoid mark_segments(const Rectangle& r) {\n    auto add_seg = [&](Point a, Point b) {\n        int dx = b.x - a.x, dy = b.y - a.y;\n        int dist = max(abs(dx), abs(dy));\n        int sx = (dist == 0) ? 0 : dx / dist, sy = (dist == 0) ? 0 : dy / dist;\n        for (int i = 0; i < dist; ++i) {\n            int x1 = a.x + i * sx, y1 = a.y + i * sy;\n            if (sy == 0) used_h[min(x1, x1 + sx)][y1] = true;\n            else if (sx == 0) used_v[x1][min(y1, y1 + sy)] = true;\n            else if (sx == sy) used_d1[y1 - x1 + N][min(x1, x1 + sx)] = true;\n            else used_d2[y1 + x1][min(x1, x1 + sx)] = true;\n        }\n    };\n    add_seg(r.p[0], r.p[1]); add_seg(r.p[1], r.p[2]); add_seg(r.p[2], r.p[3]); add_seg(r.p[3], r.p[0]);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n    cin >> N >> M;\n    memset(has_dot_init, 0, sizeof(has_dot_init));\n    for (int i = 0; i < M; ++i) { int x, y; cin >> x >> y; has_dot_init[x][y] = true; }\n    for (int x1 = 0; x1 < N; ++x1) for (int x2 = x1 + 1; x2 < N; ++x2) for (int y1 = 0; y1 < N; ++y1) for (int y2 = y1 + 1; y2 < N; ++y2) add_rect({x1, y1}, {x2, y1}, {x2, y2}, {x1, y2});\n    for (int x = 0; x < N; ++x) for (int y = 0; y < N; ++y) for (int d = 1; d < N; ++d) for (int k = 1; k < N; ++k) add_rect({x, y}, {x + d, y + d}, {x + d + k, y + d - k}, {x + k, y - k});\n\n    vector<vector<int>> temp_adj(N * N);\n    occupied_count_init.assign(all_rects.size(), 0);\n    for (int i = 0; i < (int)all_rects.size(); ++i) {\n        for (int j = 0; j < 4; ++j) temp_adj[all_rects[i].p[j].x * N + all_rects[i].p[j].y].push_back(i);\n        for (int j = 0; j < 4; ++j) if (has_dot_init[all_rects[i].p[j].x][all_rects[i].p[j].y]) occupied_count_init[i]++;\n    }\n    potential_rects_start.resize(N * N + 1);\n    for (int i = 0; i < N * N; ++i) {\n        potential_rects_start[i] = potential_rects_flat.size();\n        for (int id : temp_adj[i]) potential_rects_flat.push_back(id);\n    }\n    potential_rects_start[N * N] = potential_rects_flat.size();\n\n    vector<Op> best_ops; long long best_score = -1;\n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() < 4200) {\n        memcpy(has_dot, has_dot_init, sizeof(has_dot));\n        occupied_count = occupied_count_init;\n        is_used_rect.assign(all_rects.size(), false);\n        memset(used_h, 0, sizeof(used_h)); memset(used_v, 0, sizeof(used_v)); memset(used_d1, 0, sizeof(used_d1)); memset(used_d2, 0, sizeof(used_d2));\n        priority_queue<Candidate> pq;\n        for (int i = 0; i < (int)all_rects.size(); ++i) if (occupied_count[i] == 3) {\n            int e = -1; for(int j=0; j<4; ++j) if(!has_dot[all_rects[i].p[j].x][all_rects[i].p[j].y]) e = j;\n            if(e != -1) pq.push({get_weight(all_rects[i].p[e].x, all_rects[i].p[e].y) + (int)(rng() % 5), i});\n        }\n        vector<Op> current_ops; long long current_score = 0;\n        for(int i=0; i<N; ++i) for(int j=0; j<N; ++j) if(has_dot[i][j]) current_score += get_weight(i, j);\n        while (!pq.empty()) {\n            Candidate top = pq.top(); pq.pop();\n            int id = top.id;\n            if (is_used_rect[id] || occupied_count[id] != 3 || !check_rect_validity(all_rects[id])) continue;\n            int e = -1; for(int j=0; j<4; ++j) if(!has_dot[all_rects[id].p[j].x][all_rects[id].p[j].y]) e = j;\n            has_dot[all_rects[id].p[e].x][all_rects[id].p[e].y] = true;\n            is_used_rect[id] = true;\n            current_ops.push_back({id, e});\n            current_score += get_weight(all_rects[id].p[e].x, all_rects[id].p[e].y);\n            mark_segments(all_rects[id]);\n            int nx = all_rects[id].p[e].x, ny = all_rects[id].p[e].y;\n            for (int k = potential_rects_start[nx * N + ny]; k < potential_rects_start[nx * N + ny + 1]; ++k) {\n                int rid = potential_rects_flat[k];\n                occupied_count[rid]++;\n                if (occupied_count[rid] == 3) {\n                    int ne = -1; for(int j=0; j<4; ++j) if(!has_dot[all_rects[rid].p[j].x][all_rects[rid].p[j].y]) ne = j;\n                    if(ne != -1) pq.push({get_weight(all_rects[rid].p[ne].x, all_rects[rid].p[ne].y) + (int)(rng() % 5), rid});\n                }\n            }\n        }\n        if (current_score > best_score) { best_score = current_score; best_ops = current_ops; }\n    }\n    cout << best_ops.size() << \"\\n\";\n    for (const auto& op : best_ops) {\n        const auto& r = all_rects[op.rect_id];\n        int idx = op.p_new_idx;\n        cout << r.p[idx].x << \" \" << r.p[idx].y << \" \" << r.p[(idx + 1) % 4].x << \" \" << r.p[(idx + 1) % 4].y << \" \"\n             << r.p[(idx + 2) % 4].x << \" \" << r.p[(idx + 2) % 4].y << \" \" << r.p[(idx + 3) % 4].x << \" \" << r.p[(idx + 3) % 4].y << \"\\n\";\n    }\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <cstring>\n#include <algorithm>\n#include <ctime>\n\nusing namespace std;\n\n// Fast XorShift PRNG\nstruct XorShift {\n    uint32_t x = 123456789, y = 362436069, z = 521288629, w = 88675123;\n    inline uint32_t next() {\n        uint32_t t = x ^ (x << 11);\n        x = y; y = z; z = w;\n        return w = w ^ (w >> 19) ^ t ^ (t >> 8);\n    }\n    inline int nextInt(int n) { return next() % n; }\n} rng;\n\nstruct Board {\n    int cell[100];\n};\n\ninline void apply_tilt(Board& b, char dir) {\n    if (dir == 'F') { // Move towards top\n        for (int c = 0; c < 10; ++c) {\n            int write = 0;\n            for (int r = 0; r < 10; ++r) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[write * 10 + c] = v;\n                    write++;\n                }\n            }\n        }\n    } else if (dir == 'B') { // Move towards bottom\n        for (int c = 0; c < 10; ++c) {\n            int write = 9;\n            for (int r = 9; r >= 0; --r) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[write * 10 + c] = v;\n                    write--;\n                }\n            }\n        }\n    } else if (dir == 'L') { // Move towards left\n        for (int r = 0; r < 10; ++r) {\n            int write = 0;\n            for (int c = 0; c < 10; ++c) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[r * 10 + write] = v;\n                    write++;\n                }\n            }\n        }\n    } else if (dir == 'R') { // Move towards right\n        for (int r = 0; r < 10; ++r) {\n            int write = 9;\n            for (int c = 9; c >= 0; --c) {\n                if (b.cell[r * 10 + c]) {\n                    int v = b.cell[r * 10 + c];\n                    b.cell[r * 10 + c] = 0;\n                    b.cell[r * 10 + write] = v;\n                    write--;\n                }\n            }\n        }\n    }\n}\n\n// Optimized BFS using a reusable buffer and token system\ninline int calculate_score(const Board& b, int* visited, int& token) {\n    token++;\n    int score = 0;\n    static int q[100];\n    \n    for (int i = 0; i < 100; ++i) {\n        if (b.cell[i] == 0 || visited[i] == token) continue;\n        int flavor = b.cell[i];\n        int count = 0;\n        int head = 0, tail = 0;\n        q[tail++] = i;\n        visited[i] = token;\n        \n        while (head < tail) {\n            int curr = q[head++];\n            count++;\n            int r = curr / 10;\n            int c = curr % 10;\n            \n            if (r > 0) {\n                int next = curr - 10;\n                if (visited[next] != token && b.cell[next] == flavor) {\n                    visited[next] = token;\n                    q[tail++] = next;\n                }\n            }\n            if (r < 9) {\n                int next = curr + 10;\n                if (visited[next] != token && b.cell[next] == flavor) {\n                    visited[next] = token;\n                    q[tail++] = next;\n                }\n            }\n            if (c > 0) {\n                int next = curr - 1;\n                if (visited[next] != token && b.cell[next] == flavor) {\n                    visited[next] = token;\n                    q[tail++] = next;\n                }\n            }\n            if (c < 9) {\n                int next = curr + 1;\n                if (visited[next] != token && b.cell[next] == flavor) {\n                    visited[next] = token;\n                    q[tail++] = next;\n                }\n            }\n        }\n        score += count * count;\n    }\n    return score;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    vector<int> f(100);\n    for (int i = 0; i < 100; ++i) cin >> f[i];\n\n    Board b;\n    memset(b.cell, 0, sizeof(b.cell));\n    char directions[] = {'F', 'B', 'L', 'R'};\n    \n    int visited[100] = {0};\n    int token = 0;\n\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        cin >> p;\n        int count = 0;\n        for (int i = 0; i < 100; ++i) {\n            if (b.cell[i] == 0) {\n                count++;\n                if (count == p) {\n                    b.cell[i] = f[t];\n                    break;\n                }\n            }\n        }\n\n        if (t == 99) break;\n\n        clock_t start_time = clock();\n        double total_scores[4] = {0, 0, 0, 0};\n        int counts[4] = {0, 0, 0, 0};\n        int rollout_counter = 0;\n\n        // Perform rollouts within a strict 12ms time budget\n        while (true) {\n            if ((rollout_counter & 511) == 0) {\n                if ((double)(clock() - start_time) / CLOCKS_PER_SEC > 0.012) break;\n            }\n            rollout_counter++;\n            \n            for (int d = 0; d < 4; ++d) {\n                Board sim_b = b;\n                apply_tilt(sim_b, directions[d]);\n                \n                // Rollout capped at 12 moves for performance\n                int max_lookahead = min(100, t + 1 + 12);\n                for (int st = t + 1; st < max_lookahead; ++st) {\n                    int next_pos = rng.nextInt(100);\n                    while (sim_b.cell[next_pos] != 0) {\n                        next_pos = (next_pos + 1) % 100;\n                    }\n                    sim_b.cell[next_pos] = f[st];\n                    \n                    apply_tilt(sim_b, directions[rng.nextInt(4)]);\n                }\n                total_scores[d] += calculate_score(sim_b, visited, token);\n                counts[d]++;\n            }\n        }\n\n        double max_score = -1.0;\n        char best_dir = 'F';\n        for (int d = 0; d < 4; ++d) {\n            if (counts[d] > 0) {\n                double avg = total_scores[d] / counts[d];\n                if (avg > max_score) {\n                    max_score = avg;\n                    best_dir = directions[d];\n                }\n            }\n        }\n\n        cout << best_dir << endl;\n        apply_tilt(b, best_dir);\n    }\n    return 0;\n}","ahc016":"/*\n * Refined Approach:\n * 1. Optimized Adaptive N:\n *    - N = max({M, 4, (int)(4 + 96 * pow(min(1.0, eps / 0.4), 1.8))}).\n *    - This formula minimizes N for low noise cases (down to 4), reducing the 1/N \n *      scoring penalty, while scaling up to 100 for high noise to maintain robustness.\n *    - Ensures N >= M for distinguishable encoding.\n * 2. Encoding: Clique-based graphs.\n *    - Clique sizes distributed uniformly [1, N] ensure distinct degree sequences.\n * 3. Classification:\n *    - Euclidean distance on sorted degree sequences is used for matching.\n *    - This metric is robust against both edge-flip noise and vertex shuffling.\n */\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\n// Structure to hold graph information\nstruct Graph {\n    int id;\n    int clique_size;\n    vector<int> degree_seq;\n    string edges;\n};\n\n// Helper to compute degree sequence from edges string\nvector<int> compute_degree_seq(int N, const string& edges) {\n    vector<int> deg(N, 0);\n    int idx = 0;\n    for (int i = 0; i < N - 1; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (edges[idx] == '1') {\n                deg[i]++;\n                deg[j]++;\n            }\n            idx++;\n        }\n    }\n    // Sorting makes the degree sequence invariant to vertex permutation\n    sort(deg.begin(), deg.end());\n    return deg;\n}\n\nint main() {\n    // Optimization for I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n\n    // Optimized Adaptive N calculation:\n    // - N >= M is required to encode M distinct graphs.\n    // - N >= 4 is a hard constraint (problem says 4 <= N <= 100).\n    // - Scaling N with noise using power-law growth: 4 + 96 * (eps/0.4)^1.8\n    //   This minimizes the 1/N penalty at low noise and maintains robustness at high noise.\n    int N = max(M, 4 + (int)(96 * pow(min(1.0, eps / 0.4), 1.8)));\n    if (N > 100) N = 100;\n\n    cout << N << endl;\n\n    vector<Graph> graphs(M);\n    for (int k = 0; k < M; ++k) {\n        graphs[k].id = k;\n        \n        // Distribute clique sizes uniformly in [1, N]\n        // This ensures distinct degree sequences for each graph.\n        if (M == 1) {\n            graphs[k].clique_size = 2; // Smallest non-trivial clique size\n        } else {\n            // Map k to a value in [1, N]\n            graphs[k].clique_size = 1 + (int)((double)k * (N - 1) / (M - 1));\n        }\n\n        int c = graphs[k].clique_size;\n        \n        // Generate edge string\n        // A clique of size c has edges between all pairs (i, j) where i, j < c.\n        string s = \"\";\n        s.reserve(N * (N - 1) / 2);\n        for (int i = 0; i < N - 1; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (i < c && j < c) {\n                    s += '1';\n                } else {\n                    s += '0';\n                }\n            }\n        }\n        graphs[k].edges = s;\n        graphs[k].degree_seq = compute_degree_seq(N, s);\n    }\n\n    // Output the generated graphs\n    for (int k = 0; k < M; ++k) {\n        cout << graphs[k].edges << endl;\n    }\n\n    // Process 100 queries\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;\n\n        // Compute degree sequence of received graph\n        vector<int> degH = compute_degree_seq(N, H);\n\n        // Find the graph whose degree sequence is closest to H's\n        int best_k = 0;\n        long long min_dist = -1;\n\n        for (int k = 0; k < M; ++k) {\n            long long dist = 0;\n            const vector<int>& degG = graphs[k].degree_seq;\n            // The degree sequence is always length N\n            for (int i = 0; i < N; ++i) {\n                long long diff = (long long)degG[i] - degH[i];\n                dist += diff * diff;\n            }\n            if (min_dist == -1 || dist < min_dist) {\n                min_dist = dist;\n                best_k = k;\n            }\n        }\n        cout << best_k << endl;\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <ctime>\n\nusing namespace std;\n\n// Structure to represent an edge\nstruct Edge {\n    int u, v, w, id;\n};\n\n// Structure for predecessors in shortest path\nstruct Predecessor {\n    int u;\n    int edge_id;\n};\n\nint N, M, D, K;\nvector<vector<pair<int, pair<int, int>>>> adj;\nvector<Edge> edges;\nvector<double> edge_bc;\nvector<double> edge_cost;\n\n// Compute Betweenness Centrality using Brandes' algorithm\n// Optimized for the given constraints (N=1000, M=3000)\nvoid compute_bc() {\n    edge_bc.assign(M, 0.0);\n    for (int s = 0; s < N; ++s) {\n        vector<long long> dist(N + 1, 1e18);\n        vector<long double> sigma(N + 1, 0.0);\n        vector<vector<Predecessor>> predecessors(N + 1);\n        vector<int> order;\n        \n        dist[s + 1] = 0;\n        sigma[s + 1] = 1.0;\n        \n        priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n        pq.push({0, s + 1});\n        \n        while (!pq.empty()) {\n            long long d = pq.top().first;\n            int u = pq.top().second;\n            pq.pop();\n            \n            if (d > dist[u]) continue;\n            order.push_back(u);\n            \n            for (auto& edge : adj[u]) {\n                int v = edge.first;\n                int weight = edge.second.first;\n                int id = edge.second.second;\n                \n                if (dist[v] > dist[u] + weight) {\n                    dist[v] = dist[u] + weight;\n                    sigma[v] = sigma[u];\n                    predecessors[v].clear();\n                    predecessors[v].push_back({u, id});\n                    pq.push({dist[v], v});\n                } else if (dist[v] == dist[u] + weight) {\n                    sigma[v] += sigma[u];\n                    predecessors[v].push_back({u, id});\n                }\n            }\n        }\n        \n        vector<long double> delta(N + 1, 0.0);\n        for (int i = (int)order.size() - 1; i >= 0; --i) {\n            int w = order[i];\n            for (auto& pred : predecessors[w]) {\n                int v = pred.u;\n                int edge_id = pred.edge_id;\n                \n                if (sigma[w] > 0) {\n                    long double coeff = (sigma[v] / sigma[w]) * (1.0 + delta[w]);\n                    delta[v] += coeff;\n                    edge_bc[edge_id] += coeff;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    if (!(cin >> N >> M >> D >> K)) return 0;\n    adj.resize(N + 1);\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges[i] = {u, v, w, i};\n        adj[u].push_back({v, {w, i}});\n        adj[v].push_back({u, {w, i}});\n    }\n    \n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    compute_bc();\n    \n    // Normalization of edge costs ensures numerical stability in SA\n    edge_cost.resize(M);\n    double max_c = 0;\n    for (int i = 0; i < M; ++i) {\n        edge_cost[i] = edge_bc[i] * (double)edges[i].w;\n        if(edge_cost[i] > max_c) max_c = edge_cost[i];\n    }\n    if(max_c > 0) {\n        for(int i=0; i<M; ++i) edge_cost[i] /= max_c;\n    }\n    \n    // Initial assignment using snake distribution\n    vector<int> edge_indices(M);\n    for (int i = 0; i < M; ++i) edge_indices[i] = i;\n    \n    sort(edge_indices.begin(), edge_indices.end(), [&](int a, int b) {\n        return edge_cost[a] > edge_cost[b];\n    });\n    \n    vector<int> schedule(M);\n    vector<vector<int>> days(D + 1);\n    vector<long double> sum_cost(D + 1, 0.0);\n    \n    for (int i = 0; i < M; ++i) {\n        int day = (i / D) % 2 == 0 ? (i % D) + 1 : D - (i % D);\n        schedule[edge_indices[i]] = day;\n        days[day].push_back(edge_indices[i]);\n        sum_cost[day] += edge_cost[edge_indices[i]];\n    }\n    \n    // Simulated Annealing\n    mt19937 rng(42);\n    double start_time = clock();\n    double time_limit = 5.8 * CLOCKS_PER_SEC;\n    \n    double T_start = 0.1;\n    double T_end = 0.00001;\n    \n    int iter = 0;\n    while (true) {\n        iter++;\n        if ((iter & 2047) == 0) {\n            if (clock() - start_time > time_limit) break;\n        }\n        \n        double progress = (clock() - start_time) / time_limit;\n        double T = T_start * pow(T_end / T_start, progress);\n        \n        int d1, d2;\n        // Periodic targeted greedy move to reduce variance efficiently\n        if (iter % 100 == 0) {\n            int d_max = 1, d_min = 1;\n            for(int d=1; d<=D; ++d) {\n                if(sum_cost[d] > sum_cost[d_max]) d_max = d;\n                if(sum_cost[d] < sum_cost[d_min]) d_min = d;\n            }\n            d1 = d_max; d2 = d_min;\n        } else {\n            d1 = (rng() % D) + 1;\n            d2 = (rng() % D) + 1;\n        }\n        \n        if (d1 == d2 || days[d1].empty() || days[d2].empty()) continue;\n        \n        int idx1 = rng() % days[d1].size();\n        int idx2 = rng() % days[d2].size();\n        \n        int e1 = days[d1][idx1];\n        int e2 = days[d2][idx2];\n        \n        long double dc1 = (long double)edge_cost[e2] - edge_cost[e1];\n        long double dc2 = (long double)edge_cost[e1] - edge_cost[e2];\n        \n        long double old_sq = sum_cost[d1] * sum_cost[d1] + sum_cost[d2] * sum_cost[d2];\n        long double n1 = sum_cost[d1] + dc1;\n        long double n2 = sum_cost[d2] + dc2;\n        long double new_sq = n1 * n1 + n2 * n2;\n        \n        double delta = (double)(new_sq - old_sq);\n        \n        // Metropolis-Hastings acceptance\n        if (delta < 0 || (exp(-delta / T) > (double)rng() / rng.max())) {\n            sum_cost[d1] = n1;\n            sum_cost[d2] = n2;\n            days[d1][idx1] = e2;\n            days[d2][idx2] = e1;\n            schedule[e1] = d2;\n            schedule[e2] = d1;\n        }\n    }\n    \n    for (int i = 0; i < M; ++i) {\n        cout << schedule[i] << (i == M - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n\nusing namespace std;\n\nstruct Point {\n    int x, y, z;\n};\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int D;\n    if (!(cin >> D)) return 0;\n\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for (int i = 0; i < D; ++i) cin >> f1[i];\n    for (int i = 0; i < D; ++i) cin >> r1[i];\n    for (int i = 0; i < D; ++i) cin >> f2[i];\n    for (int i = 0; i < D; ++i) cin >> r2[i];\n\n    // Compute maximum possible objects M1 and M2\n    auto get_max_obj = [&](const vector<string>& f, const vector<string>& r) {\n        vector<vector<vector<int>>> obj(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[z][x] == '1' && r[z][y] == '1') {\n                        obj[x][y][z] = 1;\n                    }\n                }\n            }\n        }\n        return obj;\n    };\n\n    auto M1 = get_max_obj(f1, r1);\n    auto M2 = get_max_obj(f2, r2);\n\n    // Compute intersection I, and unique parts U1, U2\n    vector<vector<vector<int>>> I(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> U1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> U2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n\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 (M1[x][y][z] && M2[x][y][z]) I[x][y][z] = 1;\n                else if (M1[x][y][z]) U1[x][y][z] = 1;\n                else if (M2[x][y][z]) U2[x][y][z] = 1;\n            }\n        }\n    }\n\n    vector<vector<vector<int>>> b1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> b2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n\n    int block_id = 1;\n\n    // BFS to find connected components and assign unique block IDs\n    auto find_components = [&](vector<vector<vector<int>>>& grid, int& id_counter, vector<vector<vector<int>>>& b_map) {\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\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 (grid[x][y][z] && !visited[x][y][z]) {\n                        queue<Point> q;\n                        q.push({x, y, z});\n                        visited[x][y][z] = true;\n                        b_map[x][y][z] = id_counter;\n                        \n                        int dx[] = {1, -1, 0, 0, 0, 0};\n                        int dy[] = {0, 0, 1, -1, 0, 0};\n                        int dz[] = {0, 0, 0, 0, 1, -1};\n                        \n                        while (!q.empty()) {\n                            Point curr = q.front();\n                            q.pop();\n\n                            for (int i = 0; i < 6; ++i) {\n                                int nx = curr.x + dx[i];\n                                int ny = curr.y + dy[i];\n                                int nz = curr.z + dz[i];\n                                if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                    grid[nx][ny][nz] && !visited[nx][ny][nz]) {\n                                    visited[nx][ny][nz] = true;\n                                    b_map[nx][ny][nz] = id_counter;\n                                    q.push({nx, ny, nz});\n                                }\n                            }\n                        }\n                        id_counter++;\n                    }\n                }\n            }\n        }\n    };\n\n    // 1. Process intersection (shared)\n    find_components(I, block_id, b1);\n    for(int x=0; x<D; ++x) for(int y=0; y<D; ++y) for(int z=0; z<D; ++z) b2[x][y][z] = b1[x][y][z];\n    \n    // 2. Process unique parts for object 1\n    find_components(U1, block_id, b1);\n    // 3. Process unique parts for object 2\n    find_components(U2, block_id, b2);\n\n    // Output result\n    cout << block_id - 1 << endl;\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 << b1[x][y][z] << (x == D - 1 && y == D - 1 && z == D - 1 ? \"\" : \" \");\n            }\n        }\n    }\n    cout << endl;\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 << b2[x][y][z] << (x == D - 1 && y == D - 1 && z == D - 1 ? \"\" : \" \");\n            }\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <queue>\n#include <ctime>\n#include <random>\n#include <numeric>\n\nusing namespace std;\n\nstruct Edge { int u, v, w, id; };\nstruct Point { int x, y; };\n\nint N, M, K;\nvector<Point> stations;\nvector<Point> residents;\nvector<Edge> edges;\nvector<vector<pair<int, int>>> adj;\nvector<vector<pair<double, int>>> sorted_stations;\nvector<vector<int>> path_to_root;\nvector<bool> active;\nvector<int> P;\nvector<int> edge_usage;\nlong long total_edge_cost = 0;\nlong long total_radio_cost = 0;\n\n// Reusable buffers to avoid allocation overhead\nvector<int> next_P;\nvector<int> next_edge_usage;\n\nvoid build_mst() {\n    vector<int> min_weight(N + 1, 2e9);\n    vector<bool> visited(N + 1, false);\n    vector<int> parent_node(N + 1, -1);\n    vector<int> parent_edge_idx(N + 1, -1);\n    min_weight[1] = 0;\n    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n    pq.push({0, 1});\n    while (!pq.empty()) {\n        int u = pq.top().second;\n        pq.pop();\n        if (visited[u]) continue;\n        visited[u] = true;\n        for (auto& edge : adj[u]) {\n            int v = edge.first, idx = edge.second;\n            if (!visited[v] && edges[idx].w < min_weight[v]) {\n                min_weight[v] = edges[idx].w;\n                parent_node[v] = u;\n                parent_edge_idx[v] = idx;\n                pq.push({min_weight[v], v});\n            }\n        }\n    }\n    path_to_root.resize(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        int curr = i;\n        while (parent_node[curr] != -1) {\n            path_to_root[i].push_back(parent_edge_idx[curr]);\n            curr = parent_node[curr];\n        }\n    }\n}\n\n// Attempts to toggle a station status with Simulated Annealing acceptance\nlong long try_toggle(int u, double T, mt19937& rng) {\n    if (u == 1) return -1;\n    \n    active[u] = !active[u];\n    \n    // Check coverage and find best stations\n    bool possible = true;\n    fill(next_P.begin(), next_P.end(), 0);\n    \n    for (int k = 0; k < K; ++k) {\n        int r = 0;\n        // Find best active station for resident k\n        while (r < N && !active[sorted_stations[k][r].second]) r++;\n        \n        if (r == N || sorted_stations[k][r].first > 5000.0) {\n            possible = false; \n            break;\n        }\n        \n        int s = sorted_stations[k][r].second;\n        int d = (int)ceil(sorted_stations[k][r].first);\n        if (d > next_P[s]) next_P[s] = d;\n    }\n    \n    if (!possible) {\n        active[u] = !active[u]; \n        return -1;\n    }\n    \n    // Calculate new costs\n    fill(next_edge_usage.begin(), next_edge_usage.end(), 0);\n    long long next_edge_cost = 0;\n    \n    for (int i = 1; i <= N; ++i) {\n        if (active[i]) {\n            for (int e : path_to_root[i]) {\n                if (next_edge_usage[e] == 0) next_edge_cost += edges[e].w;\n                next_edge_usage[e]++;\n            }\n        }\n    }\n    \n    long long next_radio_cost = 0;\n    for (int i = 1; i <= N; ++i) next_radio_cost += (long long)next_P[i] * next_P[i];\n    \n    long long new_cost = next_radio_cost + next_edge_cost;\n    long long old_cost = total_radio_cost + total_edge_cost;\n    \n    // Accept logic (SA)\n    if (new_cost < old_cost || (T > 1e-9 && exp((double)(old_cost - new_cost) / T) > (double)rng() / rng.max())) {\n        total_radio_cost = next_radio_cost;\n        total_edge_cost = next_edge_cost;\n        P = next_P;\n        edge_usage = next_edge_usage;\n        return new_cost;\n    } else {\n        active[u] = !active[u];\n        return -1;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n    cin >> N >> M >> K;\n    stations.resize(N + 1);\n    for (int i = 1; i <= N; ++i) cin >> stations[i].x >> stations[i].y;\n    adj.resize(N + 1); edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w; cin >> u >> v >> w;\n        edges[i] = {u, v, w, i};\n        adj[u].push_back({v, i});\n        adj[v].push_back({u, i});\n    }\n    residents.resize(K);\n    for (int k = 0; k < K; ++k) cin >> residents[k].x >> residents[k].y;\n    \n    sorted_stations.resize(K);\n    for (int k = 0; k < K; ++k) {\n        for (int i = 1; i <= N; ++i) {\n            double d = sqrt(pow(stations[i].x - residents[k].x, 2) + pow(stations[i].y - residents[k].y, 2));\n            sorted_stations[k].push_back({d, i});\n        }\n        sort(sorted_stations[k].begin(), sorted_stations[k].end());\n    }\n    \n    build_mst();\n    \n    next_P.resize(N + 1);\n    next_edge_usage.resize(M);\n    \n    vector<int> best_P(N + 1, 0);\n    vector<int> best_edge_usage(M, 0);\n    long long best_total_cost = 4e18;\n    \n    mt19937 rng(1337);\n    clock_t start = clock();\n    \n    while ((double)(clock() - start) / CLOCKS_PER_SEC < 1.8) {\n        active.assign(N + 1, true); \n        P.assign(N + 1, 0);\n        edge_usage.assign(M, 0);\n        total_edge_cost = 0;\n        total_radio_cost = 0;\n        \n        for (int k = 0; k < K; ++k) P[sorted_stations[k][0].second] = max(P[sorted_stations[k][0].second], (int)ceil(sorted_stations[k][0].first));\n        for (int i = 1; i <= N; ++i) {\n            total_radio_cost += (long long)P[i] * P[i];\n            for (int e : path_to_root[i]) {\n                if (edge_usage[e] == 0) total_edge_cost += edges[e].w;\n                edge_usage[e]++;\n            }\n        }\n        \n        double T_start = 1e7, T_end = 1e2;\n        int iterations = 1000;\n        for (int iter = 0; iter < iterations; ++iter) {\n            double T = T_start * pow(T_end / T_start, (double)iter / iterations);\n            int u = (rng() % (N - 1)) + 2;\n            long long new_cost = try_toggle(u, T, rng);\n            if (new_cost != -1 && new_cost < best_total_cost) {\n                best_total_cost = new_cost;\n                best_P = P;\n                best_edge_usage = edge_usage;\n            }\n        }\n    }\n    \n    for (int i = 1; i <= N; ++i) cout << best_P[i] << (i == N ? \"\" : \" \");\n    cout << endl;\n    for (int i = 0; i < M; ++i) cout << (best_edge_usage[i] > 0 ? 1 : 0) << (i == M - 1 ? \"\" : \" \");\n    cout << endl;\n    \n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <chrono>\n#include <cstring>\n#include <cmath>\n\nusing namespace std;\n\n// The number of pyramid tiers is fixed to N=30.\nconstexpr int N = 30;\nint initial_board[N][N];\nint current_board[N][N];\n\nstruct SwapOp {\n    int x1, y1, x2, y2;\n    // Canonical representation for redundancy check\n    bool operator==(const SwapOp& other) const {\n        int p1 = (x1 * 30 + y1);\n        int p2 = (x2 * 30 + y2);\n        if (p1 > p2) swap(p1, p2);\n        int o1 = (other.x1 * 30 + other.y1);\n        int o2 = (other.x2 * 30 + other.y2);\n        if (o1 > o2) swap(o1, o2);\n        return p1 == o1 && p2 == o2;\n    }\n};\n\ninline void perform_swap(int x1, int y1, int x2, int y2, vector<SwapOp>& ops) {\n    swap(current_board[x1][y1], current_board[x2][y2]);\n    ops.push_back({x1, y1, x2, y2});\n}\n\n// Build heap using specific node processing permutations for each tier\nint build_heap_with_perms(const vector<vector<int>>& perms, vector<SwapOp>& ops) {\n    memcpy(current_board, initial_board, sizeof(initial_board));\n    ops.clear();\n    \n    // Bottom-up Build-Heap: N-2 down to 0\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y : perms[x]) {\n            int cur_x = x;\n            int cur_y = y;\n            while (cur_x < N - 1) {\n                int l_x = cur_x + 1;\n                int l_y = cur_y;\n                int r_x = cur_x + 1;\n                int r_y = cur_y + 1;\n                \n                int next_x = l_x;\n                int next_y = l_y;\n                // Min-heap: swap with the smaller child\n                if (current_board[r_x][r_y] < current_board[l_x][l_y]) {\n                    next_x = r_x;\n                    next_y = r_y;\n                }\n                \n                if (current_board[cur_x][cur_y] > current_board[next_x][next_y]) {\n                    perform_swap(cur_x, cur_y, next_x, next_y, ops);\n                    cur_x = next_x;\n                    cur_y = next_y;\n                } else {\n                    break;\n                }\n            }\n        }\n    }\n    \n    // Post-process: remove redundant consecutive swaps\n    if (ops.size() > 1) {\n        vector<SwapOp> cleaned_ops;\n        cleaned_ops.reserve(ops.size());\n        for (const auto& op : ops) {\n            if (!cleaned_ops.empty() && cleaned_ops.back() == op) {\n                cleaned_ops.pop_back();\n            } else {\n                cleaned_ops.push_back(op);\n            }\n        }\n        ops = std::move(cleaned_ops);\n    }\n    return ops.size();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j <= i; ++j) {\n            cin >> initial_board[i][j];\n        }\n    }\n\n    vector<vector<int>> current_perms(N);\n    for (int i = 0; i < N; ++i) {\n        current_perms[i].resize(i + 1);\n        iota(current_perms[i].begin(), current_perms[i].end(), 0);\n    }\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    vector<SwapOp> current_ops, best_ops;\n    int current_K = build_heap_with_perms(current_perms, current_ops);\n    int best_K = current_K;\n    best_ops = current_ops;\n\n    auto start_time = chrono::steady_clock::now();\n    int iterations = 0;\n    \n    double temp = 100.0;\n    double cooling_rate = 0.99995; \n\n    // Simulated Annealing\n    while (true) {\n        iterations++;\n        // Periodic time check (every 256 iterations)\n        if ((iterations & 255) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1900) break;\n        }\n\n        // Mutation: pick a tier uniformly and swap two elements\n        int tier = rng() % (N - 1); \n        int sz = tier + 1;\n        int idx1 = rng() % sz;\n        int idx2 = rng() % sz;\n        \n        swap(current_perms[tier][idx1], current_perms[tier][idx2]);\n        \n        vector<SwapOp> next_ops;\n        int next_K = build_heap_with_perms(current_perms, next_ops);\n        \n        int delta = next_K - current_K;\n        \n        // Metropolis acceptance criterion\n        if (delta <= 0 || (exp(-delta / temp) > (double)rng() / mt19937::max())) {\n            current_K = next_K;\n            current_ops = next_ops;\n            if (current_K < best_K) {\n                best_K = current_K;\n                best_ops = current_ops;\n            }\n        } else {\n            // Revert mutation\n            swap(current_perms[tier][idx1], current_perms[tier][idx2]);\n        }\n        \n        // Adaptive cooling and restart mechanism\n        temp *= cooling_rate;\n        if (temp < 0.05) {\n            temp = 100.0; // Reset temperature\n            // Full random restart\n            for (int i = 0; i < N; ++i) {\n                shuffle(current_perms[i].begin(), current_perms[i].end(), rng);\n            }\n            current_K = build_heap_with_perms(current_perms, current_ops);\n        }\n    }\n\n    cout << best_ops.size() << \"\\n\";\n    for (const auto& op : best_ops) {\n        cout << op.x1 << \" \" << op.y1 << \" \" << op.x2 << \" \" << op.y2 << \"\\n\";\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\n// Grid size D is 9, but using variables for generality.\nint D;\nint grid[10][10];\nint dist_map[10][10];\nbool is_removed[100];\nstruct Point { int r, c; };\nPoint pos[100];\n\nint dr[] = {0, 0, 1, -1};\nint dc[] = {1, -1, 0, 0};\n\n// Precompute BFS distance from the entrance (0, (D-1)/2) on an empty grid.\nvoid precompute_dist() {\n    for (int i = 0; i < D; ++i)\n        for (int j = 0; j < D; ++j)\n            dist_map[i][j] = 1000;\n    \n    int er = 0;\n    int ec = (D - 1) / 2;\n    queue<pair<int, int>> q;\n    q.push({er, ec});\n    dist_map[er][ec] = 0;\n    \n    while(!q.empty()){\n        pair<int, int> curr = q.front();\n        q.pop();\n        \n        for(int i=0; i<4; ++i){\n            int nr = curr.first + dr[i];\n            int nc = curr.second + dc[i];\n            if(nr >= 0 && nr < D && nc >= 0 && nc < D && dist_map[nr][nc] == 1000){\n                if(grid[nr][nc] != -2) {\n                    dist_map[nr][nc] = dist_map[curr.first][curr.second] + 1;\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n}\n\n// Find all currently reachable empty squares.\nvector<Point> get_reachable_empty() {\n    vector<Point> reachable;\n    bool visited[10][10] = {false};\n    queue<pair<int, int>> q;\n    \n    int er = 0;\n    int ec = (D - 1) / 2;\n    q.push({er, ec});\n    visited[er][ec] = true;\n    \n    while(!q.empty()){\n        pair<int, int> curr = q.front();\n        q.pop();\n        \n        for(int i=0; i<4; ++i){\n            int nr = curr.first + dr[i];\n            int nc = curr.second + dc[i];\n            if(nr >= 0 && nr < D && nc >= 0 && nc < D && !visited[nr][nc]){\n                // Only consider empty squares (-1).\n                if(grid[nr][nc] == -1){ \n                    visited[nr][nc] = true;\n                    reachable.push_back({nr, nc});\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n    return reachable;\n}\n\n// Check if a specific container is currently reachable from the entrance.\nbool is_container_reachable(int tr, int tc) {\n    bool visited[10][10] = {false};\n    queue<pair<int, int>> q;\n    \n    int er = 0;\n    int ec = (D - 1) / 2;\n    q.push({er, ec});\n    visited[er][ec] = true;\n    \n    while(!q.empty()){\n        pair<int, int> curr = q.front();\n        q.pop();\n        \n        if(curr.first == tr && curr.second == tc) return true;\n        \n        for(int i=0; i<4; ++i){\n            int nr = curr.first + dr[i];\n            int nc = curr.second + dc[i];\n            if(nr >= 0 && nr < D && nc >= 0 && nc < D && !visited[nr][nc]){\n                // Passable if empty (-1) or the target container itself.\n                if(grid[nr][nc] == -1 || (nr == tr && nc == tc)){\n                    visited[nr][nc] = true;\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n    return false;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int N;\n    if (!(cin >> D >> N)) return 0;\n    \n    for(int i=0; i<D; ++i)\n        for(int j=0; j<D; ++j)\n            grid[i][j] = -1;\n            \n    // Mark entrance as occupied so we don't store there.\n    grid[0][(D-1)/2] = -3;\n    \n    for(int i=0; i<N; ++i){\n        int r, c;\n        cin >> r >> c;\n        grid[r][c] = -2;\n    }\n    \n    precompute_dist();\n    int K = D * D - 1 - N;\n    \n    // Storage Phase\n    for(int d=0; d<K; ++d){\n        int t;\n        cin >> t;\n        \n        vector<Point> reachable = get_reachable_empty();\n        \n        // Farthest reachable square first to maintain entrance connectivity\n        Point best = reachable[0];\n        int max_dist = -1;\n        for(auto p : reachable){\n            if(dist_map[p.r][p.c] > max_dist){\n                max_dist = dist_map[p.r][p.c];\n                best = p;\n            }\n        }\n        \n        grid[best.r][best.c] = t;\n        pos[t] = best;\n        cout << best.r << \" \" << best.c << endl;\n    }\n    \n    // Retrieval Phase\n    int target = 0;\n    int removed_cnt = 0;\n    for(int i=0; i<100; ++i) is_removed[i] = false;\n    \n    while(removed_cnt < K){\n        if(is_removed[target]){\n            target++;\n            continue;\n        }\n        \n        if(is_container_reachable(pos[target].r, pos[target].c)){\n            cout << pos[target].r << \" \" << pos[target].c << endl;\n            grid[pos[target].r][pos[target].c] = -1;\n            is_removed[target] = true;\n            removed_cnt++;\n        } else {\n            // Find reachable blocker with the largest label (Greedy for inversion minimization)\n            int best_label = -1;\n            pair<int, int> best_pos = {-1, -1};\n            \n            for(int r=0; r<D; ++r){\n                for(int c=0; c<D; ++c){\n                    if(grid[r][c] >= 0){\n                        if(is_container_reachable(r, c)){\n                            if(grid[r][c] > best_label){\n                                best_label = grid[r][c];\n                                best_pos = {r, c};\n                            }\n                        }\n                    }\n                }\n            }\n            \n            if(best_pos.first != -1){\n                cout << best_pos.first << \" \" << best_pos.second << endl;\n                grid[best_pos.first][best_pos.second] = -1;\n                is_removed[best_label] = true;\n                removed_cnt++;\n            } else {\n                break;\n            }\n        }\n    }\n    \n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <chrono>\n#include <random>\n\nusing namespace std;\n\nconst int MAX_N = 50;\nint N, M;\nint grid[MAX_N][MAX_N];\nbool target_adj[101][101]; // Required adjacencies\nint count_adj[101][101];   // Current adjacencies\nint n_cells[101];\n\nint dr[] = {0, 0, 1, -1};\nint dc[] = {1, -1, 0, 0};\n\nint vis[MAX_N][MAX_N];\nint vis_gen = 0;\n\n// DFS to check connectivity of a color\nbool is_connected(int c) {\n    if (n_cells[c] <= 1) return true;\n    \n    vis_gen++;\n    \n    int start_r = -1, start_c = -1;\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            if(grid[i][j] == c) {\n                start_r = i; start_c = j; break;\n            }\n        }\n        if(start_r != -1) break;\n    }\n    if(start_r == -1) return true; \n\n    // Using a simple static array stack for DFS\n    static pair<int, int> st[MAX_N * MAX_N];\n    int top = 0;\n    st[top++] = {start_r, start_c};\n    vis[start_r][start_c] = vis_gen;\n\n    int visited = 0;\n    while(top > 0){\n        pair<int, int> curr = st[--top];\n        visited++;\n\n        for(int i=0; i<4; ++i) {\n            int nr = curr.first + dr[i];\n            int nc = curr.second + dc[i];\n            if(nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] == c && vis[nr][nc] != vis_gen){\n                vis[nr][nc] = vis_gen;\n                st[top++] = {nr, nc};\n            }\n        }\n    }\n    return visited == n_cells[c];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M;\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            cin >> grid[i][j];\n            n_cells[grid[i][j]]++;\n        }\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 + dr[k];\n                int nj = j + dc[k];\n                int nc;\n                if(ni < 0 || ni >= N || nj < 0 || nj >= N) nc = 0;\n                else nc = grid[ni][nj];\n                \n                if(grid[i][j] != nc) {\n                    count_adj[grid[i][j]][nc]++;\n                }\n            }\n        }\n    }\n\n    for(int i=0; i<=M; ++i) {\n        for(int j=0; j<=M; ++j) {\n            if (count_adj[i][j] > 0) target_adj[i][j] = true;\n        }\n    }\n\n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    \n    while(true) {\n        auto current_time = chrono::steady_clock::now();\n        if(chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count() > 1800) break;\n        \n        int r = rng() % N;\n        int c = rng() % N;\n        int old_c = grid[r][c];\n        if (old_c == 0) continue; \n        \n        vector<int> candidates = {0};\n        for(int k=0; k<4; ++k) {\n            int nr = r + dr[k];\n            int nc = c + dc[k];\n            if(nr >= 0 && nr < N && nc >= 0 && nc < N) {\n                candidates.push_back(grid[nr][nc]);\n            }\n        }\n        \n        shuffle(candidates.begin(), candidates.end(), rng);\n        \n        for(int new_c : candidates) {\n            if (new_c == old_c) continue;\n            \n            struct PairDelta { int u, v, d; };\n            PairDelta diffs[8]; \n            int num_diffs = 0;\n\n            for(int k=0; k<4; ++k) {\n                int nr = r + dr[k];\n                int nc = c + dc[k];\n                int neighbor_c = (nr < 0 || nr >= N || nc < 0 || nc >= N) ? 0 : grid[nr][nc];\n                \n                if (old_c != neighbor_c) {\n                    int u = min(old_c, neighbor_c);\n                    int v = max(old_c, neighbor_c);\n                    bool found = false;\n                    for(int i=0; i<num_diffs; ++i) if(diffs[i].u == u && diffs[i].v == v) { diffs[i].d--; found=true; break; }\n                    if(!found) diffs[num_diffs++] = {u, v, -1};\n                }\n                if (new_c != neighbor_c) {\n                    int u = min(new_c, neighbor_c);\n                    int v = max(new_c, neighbor_c);\n                    bool found = false;\n                    for(int i=0; i<num_diffs; ++i) if(diffs[i].u == u && diffs[i].v == v) { diffs[i].d++; found=true; break; }\n                    if(!found) diffs[num_diffs++] = {u, v, 1};\n                }\n            }\n            \n            bool adj_ok = true;\n            for(int i=0; i<num_diffs; ++i) {\n                int new_count = count_adj[diffs[i].u][diffs[i].v] + diffs[i].d;\n                if (target_adj[diffs[i].u][diffs[i].v] && new_count == 0) { adj_ok = false; break; }\n                if (!target_adj[diffs[i].u][diffs[i].v] && new_count > 0) { adj_ok = false; break; }\n            }\n            if (!adj_ok) continue;\n            \n            grid[r][c] = new_c;\n            n_cells[old_c]--;\n            n_cells[new_c]++;\n            \n            if (!is_connected(old_c)) {\n                grid[r][c] = old_c;\n                n_cells[old_c]++;\n                n_cells[new_c]--;\n            } else {\n                for(int i=0; i<num_diffs; ++i) {\n                    count_adj[diffs[i].u][diffs[i].v] += diffs[i].d;\n                    count_adj[diffs[i].v][diffs[i].u] += diffs[i].d;\n                }\n                break;\n            }\n        }\n    }\n\n    for(int i=0; i<N; ++i) {\n        for(int j=0; j<N; ++j) {\n            cout << grid[i][j] << (j == N-1 ? \"\" : \" \");\n        }\n        cout << \"\\n\";\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <string>\n#include <numeric>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <iomanip>\n#include <chrono>\n\nusing namespace std;\n\nstruct Solver {\n    int N, D, Q;\n    vector<double> weights;\n    mt19937 rng;\n\n    Solver() : rng(1337) {}\n\n    // Efficient random selection\n    inline int get_rand(int n) {\n        return (int)(rng() % (unsigned int)n);\n    }\n\n    // Optimized query selection with dynamic size reduction\n    pair<vector<int>, vector<int>> select_query(int q) {\n        double min_diff = 1e18;\n        int best_nL = 0, best_nR = 0, best_start = 0;\n        int candidates = 30; // Balanced candidates for quality vs speed\n        \n        static vector<int> all_items(100);\n        if(all_items.size() != (size_t)N) {\n            all_items.resize(N);\n            iota(all_items.begin(), all_items.end(), 0);\n        }\n\n        shuffle(all_items.begin(), all_items.end(), rng);\n\n        // Gradually reduce max query set size as queries progress\n        int max_q_size = max(2, (int)(N / 2 * (1.0 - 0.5 * (double)q / Q)));\n        \n        for(int k = 0; k < candidates; ++k) {\n            int nL = 1 + get_rand(max_q_size);\n            int nR = 1 + get_rand(max_q_size);\n            int start = get_rand(N - nL - nR + 1);\n            \n            double sumL = 0;\n            for(int i = 0; i < nL; ++i) sumL += weights[all_items[start + i]];\n            double sumR = 0;\n            for(int i = 0; i < nR; ++i) sumR += weights[all_items[start + nL + i]];\n            \n            double diff = abs(sumL - sumR);\n            if(diff < min_diff) {\n                min_diff = diff;\n                best_nL = nL;\n                best_nR = nR;\n                best_start = start;\n            }\n        }\n        \n        vector<int> L(all_items.begin() + best_start, all_items.begin() + best_start + best_nL);\n        vector<int> R(all_items.begin() + best_start + best_nL, all_items.begin() + best_start + best_nL + best_nR);\n        return {L, R};\n    }\n\n    void solve() {\n        if (!(cin >> N >> D >> Q)) return;\n        weights.assign(N, 1000.0);\n\n        for (int q = 0; q < Q; ++q) {\n            auto [L, R] = select_query(q);\n            \n            cout << L.size() << \" \" << R.size();\n            for (int i : L) cout << \" \" << i;\n            for (int i : R) cout << \" \" << i;\n            cout << endl;\n            \n            string res;\n            cin >> res;\n            \n            double sumL = 0;\n            for (int i : L) sumL += weights[i];\n            double sumR = 0;\n            for (int i : R) sumR += weights[i];\n            \n            double diff = (res == \"<\") ? (sumR - sumL) : ((res == \">\") ? (sumL - sumR) : 0);\n            \n            double alpha = 0.3 * (1.0 - 0.85 * (double)q / Q);\n            for (int i : L) weights[i] += alpha * diff / L.size();\n            for (int i : R) weights[i] -= alpha * diff / R.size();\n            \n            for (double& w : weights) w = max(1.0, w);\n        }\n        \n        // Initial Assignment (LPT)\n        vector<int> assignment(N);\n        vector<double> bucket_weights(D, 0.0);\n        vector<vector<int>> bucket_items(D);\n        vector<int> item_pos_in_bucket(N); \n        \n        vector<int> sorted_items(N);\n        iota(sorted_items.begin(), sorted_items.end(), 0);\n        sort(sorted_items.begin(), sorted_items.end(), [&](int a, int b) {\n            return weights[a] > weights[b];\n        });\n        \n        for (int i : sorted_items) {\n            int best_bucket = 0;\n            for (int d = 1; d < D; ++d) {\n                if (bucket_weights[d] < bucket_weights[best_bucket]) best_bucket = d;\n            }\n            assignment[i] = best_bucket;\n            bucket_weights[best_bucket] += weights[i];\n            item_pos_in_bucket[i] = (int)bucket_items[best_bucket].size();\n            bucket_items[best_bucket].push_back(i);\n        }\n        \n        // Simulated Annealing\n        auto start_time = chrono::steady_clock::now();\n        double T_start = 100.0;\n        double T_end = 0.01;\n        double temp = T_start;\n        \n        for(int iter = 0; ; ++iter) {\n            if ((iter & 8191) == 0) {\n                auto now = chrono::steady_clock::now();\n                if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 1850) break;\n                \n                double progress = min(1.0, (double)iter / 1000000.0); \n                temp = T_start * pow(T_end / T_start, progress);\n            }\n            \n            int b1, b2;\n            // Adaptive Targeted SA\n            double target_prob = 0.05 + 0.9 * (1.0 - temp / T_start);\n            if ((double)(rng() % 1000) / 1000.0 < target_prob) {\n                int max_idx = 0, min_idx = 0;\n                for (int d = 1; d < D; ++d) {\n                    if (bucket_weights[d] > bucket_weights[max_idx]) max_idx = d;\n                    if (bucket_weights[d] < bucket_weights[min_idx]) min_idx = d;\n                }\n                b1 = max_idx;\n                b2 = min_idx;\n            } else {\n                b1 = get_rand(D);\n                b2 = get_rand(D);\n            }\n            \n            if (b1 == b2 || bucket_items[b1].empty()) continue;\n            \n            // Swap (60%) vs Move (40%)\n            int op = (get_rand(10) < 6) ? 0 : 1; \n            \n            if (op == 0) { // swap\n                if (bucket_items[b2].empty()) continue;\n                int i1 = bucket_items[b1][get_rand((int)bucket_items[b1].size())];\n                int i2 = bucket_items[b2][get_rand((int)bucket_items[b2].size())];\n                \n                double new_bw1 = bucket_weights[b1] - weights[i1] + weights[i2];\n                double new_bw2 = bucket_weights[b2] - weights[i2] + weights[i1];\n                \n                double delta = (new_bw1*new_bw1 + new_bw2*new_bw2) - (bucket_weights[b1]*bucket_weights[b1] + bucket_weights[b2]*bucket_weights[b2]);\n                \n                if (delta < 0 || exp(-delta / temp) > (double)rng() / 4294967295.0) {\n                    assignment[i1] = b2; assignment[i2] = b1;\n                    bucket_weights[b1] = new_bw1; bucket_weights[b2] = new_bw2;\n                    \n                    int pos1 = item_pos_in_bucket[i1], last1 = bucket_items[b1].back();\n                    bucket_items[b1][pos1] = last1; item_pos_in_bucket[last1] = pos1; bucket_items[b1].pop_back();\n                    int pos2 = item_pos_in_bucket[i2], last2 = bucket_items[b2].back();\n                    bucket_items[b2][pos2] = last2; item_pos_in_bucket[last2] = pos2; bucket_items[b2].pop_back();\n                    item_pos_in_bucket[i1] = (int)bucket_items[b2].size(); bucket_items[b2].push_back(i1);\n                    item_pos_in_bucket[i2] = (int)bucket_items[b1].size(); bucket_items[b1].push_back(i2);\n                }\n            } else { // move\n                int i1 = bucket_items[b1][get_rand((int)bucket_items[b1].size())];\n                \n                double new_bw1 = bucket_weights[b1] - weights[i1];\n                double new_bw2 = bucket_weights[b2] + weights[i1];\n                \n                double delta = (new_bw1*new_bw1 + new_bw2*new_bw2) - (bucket_weights[b1]*bucket_weights[b1] + bucket_weights[b2]*bucket_weights[b2]);\n                \n                if (delta < 0 || exp(-delta / temp) > (double)rng() / 4294967295.0) {\n                    assignment[i1] = b2;\n                    bucket_weights[b1] = new_bw1; bucket_weights[b2] = new_bw2;\n                    \n                    int pos1 = item_pos_in_bucket[i1], last1 = bucket_items[b1].back();\n                    bucket_items[b1][pos1] = last1; item_pos_in_bucket[last1] = pos1; bucket_items[b1].pop_back();\n                    item_pos_in_bucket[i1] = (int)bucket_items[b2].size(); bucket_items[b2].push_back(i1);\n                }\n            }\n        }\n        \n        for (int i = 0; i < N; ++i) cout << assignment[i] << (i == N - 1 ? \"\" : \" \");\n        cout << endl;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    Solver s;\n    s.solve();\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\n// Global Configuration\nint N, M;\nvector<vector<int>> stacks;\nvector<int> box_to_stack;\nvector<int> box_to_pos;\n\n// Find the stack containing a specific target box\nint find_stack(int target) {\n    return box_to_stack[target];\n}\n\n// Calculate the score for a potential destination stack d.\n// The goal is to maximize this score.\nlong long get_stack_score(int d, int target, int b_new_bot) {\n    // 1. Empty stacks are the best destinations\n    if (stacks[d].empty()) return 1e16;\n\n    long long score = 0;\n    \n    // 2. Heavy penalty for burying immediate next targets (target+1, target+2).\n    // These boxes are needed very soon, so burying them is very costly.\n    if (target + 1 <= N && box_to_stack[target + 1] == d) score -= 1e15;\n    if (target + 2 <= N && box_to_stack[target + 2] == d) score -= 1e14;\n    \n    // 3. Continuous urgency penalty based on the min_box in the stack.\n    // The min_box defines the \"deadline\" for this stack.\n    int min_box = 1000000;\n    for (int b : stacks[d]) min_box = min(min_box, b);\n    \n    // Penalty is weighted by (1 / (min_box - target)).\n    // Small min_box (urgent) -> large penalty.\n    if (min_box > target) {\n        score -= 1e12 / (min_box - target);\n    }\n    \n    // 4. Sorting bonus:\n    // Maintaining a descending sequence is good.\n    // If the top of the destination stack is larger than the new bottom box, that's good\n    // (it maintains a descending sequence).\n    if (!stacks[d].empty() && stacks[d].back() > b_new_bot) {\n        score += 1e10;\n    }\n    \n    // 5. Size penalty to keep stacks balanced and minimize movement cost.\n    score -= (long long)stacks[d].size() * 1e5;\n    \n    return score;\n}\n\n// Find the best destination stack for moving blocks of boxes.\nint find_best_dest(int s, int target, int b_new_bot) {\n    int best_d = -1;\n    long long max_score = -2e18; // Use a very small number for initialization\n\n    for (int d = 0; d < M; ++d) {\n        if (d == s) continue; // Cannot move to the current stack\n\n        long long score = get_stack_score(d, target, b_new_bot);\n        if (score > max_score) {\n            max_score = score;\n            best_d = d;\n        }\n    }\n    return best_d;\n}\n\n// Move the block of boxes above the target box to another stack d\nvoid move_block(int s, int pos, int d) {\n    int block_start_idx = pos + 1;\n    \n    // Update stack_ids and positions for the moved boxes\n    for (int i = block_start_idx; i < (int)stacks[s].size(); ++i) {\n        int b = stacks[s][i];\n        stacks[d].push_back(b);\n        box_to_stack[b] = d;\n        box_to_pos[b] = (int)stacks[d].size() - 1;\n    }\n    \n    // Remove the moved boxes from the original stack\n    stacks[s].erase(stacks[s].begin() + block_start_idx, stacks[s].end());\n}\n\nint main() {\n    // Optimize I/O\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M)) return 0;\n    \n    stacks.resize(M);\n    box_to_stack.resize(N + 1);\n    box_to_pos.resize(N + 1);\n\n    // Read the initial stack configuration\n    for (int i = 0; i < M; ++i) {\n        for (int j = 0; j < N / M; ++j) {\n            int b;\n            cin >> b;\n            stacks[i].push_back(b);\n            box_to_stack[b] = i;\n            box_to_pos[b] = (int)stacks[i].size() - 1;\n        }\n    }\n\n    int target = 1;\n    int ops = 0;\n    \n    // Process until all boxes are removed\n    while (target <= N && ops < 5000) {\n        int s = find_stack(target);\n        int pos = box_to_pos[target];\n        \n        // If target is at the top of its stack, remove it\n        if (pos == (int)stacks[s].size() - 1) {\n            cout << target << \" 0\" << endl;\n            stacks[s].pop_back();\n            target++;\n            ops++;\n        } else {\n            // Need to move the block above the target\n            int b_new_bot = stacks[s][pos + 1];\n            int d = find_best_dest(s, target, b_new_bot);\n            \n            // Output the move operation (v, i+1)\n            cout << b_new_bot << \" \" << (d + 1) << endl;\n            \n            // Perform the move\n            move_block(s, pos, d);\n            ops++;\n        }\n    }\n\n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <queue>\n#include <ctime>\n\nusing namespace std;\n\n// Helper to map 2D coordinates to 1D\ninline int id(int r, int c, int N) {\n    return r * N + c;\n}\n\n// Helper to map 1D index to 2D coordinates\ninline pair<int, int> pos(int idx, int N) {\n    return {idx / N, idx % N};\n}\n\n// Global variables for faster access\nint N;\nvector<int> d_flat;\nvector<vector<int>> adj;\n\n// Cost function: sum(d_v / visits_v)\n// For the root, the number of visits is deg[root] + 1.\ninline double get_node_cost(int u, const vector<int>& deg) {\n    int visits = (u == 0 ? deg[u] + 1 : deg[u]);\n    return (double)d_flat[u] / visits;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N;\n    vector<string> h(N - 1), v(N);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    for (int i = 0; i < N; ++i) cin >> v[i];\n    d_flat.resize(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int d;\n            cin >> d;\n            d_flat[id(i, j, N)] = d;\n        }\n    }\n\n    adj.resize(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (i + 1 < N && h[i][j] == '0') {\n                adj[id(i, j, N)].push_back(id(i + 1, j, N));\n                adj[id(i + 1, j, N)].push_back(id(i, j, N));\n            }\n            if (j + 1 < N && v[i][j] == '0') {\n                adj[id(i, j, N)].push_back(id(i, j, N) + 1);\n                adj[id(i, j, N) + 1].push_back(id(i, j, N));\n            }\n        }\n    }\n\n    mt19937 rng(1337);\n    \n    // Randomized Prim's to find a good initial tree\n    auto generate_tree = [&](vector<int>& deg, vector<vector<int>>& tree_adj, vector<vector<bool>>& is_in_tree) {\n        deg.assign(N * N, 0);\n        tree_adj.assign(N * N, {});\n        is_in_tree.assign(N * N, vector<bool>(N * N, false));\n        vector<int> parent(N * N, -1);\n        vector<bool> visited(N * N, false);\n        \n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n        pq.push({0, 0});\n        vector<int> min_edge_w(N * N, 1e9);\n        min_edge_w[0] = 0;\n        \n        while(!pq.empty()){\n            int u = pq.top().second;\n            pq.pop();\n            if(visited[u]) continue;\n            visited[u] = true;\n            \n            if(parent[u] != -1){\n                int p = parent[u];\n                tree_adj[u].push_back(p);\n                tree_adj[p].push_back(u);\n                is_in_tree[u][p] = is_in_tree[p][u] = true;\n                deg[u]++;\n                deg[p]++;\n            }\n            \n            for(int neighbor : adj[u]){\n                if(!visited[neighbor]){\n                    // Random weight to diversify trees\n                    int weight = -(d_flat[u] + d_flat[neighbor]) * (1 + rng() % 200);\n                    if(weight < min_edge_w[neighbor]){\n                        min_edge_w[neighbor] = weight;\n                        parent[neighbor] = u;\n                        pq.push({weight, neighbor});\n                    }\n                }\n            }\n        }\n    };\n\n    vector<int> best_deg;\n    vector<vector<int>> best_tree_adj;\n    vector<vector<bool>> best_in_tree;\n    double min_total_cost = 1e18;\n    \n    auto start_time = clock();\n    \n    // Spend 0.4s to find a good initial tree\n    while ((double)(clock() - start_time) / CLOCKS_PER_SEC < 0.4) {\n        vector<int> cur_deg;\n        vector<vector<int>> cur_tree_adj;\n        vector<vector<bool>> cur_is_in_tree;\n        generate_tree(cur_deg, cur_tree_adj, cur_is_in_tree);\n        \n        double total_cost = 0;\n        for(int i = 0; i < N * N; ++i) total_cost += get_node_cost(i, cur_deg);\n        \n        if(total_cost < min_total_cost) {\n            min_total_cost = total_cost;\n            best_deg = cur_deg;\n            best_tree_adj = cur_tree_adj;\n            best_in_tree = cur_is_in_tree;\n        }\n    }\n    \n    vector<int> deg = best_deg;\n    vector<vector<int>> tree_adj = best_tree_adj;\n    vector<vector<bool>> is_in_tree = best_in_tree;\n    \n    vector<int> global_best_deg = deg;\n    vector<vector<int>> global_best_tree_adj = tree_adj;\n    double global_min_cost = min_total_cost;\n    \n    vector<pair<int, int>> non_tree_edges;\n    for(int u = 0; u < N * N; ++u) {\n        for(int v : adj[u]) {\n            if (u < v && !is_in_tree[u][v]) {\n                non_tree_edges.push_back({u, v});\n            }\n        }\n    }\n    \n    double T_start = 1.0;\n    double T_end = 0.0001;\n    \n    // Pre-allocate memory for SA\n    vector<int> path_parent(N * N, -1);\n    vector<int> q(N * N);\n    vector<bool> v_visited(N * N, false);\n    \n    // Spend remaining time in SA\n    while ((double)(clock() - start_time) / CLOCKS_PER_SEC < 1.95) {\n        double elapsed = (double)(clock() - start_time) / CLOCKS_PER_SEC;\n        double progress = (elapsed - 0.4) / 1.55;\n        if (progress > 1.0) progress = 1.0;\n        double T = T_start * pow(T_end / T_start, progress);\n\n        int idx = rng() % non_tree_edges.size();\n        int u = non_tree_edges[idx].first;\n        int v = non_tree_edges[idx].second;\n        \n        int head = 0, tail = 0;\n        q[tail++] = u;\n        fill(v_visited.begin(), v_visited.end(), false);\n        v_visited[u] = true;\n        path_parent[u] = -1;\n        \n        bool found = false;\n        while(head < tail){\n            int curr = q[head++];\n            if(curr == v) { found = true; break; }\n            for(int neighbor : tree_adj[curr]){\n                if(!v_visited[neighbor]){\n                    v_visited[neighbor] = true;\n                    path_parent[neighbor] = curr;\n                    q[tail++] = neighbor;\n                }\n            }\n        }\n        \n        if(!found) continue;\n        \n        double best_delta = 1e18;\n        pair<int, int> best_swap_e = {-1, -1};\n        \n        int curr = v;\n        while(curr != u){\n            int p = path_parent[curr];\n            int a = curr, b = p;\n            \n            double old_c = get_node_cost(a, deg) + get_node_cost(b, deg) + get_node_cost(u, deg) + get_node_cost(v, deg);\n            \n            deg[a]--; deg[b]--; deg[u]++; deg[v]++;\n            double new_c = get_node_cost(a, deg) + get_node_cost(b, deg) + get_node_cost(u, deg) + get_node_cost(v, deg);\n            deg[a]++; deg[b]++; deg[u]--; deg[v]--;\n            \n            double delta = new_c - old_c;\n            if (delta < best_delta) {\n                best_delta = delta;\n                best_swap_e = {a, b};\n            }\n            curr = p;\n        }\n\n        if (best_swap_e.first != -1 && (best_delta < 0 || exp(-best_delta / T) > (double)rng() / rng.max())) {\n            int a = best_swap_e.first;\n            int b = best_swap_e.second;\n            \n            is_in_tree[a][b] = is_in_tree[b][a] = false;\n            is_in_tree[u][v] = is_in_tree[v][u] = true;\n            \n            for(int i=0; i<(int)tree_adj[a].size(); ++i) if(tree_adj[a][i] == b) { tree_adj[a].erase(tree_adj[a].begin()+i); break; }\n            for(int i=0; i<(int)tree_adj[b].size(); ++i) if(tree_adj[b][i] == a) { tree_adj[b].erase(tree_adj[b].begin()+i); break; }\n            tree_adj[u].push_back(v);\n            tree_adj[v].push_back(u);\n            \n            deg[a]--; deg[b]--; deg[u]++; deg[v]++;\n            non_tree_edges[idx] = {a, b};\n            \n            double current_total_cost = 0;\n            for(int i = 0; i < N * N; ++i) current_total_cost += get_node_cost(i, deg);\n            if(current_total_cost < global_min_cost) {\n                global_min_cost = current_total_cost;\n                global_best_deg = deg;\n                global_best_tree_adj = tree_adj;\n            }\n        }\n    }\n    \n    tree_adj = global_best_tree_adj;\n\n    vector<vector<int>> children(N * N);\n    static vector<int> q_dfs(N * N);\n    static vector<bool> visited_node(N * N, false);\n    int head = 0, tail = 0;\n    q_dfs[tail++] = 0;\n    visited_node[0] = true;\n    \n    vector<int> parent_node(N * N, -1);\n    while(head < tail){\n        int u = q_dfs[head++];\n        for(int neighbor : tree_adj[u]){\n            if(!visited_node[neighbor]){\n                visited_node[neighbor] = true;\n                children[u].push_back(neighbor);\n                parent_node[neighbor] = u;\n                q_dfs[tail++] = neighbor;\n            }\n        }\n    }\n    \n    vector<long long> subtree_d(N * N, 0);\n    for(int i = N * N - 1; i >= 0; --i){\n        int u = q_dfs[i];\n        subtree_d[u] += d_flat[u];\n        if(parent_node[u] != -1) subtree_d[parent_node[u]] += subtree_d[u];\n    }\n    \n    for(int i=0; i<N*N; ++i) {\n        sort(children[i].begin(), children[i].end(), [&](int a, int b){\n            return subtree_d[a] > subtree_d[b];\n        });\n    }\n\n    string path_str = \"\";\n    path_str.reserve(200000); \n    auto get_dir = [&](int u, int v) {\n        pair<int, int> p1 = pos(u, N), p2 = pos(v, N);\n        if (p2.first == p1.first + 1) return 'D';\n        if (p2.first == p1.first - 1) return 'U';\n        if (p2.second == p1.second + 1) return 'R';\n        if (p2.second == p1.second - 1) return 'L';\n        return ' ';\n    };\n\n    auto dfs = [&](auto self, int u) -> void {\n        for(int neighbor : children[u]){\n            path_str += get_dir(u, neighbor);\n            self(self, neighbor);\n            path_str += get_dir(neighbor, u);\n        }\n    };\n    dfs(dfs, 0);\n    \n    string final_path = \"\";\n    final_path.reserve(100000);\n    while((int)final_path.length() + (int)path_str.length() <= 100000) final_path += path_str;\n    cout << final_path << endl;\n\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <ctime>\n\nusing namespace std;\n\n// Structure to hold grid coordinates\nstruct Pos {\n    int r, c;\n};\n\n// Function to calculate the cost of moving between two squares.\n// The cost is |r1-r2| + |c1-c2| + 1.\ninline int dist(Pos p1, Pos p2) {\n    return abs(p1.r - p2.r) + abs(p1.c - p2.c) + 1;\n}\n\n// Global variables\nint N, M;\nint si, sj;\nvector<vector<Pos>> pos_map(26);\nvector<string> t;\nvector<vector<int>> overlap;\n\n// DP function to calculate ONLY the minimum travel cost for a given superstring.\nlong long get_min_cost(const string& s) {\n    int L = s.length();\n    if (L == 0) return 0;\n\n    const auto& start_chars = pos_map[s[0] - 'A'];\n    vector<long long> dp(start_chars.size());\n    \n    Pos start_pos = {si, sj};\n    for (size_t i = 0; i < start_chars.size(); ++i) {\n        dp[i] = dist(start_pos, start_chars[i]);\n    }\n\n    for (int k = 1; k < L; ++k) {\n        const auto& curr_chars = pos_map[s[k] - 'A'];\n        const auto& prev_chars = pos_map[s[k-1] - 'A'];\n        \n        vector<long long> next_dp(curr_chars.size(), 1e18);\n        \n        for (size_t i = 0; i < curr_chars.size(); ++i) {\n            for (size_t j = 0; j < prev_chars.size(); ++j) {\n                long long d = dp[j] + dist(prev_chars[j], curr_chars[i]);\n                if (d < next_dp[i]) {\n                    next_dp[i] = d;\n                }\n            }\n        }\n        dp = next_dp;\n    }\n\n    long long min_cost = 1e18;\n    for (long long val : dp) {\n        if (val < min_cost) min_cost = val;\n    }\n    return min_cost;\n}\n\n// DP function to calculate the cost AND the path for final reconstruction.\npair<long long, vector<Pos>> solve_dp(const string& s) {\n    int L = s.length();\n    const auto& start_chars = pos_map[s[0] - 'A'];\n    vector<long long> dp(start_chars.size());\n    vector<vector<int>> parent_path(L);\n    \n    Pos start_pos = {si, sj};\n    for (size_t i = 0; i < start_chars.size(); ++i) {\n        dp[i] = dist(start_pos, start_chars[i]);\n    }\n\n    for (int k = 1; k < L; ++k) {\n        const auto& curr_chars = pos_map[s[k] - 'A'];\n        const auto& prev_chars = pos_map[s[k-1] - 'A'];\n        \n        vector<long long> next_dp(curr_chars.size(), 1e18);\n        vector<int> next_parent(curr_chars.size(), -1);\n        \n        for (size_t i = 0; i < curr_chars.size(); ++i) {\n            for (size_t j = 0; j < prev_chars.size(); ++j) {\n                long long d = dp[j] + dist(prev_chars[j], curr_chars[i]);\n                if (d < next_dp[i]) {\n                    next_dp[i] = d;\n                    next_parent[i] = (int)j;\n                }\n            }\n        }\n        dp = next_dp;\n        parent_path[k] = next_parent;\n    }\n\n    long long min_cost = 1e18;\n    int last_idx = -1;\n    for (size_t i = 0; i < dp.size(); ++i) {\n        if (dp[i] < min_cost) {\n            min_cost = dp[i];\n            last_idx = (int)i;\n        }\n    }\n\n    vector<Pos> path(L);\n    int curr_idx = last_idx;\n    for (int k = L - 1; k >= 0; --k) {\n        path[k] = pos_map[s[k] - 'A'][curr_idx];\n        if (k > 0) {\n            curr_idx = parent_path[k][curr_idx];\n        }\n    }\n    return {min_cost, path};\n}\n\nstring build_superstring(const vector<int>& p) {\n    string res = t[p[0]];\n    for (size_t i = 1; i < p.size(); ++i) {\n        res += t[p[i]].substr(overlap[p[i-1]][p[i]]);\n    }\n    return res;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M)) return 0;\n    cin >> si >> sj;\n\n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) {\n            pos_map[row[j] - 'A'].push_back({i, j});\n        }\n    }\n\n    t.resize(M);\n    for (int i = 0; i < M; ++i) cin >> t[i];\n\n    overlap.assign(M, vector<int>(M));\n    for (int i = 0; i < M; ++i) {\n        for (int j = 0; j < M; ++j) {\n            if (i == j) continue;\n            for (int len = 5; len >= 0; --len) {\n                if (t[i].substr(5 - len) == t[j].substr(0, len)) {\n                    overlap[i][j] = len;\n                    break;\n                }\n            }\n        }\n    }\n\n    // 1. Generate M greedy initial candidates\n    vector<vector<int>> candidates;\n    for (int start_node = 0; start_node < M; ++start_node) {\n        vector<int> p;\n        p.reserve(M);\n        p.push_back(start_node);\n        vector<bool> used(M, false);\n        used[start_node] = true;\n        \n        for (int i = 1; i < M; ++i) {\n            int last = p.back();\n            int best_next = -1;\n            int max_o = -1;\n            for (int j = 0; j < M; ++j) {\n                if (!used[j] && overlap[last][j] > max_o) {\n                    max_o = overlap[last][j];\n                    best_next = j;\n                }\n            }\n            p.push_back(best_next);\n            used[best_next] = true;\n        }\n        candidates.push_back(p);\n    }\n\n    // 2. Perform Hill Climbing / Local Search\n    long long best_total_cost = 2e18;\n    vector<int> best_p;\n    \n    // Find initial best\n    for(const auto& p : candidates) {\n        long long c = get_min_cost(build_superstring(p));\n        if(c < best_total_cost) {\n            best_total_cost = c;\n            best_p = p;\n        }\n    }\n\n    mt19937 rng(1337);\n    auto start_time = clock();\n    \n    int cand_idx = 0;\n    while ((double)(clock() - start_time) / CLOCKS_PER_SEC < 1.7) {\n        vector<int> p = candidates[cand_idx % M];\n        \n        // Hill climbing: 2-opt moves\n        for(int iter = 0; iter < 10; ++iter) {\n            int i = rng() % (M - 1);\n            int j = i + 1 + rng() % (M - 1 - i);\n            \n            vector<int> next_p = p;\n            reverse(next_p.begin() + i, next_p.begin() + j + 1);\n            \n            long long current_cost = get_min_cost(build_superstring(p));\n            long long next_cost = get_min_cost(build_superstring(next_p));\n            \n            if (next_cost < current_cost) {\n                p = next_p;\n                \n                // Keep track of the best global permutation found\n                if (next_cost < best_total_cost) {\n                    best_total_cost = next_cost;\n                    best_p = next_p;\n                }\n            }\n        }\n        cand_idx++;\n    }\n\n    // 3. Final path reconstruction\n    pair<long long, vector<Pos>> final_result = solve_dp(build_superstring(best_p));\n    for (const auto& pos : final_result.second) {\n        cout << pos.r << \" \" << pos.c << \"\\n\";\n    }\n\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <iomanip>\n\nusing namespace std;\n\n// Structure to represent a point on the island\nstruct Point {\n    int r, c;\n};\n\n// Structure to represent an oil field\nstruct Field {\n    vector<Point> shape;\n    int max_dr, max_dc;\n};\n\nint N, M;\ndouble eps;\nvector<Field> fields;\n\n// Global vector for precomputed is_oil: [k][r][c][i][j]\n// Using uint8_t to save memory\nvector<uint8_t> is_oil; \n\ninline bool get_is_oil(int k, int r, int c, int i, int j) {\n    if (i < r || j < c || i >= r + fields[k].max_dr + 1 || j >= c + fields[k].max_dc + 1) return false;\n    return is_oil[((((k * N + r) * N + c) * N + i) * N + j)];\n}\n\nstruct Config {\n    vector<Point> offsets;\n    double log_weight;\n};\n\nvector<Config> particles;\nconst int NUM_PARTICLES = 250;\n\nvoid init_particles() {\n    particles.clear();\n    mt19937 rng(12345);\n    for (int i = 0; i < NUM_PARTICLES; ++i) {\n        Config c;\n        for (int k = 0; k < M; ++k) {\n            uniform_int_distribution<int> dist_r(0, N - 1 - fields[k].max_dr);\n            uniform_int_distribution<int> dist_c(0, N - 1 - fields[k].max_dc);\n            c.offsets.push_back({dist_r(rng), dist_c(rng)});\n        }\n        c.log_weight = -log((double)NUM_PARTICLES);\n        particles.push_back(c);\n    }\n}\n\nint compute_v_S(const Config& c, const vector<Point>& S) {\n    int v_S = 0;\n    for (const auto& p : S) {\n        for (int k = 0; k < M; ++k) {\n            if (get_is_oil(k, c.offsets[k].r, c.offsets[k].c, p.r, p.c)) {\n                v_S++;\n            }\n        }\n    }\n    return v_S;\n}\n\nvoid update_weights(const vector<Point>& S, double obs) {\n    int k = S.size();\n    double sigma2 = (double)k * eps * (1.0 - eps);\n    double max_log_w = -1e18;\n\n    for (auto& c : particles) {\n        int v_S = compute_v_S(c, S);\n        double mu = (double)(k - v_S) * eps + (double)v_S * (1.0 - eps);\n        double log_likelihood = -0.5 * pow(obs - mu, 2) / sigma2;\n        c.log_weight += log_likelihood;\n        if (c.log_weight > max_log_w) max_log_w = c.log_weight;\n    }\n\n    double sum_w = 0;\n    for (auto& c : particles) {\n        c.log_weight -= max_log_w;\n        sum_w += exp(c.log_weight);\n    }\n    for (auto& c : particles) {\n        c.log_weight = log(exp(c.log_weight) / sum_w);\n    }\n}\n\nvoid resample() {\n    double sum_sq_w = 0;\n    for (auto& c : particles) sum_sq_w += exp(2.0 * c.log_weight);\n    if (1.0 / sum_sq_w < NUM_PARTICLES / 3.0) {\n        vector<Config> new_particles;\n        vector<double> weights;\n        for (auto& c : particles) weights.push_back(exp(c.log_weight));\n        discrete_distribution<int> dist(weights.begin(), weights.end());\n        mt19937 rng(45678);\n        for (int i = 0; i < NUM_PARTICLES; ++i) {\n            new_particles.push_back(particles[dist(rng)]);\n            new_particles.back().log_weight = -log((double)NUM_PARTICLES);\n        }\n        particles = new_particles;\n    }\n}\n\nvoid rejuvenate() {\n    double min_w = 1e18;\n    for (auto& c : particles) min_w = min(min_w, c.log_weight);\n    \n    mt19937 rng(999);\n    for (auto& c : particles) {\n        if (c.log_weight < min_w + 1e-4) {\n            for (int k = 0; k < M; ++k) {\n                c.offsets[k].r = uniform_int_distribution<int>(0, N - 1 - fields[k].max_dr)(rng);\n                c.offsets[k].c = uniform_int_distribution<int>(0, N - 1 - fields[k].max_dc)(rng);\n            }\n            c.log_weight = -log((double)NUM_PARTICLES);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    cin >> N >> M >> eps;\n    fields.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int d; cin >> d;\n        int max_dr = 0, max_dc = 0;\n        for (int i = 0; i < d; ++i) {\n            int r, c; cin >> r >> c;\n            fields[k].shape.push_back({r, c});\n            max_dr = max(max_dr, r);\n            max_dc = max(max_dc, c);\n        }\n        fields[k].max_dr = max_dr;\n        fields[k].max_dc = max_dc;\n    }\n\n    is_oil.assign(M * N * N * N * N, 0);\n    for (int k = 0; k < M; ++k) {\n        for (int r = 0; r <= N - 1 - fields[k].max_dr; ++r) {\n            for (int c = 0; c <= N - 1 - fields[k].max_dc; ++c) {\n                for (const auto& p : fields[k].shape) {\n                    is_oil[((((k * N + r) * N + c) * N + (r + p.r)) * N + (c + p.c))] = 1;\n                }\n            }\n        }\n    }\n\n    init_particles();\n    mt19937 rng(42);\n    int query_count = 0;\n    while (query_count < 2 * N * N) {\n        vector<vector<Point>> candidates;\n        for (int i = 0; i < 50; ++i) {\n            int k = uniform_int_distribution<int>(1, N * N / 2)(rng);\n            vector<Point> S;\n            for (int j = 0; j < k; ++j) S.push_back({uniform_int_distribution<int>(0, N - 1)(rng), uniform_int_distribution<int>(0, N - 1)(rng)});\n            candidates.push_back(S);\n        }\n\n        int best_idx = -1;\n        double best_var = -1.0;\n        for (int i = 0; i < candidates.size(); ++i) {\n            double mean = 0;\n            vector<int> v_Ss;\n            for (auto& c : particles) {\n                int v_S = compute_v_S(c, candidates[i]);\n                v_Ss.push_back(v_S);\n                mean += exp(c.log_weight) * v_S;\n            }\n            double var = 0;\n            for (int j = 0; j < particles.size(); ++j) var += exp(particles[j].log_weight) * pow(v_Ss[j] - mean, 2);\n            double score = var * sqrt((double)candidates[i].size());\n            if (score > best_var) { best_var = score; best_idx = i; }\n        }\n\n        cout << \"q \" << candidates[best_idx].size();\n        for (auto& p : candidates[best_idx]) cout << \" \" << p.r << \" \" << p.c;\n        cout << endl;\n        double obs; cin >> obs;\n        update_weights(candidates[best_idx], obs);\n        resample();\n        rejuvenate();\n        query_count++;\n\n        // Guess\n        vector<Point> guess_set;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                double prob = 0;\n                for (auto& c : particles) {\n                    bool oil = false;\n                    for (int k = 0; k < M; ++k) if (get_is_oil(k, c.offsets[k].r, c.offsets[k].c, i, j)) { oil = true; break; }\n                    if (oil) prob += exp(c.log_weight);\n                }\n                if (prob > 0.5) guess_set.push_back({i, j});\n            }\n        }\n\n        cout << \"a \" << guess_set.size();\n        for (auto& p : guess_set) cout << \" \" << p.r << \" \" << p.c;\n        cout << endl;\n        int resp; cin >> resp;\n        if (resp == 1) return 0;\n    }\n    return 0;\n}","ahc031":"/*\n * Problem: Minimize total cost of rental area deficiency and partition movement.\n * Approach: Partition the W x W grid into N horizontal strips.\n * Use Coordinate Descent (Hill Climbing) followed by Simulated Annealing to optimize\n * the vertical positions of the N-1 internal partition lines.\n */\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Function to calculate area cost for a given strip height\nlong long get_area_cost(int W, int a_val, int height) {\n    if (height <= 0) return 1e15; // Prevents invalid partition configurations\n    long long area = (long long)W * height;\n    if (a_val > area) return 100LL * (a_val - area);\n    return 0LL;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int W, D, N;\n    if (!(cin >> W >> D >> N)) return 0;\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    // lines[d][k] is the vertical position of the partition between strip k-1 and k.\n    vector<vector<int>> lines(D, vector<int>(N + 1));\n    for (int d = 0; d < D; ++d) {\n        lines[d][0] = 0;\n        lines[d][N] = W;\n        int current_pos = 0;\n        for (int k = 0; k < N - 1; ++k) {\n            int needed_height = (a[d][k] + W - 1) / W;\n            current_pos += max(1, needed_height);\n            lines[d][k + 1] = current_pos;\n        }\n        for (int k = 1; k < N; ++k) {\n            lines[d][k] = max(lines[d][k - 1] + 1, min(lines[d][k], W - (N - k)));\n        }\n    }\n\n    // Stage 1: Coordinate Descent (Hill Climbing)\n    for (int iter = 0; iter < 50; ++iter) {\n        bool changed = false;\n        for (int d = 0; d < D; ++d) {\n            for (int k = 1; k < N; ++k) {\n                int best_pos = lines[d][k];\n                long long min_cost = -1;\n                int low = lines[d][k - 1] + 1;\n                int high = lines[d][k + 1] - 1;\n                for (int pos = low; pos <= high; ++pos) {\n                    long long cost = 0;\n                    cost += get_area_cost(W, a[d][k - 1], pos - lines[d][k - 1]);\n                    cost += get_area_cost(W, a[d][k], lines[d][k + 1] - pos);\n                    if (d > 0 && pos != lines[d - 1][k]) cost += 2LL * W;\n                    if (d < D - 1 && pos != lines[d + 1][k]) cost += 2LL * W;\n                    if (min_cost == -1 || cost < min_cost) {\n                        min_cost = cost;\n                        best_pos = pos;\n                    }\n                }\n                if (lines[d][k] != best_pos) {\n                    lines[d][k] = best_pos;\n                    changed = true;\n                }\n            }\n        }\n        if (!changed) break;\n    }\n\n    // Stage 2: Simulated Annealing\n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    double temp = 1000.0;\n    double min_temp = 1.0;\n    int iter = 0;\n\n    while (true) {\n        if ((iter & 2047) == 0) {\n            auto now = chrono::steady_clock::now();\n            if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 2800) break;\n        }\n        iter++;\n\n        int d = uniform_int_distribution<int>(0, D - 1)(rng);\n        int k = uniform_int_distribution<int>(1, N - 1)(rng);\n\n        int old_pos = lines[d][k];\n        int low = lines[d][k - 1] + 1;\n        int high = lines[d][k + 1] - 1;\n        if (low > high) continue;\n\n        int new_pos = uniform_int_distribution<int>(low, high)(rng);\n        if (new_pos == old_pos) continue;\n\n        long long delta = 0;\n        delta -= get_area_cost(W, a[d][k - 1], old_pos - lines[d][k - 1]);\n        delta -= get_area_cost(W, a[d][k], lines[d][k + 1] - old_pos);\n        delta += get_area_cost(W, a[d][k - 1], new_pos - lines[d][k - 1]);\n        delta += get_area_cost(W, a[d][k], lines[d][k + 1] - new_pos);\n\n        if (d > 0) {\n            if (old_pos != lines[d - 1][k]) delta -= 2 * W;\n            if (new_pos != lines[d - 1][k]) delta += 2 * W;\n        }\n        if (d < D - 1) {\n            if (old_pos != lines[d + 1][k]) delta -= 2 * W;\n            if (new_pos != lines[d + 1][k]) delta += 2 * W;\n        }\n\n        double acceptance = exp(-delta / temp);\n        if (delta < 0 || uniform_real_distribution<double>(0, 1)(rng) < acceptance) {\n            lines[d][k] = new_pos;\n        }\n\n        temp = max(min_temp, temp * 0.9999995);\n    }\n\n    // Output\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << lines[d][k] << \" \" << 0 << \" \" << lines[d][k + 1] << \" \" << W << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <algorithm>\n\n#pragma GCC optimize(\"O3\")\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint N, M, K;\nvector<vector<int>> A;\nvector<vector<vector<int>>> S;\nvector<vector<long long>> board;\nlong long current_score = 0;\n\nstruct Op {\n    int m, p, q;\n};\n\n// Apply or undo a stamp operation, updating the score locally\nvoid apply_op(const Op& op, int sign) {\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            int r = op.p + i;\n            int c = op.q + j;\n            current_score -= (board[r][c] % MOD);\n            if (sign == 1) {\n                board[r][c] += S[op.m][i][j];\n            } else {\n                board[r][c] -= S[op.m][i][j];\n            }\n            current_score += (board[r][c] % MOD);\n        }\n    }\n}\n\n// Function to reset the board to the initial state A\nvoid reset_board() {\n    current_score = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            board[i][j] = A[i][j];\n            current_score += (board[i][j] % MOD);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M >> K)) return 0;\n\n    A.assign(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> A[i][j];\n    \n    S.assign(M, vector<vector<int>>(3, vector<int>(3)));\n    for (int m = 0; m < M; ++m)\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                cin >> S[m][i][j];\n\n    board.assign(N, vector<long long>(N));\n    \n    // Perform multiple randomized greedy trials to find a good starting point\n    vector<Op> best_ops;\n    long long best_total_score = -1;\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto start_time = chrono::steady_clock::now();\n\n    for (int trial = 0; trial < 20; ++trial) {\n        reset_board();\n        vector<Op> ops;\n        for (int k = 0; k < K; ++k) {\n            vector<pair<long long, Op>> candidates;\n            for (int m = 0; m < M; ++m) {\n                for (int p = 0; p <= N - 3; ++p) {\n                    for (int q = 0; q <= N - 3; ++q) {\n                        long long gain = 0;\n                        for (int i = 0; i < 3; ++i) {\n                            for (int j = 0; j < 3; ++j) {\n                                gain -= (board[p + i][q + j] % MOD);\n                                gain += ((board[p + i][q + j] + S[m][i][j]) % MOD);\n                            }\n                        }\n                        if (gain > 0) candidates.push_back({gain, {m, p, q}});\n                    }\n                }\n            }\n            if (candidates.empty()) break;\n            \n            // Randomly pick from top candidates to explore\n            sort(candidates.begin(), candidates.end(), [](const pair<long long, Op>& a, const pair<long long, Op>& b) {\n                return a.first > b.first;\n            });\n            int pick = rng() % min((int)candidates.size(), 3);\n            apply_op(candidates[pick].second, 1);\n            ops.push_back(candidates[pick].second);\n        }\n        \n        if (current_score > best_total_score) {\n            best_total_score = current_score;\n            best_ops = ops;\n        }\n        \n        if (chrono::duration<double>(chrono::steady_clock::now() - start_time).count() > 0.4) break;\n    }\n\n    // Initialize board with the best greedy solution\n    reset_board();\n    vector<Op> ops = best_ops;\n    for (const auto& op : ops) apply_op(op, 1);\n\n    // Simulated Annealing\n    double time_limit = 1.9; \n    double start_temp = 1e6;\n    double end_temp = 1e1;\n    double temp = start_temp;\n\n    int iter = 0;\n    while (true) {\n        if ((iter & 1023) == 0) {\n            auto current_time = chrono::steady_clock::now();\n            double elapsed = chrono::duration<double>(current_time - start_time).count();\n            if (elapsed > time_limit) break;\n            temp = start_temp * pow(end_temp / start_temp, elapsed / time_limit);\n        }\n        iter++;\n\n        // Move distribution: Modify (60%), Swap (30%), Add/Remove (10%)\n        int r = rng() % 100;\n        int move_type = 0;\n        if (r < 60) move_type = 0;      // Modify\n        else if (r < 90) move_type = 3; // Swap\n        else if (r < 95) move_type = 1; // Add\n        else move_type = 2;             // Remove\n\n        if (ops.empty()) move_type = 1;\n        else if ((int)ops.size() == K && move_type == 1) move_type = 0;\n        else if (ops.size() == 0 && move_type == 2) move_type = 1;\n        else if (ops.size() < 2 && move_type == 3) move_type = 0;\n\n        long long prev_score = current_score;\n        Op old_op, new_op;\n        int idx1 = -1, idx2 = -1;\n\n        if (move_type == 0) { // Modify\n            idx1 = rng() % ops.size();\n            old_op = ops[idx1];\n            new_op = { (int)(rng() % M), (int)(rng() % (N - 2)), (int)(rng() % (N - 2)) };\n            apply_op(old_op, -1);\n            apply_op(new_op, 1);\n        } else if (move_type == 1) { // Add\n            new_op = { (int)(rng() % M), (int)(rng() % (N - 2)), (int)(rng() % (N - 2)) };\n            apply_op(new_op, 1);\n        } else if (move_type == 2) { // Remove\n            idx1 = rng() % ops.size();\n            old_op = ops[idx1];\n            apply_op(old_op, -1);\n        } else if (move_type == 3) { // Swap\n            idx1 = rng() % ops.size(); idx2 = rng() % ops.size();\n            apply_op(ops[idx1], -1); apply_op(ops[idx2], -1);\n            swap(ops[idx1], ops[idx2]);\n            apply_op(ops[idx1], 1); apply_op(ops[idx2], 1);\n        }\n\n        if (current_score >= prev_score || (exp((double)(current_score - prev_score) / (temp + 1e-9)) > (double)rng() / rng.max())) {\n            if (move_type == 0) ops[idx1] = new_op;\n            else if (move_type == 1) ops.push_back(new_op);\n            else if (move_type == 2) ops.erase(ops.begin() + idx1);\n        } else {\n            if (move_type == 0) {\n                apply_op(new_op, -1); apply_op(old_op, 1); ops[idx1] = old_op;\n            } else if (move_type == 1) apply_op(new_op, -1);\n            else if (move_type == 2) apply_op(old_op, 1);\n            else if (move_type == 3) {\n                apply_op(ops[idx1], -1); apply_op(ops[idx2], -1);\n                swap(ops[idx1], ops[idx2]);\n                apply_op(ops[idx1], 1); apply_op(ops[idx2], 1);\n            }\n        }\n    }\n\n    cout << ops.size() << endl;\n    for (const auto& op : ops) cout << op.m << \" \" << op.p << \" \" << op.q << endl;\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <cstring>\n\nusing namespace std;\n\nconst int N = 5;\n\nstruct Pos {\n    int r, c;\n    bool operator==(const Pos& other) const { return r == other.r && c == other.c; }\n    bool operator!=(const Pos& other) const { return !(*this == other); }\n};\n\nstruct Crane {\n    int id;\n    Pos pos;\n    int holding;\n    bool is_large;\n    string moves;\n};\n\nint grid[N][N];\nCrane cranes[N];\nint incoming[N][N];\nint incoming_ptr[N];\nint expected_container[N];\n\n// BFS to find the next step for a crane to reach a target\nPos get_next_move(int crane_idx, Pos target) {\n    if (cranes[crane_idx].pos == target) return target;\n\n    queue<pair<Pos, Pos>> q; // {current_pos, parent_pos}\n    q.push({cranes[crane_idx].pos, {-1, -1}});\n\n    Pos parent[N][N];\n    for(int i=0; i<N; ++i) for(int j=0; j<N; ++j) parent[i][j] = {-2, -2};\n    parent[cranes[crane_idx].pos.r][cranes[crane_idx].pos.c] = {-1, -1};\n\n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n\n    bool found = false;\n    Pos last = {-1, -1};\n\n    while (!q.empty()) {\n        Pos curr = q.front().first;\n        q.pop();\n\n        if (curr == target) {\n            found = true;\n            last = curr;\n            break;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int nr = curr.r + dr[i];\n            int nc = curr.c + dc[i];\n\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N && parent[nr][nc].r == -2) {\n                // Check if another crane is already occupying the square\n                bool crane_blocked = false;\n                for (int j = 0; j < N; ++j) {\n                    if (j != crane_idx && cranes[j].pos.r == nr && cranes[j].pos.c == nc) {\n                        crane_blocked = true;\n                        break;\n                    }\n                }\n                if (crane_blocked) continue;\n\n                // Special rule:\n                // Small cranes cannot move to a square with a container IF they are carrying a container\n                // Large cranes can always move to a square with a container\n                if (!cranes[crane_idx].is_large && cranes[crane_idx].holding != -1 && grid[nr][nc] != -1) {\n                    continue; \n                }\n\n                parent[nr][nc] = curr;\n                q.push({{nr, nc}, curr});\n            }\n        }\n        if (found) break;\n    }\n\n    if (!found) return cranes[crane_idx].pos;\n\n    // Backtrack to find the first move from the start\n    Pos curr = last;\n    while (parent[curr.r][curr.c] != cranes[crane_idx].pos) {\n        curr = parent[curr.r][curr.c];\n    }\n    return curr;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n_in;\n    cin >> n_in;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) cin >> incoming[i][j];\n        incoming_ptr[i] = 0;\n        expected_container[i] = N * i;\n    }\n\n    memset(grid, -1, sizeof(grid));\n    for (int i = 0; i < N; ++i) {\n        cranes[i] = {i, {i, 0}, -1, (i == 0), \"\"};\n    }\n\n    for (int turn = 0; turn < 10000; ++turn) {\n        // 1. Receive\n        for (int i = 0; i < N; ++i) {\n            if (incoming_ptr[i] < N && grid[i][0] == -1) {\n                bool crane_at_gate = false;\n                for(int k=0; k<N; ++k) if(cranes[k].pos.r == i && cranes[k].pos.c == 0) crane_at_gate = true;\n                if (!crane_at_gate) {\n                    grid[i][0] = incoming[i][incoming_ptr[i]++];\n                }\n            }\n        }\n\n        // 2. Action planning\n        vector<char> turn_actions(N, '.');\n        vector<Pos> next_positions(N);\n        for(int i=0; i<N; ++i) next_positions[i] = cranes[i].pos;\n\n        for (int i = 0; i < N; ++i) {\n            Crane &c = cranes[i];\n            \n            if (c.holding != -1) {\n                int target_row = c.holding / N;\n                Pos target = {target_row, N - 1};\n                \n                if (c.pos == target) {\n                    turn_actions[i] = 'Q';\n                } else {\n                    Pos next = get_next_move(i, target);\n                    if (next != c.pos) {\n                        next_positions[i] = next;\n                        turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                    } else turn_actions[i] = '.';\n                }\n            } else {\n                Pos target = {-1, -1};\n                \n                // Priority 1: Clear wrong container at dispatch gate\n                for (int r = 0; r < N; ++r) {\n                    if (grid[r][N-1] != -1 && grid[r][N-1] != expected_container[r]) {\n                        target = {r, N-1};\n                        break;\n                    }\n                }\n                \n                // Priority 2: Pick up expected container for this crane's row (or any expected container for the large crane)\n                if (target.r == -1) {\n                    for (int r = 0; r < N; ++r) {\n                        for (int col = 0; col < N; ++col) {\n                            if (grid[r][col] == expected_container[r]) {\n                                // Large crane handles any, small crane only handles its own row\n                                if (i == 0 || r == i) {\n                                    target = {r, col};\n                                    goto found;\n                                }\n                            }\n                        }\n                    }\n                }\n                found:;\n                \n                // Priority 3: Move to home position\n                if (target.r == -1) {\n                    target = {i, 1};\n                }\n\n                if (c.pos == target) {\n                    // If we are at target and there is a container, P it\n                    if (grid[target.r][target.c] != -1) {\n                        turn_actions[i] = 'P';\n                    } else {\n                        turn_actions[i] = '.';\n                    }\n                } else {\n                    Pos next = get_next_move(i, target);\n                    if (next != c.pos) {\n                        next_positions[i] = next;\n                        turn_actions[i] = (next.r < c.pos.r ? 'U' : next.r > c.pos.r ? 'D' : next.c < c.pos.c ? 'L' : 'R');\n                    } else turn_actions[i] = '.';\n                }\n            }\n        }\n\n        // Conflict Resolution\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (turn_actions[i] != '.' && turn_actions[j] != '.' && \n                    turn_actions[i] != 'P' && turn_actions[j] != 'P' &&\n                    turn_actions[i] != 'Q' && turn_actions[j] != 'Q' &&\n                    next_positions[i] == next_positions[j]) {\n                    turn_actions[j] = '.';\n                    next_positions[j] = cranes[j].pos;\n                }\n            }\n        }\n\n        // Apply actions\n        for (int i = 0; i < N; ++i) {\n            char a = turn_actions[i];\n            cranes[i].moves += a;\n            if (a == 'P') {\n                cranes[i].holding = grid[cranes[i].pos.r][cranes[i].pos.c];\n                grid[cranes[i].pos.r][cranes[i].pos.c] = -1;\n            } else if (a == 'Q') {\n                grid[cranes[i].pos.r][cranes[i].pos.c] = cranes[i].holding;\n                cranes[i].holding = -1;\n            } else if (a != '.' && a != 'B') {\n                cranes[i].pos = next_positions[i];\n            }\n        }\n\n        // Dispatch\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][N-1] == expected_container[i]) {\n                grid[i][N-1] = -1;\n                expected_container[i]++;\n            }\n        }\n    }\n\n    for (int i = 0; i < N; ++i) cout << cranes[i].moves << \"\\n\";\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 20;\nint H[N][N];\nint curr_r = 0, curr_c = 0;\nlong long current_load = 0;\n\nstruct Pos {\n    int r, c;\n};\n\n// Process the current cell: pick up surplus if available, and drop off if we have a load and there is a deficit\nvoid process_cell() {\n    // 1. Pick up surplus\n    if (H[curr_r][curr_c] > 0) {\n        int d = H[curr_r][curr_c];\n        cout << \"+\" << d << \"\\n\";\n        current_load += d;\n        H[curr_r][curr_c] = 0;\n    }\n    // 2. Drop off deficit\n    if (current_load > 0 && H[curr_r][curr_c] < 0) {\n        int d = min((long long)current_load, (long long)-H[curr_r][curr_c]);\n        cout << \"-\" << d << \"\\n\";\n        current_load -= d;\n        H[curr_r][curr_c] += d;\n    }\n}\n\n// Move to adjacent cell\nvoid move_to(int nr, int nc) {\n    if (nr == curr_r - 1) cout << \"U\" << \"\\n\";\n    else if (nr == curr_r + 1) cout << \"D\" << \"\\n\";\n    else if (nc == curr_c - 1) cout << \"L\" << \"\\n\";\n    else if (nc == curr_c + 1) cout << \"R\" << \"\\n\";\n    curr_r = nr;\n    curr_c = nc;\n}\n\n// Find the best target cell using a load-aware heuristic\nPos find_best_target() {\n    double max_score = -1.0;\n    Pos best = {-1, -1};\n    \n    for(int i = 0; i < N; ++i) {\n        for(int j = 0; j < N; ++j) {\n            if (H[i][j] == 0) continue;\n            \n            // If empty, skip deficit targets\n            if (H[i][j] < 0 && current_load == 0) continue;\n            \n            int dist = abs(i - curr_r) + abs(j - curr_c);\n            double score;\n            \n            // Score based on magnitude of imbalance and inverse of distance\n            if (H[i][j] > 0) {\n                score = (double)H[i][j] / (dist + 1.0);\n            } else {\n                // Higher multiplier for deficits when carrying more load\n                score = (double)abs(H[i][j]) * (1.0 + (double)current_load / 50.0) / (dist + 1.0);\n            }\n            \n            if (score > max_score) {\n                max_score = score;\n                best = {i, j};\n            }\n        }\n    }\n    return best;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n;\n    cin >> n;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) cin >> H[i][j];\n    }\n\n    // Process initial position\n    process_cell();\n\n    while (true) {\n        Pos target = find_best_target();\n        if (target.r == -1) break;\n\n        // Move towards target step-by-step\n        while (curr_r != target.r || curr_c != target.c) {\n            int nr = curr_r, nc = curr_c;\n            \n            // Prioritize movement in the dimension with larger distance\n            if (abs(curr_r - target.r) >= abs(curr_c - target.c)) {\n                if (curr_r < target.r) nr++;\n                else if (curr_r > target.r) nr--;\n                else if (curr_c < target.c) nc++;\n                else if (curr_c > target.c) nc--;\n            } else {\n                if (curr_c < target.c) nc++;\n                else if (curr_c > target.c) nc--;\n                else if (curr_r < target.r) nr++;\n                else if (curr_r > target.r) nr--;\n            }\n            \n            move_to(nr, nc);\n            process_cell();\n        }\n    }\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\n// Fast RNG\nuint64_t x = 88172645463325252ULL;\nuint64_t next_u64() {\n    x ^= x << 13;\n    x ^= x >> 7;\n    x ^= x << 17;\n    return x;\n}\n\n// Pairwise potential: sum(max(A_l, B_l)) for all criteria l.\nint precomputed_costs[60][60];\nint adj[36][4];\nint adj_size[36];\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seed_count = 2 * N * (N - 1); // 60\n    int grid_size = N * N; // 36\n    vector<vector<int>> seeds(seed_count, vector<int>(M));\n\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i][j];\n        }\n    }\n\n    // Precompute neighbors\n    for (int i = 0; i < grid_size; ++i) {\n        int r = i / N;\n        int c = i % N;\n        int count = 0;\n        if (r > 0) adj[i][count++] = (r - 1) * N + c;\n        if (r < N - 1) adj[i][count++] = (r + 1) * N + c;\n        if (c > 0) adj[i][count++] = r * N + c - 1;\n        if (c < N - 1) adj[i][count++] = r * N + c + 1;\n        adj_size[i] = count;\n    }\n\n    for (int t = 0; t < T; t++) {\n        // Precompute pair costs for this turn\n        for (int i = 0; i < seed_count; ++i) {\n            for (int j = 0; j < seed_count; ++j) {\n                int cost = 0;\n                for (int l = 0; l < M; ++l) {\n                    cost += max(seeds[i][l], seeds[j][l]);\n                }\n                precomputed_costs[i][j] = cost;\n            }\n        }\n\n        // Selection: Pick seeds based on potential + individual value + noise for diversity\n        vector<pair<long long, int>> seed_potentials(seed_count);\n        for (int i = 0; i < seed_count; ++i) {\n            long long pot = 0;\n            long long self_val = 0;\n            for (int l = 0; l < M; ++l) self_val += seeds[i][l];\n            for (int j = 0; j < seed_count; ++j) pot += precomputed_costs[i][j];\n            seed_potentials[i] = {pot + self_val * 3 + (next_u64() % 500), i};\n        }\n        sort(seed_potentials.rbegin(), seed_potentials.rend());\n        \n        vector<int> grid_indices(grid_size);\n        vector<int> unused_indices;\n        for (int i = 0; i < grid_size; ++i) grid_indices[i] = seed_potentials[i].second;\n        for (int i = grid_size; i < seed_count; ++i) unused_indices.push_back(seed_potentials[i].second);\n\n        // Simulated Annealing\n        int iterations = 3000000;\n        double start_temp = 50.0;\n        double end_temp = 0.05;\n        double temp = start_temp;\n        double cooling = pow(end_temp / start_temp, 1.0 / iterations);\n\n        for (int iter = 0; iter < iterations; ++iter) {\n            int p1 = next_u64() % grid_size;\n            // 80% grid-grid, 20% grid-unused\n            bool is_grid_grid = (next_u64() % 100 < 80);\n            int p2;\n            if (is_grid_grid) {\n                p2 = next_u64() % grid_size;\n                if (p1 == p2) continue;\n            } else {\n                p2 = next_u64() % (int)unused_indices.size();\n            }\n\n            int v1 = grid_indices[p1];\n            int v2 = is_grid_grid ? grid_indices[p2] : unused_indices[p2];\n\n            long long delta = 0;\n            if (is_grid_grid) {\n                long long old_c = 0;\n                for (int k = 0; k < adj_size[p1]; ++k) {\n                    int n = adj[p1][k];\n                    if (n != p2) old_c += precomputed_costs[v1][grid_indices[n]];\n                }\n                for (int k = 0; k < adj_size[p2]; ++k) {\n                    int n = adj[p2][k];\n                    if (n != p1) old_c += precomputed_costs[v2][grid_indices[n]];\n                }\n\n                long long new_c = 0;\n                for (int k = 0; k < adj_size[p1]; ++k) {\n                    int n = adj[p1][k];\n                    if (n != p2) new_c += precomputed_costs[v2][grid_indices[n]];\n                }\n                for (int k = 0; k < adj_size[p2]; ++k) {\n                    int n = adj[p2][k];\n                    if (n != p1) new_c += precomputed_costs[v1][grid_indices[n]];\n                }\n                delta = new_c - old_c;\n            } else {\n                long long old_c = 0;\n                for (int k = 0; k < adj_size[p1]; ++k) old_c += precomputed_costs[v1][grid_indices[adj[p1][k]]];\n                long long new_c = 0;\n                for (int k = 0; k < adj_size[p1]; ++k) new_c += precomputed_costs[v2][grid_indices[adj[p1][k]]];\n                delta = new_c - old_c;\n            }\n\n            if (delta > 0 || (temp > 1e-9 && exp(delta / temp) > (double)(next_u64() % 1000000) / 1000000.0)) {\n                if (is_grid_grid) {\n                    swap(grid_indices[p1], grid_indices[p2]);\n                } else {\n                    grid_indices[p1] = v2;\n                    unused_indices[p2] = v1;\n                }\n            }\n            temp *= cooling;\n        }\n\n        // Output\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << grid_indices[i * N + j];\n                if (j < N - 1) cout << \" \";\n            }\n            cout << \"\\n\";\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> seeds[i][j];\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Coordinate structure\nstruct Point {\n    int x, y;\n};\n\n// Robot vertex structure\nstruct Vertex {\n    int id;\n    int parent;\n    int L;\n    int dir; // 0=R, 1=D, 2=L, 3=U\n    bool holding;\n    Point target;\n};\n\nint N, M, V_avail;\nvector<vector<int>> s, t; // s=takoyaki (1 present), t=target (1 present)\nint rx, ry;\nvector<Vertex> robot;\n\n// Directions: R, D, L, U (0, 1, 2, 3)\nint DX[] = {0, 1, 0, -1};\nint DY[] = {1, 0, -1, 0};\nchar DIRS[] = {'R', 'D', 'L', 'U'};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> M >> V_avail)) return 0;\n    s.resize(N, vector<int>(N));\n    t.resize(N, vector<int>(N));\n    \n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) s[i][j] = row[j] - '0';\n    }\n    for (int i = 0; i < N; ++i) {\n        string row; cin >> row;\n        for (int j = 0; j < N; ++j) t[i][j] = row[j] - '0';\n    }\n\n    // Design robot: star graph with varying edge lengths\n    int V_prime = V_avail;\n    robot.resize(V_prime);\n    robot[0] = {0, -1, 0, 0, false, {-1, -1}};\n    for (int i = 1; i < V_prime; ++i) {\n        // Distribute edge lengths more diversely to cover the grid\n        int len = (i - 1) % min(N - 1, 7) + 1;\n        robot[i] = {i, 0, len, 0, false, {-1, -1}};\n    }\n\n    cout << V_prime << endl;\n    for (int i = 1; i < V_prime; ++i) {\n        cout << robot[i].parent << \" \" << robot[i].L << endl;\n    }\n    rx = N / 2;\n    ry = N / 2;\n    cout << rx << \" \" << ry << endl;\n\n    // Simulation\n    for (int turn = 0; turn < 100000; ++turn) {\n        // 1. Identify/Update targets\n        int current_m = 0;\n        vector<Point> takoyaki_squares;\n        vector<Point> target_squares;\n        for(int i=0; i<N; ++i) {\n            for(int j=0; j<N; ++j) {\n                if (s[i][j] && t[i][j]) current_m++;\n                if (s[i][j] && !t[i][j]) takoyaki_squares.push_back({i, j});\n                if (t[i][j] && !s[i][j]) target_squares.push_back({i, j});\n            }\n        }\n        if (current_m == M) break;\n\n        for (int i = 1; i < V_prime; ++i) {\n            if (robot[i].target.x >= 0) {\n                bool valid = false;\n                if (robot[i].holding) {\n                    if (t[robot[i].target.x][robot[i].target.y] == 1 && s[robot[i].target.x][robot[i].target.y] == 0) valid = true;\n                } else {\n                    if (s[robot[i].target.x][robot[i].target.y] == 1 && t[robot[i].target.x][robot[i].target.y] == 0) valid = true;\n                }\n                if (!valid) robot[i].target = {-1, -1};\n            }\n\n            if (robot[i].target.x == -1) {\n                int min_dist = 1e9;\n                Point best_p = {-1, -1};\n                if (robot[i].holding) {\n                    for (auto& p : target_squares) {\n                        int dist = abs(p.x - rx) + abs(p.y - ry);\n                        if (dist < min_dist) { min_dist = dist; best_p = p; }\n                    }\n                } else {\n                    for (auto& p : takoyaki_squares) {\n                        int dist = abs(p.x - rx) + abs(p.y - ry);\n                        if (dist < min_dist) { min_dist = dist; best_p = p; }\n                    }\n                }\n                robot[i].target = best_p;\n            }\n        }\n\n        // 2. Choose best root move and rotations\n        int best_move = 4; // Stay\n        double min_cost = 1e18;\n        vector<int> best_rots(V_prime, 0);\n\n        int move_dx[] = {-1, 1, 0, 0, 0}; // U, D, L, R, .\n        int move_dy[] = {0, 0, -1, 1, 0};\n        char move_char[] = {'U', 'D', 'L', 'R', '.'};\n\n        for (int m = 0; m < 5; ++m) {\n            int nrx = rx + move_dx[m];\n            int nry = ry + move_dy[m];\n            if (nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n\n            double cost = 0;\n            vector<int> current_rots(V_prime, 0);\n\n            for (int i = 1; i < V_prime; ++i) {\n                double best_d = 1e9;\n                int best_r = 0;\n                \n                for (int r = 0; r < 3; ++r) {\n                    int ndir = robot[i].dir;\n                    if (r == 1) ndir = (ndir + 3) % 4;\n                    else if (r == 2) ndir = (ndir + 1) % 4;\n                    int fx = nrx + DX[ndir] * robot[i].L;\n                    int fy = nry + DY[ndir] * robot[i].L;\n                    \n                    double d;\n                    if (robot[i].target.x >= 0) {\n                        d = abs(fx - robot[i].target.x) + abs(fy - robot[i].target.y);\n                        // Heuristic: If holding, prioritize dropping.\n                        if (robot[i].holding) d *= 1.5; \n                    } else {\n                        // Heuristic: Move to center if idle (resting position)\n                        d = abs(fx - N/2) + abs(fy - N/2);\n                        d *= 0.1; // Lower priority than active tasks\n                    }\n                    if (d < best_d) { best_d = d; best_r = r; }\n                }\n                cost += best_d;\n                current_rots[i] = best_r;\n            }\n            if (cost < min_cost) {\n                min_cost = cost;\n                best_move = m;\n                best_rots = current_rots;\n            }\n        }\n\n        // Apply best move\n        rx += move_dx[best_move];\n        ry += move_dy[best_move];\n        \n        string S = \"\";\n        S += move_char[best_move];\n        for (int i = 1; i < V_prime; ++i) {\n            if (best_rots[i] == 1) { S += 'L'; robot[i].dir = (robot[i].dir + 3) % 4; }\n            else if (best_rots[i] == 2) { S += 'R'; robot[i].dir = (robot[i].dir + 1) % 4; }\n            else S += '.';\n        }\n\n        // 3. Actions\n        string actions = \".\";\n        for (int i = 1; i < V_prime; ++i) {\n            int fx = rx + DX[robot[i].dir] * robot[i].L;\n            int fy = ry + DY[robot[i].dir] * robot[i].L;\n            bool action = false;\n            if (fx >= 0 && fx < N && fy >= 0 && fy < N) {\n                if (robot[i].holding) {\n                    if (t[fx][fy] == 1 && s[fx][fy] == 0) {\n                        robot[i].holding = false;\n                        s[fx][fy] = 1;\n                        action = true;\n                    }\n                } else {\n                    if (s[fx][fy] == 1 && t[fx][fy] == 0) {\n                        robot[i].holding = true;\n                        s[fx][fy] = 0;\n                        action = true;\n                    }\n                }\n            }\n            actions += (action ? 'P' : '.');\n        }\n        cout << S << actions << endl;\n    }\n\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <ctime>\n\nusing namespace std;\n\nstruct Fish {\n    int x, y, type; \n};\n\nstruct Rect {\n    int x1, y1, x2, y2;\n};\n\nconst int MAX_COORD = 100000;\n\n// Optimized Scoring function: O(K + log N), where K is the number of fish in the X-range\ninline int calculate_score(const vector<Fish>& fish_sorted_x, const Rect& r) {\n    if (r.x1 >= r.x2 || r.y1 >= r.y2) return 0;\n    int score = 0;\n    auto it1 = lower_bound(fish_sorted_x.begin(), fish_sorted_x.end(), r.x1, [](const Fish& f, int val) {\n        return f.x < val;\n    });\n    auto it2 = upper_bound(fish_sorted_x.begin(), fish_sorted_x.end(), r.x2, [](int val, const Fish& f) {\n        return val < f.x;\n    });\n    \n    for (auto it = it1; it != it2; ++it) {\n        if (it->y >= r.y1 && it->y <= r.y2) {\n            score += it->type;\n        }\n    }\n    return score;\n}\n\n// Kadane's algorithm to find the best initial rectangle on a grid\nRect find_best_rect(const vector<Fish>& fish, int grid_size, double offset_x, double offset_y) {\n    vector<vector<int>> grid(grid_size, vector<int>(grid_size, 0));\n    double cell_size = (double)(MAX_COORD + 1) / grid_size;\n    for (const auto& f : fish) {\n        int gx = min(max(0, (int)((f.x - offset_x * cell_size) / cell_size)), grid_size - 1);\n        int gy = min(max(0, (int)((f.y - offset_y * cell_size) / cell_size)), grid_size - 1);\n        grid[gx][gy] += f.type;\n    }\n\n    int current_max = -2e9;\n    int c_x1 = 0, c_y1 = 0, c_x2 = 0, c_y2 = 0;\n\n    for (int i1 = 0; i1 < grid_size; ++i1) {\n        vector<int> col_sum(grid_size, 0);\n        for (int i2 = i1; i2 < grid_size; ++i2) {\n            for (int j = 0; j < grid_size; ++j) col_sum[j] += grid[i2][j];\n            int current_sum = 0, start_j = 0;\n            for (int j = 0; j < grid_size; ++j) {\n                current_sum += col_sum[j];\n                if (current_sum > current_max) {\n                    current_max = current_sum;\n                    c_x1 = i1; c_x2 = i2;\n                    c_y1 = start_j; c_y2 = j;\n                }\n                if (current_sum < 0) {\n                    current_sum = 0;\n                    start_j = j + 1;\n                }\n            }\n        }\n    }\n\n    return {\n        max(0, min(MAX_COORD, (int)((c_x1 + offset_x) * cell_size))),\n        max(0, min(MAX_COORD, (int)((c_y1 + offset_y) * cell_size))),\n        max(0, min(MAX_COORD, (int)((c_x2 + 1 + offset_x) * cell_size))),\n        max(0, min(MAX_COORD, (int)((c_y2 + 1 + offset_y) * cell_size)))\n    };\n}\n\n// Hill Climbing refinement\nRect hill_climb(const vector<Fish>& fish_sorted_x, Rect r, clock_t start_time) {\n    int current_score = calculate_score(fish_sorted_x, r);\n    int step_sizes[] = {1000, 200, 40, 8, 1};\n    \n    for (int step_size : step_sizes) {\n        bool improved = true;\n        while (improved) {\n            if ((double)(clock() - start_time) / CLOCKS_PER_SEC > 1.9) return r;\n            improved = false;\n            \n            // Adjust each edge\n            int* coords[4] = {&r.x1, &r.x2, &r.y1, &r.y2};\n            for (int i = 0; i < 4; ++i) {\n                int original = *coords[i];\n                for (int delta : {-step_size, step_size}) {\n                    int next = original + delta;\n                    if (next < 0 || next > MAX_COORD) continue;\n                    *coords[i] = next;\n                    if (r.x1 < r.x2 && r.y1 < r.y2) {\n                        int s = calculate_score(fish_sorted_x, r);\n                        if (s > current_score) {\n                            current_score = s;\n                            improved = true;\n                        } else *coords[i] = original;\n                    } else *coords[i] = original;\n                }\n            }\n            // Try shifting the entire rectangle\n            int ox1 = r.x1, ox2 = r.x2, oy1 = r.y1, oy2 = r.y2;\n            int dirs[] = {-step_size, step_size};\n            for(int dx : dirs) {\n                for(int dy : dirs) {\n                    r.x1 = ox1 + dx; r.x2 = ox2 + dx;\n                    r.y1 = oy1 + dy; r.y2 = oy2 + dy;\n                    if(r.x1 >= 0 && r.x2 <= MAX_COORD && r.y1 >= 0 && r.y2 <= MAX_COORD) {\n                        int s = calculate_score(fish_sorted_x, r);\n                        if(s > current_score) {\n                            current_score = s;\n                            improved = true;\n                        } else { r.x1 = ox1; r.x2 = ox2; r.y1 = oy1; r.y2 = oy2; }\n                    } else { r.x1 = ox1; r.x2 = ox2; r.y1 = oy1; r.y2 = oy2; }\n                }\n            }\n        }\n    }\n    return r;\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n\n    int N; cin >> N;\n    vector<Fish> fish_raw;\n    fish_raw.reserve(2 * N);\n    for (int i = 0; i < N; ++i) { int x, y; cin >> x >> y; fish_raw.push_back({x, y, 1}); }\n    for (int i = 0; i < N; ++i) { int x, y; cin >> x >> y; fish_raw.push_back({x, y, -1}); }\n    \n    vector<Fish> fish_sorted_x = fish_raw;\n    sort(fish_sorted_x.begin(), fish_sorted_x.end(), [](const Fish& a, const Fish& b) {\n        return a.x < b.x;\n    });\n\n    clock_t start_time = clock();\n    \n    int resolutions[] = {64, 128, 256};\n    double offsets[] = {0.0, 0.5};\n    Rect best_r = {0, 0, 100000, 100000};\n    int max_total_score = -2e9;\n\n    for (int res : resolutions) {\n        for (double ox : offsets) {\n            for (double oy : offsets) {\n                Rect r = find_best_rect(fish_raw, res, ox, oy);\n                r = hill_climb(fish_sorted_x, r, start_time);\n                int score = calculate_score(fish_sorted_x, r);\n                if (score > max_total_score) {\n                    max_total_score = score;\n                    best_r = r;\n                }\n                if ((double)(clock() - start_time) / CLOCKS_PER_SEC > 1.8) break;\n            }\n            if ((double)(clock() - start_time) / CLOCKS_PER_SEC > 1.8) break;\n        }\n        if ((double)(clock() - start_time) / CLOCKS_PER_SEC > 1.8) break;\n    }\n\n    cout << 4 << endl << best_r.x1 << \" \" << best_r.y1 << endl << best_r.x2 << \" \" << best_r.y1 << endl << best_r.x2 << \" \" << best_r.y2 << endl << best_r.x1 << \" \" << best_r.y2 << endl;\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\n// Configuration for a single rectangle's placement\nstruct Placement {\n    int id;\n    int r;           // Rotation (0 or 1)\n    char d;          // Direction ('U' or 'L')\n    int b;           // Reference rectangle index (-1 for origin)\n    bool included;   // Whether it's included in the packing\n};\n\nint N, T;\ndouble sigma;\nlong long W_obs_all[105], H_obs_all[105];\n\n// Rectangles data for simulation\nstruct Rect {\n    long long x, y, w, h;\n};\nRect placed_rects[105];\nbool is_included[105];\n\n// Efficient simulation using static arrays\nlong long simulate(const vector<Placement>& config, long long& W, long long& H) {\n    W = 0;\n    H = 0;\n    long long current_cost = 0;\n\n    // Reset status\n    for (int i = 0; i < N; ++i) is_included[i] = false;\n    for (int i = 0; i < N; ++i) if (config[i].included) is_included[config[i].id] = true;\n\n    for (int i = 0; i < N; ++i) {\n        if (!config[i].included) {\n            current_cost += (W_obs_all[config[i].id] + H_obs_all[config[i].id]);\n            continue;\n        }\n\n        int idx = config[i].id;\n        long long cur_w = (config[i].r == 0) ? W_obs_all[idx] : H_obs_all[idx];\n        long long cur_h = (config[i].r == 0) ? H_obs_all[idx] : W_obs_all[idx];\n\n        long long x, y;\n        int ref = config[i].b;\n        if (ref != -1 && !is_included[ref]) ref = -1;\n\n        if (config[i].d == 'U') {\n            x = (ref == -1) ? 0 : (placed_rects[ref].x + placed_rects[ref].w);\n            y = 0;\n            for (int j = 0; j < i; ++j) {\n                if (config[j].included) {\n                    const Rect& r = placed_rects[config[j].id];\n                    if (x < r.x + r.w && x + cur_w > r.x) {\n                        if (r.y + r.h > y) y = r.y + r.h;\n                    }\n                }\n            }\n        } else {\n            y = (ref == -1) ? 0 : (placed_rects[ref].y + placed_rects[ref].h);\n            x = 0;\n            for (int j = 0; j < i; ++j) {\n                if (config[j].included) {\n                    const Rect& r = placed_rects[config[j].id];\n                    if (y < r.y + r.h && y + cur_h > r.y) {\n                        if (r.x + r.w > x) x = r.x + r.w;\n                    }\n                }\n            }\n        }\n        \n        placed_rects[idx] = {x, y, cur_w, cur_h};\n        if (x + cur_w > W) W = x + cur_w;\n        if (y + cur_h > H) H = y + cur_h;\n    }\n    return W + H + current_cost;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N >> T >> sigma)) return 0;\n    for (int i = 0; i < N; ++i) cin >> W_obs_all[i] >> H_obs_all[i];\n\n    mt19937 rng(12345);\n    vector<Placement> best_config(N);\n    // Initialize config: placing rectangles in index order 0..N-1\n    for (int i = 0; i < N; ++i) best_config[i] = {i, 0, 'U', -1, true};\n\n    long long W, H;\n    long long best_sim_score = simulate(best_config, W, H);\n    double temp = 1000.0; // Initial temperature for SA\n\n    for (int t = 0; t < T; ++t) {\n        vector<Placement> current_config = best_config;\n        long long current_sim_score = best_sim_score;\n        \n        const int iterations = 500; \n        for (int iter = 0; iter < iterations; ++iter) {\n            int idx = rng() % N;\n            Placement old = current_config[idx];\n            \n            int mutation = rng() % 4;\n            if (mutation == 0) current_config[idx].r = 1 - current_config[idx].r;\n            else if (mutation == 1) current_config[idx].d = (current_config[idx].d == 'U' ? 'L' : 'U');\n            else if (mutation == 2) {\n                if (rng() % 3 == 0) current_config[idx].b = -1;\n                else if (idx > 0) {\n                    // Pick from previously placed rectangles\n                    current_config[idx].b = current_config[rng() % idx].id;\n                }\n            }\n            else current_config[idx].included = !current_config[idx].included;\n\n            long long new_W, new_H;\n            long long new_score = simulate(current_config, new_W, new_H);\n            \n            // Acceptance probability for Simulated Annealing\n            double delta = (double)(new_score - current_sim_score);\n            if (delta < 0 || exp(-delta / temp) > (double)(rng() % 10000) / 10000.0) {\n                current_sim_score = new_score;\n                if (new_score < best_sim_score) {\n                    best_sim_score = new_score;\n                    best_config = current_config;\n                }\n            } else {\n                current_config[idx] = old; // Backtrack\n            }\n        }\n        temp *= 0.95; // Cool down\n\n        // Output current best\n        int count = 0;\n        for (const auto& p : best_config) if (p.included) count++;\n        \n        cout << count << endl;\n        for (const auto& p : best_config) {\n            if (p.included)\n                cout << p.id << \" \" << p.r << \" \" << p.d << \" \" << p.b << endl;\n        }\n        cout.flush();\n\n        long long W_obs, H_obs;\n        if (!(cin >> W_obs >> H_obs)) break;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <ctime>\n#include <chrono>\n\nusing namespace std;\n\n// Struct to represent an edge in the priority queue\nstruct Item {\n    int priority;\n    int u; // parent node\n    int v; // child node\n    bool operator<(const Item& other) const {\n        return priority < other.priority;\n    }\n};\n\nvoid solve() {\n    int N, M, H;\n    if (!(cin >> N >> M >> H)) return;\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    // Skip coordinates as they are not used in the greedy logic\n    int x, y;\n    for (int i = 0; i < N; ++i) cin >> x >> y;\n\n    vector<int> best_p(N, -1);\n    long long best_score = -1;\n\n    // Time limit handling\n    clock_t start_time = clock();\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist(80, 120);\n    \n    // For root selection order\n    vector<int> nodes(N);\n    for(int i=0; i<N; ++i) nodes[i] = i;\n\n    int iter = 0;\n    while (true) {\n        // Periodically check time\n        if (iter % 10 == 0) {\n            if ((double)(clock() - start_time) / CLOCKS_PER_SEC > 1.8) break;\n        }\n        iter++;\n        \n        vector<int> p(N, -1);\n        vector<int> depth(N, 0);\n        vector<bool> visited(N, false);\n        \n        // Root selection heuristic to explore different configurations\n        if (iter % 3 == 0) {\n            sort(nodes.begin(), nodes.end(), [&](int a, int b){ return A[a] < A[b]; });\n        } else if (iter % 3 == 1) {\n            sort(nodes.begin(), nodes.end(), [&](int a, int b){ return A[a] > A[b]; });\n        } else {\n            shuffle(nodes.begin(), nodes.end(), rng);\n        }\n        \n        priority_queue<Item> pq;\n        int unvisited_count = N;\n        int order_idx = 0;\n        \n        // Build the forest\n        while (unvisited_count > 0) {\n            // Find next unvisited node to be a potential root\n            while (order_idx < N && visited[nodes[order_idx]]) {\n                order_idx++;\n            }\n            \n            if (pq.empty()) {\n                if (order_idx < N) {\n                    int r = nodes[order_idx];\n                    visited[r] = true;\n                    p[r] = -1;\n                    depth[r] = 0;\n                    unvisited_count--;\n                    \n                    // Add neighbors to PQ\n                    for (int neighbor : adj[r]) {\n                        if (!visited[neighbor]) {\n                            int gain = (depth[r] + 2) * A[neighbor];\n                            int randomized_gain = gain * dist(rng) / 100;\n                            pq.push({randomized_gain, r, neighbor});\n                        }\n                    }\n                }\n            } else {\n                Item top = pq.top();\n                pq.pop();\n                \n                if (visited[top.v]) continue;\n                // Constraint check: must not exceed depth H\n                if (depth[top.u] >= H) continue;\n                \n                visited[top.v] = true;\n                p[top.v] = top.u;\n                depth[top.v] = depth[top.u] + 1;\n                unvisited_count--;\n                \n                // Add neighbors to PQ\n                for (int neighbor : adj[top.v]) {\n                    if (!visited[neighbor]) {\n                        int gain = (depth[top.v] + 2) * A[neighbor];\n                        int randomized_gain = gain * dist(rng) / 100;\n                        pq.push({randomized_gain, top.v, neighbor});\n                    }\n                }\n            }\n        }\n        \n        // Calculate score\n        long long current_score = 0;\n        for (int j = 0; j < N; ++j) {\n            current_score += (long long)(depth[j] + 1) * A[j];\n        }\n        \n        // Keep the best solution\n        if (current_score > best_score) {\n            best_score = current_score;\n            best_p = p;\n        }\n    }\n    \n    // Output final solution\n    for (int i = 0; i < N; ++i) {\n        cout << best_p[i] << (i == N - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    solve();\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\n// Global variables\nint N;\nchar board[20][20];\n// Pre-calculate safety using prefix sums\n// row_fuku[r][c] = number of Fukunokami in row r in columns 0 to c-1\nint row_fuku[20][21]; \nint col_fuku[20][21]; \n\n// Update prefix sums after a board change\nvoid update_fuku_prefix() {\n    for (int i = 0; i < N; ++i) {\n        row_fuku[i][0] = 0;\n        for (int j = 0; j < N; ++j) {\n            row_fuku[i][j+1] = row_fuku[i][j] + (board[i][j] == 'o' ? 1 : 0);\n        }\n    }\n    for (int j = 0; j < N; ++j) {\n        col_fuku[j][0] = 0;\n        for (int i = 0; i < N; ++i) {\n            col_fuku[j][i+1] = col_fuku[j][i] + (board[i][j] == 'o' ? 1 : 0);\n        }\n    }\n}\n\n// O(1) safety check using prefix sums\nbool is_safe_fast(int r, int c, char dir) {\n    if (dir == 'U') {\n        // No Fukunokami in col c, rows 0 to r-1\n        return (col_fuku[c][r] - col_fuku[c][0]) == 0;\n    } else if (dir == 'D') {\n        // No Fukunokami in col c, rows r+1 to N-1\n        return (col_fuku[c][N] - col_fuku[c][r+1]) == 0;\n    } else if (dir == 'L') {\n        // No Fukunokami in row r, cols 0 to c-1\n        return (row_fuku[r][c] - row_fuku[r][0]) == 0;\n    } else if (dir == 'R') {\n        // No Fukunokami in row r, cols c+1 to N-1\n        return (row_fuku[r][N] - row_fuku[r][c+1]) == 0;\n    }\n    return true;\n}\n\n// Perform the shift\nvoid apply_move(char dir, int p) {\n    if (dir == 'U') {\n        for (int i = 0; i < N - 1; ++i) board[i][p] = board[i+1][p];\n        board[N-1][p] = '.';\n    } else if (dir == 'D') {\n        for (int i = N - 1; i > 0; --i) board[i][p] = board[i-1][p];\n        board[0][p] = '.';\n    } else if (dir == 'L') {\n        for (int j = 0; j < N - 1; ++j) board[p][j] = board[p][j+1];\n        board[p][N-1] = '.';\n    } else if (dir == 'R') {\n        for (int j = N - 1; j > 0; --j) board[p][j] = board[p][j-1];\n        board[p][0] = '.';\n    }\n    update_fuku_prefix();\n}\n\nstruct Move {\n    char dir;\n    int p;\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    if (!(cin >> N)) return 0;\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) board[i][j] = row[j];\n    }\n    update_fuku_prefix();\n\n    vector<Move> ans;\n    // Iterate up to the max possible moves 4N^2\n    for (int iter = 0; iter < 4 * N * N; ++iter) {\n        int best_r = -1, best_c = -1;\n        char best_dir = ' ';\n        int best_score = -1;\n        bool oni_found = false;\n\n        // Greedy search: find the best safe move\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (board[r][c] == 'x') {\n                    oni_found = true;\n                    char dirs[] = {'U', 'D', 'L', 'R'};\n                    for (char d : dirs) {\n                        if (is_safe_fast(r, c, d)) {\n                            // Check if this move removes the Oni immediately\n                            bool immediate = false;\n                            if (d == 'U' && r == 0) immediate = true;\n                            else if (d == 'D' && r == N - 1) immediate = true;\n                            else if (d == 'L' && c == 0) immediate = true;\n                            else if (d == 'R' && c == N - 1) immediate = true;\n\n                            // Score: Priority to immediate removals\n                            int score = immediate ? 2 : 1;\n                            if (score > best_score) {\n                                best_score = score;\n                                best_dir = d;\n                                best_r = r;\n                                best_c = c;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        if (!oni_found) break; // All Oni removed\n        if (best_dir == ' ') break; // Should not happen based on problem constraints\n\n        int p = (best_dir == 'U' || best_dir == 'D') ? best_c : best_r;\n        apply_move(best_dir, p);\n        ans.push_back({best_dir, p});\n    }\n\n    for (const auto& m : ans) {\n        cout << m.dir << \" \" << m.p << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cstring>\n#include <cstdint>\n\nusing namespace std;\n\n// Problem constants\nconst int MAX_N = 100;\nint N, L;\nint T[MAX_N];\nint a[MAX_N], b[MAX_N];\nint best_a[MAX_N], best_b[MAX_N];\nint trans[2 * MAX_N]; // Global trans table for simulation\n\n// Fast Xorshift RNG\nuint64_t xorshift_state;\ninline uint64_t xorshift() {\n    xorshift_state ^= xorshift_state << 13;\n    xorshift_state ^= xorshift_state >> 7;\n    xorshift_state ^= xorshift_state << 17;\n    return xorshift_state;\n}\n\n// Fast simulation: O(L)\n// Optimized branchless simulation\ninline long long calculate_error(int* counts_out) {\n    memset(counts_out, 0, N * sizeof(int));\n    int current = 0;\n    counts_out[0] = 1;\n    \n    // Branchless simulation using the trans table and parity check\n    int* t = trans;\n    for (int i = 1; i < L; ++i) {\n        current = t[(current << 1) + (counts_out[current] & 1)];\n        counts_out[current]++;\n    }\n    \n    long long error = 0;\n    for (int i = 0; i < N; ++i) {\n        int diff = counts_out[i] - T[i];\n        error += (diff < 0 ? -diff : diff);\n    }\n    return error;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    if (!(cin >> N >> L)) return 0;\n    for (int i = 0; i < N; ++i) cin >> T[i];\n    \n    xorshift_state = chrono::steady_clock::now().time_since_epoch().count();\n    \n    long long best_total_error = 2e18;\n    auto start_time = chrono::steady_clock::now();\n    \n    // Multi-start strategy: run multiple SA optimizations\n    const int NUM_RESTARTS = 6;\n    for(int r = 0; r < NUM_RESTARTS; ++r) {\n        if (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() > 1850) break;\n        \n        // Initialize state randomly\n        for (int i = 0; i < N; ++i) {\n            a[i] = xorshift() % N;\n            b[i] = xorshift() % N;\n            trans[2 * i] = b[i];\n            trans[2 * i + 1] = a[i];\n        }\n        \n        int counts[MAX_N];\n        long long current_error = calculate_error(counts);\n        \n        double initial_temp = 5000.0;\n        const int MAX_ITER = 20000;\n        \n        for (int iter = 0; iter < MAX_ITER; ++iter) {\n            if ((iter & 63) == 0) { \n                if (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start_time).count() > 1850) break;\n            }\n            \n            double temp = initial_temp * (1.0 - (double)iter / MAX_ITER);\n            \n            // Tournament selection\n            int i = xorshift() % N;\n            for(int k = 0; k < 2; ++k) {\n                int cand = xorshift() % N;\n                if (abs(counts[cand] - T[cand]) > abs(counts[i] - T[i])) i = cand;\n            }\n            \n            bool is_a = (xorshift() & 1);\n            int old_val = is_a ? a[i] : b[i];\n            \n            int new_val;\n            int r_val = xorshift() % 100;\n            // Mutation Heuristics\n            if (r_val < 80) { // Target most under-represented\n                int best_target = 0;\n                int max_diff = -1e9;\n                for(int cand = 0; cand < N; ++cand) {\n                    int diff = T[cand] - counts[cand];\n                    if (diff > max_diff) {\n                        max_diff = diff;\n                        best_target = cand;\n                    }\n                }\n                new_val = best_target;\n            } else if (r_val < 90) { // Pointer swap\n                new_val = is_a ? b[i] : a[i];\n            } else { // Random\n                new_val = xorshift() % N;\n            }\n            \n            if (is_a) { a[i] = new_val; trans[2 * i + 1] = new_val; }\n            else { b[i] = new_val; trans[2 * i] = new_val; }\n            \n            int next_counts[MAX_N];\n            long long new_error = calculate_error(next_counts);\n            \n            // Metropolis acceptance\n            if (new_error < current_error || (temp > 0 && exp((current_error - new_error) / temp) > (double)(xorshift() % 1000000) / 1000000.0)) {\n                current_error = new_error;\n                memcpy(counts, next_counts, sizeof(int) * N);\n                if (current_error < best_total_error) {\n                    best_total_error = current_error;\n                    memcpy(best_a, a, sizeof(int) * N);\n                    memcpy(best_b, b, sizeof(int) * N);\n                }\n            } else {\n                if (is_a) { a[i] = old_val; trans[2 * i + 1] = old_val; }\n                else { b[i] = old_val; trans[2 * i] = old_val; }\n            }\n        }\n    }\n    \n    // Output best result found across all restarts\n    for (int i = 0; i < N; ++i) cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    \n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\n// Structure to represent a city\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double x, y; // Estimated coordinates\n};\n\n// Structure for an edge\nstruct Edge {\n    int u, v;\n    long long w;\n    int group_id;\n};\n\n// Function to calculate distance squared\ndouble distSq(double x1, double y1, double x2, double y2) {\n    return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\n}\n\n// Function to calculate distance rounded down\nlong long distInt(double x1, double y1, double x2, double y2) {\n    return (long long)floor(sqrt(distSq(x1, y1, x2, y2)));\n}\n\n// Function to perform a query\nvector<pair<int, int>> query(const vector<int>& c) {\n    if (c.size() < 2) return {};\n    cout << \"? \" << c.size();\n    for (int city_id : c) cout << \" \" << city_id;\n    cout << endl;\n    \n    vector<pair<int, int>> edges;\n    for (int i = 0; i < (int)c.size() - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        edges.push_back({u, v});\n    }\n    return edges;\n}\n\n// Calculate MST cost for a single group\ndouble calculateGroupMST(const vector<int>& group, const vector<City>& cities) {\n    if (group.size() <= 1) return 0;\n    int n = group.size();\n    vector<bool> visited(n, false);\n    vector<double> min_dist(n, 1e18);\n    min_dist[0] = 0;\n    double cost = 0;\n    for(int i=0; i<n; ++i) {\n        int u = -1;\n        for(int j=0; j<n; ++j) {\n            if(!visited[j] && (u == -1 || min_dist[j] < min_dist[u])) u = j;\n        }\n        if (u == -1 || min_dist[u] == 1e18) break;\n        visited[u] = true;\n        cost += min_dist[u];\n        for(int v=0; v<n; ++v) {\n            if(!visited[v]) {\n                double d = sqrt(distSq(cities[group[u]].x, cities[group[u]].y, \n                                       cities[group[v]].x, cities[group[v]].y));\n                min_dist[v] = min(min_dist[v], d);\n            }\n        }\n    }\n    return cost;\n}\n\nint main() {\n    // Optimize I/O\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    vector<City> cities(N);\n    for (int i = 0; i < N; ++i) {\n        cities[i].id = 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.0;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2.0;\n    }\n\n    // 1. Multi-angle Clustering\n    vector<vector<int>> best_groups;\n    double min_cost = 1e18;\n    int num_angles = 100;\n\n    for (int i = 0; i < num_angles; ++i) {\n        double angle = M_PI * i / num_angles;\n        double cos_a = cos(angle);\n        double sin_a = sin(angle);\n        \n        vector<int> indices(N);\n        for(int j=0; j<N; ++j) indices[j] = j;\n        \n        sort(indices.begin(), indices.end(), [&](int a, int b) {\n            double pos_a = cities[a].x * cos_a + cities[a].y * sin_a;\n            double pos_b = cities[b].x * cos_a + cities[b].y * sin_a;\n            return pos_a < pos_b;\n        });\n        \n        vector<vector<int>> current_groups(M);\n        int start_idx = 0;\n        for(int j=0; j<M; ++j) {\n            for(int k=0; k<G[j]; ++k) {\n                current_groups[j].push_back(indices[start_idx++]);\n            }\n        }\n        \n        double cost = 0;\n        for (const auto& group : current_groups) cost += calculateGroupMST(group, cities);\n        if (cost < min_cost) {\n            min_cost = cost;\n            best_groups = current_groups;\n        }\n    }\n    \n    vector<vector<int>> groups = best_groups;\n\n    // 2. Identify expensive edges to query\n    vector<Edge> all_expensive_edges;\n    for(int i=0; i<M; ++i) {\n        if (groups[i].size() <= 1) continue;\n        \n        vector<Edge> group_edges;\n        for(size_t u=0; u<groups[i].size(); ++u) {\n            for(size_t v=u+1; v<groups[i].size(); ++v) {\n                int city_u = groups[i][u];\n                int city_v = groups[i][v];\n                group_edges.push_back({city_u, city_v, distInt(cities[city_u].x, cities[city_u].y, cities[city_v].x, cities[city_v].y), i});\n            }\n        }\n        sort(group_edges.begin(), group_edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        \n        vector<int> parent(N);\n        for(int j=0; j<N; ++j) parent[j] = j;\n        auto find = [&](auto self, int node) -> int {\n            return parent[node] == node ? node : parent[node] = self(self, parent[node]);\n        };\n        \n        for(const auto& e : group_edges) {\n            int root_u = find(find, e.u);\n            int root_v = find(find, e.v);\n            if(root_u != root_v) {\n                parent[root_u] = root_v;\n                all_expensive_edges.push_back(e);\n            }\n        }\n    }\n    \n    // Sort all MST edges by weight descending to prioritize expensive edges\n    sort(all_expensive_edges.begin(), all_expensive_edges.end(), [](const Edge& a, const Edge& b) {\n        return a.w > b.w;\n    });\n\n    // 3. Querying\n    vector<vector<pair<int, int>>> query_edges(M);\n    int queries_left = Q;\n    \n    for(const auto& e : all_expensive_edges) {\n        if (queries_left <= 0) break;\n        \n        int gid = e.group_id;\n        if (groups[gid].size() < 2) continue;\n        \n        // Pick u, v and find L-2 nearest neighbors to the midpoint of u and v\n        int u = e.u;\n        int v = e.v;\n        double mid_x = (cities[u].x + cities[v].x) / 2.0;\n        double mid_y = (cities[u].y + cities[v].y) / 2.0;\n        \n        vector<pair<double, int>> neighbors;\n        for(int city_id : groups[gid]) {\n            if (city_id == u || city_id == v) continue;\n            double d = distSq(cities[city_id].x, cities[city_id].y, mid_x, mid_y);\n            neighbors.push_back({d, city_id});\n        }\n        sort(neighbors.begin(), neighbors.end());\n        \n        vector<int> subset = {u, v};\n        int num_neighbors = min((int)neighbors.size(), L - 2);\n        for(int i=0; i<num_neighbors; ++i) subset.push_back(neighbors[i].second);\n        \n        auto edges = query(subset);\n        for(auto& edge : edges) {\n            query_edges[gid].push_back(edge);\n        }\n        queries_left--;\n    }\n    \n    // 4. Output MST construction\n    cout << \"!\" << endl;\n    for(int i=0; i<M; ++i) {\n        // Output cities\n        for(int j=0; j<G[i]; ++j) {\n            cout << groups[i][j] << (j == G[i]-1 ? \"\" : \" \");\n        }\n        cout << endl;\n        \n        // Build final MST\n        vector<Edge> final_edges;\n        \n        // Add query edges (weight 0 to ensure priority)\n        for(auto& edge : query_edges[i]) {\n            final_edges.push_back({edge.first, edge.second, 0, i});\n        }\n        \n        // Add all other edges (weight = estimated Euclidean distance)\n        for(size_t u=0; u<groups[i].size(); ++u) {\n            for(size_t v=u+1; v<groups[i].size(); ++v) {\n                int city_u = groups[i][u];\n                int city_v = groups[i][v];\n                long long d = distInt(cities[city_u].x, cities[city_u].y, cities[city_v].x, cities[city_v].y);\n                final_edges.push_back({city_u, city_v, d, i});\n            }\n        }\n        \n        sort(final_edges.begin(), final_edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        \n        // DSU\n        vector<int> parent(N);\n        for(int j=0; j<N; ++j) parent[j] = j;\n        \n        auto find = [&](auto self, int node) -> int {\n            return parent[node] == node ? node : parent[node] = self(self, parent[node]);\n        };\n        \n        vector<pair<int, int>> mst_edges;\n        for(auto& e : final_edges) {\n            int root_u = find(find, e.u);\n            int root_v = find(find, e.v);\n            if(root_u != root_v) {\n                parent[root_u] = root_v;\n                mst_edges.push_back({e.u, e.v});\n            }\n        }\n        \n        for(auto& e : mst_edges) {\n            cout << e.first << \" \" << e.second << endl;\n        }\n    }\n    \n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <tuple>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\n// Constants\nconst int N = 20;\n\n// Directions: U, D, L, R\nconst int DR[] = {-1, 1, 0, 0};\nconst int DC[] = {0, 0, -1, 1};\nconst char D_CHAR[] = {'U', 'D', 'L', 'R'};\n\nstruct State {\n    int r, c, dist;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\n// Function to simulate sliding and find the stopping position\npair<int, int> get_stop_pos(int r, int c, int dr, int dc, const vector<vector<int>>& grid) {\n    int nr = r, nc = c;\n    while (true) {\n        int next_r = nr + dr;\n        int next_c = nc + dc;\n        // Blocks are at the edges, so sliding always stops\n        if (next_r < 0 || next_r >= N || next_c < 0 || next_c >= N || grid[next_r][next_c] == 1) {\n            return {nr, nc};\n        }\n        nr = next_r;\n        nc = next_c;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n, m;\n    cin >> n >> m;\n    int r0, c0;\n    cin >> r0 >> c0;\n    vector<pair<int, int>> targets(m);\n    for (int i = 0; i < m; ++i) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n\n    vector<vector<int>> grid(N, vector<int>(N, 0));\n    int curr_r = r0, curr_c = c0;\n\n    for (int t = 0; t < m; ++t) {\n        int tr = targets[t].first;\n        int tc = targets[t].second;\n\n        // Dijkstra to find shortest path to (tr, tc)\n        vector<vector<int>> dist(N, vector<int>(N, 1e9));\n        vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n        vector<vector<string>> action_path(N, vector<string>(N, \"\"));\n        \n        priority_queue<State, vector<State>, greater<State>> pq;\n        dist[curr_r][curr_c] = 0;\n        pq.push({curr_r, curr_c, 0});\n        \n        while (!pq.empty()) {\n            State top = pq.top();\n            pq.pop();\n            \n            if (top.dist > dist[top.r][top.c]) continue;\n            if (top.r == tr && top.c == tc) break;\n            \n            for (int i = 0; i < 4; ++i) {\n                // Move action\n                int nr = top.r + DR[i];\n                int nc = top.c + DC[i];\n                if (nr >= 0 && nr < N && nc >= 0 && nc < N) {\n                    int cost = (grid[nr][nc] == 1) ? 2 : 1;\n                    string actions = \"\";\n                    if (grid[nr][nc] == 1) actions += string(\"A \") + D_CHAR[i] + \"\\n\";\n                    actions += string(\"M \") + D_CHAR[i] + \"\\n\";\n                    \n                    if (dist[top.r][top.c] + cost < dist[nr][nc]) {\n                        dist[nr][nc] = dist[top.r][top.c] + cost;\n                        parent[nr][nc] = {top.r, top.c};\n                        action_path[nr][nc] = actions;\n                        pq.push({nr, nc, dist[nr][nc]});\n                    }\n                }\n                \n                // Slide action\n                pair<int, int> stop = get_stop_pos(top.r, top.c, DR[i], DC[i], grid);\n                int sr = stop.first, sc = stop.second;\n                int br = sr + DR[i], bc = sc + DC[i];\n                \n                // Check if we need to add a block to stop at (sr, sc)\n                bool need_block = (br >= 0 && br < N && bc >= 0 && bc < N && grid[br][bc] == 0);\n                int cost = need_block ? 2 : 1;\n                \n                string actions = \"\";\n                if (need_block) actions += string(\"A \") + D_CHAR[i] + \"\\n\";\n                actions += string(\"S \") + D_CHAR[i] + \"\\n\";\n                \n                if (dist[top.r][top.c] + cost < dist[sr][sc]) {\n                    dist[sr][sc] = dist[top.r][top.c] + cost;\n                    parent[sr][sc] = {top.r, top.c};\n                    action_path[sr][sc] = actions;\n                    pq.push({sr, sc, dist[sr][sc]});\n                }\n            }\n        }\n        \n        // Reconstruct and execute path\n        vector<string> path_actions;\n        int curr_r2 = tr, curr_c2 = tc;\n        while (curr_r2 != curr_r || curr_c2 != curr_c) {\n            path_actions.push_back(action_path[curr_r2][curr_c2]);\n            pair<int, int> p = parent[curr_r2][curr_c2];\n            curr_r2 = p.first;\n            curr_c2 = p.second;\n        }\n        reverse(path_actions.begin(), path_actions.end());\n        \n        for (const string& s : path_actions) {\n            cout << s;\n            size_t pos = 0;\n            while(pos < s.length()){\n                size_t next_line = s.find('\\n', pos);\n                string line = s.substr(pos, next_line - pos);\n                pos = next_line + 1;\n                if(line.empty()) continue;\n                \n                char act = line[0], dir = line[2];\n                int dr = 0, dc = 0;\n                if(dir == 'U') dr = -1; else if(dir == 'D') dr = 1; else if(dir == 'L') dc = -1; else if(dir == 'R') dc = 1;\n                \n                if(act == 'A'){\n                    int nr = curr_r + dr;\n                    int nc = curr_c + dc;\n                    grid[nr][nc] = 1 - grid[nr][nc];\n                } else if(act == 'M'){\n                    curr_r += dr;\n                    curr_c += dc;\n                } else if(act == 'S'){\n                    pair<int, int> stop = get_stop_pos(curr_r, curr_c, dr, dc, grid);\n                    curr_r = stop.first;\n                    curr_c = stop.second;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}"}}}