{"model_name":"deepseek-v3.1-terminus","codes":{"1":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <cmath>\n#include <set>\n#include <map>\n#include <random>\n#include <functional>\n\nusing namespace std;\n\nstruct Company {\n    int id;\n    int x, y, r;\n    int a, b, c, d; // rectangle coordinates\n    int area() const { return (c - a) * (d - b); }\n    double satisfaction() const {\n        int s = area();\n        if (s == 0) return 0.0;\n        double ratio = min(r, s) / (double)max(r, s);\n        return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n    }\n};\n\nstruct Rectangle {\n    int a, b, c, d;\n    Rectangle(int a, int b, int c, int d) : a(a), b(b), c(c), d(d) {}\n    bool contains(int x, int y) const {\n        return a <= x && x < c && b <= y && y < d;\n    }\n    bool overlaps(const Rectangle& other) const {\n        return !(c <= other.a || other.c <= a || d <= other.b || other.d <= b);\n    }\n    int area() const { return (c - a) * (d - b); }\n};\n\nclass RectanglePacker {\nprivate:\n    int grid_size;\n    vector<Company> companies;\n    vector<Rectangle> rectangles;\n    vector<bool> fixed;\n    \npublic:\n    RectanglePacker(int n, const vector<tuple<int, int, int>>& input) : grid_size(10000) {\n        companies.resize(n);\n        for (int i = 0; i < n; i++) {\n            auto [x, y, r] = input[i];\n            companies[i] = {i, x, y, r, x, y, x + 1, y + 1};\n        }\n        rectangles.reserve(n);\n        fixed.resize(n, false);\n    }\n    \n    void solve() {\n        // Sort companies by desired area (largest first)\n        sort(companies.begin(), companies.end(), [](const Company& a, const Company& b) {\n            return a.r > b.r;\n        });\n        \n        // Initialize rectangles as 1x1 around desired points\n        for (auto& company : companies) {\n            rectangles.emplace_back(company.x, company.y, company.x + 1, company.y + 1);\n        }\n        \n        // Priority queue for expansion (companies that need more area)\n        auto comp = [](const pair<int, int>& a, const pair<int, int>& b) {\n            return a.second < b.second; // prioritize larger area deficit\n        };\n        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comp)> pq(comp);\n        \n        for (int i = 0; i < companies.size(); i++) {\n            int deficit = companies[i].r - rectangles[i].area();\n            if (deficit > 0) {\n                pq.push({i, deficit});\n            }\n        }\n        \n        // Expand rectangles greedily\n        while (!pq.empty()) {\n            auto [idx, deficit] = pq.top();\n            pq.pop();\n            \n            if (fixed[idx]) continue;\n            \n            Company& company = companies[idx];\n            Rectangle& rect = rectangles[idx];\n            \n            // Try to expand in each direction\n            vector<tuple<int, int, int>> expansions; // direction, new_area, overlap_penalty\n            \n            // Expand left\n            if (rect.a > 0) {\n                Rectangle new_rect(rect.a - 1, rect.b, rect.c, rect.d);\n                if (!hasOverlap(new_rect, idx)) {\n                    int new_area = new_rect.area();\n                    expansions.emplace_back(0, new_area, 0);\n                }\n            }\n            \n            // Expand right\n            if (rect.c < grid_size) {\n                Rectangle new_rect(rect.a, rect.b, rect.c + 1, rect.d);\n                if (!hasOverlap(new_rect, idx)) {\n                    int new_area = new_rect.area();\n                    expansions.emplace_back(1, new_area, 0);\n                }\n            }\n            \n            // Expand down\n            if (rect.b > 0) {\n                Rectangle new_rect(rect.a, rect.b - 1, rect.c, rect.d);\n                if (!hasOverlap(new_rect, idx)) {\n                    int new_area = new_rect.area();\n                    expansions.emplace_back(2, new_area, 0);\n                }\n            }\n            \n            // Expand up\n            if (rect.d < grid_size) {\n                Rectangle new_rect(rect.a, rect.b, rect.c, rect.d + 1);\n                if (!hasOverlap(new_rect, idx)) {\n                    int new_area = new_rect.area();\n                    expansions.emplace_back(3, new_area, 0);\n                }\n            }\n            \n            if (expansions.empty()) {\n                fixed[idx] = true;\n                continue;\n            }\n            \n            // Choose best expansion (closest to desired area)\n            sort(expansions.begin(), expansions.end(), [&](const auto& a, const auto& b) {\n                int area_a = get<1>(a);\n                int area_b = get<1>(b);\n                return abs(area_a - company.r) < abs(area_b - company.r);\n            });\n            \n            auto [direction, new_area, penalty] = expansions[0];\n            \n            // Apply expansion\n            switch (direction) {\n                case 0: rect.a--; break;\n                case 1: rect.c++; break;\n                case 2: rect.b--; break;\n                case 3: rect.d++; break;\n            }\n            \n            // Update company rectangle\n            company.a = rect.a;\n            company.b = rect.b;\n            company.c = rect.c;\n            company.d = rect.d;\n            \n            // Recalculate deficit and push back to queue if needed\n            deficit = company.r - company.area();\n            if (deficit > 0 && company.area() < grid_size * grid_size) {\n                pq.push({idx, deficit});\n            } else {\n                fixed[idx] = true;\n            }\n        }\n        \n        // Final adjustment phase - try to improve satisfaction\n        improveSolution();\n    }\n    \n    bool hasOverlap(const Rectangle& rect, int exclude_idx) const {\n        for (int i = 0; i < rectangles.size(); i++) {\n            if (i == exclude_idx) continue;\n            if (rect.overlaps(rectangles[i])) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    void improveSolution() {\n        // Try small adjustments to improve satisfaction\n        for (int iter = 0; iter < 1000; iter++) {\n            bool improved = false;\n            \n            for (int i = 0; i < companies.size(); i++) {\n                Company& company = companies[i];\n                Rectangle& rect = rectangles[i];\n                \n                double current_sat = company.satisfaction();\n                \n                // Try small expansions/contractions\n                for (int da = -1; da <= 1; da += 2) {\n                    for (int db = -1; db <= 1; db += 2) {\n                        if (da == 0 && db == 0) continue;\n                        \n                        int new_a = max(0, min(rect.a + da, grid_size - 1));\n                        int new_b = max(0, min(rect.b + db, grid_size - 1));\n                        int new_c = max(0, min(rect.c + da, grid_size));\n                        int new_d = max(0, min(rect.d + db, grid_size));\n                        \n                        if (new_a >= new_c || new_b >= new_d) continue;\n                        \n                        Rectangle new_rect(new_a, new_b, new_c, new_d);\n                        if (!hasOverlap(new_rect, i) && new_rect.contains(company.x, company.y)) {\n                            Company temp = company;\n                            temp.a = new_a; temp.b = new_b; temp.c = new_c; temp.d = new_d;\n                            double new_sat = temp.satisfaction();\n                            \n                            if (new_sat > current_sat) {\n                                rect = new_rect;\n                                company = temp;\n                                improved = true;\n                            }\n                        }\n                    }\n                }\n            }\n            \n            if (!improved) break;\n        }\n    }\n    \n    vector<tuple<int, int, int, int>> getSolution() const {\n        vector<tuple<int, int, int, int>> result;\n        result.reserve(companies.size());\n        \n        for (const auto& company : companies) {\n            result.emplace_back(company.a, company.b, company.c, company.d);\n        }\n        \n        return result;\n    }\n    \n    double calculateScore() const {\n        double total = 0.0;\n        for (const auto& company : companies) {\n            total += company.satisfaction();\n        }\n        return 1e9 * total / companies.size();\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    vector<tuple<int, int, int>> input;\n    for (int i = 0; i < n; i++) {\n        int x, y, r;\n        cin >> x >> y >> r;\n        input.emplace_back(x, y, r);\n    }\n    \n    RectanglePacker packer(n, input);\n    packer.solve();\n    \n    auto solution = packer.getSolution();\n    for (const auto& [a, b, c, d] : solution) {\n        cout << a << \" \" << b << \" \" << c << \" \" << d << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <array>\n#include <bitset>\n#include <algorithm>\n#include <functional>\n#include <unordered_set>\n\nusing namespace std;\n\nconst int GRID_SIZE = 50;\nconst int MAX_TILES = 2500; // Maximum possible tiles\nconst int BEAM_WIDTH = 100; // Number of paths to keep at each step\n\nstruct State {\n    int i, j;\n    int score;\n    string path;\n    bitset<MAX_TILES> visited_tiles;\n    \n    bool operator<(const State& other) const {\n        return score < other.score; // For max-heap\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<vector<int>> tile_id(GRID_SIZE, vector<int>(GRID_SIZE));\n    vector<vector<int>> values(GRID_SIZE, vector<int>(GRID_SIZE));\n    \n    // Read tile IDs\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            cin >> tile_id[i][j];\n        }\n    }\n    \n    // Read square values\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            cin >> values[i][j];\n        }\n    }\n    \n    // Find maximum tile ID to optimize bitset size\n    int max_tile = 0;\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            max_tile = max(max_tile, tile_id[i][j]);\n        }\n    }\n    \n    // Movement directions: Up, Down, Left, Right\n    array<pair<int, int>, 4> directions = {{\n        {-1, 0}, {1, 0}, {0, -1}, {0, 1}\n    }};\n    array<char, 4> dir_chars = {'U', 'D', 'L', 'R'};\n    \n    // Initial state\n    State initial;\n    initial.i = si;\n    initial.j = sj;\n    initial.score = values[si][sj];\n    initial.path = \"\";\n    initial.visited_tiles.set(tile_id[si][sj]);\n    \n    // Beam search\n    vector<State> current_beams = {initial};\n    \n    while (!current_beams.empty()) {\n        vector<State> next_beams;\n        next_beams.reserve(BEAM_WIDTH * 4);\n        \n        for (const auto& state : current_beams) {\n            for (int d = 0; d < 4; d++) {\n                int ni = state.i + directions[d].first;\n                int nj = state.j + directions[d].second;\n                \n                // Check bounds\n                if (ni < 0 || ni >= GRID_SIZE || nj < 0 || nj >= GRID_SIZE) {\n                    continue;\n                }\n                \n                // Check if tile already visited\n                int next_tile = tile_id[ni][nj];\n                if (state.visited_tiles.test(next_tile)) {\n                    continue;\n                }\n                \n                // Create new state\n                State new_state = state;\n                new_state.i = ni;\n                new_state.j = nj;\n                new_state.score += values[ni][nj];\n                new_state.path += dir_chars[d];\n                new_state.visited_tiles.set(next_tile);\n                \n                next_beams.push_back(new_state);\n            }\n        }\n        \n        // If no moves possible, break\n        if (next_beams.empty()) {\n            break;\n        }\n        \n        // Sort by score and keep top BEAM_WIDTH states\n        sort(next_beams.begin(), next_beams.end(), greater<State>());\n        if (next_beams.size() > BEAM_WIDTH) {\n            next_beams.resize(BEAM_WIDTH);\n        }\n        \n        current_beams = move(next_beams);\n    }\n    \n    // Output the best path found\n    if (!current_beams.empty()) {\n        cout << current_beams[0].path << endl;\n    } else {\n        // If no moves were possible, output empty path (just starting position)\n        cout << \"\" << endl;\n    }\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nconst double INIT_WEIGHT = 5000.0;\nconst double MIN_WEIGHT = 1000.0;\nconst double MAX_WEIGHT = 9000.0;\nconst double LEARNING_RATE = 0.1;\n\ndouble horizontal[N][N-1];\ndouble vertical[N-1][N];\n\nstruct Node {\n    int i, j;\n    double cost;\n    bool operator<(const Node& other) const {\n        return cost > other.cost;\n    }\n};\n\nstring reconstruct_path(pair<int,int> parent[N][N], int si, int sj, int ti, int tj) {\n    string path = \"\";\n    int i = ti, j = tj;\n    \n    while (i != si || j != sj) {\n        int pi = parent[i][j].first;\n        int pj = parent[i][j].second;\n        \n        if (pi == i) {\n            if (pj < j) path += 'R';\n            else path += 'L';\n        } else {\n            if (pi < i) path += 'D';\n            else path += 'U';\n        }\n        i = pi;\n        j = pj;\n    }\n    \n    reverse(path.begin(), path.end());\n    return path;\n}\n\nstring find_path(int si, int sj, int ti, int tj) {\n    double dist[N][N];\n    pair<int,int> parent[N][N];\n    bool visited[N][N] = {false};\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            dist[i][j] = 1e18;\n        }\n    }\n    \n    dist[si][sj] = 0;\n    priority_queue<Node> pq;\n    pq.push({si, sj, 0});\n    \n    int dx[4] = {-1, 1, 0, 0};\n    int dy[4] = {0, 0, -1, 1};\n    \n    while (!pq.empty()) {\n        auto [i, j, cost] = pq.top();\n        pq.pop();\n        \n        if (visited[i][j]) continue;\n        visited[i][j] = true;\n        \n        if (i == ti && j == tj) break;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + dx[d];\n            int nj = j + dy[d];\n            \n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            \n            double edge_cost;\n            if (dx[d] != 0) { // vertical move\n                int edge_i = min(i, ni);\n                edge_cost = vertical[edge_i][j];\n            } else { // horizontal move\n                int edge_j = min(j, nj);\n                edge_cost = horizontal[i][edge_j];\n            }\n            \n            double new_cost = dist[i][j] + edge_cost;\n            if (new_cost < dist[ni][nj]) {\n                dist[ni][nj] = new_cost;\n                parent[ni][nj] = {i, j};\n                double heuristic = abs(ni - ti) + abs(nj - tj); // Manhattan distance\n                pq.push({ni, nj, new_cost + heuristic * MIN_WEIGHT});\n            }\n        }\n    }\n    \n    return reconstruct_path(parent, si, sj, ti, tj);\n}\n\ndouble calculate_estimated_length(const string& path, int si, int sj) {\n    double length = 0;\n    int i = si, j = sj;\n    \n    for (char move : path) {\n        if (move == 'U') {\n            length += vertical[i-1][j];\n            i--;\n        } else if (move == 'D') {\n            length += vertical[i][j];\n            i++;\n        } else if (move == 'L') {\n            length += horizontal[i][j-1];\n            j--;\n        } else if (move == 'R') {\n            length += horizontal[i][j];\n            j++;\n        }\n    }\n    \n    return length;\n}\n\nvoid update_weights(const string& path, int si, int sj, double observed_length) {\n    double estimated_length = calculate_estimated_length(path, si, sj);\n    double ratio = observed_length / estimated_length;\n    double update_factor = 1.0 + LEARNING_RATE * (ratio - 1.0);\n    \n    int i = si, j = sj;\n    for (char move : path) {\n        if (move == 'U') {\n            vertical[i-1][j] *= update_factor;\n            vertical[i-1][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[i-1][j]));\n            i--;\n        } else if (move == 'D') {\n            vertical[i][j] *= update_factor;\n            vertical[i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[i][j]));\n            i++;\n        } else if (move == 'L') {\n            horizontal[i][j-1] *= update_factor;\n            horizontal[i][j-1] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][j-1]));\n            j--;\n        } else if (move == 'R') {\n            horizontal[i][j] *= update_factor;\n            horizontal[i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][j]));\n            j++;\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Initialize edge weights\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N-1; j++) {\n            horizontal[i][j] = INIT_WEIGHT;\n        }\n    }\n    for (int i = 0; i < N-1; i++) {\n        for (int j = 0; j < N; j++) {\n            vertical[i][j] = INIT_WEIGHT;\n        }\n    }\n    \n    for (int k = 0; k < 1000; k++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        string path = find_path(si, sj, ti, tj);\n        cout << path << endl;\n        cout.flush();\n        \n        int observed_length;\n        cin >> observed_length;\n        \n        update_weights(path, si, sj, observed_length);\n    }\n    \n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <map>\n#include <array>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    cin >> N >> M;\n    \n    vector<string> sequences(M);\n    for (int i = 0; i < M; i++) {\n        cin >> sequences[i];\n    }\n    \n    // Count character frequencies\n    array<int, 8> freq = {0}; // A-H\n    int total_chars = 0;\n    \n    for (const auto& s : sequences) {\n        for (char c : s) {\n            freq[c - 'A']++;\n            total_chars++;\n        }\n    }\n    \n    // Calculate target counts for each character\n    array<int, 8> target_counts;\n    int remaining = N * N;\n    for (int i = 0; i < 8; i++) {\n        target_counts[i] = (freq[i] * N * N + total_chars / 2) / total_chars;\n        remaining -= target_counts[i];\n    }\n    \n    // Distribute remaining cells to most frequent characters\n    vector<pair<int, int>> freq_index;\n    for (int i = 0; i < 8; i++) {\n        freq_index.emplace_back(freq[i], i);\n    }\n    sort(freq_index.rbegin(), freq_index.rend());\n    \n    for (int i = 0; i < remaining; i++) {\n        target_counts[freq_index[i % 8].second]++;\n    }\n    \n    // Create character pool\n    vector<char> char_pool;\n    for (int i = 0; i < 8; i++) {\n        for (int j = 0; j < target_counts[i]; j++) {\n            char_pool.push_back('A' + i);\n        }\n    }\n    \n    // Shuffle and fill matrix\n    random_device rd;\n    mt19937 g(rd());\n    shuffle(char_pool.begin(), char_pool.end(), g);\n    \n    vector<string> matrix(N, string(N, '.'));\n    int idx = 0;\n    for (int i = 0; i < N && idx < char_pool.size(); i++) {\n        for (int j = 0; j < N && idx < char_pool.size(); j++) {\n            matrix[i][j] = char_pool[idx++];\n        }\n    }\n    \n    // Output the matrix\n    for (const auto& row : matrix) {\n        cout << row << '\\n';\n    }\n    \n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <stack>\n#include <queue>\n#include <string>\n#include <tuple>\n\nusing namespace std;\n\nclass UnionFind {\npublic:\n    vector<int> parent;\n    UnionFind(int n) {\n        parent.resize(n);\n        for (int i = 0; i < n; i++) {\n            parent[i] = i;\n        }\n    }\n    int find(int x) {\n        if (parent[x] != x) {\n            parent[x] = find(parent[x]);\n        }\n        return parent[x];\n    }\n    void unite(int x, int y) {\n        x = find(x);\n        y = find(y);\n        if (x != y) {\n            parent[x] = y;\n        }\n    }\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n\n    vector<pair<int, int>> points;\n    map<pair<int, int>, int> point_to_index;\n    vector<int> costs;\n    int index = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                points.push_back({i, j});\n                int cost = grid[i][j] - '0';\n                costs.push_back(cost);\n                point_to_index[{i, j}] = index;\n                index++;\n            }\n        }\n    }\n    int V = points.size();\n    if (V == 0) {\n        cout << \"\" << endl;\n        return 0;\n    }\n\n    vector<tuple<int, int, int>> edges;\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    for (int i = 0; i < V; i++) {\n        int x = points[i].first;\n        int y = points[i].second;\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d];\n            int ny = y + dy[d];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] != '#') {\n                int j = point_to_index[{nx, ny}];\n                int w = costs[i] + costs[j];\n                edges.push_back({i, j, w});\n            }\n        }\n    }\n\n    sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {\n        return get<2>(a) < get<2>(b);\n    });\n\n    UnionFind uf(V);\n    vector<vector<int>> mst_graph(V);\n    for (const auto& edge : edges) {\n        int u = get<0>(edge);\n        int v = get<1>(edge);\n        if (!uf.same(u, v)) {\n            uf.unite(u, v);\n            mst_graph[u].push_back(v);\n            mst_graph[v].push_back(u);\n        }\n    }\n\n    int start_index = point_to_index[{si, sj}];\n    vector<vector<int>> children(V);\n    vector<bool> visited(V, false);\n    queue<int> q;\n    q.push(start_index);\n    visited[start_index] = true;\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        for (int v : mst_graph[u]) {\n            if (!visited[v]) {\n                visited[v] = true;\n                children[u].push_back(v);\n                q.push(v);\n            }\n        }\n    }\n\n    vector<int> nextChild(V, 0);\n    stack<int> st;\n    string path;\n    int current = start_index;\n    while (true) {\n        if (nextChild[current] < children[current].size()) {\n            int child = children[current][nextChild[current]];\n            nextChild[current]++;\n            int x1 = points[current].first;\n            int y1 = points[current].second;\n            int x2 = points[child].first;\n            int y2 = points[child].second;\n            if (x2 == x1 - 1) path += 'U';\n            else if (x2 == x1 + 1) path += 'D';\n            else if (y2 == y1 - 1) path += 'L';\n            else if (y2 == y1 + 1) path += 'R';\n            st.push(current);\n            current = child;\n        } else {\n            if (st.empty()) break;\n            int parent = st.top();\n            st.pop();\n            int x1 = points[current].first;\n            int y1 = points[current].second;\n            int x2 = points[parent].first;\n            int y2 = points[parent].second;\n            if (x2 == x1 - 1) path += 'U';\n            else if (x2 == x1 + 1) path += 'D';\n            else if (y2 == y1 - 1) path += 'L';\n            else if (y2 == y1 + 1) path += 'R';\n            current = parent;\n        }\n    }\n\n    cout << path << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nenum Status {\n    NOT_STARTED = 0,\n    ASSIGNED = 1,\n    COMPLETED = 2\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<vector<int>> task_difficulty(N+1, vector<int>(K));\n    for (int i=1; i<=N; i++) {\n        for (int j=0; j<K; j++) {\n            cin >> task_difficulty[i][j];\n        }\n    }\n\n    vector<vector<int>> succ_graph(N+1);\n    vector<vector<int>> prereqs(N+1);\n    for (int i=0; i<R; i++) {\n        int u, v;\n        cin >> u >> v;\n        succ_graph[u].push_back(v);\n        prereqs[v].push_back(u);\n    }\n\n    // Precompute descendant counts\n    vector<int> desc_count(N+1, 0);\n    for (int i=1; i<=N; i++) {\n        vector<bool> visited(N+1, false);\n        queue<int> q;\n        q.push(i);\n        visited[i] = true;\n        int count = 0;\n        while (!q.empty()) {\n            int u = q.front(); q.pop();\n            count++;\n            for (int v : succ_graph[u]) {\n                if (!visited[v]) {\n                    visited[v] = true;\n                    q.push(v);\n                }\n            }\n        }\n        desc_count[i] = count;\n    }\n\n    // Initialize arrays\n    vector<Status> task_status(N+1, NOT_STARTED);\n    vector<int> member_task(M+1, -1); // -1 means idle\n    vector<int> member_start_day(M+1, 0);\n    vector<vector<double>> s_est(M+1, vector<double>(K, 40.0)); // initial skill estimate 40\n\n    vector<int> unfinished_prereqs(N+1, 0);\n    for (int i=1; i<=N; i++) {\n        unfinished_prereqs[i] = prereqs[i].size();\n    }\n\n    int current_day = 1;\n    while (true) {\n        // Identify available tasks and members\n        vector<int> available_tasks;\n        for (int i=1; i<=N; i++) {\n            if (task_status[i] == NOT_STARTED && unfinished_prereqs[i] == 0) {\n                available_tasks.push_back(i);\n            }\n        }\n\n        vector<int> available_members;\n        for (int j=1; j<=M; j++) {\n            if (member_task[j] == -1) {\n                available_members.push_back(j);\n            }\n        }\n\n        // Sort available tasks by descendant count descending\n        sort(available_tasks.begin(), available_tasks.end(), [&](int a, int b) {\n            return desc_count[a] > desc_count[b];\n        });\n\n        vector<pair<int, int>> assignments;\n        for (int task : available_tasks) {\n            if (available_members.empty()) break;\n            int best_member = -1;\n            double best_est_t = 1e9;\n\n            // Function to compute estimated time for task and member\n            auto compute_est_t = [&](int t, int m) {\n                double w = 0.0;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[t][k] > s_est[m][k]) {\n                        w += task_difficulty[t][k] - s_est[m][k];\n                    }\n                }\n                if (w == 0) return 1.0;\n                else return w;\n            };\n\n            for (int member : available_members) {\n                double est_t = compute_est_t(task, member);\n                if (est_t < best_est_t) {\n                    best_est_t = est_t;\n                    best_member = member;\n                }\n            }\n\n            if (best_member != -1) {\n                assignments.push_back({best_member, task});\n                task_status[task] = ASSIGNED;\n                member_task[best_member] = task;\n                member_start_day[best_member] = current_day;\n                // Remove the member from available_members\n                auto it = find(available_members.begin(), available_members.end(), best_member);\n                available_members.erase(it);\n            }\n        }\n\n        // Output assignments\n        cout << assignments.size();\n        for (auto& ass : assignments) {\n            cout << \" \" << ass.first << \" \" << ass.second;\n        }\n        cout << endl;\n        cout.flush();\n\n        // Read input for the day\n        int n;\n        cin >> n;\n        if (n == -1) {\n            break;\n        }\n\n        vector<int> completed_members(n);\n        for (int i=0; i<n; i++) {\n            cin >> completed_members[i];\n        }\n\n        // Process completed members\n        for (int j : completed_members) {\n            int task = member_task[j];\n            if (task == -1) continue; // Should not happen\n            int start_day = member_start_day[j];\n            int t = current_day - start_day + 1;\n\n            // Update skill estimates\n            if (t == 1) {\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        s_est[j][k] = task_difficulty[task][k];\n                    }\n                }\n            } else {\n                double w_pred = 0.0;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        w_pred += task_difficulty[task][k] - s_est[j][k];\n                    }\n                }\n                double e = t - w_pred;\n                double alpha = 0.01;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        s_est[j][k] += 2 * alpha * e;\n                        if (s_est[j][k] < 0) s_est[j][k] = 0;\n                    }\n                }\n            }\n\n            // Update task and member status\n            task_status[task] = COMPLETED;\n            member_task[j] = -1;\n\n            // Update unfinished prerequisites for successors\n            for (int v : succ_graph[task]) {\n                unfinished_prereqs[v]--;\n            }\n        }\n\n        current_day++;\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nint main() {\n    int a[1000], b[1000], c[1000], d[1000];\n    for (int i = 0; i < 1000; i++) {\n        cin >> a[i] >> b[i] >> c[i] >> d[i];\n    }\n\n    vector<pair<int, int>> route;\n    route.push_back({400, 400});\n    int current_x = 400, current_y = 400;\n    vector<bool> picked(1000, false);\n    vector<bool> delivered(1000, false);\n    vector<int> pickup_index(1000, -1);\n    vector<int> dropoff_index(1000, -1);\n    int selected_count = 0;\n    int delivered_count = 0;\n\n    while (selected_count < 50 || delivered_count < 50) {\n        int min_dist = 1e9;\n        int best_i = -1;\n        bool is_pickup = true;\n\n        for (int i = 0; i < 1000; i++) {\n            if (!picked[i] && selected_count < 50) {\n                int dx = abs(current_x - a[i]);\n                int dy = abs(current_y - b[i]);\n                int dist = dx + dy;\n                if (dist < min_dist) {\n                    min_dist = dist;\n                    best_i = i;\n                    is_pickup = true;\n                }\n            }\n            if (picked[i] && !delivered[i]) {\n                int dx = abs(current_x - c[i]);\n                int dy = abs(current_y - d[i]);\n                int dist = dx + dy;\n                if (dist < min_dist) {\n                    min_dist = dist;\n                    best_i = i;\n                    is_pickup = false;\n                }\n            }\n        }\n\n        if (best_i == -1) {\n            break;\n        }\n\n        if (is_pickup) {\n            picked[best_i] = true;\n            selected_count++;\n            current_x = a[best_i];\n            current_y = b[best_i];\n            route.push_back({current_x, current_y});\n            pickup_index[best_i] = route.size() - 1;\n        } else {\n            delivered[best_i] = true;\n            delivered_count++;\n            current_x = c[best_i];\n            current_y = d[best_i];\n            route.push_back({current_x, current_y});\n            dropoff_index[best_i] = route.size() - 1;\n        }\n    }\n\n    route.push_back({400, 400});\n\n    int n = route.size();\n    double total_dist = 0;\n    for (int i = 0; i < n - 1; i++) {\n        total_dist += abs(route[i].first - route[i+1].first) + abs(route[i].second - route[i+1].second);\n    }\n\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 0; i <= n - 3; i++) {\n            for (int j = i + 1; j <= n - 2; j++) {\n                bool valid = true;\n                for (int k = 0; k < 1000; k++) {\n                    if (picked[k]) {\n                        int pi = pickup_index[k];\n                        int di = dropoff_index[k];\n                        if (pi >= i+1 && pi <= j && di >= i+1 && di <= j) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                }\n                if (!valid) {\n                    continue;\n                }\n\n                double new_dist = total_dist;\n                new_dist -= abs(route[i].first - route[i+1].first) + abs(route[i].second - route[i+1].second);\n                new_dist -= abs(route[j].first - route[j+1].first) + abs(route[j].second - route[j+1].second);\n                new_dist += abs(route[i].first - route[j].first) + abs(route[i].second - route[j].second);\n                new_dist += abs(route[i+1].first - route[j+1].first) + abs(route[i+1].second - route[j+1].second);\n\n                if (new_dist < total_dist) {\n                    reverse(route.begin() + i + 1, route.begin() + j + 1);\n                    total_dist = new_dist;\n                    improved = true;\n                    for (int k = 0; k < 1000; k++) {\n                        if (picked[k]) {\n                            if (pickup_index[k] >= i+1 && pickup_index[k] <= j) {\n                                pickup_index[k] = i + 1 + j - pickup_index[k];\n                            }\n                            if (dropoff_index[k] >= i+1 && dropoff_index[k] <= j) {\n                                dropoff_index[k] = i + 1 + j - dropoff_index[k];\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    cout << 50 << \" \";\n    for (int i = 0; i < 1000; i++) {\n        if (picked[i]) {\n            cout << i + 1 << \" \";\n        }\n    }\n    cout << endl;\n\n    cout << route.size() << \" \";\n    for (auto &p : route) {\n        cout << p.first << \" \" << p.second << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <functional>\n\nusing namespace std;\n\nconst int N = 400;\nconst int M = 1995;\n\nint main() {\n    vector<double> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<pair<int, int>> edges(M);\n    for (int i = 0; i < M; i++) {\n        int u, v;\n        cin >> u >> v;\n        edges[i] = {u, v};\n    }\n\n    vector<int> d(M);\n    for (int i = 0; i < M; i++) {\n        int u = edges[i].first;\n        int v = edges[i].second;\n        double dx = x[u] - x[v];\n        double dy = y[u] - y[v];\n        double dist = sqrt(dx*dx + dy*dy);\n        d[i] = static_cast<int>(round(dist));\n    }\n\n    vector<int> parent(N);\n    for (int i = 0; i < N; i++) {\n        parent[i] = i;\n    }\n\n    function<int(int)> find = [&](int a) {\n        if (parent[a] == a) return a;\n        return parent[a] = find(parent[a]);\n    };\n\n    int num_components = N;\n\n    auto unite = [&](int a, int b) {\n        a = find(a);\n        b = find(b);\n        if (a != b) {\n            parent[a] = b;\n            num_components--;\n            return true;\n        }\n        return false;\n    };\n\n    for (int i = 0; i < M; i++) {\n        int l_i;\n        cin >> l_i;\n\n        int u = edges[i].first;\n        int v = edges[i].second;\n\n        int comp_u = find(u);\n        int comp_v = find(v);\n\n        if (comp_u == comp_v) {\n            cout << 0 << endl;\n        } else {\n            if (l_i <= 2 * d[i] || (M - i - 1) < (num_components - 1)) {\n                cout << 1 << endl;\n                unite(u, v);\n            } else {\n                cout << 0 << endl;\n            }\n        }\n        cout.flush();\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int MAX_TURNS = 300;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<tuple<int, int, int>> pets;\n    for (int i = 0; i < N; i++) {\n        int x, y, t;\n        cin >> x >> y >> t;\n        pets.push_back({x, y, t});\n    }\n    int M;\n    cin >> M;\n    vector<pair<int, int>> humans;\n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        humans.push_back({x, y});\n    }\n\n    vector<vector<bool>> blocked(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n    vector<pair<int, int>> wall_squares;\n    vector<pair<int, int>> base_squares;\n\n    for (int i = 1; i <= 20; i++) {\n        wall_squares.push_back({20, i});\n        base_squares.push_back({19, i});\n    }\n    for (int i = 1; i <= 19; i++) {\n        wall_squares.push_back({i, 20});\n        base_squares.push_back({i, 19});\n    }\n\n    int total_walls = wall_squares.size();\n    vector<vector<pair<int, int>>> human_wall_squares(M);\n    vector<vector<pair<int, int>>> human_base_squares(M);\n\n    for (int i = 0; i < total_walls; i++) {\n        int human_idx = i % M;\n        human_wall_squares[human_idx].push_back(wall_squares[i]);\n        human_base_squares[human_idx].push_back(base_squares[i]);\n    }\n\n    vector<int> human_target_index(M, 0);\n    vector<vector<bool>> wall_built(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n\n    for (int turn = 1; turn <= MAX_TURNS; turn++) {\n        vector<char> actions(M, '.');\n        set<pair<int, int>> reserved_blocks;\n\n        for (int i = 0; i < M; i++) {\n            if (human_target_index[i] >= human_wall_squares[i].size()) {\n                continue;\n            }\n\n            pair<int, int> target_wall = human_wall_squares[i][human_target_index[i]];\n            pair<int, int> target_base = human_base_squares[i][human_target_index[i]];\n\n            if (wall_built[target_wall.first][target_wall.second]) {\n                human_target_index[i]++;\n                if (human_target_index[i] < human_wall_squares[i].size()) {\n                    target_wall = human_wall_squares[i][human_target_index[i]];\n                    target_base = human_base_squares[i][human_target_index[i]];\n                } else {\n                    continue;\n                }\n            }\n\n            if (humans[i] == target_base) {\n                bool can_block = true;\n\n                for (auto& pet : pets) {\n                    if (get<0>(pet) == target_wall.first && get<1>(pet) == target_wall.second) {\n                        can_block = false;\n                        break;\n                    }\n                }\n                if (can_block) {\n                    for (int j = 0; j < M; j++) {\n                        if (i != j && humans[j].first == target_wall.first && humans[j].second == target_wall.second) {\n                            can_block = false;\n                            break;\n                        }\n                    }\n                }\n\n                if (can_block) {\n                    int dx[] = {1, -1, 0, 0};\n                    int dy[] = {0, 0, 1, -1};\n                    for (int d = 0; d < 4; d++) {\n                        int nx = target_wall.first + dx[d];\n                        int ny = target_wall.second + dy[d];\n                        if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                        for (auto& pet : pets) {\n                            if (get<0>(pet) == nx && get<1>(pet) == ny) {\n                                can_block = false;\n                                break;\n                            }\n                        }\n                        if (!can_block) break;\n                    }\n                }\n\n                if (can_block) {\n                    int dx = target_wall.first - target_base.first;\n                    int dy = target_wall.second - target_base.second;\n                    char action;\n                    if (dx == 1) action = 'd';\n                    else if (dx == -1) action = 'u';\n                    else if (dy == 1) action = 'r';\n                    else if (dy == -1) action = 'l';\n                    else action = '.';\n                    actions[i] = action;\n                    reserved_blocks.insert(target_wall);\n                }\n            } else {\n                vector<vector<bool>> obstacles(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n                for (int x = 1; x <= GRID_SIZE; x++) {\n                    for (int y = 1; y <= GRID_SIZE; y++) {\n                        if (blocked[x][y]) obstacles[x][y] = true;\n                    }\n                }\n                for (auto& block : reserved_blocks) {\n                    obstacles[block.first][block.second] = true;\n                }\n                for (auto& pet : pets) {\n                    obstacles[get<0>(pet)][get<1>(pet)] = true;\n                }\n\n                queue<pair<int, int>> q;\n                vector<vector<int>> dist(GRID_SIZE + 1, vector<int>(GRID_SIZE + 1, -1));\n                vector<vector<pair<int, int>>> prev(GRID_SIZE + 1, vector<pair<int, int>>(GRID_SIZE + 1, {-1, -1}));\n                int start_x = humans[i].first;\n                int start_y = humans[i].second;\n                dist[start_x][start_y] = 0;\n                q.push({start_x, start_y});\n\n                int dx[] = {1, -1, 0, 0};\n                int dy[] = {0, 0, 1, -1};\n\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d];\n                        int ny = y + dy[d];\n                        if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                        if (obstacles[nx][ny]) continue;\n                        if (dist[nx][ny] == -1) {\n                            dist[nx][ny] = dist[x][y] + 1;\n                            prev[nx][ny] = {x, y};\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n\n                if (dist[target_base.first][target_base.second] != -1) {\n                    vector<pair<int, int>> path;\n                    pair<int, int> cur = target_base;\n                    while (cur != make_pair(start_x, start_y)) {\n                        path.push_back(cur);\n                        cur = prev[cur.first][cur.second];\n                    }\n                    reverse(path.begin(), path.end());\n                    if (!path.empty()) {\n                        pair<int, int> first_step = path[0];\n                        int dx = first_step.first - start_x;\n                        int dy = first_step.second - start_y;\n                        char action;\n                        if (dx == 1) action = 'D';\n                        else if (dx == -1) action = 'U';\n                        else if (dy == 1) action = 'R';\n                        else if (dy == -1) action = 'L';\n                        else action = '.';\n                        actions[i] = action;\n                    }\n                }\n            }\n        }\n\n        string action_str;\n        for (int i = 0; i < M; i++) {\n            action_str += actions[i];\n        }\n        cout << action_str << endl;\n        cout.flush();\n\n        vector<string> pet_movements(N);\n        for (int i = 0; i < N; i++) {\n            cin >> pet_movements[i];\n        }\n\n        for (int i = 0; i < M; i++) {\n            char action = actions[i];\n            if (action == 'u' || action == 'd' || action == 'l' || action == 'r') {\n                int x = humans[i].first;\n                int y = humans[i].second;\n                int block_x, block_y;\n                if (action == 'u') block_x = x - 1, block_y = y;\n                else if (action == 'd') block_x = x + 1, block_y = y;\n                else if (action == 'l') block_x = x, block_y = y - 1;\n                else if (action == 'r') block_x = x, block_y = y + 1;\n\n                if (block_x >= 1 && block_x <= GRID_SIZE && block_y >= 1 && block_y <= GRID_SIZE) {\n                    blocked[block_x][block_y] = true;\n                    for (auto& wall : wall_squares) {\n                        if (wall.first == block_x && wall.second == block_y) {\n                            wall_built[block_x][block_y] = true;\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        for (int i = 0; i < M; i++) {\n            char action = actions[i];\n            if (action == 'U') humans[i].first--;\n            else if (action == 'D') humans[i].first++;\n            else if (action == 'L') humans[i].second--;\n            else if (action == 'R') humans[i].second++;\n        }\n\n        for (int i = 0; i < N; i++) {\n            string moves = pet_movements[i];\n            int x = get<0>(pets[i]);\n            int y = get<1>(pets[i]);\n            for (char move : moves) {\n                if (move == 'U') x--;\n                else if (move == 'D') x++;\n                else if (move == 'L') y--;\n                else if (move == 'R') y++;\n            }\n            get<0>(pets[i]) = x;\n            get<1>(pets[i]) = y;\n        }\n    }\n\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <string>\n#include <utility>\n#include <map>\n\nusing namespace std;\n\nconst int GRID_SIZE = 20;\n\n// Directions: Up, Down, Left, Right\nconst int dx[4] = {-1, 1, 0, 0};\nconst int dy[4] = {0, 0, -1, 1};\nconst char dir_char[4] = {'U', 'D', 'L', 'R'};\n\nstruct Cell {\n    int i, j;\n    Cell(int i = 0, int j = 0) : i(i), j(j) {}\n    bool operator==(const Cell& other) const {\n        return i == other.i && j == other.j;\n    }\n    bool operator<(const Cell& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nclass Grid {\npublic:\n    Grid(int si, int sj, int ti, int tj, double p, \n         const vector<string>& h, const vector<string>& v) \n        : si(si), sj(sj), ti(ti), tj(tj), p(p) {\n        // Initialize wall arrays\n        this->h = h;\n        this->v = v;\n    }\n\n    // Check if a move is allowed from cell (i,j) in direction d\n    bool is_move_allowed(int i, int j, int d) const {\n        if (d == 0) { // Up\n            return i > 0 && v[i-1][j] == '0';\n        } else if (d == 1) { // Down\n            return i < GRID_SIZE - 1 && v[i][j] == '0';\n        } else if (d == 2) { // Left\n            return j > 0 && h[i][j-1] == '0';\n        } else if (d == 3) { // Right\n            return j < GRID_SIZE - 1 && h[i][j] == '0';\n        }\n        return false;\n    }\n\n    // Find the shortest path from start to end using BFS\n    string find_shortest_path() const {\n        Cell start(si, sj);\n        Cell end(ti, tj);\n\n        map<Cell, Cell> parent;\n        map<Cell, int> move_dir;\n        queue<Cell> q;\n        q.push(start);\n        parent[start] = start;\n        move_dir[start] = -1;\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            if (current == end) {\n                break;\n            }\n            for (int d = 0; d < 4; d++) {\n                if (is_move_allowed(current.i, current.j, d)) {\n                    Cell next(current.i + dx[d], current.j + dy[d]);\n                    if (parent.find(next) == parent.end()) {\n                        parent[next] = current;\n                        move_dir[next] = d;\n                        q.push(next);\n                    }\n                }\n            }\n        }\n\n        // Reconstruct the path from end to start\n        string path;\n        Cell current = end;\n        while (current != start) {\n            int d = move_dir[current];\n            path.push_back(dir_char[d]);\n            current = parent[current];\n        }\n        reverse(path.begin(), path.end());\n        return path;\n    }\n\n    // Find a cycle of length 2 from the target cell\n    string find_cycle() const {\n        // Check for UD cycle\n        if (is_move_allowed(ti, tj, 0) && is_move_allowed(ti-1, tj, 1)) {\n            return \"UD\";\n        }\n        // Check for LR cycle\n        if (is_move_allowed(ti, tj, 2) && is_move_allowed(ti, tj-1, 3)) {\n            return \"LR\";\n        }\n        // If no cycle found, return an empty string? But should always find one due to grid connectivity.\n        return \"UD\"; // default\n    }\n\nprivate:\n    int si, sj, ti, tj;\n    double p;\n    vector<string> h;\n    vector<string> v;\n};\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    vector<string> h(GRID_SIZE);\n    for (int i = 0; i < GRID_SIZE; i++) {\n        cin >> h[i];\n    }\n\n    vector<string> v(GRID_SIZE - 1);\n    for (int i = 0; i < GRID_SIZE - 1; i++) {\n        cin >> v[i];\n    }\n\n    Grid grid(si, sj, ti, tj, p, h, v);\n    string path = grid.find_shortest_path();\n    string cycle = grid.find_cycle();\n\n    string result = path;\n    int remaining = 200 - result.size();\n    if (remaining > 0) {\n        int cycle_len = cycle.size();\n        int num_cycles = remaining / cycle_len;\n        for (int i = 0; i < num_cycles; i++) {\n            result += cycle;\n        }\n        // Append partial cycle if needed\n        int extra = remaining % cycle_len;\n        if (extra > 0) {\n            result += cycle.substr(0, extra);\n        }\n    } else {\n        // If path is longer than 200, truncate (but should not happen)\n        result = result.substr(0, 200);\n    }\n\n    cout << result << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int to[8][4] = {\n        {1, 0, -1, -1}, // type 0\n        {3, -1, -1, 0}, // type 1\n        {-1, -1, 3, 2}, // type 2\n        {-1, 2, 1, -1}, // type 3\n        {1, 0, 3, 2}, // type 4\n        {3, 2, 1, 0}, // type 5\n        {2, -1, 0, -1}, // type 6\n        {-1, 3, -1, 1}  // type 7\n    };\n\n    for (int t = 0; t < 100; t++) {\n        vector<string> grid;\n        for (int i = 0; i < 30; i++) {\n            string line;\n            cin >> line;\n            grid.push_back(line);\n        }\n\n        string result(900, '0');\n        for (int i = 0; i < 30; i++) {\n            for (int j = 0; j < 30; j++) {\n                int T = grid[i][j] - '0';\n                bool has_neighbor[4] = {false};\n                if (j > 0) has_neighbor[0] = true;\n                if (i > 0) has_neighbor[1] = true;\n                if (j < 29) has_neighbor[2] = true;\n                if (i < 29) has_neighbor[3] = true;\n\n                int best_R = 0;\n                int best_score = 1000000;\n\n                for (int R = 0; R < 4; R++) {\n                    int score = 0;\n                    for (int d = 0; d < 4; d++) {\n                        if (!has_neighbor[d]) continue;\n                        int d_local = (d - R + 4) % 4;\n                        int e_local = to[T][d_local];\n                        if (e_local == -1) {\n                            score++;\n                        } else {\n                            int e = (e_local + R) % 4;\n                            if (!has_neighbor[e]) {\n                                score++;\n                            }\n                        }\n                    }\n                    if (score < best_score) {\n                        best_score = score;\n                        best_R = R;\n                    }\n                }\n                result[i * 30 + j] = '0' + best_R;\n            }\n        }\n        cout << result << endl;\n    }\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n\nusing namespace std;\n\nint compute_delta(char D, vector<vector<int>> &grid, int er, int ec, int N) {\n    int pr, pc;\n    if (D == 'U') {\n        pr = er - 1;\n        pc = ec;\n    } else if (D == 'D') {\n        pr = er + 1;\n        pc = ec;\n    } else if (D == 'L') {\n        pr = er;\n        pc = ec - 1;\n    } else if (D == 'R') {\n        pr = er;\n        pc = ec + 1;\n    }\n\n    int tile = grid[pr][pc];\n\n    int dr[4] = {-1, 1, 0, 0};\n    int dc[4] = {0, 0, -1, 1};\n    int self_line[4] = {2, 8, 1, 4};\n    int neighbor_line[4] = {8, 2, 4, 1};\n\n    int matches_old = 0;\n    for (int i = 0; i < 4; i++) {\n        int nr = pr + dr[i];\n        int nc = pc + dc[i];\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n        if (grid[nr][nc] == 0) continue;\n        if (tile & self_line[i]) {\n            if (grid[nr][nc] & neighbor_line[i]) {\n                matches_old++;\n            }\n        }\n    }\n\n    int move_index;\n    if (D == 'U') move_index = 0;\n    else if (D == 'D') move_index = 1;\n    else if (D == 'L') move_index = 2;\n    else if (D == 'R') move_index = 3;\n\n    int matches_new = 0;\n    for (int i = 0; i < 4; i++) {\n        if (i == move_index) continue;\n        int nr = er + dr[i];\n        int nc = ec + dc[i];\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n        if (grid[nr][nc] == 0) continue;\n        if (tile & self_line[i]) {\n            if (grid[nr][nc] & neighbor_line[i]) {\n                matches_new++;\n            }\n        }\n    }\n\n    return matches_new - matches_old;\n}\n\nvoid make_move(char D, vector<vector<int>> &grid, int &er, int &ec) {\n    int pr, pc;\n    if (D == 'U') {\n        pr = er - 1;\n        pc = ec;\n    } else if (D == 'D') {\n        pr = er + 1;\n        pc = ec;\n    } else if (D == 'L') {\n        pr = er;\n        pc = ec - 1;\n    } else if (D == 'R') {\n        pr = er;\n        pc = ec + 1;\n    }\n\n    grid[er][ec] = grid[pr][pc];\n    grid[pr][pc] = 0;\n    er = pr;\n    ec = pc;\n}\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n\n    vector<vector<int>> grid(N, vector<int>(N));\n    int empty_row = 0, empty_col = 0;\n\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            char c = s[j];\n            if (c >= '0' && c <= '9') {\n                grid[i][j] = c - '0';\n            } else if (c >= 'a' && c <= 'f') {\n                grid[i][j] = 10 + (c - 'a');\n            } else {\n                grid[i][j] = 0;\n            }\n            if (grid[i][j] == 0) {\n                empty_row = i;\n                empty_col = j;\n            }\n        }\n    }\n\n    int M_current = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == 0) continue;\n            if (j < N-1 && grid[i][j+1] != 0) {\n                if ((grid[i][j] & 4) && (grid[i][j+1] & 1)) {\n                    M_current++;\n                }\n            }\n            if (i < N-1 && grid[i+1][j] != 0) {\n                if ((grid[i][j] & 8) && (grid[i+1][j] & 2)) {\n                    M_current++;\n                }\n            }\n        }\n    }\n\n    int M_max = 2 * N * N - 4;\n    string moves = \"\";\n    int t = 0;\n    double T0 = 10.0;\n\n    srand(time(0));\n\n    while (t < T && M_current < M_max) {\n        int er = empty_row, ec = empty_col;\n        vector<char> directions;\n        if (er > 0) directions.push_back('U');\n        if (er < N-1) directions.push_back('D');\n        if (ec > 0) directions.push_back('L');\n        if (ec < N-1) directions.push_back('R');\n\n        if (directions.empty()) break;\n\n        int idx = rand() % directions.size();\n        char D = directions[idx];\n\n        int delta = compute_delta(D, grid, er, ec, N);\n\n        double temp = T0 * (1.0 - static_cast<double>(t) / T);\n        if (temp < 0) temp = 0;\n\n        bool accept = false;\n        if (delta > 0) {\n            accept = true;\n        } else {\n            double prob = exp(delta / temp);\n            double r = static_cast<double>(rand()) / RAND_MAX;\n            if (prob > r) {\n                accept = true;\n            }\n        }\n\n        if (accept) {\n            make_move(D, grid, empty_row, empty_col);\n            moves += D;\n            M_current += delta;\n        }\n        t++;\n    }\n\n    cout << moves << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int N, K;\n    cin >> N >> K;\n    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10;\n    cin >> a1 >> a2 >> a3 >> a4 >> a5 >> a6 >> a7 >> a8 >> a9 >> a10;\n    vector<pair<int, int>> points;\n    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n        points.push_back({x, y});\n    }\n\n    int V = 50;\n    int H = 50;\n    int start = -10000;\n    int end = 10000;\n    int step = 400;\n\n    cout << K << endl;\n    for (int i = 1; i <= V; i++) {\n        int x = start + i * step;\n        cout << x << \" -1000000000 \" << x << \" 1000000000\" << endl;\n    }\n    for (int i = 1; i <= H; i++) {\n        int y = start + i * step;\n        cout << \"-1000000000 \" << y << \" 1000000000 \" << y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const { return x == other.x && y == other.y; }\n    bool operator<(const Point& other) const {\n        return x < other.x || (x == other.x && y < other.y);\n    }\n};\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nclass RectJoinSolver {\nprivate:\n    int N, M;\n    vector<Point> initial_dots;\n    set<Point> dots;\n    set<pair<Point, Point>> used_segments;\n    vector<Rectangle> operations;\n    vector<vector<int>> weight;\n    Point center;\n    \n    // Precompute weights\n    void precompute_weights() {\n        weight.resize(N, vector<int>(N, 0));\n        center = Point((N-1)/2, (N-1)/2);\n        for (int x = 0; x < N; x++) {\n            for (int y = 0; y < N; y++) {\n                int dx = x - center.x;\n                int dy = y - center.y;\n                weight[x][y] = dx*dx + dy*dy + 1;\n            }\n        }\n    }\n    \n    // Check if point is valid\n    bool is_valid_point(int x, int y) {\n        return x >= 0 && x < N && y >= 0 && y < N;\n    }\n    \n    // Check if point has a dot\n    bool has_dot(int x, int y) {\n        return dots.count(Point(x, y));\n    }\n    \n    // Check if segment is used\n    bool is_segment_used(const Point& a, const Point& b) {\n        if (a < b) return used_segments.count({a, b});\n        return used_segments.count({b, a});\n    }\n    \n    // Get all points on a line segment\n    vector<Point> get_points_on_segment(const Point& a, const Point& b) {\n        vector<Point> points;\n        if (a.x == b.x) { // vertical\n            int y1 = min(a.y, b.y), y2 = max(a.y, b.y);\n            for (int y = y1; y <= y2; y++) {\n                points.push_back(Point(a.x, y));\n            }\n        } else if (a.y == b.y) { // horizontal\n            int x1 = min(a.x, b.x), x2 = max(a.x, b.x);\n            for (int x = x1; x <= x2; x++) {\n                points.push_back(Point(x, a.y));\n            }\n        } else if (abs(a.x - b.x) == abs(a.y - b.y)) { // diagonal\n            int dx = (b.x > a.x) ? 1 : -1;\n            int dy = (b.y > a.y) ? 1 : -1;\n            int steps = abs(a.x - b.x);\n            for (int i = 0; i <= steps; i++) {\n                points.push_back(Point(a.x + i*dx, a.y + i*dy));\n            }\n        }\n        return points;\n    }\n    \n    // Check condition 2: no other dots on perimeter\n    bool check_no_other_dots(const vector<Point>& corners, const Point& new_dot) {\n        set<Point> corner_set(corners.begin(), corners.end());\n        corner_set.insert(new_dot);\n        \n        // Check all four sides\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            vector<Point> segment_points = get_points_on_segment(a, b);\n            for (const Point& p : segment_points) {\n                if (!corner_set.count(p) && has_dot(p.x, p.y)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    // Check condition 3: no overlapping segments\n    bool check_no_overlapping_segments(const vector<Point>& corners) {\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            vector<Point> segment_points = get_points_on_segment(a, b);\n            \n            // Check each segment between consecutive points\n            for (int j = 0; j < (int)segment_points.size() - 1; j++) {\n                Point p1 = segment_points[j];\n                Point p2 = segment_points[j+1];\n                if (is_segment_used(p1, p2)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    // Mark segments as used\n    void mark_segments_used(const vector<Point>& corners) {\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            vector<Point> segment_points = get_points_on_segment(a, b);\n            \n            for (int j = 0; j < (int)segment_points.size() - 1; j++) {\n                Point p1 = segment_points[j];\n                Point p2 = segment_points[j+1];\n                if (p1 < p2) {\n                    used_segments.insert({p1, p2});\n                } else {\n                    used_segments.insert({p2, p1});\n                }\n            }\n        }\n    }\n    \n    // Generate axis-aligned rectangle candidates\n    vector<pair<Point, vector<Point>>> generate_axis_aligned_candidates() {\n        vector<pair<Point, vector<Point>>> candidates;\n        \n        for (const Point& p1 : dots) {\n            for (const Point& p2 : dots) {\n                if (p1 == p2) continue;\n                \n                // Try different combinations for rectangle corners\n                vector<Point> possible_p3 = {\n                    Point(p1.x, p2.y),\n                    Point(p2.x, p1.y)\n                };\n                \n                for (const Point& p3 : possible_p3) {\n                    if (!is_valid_point(p3.x, p3.y)) continue;\n                    \n                    // Calculate the fourth point\n                    Point p4 = Point(p2.x + p1.x - p3.x, p2.y + p1.y - p3.y);\n                    if (!is_valid_point(p4.x, p4.y)) continue;\n                    \n                    // Check if p3 has dot and p4 is free\n                    if (has_dot(p3.x, p3.y) && !has_dot(p4.x, p4.y)) {\n                        vector<Point> corners = {p1, p3, p2, p4};\n                        candidates.push_back({p4, corners});\n                    }\n                }\n            }\n        }\n        \n        return candidates;\n    }\n    \n    // Generate 45-degree rotated rectangle candidates\n    vector<pair<Point, vector<Point>>> generate_rotated_candidates() {\n        vector<pair<Point, vector<Point>>> candidates;\n        \n        for (const Point& p1 : dots) {\n            for (const Point& p2 : dots) {\n                if (p1 == p2) continue;\n                \n                int dx = p2.x - p1.x;\n                int dy = p2.y - p1.y;\n                \n                // Check if this could be a diagonal of a square\n                if (abs(dx) == abs(dy) && dx != 0) {\n                    // Try both possible squares\n                    vector<Point> possible_p3 = {\n                        Point(p1.x + dy, p1.y + dx),  // rotated 90 degrees\n                        Point(p1.x - dy, p1.y - dx)   // rotated -90 degrees\n                    };\n                    \n                    for (const Point& p3 : possible_p3) {\n                        if (!is_valid_point(p3.x, p3.y)) continue;\n                        \n                        Point p4 = Point(p2.x + (p3.x - p1.x), p2.y + (p3.y - p1.y));\n                        if (!is_valid_point(p4.x, p4.y)) continue;\n                        \n                        // Check if p3 has dot and p4 is free\n                        if (has_dot(p3.x, p3.y) && !has_dot(p4.x, p4.y)) {\n                            vector<Point> corners = {p1, p3, p2, p4};\n                            candidates.push_back({p4, corners});\n                        }\n                    }\n                }\n            }\n        }\n        \n        return candidates;\n    }\n    \npublic:\n    RectJoinSolver(int N, int M, const vector<Point>& initial_dots) \n        : N(N), M(M), initial_dots(initial_dots) {\n        precompute_weights();\n        for (const Point& p : initial_dots) {\n            dots.insert(p);\n        }\n    }\n    \n    void solve() {\n        bool found_operation = true;\n        int max_operations = N * N - M; // Maximum possible operations\n        \n        while (found_operation && operations.size() < max_operations) {\n            found_operation = false;\n            Rectangle best_operation(Point(0,0), Point(0,0), Point(0,0), Point(0,0));\n            int best_score = -1;\n            \n            // Generate candidates from both types of rectangles\n            vector<pair<Point, vector<Point>>> candidates;\n            \n            auto axis_candidates = generate_axis_aligned_candidates();\n            candidates.insert(candidates.end(), axis_candidates.begin(), axis_candidates.end());\n            \n            auto rotated_candidates = generate_rotated_candidates();\n            candidates.insert(candidates.end(), rotated_candidates.begin(), rotated_candidates.end());\n            \n            // Evaluate candidates\n            for (auto& candidate : candidates) {\n                Point new_dot = candidate.first;\n                vector<Point> corners = candidate.second;\n                \n                if (check_no_other_dots(corners, new_dot) && \n                    check_no_overlapping_segments(corners)) {\n                    \n                    int score = weight[new_dot.x][new_dot.y];\n                    if (score > best_score) {\n                        best_score = score;\n                        best_operation = Rectangle(new_dot, corners[0], corners[1], corners[2]);\n                        found_operation = true;\n                    }\n                }\n            }\n            \n            if (found_operation) {\n                // Add the best operation\n                operations.push_back(best_operation);\n                dots.insert(best_operation.p1);\n                \n                // Mark segments as used\n                vector<Point> corners = {\n                    best_operation.p1, best_operation.p2, \n                    best_operation.p3, best_operation.p4\n                };\n                mark_segments_used(corners);\n            }\n        }\n    }\n    \n    void output() {\n        cout << operations.size() << endl;\n        for (const Rectangle& rect : operations) {\n            cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n                 << rect.p2.x << \" \" << rect.p2.y << \" \"\n                 << rect.p3.x << \" \" << rect.p3.y << \" \"\n                 << rect.p4.x << \" \" << rect.p4.y << endl;\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    cin >> N >> M;\n    \n    vector<Point> initial_dots(M);\n    for (int i = 0; i < M; i++) {\n        cin >> initial_dots[i].x >> initial_dots[i].y;\n    }\n    \n    RectJoinSolver solver(N, M, initial_dots);\n    solver.solve();\n    solver.output();\n    \n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\nusing namespace std;\n\nvector<vector<int>> tilt_grid(const vector<vector<int>>& state, char direction) {\n    int n = 10;\n    vector<vector<int>> new_state(11, vector<int>(11, 0));\n    if (direction == 'L') {\n        for (int i = 1; i <= n; i++) {\n            vector<int> non_empty;\n            for (int j = 1; j <= n; j++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int j = 1; j <= k; j++) {\n                new_state[i][j] = non_empty[j-1];\n            }\n            for (int j = k+1; j <= n; j++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'R') {\n        for (int i = 1; i <= n; i++) {\n            vector<int> non_empty;\n            for (int j = 1; j <= n; j++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int j = 1; j <= k; j++) {\n                new_state[i][n - k + j] = non_empty[j-1];\n            }\n            for (int j = 1; j <= n-k; j++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'F') {\n        for (int j = 1; j <= n; j++) {\n            vector<int> non_empty;\n            for (int i = 1; i <= n; i++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int i = 1; i <= k; i++) {\n                new_state[i][j] = non_empty[i-1];\n            }\n            for (int i = k+1; i <= n; i++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'B') {\n        for (int j = 1; j <= n; j++) {\n            vector<int> non_empty;\n            for (int i = 1; i <= n; i++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int i = 1; i <= k; i++) {\n                new_state[n - k + i][j] = non_empty[i-1];\n            }\n            for (int i = 1; i <= n-k; i++) {\n                new_state[i][j] = 0;\n            }\n        }\n    }\n    return new_state;\n}\n\nint compute_score(const vector<vector<int>>& grid) {\n    vector<vector<bool>> visited(11, vector<bool>(11, false));\n    int score = 0;\n    for (int i = 1; i <= 10; i++) {\n        for (int j = 1; j <= 10; j++) {\n            if (!visited[i][j] && grid[i][j] != 0) {\n                int flavor = grid[i][j];\n                int size = 0;\n                queue<pair<int, int>> q;\n                q.push({i, j});\n                visited[i][j] = true;\n                while (!q.empty()) {\n                    pair<int, int> pos = q.front();\n                    q.pop();\n                    int x = pos.first, y = pos.second;\n                    size++;\n                    int dx[] = {1, -1, 0, 0};\n                    int dy[] = {0, 0, 1, -1};\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d], ny = y + dy[d];\n                        if (nx >= 1 && nx <= 10 && ny >= 1 && ny <= 10 && !visited[nx][ny] && grid[nx][ny] == flavor) {\n                            visited[nx][ny] = true;\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n                score += size * size;\n            }\n        }\n    }\n    return score;\n}\n\nint main() {\n    int f[101];\n    for (int i = 1; i <= 100; i++) {\n        cin >> f[i];\n    }\n\n    vector<vector<int>> grid(11, vector<int>(11, 0));\n\n    for (int t = 1; t <= 100; t++) {\n        int p;\n        cin >> p;\n\n        int count = 0;\n        int i_place = 0, j_place = 0;\n        for (int i = 1; i <= 10; i++) {\n            for (int j = 1; j <= 10; j++) {\n                if (grid[i][j] == 0) {\n                    count++;\n                    if (count == p) {\n                        i_place = i;\n                        j_place = j;\n                        break;\n                    }\n                }\n            }\n            if (j_place != 0) break;\n        }\n\n        grid[i_place][j_place] = f[t];\n\n        vector<char> directions = {'F', 'B', 'L', 'R'};\n        int best_score = -1;\n        char best_dir = 'F';\n        for (char dir : directions) {\n            vector<vector<int>> new_grid = tilt_grid(grid, dir);\n            int score = compute_score(new_grid);\n            if (score > best_score) {\n                best_score = score;\n                best_dir = dir;\n            }\n        }\n\n        cout << best_dir << endl;\n        cout.flush();\n\n        grid = tilt_grid(grid, best_dir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <string>\n\nusing namespace std;\n\nint main() {\n    int M;\n    double eps;\n    cin >> M >> eps;\n\n    const int N = 20;\n    const int T = N * (N - 1) / 2;\n\n    vector<int> offset(N);\n    offset[0] = 0;\n    for (int i = 1; i < N; i++) {\n        offset[i] = offset[i - 1] + (N - i);\n    }\n\n    cout << N << endl;\n\n    vector<vector<int>> deg_sequences(M);\n\n    for (int k = 0; k < M; k++) {\n        string g;\n        g.append(k, '1');\n        g.append(T - k, '0');\n        cout << g << endl;\n\n        vector<int> deg(N, 0);\n        for (int i = 0; i < N; i++) {\n            for (int j = i + 1; j < N; j++) {\n                int idx = offset[i] + (j - i - 1);\n                if (g[idx] == '1') {\n                    deg[i]++;\n                }\n            }\n            for (int j = 0; j < i; j++) {\n                int idx = offset[j] + (i - j - 1);\n                if (g[idx] == '1') {\n                    deg[i]++;\n                }\n            }\n        }\n        sort(deg.begin(), deg.end());\n        deg_sequences[k] = deg;\n    }\n\n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n\n        vector<int> deg_H(N, 0);\n        for (int i = 0; i < N; i++) {\n            for (int j = i + 1; j < N; j++) {\n                int idx = offset[i] + (j - i - 1);\n                if (H[idx] == '1') {\n                    deg_H[i]++;\n                }\n            }\n            for (int j = 0; j < i; j++) {\n                int idx = offset[j] + (i - j - 1);\n                if (H[idx] == '1') {\n                    deg_H[i]++;\n                }\n            }\n        }\n        sort(deg_H.begin(), deg_H.end());\n\n        int best_k = 0;\n        double min_dist = 1e9;\n        for (int k = 0; k < M; k++) {\n            double dist = 0.0;\n            for (int i = 0; i < N; i++) {\n                int diff = deg_H[i] - deg_sequences[k][i];\n                dist += diff * diff;\n            }\n            dist = sqrt(dist);\n            if (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 <algorithm>\n#include <queue>\n#include <limits>\n#include <tuple>\n\nusing namespace std;\n\nconst int INF = 1000000000;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    vector<tuple<int, int, int>> edges;\n    for (int i = 0; i < M; i++) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges.push_back({u, v, w});\n    }\n\n    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n        // Coordinates are read but not used in this solution\n    }\n\n    vector<vector<pair<int, int>>> graph(N + 1);\n    vector<vector<int>> edge_index(N + 1, vector<int>(N + 1, -1));\n\n    for (int i = 0; i < M; i++) {\n        int u = get<0>(edges[i]);\n        int v = get<1>(edges[i]);\n        int w = get<2>(edges[i]);\n        graph[u].emplace_back(v, w);\n        graph[v].emplace_back(u, w);\n        edge_index[u][v] = i;\n        edge_index[v][u] = i;\n    }\n\n    vector<double> betweenness(M, 0.0);\n\n    for (int s = 1; s <= N; s++) {\n        vector<int> dist(N + 1, INF);\n        dist[s] = 0;\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n        pq.push({0, s});\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            for (auto [v, w] : graph[u]) {\n                int new_d = d + w;\n                if (new_d < dist[v]) {\n                    dist[v] = new_d;\n                    pq.push({new_d, v});\n                }\n            }\n        }\n\n        vector<double> sigma(N + 1, 0.0);\n        sigma[s] = 1.0;\n\n        vector<int> vertices(N);\n        for (int i = 0; i < N; i++) {\n            vertices[i] = i + 1;\n        }\n        sort(vertices.begin(), vertices.end(), [&](int a, int b) {\n            return dist[a] < dist[b];\n        });\n\n        for (int v : vertices) {\n            if (v == s) continue;\n            for (auto [u, w] : graph[v]) {\n                if (dist[u] + w == dist[v]) {\n                    sigma[v] += sigma[u];\n                }\n            }\n        }\n\n        vector<double> delta(N + 1, 0.0);\n        sort(vertices.begin(), vertices.end(), [&](int a, int b) {\n            return dist[a] > dist[b];\n        });\n\n        for (int v : vertices) {\n            if (v == s) continue;\n            for (auto [u, w] : graph[v]) {\n                if (dist[u] + w == dist[v]) {\n                    double c = sigma[u] / sigma[v] * (1.0 + delta[v]);\n                    int idx = edge_index[u][v];\n                    if (idx != -1) {\n                        betweenness[idx] += c;\n                    }\n                    delta[u] += c;\n                }\n            }\n        }\n    }\n\n    vector<int> edge_indices(M);\n    for (int i = 0; i < M; i++) {\n        edge_indices[i] = i;\n    }\n    sort(edge_indices.begin(), edge_indices.end(), [&](int a, int b) {\n        return betweenness[a] > betweenness[b];\n    });\n\n    vector<int> assignment(M);\n    for (int i = 0; i < M; i++) {\n        assignment[edge_indices[i]] = (i % D) + 1;\n    }\n\n    for (int i = 0; i < M; i++) {\n        cout << assignment[i];\n        if (i < M - 1) {\n            cout << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <queue>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\nint main() {\n    int D;\n    cin >> D;\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 required positions for each silhouette\n    set<tuple<int, int, int>> M1, M2;\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 (f1[z][x] == '1' && r1[z][y] == '1') {\n                    M1.insert({x, y, z});\n                }\n                if (f2[z][x] == '1' && r2[z][y] == '1') {\n                    M2.insert({x, y, z});\n                }\n            }\n        }\n    }\n\n    // Find intersection of required positions\n    set<tuple<int, int, int>> I;\n    set_intersection(M1.begin(), M1.end(), M2.begin(), M2.end(),\n                    inserter(I, I.begin()));\n\n    // 6-directional neighbors\n    vector<tuple<int, int, int>> directions = {\n        {1, 0, 0}, {-1, 0, 0},\n        {0, 1, 0}, {0, -1, 0},\n        {0, 0, 1}, {0, 0, -1}\n    };\n\n    // Find connected components in intersection\n    map<tuple<int, int, int>, int> comp_id;\n    int comp_count = 0;\n    \n    for (const auto& coord : I) {\n        if (comp_id.count(coord)) continue;\n        \n        comp_count++;\n        queue<tuple<int, int, int>> q;\n        q.push(coord);\n        comp_id[coord] = comp_count;\n        \n        while (!q.empty()) {\n            auto [x, y, z] = q.front();\n            q.pop();\n            \n            for (auto [dx, dy, dz] : directions) {\n                int nx = x + dx, ny = y + dy, nz = z + dz;\n                tuple<int, int, int> neighbor = {nx, ny, nz};\n                \n                if (I.count(neighbor) && !comp_id.count(neighbor)) {\n                    comp_id[neighbor] = comp_count;\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n\n    // Calculate total blocks\n    int n = comp_count + (M1.size() - I.size()) + (M2.size() - I.size());\n    \n    // Create output arrays\n    vector<int> arr1(D * D * D, 0), arr2(D * D * D, 0);\n    \n    // Assign blocks for first arrangement\n    int id_counter = comp_count + 1;\n    map<tuple<int, int, int>, int> id_map1;\n    \n    for (const auto& coord : M1) {\n        auto [x, y, z] = coord;\n        int idx = x * D * D + y * D + z;\n        \n        if (I.count(coord)) {\n            arr1[idx] = comp_id[coord];\n        } else {\n            if (!id_map1.count(coord)) {\n                id_map1[coord] = id_counter++;\n            }\n            arr1[idx] = id_map1[coord];\n        }\n    }\n    \n    // Assign blocks for second arrangement\n    map<tuple<int, int, int>, int> id_map2;\n    \n    for (const auto& coord : M2) {\n        auto [x, y, z] = coord;\n        int idx = x * D * D + y * D + z;\n        \n        if (I.count(coord)) {\n            arr2[idx] = comp_id[coord];\n        } else {\n            if (!id_map2.count(coord)) {\n                id_map2[coord] = id_counter++;\n            }\n            arr2[idx] = id_map2[coord];\n        }\n    }\n    \n    // Output results\n    cout << n << endl;\n    \n    for (int i = 0; i < D * D * D; i++) {\n        cout << arr1[i] << (i == D * D * D - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    for (int i = 0; i < D * D * D; i++) {\n        cout << arr2[i] << (i == D * D * D - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <tuple>\n#include <iostream>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read input\n    int N, M, K;\n    cin >> N >> M >> K;\n    \n    vector<ll> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<tuple<int, int, ll>> edges(M);\n    for (int i = 0; i < M; i++) {\n        int u, v;\n        ll w;\n        cin >> u >> v >> w;\n        edges[i] = {u-1, v-1, w};\n    }\n    \n    vector<ll> a(K), b(K);\n    for (int i = 0; i < K; i++) {\n        cin >> a[i] >> b[i];\n    }\n    \n    // Step 1: Assign residents to nearest stations\n    vector<vector<int>> station_residents(N);\n    \n    for (int k = 0; k < K; k++) {\n        ll min_dist = 1e18;\n        int best_station = 0;\n        \n        for (int i = 0; i < N; i++) {\n            ll dx = x[i] - a[k];\n            ll dy = y[i] - b[k];\n            ll dist_sq = dx * dx + dy * dy;\n            \n            if (dist_sq < min_dist) {\n                min_dist = dist_sq;\n                best_station = i;\n            }\n        }\n        station_residents[best_station].push_back(k);\n    }\n    \n    // Step 2: Calculate required power for each station\n    vector<ll> P(N, 0);\n    for (int i = 0; i < N; i++) {\n        if (station_residents[i].empty()) continue;\n        \n        ll max_dist_sq = 0;\n        for (int k : station_residents[i]) {\n            ll dx = x[i] - a[k];\n            ll dy = y[i] - b[k];\n            ll dist_sq = dx * dx + dy * dy;\n            max_dist_sq = max(max_dist_sq, dist_sq);\n        }\n        \n        // P_i = ceil(sqrt(max_dist_sq)) but we need to be careful with integer math\n        ll dist = sqrt(max_dist_sq);\n        if (dist * dist < max_dist_sq) dist++;\n        P[i] = min(5000LL, dist); // Cap at 5000\n    }\n    \n    // Step 3: Build MST to connect stations with P_i > 0 to root\n    vector<bool> used_station(N, false);\n    used_station[0] = true; // Root is always used\n    \n    // Mark stations that need to be connected (those with residents assigned)\n    for (int i = 0; i < N; i++) {\n        if (P[i] > 0) {\n            used_station[i] = true;\n        }\n    }\n    \n    // Build complete graph distances between used stations\n    vector<vector<ll>> dist_matrix(N, vector<ll>(N, 1e18));\n    for (int i = 0; i < N; i++) {\n        dist_matrix[i][i] = 0;\n    }\n    \n    for (auto& [u, v, w] : edges) {\n        dist_matrix[u][v] = min(dist_matrix[u][v], w);\n        dist_matrix[v][u] = min(dist_matrix[v][u], w);\n    }\n    \n    // Floyd-Warshall for shortest paths\n    for (int k = 0; k < N; k++) {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (dist_matrix[i][k] < 1e18 && dist_matrix[k][j] < 1e18) {\n                    dist_matrix[i][j] = min(dist_matrix[i][j], \n                                           dist_matrix[i][k] + dist_matrix[k][j]);\n                }\n            }\n        }\n    }\n    \n    // Prim's algorithm to build MST on used stations\n    vector<bool> in_mst(N, false);\n    vector<ll> key(N, 1e18);\n    vector<int> parent(N, -1);\n    \n    priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n    \n    // Start from root\n    key[0] = 0;\n    pq.push({0, 0});\n    \n    while (!pq.empty()) {\n        int u = pq.top().second;\n        pq.pop();\n        \n        if (in_mst[u] || !used_station[u]) continue;\n        in_mst[u] = true;\n        \n        for (int v = 0; v < N; v++) {\n            if (used_station[v] && !in_mst[v] && dist_matrix[u][v] < key[v]) {\n                key[v] = dist_matrix[u][v];\n                parent[v] = u;\n                pq.push({key[v], v});\n            }\n        }\n    }\n    \n    // Step 4: Determine which edges to turn ON\n    vector<bool> edge_on(M, false);\n    \n    // For each station in MST, find path to its parent in the original graph\n    for (int i = 0; i < N; i++) {\n        if (parent[i] != -1) {\n            // Find shortest path from i to parent[i] in original graph\n            // Use BFS on original graph with the given weights\n            vector<ll> dist(N, 1e18);\n            vector<int> prev(N, -1);\n            vector<int> edge_index(N, -1);\n            \n            priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> dijkstra;\n            dist[i] = 0;\n            dijkstra.push({0, i});\n            \n            while (!dijkstra.empty()) {\n                auto [d, u] = dijkstra.top();\n                dijkstra.pop();\n                \n                if (u == parent[i]) break;\n                if (d > dist[u]) continue;\n                \n                for (int j = 0; j < M; j++) {\n                    auto [u1, v1, w1] = edges[j];\n                    if (u1 == u) {\n                        if (dist[v1] > dist[u] + w1) {\n                            dist[v1] = dist[u] + w1;\n                            prev[v1] = u;\n                            edge_index[v1] = j;\n                            dijkstra.push({dist[v1], v1});\n                        }\n                    }\n                    if (v1 == u) {\n                        if (dist[u1] > dist[u] + w1) {\n                            dist[u1] = dist[u] + w1;\n                            prev[u1] = u;\n                            edge_index[u1] = j;\n                            dijkstra.push({dist[u1], u1});\n                        }\n                    }\n                }\n            }\n            \n            // Mark edges along the path\n            int current = parent[i];\n            while (prev[current] != -1) {\n                edge_on[edge_index[current]] = true;\n                current = prev[current];\n            }\n        }\n    }\n    \n    // Also include edges that directly connect used stations if they're cheap\n    for (int j = 0; j < M; j++) {\n        auto [u, v, w] = edges[j];\n        if ((used_station[u] && used_station[v]) && w == dist_matrix[u][v]) {\n            edge_on[j] = true;\n        }\n    }\n    \n    // Output results\n    for (int i = 0; i < N; i++) {\n        cout << P[i];\n        if (i < N-1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    for (int j = 0; j < M; j++) {\n        cout << (edge_on[j] ? 1 : 0);\n        if (j < M-1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <tuple>\nusing namespace std;\n\nconst int N = 30;\n\nint main() {\n    vector<vector<int>> pyramid(N);\n    for (int x = 0; x < N; x++) {\n        for (int y = 0; y <= x; y++) {\n            int num;\n            cin >> num;\n            pyramid[x].push_back(num);\n        }\n    }\n\n    vector<tuple<int, int, int, int>> swaps;\n\n    for (int x = N-2; x >= 0; x--) {\n        for (int y = 0; y <= x; y++) {\n            int current_x = x;\n            int current_y = y;\n            while (current_x < N-1) {\n                int child1_x = current_x + 1;\n                int child1_y = current_y;\n                int child2_x = current_x + 1;\n                int child2_y = current_y + 1;\n\n                int current_val = pyramid[current_x][current_y];\n                int child1_val = pyramid[child1_x][child1_y];\n                int child2_val = pyramid[child2_x][child2_y];\n\n                if (current_val <= child1_val && current_val <= child2_val) {\n                    break;\n                }\n\n                int swap_x, swap_y;\n                if (child1_val <= child2_val) {\n                    swap_x = child1_x;\n                    swap_y = child1_y;\n                } else {\n                    swap_x = child2_x;\n                    swap_y = child2_y;\n                }\n\n                swap(pyramid[current_x][current_y], pyramid[swap_x][swap_y]);\n                swaps.push_back({current_x, current_y, swap_x, swap_y});\n\n                current_x = swap_x;\n                current_y = swap_y;\n            }\n        }\n    }\n\n    cout << swaps.size() << endl;\n    for (const auto& swap : swaps) {\n        cout << get<0>(swap) << \" \" << get<1>(swap) << \" \" << get<2>(swap) << \" \" << get<3>(swap) << endl;\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = 4;\n\nvector<vector<int>> grid;\nvector<pair<int, int>> container_positions;\n\n// Directions: up, down, left, right\nconst int di[] = {-1, 1, 0, 0};\nconst int dj[] = {0, 0, -1, 1};\n\n// Check if a position is valid and empty\nbool is_valid(int i, int j) {\n    return i >= 0 && i < D && j >= 0 && j < D && grid[i][j] == -1;\n}\n\n// BFS to find reachable positions from entrance\nvector<pair<int, int>> get_reachable_positions() {\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> reachable;\n    \n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            \n            if (ni >= 0 && ni < D && nj >= 0 && nj < D && \n                !visited[ni][nj] && grid[ni][nj] == -1) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                reachable.push_back({ni, nj});\n            }\n        }\n    }\n    \n    return reachable;\n}\n\n// Calculate Manhattan distance from entrance\nint distance_from_entrance(int i, int j) {\n    return abs(i - ENTRANCE_I) + abs(j - ENTRANCE_J);\n}\n\n// Find best position for placement based on container number\npair<int, int> find_best_position(int container_num, int total_containers) {\n    auto reachable = get_reachable_positions();\n    \n    if (reachable.empty()) {\n        // Should not happen if grid is properly connected\n        for (int i = 0; i < D; i++) {\n            for (int j = 0; j < D; j++) {\n                if (grid[i][j] == -1) {\n                    return {i, j};\n                }\n            }\n        }\n    }\n    \n    // Sort positions by distance from entrance\n    sort(reachable.begin(), reachable.end(), [](const pair<int, int>& a, const pair<int, int>& b) {\n        int dist_a = distance_from_entrance(a.first, a.second);\n        int dist_b = distance_from_entrance(b.first, b.second);\n        return dist_a < dist_b;\n    });\n    \n    // Use container number to determine placement strategy\n    // Lower numbers should be placed closer to exit for easier retrieval\n    int idx = (container_num * reachable.size()) / total_containers;\n    idx = min(idx, (int)reachable.size() - 1);\n    \n    return reachable[idx];\n}\n\n// Get accessible containers for retrieval\nvector<pair<int, int>> get_accessible_containers() {\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> accessible;\n    \n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        // Check if current position has a container\n        if (grid[i][j] >= 0) {\n            accessible.push_back({i, j});\n        }\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            \n            if (ni >= 0 && ni < D && nj >= 0 && nj < D && \n                !visited[ni][nj] && grid[ni][nj] != -2) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    return accessible;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read warehouse configuration\n    int N;\n    cin >> D >> N;\n    \n    // Initialize grid: -2 = obstacle, -1 = empty, >=0 = container number\n    grid.assign(D, vector<int>(D, -1));\n    container_positions.clear();\n    \n    // Mark entrance and adjacent squares\n    grid[ENTRANCE_I][ENTRANCE_J] = -3; // Entrance\n    grid[ENTRANCE_I][ENTRANCE_J-1] = -1;\n    grid[ENTRANCE_I][ENTRANCE_J+1] = -1;\n    grid[ENTRANCE_I+1][ENTRANCE_J] = -1;\n    \n    // Read obstacles\n    for (int k = 0; k < N; k++) {\n        int ri, rj;\n        cin >> ri >> rj;\n        grid[ri][rj] = -2; // Obstacle\n    }\n    \n    int total_containers = D * D - 1 - N;\n    \n    // Process container arrivals\n    for (int d = 0; d < total_containers; d++) {\n        int container_num;\n        cin >> container_num;\n        \n        // Find best position for this container\n        auto [pi, pj] = find_best_position(container_num, total_containers);\n        \n        // Place container\n        grid[pi][pj] = container_num;\n        container_positions.push_back({pi, pj});\n        \n        // Output placement\n        cout << pi << \" \" << pj << endl;\n        cout.flush();\n    }\n    \n    // Determine retrieval order using greedy strategy\n    vector<pair<int, int>> retrieval_order;\n    \n    while (retrieval_order.size() < total_containers) {\n        auto accessible = get_accessible_containers();\n        \n        if (accessible.empty()) {\n            break; // Should not happen\n        }\n        \n        // Find container with smallest number\n        int best_idx = 0;\n        int best_num = grid[accessible[0].first][accessible[0].second];\n        \n        for (int i = 1; i < accessible.size(); i++) {\n            int current_num = grid[accessible[i].first][accessible[i].second];\n            if (current_num < best_num) {\n                best_num = current_num;\n                best_idx = i;\n            }\n        }\n        \n        auto [qi, qj] = accessible[best_idx];\n        retrieval_order.push_back({qi, qj});\n        grid[qi][qj] = -1; // Remove container\n    }\n    \n    // Output retrieval order\n    for (auto [qi, qj] : retrieval_order) {\n        cout << qi << \" \" << qj << endl;\n    }\n    cout.flush();\n    \n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> grid(n, vector<int>(n));\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> grid[i][j];\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cout << grid[i][j];\n            if (j < n - 1) cout << \" \";\n        }\n        cout << endl;\n    }\n    \n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <set>\n\nusing namespace std;\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n\n    vector<int> wins(N, 0);\n    vector<int> comp(N, 0);\n\n    vector<pair<int, int>> distinct_pairs;\n    for (int i = 0; i < N; i++) {\n        for (int j = i + 1; j < N; j++) {\n            distinct_pairs.push_back({i, j});\n        }\n    }\n\n    random_device rd;\n    mt19937 g(rd());\n    shuffle(distinct_pairs.begin(), distinct_pairs.end(), g);\n\n    vector<pair<int, int>> query_pairs;\n    int L = distinct_pairs.size();\n    for (int i = 0; i < Q; i++) {\n        query_pairs.push_back(distinct_pairs[i % L]);\n    }\n\n    set<pair<int, int>> compared_set;\n\n    for (int q = 0; q < Q; q++) {\n        int i = query_pairs[q].first;\n        int j = query_pairs[q].second;\n\n        cout << \"1 1 \" << i << \" \" << j << endl;\n        cout.flush();\n\n        string result;\n        cin >> result;\n\n        if (compared_set.find({i, j}) == compared_set.end()) {\n            compared_set.insert({i, j});\n            comp[i]++;\n            comp[j]++;\n            if (result == \">\") {\n                wins[i]++;\n            } else if (result == \"<\") {\n                wins[j]++;\n            }\n        }\n    }\n\n    vector<double> scores(N);\n    for (int i = 0; i < N; i++) {\n        if (comp[i] > 0) {\n            scores[i] = static_cast<double>(wins[i]) / comp[i];\n        } else {\n            scores[i] = 0.5;\n        }\n    }\n\n    double lambda = 0.00001;\n    vector<double> est_weights(N);\n    for (int i = 0; i < N; i++) {\n        double p = scores[i];\n        p = max(p, 0.000001);\n        p = min(p, 0.999999);\n        est_weights[i] = -log(1.0 - p) / lambda;\n    }\n\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n    sort(indices.begin(), indices.end(), [&est_weights](int a, int b) {\n        return est_weights[a] > est_weights[b];\n    });\n\n    vector<double> bin_sums(D, 0.0);\n    vector<int> assignment(N);\n    for (int idx : indices) {\n        int min_bin = 0;\n        for (int b = 1; b < D; b++) {\n            if (bin_sums[b] < bin_sums[min_bin]) {\n                min_bin = b;\n            }\n        }\n        assignment[idx] = min_bin;\n        bin_sums[min_bin] += est_weights[idx];\n    }\n\n    for (int i = 0; i < N; i++) {\n        cout << assignment[i];\n        if (i < N - 1) {\n            cout << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <queue>\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    \n    vector<vector<int>> stacks(m + 1);\n    vector<int> box_pos(n + 1, -1); // stack index for each box\n    vector<int> box_height(n + 1, -1); // height in stack for each box\n    \n    // Read initial configuration\n    for (int i = 1; i <= m; i++) {\n        for (int j = 0; j < n / m; j++) {\n            int box;\n            cin >> box;\n            stacks[i].push_back(box);\n            box_pos[box] = i;\n            box_height[box] = j + 1;\n        }\n    }\n    \n    vector<pair<int, int>> operations;\n    int next_box = 1;\n    vector<bool> carried_out(n + 1, false);\n    \n    // Precompute target stack for each box\n    vector<int> target_stack(n + 1);\n    int boxes_per_stack = n / m;\n    for (int i = 1; i <= n; i++) {\n        // Assign boxes to stacks in ranges\n        target_stack[i] = (i - 1) / boxes_per_stack + 1;\n        if (target_stack[i] > m) target_stack[i] = m;\n    }\n    \n    while (next_box <= n) {\n        // Check if next_box is already at top and can be carried out\n        int current_stack = box_pos[next_box];\n        int current_height = box_height[next_box];\n        \n        // Check if next_box is at top of its stack\n        bool is_top = true;\n        for (int box : stacks[current_stack]) {\n            if (box == next_box) {\n                // Check if there are boxes above it\n                auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), next_box);\n                if (it != stacks[current_stack].end() - 1) {\n                    is_top = false;\n                }\n                break;\n            }\n        }\n        \n        if (is_top) {\n            // Carry out the box\n            operations.push_back({next_box, 0});\n            carried_out[next_box] = true;\n            \n            // Remove from stack\n            auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), next_box);\n            if (it != stacks[current_stack].end()) {\n                stacks[current_stack].erase(it);\n            }\n            \n            next_box++;\n            continue;\n        }\n        \n        // next_box is not at top, need to move boxes above it\n        // Find the boxes above next_box in its current stack\n        vector<int> boxes_to_move;\n        bool found_next = false;\n        \n        for (int box : stacks[current_stack]) {\n            if (box == next_box) {\n                found_next = true;\n                continue;\n            }\n            if (found_next && !carried_out[box]) {\n                boxes_to_move.push_back(box);\n            }\n        }\n        \n        if (boxes_to_move.empty()) {\n            // This shouldn't happen if next_box is not at top\n            next_box++;\n            continue;\n        }\n        \n        // Choose destination stack - prefer target stack or empty stacks\n        int dest_stack = -1;\n        \n        // First try: move to target stack of the top box in the moving segment\n        int top_box = boxes_to_move.back();\n        int preferred_dest = target_stack[top_box];\n        \n        if (preferred_dest != current_stack && !carried_out[top_box]) {\n            dest_stack = preferred_dest;\n        } else {\n            // Find an empty stack or one with minimal disruption\n            for (int i = 1; i <= m; i++) {\n                if (i != current_stack && stacks[i].size() < boxes_per_stack) {\n                    dest_stack = i;\n                    break;\n                }\n            }\n            \n            // If no suitable stack found, use the one with most space\n            if (dest_stack == -1) {\n                for (int i = 1; i <= m; i++) {\n                    if (i != current_stack) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n        }\n        \n        if (dest_stack == -1) {\n            // Fallback: use stack 1 if all else fails\n            dest_stack = 1;\n            if (dest_stack == current_stack) dest_stack = 2;\n        }\n        \n        // Move the top box in the blocking segment\n        int box_to_move = boxes_to_move.back();\n        operations.push_back({box_to_move, dest_stack});\n        \n        // Update stack configuration\n        auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), box_to_move);\n        if (it != stacks[current_stack].end()) {\n            // Move this box and all boxes above it to destination stack\n            vector<int> moving_boxes(it, stacks[current_stack].end());\n            stacks[current_stack].erase(it, stacks[current_stack].end());\n            \n            // Add to destination stack\n            stacks[dest_stack].insert(stacks[dest_stack].end(), moving_boxes.begin(), moving_boxes.end());\n            \n            // Update positions\n            for (int i = 0; i < moving_boxes.size(); i++) {\n                box_pos[moving_boxes[i]] = dest_stack;\n                box_height[moving_boxes[i]] = stacks[dest_stack].size() - moving_boxes.size() + i + 1;\n            }\n        }\n        \n        // Safety check to prevent infinite loops\n        if (operations.size() > 4500) {\n            // Force carry out if we're approaching limit\n            for (int i = 1; i <= n; i++) {\n                if (!carried_out[i] && box_height[i] == (int)stacks[box_pos[i]].size()) {\n                    operations.push_back({i, 0});\n                    carried_out[i] = true;\n                    auto it2 = find(stacks[box_pos[i]].begin(), stacks[box_pos[i]].end(), i);\n                    if (it2 != stacks[box_pos[i]].end()) {\n                        stacks[box_pos[i]].erase(it2);\n                    }\n                }\n            }\n            break;\n        }\n    }\n    \n    // Output operations\n    for (auto op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n    \n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <cmath>\nusing namespace std;\n\nint main() {\n    int N;\n    cin >> N;\n    \n    vector<string> h(N-1);\n    for (int i = 0; i < N-1; i++) {\n        cin >> h[i];\n    }\n    \n    vector<string> v(N);\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\n    }\n    \n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n        }\n    }\n    \n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    queue<pair<int, int>> q;\n    dist[0][0] = 0;\n    q.push({0, 0});\n    \n    while (!q.empty()) {\n        int i = q.front().first;\n        int j = q.front().second;\n        q.pop();\n        \n        if (i > 0 && h[i-1][j] == '0') {\n            if (dist[i-1][j] == -1) {\n                dist[i-1][j] = dist[i][j] + 1;\n                q.push({i-1, j});\n            }\n        }\n        if (i < N-1 && h[i][j] == '0') {\n            if (dist[i+1][j] == -1) {\n                dist[i+1][j] = dist[i][j] + 1;\n                q.push({i+1, j});\n            }\n        }\n        if (j > 0 && v[i][j-1] == '0') {\n            if (dist[i][j-1] == -1) {\n                dist[i][j-1] = dist[i][j] + 1;\n                q.push({i, j-1});\n            }\n        }\n        if (j < N-1 && v[i][j] == '0') {\n            if (dist[i][j+1] == -1) {\n                dist[i][j+1] = dist[i][j] + 1;\n                q.push({i, j+1});\n            }\n        }\n    }\n    \n    const int L = 100000;\n    int current_i = 0, current_j = 0;\n    vector<vector<int>> V(N, vector<int>(N, 0));\n    string moves;\n    \n    for (int t = 0; t < L; t++) {\n        int rem_after = L - t - 1;\n        double best_weight = -1.0;\n        char best_dir = 'U';\n        int best_i = current_i, best_j = current_j;\n        \n        if (current_i > 0 && h[current_i-1][current_j] == '0') {\n            int new_i = current_i - 1;\n            int new_j = current_j;\n            if (dist[new_i][new_j] <= rem_after) {\n                double weight;\n                if (V[new_i][new_j] == 0) {\n                    weight = d[new_i][new_j] * 1000000.0;\n                } else {\n                    weight = d[new_i][new_j] / static_cast<double>(V[new_i][new_j] * V[new_i][new_j]);\n                }\n                if (weight > best_weight) {\n                    best_weight = weight;\n                    best_dir = 'U';\n                    best_i = new_i;\n                    best_j = new_j;\n                }\n            }\n        }\n        \n        if (current_i < N-1 && h[current_i][current_j] == '0') {\n            int new_i = current_i + 1;\n            int new_j = current_j;\n            if (dist[new_i][new_j] <= rem_after) {\n                double weight;\n                if (V[new_i][new_j] == 0) {\n                    weight = d[new_i][new_j] * 1000000.0;\n                } else {\n                    weight = d[new_i][new_j] / static_cast<double>(V[new_i][new_j] * V[new_i][new_j]);\n                }\n                if (weight > best_weight) {\n                    best_weight = weight;\n                    best_dir = 'D';\n                    best_i = new_i;\n                    best_j = new_j;\n                }\n            }\n        }\n        \n        if (current_j > 0 && v[current_i][current_j-1] == '0') {\n            int new_i = current_i;\n            int new_j = current_j - 1;\n            if (dist[new_i][new_j] <= rem_after) {\n                double weight;\n                if (V[new_i][new_j] == 0) {\n                    weight = d[new_i][new_j] * 1000000.0;\n                } else {\n                    weight = d[new_i][new_j] / static_cast<double>(V[new_i][new_j] * V[new_i][new_j]);\n                }\n                if (weight > best_weight) {\n                    best_weight = weight;\n                    best_dir = 'L';\n                    best_i = new_i;\n                    best_j = new_j;\n                }\n            }\n        }\n        \n        if (current_j < N-1 && v[current_i][current_j] == '0') {\n            int new_i = current_i;\n            int new_j = current_j + 1;\n            if (dist[new_i][new_j] <= rem_after) {\n                double weight;\n                if (V[new_i][new_j] == 0) {\n                    weight = d[new_i][new_j] * 1000000.0;\n                } else {\n                    weight = d[new_i][new_j] / static_cast<double>(V[new_i][new_j] * V[new_i][new_j]);\n                }\n                if (weight > best_weight) {\n                    best_weight = weight;\n                    best_dir = 'R';\n                    best_i = new_i;\n                    best_j = new_j;\n                }\n            }\n        }\n        \n        moves += best_dir;\n        current_i = best_i;\n        current_j = best_j;\n        V[current_i][current_j]++;\n    }\n    \n    cout << moves << endl;\n    \n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <map>\n#include <limits>\n#include <cmath>\n\nusing namespace std;\n\nconst int INF = numeric_limits<int>::max();\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int s_i, s_j;\n    cin >> s_i >> s_j;\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    vector<string> words(M);\n    for (int i = 0; i < M; i++) {\n        cin >> words[i];\n    }\n\n    map<char, vector<pair<int, int>>> letter_points;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            char c = grid[i][j];\n            letter_points[c].push_back({i, j});\n        }\n    }\n\n    auto dist = [](pair<int, int> a, pair<int, int> b) {\n        return abs(a.first - b.first) + abs(a.second - b.second);\n    };\n\n    vector<string> remaining_words = words;\n    string S = remaining_words[0];\n    remaining_words.erase(remaining_words.begin());\n\n    while (!remaining_words.empty()) {\n        int best_overlap = -1;\n        int best_index = -1;\n        for (int i = 0; i < remaining_words.size(); i++) {\n            string w = remaining_words[i];\n            int overlap = 0;\n            int len = min(S.size(), w.size());\n            for (int l = len; l > 0; l--) {\n                if (S.substr(S.size() - l) == w.substr(0, l)) {\n                    overlap = l;\n                    break;\n                }\n            }\n            if (overlap > best_overlap) {\n                best_overlap = overlap;\n                best_index = i;\n            }\n        }\n        string best_word = remaining_words[best_index];\n        if (best_overlap > 0) {\n            S += best_word.substr(best_overlap);\n        } else {\n            S += best_word;\n        }\n        remaining_words.erase(remaining_words.begin() + best_index);\n    }\n\n    int L = S.size();\n    vector<vector<pair<int, int>>> points_for_S(L);\n    for (int i = 0; i < L; i++) {\n        points_for_S[i] = letter_points[S[i]];\n    }\n\n    pair<int, int> initial = {s_i, s_j};\n    vector<map<pair<int, int>, int>> dp(L);\n    vector<map<pair<int, int>, pair<int, int>>> prev(L);\n\n    for (auto p : points_for_S[0]) {\n        int cost = dist(initial, p) + 1;\n        dp[0][p] = cost;\n        prev[0][p] = initial;\n    }\n\n    for (int i = 1; i < L; i++) {\n        for (auto p : points_for_S[i]) {\n            int best_cost = INF;\n            pair<int, int> best_prev;\n            for (auto q : points_for_S[i-1]) {\n                if (dp[i-1].find(q) == dp[i-1].end()) continue;\n                int cost = dp[i-1][q] + dist(q, p) + 1;\n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_prev = q;\n                }\n            }\n            if (best_cost < INF) {\n                dp[i][p] = best_cost;\n                prev[i][p] = best_prev;\n            }\n        }\n    }\n\n    int min_cost = INF;\n    pair<int, int> best_point;\n    for (auto p : points_for_S[L-1]) {\n        if (dp[L-1].find(p) != dp[L-1].end() && dp[L-1][p] < min_cost) {\n            min_cost = dp[L-1][p];\n            best_point = p;\n        }\n    }\n\n    vector<pair<int, int>> sequence;\n    pair<int, int> current = best_point;\n    for (int i = L-1; i >= 0; i--) {\n        sequence.push_back(current);\n        if (i > 0) {\n            current = prev[i][current];\n        }\n    }\n    reverse(sequence.begin(), sequence.end());\n\n    for (auto p : sequence) {\n        cout << p.first << \" \" << p.second << endl;\n    }\n\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n\n    vector<vector<pair<int, int>>> fields(M);\n    for (int k = 0; k < M; k++) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < d; i++) {\n            int x, y;\n            cin >> x >> y;\n            fields[k].push_back({x, y});\n        }\n    }\n\n    vector<pair<int, int>> oil_squares;\n    \n    // Drill each square sequentially\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cout << \"q 1 \" << i << \" \" << j << endl;\n            int resp;\n            cin >> resp;\n            if (resp > 0) {\n                oil_squares.push_back({i, j});\n            }\n        }\n    }\n\n    // Output final answer\n    cout << \"a \" << oil_squares.size();\n    for (auto [i, j] : oil_squares) {\n        cout << \" \" << i << \" \" << j;\n    }\n    cout << endl;\n\n    int result;\n    cin >> result;\n    // Program ends after correct guess\n\n    return 0;\n}","ahc031":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nint main() {\n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    // Determine grid dimensions - aim for roughly square cells\n    int grid_size = ceil(sqrt(N));\n    int rows = grid_size;\n    int cols = ceil((double)N / rows);\n    \n    // Initialize grid lines - start with equal spacing\n    vector<vector<int>> h_lines(D, vector<int>(rows + 1));\n    vector<vector<int>> v_lines(D, vector<int>(cols + 1));\n    \n    // Day 0: Set up initial grid\n    for (int i = 0; i <= rows; i++) {\n        h_lines[0][i] = (i * W) / rows;\n    }\n    for (int j = 0; j <= cols; j++) {\n        v_lines[0][j] = (j * W) / cols;\n    }\n    \n    // For each day, adjust grid lines to meet area requirements\n    for (int d = 0; d < D; d++) {\n        if (d > 0) {\n            // Start with previous day's layout\n            h_lines[d] = h_lines[d-1];\n            v_lines[d] = v_lines[d-1];\n        }\n        \n        // Calculate current cell areas\n        vector<int> cell_areas;\n        for (int i = 0; i < rows; i++) {\n            for (int j = 0; j < cols; j++) {\n                int width = v_lines[d][j+1] - v_lines[d][j];\n                int height = h_lines[d][i+1] - h_lines[d][i];\n                cell_areas.push_back(width * height);\n            }\n        }\n        \n        // Sort both desired areas and cell areas\n        vector<int> sorted_areas = a[d];\n        sort(sorted_areas.begin(), sorted_areas.end());\n        sort(cell_areas.begin(), cell_areas.end());\n        \n        // Adjust grid lines to better match area requirements\n        // Focus on horizontal lines first (affects row heights)\n        for (int iter = 0; iter < 2; iter++) {\n            for (int i = 1; i < rows; i++) {\n                int left_area = 0, right_area = 0;\n                \n                // Calculate total desired area for left and right sections\n                for (int k = 0; k < N; k++) {\n                    if (k < i * cols) {\n                        left_area += sorted_areas[k];\n                    } else {\n                        right_area += sorted_areas[k];\n                    }\n                }\n                \n                // Adjust horizontal line proportionally\n                int total_area = left_area + right_area;\n                if (total_area > 0) {\n                    int target_line = (left_area * W) / total_area;\n                    // Smooth adjustment to avoid large changes\n                    h_lines[d][i] = (h_lines[d][i] + target_line) / 2;\n                }\n            }\n            \n            // Adjust vertical lines similarly\n            for (int j = 1; j < cols; j++) {\n                int left_area = 0, right_area = 0;\n                \n                for (int k = 0; k < N; k++) {\n                    int col = k % cols;\n                    if (col < j) {\n                        left_area += sorted_areas[k];\n                    } else {\n                        right_area += sorted_areas[k];\n                    }\n                }\n                \n                int total_area = left_area + right_area;\n                if (total_area > 0) {\n                    int target_line = (left_area * W) / total_area;\n                    v_lines[d][j] = (v_lines[d][j] + target_line) / 2;\n                }\n            }\n        }\n        \n        // Ensure boundaries\n        h_lines[d][0] = 0;\n        h_lines[d][rows] = W;\n        v_lines[d][0] = 0;\n        v_lines[d][cols] = W;\n        \n        // Output assignments for this day\n        for (int k = 0; k < N; k++) {\n            int i = k / cols;\n            int j = k % cols;\n            \n            int i0 = h_lines[d][i];\n            int j0 = v_lines[d][j];\n            int i1 = h_lines[d][i+1];\n            int j1 = v_lines[d][j+1];\n            \n            // Ensure minimum area requirement is met\n            int current_area = (i1 - i0) * (j1 - j0);\n            int desired_area = a[d][k];\n            \n            if (current_area < desired_area) {\n                // Expand rectangle to meet requirement\n                int shortage = desired_area - current_area;\n                int expand_x = min(shortage / (i1 - i0), W - j1);\n                int expand_y = min(shortage / (j1 - j0), W - i1);\n                \n                if (expand_x > expand_y) {\n                    j1 += expand_x;\n                } else {\n                    i1 += expand_y;\n                }\n            }\n            \n            cout << i0 << \" \" << j0 << \" \" << i1 << \" \" << j1 << endl;\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <tuple>\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\n\nint main() {\n    int n, m, k;\n    cin >> n >> m >> k;\n    \n    int a[N][N];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> a[i][j];\n        }\n    }\n    \n    int stamps[M][3][3];\n    for (int mm = 0; mm < m; mm++) {\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                cin >> stamps[mm][i][j];\n            }\n        }\n    }\n    \n    int u[N][N];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            u[i][j] = a[i][j] % MOD;\n        }\n    }\n    \n    vector<tuple<int, int, int>> operations;\n    int max_p = n - 3;\n    int max_q = n - 3;\n    \n    for (int step = 0; step < k; step++) {\n        int best_delta = -1000000000;\n        int best_m = -1, best_p = -1, best_q = -1;\n        \n        for (int mm = 0; mm < m; mm++) {\n            for (int p = 0; p <= max_p; p++) {\n                for (int q = 0; q <= max_q; q++) {\n                    int delta = 0;\n                    for (int i = 0; i < 3; i++) {\n                        for (int j = 0; j < 3; j++) {\n                            int x = p + i;\n                            int y = q + j;\n                            int s_val = stamps[mm][i][j];\n                            int current_u = u[x][y];\n                            int new_u = (current_u + s_val) % MOD;\n                            delta += new_u - current_u;\n                        }\n                    }\n                    if (delta > best_delta) {\n                        best_delta = delta;\n                        best_m = mm;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n        \n        if (best_delta <= 0) {\n            break;\n        }\n        \n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = best_p + i;\n                int y = best_q + j;\n                int s_val = stamps[best_m][i][j];\n                u[x][y] = (u[x][y] + s_val) % MOD;\n            }\n        }\n        \n        operations.push_back(make_tuple(best_m, best_p, best_q));\n    }\n    \n    cout << operations.size() << endl;\n    for (auto op : operations) {\n        int m, p, q;\n        tie(m, p, q) = op;\n        cout << m << \" \" << p << \" \" << q << endl;\n    }\n    \n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <array>\n#include <algorithm>\nusing namespace std;\n\nconst int N = 5;\n\narray<array<int, N>, N> grid;\narray<int, N> brought = {0};\narray<int, N> dispatched = {0};\narray<array<int, N>, N> A;\n\nstruct Crane {\n    int i, j;\n    bool carrying;\n    int container;\n    bool active;\n    bool is_large;\n};\n\nvector<Crane> cranes;\nvector<string> actions(N);\n\nvoid init_cranes() {\n    cranes.resize(N);\n    for (int i = 0; i < N; i++) {\n        cranes[i].i = i;\n        cranes[i].j = 0;\n        cranes[i].carrying = false;\n        cranes[i].active = true;\n        cranes[i].is_large = (i == 0);\n    }\n}\n\nbool is_crane_on(int i, int j) {\n    for (const Crane& crane : cranes) {\n        if (crane.active && crane.i == i && crane.j == j) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> A[i][j];\n        }\n    }\n\n    init_cranes();\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            grid[i][j] = -1;\n        }\n    }\n\n    int turns = 0;\n    const int max_turns = 10000;\n\n    while (turns < max_turns) {\n        for (int i = 0; i < N; i++) {\n            if (brought[i] < N && grid[i][0] == -1 && !is_crane_on(i, 0)) {\n                grid[i][0] = A[i][brought[i]];\n                brought[i]++;\n            }\n        }\n\n        vector<Crane> old_cranes = cranes;\n        for (int idx = 0; idx < N; idx++) {\n            Crane& crane = cranes[idx];\n            if (!crane.active) {\n                actions[idx] += '.';\n                continue;\n            }\n\n            if (!crane.is_large) {\n                if (crane.j == 0) {\n                    actions[idx] += 'R';\n                    crane.j = 1;\n                } else {\n                    actions[idx] += '.';\n                }\n            } else {\n                if (crane.carrying) {\n                    int b = crane.container;\n                    int target_i = b / N;\n                    if (crane.i == target_i) {\n                        bool placed = false;\n                        if (b == target_i * N + dispatched[target_i]) {\n                            if (grid[target_i][N-1] == -1 && !is_crane_on(target_i, N-1)) {\n                                actions[idx] += 'Q';\n                                grid[target_i][N-1] = b;\n                                crane.carrying = false;\n                                placed = true;\n                            }\n                        }\n                        if (!placed) {\n                            for (int j = 1; j < N-1; j++) {\n                                if (grid[target_i][j] == -1 && !is_crane_on(target_i, j)) {\n                                    if (crane.j != j) {\n                                        if (crane.j < j) actions[idx] += 'R';\n                                        else actions[idx] += 'L';\n                                        crane.j += (crane.j < j) ? 1 : -1;\n                                    } else {\n                                        actions[idx] += 'Q';\n                                        grid[target_i][j] = b;\n                                        crane.carrying = false;\n                                    }\n                                    placed = true;\n                                    break;\n                                }\n                            }\n                        }\n                        if (!placed) {\n                            actions[idx] += '.';\n                        }\n                    } else {\n                        if (crane.i < target_i) {\n                            actions[idx] += 'D';\n                            crane.i++;\n                        } else {\n                            actions[idx] += 'U';\n                            crane.i--;\n                        }\n                    }\n                } else {\n                    int pick_i = -1;\n                    for (int i = 0; i < N; i++) {\n                        if (grid[i][0] != -1 && !is_crane_on(i, 0)) {\n                            pick_i = i;\n                            break;\n                        }\n                    }\n                    if (pick_i != -1) {\n                        if (crane.i != pick_i) {\n                            if (crane.i < pick_i) {\n                                actions[idx] += 'D';\n                                crane.i++;\n                            } else {\n                                actions[idx] += 'U';\n                                crane.i--;\n                            }\n                        } else if (crane.j != 0) {\n                            if (crane.j > 0) {\n                                actions[idx] += 'L';\n                                crane.j--;\n                            }\n                        } else {\n                            actions[idx] += 'P';\n                            crane.carrying = true;\n                            crane.container = grid[pick_i][0];\n                            grid[pick_i][0] = -1;\n                        }\n                    } else {\n                        actions[idx] += '.';\n                    }\n                }\n            }\n        }\n\n        for (int i = 0; i < N; i++) {\n            if (grid[i][N-1] != -1) {\n                int b = grid[i][N-1];\n                grid[i][N-1] = -1;\n                if (b >= i * N && b < i * N + N) {\n                    dispatched[i]++;\n                }\n            }\n        }\n\n        turns++;\n        bool all_dispatched = true;\n        for (int i = 0; i < N; i++) {\n            if (dispatched[i] < N) {\n                all_dispatched = false;\n                break;\n            }\n        }\n        if (all_dispatched) break;\n    }\n\n    size_t max_len = 0;\n    for (int i = 0; i < N; i++) {\n        if (actions[i].size() > max_len) {\n            max_len = actions[i].size();\n        }\n    }\n    for (int i = 0; i < N; i++) {\n        string s = actions[i];\n        s.resize(max_len, '.');\n        cout << s << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nvector<string> get_moves(int from_i, int from_j, int to_i, int to_j) {\n    vector<string> moves;\n    int di = to_i - from_i;\n    int dj = to_j - from_j;\n    if (di > 0) {\n        for (int i = 0; i < di; i++) {\n            moves.push_back(\"D\");\n        }\n    } else if (di < 0) {\n        for (int i = 0; i < -di; i++) {\n            moves.push_back(\"U\");\n        }\n    }\n    if (dj > 0) {\n        for (int j = 0; j < dj; j++) {\n            moves.push_back(\"R\");\n        }\n    } else if (dj < 0) {\n        for (int j = 0; j < -dj; j++) {\n            moves.push_back(\"L\");\n        }\n    }\n    return moves;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<vector<int>> h_init(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h_init[i][j];\n        }\n    }\n\n    vector<vector<bool>> in_pos(N, vector<bool>(N, false));\n    vector<vector<bool>> in_neg(N, vector<bool>(N, false));\n\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (h_init[i][j] > 0) {\n                in_pos[i][j] = true;\n            } else if (h_init[i][j] < 0) {\n                in_neg[i][j] = true;\n            }\n        }\n    }\n\n    int current_i = 0, current_j = 0;\n    int load = 0;\n    vector<string> operations;\n\n    // Positive phase: visit all cells with positive height\n    while (true) {\n        bool has_pos = false;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (in_pos[i][j]) {\n                    has_pos = true;\n                    break;\n                }\n            }\n            if (has_pos) break;\n        }\n        if (!has_pos) break;\n\n        if (in_pos[current_i][current_j]) {\n            int d = h_init[current_i][current_j];\n            operations.push_back(\"+\" + to_string(d));\n            load += d;\n            in_pos[current_i][current_j] = false;\n        } else {\n            int best_i = -1, best_j = -1;\n            int best_cost = 1e9;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (in_pos[i][j]) {\n                        int dist = abs(i - current_i) + abs(j - current_j);\n                        int cost = dist * (100 + load) + h_init[i][j];\n                        if (cost < best_cost) {\n                            best_cost = cost;\n                            best_i = i;\n                            best_j = j;\n                        }\n                    }\n                }\n            }\n            if (best_i == -1) break;\n            vector<string> moves = get_moves(current_i, current_j, best_i, best_j);\n            operations.insert(operations.end(), moves.begin(), moves.end());\n            current_i = best_i;\n            current_j = best_j;\n        }\n    }\n\n    // Negative phase: visit all cells with negative height\n    while (true) {\n        bool has_neg = false;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (in_neg[i][j]) {\n                    has_neg = true;\n                    break;\n                }\n            }\n            if (has_neg) break;\n        }\n        if (!has_neg) break;\n\n        if (in_neg[current_i][current_j]) {\n            int d = -h_init[current_i][current_j];\n            operations.push_back(\"-\" + to_string(d));\n            load -= d;\n            in_neg[current_i][current_j] = false;\n        } else {\n            int best_i = -1, best_j = -1;\n            int best_cost = 1e9;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (in_neg[i][j]) {\n                        int dist = abs(i - current_i) + abs(j - current_j);\n                        int cost = dist * (100 + load) + (-h_init[i][j]);\n                        if (cost < best_cost) {\n                            best_cost = cost;\n                            best_i = i;\n                            best_j = j;\n                        }\n                    }\n                }\n            }\n            if (best_i == -1) break;\n            vector<string> moves = get_moves(current_i, current_j, best_i, best_j);\n            operations.insert(operations.end(), moves.begin(), moves.end());\n            current_i = best_i;\n            current_j = best_j;\n        }\n    }\n\n    for (const string& op : operations) {\n        cout << op << endl;\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nint main() {\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    for (int t = 0; t < T; t++) {\n        vector<int> values(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            values[i] = accumulate(seeds[i].begin(), seeds[i].end(), 0);\n        }\n\n        vector<int> max_per_criterion(M, 0);\n        for (int l = 0; l < M; l++) {\n            int max_val = 0;\n            for (int i = 0; i < seed_count; i++) {\n                if (seeds[i][l] > max_val) {\n                    max_val = seeds[i][l];\n                }\n            }\n            max_per_criterion[l] = max_val;\n        }\n\n        vector<int> indices(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            indices[i] = i;\n        }\n        sort(indices.begin(), indices.end(), [&](int a, int b) {\n            return values[a] > values[b];\n        });\n\n        vector<int> plant_indices;\n        for (int i = 0; i < N * N; i++) {\n            plant_indices.push_back(indices[i]);\n        }\n\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        vector<bool> assigned(plant_indices.size(), false);\n\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                vector<int> neighbor_seeds;\n                if (i > 0) {\n                    neighbor_seeds.push_back(A[i-1][j]);\n                }\n                if (j > 0) {\n                    neighbor_seeds.push_back(A[i][j-1]);\n                }\n\n                if (neighbor_seeds.empty()) {\n                    for (int k = 0; k < plant_indices.size(); k++) {\n                        if (!assigned[k]) {\n                            A[i][j] = plant_indices[k];\n                            assigned[k] = true;\n                            break;\n                        }\n                    }\n                } else {\n                    vector<int> D(M, 0);\n                    for (int l = 0; l < M; l++) {\n                        for (int n_index : neighbor_seeds) {\n                            D[l] += max_per_criterion[l] - seeds[n_index][l];\n                        }\n                    }\n\n                    int best_score = -1;\n                    int best_seed_index = -1;\n                    for (int k = 0; k < plant_indices.size(); k++) {\n                        if (assigned[k]) continue;\n                        int s_index = plant_indices[k];\n                        int score = 0;\n                        for (int l = 0; l < M; l++) {\n                            score += seeds[s_index][l] * D[l];\n                        }\n                        if (score > best_score) {\n                            best_score = score;\n                            best_seed_index = k;\n                        }\n                    }\n                    if (best_seed_index != -1) {\n                        A[i][j] = plant_indices[best_seed_index];\n                        assigned[best_seed_index] = true;\n                    } else {\n                        for (int k = 0; k < plant_indices.size(); k++) {\n                            if (!assigned[k]) {\n                                A[i][j] = plant_indices[k];\n                                assigned[k] = true;\n                                break;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << A[i][j];\n                if (j < N - 1) {\n                    cout << \" \";\n                }\n            }\n            cout << endl;\n        }\n        cout.flush();\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\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <random>\n\nusing namespace std;\n\nconst int MAX_N = 30;\nconst int MAX_V = 15;\n\n// Directions: 0=right, 1=down, 2=left, 3=up\nconst int dx[4] = {0, 1, 0, -1};\nconst int dy[4] = {1, 0, -1, 0};\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    \n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    \n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n    \n    int manhattan(const Point& other) const {\n        return abs(x - other.x) + abs(y - other.y);\n    }\n};\n\nclass RoboticArm {\nprivate:\n    int N, M, V;\n    vector<string> s, t;\n    Point root;\n    vector<int> parent;\n    vector<int> length;\n    vector<int> dirs; // direction for each vertex (except root)\n    vector<bool> holding;\n    set<Point> initial_set;\n    set<Point> target_set;\n    vector<vector<bool>> grid;\n    int turns;\n    mt19937 rng;\n    \n    // Check if point is within grid\n    bool in_grid(int x, int y) {\n        return x >= 0 && x < N && y >= 0 && y < N;\n    }\n    \n    // Get position of a vertex\n    Point get_position(int vertex) {\n        if (vertex == 0) return root;\n        \n        Point pos = root;\n        int current = vertex;\n        vector<int> path;\n        \n        // Get path from root to vertex\n        while (current != 0) {\n            path.push_back(current);\n            current = parent[current];\n        }\n        \n        // Reverse to go from root to vertex\n        for (int i = path.size() - 1; i >= 0; i--) {\n            int v = path[i];\n            int d = dirs[v];\n            pos.x += dx[d] * length[v];\n            pos.y += dy[d] * length[v];\n        }\n        \n        return pos;\n    }\n    \n    // Evaluate a move and rotation\n    double evaluate_action(int move, int rotation, const vector<Point>& desired_pos) {\n        Point new_root = root;\n        vector<int> new_dirs = dirs;\n        \n        // Apply move\n        if (move == 1) new_root.y++; // U\n        else if (move == 2) new_root.y--; // D\n        else if (move == 3) new_root.x--; // L\n        else if (move == 4) new_root.x++; // R\n        \n        if (!in_grid(new_root.x, new_root.y)) return numeric_limits<double>::max();\n        \n        // Apply rotation to vertex 1 (the only joint in our star design)\n        if (rotation != 0) {\n            for (int i = 1; i < V; i++) {\n                if (rotation == 1) new_dirs[i] = (new_dirs[i] + 1) % 4; // clockwise\n                else new_dirs[i] = (new_dirs[i] + 3) % 4; // counterclockwise\n            }\n        }\n        \n        // Calculate new positions and score\n        double score = 0;\n        for (int i = 2; i < V; i++) { // leaves are vertices 2 to V-1\n            Point leaf_pos = new_root;\n            int d = new_dirs[i];\n            leaf_pos.x += dx[d] * length[i];\n            leaf_pos.y += dy[d] * length[i];\n            \n            if (!desired_pos[i].x == -1) {\n                score += leaf_pos.manhattan(desired_pos[i]);\n            }\n        }\n        \n        return score;\n    }\n\npublic:\n    RoboticArm(int N, int M, int V, const vector<string>& s, const vector<string>& t) \n        : N(N), M(M), V(V), s(s), t(t), turns(0), rng(42) {\n        \n        // Initialize grid and sets\n        grid.assign(N, vector<bool>(N, false));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (s[i][j] == '1') {\n                    grid[i][j] = true;\n                    initial_set.insert(Point(i, j));\n                }\n                if (t[i][j] == '1') {\n                    target_set.insert(Point(i, j));\n                }\n            }\n        }\n        \n        // Initialize tree structure (star design)\n        parent.resize(V);\n        length.resize(V);\n        dirs.resize(V, 0); // all directions initially right\n        holding.resize(V, false);\n        \n        // Root at center\n        root = Point(N / 2, N / 2);\n        \n        // All vertices except root are children of root\n        for (int i = 1; i < V; i++) {\n            parent[i] = 0;\n            length[i] = N - 1;\n        }\n    }\n    \n    void output_tree() {\n        cout << V << endl;\n        for (int i = 1; i < V; i++) {\n            cout << parent[i] << \" \" << length[i] << endl;\n        }\n        cout << root.x << \" \" << root.y << endl;\n    }\n    \n    void solve() {\n        output_tree();\n        \n        while (turns < 100000) {\n            // Check if all takoyaki are placed\n            bool all_placed = true;\n            for (const auto& p : target_set) {\n                if (!grid[p.x][p.y]) {\n                    all_placed = false;\n                    break;\n                }\n            }\n            if (all_placed) break;\n            \n            // Assign desired positions for each leaf\n            vector<Point> desired_pos(V, Point(-1, -1));\n            set<Point> available_initial = initial_set;\n            set<Point> available_target = target_set;\n            \n            // Remove already placed takoyaki from available targets\n            for (const auto& p : target_set) {\n                if (grid[p.x][p.y]) {\n                    available_target.erase(p);\n                }\n            }\n            \n            // Greedy assignment\n            for (int i = 2; i < V; i++) {\n                if (!holding[i]) {\n                    // Find closest available initial position\n                    Point best_pos(-1, -1);\n                    int best_dist = numeric_limits<int>::max();\n                    Point current_pos = get_position(i);\n                    \n                    for (const auto& p : available_initial) {\n                        if (grid[p.x][p.y]) {\n                            int dist = current_pos.manhattan(p);\n                            if (dist < best_dist) {\n                                best_dist = dist;\n                                best_pos = p;\n                            }\n                        }\n                    }\n                    \n                    if (best_dist < numeric_limits<int>::max()) {\n                        desired_pos[i] = best_pos;\n                        available_initial.erase(best_pos);\n                    }\n                } else {\n                    // Find closest available target position\n                    Point best_pos(-1, -1);\n                    int best_dist = numeric_limits<int>::max();\n                    Point current_pos = get_position(i);\n                    \n                    for (const auto& p : available_target) {\n                        if (!grid[p.x][p.y]) {\n                            int dist = current_pos.manhattan(p);\n                            if (dist < best_dist) {\n                                best_dist = dist;\n                                best_pos = p;\n                            }\n                        }\n                    }\n                    \n                    if (best_dist < numeric_limits<int>::max()) {\n                        desired_pos[i] = best_pos;\n                        available_target.erase(best_pos);\n                    }\n                }\n            }\n            \n            // Evaluate all possible actions\n            int best_move = 0; // 0=no move, 1=U, 2=D, 3=L, 4=R\n            int best_rotation = 0; // 0=no rotation, 1=clockwise, 2=counterclockwise\n            double best_score = numeric_limits<double>::max();\n            \n            for (int move = 0; move <= 4; move++) {\n                for (int rotation = 0; rotation <= 2; rotation++) {\n                    double score = evaluate_action(move, rotation, desired_pos);\n                    if (score < best_score) {\n                        best_score = score;\n                        best_move = move;\n                        best_rotation = rotation;\n                    }\n                }\n            }\n            \n            // Apply best action\n            string operation;\n            operation.resize(2 * V, '.');\n            \n            // Move\n            if (best_move == 1) { // U\n                root.y++;\n                operation[0] = 'U';\n            } else if (best_move == 2) { // D\n                root.y--;\n                operation[0] = 'D';\n            } else if (best_move == 3) { // L\n                root.x--;\n                operation[0] = 'L';\n            } else if (best_move == 4) { // R\n                root.x++;\n                operation[0] = 'R';\n            }\n            \n            // Rotation\n            if (best_rotation == 1) { // clockwise\n                for (int i = 1; i < V; i++) {\n                    dirs[i] = (dirs[i] + 1) % 4;\n                    operation[i] = 'R';\n                }\n            } else if (best_rotation == 2) { // counterclockwise\n                for (int i = 1; i < V; i++) {\n                    dirs[i] = (dirs[i] + 3) % 4;\n                    operation[i] = 'L';\n                }\n            }\n            \n            // Pick/place operations\n            for (int i = 2; i < V; i++) {\n                Point pos = get_position(i);\n                if (in_grid(pos.x, pos.y)) {\n                    if (!holding[i] && initial_set.find(pos) != initial_set.end() && grid[pos.x][pos.y]) {\n                        // Pick up takoyaki\n                        grid[pos.x][pos.y] = false;\n                        holding[i] = true;\n                        operation[V + i] = 'P';\n                    } else if (holding[i] && target_set.find(pos) != target_set.end() && !grid[pos.x][pos.y]) {\n                        // Place takoyaki\n                        grid[pos.x][pos.y] = true;\n                        holding[i] = false;\n                        operation[V + i] = 'P';\n                    }\n                }\n            }\n            \n            cout << operation << endl;\n            turns++;\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, V;\n    cin >> N >> M >> V;\n    \n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; i++) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> t[i];\n    }\n    \n    RoboticArm arm(N, M, V, s, t);\n    arm.solve();\n    \n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    int type; // 0 for mackerel, 1 for sardine\n};\n\npair<int, int> optimize_axis(const vector<Point>& points_sorted, int fixed_min, int fixed_max, bool is_x_fixed) {\n    auto cmp_lower = [is_x_fixed](const Point& p, int val) {\n        if (is_x_fixed) return p.x < val;\n        else return p.y < val;\n    };\n    auto cmp_upper = [is_x_fixed](int val, const Point& p) {\n        if (is_x_fixed) return val < p.x;\n        else return val < p.y;\n    };\n\n    auto start_it = lower_bound(points_sorted.begin(), points_sorted.end(), fixed_min, cmp_lower);\n    auto end_it = upper_bound(points_sorted.begin(), points_sorted.end(), fixed_max, cmp_upper);\n\n    vector<int> value(100001, 0);\n    for (auto it = start_it; it != end_it; ++it) {\n        int coord;\n        if (is_x_fixed) {\n            coord = it->y;\n        } else {\n            coord = it->x;\n        }\n        if (it->type == 0) {\n            value[coord] += 1;\n        } else {\n            value[coord] -= 1;\n        }\n    }\n\n    vector<int> cum_net(100001);\n    cum_net[0] = value[0];\n    for (int i = 1; i <= 100000; i++) {\n        cum_net[i] = cum_net[i-1] + value[i];\n    }\n\n    int min_cum = 0;\n    int min_index = -1;\n    int best_diff = INT_MIN;\n    int best_a = 0, best_b = 0;\n\n    for (int i = 0; i <= 100000; i++) {\n        int diff = cum_net[i] - min_cum;\n        if (diff > best_diff) {\n            best_diff = diff;\n            best_a = min_index + 1;\n            best_b = i;\n        }\n        if (cum_net[i] < min_cum) {\n            min_cum = cum_net[i];\n            min_index = i;\n        }\n    }\n\n    if (best_a > best_b) {\n        swap(best_a, best_b);\n    }\n    if (best_a == best_b) {\n        if (best_b < 100000) {\n            best_b++;\n        } else if (best_a > 0) {\n            best_a--;\n        } else {\n            best_b++;\n        }\n    }\n\n    return {best_a, best_b};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n\n    int N;\n    int test_case_count = 0;\n    while (cin >> N) {\n        test_case_count++;\n        if (test_case_count > 150) break;\n\n        vector<Point> points(2 * N);\n        for (int i = 0; i < 2 * N; i++) {\n            cin >> points[i].x >> points[i].y;\n            points[i].type = (i < N) ? 0 : 1;\n        }\n\n        int x_min = INT_MAX, x_max = INT_MIN;\n        int y_min = INT_MAX, y_max = INT_MIN;\n        for (int i = 0; i < N; i++) {\n            x_min = min(x_min, points[i].x);\n            x_max = max(x_max, points[i].x);\n            y_min = min(y_min, points[i].y);\n            y_max = max(y_max, points[i].y);\n        }\n\n        vector<Point> points_by_x = points;\n        sort(points_by_x.begin(), points_by_x.end(), [](const Point& a, const Point& b) {\n            return a.x < b.x;\n        });\n        vector<Point> points_by_y = points;\n        sort(points_by_y.begin(), points_by_y.end(), [](const Point& a, const Point& b) {\n            return a.y < b.y;\n        });\n\n        int x1 = x_min, x2 = x_max;\n        int y1 = y_min, y2 = y_max;\n\n        for (int iter = 0; iter < 10; iter++) {\n            auto new_y = optimize_axis(points_by_x, x1, x2, true);\n            y1 = new_y.first;\n            y2 = new_y.second;\n\n            auto new_x = optimize_axis(points_by_y, y1, y2, false);\n            x1 = new_x.first;\n            x2 = new_x.second;\n        }\n\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    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <tuple>\n\nusing namespace std;\n\nint main() {\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n    vector<int> w_meas(N), h_meas(N);\n    for (int i = 0; i < N; i++) {\n        cin >> w_meas[i] >> h_meas[i];\n    }\n\n    vector<long long> sum_w(N, 0), sum_h(N, 0);\n    vector<int> count(N, 0);\n\n    for (int t = 0; t < T; t++) {\n        if (t < N) {\n            int i = t;\n            int r = 0;\n            char d = 'U';\n            int b = -1;\n            cout << 1 << endl;\n            cout << i << \" \" << r << \" \" << d << \" \" << b << endl;\n            cout.flush();\n\n            int Wp, Hp;\n            cin >> Wp >> Hp;\n            sum_w[i] += Wp;\n            sum_h[i] += Hp;\n            count[i]++;\n        } else {\n            vector<int> est_w(N), est_h(N);\n            for (int i = 0; i < N; i++) {\n                if (count[i] > 0) {\n                    est_w[i] = sum_w[i] / count[i];\n                    est_h[i] = sum_h[i] / count[i];\n                } else {\n                    est_w[i] = w_meas[i];\n                    est_h[i] = h_meas[i];\n                }\n            }\n\n            int W = 0, H = 0;\n            vector<tuple<int, int, char, int>> actions;\n            for (int i = 0; i < N; i++) {\n                int best_r = 0;\n                char best_d = 'U';\n                int best_score = 1e9;\n                int w0 = est_w[i];\n                int h0 = est_h[i];\n                for (int r = 0; r <= 1; r++) {\n                    int w, h;\n                    if (r == 0) {\n                        w = w0;\n                        h = h0;\n                    } else {\n                        w = h0;\n                        h = w0;\n                    }\n                    for (char d : {'U', 'L'}) {\n                        int new_W, new_H;\n                        if (d == 'U') {\n                            new_W = (W > w) ? W : w;\n                            new_H = H + h;\n                        } else {\n                            new_W = W + w;\n                            new_H = (H > h) ? H : h;\n                        }\n                        int new_score = new_W + new_H;\n                        if (new_score < best_score) {\n                            best_score = new_score;\n                            best_r = r;\n                            best_d = d;\n                        }\n                    }\n                }\n                actions.push_back({i, best_r, best_d, -1});\n                int w, h;\n                if (best_r == 0) {\n                    w = est_w[i];\n                    h = est_h[i];\n                } else {\n                    w = est_h[i];\n                    h = est_w[i];\n                }\n                if (best_d == 'U') {\n                    W = (W > w) ? W : w;\n                    H = H + h;\n                } else {\n                    W = W + w;\n                    H = (H > h) ? H : h;\n                }\n            }\n\n            cout << N << endl;\n            for (const auto& action : actions) {\n                int i, r, b;\n                char d;\n                tie(i, r, d, b) = action;\n                cout << i << \" \" << r << \" \" << d << \" \" << b << endl;\n            }\n            cout.flush();\n\n            int Wp, Hp;\n            cin >> Wp >> Hp;\n        }\n    }\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    int index;\n    int beauty;\n};\n\ndouble distance(const Point& a, const Point& b) {\n    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, H;\n    cin >> N >> M >> H;\n    \n    vector<int> A(N);\n    for (int i = 0; i < N; i++) {\n        cin >> A[i];\n    }\n    \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    vector<Point> points(N);\n    Point center = {500, 500, -1, 0}; // Circle center\n    for (int i = 0; i < N; i++) {\n        cin >> points[i].x >> points[i].y;\n        points[i].index = i;\n        points[i].beauty = A[i];\n    }\n    \n    // Sort points by distance from center (ascending) and beauty (ascending)\n    // Prefer points near center with low beauty as roots\n    vector<int> point_indices(N);\n    iota(point_indices.begin(), point_indices.end(), 0);\n    sort(point_indices.begin(), point_indices.end(), [&](int i, int j) {\n        double dist_i = distance(points[i], center);\n        double dist_j = distance(points[j], center);\n        if (abs(dist_i - dist_j) < 1e-9) {\n            return A[i] < A[j]; // Lower beauty first if same distance\n        }\n        return dist_i < dist_j;\n    });\n    \n    vector<int> parent(N, -1);\n    vector<int> depth(N, -1);\n    vector<bool> assigned(N, false);\n    \n    // Priority queue for BFS: (depth, -beauty, vertex)\n    // We want to process vertices with higher depth first, and for same depth,\n    // process lower beauty vertices first (to reserve high beauty for deeper positions)\n    auto cmp = [](const tuple<int, int, int>& a, const tuple<int, int, int>& b) {\n        if (get<0>(a) != get<0>(b)) return get<0>(a) < get<0>(b);\n        return get<1>(a) > get<1>(b); // Higher beauty has lower negative value\n    };\n    priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, decltype(cmp)> pq(cmp);\n    \n    // Assign roots starting from points near center with low beauty\n    for (int idx : point_indices) {\n        if (!assigned[idx] && depth[idx] == -1) {\n            // Make this point a root\n            parent[idx] = -1;\n            depth[idx] = 0;\n            assigned[idx] = true;\n            pq.push({0, -A[idx], idx});\n        }\n    }\n    \n    // Process vertices in BFS order with depth constraint\n    while (!pq.empty()) {\n        auto [current_depth, neg_beauty, u] = pq.top();\n        pq.pop();\n        \n        if (current_depth >= H) continue;\n        \n        // Sort neighbors by beauty descending (we want to assign high beauty vertices first)\n        vector<pair<int, int>> neighbors; // (beauty, vertex)\n        for (int v : adj[u]) {\n            if (!assigned[v]) {\n                neighbors.push_back({A[v], v});\n            }\n        }\n        \n        sort(neighbors.begin(), neighbors.end(), greater<pair<int, int>>());\n        \n        for (auto [beauty, v] : neighbors) {\n            if (!assigned[v] && depth[v] == -1) {\n                parent[v] = u;\n                depth[v] = current_depth + 1;\n                assigned[v] = true;\n                pq.push({depth[v], -A[v], v});\n            }\n        }\n    }\n    \n    // Output the parent array\n    for (int i = 0; i < N; i++) {\n        cout << parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n    const int N = 20;\n    vector<string> board(N);\n    for (int i = 0; i < N; i++) {\n        cin >> board[i];\n    }\n\n    vector<char> directions;\n    vector<int> indices;\n\n    for (int j = 0; j < N; j++) {\n        int max_r = -1;\n        int min_r = N;\n        bool has_oni = false;\n        for (int i = 0; i < N; i++) {\n            if (board[i][j] == 'x') {\n                has_oni = true;\n                if (i > max_r) max_r = i;\n                if (i < min_r) min_r = i;\n            }\n        }\n        if (!has_oni) continue;\n\n        bool safe_up = true;\n        for (int i = 0; i < max_r; i++) {\n            if (board[i][j] == 'o') {\n                safe_up = false;\n                break;\n            }\n        }\n\n        bool safe_down = true;\n        for (int i = min_r + 1; i < N; i++) {\n            if (board[i][j] == 'o') {\n                safe_down = false;\n                break;\n            }\n        }\n\n        int shifts_up = max_r + 1;\n        int shifts_down = N - min_r;\n\n        char dir;\n        int shifts;\n        if (safe_up && safe_down) {\n            if (shifts_up <= shifts_down) {\n                dir = 'U';\n                shifts = shifts_up;\n            } else {\n                dir = 'D';\n                shifts = shifts_down;\n            }\n        } else if (safe_up) {\n            dir = 'U';\n            shifts = shifts_up;\n        } else if (safe_down) {\n            dir = 'D';\n            shifts = shifts_down;\n        } else {\n            dir = 'U';\n            shifts = shifts_up;\n        }\n\n        for (int k = 0; k < shifts; k++) {\n            directions.push_back(dir);\n            indices.push_back(j);\n        }\n    }\n\n    for (size_t i = 0; i < directions.size(); i++) {\n        cout << directions[i] << \" \" << indices[i] << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    int N, L;\n    cin >> N >> L;\n    vector<int> T(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n\n    double scale = L / (2.0 * N);\n    vector<double> e_star(N);\n    for (int i = 0; i < N; i++) {\n        e_star[i] = T[i] / scale;\n    }\n\n    vector<int> e_min(N);\n    int total_min = 0;\n    for (int i = 0; i < N; i++) {\n        e_min[i] = floor(e_star[i]);\n        total_min += e_min[i];\n    }\n\n    int K = 2 * N - total_min;\n    vector<pair<double, int>> fractions;\n    for (int i = 0; i < N; i++) {\n        double frac = e_star[i] - e_min[i];\n        fractions.push_back({frac, i});\n    }\n    sort(fractions.begin(), fractions.end(), [](const pair<double, int> &a, const pair<double, int> &b) {\n        return a.first > b.first;\n    });\n\n    vector<int> e(N);\n    for (int i = 0; i < N; i++) {\n        e[i] = e_min[i];\n    }\n    for (int i = 0; i < K; i++) {\n        int idx = fractions[i].second;\n        e[idx]++;\n    }\n\n    vector<int> pointers;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < e[i]; j++) {\n            pointers.push_back(i);\n        }\n    }\n\n    random_device rd;\n    mt19937 g(rd());\n    shuffle(pointers.begin(), pointers.end(), g);\n\n    vector<int> a(N), b(N);\n    for (int j = 0; j < N; j++) {\n        a[j] = pointers[2 * j];\n        b[j] = pointers[2 * j + 1];\n    }\n\n    for (int i = 0; i < N; i++) {\n        cout << a[i] << \" \" << b[i] << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    int A, B;\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (int i = 0; i < M; i++) {\n        cin >> G[i];\n    }\n    vector<City> cities(N);\n    for (int i = 0; i < N; i++) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].id = i;\n        cities[i].A = cities[i].lx + cities[i].rx;\n        cities[i].B = cities[i].ly + cities[i].ry;\n    }\n\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n    sort(indices.begin(), indices.end(), [&](int i, int j) {\n        if (cities[i].A != cities[j].A) return cities[i].A < cities[j].A;\n        return cities[i].B < cities[j].B;\n    });\n\n    vector<vector<int>> groups(M);\n    int start = 0;\n    for (int i = 0; i < M; i++) {\n        int g_size = G[i];\n        groups[i].resize(g_size);\n        for (int j = 0; j < g_size; j++) {\n            groups[i][j] = indices[start + j];\n        }\n        start += g_size;\n    }\n\n    vector<pair<int, int>> collected_edges;\n\n    for (int i = 0; i < M; i++) {\n        int g = groups[i].size();\n        if (g < 2) continue;\n\n        if (g <= L) {\n            cout << \"? \" << g;\n            for (int city_id : groups[i]) {\n                cout << \" \" << city_id;\n            }\n            cout << endl;\n            cout.flush();\n\n            for (int j = 0; j < g - 1; j++) {\n                int a, b;\n                cin >> a >> b;\n                if (a > b) swap(a, b);\n                collected_edges.push_back({a, b});\n            }\n        } else {\n            int step = L - 1;\n            int num_queries = (g - 1 + step - 1) / step;\n            for (int j = 0; j < num_queries; j++) {\n                int start_index = j * step;\n                int end_index = min(start_index + L, g);\n                int size = end_index - start_index;\n                if (size < 2) continue;\n                cout << \"? \" << size;\n                for (int k = start_index; k < end_index; k++) {\n                    cout << \" \" << groups[i][k];\n                }\n                cout << endl;\n                cout.flush();\n\n                for (int k = 0; k < size - 1; k++) {\n                    int a, b;\n                    cin >> a >> b;\n                    if (a > b) swap(a, b);\n                    collected_edges.push_back({a, b});\n                }\n            }\n        }\n    }\n\n    cout << \"!\" << endl;\n\n    for (int i = 0; i < M; i++) {\n        vector<int> &S = groups[i];\n        int g = S.size();\n        for (int j = 0; j < g; j++) {\n            if (j > 0) cout << \" \";\n            cout << S[j];\n        }\n        cout << endl;\n\n        if (g == 1) continue;\n\n        set<pair<int, int>> collected_set;\n        for (auto &e : collected_edges) {\n            int u = e.first, v = e.second;\n            if (find(S.begin(), S.end(), u) != S.end() && find(S.begin(), S.end(), v) != S.end()) {\n                collected_set.insert({u, v});\n            }\n        }\n\n        vector<tuple<int, long long, int, int>> edges;\n        map<int, int> id_to_index;\n        for (int idx = 0; idx < g; idx++) {\n            id_to_index[S[idx]] = idx;\n        }\n\n        for (int a = 0; a < g; a++) {\n            for (int b = a + 1; b < g; b++) {\n                int u = S[a], v = S[b];\n                long long dx = cities[u].A - cities[v].A;\n                long long dy = cities[u].B - cities[v].B;\n                long long d_sq = dx * dx + dy * dy;\n                bool collected = collected_set.count({u, v});\n                int priority = collected ? 0 : 1;\n                edges.push_back({priority, d_sq, u, v});\n            }\n        }\n\n        sort(edges.begin(), edges.end(), [](const auto &a, const auto &b) {\n            if (get<0>(a) != get<0>(b)) return get<0>(a) < get<0>(b);\n            if (get<1>(a) != get<1>(b)) return get<1>(a) < get<1>(b);\n            if (get<2>(a) != get<2>(b)) return get<2>(a) < get<2>(b);\n            return get<3>(a) < get<3>(b);\n        });\n\n        vector<int> parent(g);\n        iota(parent.begin(), parent.end(), 0);\n        auto find = [&](int x) {\n            while (parent[x] != x) {\n                parent[x] = parent[parent[x]];\n                x = parent[x];\n            }\n            return x;\n        };\n\n        vector<pair<int, int>> selected_edges;\n        for (auto &edge : edges) {\n            int u = get<2>(edge);\n            int v = get<3>(edge);\n            int idx_u = id_to_index[u];\n            int idx_v = id_to_index[v];\n            int root_u = find(idx_u);\n            int root_v = find(idx_v);\n            if (root_u != root_v) {\n                selected_edges.push_back({u, v});\n                parent[root_u] = root_v;\n                if (selected_edges.size() == g - 1) break;\n            }\n        }\n\n        for (auto &e : selected_edges) {\n            cout << e.first << \" \" << e.second << endl;\n        }\n    }\n\n    cout.flush();\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<pair<int, int>> points;\n    for (int i = 0; i < M; i++) {\n        int i_val, j_val;\n        cin >> i_val >> j_val;\n        points.push_back({i_val, j_val});\n    }\n\n    int cur_i = points[0].first;\n    int cur_j = points[0].second;\n\n    for (int idx = 1; idx < M; idx++) {\n        int target_i = points[idx].first;\n        int target_j = points[idx].second;\n\n        int dj = target_j - cur_j;\n        if (dj > 0) {\n            for (int k = 0; k < dj; k++) {\n                cout << \"M R\" << endl;\n            }\n        } else if (dj < 0) {\n            for (int k = 0; k < -dj; k++) {\n                cout << \"M L\" << endl;\n            }\n        }\n\n        int di = target_i - cur_i;\n        if (di > 0) {\n            for (int k = 0; k < di; k++) {\n                cout << \"M D\" << endl;\n            }\n        } else if (di < 0) {\n            for (int k = 0; k < -di; k++) {\n                cout << \"M U\" << endl;\n            }\n        }\n\n        cur_i = target_i;\n        cur_j = target_j;\n    }\n\n    return 0;\n}"},"2":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <cmath>\n#include <set>\n#include <map>\n#include <random>\n#include <functional>\n\nusing namespace std;\n\nstruct Company {\n    int id;\n    int x, y, r;\n    int a, b, c, d; // rectangle coordinates\n    int area() const { return (c - a) * (d - b); }\n    double satisfaction() const {\n        int s = area();\n        if (s == 0) return 0.0;\n        double ratio = min(r, s) / (double)max(r, s);\n        return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n    }\n};\n\nstruct Rectangle {\n    int a, b, c, d;\n    Rectangle(int a, int b, int c, int d) : a(a), b(b), c(c), d(d) {}\n    bool contains(int x, int y) const {\n        return a <= x && x < c && b <= y && y < d;\n    }\n    bool overlaps(const Rectangle& other) const {\n        return !(c <= other.a || other.c <= a || d <= other.b || other.d <= b);\n    }\n    int area() const { return (c - a) * (d - b); }\n};\n\nclass RectanglePacker {\nprivate:\n    int grid_size;\n    vector<Company> companies;\n    vector<Rectangle> rectangles;\n    vector<bool> fixed;\n    \npublic:\n    RectanglePacker(int n, const vector<tuple<int, int, int>>& input) : grid_size(10000) {\n        companies.resize(n);\n        for (int i = 0; i < n; i++) {\n            auto [x, y, r] = input[i];\n            companies[i] = {i, x, y, r, x, y, x + 1, y + 1};\n        }\n        rectangles.reserve(n);\n        fixed.resize(n, false);\n    }\n    \n    void solve() {\n        // Sort companies by desired area (largest first)\n        sort(companies.begin(), companies.end(), [](const Company& a, const Company& b) {\n            return a.r > b.r;\n        });\n        \n        // Initialize rectangles as 1x1 around desired points\n        for (auto& company : companies) {\n            rectangles.emplace_back(company.x, company.y, company.x + 1, company.y + 1);\n        }\n        \n        // Priority queue for expansion (companies that need more area)\n        auto comp = [](const pair<int, int>& a, const pair<int, int>& b) {\n            return a.second < b.second; // prioritize larger area deficit\n        };\n        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comp)> pq(comp);\n        \n        for (int i = 0; i < companies.size(); i++) {\n            int deficit = companies[i].r - rectangles[i].area();\n            if (deficit > 0) {\n                pq.push({i, deficit});\n            }\n        }\n        \n        // Expand rectangles greedily\n        while (!pq.empty()) {\n            auto [idx, deficit] = pq.top();\n            pq.pop();\n            \n            if (fixed[idx]) continue;\n            \n            Company& company = companies[idx];\n            Rectangle& rect = rectangles[idx];\n            \n            // Try to expand in each direction\n            vector<tuple<int, int, int>> expansions; // direction, new_area, overlap_penalty\n            \n            // Expand left\n            if (rect.a > 0) {\n                Rectangle new_rect(rect.a - 1, rect.b, rect.c, rect.d);\n                if (!hasOverlap(new_rect, idx)) {\n                    int new_area = new_rect.area();\n                    expansions.emplace_back(0, new_area, 0);\n                }\n            }\n            \n            // Expand right\n            if (rect.c < grid_size) {\n                Rectangle new_rect(rect.a, rect.b, rect.c + 1, rect.d);\n                if (!hasOverlap(new_rect, idx)) {\n                    int new_area = new_rect.area();\n                    expansions.emplace_back(1, new_area, 0);\n                }\n            }\n            \n            // Expand down\n            if (rect.b > 0) {\n                Rectangle new_rect(rect.a, rect.b - 1, rect.c, rect.d);\n                if (!hasOverlap(new_rect, idx)) {\n                    int new_area = new_rect.area();\n                    expansions.emplace_back(2, new_area, 0);\n                }\n            }\n            \n            // Expand up\n            if (rect.d < grid_size) {\n                Rectangle new_rect(rect.a, rect.b, rect.c, rect.d + 1);\n                if (!hasOverlap(new_rect, idx)) {\n                    int new_area = new_rect.area();\n                    expansions.emplace_back(3, new_area, 0);\n                }\n            }\n            \n            if (expansions.empty()) {\n                fixed[idx] = true;\n                continue;\n            }\n            \n            // Choose best expansion (closest to desired area)\n            sort(expansions.begin(), expansions.end(), [&](const auto& a, const auto& b) {\n                int area_a = get<1>(a);\n                int area_b = get<1>(b);\n                return abs(area_a - company.r) < abs(area_b - company.r);\n            });\n            \n            auto [direction, new_area, penalty] = expansions[0];\n            \n            // Apply expansion\n            switch (direction) {\n                case 0: rect.a--; break;\n                case 1: rect.c++; break;\n                case 2: rect.b--; break;\n                case 3: rect.d++; break;\n            }\n            \n            // Update company rectangle\n            company.a = rect.a;\n            company.b = rect.b;\n            company.c = rect.c;\n            company.d = rect.d;\n            \n            // Recalculate deficit and push back to queue if needed\n            deficit = company.r - company.area();\n            if (deficit > 0 && company.area() < grid_size * grid_size) {\n                pq.push({idx, deficit});\n            } else {\n                fixed[idx] = true;\n            }\n        }\n        \n        // Final adjustment phase - try to improve satisfaction\n        improveSolution();\n    }\n    \n    bool hasOverlap(const Rectangle& rect, int exclude_idx) const {\n        for (int i = 0; i < rectangles.size(); i++) {\n            if (i == exclude_idx) continue;\n            if (rect.overlaps(rectangles[i])) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    void improveSolution() {\n        // Try small adjustments to improve satisfaction\n        for (int iter = 0; iter < 1000; iter++) {\n            bool improved = false;\n            \n            for (int i = 0; i < companies.size(); i++) {\n                Company& company = companies[i];\n                Rectangle& rect = rectangles[i];\n                \n                double current_sat = company.satisfaction();\n                \n                // Try small expansions/contractions\n                for (int da = -1; da <= 1; da += 2) {\n                    for (int db = -1; db <= 1; db += 2) {\n                        if (da == 0 && db == 0) continue;\n                        \n                        int new_a = max(0, min(rect.a + da, grid_size - 1));\n                        int new_b = max(0, min(rect.b + db, grid_size - 1));\n                        int new_c = max(0, min(rect.c + da, grid_size));\n                        int new_d = max(0, min(rect.d + db, grid_size));\n                        \n                        if (new_a >= new_c || new_b >= new_d) continue;\n                        \n                        Rectangle new_rect(new_a, new_b, new_c, new_d);\n                        if (!hasOverlap(new_rect, i) && new_rect.contains(company.x, company.y)) {\n                            Company temp = company;\n                            temp.a = new_a; temp.b = new_b; temp.c = new_c; temp.d = new_d;\n                            double new_sat = temp.satisfaction();\n                            \n                            if (new_sat > current_sat) {\n                                rect = new_rect;\n                                company = temp;\n                                improved = true;\n                            }\n                        }\n                    }\n                }\n            }\n            \n            if (!improved) break;\n        }\n    }\n    \n    vector<tuple<int, int, int, int>> getSolution() const {\n        vector<tuple<int, int, int, int>> result;\n        result.reserve(companies.size());\n        \n        for (const auto& company : companies) {\n            result.emplace_back(company.a, company.b, company.c, company.d);\n        }\n        \n        return result;\n    }\n    \n    double calculateScore() const {\n        double total = 0.0;\n        for (const auto& company : companies) {\n            total += company.satisfaction();\n        }\n        return 1e9 * total / companies.size();\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    vector<tuple<int, int, int>> input;\n    for (int i = 0; i < n; i++) {\n        int x, y, r;\n        cin >> x >> y >> r;\n        input.emplace_back(x, y, r);\n    }\n    \n    RectanglePacker packer(n, input);\n    packer.solve();\n    \n    auto solution = packer.getSolution();\n    for (const auto& [a, b, c, d] : solution) {\n        cout << a << \" \" << b << \" \" << c << \" \" << d << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <array>\n#include <bitset>\n#include <algorithm>\n#include <functional>\n#include <string>\n\nusing namespace std;\n\nconst int GRID_SIZE = 50;\nconst int MAX_BEAM_WIDTH = 50; // Reduced for efficiency\n\nstruct State {\n    int i, j;\n    int score;\n    string path;\n    vector<bool> visited_tiles;\n    \n    // Define comparison operators for sorting\n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n    \n    bool operator>(const State& other) const {\n        return score > other.score;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<vector<int>> tile_id(GRID_SIZE, vector<int>(GRID_SIZE));\n    vector<vector<int>> values(GRID_SIZE, vector<int>(GRID_SIZE));\n    \n    // Read tile IDs\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            cin >> tile_id[i][j];\n        }\n    }\n    \n    // Read square values\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            cin >> values[i][j];\n        }\n    }\n    \n    // Find maximum tile ID to determine bitset size\n    int max_tile = 0;\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            max_tile = max(max_tile, tile_id[i][j]);\n        }\n    }\n    int tile_count = max_tile + 1;\n    \n    // Movement directions: Up, Down, Left, Right\n    array<pair<int, int>, 4> directions = {{\n        {-1, 0}, {1, 0}, {0, -1}, {0, 1}\n    }};\n    array<char, 4> dir_chars = {'U', 'D', 'L', 'R'};\n    \n    // Precompute tile sizes for better heuristics\n    vector<int> tile_sizes(tile_count, 0);\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            tile_sizes[tile_id[i][j]]++;\n        }\n    }\n    \n    // Initial state\n    State initial;\n    initial.i = si;\n    initial.j = sj;\n    initial.score = values[si][sj];\n    initial.path = \"\";\n    initial.visited_tiles = vector<bool>(tile_count, false);\n    initial.visited_tiles[tile_id[si][sj]] = true;\n    \n    // Beam search with priority queue\n    priority_queue<State, vector<State>, greater<State>> beam; // Min-heap (we want max score)\n    beam.push(initial);\n    \n    State best_state = initial;\n    int max_path_length = min(1000, GRID_SIZE * GRID_SIZE); // Limit path length\n    \n    for (int step = 0; step < max_path_length && !beam.empty(); step++) {\n        vector<State> next_states;\n        int beams_processed = 0;\n        const int current_beam_width = min(MAX_BEAM_WIDTH, (int)beam.size());\n        \n        // Process current beam\n        while (!beam.empty() && beams_processed < current_beam_width) {\n            State current = beam.top();\n            beam.pop();\n            beams_processed++;\n            \n            // Update best state\n            if (current.score > best_state.score) {\n                best_state = current;\n            }\n            \n            // Try all possible moves\n            for (int d = 0; d < 4; d++) {\n                int ni = current.i + directions[d].first;\n                int nj = current.j + directions[d].second;\n                \n                // Check bounds\n                if (ni < 0 || ni >= GRID_SIZE || nj < 0 || nj >= GRID_SIZE) {\n                    continue;\n                }\n                \n                // Check if tile already visited\n                int next_tile = tile_id[ni][nj];\n                if (current.visited_tiles[next_tile]) {\n                    continue;\n                }\n                \n                // Create new state\n                State new_state = current;\n                new_state.i = ni;\n                new_state.j = nj;\n                new_state.score += values[ni][nj];\n                new_state.path += dir_chars[d];\n                new_state.visited_tiles[next_tile] = true;\n                \n                next_states.push_back(new_state);\n            }\n        }\n        \n        // Clear the remaining beam if we didn't process all\n        while (!beam.empty()) {\n            beam.pop();\n        }\n        \n        // Sort next states by score (descending) and add to beam\n        sort(next_states.begin(), next_states.end(), greater<State>());\n        \n        for (int i = 0; i < min(MAX_BEAM_WIDTH, (int)next_states.size()); i++) {\n            beam.push(next_states[i]);\n        }\n    }\n    \n    // Output the best path found\n    cout << best_state.path << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nconst double INIT_WEIGHT = 5000.0;\nconst double MIN_WEIGHT = 1000.0;\nconst double MAX_WEIGHT = 9000.0;\nconst double BASE_LEARNING_RATE = 0.1;\nconst double SMOOTHING_BETA = 0.05;\n\ndouble horizontal[N][N-1];\ndouble vertical[N-1][N];\nint horizontal_count[N][N-1] = {0};\nint vertical_count[N-1][N] = {0};\n\nstruct Node {\n    int i, j;\n    double cost;\n    bool operator<(const Node& other) const {\n        return cost > other.cost;\n    }\n};\n\nstring reconstruct_path(pair<int,int> parent[N][N], int si, int sj, int ti, int tj) {\n    string path = \"\";\n    int i = ti, j = tj;\n    \n    while (i != si || j != sj) {\n        int pi = parent[i][j].first;\n        int pj = parent[i][j].second;\n        \n        if (pi == i) {\n            if (pj < j) path += 'R';\n            else path += 'L';\n        } else {\n            if (pi < i) path += 'D';\n            else path += 'U';\n        }\n        i = pi;\n        j = pj;\n    }\n    \n    reverse(path.begin(), path.end());\n    return path;\n}\n\nstring find_path(int si, int sj, int ti, int tj) {\n    double dist[N][N];\n    pair<int,int> parent[N][N];\n    bool visited[N][N] = {false};\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            dist[i][j] = 1e18;\n        }\n    }\n    \n    dist[si][sj] = 0;\n    priority_queue<Node> pq;\n    pq.push({si, sj, 0});\n    \n    int dx[4] = {-1, 1, 0, 0};\n    int dy[4] = {0, 0, -1, 1};\n    \n    while (!pq.empty()) {\n        auto [i, j, cost] = pq.top();\n        pq.pop();\n        \n        if (visited[i][j]) continue;\n        visited[i][j] = true;\n        \n        if (i == ti && j == tj) break;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + dx[d];\n            int nj = j + dy[d];\n            \n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            \n            double edge_cost;\n            if (dx[d] != 0) { // vertical move\n                int edge_i = min(i, ni);\n                edge_cost = vertical[edge_i][j];\n            } else { // horizontal move\n                int edge_j = min(j, nj);\n                edge_cost = horizontal[i][edge_j];\n            }\n            \n            double new_cost = dist[i][j] + edge_cost;\n            if (new_cost < dist[ni][nj]) {\n                dist[ni][nj] = new_cost;\n                parent[ni][nj] = {i, j};\n                double heuristic = abs(ni - ti) + abs(nj - tj); // Manhattan distance\n                pq.push({ni, nj, new_cost + heuristic * MIN_WEIGHT});\n            }\n        }\n    }\n    \n    return reconstruct_path(parent, si, sj, ti, tj);\n}\n\ndouble calculate_estimated_length(const string& path, int si, int sj) {\n    double length = 0;\n    int i = si, j = sj;\n    \n    for (char move : path) {\n        if (move == 'U') {\n            length += vertical[i-1][j];\n            i--;\n        } else if (move == 'D') {\n            length += vertical[i][j];\n            i++;\n        } else if (move == 'L') {\n            length += horizontal[i][j-1];\n            j--;\n        } else if (move == 'R') {\n            length += horizontal[i][j];\n            j++;\n        }\n    }\n    \n    return length;\n}\n\nvoid update_weights(const string& path, int si, int sj, double observed_length) {\n    double estimated_length = calculate_estimated_length(path, si, sj);\n    double ratio = observed_length / estimated_length;\n    \n    int i = si, j = sj;\n    for (char move : path) {\n        if (move == 'U') {\n            int edge_i = i-1;\n            vertical_count[edge_i][j]++;\n            double alpha = BASE_LEARNING_RATE / (1 + vertical_count[edge_i][j]);\n            vertical[edge_i][j] *= (1 + alpha * (ratio - 1));\n            vertical[edge_i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[edge_i][j]));\n            i--;\n        } else if (move == 'D') {\n            int edge_i = i;\n            vertical_count[edge_i][j]++;\n            double alpha = BASE_LEARNING_RATE / (1 + vertical_count[edge_i][j]);\n            vertical[edge_i][j] *= (1 + alpha * (ratio - 1));\n            vertical[edge_i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[edge_i][j]));\n            i++;\n        } else if (move == 'L') {\n            int edge_j = j-1;\n            horizontal_count[i][edge_j]++;\n            double alpha = BASE_LEARNING_RATE / (1 + horizontal_count[i][edge_j]);\n            horizontal[i][edge_j] *= (1 + alpha * (ratio - 1));\n            horizontal[i][edge_j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][edge_j]));\n            j--;\n        } else if (move == 'R') {\n            int edge_j = j;\n            horizontal_count[i][edge_j]++;\n            double alpha = BASE_LEARNING_RATE / (1 + horizontal_count[i][edge_j]);\n            horizontal[i][edge_j] *= (1 + alpha * (ratio - 1));\n            horizontal[i][edge_j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][edge_j]));\n            j++;\n        }\n    }\n    \n    // Smooth horizontal edges towards row averages\n    for (int i = 0; i < N; i++) {\n        double sum = 0.0;\n        for (int j = 0; j < N-1; j++) {\n            sum += horizontal[i][j];\n        }\n        double row_avg = sum / (N-1);\n        for (int j = 0; j < N-1; j++) {\n            horizontal[i][j] = (1 - SMOOTHING_BETA) * horizontal[i][j] + SMOOTHING_BETA * row_avg;\n            horizontal[i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][j]));\n        }\n    }\n    \n    // Smooth vertical edges towards column averages\n    for (int j = 0; j < N; j++) {\n        double sum = 0.0;\n        for (int i = 0; i < N-1; i++) {\n            sum += vertical[i][j];\n        }\n        double col_avg = sum / (N-1);\n        for (int i = 0; i < N-1; i++) {\n            vertical[i][j] = (1 - SMOOTHING_BETA) * vertical[i][j] + SMOOTHING_BETA * col_avg;\n            vertical[i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[i][j]));\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Initialize edge weights\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N-1; j++) {\n            horizontal[i][j] = INIT_WEIGHT;\n        }\n    }\n    for (int i = 0; i < N-1; i++) {\n        for (int j = 0; j < N; j++) {\n            vertical[i][j] = INIT_WEIGHT;\n        }\n    }\n    \n    for (int k = 0; k < 1000; k++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        string path = find_path(si, sj, ti, tj);\n        cout << path << endl;\n        cout.flush();\n        \n        int observed_length;\n        cin >> observed_length;\n        \n        update_weights(path, si, sj, observed_length);\n    }\n    \n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nbool is_substring_circular(const string& str, const string& sub) {\n    int n = str.size();\n    int L = sub.size();\n    for (int start = 0; start < n; start++) {\n        bool match = true;\n        for (int p = 0; p < L; p++) {\n            if (str[(start + p) % n] != sub[p]) {\n                match = false;\n                break;\n            }\n        }\n        if (match) return true;\n    }\n    return false;\n}\n\nvector<bool> get_matched_sequences_horizontal(const vector<string>& matrix, int i, const vector<string>& sequences) {\n    int n = matrix.size();\n    string row_str;\n    for (int j = 0; j < n; j++) {\n        row_str += matrix[i][j];\n    }\n    vector<bool> matched(sequences.size(), false);\n    for (int idx = 0; idx < sequences.size(); idx++) {\n        matched[idx] = is_substring_circular(row_str, sequences[idx]);\n    }\n    return matched;\n}\n\nvector<bool> get_matched_sequences_vertical(const vector<string>& matrix, int j, const vector<string>& sequences) {\n    int n = matrix.size();\n    string col_str;\n    for (int i = 0; i < n; i++) {\n        col_str += matrix[i][j];\n    }\n    vector<bool> matched(sequences.size(), false);\n    for (int idx = 0; idx < sequences.size(); idx++) {\n        matched[idx] = is_substring_circular(col_str, sequences[idx]);\n    }\n    return matched;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    cin >> N >> M;\n    vector<string> sequences(M);\n    for (int i = 0; i < M; i++) {\n        cin >> sequences[i];\n    }\n    \n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> char_dist(0, 7);\n    uniform_int_distribution<int> pos_dist(0, N-1);\n    uniform_real_distribution<double> prob_dist(0.0, 1.0);\n    \n    vector<int> freq(8, 0);\n    int total_chars = 0;\n    for (const auto& s : sequences) {\n        for (char c : s) {\n            freq[c - 'A']++;\n            total_chars++;\n        }\n    }\n    \n    vector<char> char_pool;\n    for (int i = 0; i < 8; i++) {\n        int count = (freq[i] * N * N) / total_chars;\n        for (int j = 0; j < count; j++) {\n            char_pool.push_back('A' + i);\n        }\n    }\n    \n    while (char_pool.size() < N * N) {\n        int max_freq = 0;\n        int max_idx = 0;\n        for (int i = 0; i < 8; i++) {\n            if (freq[i] > max_freq) {\n                max_freq = freq[i];\n                max_idx = i;\n            }\n        }\n        char_pool.push_back('A' + max_idx);\n    }\n    \n    shuffle(char_pool.begin(), char_pool.end(), gen);\n    \n    vector<string> matrix(N, string(N, ' '));\n    int idx = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            matrix[i][j] = char_pool[idx++];\n        }\n    }\n    \n    vector<int> horiz_count(M, 0);\n    vector<int> vert_count(M, 0);\n    int c = 0;\n    \n    for (int i = 0; i < N; i++) {\n        vector<bool> matched = get_matched_sequences_horizontal(matrix, i, sequences);\n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (matched[s_idx]) {\n                horiz_count[s_idx]++;\n            }\n        }\n    }\n    \n    for (int j = 0; j < N; j++) {\n        vector<bool> matched = get_matched_sequences_vertical(matrix, j, sequences);\n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (matched[s_idx]) {\n                vert_count[s_idx]++;\n            }\n        }\n    }\n    \n    for (int s_idx = 0; s_idx < M; s_idx++) {\n        if (horiz_count[s_idx] > 0 || vert_count[s_idx] > 0) {\n            c++;\n        }\n    }\n    \n    int iterations = 5000;\n    double initial_temp = 1.0;\n    double cooling_rate = 0.999;\n    \n    for (int iter = 0; iter < iterations; iter++) {\n        double temp = initial_temp * pow(cooling_rate, iter);\n        \n        int i = pos_dist(gen);\n        int j = pos_dist(gen);\n        char old_ch = matrix[i][j];\n        char new_ch;\n        do {\n            new_ch = 'A' + char_dist(gen);\n        } while (new_ch == old_ch);\n        \n        vector<int> saved_horiz_count = horiz_count;\n        vector<int> saved_vert_count = vert_count;\n        int saved_c = c;\n        \n        vector<bool> S_old_row = get_matched_sequences_horizontal(matrix, i, sequences);\n        vector<bool> S_old_col = get_matched_sequences_vertical(matrix, j, sequences);\n        \n        matrix[i][j] = new_ch;\n        \n        vector<bool> S_new_row = get_matched_sequences_horizontal(matrix, i, sequences);\n        vector<bool> S_new_col = get_matched_sequences_vertical(matrix, j, sequences);\n        \n        int new_c = saved_c;\n        \n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (S_old_row[s_idx] && !S_new_row[s_idx]) {\n                if (horiz_count[s_idx] == 1 && vert_count[s_idx] == 0) {\n                    new_c--;\n                }\n                horiz_count[s_idx]--;\n            }\n            if (!S_old_row[s_idx] && S_new_row[s_idx]) {\n                horiz_count[s_idx]++;\n                if (horiz_count[s_idx] == 1 && vert_count[s_idx] == 0) {\n                    new_c++;\n                }\n            }\n        }\n        \n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (S_old_col[s_idx] && !S_new_col[s_idx]) {\n                if (vert_count[s_idx] == 1 && horiz_count[s_idx] == 0) {\n                    new_c--;\n                }\n                vert_count[s_idx]--;\n            }\n            if (!S_old_col[s_idx] && S_new_col[s_idx]) {\n                vert_count[s_idx]++;\n                if (vert_count[s_idx] == 1 && horiz_count[s_idx] == 0) {\n                    new_c++;\n                }\n            }\n        }\n        \n        double delta_c = new_c - saved_c;\n        if (delta_c > 0 || prob_dist(gen) < exp(delta_c / temp)) {\n            c = new_c;\n        } else {\n            matrix[i][j] = old_ch;\n            horiz_count = saved_horiz_count;\n            vert_count = saved_vert_count;\n            c = saved_c;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << matrix[i] << '\\n';\n    }\n    \n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <stack>\n#include <queue>\n#include <string>\n#include <tuple>\n\nusing namespace std;\n\nclass UnionFind {\npublic:\n    vector<int> parent;\n    UnionFind(int n) {\n        parent.resize(n);\n        for (int i = 0; i < n; i++) {\n            parent[i] = i;\n        }\n    }\n    int find(int x) {\n        if (parent[x] != x) {\n            parent[x] = find(parent[x]);\n        }\n        return parent[x];\n    }\n    void unite(int x, int y) {\n        x = find(x);\n        y = find(y);\n        if (x != y) {\n            parent[x] = y;\n        }\n    }\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n\n    vector<pair<int, int>> points;\n    map<pair<int, int>, int> point_to_index;\n    vector<int> costs;\n    int index = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                points.push_back({i, j});\n                int cost = grid[i][j] - '0';\n                costs.push_back(cost);\n                point_to_index[{i, j}] = index;\n                index++;\n            }\n        }\n    }\n    int V = points.size();\n    if (V == 0) {\n        cout << \"\" << endl;\n        return 0;\n    }\n\n    vector<tuple<int, int, int>> edges;\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    for (int i = 0; i < V; i++) {\n        int x = points[i].first;\n        int y = points[i].second;\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d];\n            int ny = y + dy[d];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] != '#') {\n                int j = point_to_index[{nx, ny}];\n                int w = costs[i] + costs[j];\n                edges.push_back({i, j, w});\n            }\n        }\n    }\n\n    sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {\n        return get<2>(a) < get<2>(b);\n    });\n\n    UnionFind uf(V);\n    vector<vector<int>> mst_graph(V);\n    for (const auto& edge : edges) {\n        int u = get<0>(edge);\n        int v = get<1>(edge);\n        if (!uf.same(u, v)) {\n            uf.unite(u, v);\n            mst_graph[u].push_back(v);\n            mst_graph[v].push_back(u);\n        }\n    }\n\n    int start_index = point_to_index[{si, sj}];\n    vector<vector<int>> children(V);\n    vector<bool> visited(V, false);\n    queue<int> q;\n    q.push(start_index);\n    visited[start_index] = true;\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        for (int v : mst_graph[u]) {\n            if (!visited[v]) {\n                visited[v] = true;\n                children[u].push_back(v);\n                q.push(v);\n            }\n        }\n    }\n\n    vector<int> nextChild(V, 0);\n    stack<int> st;\n    string path;\n    int current = start_index;\n    while (true) {\n        if (nextChild[current] < children[current].size()) {\n            int child = children[current][nextChild[current]];\n            nextChild[current]++;\n            int x1 = points[current].first;\n            int y1 = points[current].second;\n            int x2 = points[child].first;\n            int y2 = points[child].second;\n            if (x2 == x1 - 1) path += 'U';\n            else if (x2 == x1 + 1) path += 'D';\n            else if (y2 == y1 - 1) path += 'L';\n            else if (y2 == y1 + 1) path += 'R';\n            st.push(current);\n            current = child;\n        } else {\n            if (st.empty()) break;\n            int parent = st.top();\n            st.pop();\n            int x1 = points[current].first;\n            int y1 = points[current].second;\n            int x2 = points[parent].first;\n            int y2 = points[parent].second;\n            if (x2 == x1 - 1) path += 'U';\n            else if (x2 == x1 + 1) path += 'D';\n            else if (y2 == y1 - 1) path += 'L';\n            else if (y2 == y1 + 1) path += 'R';\n            current = parent;\n        }\n    }\n\n    cout << path << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nenum Status {\n    NOT_STARTED = 0,\n    ASSIGNED = 1,\n    COMPLETED = 2\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<vector<int>> task_difficulty(N+1, vector<int>(K));\n    for (int i=1; i<=N; i++) {\n        for (int j=0; j<K; j++) {\n            cin >> task_difficulty[i][j];\n        }\n    }\n\n    vector<vector<int>> succ_graph(N+1);\n    vector<vector<int>> prereqs(N+1);\n    for (int i=0; i<R; i++) {\n        int u, v;\n        cin >> u >> v;\n        succ_graph[u].push_back(v);\n        prereqs[v].push_back(u);\n    }\n\n    // Precompute descendant counts\n    vector<int> desc_count(N+1, 0);\n    for (int i=1; i<=N; i++) {\n        vector<bool> visited(N+1, false);\n        queue<int> q;\n        q.push(i);\n        visited[i] = true;\n        int count = 0;\n        while (!q.empty()) {\n            int u = q.front(); q.pop();\n            count++;\n            for (int v : succ_graph[u]) {\n                if (!visited[v]) {\n                    visited[v] = true;\n                    q.push(v);\n                }\n            }\n        }\n        desc_count[i] = count;\n    }\n\n    // Initialize arrays\n    vector<Status> task_status(N+1, NOT_STARTED);\n    vector<int> member_task(M+1, -1); // -1 means idle\n    vector<int> member_start_day(M+1, 0);\n    vector<vector<double>> s_est(M+1, vector<double>(K, 40.0)); // initial skill estimate 40\n\n    vector<int> unfinished_prereqs(N+1, 0);\n    for (int i=1; i<=N; i++) {\n        unfinished_prereqs[i] = prereqs[i].size();\n    }\n\n    int current_day = 1;\n    while (true) {\n        // Identify available tasks and members\n        vector<int> available_tasks;\n        for (int i=1; i<=N; i++) {\n            if (task_status[i] == NOT_STARTED && unfinished_prereqs[i] == 0) {\n                available_tasks.push_back(i);\n            }\n        }\n\n        vector<int> available_members;\n        for (int j=1; j<=M; j++) {\n            if (member_task[j] == -1) {\n                available_members.push_back(j);\n            }\n        }\n\n        // Sort available tasks by descendant count descending\n        sort(available_tasks.begin(), available_tasks.end(), [&](int a, int b) {\n            return desc_count[a] > desc_count[b];\n        });\n\n        vector<pair<int, int>> assignments;\n        for (int task : available_tasks) {\n            if (available_members.empty()) break;\n            int best_member = -1;\n            double best_est_t = 1e9;\n\n            // Function to compute estimated time for task and member\n            auto compute_est_t = [&](int t, int m) {\n                double w = 0.0;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[t][k] > s_est[m][k]) {\n                        w += task_difficulty[t][k] - s_est[m][k];\n                    }\n                }\n                if (w == 0) return 1.0;\n                else return w;\n            };\n\n            for (int member : available_members) {\n                double est_t = compute_est_t(task, member);\n                if (est_t < best_est_t) {\n                    best_est_t = est_t;\n                    best_member = member;\n                }\n            }\n\n            if (best_member != -1) {\n                assignments.push_back({best_member, task});\n                task_status[task] = ASSIGNED;\n                member_task[best_member] = task;\n                member_start_day[best_member] = current_day;\n                // Remove the member from available_members\n                auto it = find(available_members.begin(), available_members.end(), best_member);\n                available_members.erase(it);\n            }\n        }\n\n        // Output assignments\n        cout << assignments.size();\n        for (auto& ass : assignments) {\n            cout << \" \" << ass.first << \" \" << ass.second;\n        }\n        cout << endl;\n        cout.flush();\n\n        // Read input for the day\n        int n;\n        cin >> n;\n        if (n == -1) {\n            break;\n        }\n\n        vector<int> completed_members(n);\n        for (int i=0; i<n; i++) {\n            cin >> completed_members[i];\n        }\n\n        // Process completed members\n        for (int j : completed_members) {\n            int task = member_task[j];\n            if (task == -1) continue; // Should not happen\n            int start_day = member_start_day[j];\n            int t = current_day - start_day + 1;\n\n            // Update skill estimates\n            if (t == 1) {\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        s_est[j][k] = task_difficulty[task][k];\n                    }\n                }\n            } else {\n                double w_pred = 0.0;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        w_pred += task_difficulty[task][k] - s_est[j][k];\n                    }\n                }\n                double e = t - w_pred;\n                double alpha = 0.01;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        s_est[j][k] += 2 * alpha * e;\n                        if (s_est[j][k] < 0) s_est[j][k] = 0;\n                    }\n                }\n            }\n\n            // Update task and member status\n            task_status[task] = COMPLETED;\n            member_task[j] = -1;\n\n            // Update unfinished prerequisites for successors\n            for (int v : succ_graph[task]) {\n                unfinished_prereqs[v]--;\n            }\n        }\n\n        current_day++;\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nint main() {\n    int a[1000], b[1000], c[1000], d[1000];\n    for (int i = 0; i < 1000; i++) {\n        cin >> a[i] >> b[i] >> c[i] >> d[i];\n    }\n\n    vector<pair<int, int>> route;\n    route.push_back({400, 400});\n    int current_x = 400, current_y = 400;\n    vector<bool> picked(1000, false);\n    vector<bool> delivered(1000, false);\n    vector<int> pickup_index(1000, -1);\n    vector<int> dropoff_index(1000, -1);\n    int selected_count = 0;\n    int delivered_count = 0;\n\n    while (selected_count < 50 || delivered_count < 50) {\n        int min_dist = 1e9;\n        int best_i = -1;\n        bool is_pickup = true;\n\n        for (int i = 0; i < 1000; i++) {\n            if (!picked[i] && selected_count < 50) {\n                int dx = abs(current_x - a[i]);\n                int dy = abs(current_y - b[i]);\n                int dist = dx + dy;\n                if (dist < min_dist) {\n                    min_dist = dist;\n                    best_i = i;\n                    is_pickup = true;\n                }\n            }\n            if (picked[i] && !delivered[i]) {\n                int dx = abs(current_x - c[i]);\n                int dy = abs(current_y - d[i]);\n                int dist = dx + dy;\n                if (dist < min_dist) {\n                    min_dist = dist;\n                    best_i = i;\n                    is_pickup = false;\n                }\n            }\n        }\n\n        if (best_i == -1) {\n            break;\n        }\n\n        if (is_pickup) {\n            picked[best_i] = true;\n            selected_count++;\n            current_x = a[best_i];\n            current_y = b[best_i];\n            route.push_back({current_x, current_y});\n            pickup_index[best_i] = route.size() - 1;\n        } else {\n            delivered[best_i] = true;\n            delivered_count++;\n            current_x = c[best_i];\n            current_y = d[best_i];\n            route.push_back({current_x, current_y});\n            dropoff_index[best_i] = route.size() - 1;\n        }\n    }\n\n    route.push_back({400, 400});\n\n    int n = route.size();\n    double total_dist = 0;\n    for (int i = 0; i < n - 1; i++) {\n        total_dist += abs(route[i].first - route[i+1].first) + abs(route[i].second - route[i+1].second);\n    }\n\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 0; i <= n - 3; i++) {\n            for (int j = i + 1; j <= n - 2; j++) {\n                bool valid = true;\n                for (int k = 0; k < 1000; k++) {\n                    if (picked[k]) {\n                        int pi = pickup_index[k];\n                        int di = dropoff_index[k];\n                        if (pi >= i+1 && pi <= j && di >= i+1 && di <= j) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                }\n                if (!valid) {\n                    continue;\n                }\n\n                double new_dist = total_dist;\n                new_dist -= abs(route[i].first - route[i+1].first) + abs(route[i].second - route[i+1].second);\n                new_dist -= abs(route[j].first - route[j+1].first) + abs(route[j].second - route[j+1].second);\n                new_dist += abs(route[i].first - route[j].first) + abs(route[i].second - route[j].second);\n                new_dist += abs(route[i+1].first - route[j+1].first) + abs(route[i+1].second - route[j+1].second);\n\n                if (new_dist < total_dist) {\n                    reverse(route.begin() + i + 1, route.begin() + j + 1);\n                    total_dist = new_dist;\n                    improved = true;\n                    for (int k = 0; k < 1000; k++) {\n                        if (picked[k]) {\n                            if (pickup_index[k] >= i+1 && pickup_index[k] <= j) {\n                                pickup_index[k] = i + 1 + j - pickup_index[k];\n                            }\n                            if (dropoff_index[k] >= i+1 && dropoff_index[k] <= j) {\n                                dropoff_index[k] = i + 1 + j - dropoff_index[k];\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    cout << 50 << \" \";\n    for (int i = 0; i < 1000; i++) {\n        if (picked[i]) {\n            cout << i + 1 << \" \";\n        }\n    }\n    cout << endl;\n\n    cout << route.size() << \" \";\n    for (auto &p : route) {\n        cout << p.first << \" \" << p.second << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <functional>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\nconst int N = 400;\nconst int M = 1995;\n\nint main() {\n    vector<double> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<pair<int, int>> edge_pairs(M);\n    for (int i = 0; i < M; i++) {\n        int u, v;\n        cin >> u >> v;\n        edge_pairs[i] = {u, v};\n    }\n\n    vector<int> d(M);\n    for (int i = 0; i < M; i++) {\n        int u = edge_pairs[i].first;\n        int v = edge_pairs[i].second;\n        double dx = x[u] - x[v];\n        double dy = y[u] - y[v];\n        double dist = sqrt(dx*dx + dy*dy);\n        d[i] = static_cast<int>(round(dist));\n    }\n\n    vector<tuple<int, int, int, int>> edges_for_mst;\n    for (int i = 0; i < M; i++) {\n        edges_for_mst.push_back({d[i], edge_pairs[i].first, edge_pairs[i].second, i});\n    }\n\n    sort(edges_for_mst.begin(), edges_for_mst.end());\n\n    vector<int> parent_mst(N);\n    for (int i = 0; i < N; i++) {\n        parent_mst[i] = i;\n    }\n\n    function<int(int)> find_mst = [&](int a) {\n        if (parent_mst[a] == a) return a;\n        return parent_mst[a] = find_mst(parent_mst[a]);\n    };\n\n    vector<bool> in_mst(M, false);\n    for (auto& edge : edges_for_mst) {\n        int d_val = get<0>(edge);\n        int u = get<1>(edge);\n        int v = get<2>(edge);\n        int idx = get<3>(edge);\n        int pu = find_mst(u);\n        int pv = find_mst(v);\n        if (pu != pv) {\n            in_mst[idx] = true;\n            parent_mst[pu] = pv;\n        }\n    }\n\n    vector<int> parent(N);\n    for (int i = 0; i < N; i++) {\n        parent[i] = i;\n    }\n\n    function<int(int)> find = [&](int a) {\n        if (parent[a] == a) return a;\n        return parent[a] = find(parent[a]);\n    };\n\n    int num_components = N;\n\n    auto unite = [&](int a, int b) {\n        a = find(a);\n        b = find(b);\n        if (a != b) {\n            parent[a] = b;\n            num_components--;\n            return true;\n        }\n        return false;\n    };\n\n    for (int i = 0; i < M; i++) {\n        int l_i;\n        cin >> l_i;\n\n        int u = edge_pairs[i].first;\n        int v = edge_pairs[i].second;\n\n        if (find(u) == find(v)) {\n            cout << 0 << endl;\n        } else {\n            if (in_mst[i] || l_i <= 2 * d[i] || (M - i - 1) < (num_components - 1)) {\n                cout << 1 << endl;\n                unite(u, v);\n            } else {\n                cout << 0 << endl;\n            }\n        }\n        cout.flush();\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int MAX_TURNS = 300;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<tuple<int, int, int>> pets;\n    for (int i = 0; i < N; i++) {\n        int x, y, t;\n        cin >> x >> y >> t;\n        pets.push_back({x, y, t});\n    }\n    int M;\n    cin >> M;\n    vector<pair<int, int>> humans;\n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        humans.push_back({x, y});\n    }\n\n    vector<vector<bool>> blocked(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n    vector<pair<int, int>> wall_squares;\n    vector<pair<int, int>> base_squares;\n\n    for (int i = 1; i <= 20; i++) {\n        wall_squares.push_back({20, i});\n        base_squares.push_back({19, i});\n    }\n    for (int i = 1; i <= 19; i++) {\n        wall_squares.push_back({i, 20});\n        base_squares.push_back({i, 19});\n    }\n\n    int total_walls = wall_squares.size();\n    vector<vector<pair<int, int>>> human_wall_squares(M);\n    vector<vector<pair<int, int>>> human_base_squares(M);\n\n    for (int i = 0; i < total_walls; i++) {\n        int human_idx = i % M;\n        human_wall_squares[human_idx].push_back(wall_squares[i]);\n        human_base_squares[human_idx].push_back(base_squares[i]);\n    }\n\n    vector<int> human_target_index(M, 0);\n    vector<vector<bool>> wall_built(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n\n    for (int turn = 1; turn <= MAX_TURNS; turn++) {\n        vector<char> actions(M, '.');\n        set<pair<int, int>> blocks_this_turn;\n\n        // First pass: Decide block actions\n        for (int i = 0; i < M; i++) {\n            if (human_target_index[i] >= human_wall_squares[i].size()) {\n                continue;\n            }\n\n            pair<int, int> target_wall = human_wall_squares[i][human_target_index[i]];\n            pair<int, int> target_base = human_base_squares[i][human_target_index[i]];\n\n            if (wall_built[target_wall.first][target_wall.second]) {\n                human_target_index[i]++;\n                if (human_target_index[i] < human_wall_squares[i].size()) {\n                    target_wall = human_wall_squares[i][human_target_index[i]];\n                    target_base = human_base_squares[i][human_target_index[i]];\n                } else {\n                    continue;\n                }\n            }\n\n            if (humans[i] == target_base) {\n                bool can_block = true;\n\n                // Check if wall square is empty\n                for (auto& pet : pets) {\n                    if (get<0>(pet) == target_wall.first && get<1>(pet) == target_wall.second) {\n                        can_block = false;\n                        break;\n                    }\n                }\n                if (can_block) {\n                    for (int j = 0; j < M; j++) {\n                        if (humans[j].first == target_wall.first && humans[j].second == target_wall.second) {\n                            can_block = false;\n                            break;\n                        }\n                    }\n                }\n\n                // Check adjacent squares for pets\n                if (can_block) {\n                    int dx[] = {1, -1, 0, 0};\n                    int dy[] = {0, 0, 1, -1};\n                    for (int d = 0; d < 4; d++) {\n                        int nx = target_wall.first + dx[d];\n                        int ny = target_wall.second + dy[d];\n                        if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                        for (auto& pet : pets) {\n                            if (get<0>(pet) == nx && get<1>(pet) == ny) {\n                                can_block = false;\n                                break;\n                            }\n                        }\n                        if (!can_block) break;\n                    }\n                }\n\n                if (can_block) {\n                    int dx = target_wall.first - target_base.first;\n                    int dy = target_wall.second - target_base.second;\n                    char action;\n                    if (dx == 1) action = 'd';\n                    else if (dx == -1) action = 'u';\n                    else if (dy == 1) action = 'r';\n                    else if (dy == -1) action = 'l';\n                    else action = '.';\n                    actions[i] = action;\n                    blocks_this_turn.insert(target_wall);\n                }\n            }\n        }\n\n        // Second pass: Decide movement actions\n        for (int i = 0; i < M; i++) {\n            if (actions[i] != '.') continue; // Skip if already decided (block action)\n\n            if (human_target_index[i] >= human_wall_squares[i].size()) {\n                continue;\n            }\n\n            pair<int, int> target_wall = human_wall_squares[i][human_target_index[i]];\n            pair<int, int> target_base = human_base_squares[i][human_target_index[i]];\n\n            if (wall_built[target_wall.first][target_wall.second]) {\n                human_target_index[i]++;\n                if (human_target_index[i] < human_wall_squares[i].size()) {\n                    target_wall = human_wall_squares[i][human_target_index[i]];\n                    target_base = human_base_squares[i][human_target_index[i]];\n                } else {\n                    continue;\n                }\n            }\n\n            if (humans[i] != target_base) {\n                vector<vector<bool>> obstacles(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n                // Mark static obstacles\n                for (int x = 1; x <= GRID_SIZE; x++) {\n                    for (int y = 1; y <= GRID_SIZE; y++) {\n                        if (blocked[x][y]) obstacles[x][y] = true;\n                    }\n                }\n                // Mark blocks that will be placed this turn\n                for (auto& block : blocks_this_turn) {\n                    obstacles[block.first][block.second] = true;\n                }\n\n                queue<pair<int, int>> q;\n                vector<vector<int>> dist(GRID_SIZE + 1, vector<int>(GRID_SIZE + 1, -1));\n                vector<vector<pair<int, int>>> prev(GRID_SIZE + 1, vector<pair<int, int>>(GRID_SIZE + 1, {-1, -1}));\n                int start_x = humans[i].first;\n                int start_y = humans[i].second;\n                dist[start_x][start_y] = 0;\n                q.push({start_x, start_y});\n\n                int dx[] = {1, -1, 0, 0};\n                int dy[] = {0, 0, 1, -1};\n\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d];\n                        int ny = y + dy[d];\n                        if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                        if (obstacles[nx][ny]) continue;\n                        if (dist[nx][ny] == -1) {\n                            dist[nx][ny] = dist[x][y] + 1;\n                            prev[nx][ny] = {x, y};\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n\n                if (dist[target_base.first][target_base.second] != -1) {\n                    vector<pair<int, int>> path;\n                    pair<int, int> cur = target_base;\n                    while (cur != make_pair(start_x, start_y)) {\n                        path.push_back(cur);\n                        cur = prev[cur.first][cur.second];\n                    }\n                    reverse(path.begin(), path.end());\n                    if (!path.empty()) {\n                        pair<int, int> first_step = path[0];\n                        int dx = first_step.first - start_x;\n                        int dy = first_step.second - start_y;\n                        char action;\n                        if (dx == 1) action = 'D';\n                        else if (dx == -1) action = 'U';\n                        else if (dy == 1) action = 'R';\n                        else if (dy == -1) action = 'L';\n                        else action = '.';\n                        actions[i] = action;\n                    }\n                }\n            }\n        }\n\n        string action_str;\n        for (int i = 0; i < M; i++) {\n            action_str += actions[i];\n        }\n        cout << action_str << endl;\n        cout.flush();\n\n        // Update state based on actions\n        for (int i = 0; i < M; i++) {\n            char action = actions[i];\n            if (action == 'u' || action == 'd' || action == 'l' || action == 'r') {\n                int x = humans[i].first;\n                int y = humans[i].second;\n                int block_x, block_y;\n                if (action == 'u') block_x = x - 1, block_y = y;\n                else if (action == 'd') block_x = x + 1, block_y = y;\n                else if (action == 'l') block_x = x, block_y = y - 1;\n                else if (action == 'r') block_x = x, block_y = y + 1;\n\n                if (block_x >= 1 && block_x <= GRID_SIZE && block_y >= 1 && block_y <= GRID_SIZE) {\n                    blocked[block_x][block_y] = true;\n                    wall_built[block_x][block_y] = true;\n                }\n            }\n        }\n\n        // Update human positions\n        for (int i = 0; i < M; i++) {\n            char action = actions[i];\n            if (action == 'U') humans[i].first--;\n            else if (action == 'D') humans[i].first++;\n            else if (action == 'L') humans[i].second--;\n            else if (action == 'R') humans[i].second++;\n        }\n\n        // Read and update pet positions\n        vector<string> pet_movements(N);\n        for (int i = 0; i < N; i++) {\n            cin >> pet_movements[i];\n        }\n\n        for (int i = 0; i < N; i++) {\n            string moves = pet_movements[i];\n            int x = get<0>(pets[i]);\n            int y = get<1>(pets[i]);\n            for (char move : moves) {\n                if (move == 'U') x--;\n                else if (move == 'D') x++;\n                else if (move == 'L') y--;\n                else if (move == 'R') y++;\n            }\n            get<0>(pets[i]) = x;\n            get<1>(pets[i]) = y;\n        }\n    }\n\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <string>\n#include <utility>\n#include <map>\n\nusing namespace std;\n\nconst int GRID_SIZE = 20;\n\n// Directions: Up, Down, Left, Right\nconst int dx[4] = {-1, 1, 0, 0};\nconst int dy[4] = {0, 0, -1, 1};\nconst char dir_char[4] = {'U', 'D', 'L', 'R'};\n\nstruct Cell {\n    int i, j;\n    Cell(int i = 0, int j = 0) : i(i), j(j) {}\n    bool operator==(const Cell& other) const {\n        return i == other.i && j == other.j;\n    }\n    bool operator<(const Cell& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nclass Grid {\npublic:\n    Grid(int si, int sj, int ti, int tj, double p, \n         const vector<string>& h, const vector<string>& v) \n        : si(si), sj(sj), ti(ti), tj(tj), p(p) {\n        this->h = h;\n        this->v = v;\n    }\n\n    bool is_move_allowed(int i, int j, int d) const {\n        if (d == 0) { // Up\n            return i > 0 && v[i-1][j] == '0';\n        } else if (d == 1) { // Down\n            return i < GRID_SIZE - 1 && v[i][j] == '0';\n        } else if (d == 2) { // Left\n            return j > 0 && h[i][j-1] == '0';\n        } else if (d == 3) { // Right\n            return j < GRID_SIZE - 1 && h[i][j] == '0';\n        }\n        return false;\n    }\n\n    string find_shortest_path() const {\n        Cell start(si, sj);\n        Cell end(ti, tj);\n\n        map<Cell, Cell> parent;\n        map<Cell, int> move_dir;\n        queue<Cell> q;\n        q.push(start);\n        parent[start] = start;\n        move_dir[start] = -1;\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            if (current == end) {\n                break;\n            }\n            for (int d = 0; d < 4; d++) {\n                if (is_move_allowed(current.i, current.j, d)) {\n                    Cell next(current.i + dx[d], current.j + dy[d]);\n                    if (parent.find(next) == parent.end()) {\n                        parent[next] = current;\n                        move_dir[next] = d;\n                        q.push(next);\n                    }\n                }\n            }\n        }\n\n        string path;\n        Cell current = end;\n        while (current != start) {\n            int d = move_dir[current];\n            path.push_back(dir_char[d]);\n            current = parent[current];\n        }\n        reverse(path.begin(), path.end());\n        return path;\n    }\n\n    string find_cycle() const {\n        if (is_move_allowed(ti, tj, 0) && is_move_allowed(ti-1, tj, 1)) {\n            return \"UD\";\n        }\n        if (is_move_allowed(ti, tj, 2) && is_move_allowed(ti, tj-1, 3)) {\n            return \"LR\";\n        }\n        return \"UD\";\n    }\n\nprivate:\n    int si, sj, ti, tj;\n    double p;\n    vector<string> h;\n    vector<string> v;\n};\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    vector<string> h(GRID_SIZE);\n    for (int i = 0; i < GRID_SIZE; i++) {\n        cin >> h[i];\n    }\n\n    vector<string> v(GRID_SIZE - 1);\n    for (int i = 0; i < GRID_SIZE - 1; i++) {\n        cin >> v[i];\n    }\n\n    Grid grid(si, sj, ti, tj, p, h, v);\n    string path = grid.find_shortest_path();\n    string cycle = grid.find_cycle();\n\n    string result = path + path;\n    int remaining = 200 - result.size();\n    if (remaining > 0) {\n        int cycle_len = cycle.size();\n        int num_cycles = remaining / cycle_len;\n        for (int i = 0; i < num_cycles; i++) {\n            result += cycle;\n        }\n        int extra = remaining % cycle_len;\n        if (extra > 0) {\n            result += cycle.substr(0, extra);\n        }\n    } else {\n        result = result.substr(0, 200);\n    }\n\n    cout << result << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int to[8][4] = {\n        {1, 0, -1, -1}, // type 0\n        {3, -1, -1, 0}, // type 1\n        {-1, -1, 3, 2}, // type 2\n        {-1, 2, 1, -1}, // type 3\n        {1, 0, 3, 2}, // type 4\n        {3, 2, 1, 0}, // type 5\n        {2, -1, 0, -1}, // type 6\n        {-1, 3, -1, 1}  // type 7\n    };\n\n    for (int t = 0; t < 100; t++) {\n        vector<string> grid;\n        for (int i = 0; i < 30; i++) {\n            string line;\n            cin >> line;\n            grid.push_back(line);\n        }\n\n        string result(900, '0');\n        for (int i = 0; i < 30; i++) {\n            for (int j = 0; j < 30; j++) {\n                int T = grid[i][j] - '0';\n                bool has_neighbor[4] = {false};\n                if (j > 0) has_neighbor[0] = true;\n                if (i > 0) has_neighbor[1] = true;\n                if (j < 29) has_neighbor[2] = true;\n                if (i < 29) has_neighbor[3] = true;\n\n                int best_R = 0;\n                int best_score = 1000000;\n\n                for (int R = 0; R < 4; R++) {\n                    int score = 0;\n                    for (int d = 0; d < 4; d++) {\n                        if (!has_neighbor[d]) continue;\n                        int d_local = (d - R + 4) % 4;\n                        int e_local = to[T][d_local];\n                        if (e_local == -1) {\n                            score++;\n                        } else {\n                            int e = (e_local + R) % 4;\n                            if (!has_neighbor[e]) {\n                                score++;\n                            }\n                        }\n                    }\n                    if (score < best_score) {\n                        best_score = score;\n                        best_R = R;\n                    }\n                }\n                result[i * 30 + j] = '0' + best_R;\n            }\n        }\n        cout << result << endl;\n    }\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n\nusing namespace std;\n\nint compute_delta(char D, vector<vector<int>> &grid, int er, int ec, int N) {\n    int pr, pc;\n    if (D == 'U') {\n        pr = er - 1;\n        pc = ec;\n    } else if (D == 'D') {\n        pr = er + 1;\n        pc = ec;\n    } else if (D == 'L') {\n        pr = er;\n        pc = ec - 1;\n    } else if (D == 'R') {\n        pr = er;\n        pc = ec + 1;\n    }\n\n    int tile = grid[pr][pc];\n\n    int dr[4] = {-1, 1, 0, 0};\n    int dc[4] = {0, 0, -1, 1};\n    int self_line[4] = {2, 8, 1, 4};\n    int neighbor_line[4] = {8, 2, 4, 1};\n\n    int matches_old = 0;\n    for (int i = 0; i < 4; i++) {\n        int nr = pr + dr[i];\n        int nc = pc + dc[i];\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n        if (grid[nr][nc] == 0) continue;\n        if (tile & self_line[i]) {\n            if (grid[nr][nc] & neighbor_line[i]) {\n                matches_old++;\n            }\n        }\n    }\n\n    int move_index;\n    if (D == 'U') move_index = 0;\n    else if (D == 'D') move_index = 1;\n    else if (D == 'L') move_index = 2;\n    else if (D == 'R') move_index = 3;\n\n    int matches_new = 0;\n    for (int i = 0; i < 4; i++) {\n        if (i == move_index) continue;\n        int nr = er + dr[i];\n        int nc = ec + dc[i];\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n        if (grid[nr][nc] == 0) continue;\n        if (tile & self_line[i]) {\n            if (grid[nr][nc] & neighbor_line[i]) {\n                matches_new++;\n            }\n        }\n    }\n\n    return matches_new - matches_old;\n}\n\nvoid make_move(char D, vector<vector<int>> &grid, int &er, int &ec) {\n    int pr, pc;\n    if (D == 'U') {\n        pr = er - 1;\n        pc = ec;\n    } else if (D == 'D') {\n        pr = er + 1;\n        pc = ec;\n    } else if (D == 'L') {\n        pr = er;\n        pc = ec - 1;\n    } else if (D == 'R') {\n        pr = er;\n        pc = ec + 1;\n    }\n\n    grid[er][ec] = grid[pr][pc];\n    grid[pr][pc] = 0;\n    er = pr;\n    ec = pc;\n}\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n\n    vector<vector<int>> grid(N, vector<int>(N));\n    int empty_row = 0, empty_col = 0;\n\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            char c = s[j];\n            if (c >= '0' && c <= '9') {\n                grid[i][j] = c - '0';\n            } else if (c >= 'a' && c <= 'f') {\n                grid[i][j] = 10 + (c - 'a');\n            } else {\n                grid[i][j] = 0;\n            }\n            if (grid[i][j] == 0) {\n                empty_row = i;\n                empty_col = j;\n            }\n        }\n    }\n\n    int M_current = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == 0) continue;\n            if (j < N-1 && grid[i][j+1] != 0) {\n                if ((grid[i][j] & 4) && (grid[i][j+1] & 1)) {\n                    M_current++;\n                }\n            }\n            if (i < N-1 && grid[i+1][j] != 0) {\n                if ((grid[i][j] & 8) && (grid[i+1][j] & 2)) {\n                    M_current++;\n                }\n            }\n        }\n    }\n\n    int M_max = 2 * N * N - 4;\n    string moves = \"\";\n    int t = 0;\n    double T0 = 10.0;\n\n    srand(time(0));\n\n    while (t < T && M_current < M_max) {\n        int er = empty_row, ec = empty_col;\n        vector<char> directions;\n        if (er > 0) directions.push_back('U');\n        if (er < N-1) directions.push_back('D');\n        if (ec > 0) directions.push_back('L');\n        if (ec < N-1) directions.push_back('R');\n\n        if (directions.empty()) break;\n\n        int idx = rand() % directions.size();\n        char D = directions[idx];\n\n        int delta = compute_delta(D, grid, er, ec, N);\n\n        double temp = T0 * (1.0 - static_cast<double>(t) / T);\n        if (temp < 0) temp = 0;\n\n        bool accept = false;\n        if (delta > 0) {\n            accept = true;\n        } else {\n            double prob = exp(delta / temp);\n            double r = static_cast<double>(rand()) / RAND_MAX;\n            if (prob > r) {\n                accept = true;\n            }\n        }\n\n        if (accept) {\n            make_move(D, grid, empty_row, empty_col);\n            moves += D;\n            M_current += delta;\n        }\n        t++;\n    }\n\n    cout << moves << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    int N, K;\n    cin >> N >> K;\n    int a[10];\n    for (int i = 0; i < 10; i++) {\n        cin >> a[i];\n    }\n    vector<pair<int, int>> points;\n    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n        points.push_back({x, y});\n    }\n\n    int S = 0;\n    for (int i = 0; i < 10; i++) {\n        S += a[i];\n    }\n\n    int R = floor(sqrt(S));\n    int C = ceil(static_cast<double>(S) / R);\n    int lines_count = R + C - 2;\n    int additional_lines = K - lines_count;\n    if (additional_lines < 0) {\n        lines_count = K;\n        additional_lines = 0;\n        R = 50;\n        C = 50;\n    }\n\n    cout << lines_count + additional_lines << endl;\n\n    const int min_x = -10000, max_x = 10000;\n    const int min_y = -10000, max_y = 10000;\n\n    double step_x = static_cast<double>(max_x - min_x) / C;\n    for (int i = 1; i < C; i++) {\n        int x = min_x + round(i * step_x);\n        cout << x << \" \" << -1000000000 << \" \" << x << \" \" << 1000000000 << endl;\n    }\n\n    double step_y = static_cast<double>(max_y - min_y) / R;\n    for (int i = 1; i < R; i++) {\n        int y = min_y + round(i * step_y);\n        cout << -1000000000 << \" \" << y << \" \" << 1000000000 << \" \" << y << endl;\n    }\n\n    if (additional_lines > 0) {\n        double new_step_x = static_cast<double>(max_x - min_x) / (additional_lines + 1);\n        for (int i = 1; i <= additional_lines; i++) {\n            int x = min_x + round(i * new_step_x);\n            cout << x << \" \" << -1000000000 << \" \" << x << \" \" << 1000000000 << endl;\n        }\n    }\n\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const { return x == other.x && y == other.y; }\n    bool operator<(const Point& other) const {\n        return x < other.x || (x == other.x && y < other.y);\n    }\n};\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nclass RectJoinSolver {\nprivate:\n    int N, M;\n    vector<Point> initial_dots;\n    set<Point> dots;\n    set<pair<Point, Point>> used_segments;\n    vector<Rectangle> operations;\n    vector<vector<int>> weight;\n    Point center;\n    \n    // Precompute weights\n    void precompute_weights() {\n        weight.resize(N, vector<int>(N, 0));\n        center = Point((N-1)/2, (N-1)/2);\n        for (int x = 0; x < N; x++) {\n            for (int y = 0; y < N; y++) {\n                int dx = x - center.x;\n                int dy = y - center.y;\n                weight[x][y] = dx*dx + dy*dy + 1;\n            }\n        }\n    }\n    \n    // Check if point is valid\n    bool is_valid_point(int x, int y) {\n        return x >= 0 && x < N && y >= 0 && y < N;\n    }\n    \n    // Check if point has a dot\n    bool has_dot(int x, int y) {\n        return dots.count(Point(x, y));\n    }\n    \n    // Check if segment is used\n    bool is_segment_used(const Point& a, const Point& b) {\n        if (a < b) return used_segments.count({a, b});\n        return used_segments.count({b, a});\n    }\n    \n    // Get all points on a line segment\n    vector<Point> get_points_on_segment(const Point& a, const Point& b) {\n        vector<Point> points;\n        if (a.x == b.x) { // vertical\n            int y1 = min(a.y, b.y), y2 = max(a.y, b.y);\n            for (int y = y1; y <= y2; y++) {\n                points.push_back(Point(a.x, y));\n            }\n        } else if (a.y == b.y) { // horizontal\n            int x1 = min(a.x, b.x), x2 = max(a.x, b.x);\n            for (int x = x1; x <= x2; x++) {\n                points.push_back(Point(x, a.y));\n            }\n        } else if (abs(a.x - b.x) == abs(a.y - b.y)) { // diagonal\n            int dx = (b.x > a.x) ? 1 : -1;\n            int dy = (b.y > a.y) ? 1 : -1;\n            int steps = abs(a.x - b.x);\n            for (int i = 0; i <= steps; i++) {\n                points.push_back(Point(a.x + i*dx, a.y + i*dy));\n            }\n        }\n        return points;\n    }\n    \n    // Check condition 2: no other dots on perimeter\n    bool check_no_other_dots(const vector<Point>& corners, const Point& new_dot) {\n        set<Point> corner_set(corners.begin(), corners.end());\n        corner_set.insert(new_dot);\n        \n        // Check all four sides\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            vector<Point> segment_points = get_points_on_segment(a, b);\n            for (const Point& p : segment_points) {\n                if (!corner_set.count(p) && has_dot(p.x, p.y)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    // Check condition 3: no overlapping segments\n    bool check_no_overlapping_segments(const vector<Point>& corners) {\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            vector<Point> segment_points = get_points_on_segment(a, b);\n            \n            // Check each segment between consecutive points\n            for (int j = 0; j < (int)segment_points.size() - 1; j++) {\n                Point p1 = segment_points[j];\n                Point p2 = segment_points[j+1];\n                if (is_segment_used(p1, p2)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    // Mark segments as used\n    void mark_segments_used(const vector<Point>& corners) {\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            vector<Point> segment_points = get_points_on_segment(a, b);\n            \n            for (int j = 0; j < (int)segment_points.size() - 1; j++) {\n                Point p1 = segment_points[j];\n                Point p2 = segment_points[j+1];\n                if (p1 < p2) {\n                    used_segments.insert({p1, p2});\n                } else {\n                    used_segments.insert({p2, p1});\n                }\n            }\n        }\n    }\n    \n    // Generate axis-aligned rectangle candidates\n    vector<pair<Point, vector<Point>>> generate_axis_aligned_candidates() {\n        vector<pair<Point, vector<Point>>> candidates;\n        \n        for (const Point& p1 : dots) {\n            for (const Point& p2 : dots) {\n                if (p1 == p2) continue;\n                \n                // Try different combinations for rectangle corners\n                vector<Point> possible_p3 = {\n                    Point(p1.x, p2.y),\n                    Point(p2.x, p1.y)\n                };\n                \n                for (const Point& p3 : possible_p3) {\n                    if (!is_valid_point(p3.x, p3.y)) continue;\n                    \n                    // Calculate the fourth point\n                    Point p4 = Point(p2.x + p1.x - p3.x, p2.y + p1.y - p3.y);\n                    if (!is_valid_point(p4.x, p4.y)) continue;\n                    \n                    // Check if p3 has dot and p4 is free\n                    if (has_dot(p3.x, p3.y) && !has_dot(p4.x, p4.y)) {\n                        vector<Point> corners = {p1, p3, p2, p4};\n                        candidates.push_back({p4, corners});\n                    }\n                }\n            }\n        }\n        \n        return candidates;\n    }\n    \n    // Generate 45-degree rotated rectangle candidates\n    vector<pair<Point, vector<Point>>> generate_rotated_candidates() {\n        vector<pair<Point, vector<Point>>> candidates;\n        \n        for (const Point& p1 : dots) {\n            for (const Point& p2 : dots) {\n                if (p1 == p2) continue;\n                \n                int dx = p2.x - p1.x;\n                int dy = p2.y - p1.y;\n                \n                // Check if this could be a diagonal of a square\n                if (abs(dx) == abs(dy) && dx != 0) {\n                    // Try both possible squares\n                    vector<Point> possible_p3 = {\n                        Point(p1.x + dy, p1.y + dx),  // rotated 90 degrees\n                        Point(p1.x - dy, p1.y - dx)   // rotated -90 degrees\n                    };\n                    \n                    for (const Point& p3 : possible_p3) {\n                        if (!is_valid_point(p3.x, p3.y)) continue;\n                        \n                        Point p4 = Point(p2.x + (p3.x - p1.x), p2.y + (p3.y - p1.y));\n                        if (!is_valid_point(p4.x, p4.y)) continue;\n                        \n                        // Check if p3 has dot and p4 is free\n                        if (has_dot(p3.x, p3.y) && !has_dot(p4.x, p4.y)) {\n                            vector<Point> corners = {p1, p3, p2, p4};\n                            candidates.push_back({p4, corners});\n                        }\n                    }\n                }\n            }\n        }\n        \n        return candidates;\n    }\n    \npublic:\n    RectJoinSolver(int N, int M, const vector<Point>& initial_dots) \n        : N(N), M(M), initial_dots(initial_dots) {\n        precompute_weights();\n        for (const Point& p : initial_dots) {\n            dots.insert(p);\n        }\n    }\n    \n    void solve() {\n        bool found_operation = true;\n        int max_operations = N * N - M; // Maximum possible operations\n        \n        while (found_operation && operations.size() < max_operations) {\n            found_operation = false;\n            Rectangle best_operation(Point(0,0), Point(0,0), Point(0,0), Point(0,0));\n            int best_score = -1;\n            \n            // Generate candidates from both types of rectangles\n            vector<pair<Point, vector<Point>>> candidates;\n            \n            auto axis_candidates = generate_axis_aligned_candidates();\n            candidates.insert(candidates.end(), axis_candidates.begin(), axis_candidates.end());\n            \n            auto rotated_candidates = generate_rotated_candidates();\n            candidates.insert(candidates.end(), rotated_candidates.begin(), rotated_candidates.end());\n            \n            // Evaluate candidates\n            for (auto& candidate : candidates) {\n                Point new_dot = candidate.first;\n                vector<Point> corners = candidate.second;\n                \n                if (check_no_other_dots(corners, new_dot) && \n                    check_no_overlapping_segments(corners)) {\n                    \n                    int score = weight[new_dot.x][new_dot.y];\n                    if (score > best_score) {\n                        best_score = score;\n                        best_operation = Rectangle(new_dot, corners[0], corners[1], corners[2]);\n                        found_operation = true;\n                    }\n                }\n            }\n            \n            if (found_operation) {\n                // Add the best operation\n                operations.push_back(best_operation);\n                dots.insert(best_operation.p1);\n                \n                // Mark segments as used\n                vector<Point> corners = {\n                    best_operation.p1, best_operation.p2, \n                    best_operation.p3, best_operation.p4\n                };\n                mark_segments_used(corners);\n            }\n        }\n    }\n    \n    void output() {\n        cout << operations.size() << endl;\n        for (const Rectangle& rect : operations) {\n            cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n                 << rect.p2.x << \" \" << rect.p2.y << \" \"\n                 << rect.p3.x << \" \" << rect.p3.y << \" \"\n                 << rect.p4.x << \" \" << rect.p4.y << endl;\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    cin >> N >> M;\n    \n    vector<Point> initial_dots(M);\n    for (int i = 0; i < M; i++) {\n        cin >> initial_dots[i].x >> initial_dots[i].y;\n    }\n    \n    RectJoinSolver solver(N, M, initial_dots);\n    solver.solve();\n    solver.output();\n    \n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n#include <cstring>\nusing namespace std;\n\nconst int N = 10;\nvector<vector<int>> tilt_grid(const vector<vector<int>>& state, char direction) {\n    vector<vector<int>> new_state(N+1, vector<int>(N+1, 0));\n    if (direction == 'L') {\n        for (int i = 1; i <= N; i++) {\n            vector<int> non_empty;\n            for (int j = 1; j <= N; j++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int j = 1; j <= k; j++) {\n                new_state[i][j] = non_empty[j-1];\n            }\n            for (int j = k+1; j <= N; j++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'R') {\n        for (int i = 1; i <= N; i++) {\n            vector<int> non_empty;\n            for (int j = 1; j <= N; j++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int j = 1; j <= k; j++) {\n                new_state[i][N - k + j] = non_empty[j-1];\n            }\n            for (int j = 1; j <= N-k; j++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'F') {\n        for (int j = 1; j <= N; j++) {\n            vector<int> non_empty;\n            for (int i = 1; i <= N; i++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int i = 1; i <= k; i++) {\n                new_state[i][j] = non_empty[i-1];\n            }\n            for (int i = k+1; i <= N; i++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'B') {\n        for (int j = 1; j <= N; j++) {\n            vector<int> non_empty;\n            for (int i = 1; i <= N; i++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int i = 1; i <= k; i++) {\n                new_state[N - k + i][j] = non_empty[i-1];\n            }\n            for (int i = 1; i <= N-k; i++) {\n                new_state[i][j] = 0;\n            }\n        }\n    }\n    return new_state;\n}\n\nint compute_score(const vector<vector<int>>& grid, vector<vector<bool>>& visited) {\n    int score = 0;\n    for (int i = 1; i <= N; i++) {\n        for (int j = 1; j <= N; j++) {\n            visited[i][j] = false;\n        }\n    }\n    for (int i = 1; i <= N; i++) {\n        for (int j = 1; j <= N; j++) {\n            if (!visited[i][j] && grid[i][j] != 0) {\n                int flavor = grid[i][j];\n                int size = 0;\n                queue<pair<int, int>> q;\n                q.push({i, j});\n                visited[i][j] = true;\n                while (!q.empty()) {\n                    pair<int, int> pos = q.front();\n                    q.pop();\n                    int x = pos.first, y = pos.second;\n                    size++;\n                    int dx[] = {1, -1, 0, 0};\n                    int dy[] = {0, 0, 1, -1};\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d], ny = y + dy[d];\n                        if (nx >= 1 && nx <= N && ny >= 1 && ny <= N && !visited[nx][ny] && grid[nx][ny] == flavor) {\n                            visited[nx][ny] = true;\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n                score += size * size;\n            }\n        }\n    }\n    return score;\n}\n\nint main() {\n    int f[101];\n    for (int i = 1; i <= 100; i++) {\n        cin >> f[i];\n    }\n\n    vector<vector<int>> grid(N+1, vector<int>(N+1, 0));\n    vector<vector<bool>> visited(N+1, vector<bool>(N+1, false));\n    vector<char> directions = {'F', 'B', 'L', 'R'};\n\n    for (int t = 1; t <= 100; t++) {\n        int p;\n        cin >> p;\n\n        int count = 0;\n        int i_place = 0, j_place = 0;\n        for (int i = 1; i <= N; i++) {\n            for (int j = 1; j <= N; j++) {\n                if (grid[i][j] == 0) {\n                    count++;\n                    if (count == p) {\n                        i_place = i;\n                        j_place = j;\n                        break;\n                    }\n                }\n            }\n            if (j_place != 0) break;\n        }\n\n        grid[i_place][j_place] = f[t];\n\n        if (t == 100) {\n            // For the last candy, use greedy since no next candy\n            int best_score = -1;\n            char best_dir = 'F';\n            for (char dir : directions) {\n                vector<vector<int>> new_grid = tilt_grid(grid, dir);\n                int score = compute_score(new_grid, visited);\n                if (score > best_score) {\n                    best_score = score;\n                    best_dir = dir;\n                }\n            }\n            cout << best_dir << endl;\n            cout.flush();\n            grid = tilt_grid(grid, best_dir);\n            continue;\n        }\n\n        int best_avg_score = -1;\n        char best_dir = 'F';\n        for (char dir : directions) {\n            vector<vector<int>> grid_after_tilt = tilt_grid(grid, dir);\n            int empty_count = 0;\n            double total_score = 0.0;\n\n            for (int i = 1; i <= N; i++) {\n                for (int j = 1; j <= N; j++) {\n                    if (grid_after_tilt[i][j] == 0) {\n                        empty_count++;\n                        vector<vector<int>> grid_with_next = grid_after_tilt;\n                        grid_with_next[i][j] = f[t+1];\n                        int best_next_score = -1;\n                        for (char dir2 : directions) {\n                            vector<vector<int>> grid_after_tilt2 = tilt_grid(grid_with_next, dir2);\n                            int score = compute_score(grid_after_tilt2, visited);\n                            if (score > best_next_score) {\n                                best_next_score = score;\n                            }\n                        }\n                        total_score += best_next_score;\n                    }\n                }\n            }\n\n            double avg_score = total_score / empty_count;\n            if (avg_score > best_avg_score) {\n                best_avg_score = avg_score;\n                best_dir = dir;\n            }\n        }\n\n        cout << best_dir << endl;\n        cout.flush();\n        grid = tilt_grid(grid, best_dir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\nusing namespace std;\n\nint main() {\n    int M;\n    double eps;\n    cin >> M >> eps;\n\n    double requiredN = sqrt(2 * M) + 10 * eps;\n    int N = min(100, max(4, (int)ceil(requiredN)));\n    int T = N * (N - 1) / 2;\n\n    cout << N << endl;\n\n    vector<string> graphs(M);\n    for (int k = 0; k < M; k++) {\n        string g(T, '0');\n        for (int idx = 0; idx < k && idx < T; idx++) {\n            g[idx] = '1';\n        }\n        cout << g << endl;\n        graphs[k] = g;\n    }\n\n    vector<vector<double>> eigenvals(M);\n    for (int k = 0; k < M; k++) {\n        Eigen::MatrixXd A(N, N);\n        A.setZero();\n        int pos = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = i + 1; j < N; j++) {\n                if (graphs[k][pos] == '1') {\n                    A(i, j) = 1;\n                    A(j, i) = 1;\n                }\n                pos++;\n            }\n        }\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(A);\n        Eigen::VectorXd evals = solver.eigenvalues();\n        vector<double> eval_vec(evals.data(), evals.data() + evals.size());\n        sort(eval_vec.begin(), eval_vec.end());\n        eigenvals[k] = eval_vec;\n    }\n\n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n\n        Eigen::MatrixXd A_H(N, N);\n        A_H.setZero();\n        int pos = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = i + 1; j < N; j++) {\n                if (H[pos] == '1') {\n                    A_H(i, j) = 1;\n                    A_H(j, i) = 1;\n                }\n                pos++;\n            }\n        }\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver_H(A_H);\n        Eigen::VectorXd evals_H = solver_H.eigenvalues();\n        vector<double> eval_vec_H(evals_H.data(), evals_H.data() + evals_H.size());\n        sort(eval_vec_H.begin(), eval_vec_H.end());\n\n        int best_k = 0;\n        double min_dist = 1e9;\n        for (int k = 0; k < M; k++) {\n            double dist = 0.0;\n            for (int i = 0; i < N; i++) {\n                double diff = eval_vec_H[i] - eigenvals[k][i];\n                dist += diff * diff;\n            }\n            dist = sqrt(dist);\n            if (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 <algorithm>\n#include <queue>\n#include <limits>\n#include <tuple>\n\nusing namespace std;\n\nconst int INF = 1000000000;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    vector<tuple<int, int, int>> edges;\n    for (int i = 0; i < M; i++) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges.push_back({u, v, w});\n    }\n\n    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n        // Coordinates are read but not used in this solution\n    }\n\n    vector<vector<pair<int, int>>> graph(N + 1);\n    vector<vector<int>> edge_index(N + 1, vector<int>(N + 1, -1));\n\n    for (int i = 0; i < M; i++) {\n        int u = get<0>(edges[i]);\n        int v = get<1>(edges[i]);\n        int w = get<2>(edges[i]);\n        graph[u].emplace_back(v, w);\n        graph[v].emplace_back(u, w);\n        edge_index[u][v] = i;\n        edge_index[v][u] = i;\n    }\n\n    vector<double> betweenness(M, 0.0);\n\n    for (int s = 1; s <= N; s++) {\n        vector<int> dist(N + 1, INF);\n        dist[s] = 0;\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n        pq.push({0, s});\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            for (auto [v, w] : graph[u]) {\n                int new_d = d + w;\n                if (new_d < dist[v]) {\n                    dist[v] = new_d;\n                    pq.push({new_d, v});\n                }\n            }\n        }\n\n        vector<double> sigma(N + 1, 0.0);\n        sigma[s] = 1.0;\n\n        vector<int> vertices(N);\n        for (int i = 0; i < N; i++) {\n            vertices[i] = i + 1;\n        }\n        sort(vertices.begin(), vertices.end(), [&](int a, int b) {\n            return dist[a] < dist[b];\n        });\n\n        for (int v : vertices) {\n            if (v == s) continue;\n            for (auto [u, w] : graph[v]) {\n                if (dist[u] + w == dist[v]) {\n                    sigma[v] += sigma[u];\n                }\n            }\n        }\n\n        vector<double> delta(N + 1, 0.0);\n        sort(vertices.begin(), vertices.end(), [&](int a, int b) {\n            return dist[a] > dist[b];\n        });\n\n        for (int v : vertices) {\n            if (v == s) continue;\n            for (auto [u, w] : graph[v]) {\n                if (dist[u] + w == dist[v]) {\n                    double c = sigma[u] / sigma[v] * (1.0 + delta[v]);\n                    int idx = edge_index[u][v];\n                    if (idx != -1) {\n                        betweenness[idx] += c;\n                    }\n                    delta[u] += c;\n                }\n            }\n        }\n    }\n\n    vector<int> edge_indices(M);\n    for (int i = 0; i < M; i++) {\n        edge_indices[i] = i;\n    }\n    sort(edge_indices.begin(), edge_indices.end(), [&](int a, int b) {\n        return betweenness[a] > betweenness[b];\n    });\n\n    vector<int> assignment(M);\n    for (int i = 0; i < M; i++) {\n        assignment[edge_indices[i]] = (i % D) + 1;\n    }\n\n    for (int i = 0; i < M; i++) {\n        cout << assignment[i];\n        if (i < M - 1) {\n            cout << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <queue>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\nint main() {\n    int D;\n    cin >> D;\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 required positions for each silhouette\n    set<tuple<int, int, int>> M1, M2;\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 (f1[z][x] == '1' && r1[z][y] == '1') {\n                    M1.insert({x, y, z});\n                }\n                if (f2[z][x] == '1' && r2[z][y] == '1') {\n                    M2.insert({x, y, z});\n                }\n            }\n        }\n    }\n\n    // Find intersection of required positions\n    set<tuple<int, int, int>> I;\n    set_intersection(M1.begin(), M1.end(), M2.begin(), M2.end(),\n                    inserter(I, I.begin()));\n\n    // 6-directional neighbors\n    vector<tuple<int, int, int>> directions = {\n        {1, 0, 0}, {-1, 0, 0},\n        {0, 1, 0}, {0, -1, 0},\n        {0, 0, 1}, {0, 0, -1}\n    };\n\n    // Find connected components in intersection\n    map<tuple<int, int, int>, int> comp_id;\n    int comp_count = 0;\n    \n    for (const auto& coord : I) {\n        if (comp_id.count(coord)) continue;\n        \n        comp_count++;\n        queue<tuple<int, int, int>> q;\n        q.push(coord);\n        comp_id[coord] = comp_count;\n        \n        while (!q.empty()) {\n            auto [x, y, z] = q.front();\n            q.pop();\n            \n            for (auto [dx, dy, dz] : directions) {\n                int nx = x + dx, ny = y + dy, nz = z + dz;\n                tuple<int, int, int> neighbor = {nx, ny, nz};\n                \n                if (I.count(neighbor) && !comp_id.count(neighbor)) {\n                    comp_id[neighbor] = comp_count;\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n\n    // Calculate total blocks\n    int n = comp_count + (M1.size() - I.size()) + (M2.size() - I.size());\n    \n    // Create output arrays\n    vector<int> arr1(D * D * D, 0), arr2(D * D * D, 0);\n    \n    // Assign blocks for first arrangement\n    int id_counter = comp_count + 1;\n    map<tuple<int, int, int>, int> id_map1;\n    \n    for (const auto& coord : M1) {\n        auto [x, y, z] = coord;\n        int idx = x * D * D + y * D + z;\n        \n        if (I.count(coord)) {\n            arr1[idx] = comp_id[coord];\n        } else {\n            if (!id_map1.count(coord)) {\n                id_map1[coord] = id_counter++;\n            }\n            arr1[idx] = id_map1[coord];\n        }\n    }\n    \n    // Assign blocks for second arrangement\n    map<tuple<int, int, int>, int> id_map2;\n    \n    for (const auto& coord : M2) {\n        auto [x, y, z] = coord;\n        int idx = x * D * D + y * D + z;\n        \n        if (I.count(coord)) {\n            arr2[idx] = comp_id[coord];\n        } else {\n            if (!id_map2.count(coord)) {\n                id_map2[coord] = id_counter++;\n            }\n            arr2[idx] = id_map2[coord];\n        }\n    }\n    \n    // Output results\n    cout << n << endl;\n    \n    for (int i = 0; i < D * D * D; i++) {\n        cout << arr1[i] << (i == D * D * D - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    for (int i = 0; i < D * D * D; i++) {\n        cout << arr2[i] << (i == D * D * D - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read input\n    int N, M, K;\n    cin >> N >> M >> K;\n    \n    vector<ll> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<tuple<int, int, ll>> edges(M);\n    map<pair<int, int>, int> edge_index_map;\n    for (int i = 0; i < M; i++) {\n        int u, v;\n        ll w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edges[i] = {u, v, w};\n        if (u > v) swap(u, v);\n        edge_index_map[{u, v}] = i;\n    }\n    \n    vector<ll> a(K), b(K);\n    for (int i = 0; i < K; i++) {\n        cin >> a[i] >> b[i];\n    }\n    \n    // Precompute squared distances from stations to residents\n    vector<vector<ll>> dist_sq(N, vector<ll>(K));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < K; j++) {\n            ll dx = x[i] - a[j];\n            ll dy = y[i] - b[j];\n            dist_sq[i][j] = dx * dx + dy * dy;\n        }\n    }\n    \n    // Precompute shortest paths between stations using Floyd-Warshall\n    vector<vector<ll>> dist_station(N, vector<ll>(N, 1e18));\n    vector<vector<int>> next_hop(N, vector<int>(N, -1));\n    for (int i = 0; i < N; i++) {\n        dist_station[i][i] = 0;\n        next_hop[i][i] = i;\n    }\n    for (int i = 0; i < M; i++) {\n        auto [u, v, w] = edges[i];\n        if (w < dist_station[u][v]) {\n            dist_station[u][v] = w;\n            dist_station[v][u] = w;\n            next_hop[u][v] = v;\n            next_hop[v][u] = u;\n        }\n    }\n    for (int k = 0; k < N; k++) {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (dist_station[i][k] < 1e18 && dist_station[k][j] < 1e18) {\n                    if (dist_station[i][j] > dist_station[i][k] + dist_station[k][j]) {\n                        dist_station[i][j] = dist_station[i][k] + dist_station[k][j];\n                        next_hop[i][j] = next_hop[i][k];\n                    }\n                }\n            }\n        }\n    }\n    \n    // Initial assignment: assign each resident to the nearest station\n    vector<int> assignment(K);\n    vector<multiset<ll>> station_residents(N);\n    for (int j = 0; j < K; j++) {\n        int best_station = 0;\n        ll min_d_sq = dist_sq[0][j];\n        for (int i = 1; i < N; i++) {\n            if (dist_sq[i][j] < min_d_sq) {\n                min_d_sq = dist_sq[i][j];\n                best_station = i;\n            }\n        }\n        assignment[j] = best_station;\n        station_residents[best_station].insert(dist_sq[best_station][j]);\n    }\n    \n    // Function to compute P_i from a multiset of squared distances\n    auto compute_P = [](const multiset<ll>& residents) -> ll {\n        if (residents.empty()) return 0;\n        ll max_d_sq = *residents.rbegin();\n        ll P = sqrt(max_d_sq);\n        if (P * P < max_d_sq) P++;\n        return min(P, 5000LL);\n    };\n    \n    // Function to build MST on a set of stations\n    auto build_mst = [&](const set<int>& S) -> tuple<ll, set<pair<int, int>>> {\n        if (S.empty()) return {0, {}};\n        // Create a list of stations in S\n        vector<int> stations(S.begin(), S.end());\n        int n_s = stations.size();\n        // Map station index to index in the list\n        map<int, int> station_index;\n        for (int i = 0; i < n_s; i++) {\n            station_index[stations[i]] = i;\n        }\n        // Build complete graph on stations\n        vector<vector<ll>> dist_s(n_s, vector<ll>(n_s, 1e18));\n        for (int i = 0; i < n_s; i++) {\n            for (int j = i+1; j < n_s; j++) {\n                int u = stations[i], v = stations[j];\n                dist_s[i][j] = dist_station[u][v];\n                dist_s[j][i] = dist_station[u][v];\n            }\n        }\n        // Prim's algorithm\n        vector<ll> key(n_s, 1e18);\n        vector<int> parent(n_s, -1);\n        vector<bool> in_mst(n_s, false);\n        key[0] = 0;\n        priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n        pq.push({0, 0});\n        while (!pq.empty()) {\n            int u = pq.top().second;\n            pq.pop();\n            if (in_mst[u]) continue;\n            in_mst[u] = true;\n            for (int v = 0; v < n_s; v++) {\n                if (!in_mst[v] && dist_s[u][v] < key[v]) {\n                    key[v] = dist_s[u][v];\n                    parent[v] = u;\n                    pq.push({key[v], v});\n                }\n            }\n        }\n        // Collect MST edges\n        set<pair<int, int>> mst_edges;\n        ll total_cost = 0;\n        for (int i = 1; i < n_s; i++) {\n            int u = stations[i], v = stations[parent[i]];\n            if (u > v) swap(u, v);\n            mst_edges.insert({u, v});\n            total_cost += dist_station[u][v];\n        }\n        return {total_cost, mst_edges};\n    };\n    \n    // Function to get the path between two stations and mark edges\n    auto mark_path_edges = [&](int u, int v, vector<bool>& edge_on) {\n        if (u == v) return;\n        int current = u;\n        while (current != v) {\n            int next = next_hop[current][v];\n            int u1 = current, v1 = next;\n            if (u1 > v1) swap(u1, v1);\n            auto it = edge_index_map.find({u1, v1});\n            if (it != edge_index_map.end()) {\n                edge_on[it->second] = true;\n            }\n            current = next;\n        }\n    };\n    \n    // Initial set S: stations with at least one resident\n    set<int> S;\n    for (int i = 0; i < N; i++) {\n        if (!station_residents[i].empty()) {\n            S.insert(i);\n        }\n    }\n    \n    // Build initial MST\n    auto [current_edge_cost, mst_edges] = build_mst(S);\n    \n    // Compute initial power cost\n    ll current_power_cost = 0;\n    vector<ll> P(N, 0);\n    for (int i = 0; i < N; i++) {\n        P[i] = compute_P(station_residents[i]);\n        current_power_cost += P[i] * P[i];\n    }\n    ll current_total_cost = current_power_cost + current_edge_cost;\n    \n    // Local search improvement\n    bool improved = true;\n    int max_iter = 10;\n    for (int iter = 0; iter < max_iter && improved; iter++) {\n        improved = false;\n        // Create a list of residents in random order\n        vector<int> residents(K);\n        iota(residents.begin(), residents.end(), 0);\n        random_shuffle(residents.begin(), residents.end());\n        \n        for (int j : residents) {\n            int old_station = assignment[j];\n            ll old_d_sq = dist_sq[old_station][j];\n            // Remove j from old_station\n            station_residents[old_station].erase(station_residents[old_station].find(old_d_sq));\n            ll old_P_old = P[old_station];\n            P[old_station] = compute_P(station_residents[old_station]);\n            ll power_cost_without_j = current_power_cost - old_P_old * old_P_old + P[old_station] * P[old_station];\n            \n            // Try reassigning to other stations in S\n            for (int new_station : S) {\n                if (new_station == old_station) continue;\n                ll new_d_sq = dist_sq[new_station][j];\n                ll old_P_new = P[new_station];\n                station_residents[new_station].insert(new_d_sq);\n                P[new_station] = compute_P(station_residents[new_station]);\n                ll new_power_cost = power_cost_without_j - old_P_new * old_P_new + P[new_station] * P[new_station];\n                \n                // Check if power cost improves\n                if (new_power_cost < current_power_cost) {\n                    // Accept reassignment\n                    assignment[j] = new_station;\n                    current_power_cost = new_power_cost;\n                    improved = true;\n                    // Update S if old_station becomes empty\n                    if (station_residents[old_station].empty()) {\n                        S.erase(old_station);\n                    }\n                    // new_station is already in S\n                    break;\n                } else {\n                    // Revert changes to new_station\n                    station_residents[new_station].erase(station_residents[new_station].find(new_d_sq));\n                    P[new_station] = old_P_new;\n                }\n            }\n            // If not reassigned, revert old_station\n            if (assignment[j] == old_station) {\n                station_residents[old_station].insert(old_d_sq);\n                P[old_station] = old_P_old;\n            }\n        }\n        \n        // After reassignment, update S and rebuild MST\n        S.clear();\n        for (int i = 0; i < N; i++) {\n            if (!station_residents[i].empty()) {\n                S.insert(i);\n            }\n        }\n        tie(current_edge_cost, mst_edges) = build_mst(S);\n        current_total_cost = current_power_cost + current_edge_cost;\n    }\n    \n    // Final output preparation\n    // Compute final P values\n    for (int i = 0; i < N; i++) {\n        P[i] = compute_P(station_residents[i]);\n    }\n    \n    // Mark edges for MST\n    vector<bool> edge_on(M, false);\n    for (auto [u, v] : mst_edges) {\n        mark_path_edges(u, v, edge_on);\n    }\n    \n    // Output P and B\n    for (int i = 0; i < N; i++) {\n        cout << P[i];\n        if (i < N-1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    for (int i = 0; i < M; i++) {\n        cout << (edge_on[i] ? 1 : 0);\n        if (i < M-1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <tuple>\nusing namespace std;\n\nconst int N = 30;\n\nint main() {\n    vector<vector<int>> pyramid(N);\n    for (int x = 0; x < N; x++) {\n        for (int y = 0; y <= x; y++) {\n            int num;\n            cin >> num;\n            pyramid[x].push_back(num);\n        }\n    }\n\n    vector<tuple<int, int, int, int>> swaps;\n\n    for (int x = N-2; x >= 0; x--) {\n        for (int y = 0; y <= x; y++) {\n            int current_x = x;\n            int current_y = y;\n            while (current_x < N-1) {\n                int child1_x = current_x + 1;\n                int child1_y = current_y;\n                int child2_x = current_x + 1;\n                int child2_y = current_y + 1;\n\n                int current_val = pyramid[current_x][current_y];\n                int child1_val = pyramid[child1_x][child1_y];\n                int child2_val = pyramid[child2_x][child2_y];\n\n                if (current_val <= child1_val && current_val <= child2_val) {\n                    break;\n                }\n\n                int swap_x, swap_y;\n                if (child1_val <= child2_val) {\n                    swap_x = child1_x;\n                    swap_y = child1_y;\n                } else {\n                    swap_x = child2_x;\n                    swap_y = child2_y;\n                }\n\n                swap(pyramid[current_x][current_y], pyramid[swap_x][swap_y]);\n                swaps.push_back({current_x, current_y, swap_x, swap_y});\n\n                current_x = swap_x;\n                current_y = swap_y;\n            }\n        }\n    }\n\n    cout << swaps.size() << endl;\n    for (const auto& swap : swaps) {\n        cout << get<0>(swap) << \" \" << get<1>(swap) << \" \" << get<2>(swap) << \" \" << get<3>(swap) << endl;\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = 4;\n\nvector<vector<int>> grid;\nvector<pair<int, int>> container_positions;\n\n// Directions: up, down, left, right\nconst int di[] = {-1, 1, 0, 0};\nconst int dj[] = {0, 0, -1, 1};\n\n// Check if a position is valid and empty\nbool is_valid(int i, int j) {\n    return i >= 0 && i < D && j >= 0 && j < D && grid[i][j] == -1;\n}\n\n// BFS to find reachable positions from entrance\nvector<pair<int, int>> get_reachable_positions() {\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> reachable;\n    \n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            \n            if (ni >= 0 && ni < D && nj >= 0 && nj < D && \n                !visited[ni][nj] && grid[ni][nj] == -1) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                reachable.push_back({ni, nj});\n            }\n        }\n    }\n    \n    return reachable;\n}\n\n// Calculate Manhattan distance from entrance\nint distance_from_entrance(int i, int j) {\n    return abs(i - ENTRANCE_I) + abs(j - ENTRANCE_J);\n}\n\n// Find best position for placement based on container number\npair<int, int> find_best_position(int container_num, int total_containers) {\n    auto reachable = get_reachable_positions();\n    \n    if (reachable.empty()) {\n        // Should not happen if grid is properly connected\n        for (int i = 0; i < D; i++) {\n            for (int j = 0; j < D; j++) {\n                if (grid[i][j] == -1) {\n                    return {i, j};\n                }\n            }\n        }\n    }\n    \n    // Sort positions by distance from entrance\n    sort(reachable.begin(), reachable.end(), [](const pair<int, int>& a, const pair<int, int>& b) {\n        int dist_a = distance_from_entrance(a.first, a.second);\n        int dist_b = distance_from_entrance(b.first, b.second);\n        return dist_a < dist_b;\n    });\n    \n    // Use container number to determine placement strategy\n    // Lower numbers should be placed closer to exit for easier retrieval\n    int idx = (container_num * reachable.size()) / total_containers;\n    idx = min(idx, (int)reachable.size() - 1);\n    \n    return reachable[idx];\n}\n\n// Get accessible containers for retrieval\nvector<pair<int, int>> get_accessible_containers() {\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> accessible;\n    \n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        // Check if current position has a container\n        if (grid[i][j] >= 0) {\n            accessible.push_back({i, j});\n        }\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            \n            if (ni >= 0 && ni < D && nj >= 0 && nj < D && \n                !visited[ni][nj] && grid[ni][nj] != -2) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    return accessible;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read warehouse configuration\n    int N;\n    cin >> D >> N;\n    \n    // Initialize grid: -2 = obstacle, -1 = empty, >=0 = container number\n    grid.assign(D, vector<int>(D, -1));\n    container_positions.clear();\n    \n    // Mark entrance and adjacent squares\n    grid[ENTRANCE_I][ENTRANCE_J] = -3; // Entrance\n    grid[ENTRANCE_I][ENTRANCE_J-1] = -1;\n    grid[ENTRANCE_I][ENTRANCE_J+1] = -1;\n    grid[ENTRANCE_I+1][ENTRANCE_J] = -1;\n    \n    // Read obstacles\n    for (int k = 0; k < N; k++) {\n        int ri, rj;\n        cin >> ri >> rj;\n        grid[ri][rj] = -2; // Obstacle\n    }\n    \n    int total_containers = D * D - 1 - N;\n    \n    // Process container arrivals\n    for (int d = 0; d < total_containers; d++) {\n        int container_num;\n        cin >> container_num;\n        \n        // Find best position for this container\n        auto [pi, pj] = find_best_position(container_num, total_containers);\n        \n        // Place container\n        grid[pi][pj] = container_num;\n        container_positions.push_back({pi, pj});\n        \n        // Output placement\n        cout << pi << \" \" << pj << endl;\n        cout.flush();\n    }\n    \n    // Determine retrieval order using greedy strategy\n    vector<pair<int, int>> retrieval_order;\n    \n    while (retrieval_order.size() < total_containers) {\n        auto accessible = get_accessible_containers();\n        \n        if (accessible.empty()) {\n            break; // Should not happen\n        }\n        \n        // Find container with smallest number\n        int best_idx = 0;\n        int best_num = grid[accessible[0].first][accessible[0].second];\n        \n        for (int i = 1; i < accessible.size(); i++) {\n            int current_num = grid[accessible[i].first][accessible[i].second];\n            if (current_num < best_num) {\n                best_num = current_num;\n                best_idx = i;\n            }\n        }\n        \n        auto [qi, qj] = accessible[best_idx];\n        retrieval_order.push_back({qi, qj});\n        grid[qi][qj] = -1; // Remove container\n    }\n    \n    // Output retrieval order\n    for (auto [qi, qj] : retrieval_order) {\n        cout << qi << \" \" << qj << endl;\n    }\n    cout.flush();\n    \n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> grid(n, vector<int>(n));\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> grid[i][j];\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cout << grid[i][j];\n            if (j < n - 1) cout << \" \";\n        }\n        cout << endl;\n    }\n    \n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n\n    vector<double> ratings(N, 1000.0);\n\n    vector<pair<int, int>> distinct_pairs;\n    for (int i = 0; i < N; i++) {\n        for (int j = i + 1; j < N; j++) {\n            distinct_pairs.push_back({i, j});\n        }\n    }\n\n    random_device rd;\n    mt19937 g(rd());\n    shuffle(distinct_pairs.begin(), distinct_pairs.end(), g);\n\n    vector<pair<int, int>> query_pairs;\n    int L = distinct_pairs.size();\n    for (int i = 0; i < Q; i++) {\n        query_pairs.push_back(distinct_pairs[i % L]);\n    }\n\n    const double K = 32.0;\n\n    for (int q = 0; q < Q; q++) {\n        int i = query_pairs[q].first;\n        int j = query_pairs[q].second;\n\n        cout << \"1 1 \" << i << \" \" << j << endl;\n        cout.flush();\n\n        string result;\n        cin >> result;\n\n        double outcome_i, outcome_j;\n        if (result == \">\") {\n            outcome_i = 1.0;\n            outcome_j = 0.0;\n        } else if (result == \"<\") {\n            outcome_i = 0.0;\n            outcome_j = 1.0;\n        } else {\n            outcome_i = 0.5;\n            outcome_j = 0.5;\n        }\n\n        double diff = ratings[j] - ratings[i];\n        double expected_i = 1.0 / (1.0 + pow(10.0, diff / 400.0));\n        double expected_j = 1.0 - expected_i;\n\n        ratings[i] += K * (outcome_i - expected_i);\n        ratings[j] += K * (outcome_j - expected_j);\n    }\n\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n    sort(indices.begin(), indices.end(), [&ratings](int a, int b) {\n        return ratings[a] > ratings[b];\n    });\n\n    vector<double> bin_sums(D, 0.0);\n    vector<int> assignment(N);\n    for (int idx : indices) {\n        int min_bin = 0;\n        for (int b = 1; b < D; b++) {\n            if (bin_sums[b] < bin_sums[min_bin]) {\n                min_bin = b;\n            }\n        }\n        assignment[idx] = min_bin;\n        bin_sums[min_bin] += ratings[idx];\n    }\n\n    for (int i = 0; i < N; i++) {\n        cout << assignment[i];\n        if (i < N - 1) {\n            cout << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <queue>\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    \n    vector<vector<int>> stacks(m + 1);\n    vector<int> box_pos(n + 1, -1); // stack index for each box\n    vector<int> box_height(n + 1, -1); // height in stack for each box\n    \n    // Read initial configuration\n    for (int i = 1; i <= m; i++) {\n        for (int j = 0; j < n / m; j++) {\n            int box;\n            cin >> box;\n            stacks[i].push_back(box);\n            box_pos[box] = i;\n            box_height[box] = j + 1;\n        }\n    }\n    \n    vector<pair<int, int>> operations;\n    int next_box = 1;\n    vector<bool> carried_out(n + 1, false);\n    \n    // Precompute target stack for each box\n    vector<int> target_stack(n + 1);\n    int boxes_per_stack = n / m;\n    for (int i = 1; i <= n; i++) {\n        // Assign boxes to stacks in ranges\n        target_stack[i] = (i - 1) / boxes_per_stack + 1;\n        if (target_stack[i] > m) target_stack[i] = m;\n    }\n    \n    while (next_box <= n) {\n        // Check if next_box is already at top and can be carried out\n        int current_stack = box_pos[next_box];\n        int current_height = box_height[next_box];\n        \n        // Check if next_box is at top of its stack\n        bool is_top = true;\n        for (int box : stacks[current_stack]) {\n            if (box == next_box) {\n                // Check if there are boxes above it\n                auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), next_box);\n                if (it != stacks[current_stack].end() - 1) {\n                    is_top = false;\n                }\n                break;\n            }\n        }\n        \n        if (is_top) {\n            // Carry out the box\n            operations.push_back({next_box, 0});\n            carried_out[next_box] = true;\n            \n            // Remove from stack\n            auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), next_box);\n            if (it != stacks[current_stack].end()) {\n                stacks[current_stack].erase(it);\n            }\n            \n            next_box++;\n            continue;\n        }\n        \n        // next_box is not at top, need to move boxes above it\n        // Find the boxes above next_box in its current stack\n        vector<int> boxes_to_move;\n        bool found_next = false;\n        \n        for (int box : stacks[current_stack]) {\n            if (box == next_box) {\n                found_next = true;\n                continue;\n            }\n            if (found_next && !carried_out[box]) {\n                boxes_to_move.push_back(box);\n            }\n        }\n        \n        if (boxes_to_move.empty()) {\n            // This shouldn't happen if next_box is not at top\n            next_box++;\n            continue;\n        }\n        \n        // Choose destination stack - prefer target stack or empty stacks\n        int dest_stack = -1;\n        \n        // First try: move to target stack of the top box in the moving segment\n        int top_box = boxes_to_move.back();\n        int preferred_dest = target_stack[top_box];\n        \n        if (preferred_dest != current_stack && !carried_out[top_box]) {\n            dest_stack = preferred_dest;\n        } else {\n            // Find an empty stack or one with minimal disruption\n            for (int i = 1; i <= m; i++) {\n                if (i != current_stack && stacks[i].size() < boxes_per_stack) {\n                    dest_stack = i;\n                    break;\n                }\n            }\n            \n            // If no suitable stack found, use the one with most space\n            if (dest_stack == -1) {\n                for (int i = 1; i <= m; i++) {\n                    if (i != current_stack) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n        }\n        \n        if (dest_stack == -1) {\n            // Fallback: use stack 1 if all else fails\n            dest_stack = 1;\n            if (dest_stack == current_stack) dest_stack = 2;\n        }\n        \n        // Move the top box in the blocking segment\n        int box_to_move = boxes_to_move.back();\n        operations.push_back({box_to_move, dest_stack});\n        \n        // Update stack configuration\n        auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), box_to_move);\n        if (it != stacks[current_stack].end()) {\n            // Move this box and all boxes above it to destination stack\n            vector<int> moving_boxes(it, stacks[current_stack].end());\n            stacks[current_stack].erase(it, stacks[current_stack].end());\n            \n            // Add to destination stack\n            stacks[dest_stack].insert(stacks[dest_stack].end(), moving_boxes.begin(), moving_boxes.end());\n            \n            // Update positions\n            for (int i = 0; i < moving_boxes.size(); i++) {\n                box_pos[moving_boxes[i]] = dest_stack;\n                box_height[moving_boxes[i]] = stacks[dest_stack].size() - moving_boxes.size() + i + 1;\n            }\n        }\n        \n        // Safety check to prevent infinite loops\n        if (operations.size() > 4500) {\n            // Force carry out if we're approaching limit\n            for (int i = 1; i <= n; i++) {\n                if (!carried_out[i] && box_height[i] == (int)stacks[box_pos[i]].size()) {\n                    operations.push_back({i, 0});\n                    carried_out[i] = true;\n                    auto it2 = find(stacks[box_pos[i]].begin(), stacks[box_pos[i]].end(), i);\n                    if (it2 != stacks[box_pos[i]].end()) {\n                        stacks[box_pos[i]].erase(it2);\n                    }\n                }\n            }\n            break;\n        }\n    }\n    \n    // Output operations\n    for (auto op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n    \n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <cmath>\nusing namespace std;\n\nint main() {\n    int N;\n    cin >> N;\n    \n    vector<string> h(N-1);\n    for (int i = 0; i < N-1; i++) {\n        cin >> h[i];\n    }\n    \n    vector<string> v(N);\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\n    }\n    \n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n        }\n    }\n    \n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    queue<pair<int, int>> q;\n    dist[0][0] = 0;\n    q.push({0, 0});\n    \n    while (!q.empty()) {\n        int i = q.front().first;\n        int j = q.front().second;\n        q.pop();\n        \n        if (i > 0 && h[i-1][j] == '0') {\n            if (dist[i-1][j] == -1) {\n                dist[i-1][j] = dist[i][j] + 1;\n                q.push({i-1, j});\n            }\n        }\n        if (i < N-1 && h[i][j] == '0') {\n            if (dist[i+1][j] == -1) {\n                dist[i+1][j] = dist[i][j] + 1;\n                q.push({i+1, j});\n            }\n        }\n        if (j > 0 && v[i][j-1] == '0') {\n            if (dist[i][j-1] == -1) {\n                dist[i][j-1] = dist[i][j] + 1;\n                q.push({i, j-1});\n            }\n        }\n        if (j < N-1 && v[i][j] == '0') {\n            if (dist[i][j+1] == -1) {\n                dist[i][j+1] = dist[i][j] + 1;\n                q.push({i, j+1});\n            }\n        }\n    }\n    \n    const int L = 100000;\n    int current_i = 0, current_j = 0;\n    vector<vector<int>> V(N, vector<int>(N, 0));\n    string moves;\n    \n    for (int t = 0; t < L; t++) {\n        int rem_after = L - t - 1;\n        double best_weight = -1.0;\n        char best_dir = 'U';\n        int best_i = current_i, best_j = current_j;\n        \n        if (current_i > 0 && h[current_i-1][current_j] == '0') {\n            int new_i = current_i - 1;\n            int new_j = current_j;\n            if (dist[new_i][new_j] <= rem_after) {\n                double weight;\n                if (V[new_i][new_j] == 0) {\n                    weight = d[new_i][new_j] * 1000000.0;\n                } else {\n                    weight = d[new_i][new_j] / static_cast<double>(V[new_i][new_j] * V[new_i][new_j]);\n                }\n                if (weight > best_weight) {\n                    best_weight = weight;\n                    best_dir = 'U';\n                    best_i = new_i;\n                    best_j = new_j;\n                }\n            }\n        }\n        \n        if (current_i < N-1 && h[current_i][current_j] == '0') {\n            int new_i = current_i + 1;\n            int new_j = current_j;\n            if (dist[new_i][new_j] <= rem_after) {\n                double weight;\n                if (V[new_i][new_j] == 0) {\n                    weight = d[new_i][new_j] * 1000000.0;\n                } else {\n                    weight = d[new_i][new_j] / static_cast<double>(V[new_i][new_j] * V[new_i][new_j]);\n                }\n                if (weight > best_weight) {\n                    best_weight = weight;\n                    best_dir = 'D';\n                    best_i = new_i;\n                    best_j = new_j;\n                }\n            }\n        }\n        \n        if (current_j > 0 && v[current_i][current_j-1] == '0') {\n            int new_i = current_i;\n            int new_j = current_j - 1;\n            if (dist[new_i][new_j] <= rem_after) {\n                double weight;\n                if (V[new_i][new_j] == 0) {\n                    weight = d[new_i][new_j] * 1000000.0;\n                } else {\n                    weight = d[new_i][new_j] / static_cast<double>(V[new_i][new_j] * V[new_i][new_j]);\n                }\n                if (weight > best_weight) {\n                    best_weight = weight;\n                    best_dir = 'L';\n                    best_i = new_i;\n                    best_j = new_j;\n                }\n            }\n        }\n        \n        if (current_j < N-1 && v[current_i][current_j] == '0') {\n            int new_i = current_i;\n            int new_j = current_j + 1;\n            if (dist[new_i][new_j] <= rem_after) {\n                double weight;\n                if (V[new_i][new_j] == 0) {\n                    weight = d[new_i][new_j] * 1000000.0;\n                } else {\n                    weight = d[new_i][new_j] / static_cast<double>(V[new_i][new_j] * V[new_i][new_j]);\n                }\n                if (weight > best_weight) {\n                    best_weight = weight;\n                    best_dir = 'R';\n                    best_i = new_i;\n                    best_j = new_j;\n                }\n            }\n        }\n        \n        moves += best_dir;\n        current_i = best_i;\n        current_j = best_j;\n        V[current_i][current_j]++;\n    }\n    \n    cout << moves << endl;\n    \n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <map>\n#include <limits>\n#include <cmath>\n\nusing namespace std;\n\nconst int INF = numeric_limits<int>::max();\n\nint dist(pair<int, int> a, pair<int, int> b) {\n    return abs(a.first - b.first) + abs(a.second - b.second);\n}\n\npair<int, pair<int, int>> cost_to_type(const string& str, const pair<int, int>& start, const map<char, vector<pair<int, int>>>& letter_points) {\n    int L = str.length();\n    if (L == 0) return {0, start};\n\n    vector<map<pair<int, int>, int>> dp(L);\n    vector<map<pair<int, int>, pair<int, int>>> prev(L);\n\n    char c0 = str[0];\n    if (letter_points.find(c0) == letter_points.end()) return {INF, {0,0}};\n    for (auto p : letter_points.at(c0)) {\n        int cost = dist(start, p) + 1;\n        dp[0][p] = cost;\n        prev[0][p] = start;\n    }\n\n    for (int i = 1; i < L; i++) {\n        char c = str[i];\n        if (letter_points.find(c) == letter_points.end()) return {INF, {0,0}};\n        for (auto p : letter_points.at(c)) {\n            int best_cost = INF;\n            pair<int, int> best_prev;\n            char prev_c = str[i-1];\n            if (letter_points.find(prev_c) == letter_points.end()) return {INF, {0,0}};\n            for (auto q : letter_points.at(prev_c)) {\n                if (dp[i-1].find(q) == dp[i-1].end()) continue;\n                int cost = dp[i-1][q] + dist(q, p) + 1;\n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_prev = q;\n                }\n            }\n            if (best_cost < INF) {\n                dp[i][p] = best_cost;\n                prev[i][p] = best_prev;\n            }\n        }\n    }\n\n    int min_cost = INF;\n    pair<int, int> end_pos = start;\n    char last_c = str[L-1];\n    if (letter_points.find(last_c) == letter_points.end()) return {INF, {0,0}};\n    for (auto p : letter_points.at(last_c)) {\n        if (dp[L-1].find(p) != dp[L-1].end() && dp[L-1][p] < min_cost) {\n            min_cost = dp[L-1][p];\n            end_pos = p;\n        }\n    }\n    if (min_cost == INF) return {INF, start};\n    return {min_cost, end_pos};\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int s_i, s_j;\n    cin >> s_i >> s_j;\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    vector<string> words(M);\n    for (int i = 0; i < M; i++) {\n        cin >> words[i];\n    }\n\n    map<char, vector<pair<int, int>>> letter_points;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            char c = grid[i][j];\n            letter_points[c].push_back({i, j});\n        }\n    }\n\n    pair<int, int> current_pos = {s_i, s_j};\n    vector<string> uncovered_words = words;\n    string S = \"\";\n\n    if (!uncovered_words.empty()) {\n        int min_cost = INF;\n        string best_word;\n        pair<int, int> best_end_pos;\n        for (string w : uncovered_words) {\n            auto [cost, end_pos] = cost_to_type(w, current_pos, letter_points);\n            if (cost < min_cost) {\n                min_cost = cost;\n                best_word = w;\n                best_end_pos = end_pos;\n            }\n        }\n        S = best_word;\n        current_pos = best_end_pos;\n        uncovered_words.erase(find(uncovered_words.begin(), uncovered_words.end(), best_word));\n    }\n\n    while (!uncovered_words.empty()) {\n        int min_cost = INF;\n        string best_word;\n        string best_suffix;\n        pair<int, int> best_end_pos;\n        for (string w : uncovered_words) {\n            int max_overlap = 0;\n            for (int k = min(S.length(), w.length()); k > 0; k--) {\n                if (S.substr(S.length() - k) == w.substr(0, k)) {\n                    max_overlap = k;\n                    break;\n                }\n            }\n            string suffix = w.substr(max_overlap);\n            auto [cost, end_pos] = cost_to_type(suffix, current_pos, letter_points);\n            if (cost < min_cost) {\n                min_cost = cost;\n                best_word = w;\n                best_suffix = suffix;\n                best_end_pos = end_pos;\n            }\n        }\n        S += best_suffix;\n        current_pos = best_end_pos;\n        uncovered_words.erase(find(uncovered_words.begin(), uncovered_words.end(), best_word));\n    }\n\n    int L = S.size();\n    vector<vector<pair<int, int>>> points_for_S(L);\n    for (int i = 0; i < L; i++) {\n        points_for_S[i] = letter_points[S[i]];\n    }\n\n    pair<int, int> initial = {s_i, s_j};\n    vector<map<pair<int, int>, int>> dp(L);\n    vector<map<pair<int, int>, pair<int, int>>> prev(L);\n\n    for (auto p : points_for_S[0]) {\n        int cost = dist(initial, p) + 1;\n        dp[0][p] = cost;\n        prev[0][p] = initial;\n    }\n\n    for (int i = 1; i < L; i++) {\n        for (auto p : points_for_S[i]) {\n            int best_cost = INF;\n            pair<int, int> best_prev;\n            for (auto q : points_for_S[i-1]) {\n                if (dp[i-1].find(q) == dp[i-1].end()) continue;\n                int cost = dp[i-1][q] + dist(q, p) + 1;\n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_prev = q;\n                }\n            }\n            if (best_cost < INF) {\n                dp[i][p] = best_cost;\n                prev[i][p] = best_prev;\n            }\n        }\n    }\n\n    int min_cost = INF;\n    pair<int, int> best_point;\n    for (auto p : points_for_S[L-1]) {\n        if (dp[L-1].find(p) != dp[L-1].end() && dp[L-1][p] < min_cost) {\n            min_cost = dp[L-1][p];\n            best_point = p;\n        }\n    }\n\n    vector<pair<int, int>> sequence;\n    pair<int, int> current = best_point;\n    for (int i = L-1; i >= 0; i--) {\n        sequence.push_back(current);\n        if (i > 0) {\n            current = prev[i][current];\n        }\n    }\n    reverse(sequence.begin(), sequence.end());\n\n    for (auto p : sequence) {\n        cout << p.first << \" \" << p.second << endl;\n    }\n\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n\n    vector<vector<pair<int, int>>> fields(M);\n    for (int k = 0; k < M; k++) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < d; i++) {\n            int x, y;\n            cin >> x >> y;\n            fields[k].push_back({x, y});\n        }\n    }\n\n    vector<pair<int, int>> oil_squares;\n    \n    // Drill each square sequentially\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cout << \"q 1 \" << i << \" \" << j << endl;\n            int resp;\n            cin >> resp;\n            if (resp > 0) {\n                oil_squares.push_back({i, j});\n            }\n        }\n    }\n\n    // Output final answer\n    cout << \"a \" << oil_squares.size();\n    for (auto [i, j] : oil_squares) {\n        cout << \" \" << i << \" \" << j;\n    }\n    cout << endl;\n\n    int result;\n    cin >> result;\n    // Program ends after correct guess\n\n    return 0;\n}","ahc031":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nint main() {\n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    // Determine grid dimensions - aim for roughly square cells\n    int grid_size = ceil(sqrt(N));\n    int rows = grid_size;\n    int cols = ceil((double)N / rows);\n    \n    // Initialize grid lines - start with equal spacing\n    vector<vector<int>> h_lines(D, vector<int>(rows + 1));\n    vector<vector<int>> v_lines(D, vector<int>(cols + 1));\n    \n    // Day 0: Set up initial grid\n    for (int i = 0; i <= rows; i++) {\n        h_lines[0][i] = (i * W) / rows;\n    }\n    for (int j = 0; j <= cols; j++) {\n        v_lines[0][j] = (j * W) / cols;\n    }\n    \n    // For each day, adjust grid lines to meet area requirements\n    for (int d = 0; d < D; d++) {\n        if (d > 0) {\n            // Start with previous day's layout\n            h_lines[d] = h_lines[d-1];\n            v_lines[d] = v_lines[d-1];\n        }\n        \n        // Calculate current cell areas\n        vector<int> cell_areas;\n        for (int i = 0; i < rows; i++) {\n            for (int j = 0; j < cols; j++) {\n                int width = v_lines[d][j+1] - v_lines[d][j];\n                int height = h_lines[d][i+1] - h_lines[d][i];\n                cell_areas.push_back(width * height);\n            }\n        }\n        \n        // Sort both desired areas and cell areas\n        vector<int> sorted_areas = a[d];\n        sort(sorted_areas.begin(), sorted_areas.end());\n        sort(cell_areas.begin(), cell_areas.end());\n        \n        // Adjust grid lines to better match area requirements\n        // Focus on horizontal lines first (affects row heights)\n        for (int iter = 0; iter < 2; iter++) {\n            for (int i = 1; i < rows; i++) {\n                int left_area = 0, right_area = 0;\n                \n                // Calculate total desired area for left and right sections\n                for (int k = 0; k < N; k++) {\n                    if (k < i * cols) {\n                        left_area += sorted_areas[k];\n                    } else {\n                        right_area += sorted_areas[k];\n                    }\n                }\n                \n                // Adjust horizontal line proportionally\n                int total_area = left_area + right_area;\n                if (total_area > 0) {\n                    int target_line = (left_area * W) / total_area;\n                    // Smooth adjustment to avoid large changes\n                    h_lines[d][i] = (h_lines[d][i] + target_line) / 2;\n                }\n            }\n            \n            // Adjust vertical lines similarly\n            for (int j = 1; j < cols; j++) {\n                int left_area = 0, right_area = 0;\n                \n                for (int k = 0; k < N; k++) {\n                    int col = k % cols;\n                    if (col < j) {\n                        left_area += sorted_areas[k];\n                    } else {\n                        right_area += sorted_areas[k];\n                    }\n                }\n                \n                int total_area = left_area + right_area;\n                if (total_area > 0) {\n                    int target_line = (left_area * W) / total_area;\n                    v_lines[d][j] = (v_lines[d][j] + target_line) / 2;\n                }\n            }\n        }\n        \n        // Ensure boundaries\n        h_lines[d][0] = 0;\n        h_lines[d][rows] = W;\n        v_lines[d][0] = 0;\n        v_lines[d][cols] = W;\n        \n        // Output assignments for this day\n        for (int k = 0; k < N; k++) {\n            int i = k / cols;\n            int j = k % cols;\n            \n            int i0 = h_lines[d][i];\n            int j0 = v_lines[d][j];\n            int i1 = h_lines[d][i+1];\n            int j1 = v_lines[d][j+1];\n            \n            // Ensure minimum area requirement is met\n            int current_area = (i1 - i0) * (j1 - j0);\n            int desired_area = a[d][k];\n            \n            if (current_area < desired_area) {\n                // Expand rectangle to meet requirement\n                int shortage = desired_area - current_area;\n                int expand_x = min(shortage / (i1 - i0), W - j1);\n                int expand_y = min(shortage / (j1 - j0), W - i1);\n                \n                if (expand_x > expand_y) {\n                    j1 += expand_x;\n                } else {\n                    i1 += expand_y;\n                }\n            }\n            \n            cout << i0 << \" \" << j0 << \" \" << i1 << \" \" << j1 << endl;\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <tuple>\n#include <set>\n#include <map>\n#include <cstdlib>\n#include <ctime>\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\n\nint main() {\n    srand(time(0)); // Seed the random number generator\n\n    int n, m, k;\n    cin >> n >> m >> k;\n    \n    int a[N][N];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> a[i][j];\n        }\n    }\n    \n    int stamps[M][3][3];\n    for (int mm = 0; mm < m; mm++) {\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                cin >> stamps[mm][i][j];\n            }\n        }\n    }\n    \n    int u[N][N];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            u[i][j] = a[i][j] % MOD;\n        }\n    }\n    \n    vector<tuple<int, int, int>> operations;\n    int max_p = n - 3;\n    int max_q = n - 3;\n    \n    // Greedy algorithm: select the best operation at each step\n    for (int step = 0; step < k; step++) {\n        int best_delta = -1000000000;\n        int best_m = -1, best_p = -1, best_q = -1;\n        \n        for (int mm = 0; mm < m; mm++) {\n            for (int p = 0; p <= max_p; p++) {\n                for (int q = 0; q <= max_q; q++) {\n                    int delta = 0;\n                    for (int i = 0; i < 3; i++) {\n                        for (int j = 0; j < 3; j++) {\n                            int x = p + i;\n                            int y = q + j;\n                            int current_u = u[x][y];\n                            int s_val = stamps[mm][i][j];\n                            int new_u = (current_u + s_val) % MOD;\n                            delta += new_u - current_u;\n                        }\n                    }\n                    if (delta > best_delta) {\n                        best_delta = delta;\n                        best_m = mm;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n        \n        if (best_delta <= 0) {\n            break; // Stop if no positive gain\n        }\n        \n        // Apply the best operation\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = best_p + i;\n                int y = best_q + j;\n                int s_val = stamps[best_m][i][j];\n                u[x][y] = (u[x][y] + s_val) % MOD;\n            }\n        }\n        \n        operations.push_back(make_tuple(best_m, best_p, best_q));\n    }\n    \n    // Local search: refine the solution by changing operations\n    int num_iterations = 100;\n    for (int iter = 0; iter < num_iterations; iter++) {\n        if (operations.empty()) {\n            break;\n        }\n        int idx = rand() % operations.size();\n        int old_m, old_p, old_q;\n        tie(old_m, old_p, old_q) = operations[idx];\n        \n        int new_m = rand() % M;\n        int new_p = rand() % (max_p + 1);\n        int new_q = rand() % (max_q + 1);\n        \n        if (old_m == new_m && old_p == new_p && old_q == new_q) {\n            continue;\n        }\n        \n        // Calculate the change in score\n        int delta_score = 0;\n        set<pair<int, int>> affected_cells;\n        map<pair<int, int>, int> delta_contrib;\n        \n        // Subtract the old operation's contribution\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = old_p + i;\n                int y = old_q + j;\n                affected_cells.insert({x, y});\n                delta_contrib[{x, y}] -= stamps[old_m][i][j];\n            }\n        }\n        \n        // Add the new operation's contribution\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = new_p + i;\n                int y = new_q + j;\n                affected_cells.insert({x, y});\n                delta_contrib[{x, y}] += stamps[new_m][i][j];\n            }\n        }\n        \n        // Compute the change in modulo values for affected cells\n        for (auto cell : affected_cells) {\n            int x = cell.first, y = cell.second;\n            int change = delta_contrib[{x, y}];\n            int old_u = u[x][y];\n            int new_u = (old_u + change) % MOD;\n            if (new_u < 0) new_u += MOD;\n            delta_score += new_u - old_u;\n        }\n        \n        // Accept the change if it improves the score\n        if (delta_score > 0) {\n            for (auto cell : affected_cells) {\n                int x = cell.first, y = cell.second;\n                int change = delta_contrib[{x, y}];\n                u[x][y] = (u[x][y] + change) % MOD;\n                if (u[x][y] < 0) u[x][y] += MOD;\n            }\n            operations[idx] = make_tuple(new_m, new_p, new_q);\n        }\n    }\n    \n    // Output the operations\n    cout << operations.size() << endl;\n    for (auto op : operations) {\n        int m, p, q;\n        tie(m, p, q) = op;\n        cout << m << \" \" << p << \" \" << q << endl;\n    }\n    \n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <array>\n#include <algorithm>\nusing namespace std;\n\nconst int N = 5;\n\narray<array<int, N>, N> grid;\narray<int, N> brought = {0};\narray<int, N> dispatched = {0};\narray<array<int, N>, N> A;\n\nstruct Crane {\n    int i, j;\n    bool carrying;\n    int container;\n    bool active;\n    bool is_large;\n};\n\nvector<Crane> cranes;\nvector<string> actions(N);\n\nvoid init_cranes() {\n    cranes.resize(N);\n    for (int i = 0; i < N; i++) {\n        cranes[i].i = i;\n        cranes[i].j = 0;\n        cranes[i].carrying = false;\n        cranes[i].active = true;\n        cranes[i].is_large = (i == 0);\n    }\n}\n\nbool is_crane_on(int i, int j) {\n    for (const Crane& crane : cranes) {\n        if (crane.active && crane.i == i && crane.j == j) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> A[i][j];\n        }\n    }\n\n    init_cranes();\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            grid[i][j] = -1;\n        }\n    }\n\n    int turns = 0;\n    const int max_turns = 10000;\n\n    while (turns < max_turns) {\n        for (int i = 0; i < N; i++) {\n            if (brought[i] < N && grid[i][0] == -1 && !is_crane_on(i, 0)) {\n                grid[i][0] = A[i][brought[i]];\n                brought[i]++;\n            }\n        }\n\n        vector<Crane> old_cranes = cranes;\n        for (int idx = 0; idx < N; idx++) {\n            Crane& crane = cranes[idx];\n            if (!crane.active) {\n                actions[idx] += '.';\n                continue;\n            }\n\n            if (!crane.is_large) {\n                if (crane.j == 0) {\n                    actions[idx] += 'R';\n                    crane.j = 1;\n                } else {\n                    actions[idx] += '.';\n                }\n            } else {\n                if (crane.carrying) {\n                    int b = crane.container;\n                    int target_i = b / N;\n                    if (crane.i == target_i) {\n                        bool placed = false;\n                        if (b == target_i * N + dispatched[target_i]) {\n                            if (grid[target_i][N-1] == -1 && !is_crane_on(target_i, N-1)) {\n                                actions[idx] += 'Q';\n                                grid[target_i][N-1] = b;\n                                crane.carrying = false;\n                                placed = true;\n                            }\n                        }\n                        if (!placed) {\n                            for (int j = 1; j < N-1; j++) {\n                                if (grid[target_i][j] == -1 && !is_crane_on(target_i, j)) {\n                                    if (crane.j != j) {\n                                        if (crane.j < j) actions[idx] += 'R';\n                                        else actions[idx] += 'L';\n                                        crane.j += (crane.j < j) ? 1 : -1;\n                                    } else {\n                                        actions[idx] += 'Q';\n                                        grid[target_i][j] = b;\n                                        crane.carrying = false;\n                                    }\n                                    placed = true;\n                                    break;\n                                }\n                            }\n                        }\n                        if (!placed) {\n                            actions[idx] += '.';\n                        }\n                    } else {\n                        if (crane.i < target_i) {\n                            actions[idx] += 'D';\n                            crane.i++;\n                        } else {\n                            actions[idx] += 'U';\n                            crane.i--;\n                        }\n                    }\n                } else {\n                    int pick_i = -1;\n                    for (int i = 0; i < N; i++) {\n                        if (grid[i][0] != -1 && !is_crane_on(i, 0)) {\n                            pick_i = i;\n                            break;\n                        }\n                    }\n                    if (pick_i != -1) {\n                        if (crane.i != pick_i) {\n                            if (crane.i < pick_i) {\n                                actions[idx] += 'D';\n                                crane.i++;\n                            } else {\n                                actions[idx] += 'U';\n                                crane.i--;\n                            }\n                        } else if (crane.j != 0) {\n                            if (crane.j > 0) {\n                                actions[idx] += 'L';\n                                crane.j--;\n                            }\n                        } else {\n                            actions[idx] += 'P';\n                            crane.carrying = true;\n                            crane.container = grid[pick_i][0];\n                            grid[pick_i][0] = -1;\n                        }\n                    } else {\n                        actions[idx] += '.';\n                    }\n                }\n            }\n        }\n\n        for (int i = 0; i < N; i++) {\n            if (grid[i][N-1] != -1) {\n                int b = grid[i][N-1];\n                grid[i][N-1] = -1;\n                if (b >= i * N && b < i * N + N) {\n                    dispatched[i]++;\n                }\n            }\n        }\n\n        turns++;\n        bool all_dispatched = true;\n        for (int i = 0; i < N; i++) {\n            if (dispatched[i] < N) {\n                all_dispatched = false;\n                break;\n            }\n        }\n        if (all_dispatched) break;\n    }\n\n    size_t max_len = 0;\n    for (int i = 0; i < N; i++) {\n        if (actions[i].size() > max_len) {\n            max_len = actions[i].size();\n        }\n    }\n    for (int i = 0; i < N; i++) {\n        string s = actions[i];\n        s.resize(max_len, '.');\n        cout << s << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nvector<string> get_moves(int from_i, int from_j, int to_i, int to_j) {\n    vector<string> moves;\n    int di = to_i - from_i;\n    int dj = to_j - from_j;\n    if (di > 0) {\n        for (int i = 0; i < di; i++) {\n            moves.push_back(\"D\");\n        }\n    } else if (di < 0) {\n        for (int i = 0; i < -di; i++) {\n            moves.push_back(\"U\");\n        }\n    }\n    if (dj > 0) {\n        for (int j = 0; j < dj; j++) {\n            moves.push_back(\"R\");\n        }\n    } else if (dj < 0) {\n        for (int j = 0; j < -dj; j++) {\n            moves.push_back(\"L\");\n        }\n    }\n    return moves;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<vector<int>> h_init(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h_init[i][j];\n        }\n    }\n\n    vector<vector<bool>> in_pos(N, vector<bool>(N, false));\n    vector<vector<bool>> in_neg(N, vector<bool>(N, false));\n\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (h_init[i][j] > 0) {\n                in_pos[i][j] = true;\n            } else if (h_init[i][j] < 0) {\n                in_neg[i][j] = true;\n            }\n        }\n    }\n\n    int current_i = 0, current_j = 0;\n    int load = 0;\n    vector<string> operations;\n\n    // Positive phase: visit all cells with positive height\n    while (true) {\n        bool has_pos = false;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (in_pos[i][j]) {\n                    has_pos = true;\n                    break;\n                }\n            }\n            if (has_pos) break;\n        }\n        if (!has_pos) break;\n\n        if (in_pos[current_i][current_j]) {\n            int d = h_init[current_i][current_j];\n            operations.push_back(\"+\" + to_string(d));\n            load += d;\n            in_pos[current_i][current_j] = false;\n        } else {\n            int best_i = -1, best_j = -1;\n            int best_cost = 1e9;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (in_pos[i][j]) {\n                        int dist = abs(i - current_i) + abs(j - current_j);\n                        int cost = dist * (100 + load) + h_init[i][j];\n                        if (cost < best_cost) {\n                            best_cost = cost;\n                            best_i = i;\n                            best_j = j;\n                        }\n                    }\n                }\n            }\n            if (best_i == -1) break;\n            vector<string> moves = get_moves(current_i, current_j, best_i, best_j);\n            operations.insert(operations.end(), moves.begin(), moves.end());\n            current_i = best_i;\n            current_j = best_j;\n        }\n    }\n\n    // Negative phase: visit all cells with negative height\n    while (true) {\n        bool has_neg = false;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (in_neg[i][j]) {\n                    has_neg = true;\n                    break;\n                }\n            }\n            if (has_neg) break;\n        }\n        if (!has_neg) break;\n\n        if (in_neg[current_i][current_j]) {\n            int d = -h_init[current_i][current_j];\n            operations.push_back(\"-\" + to_string(d));\n            load -= d;\n            in_neg[current_i][current_j] = false;\n        } else {\n            int best_i = -1, best_j = -1;\n            int best_cost = 1e9;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (in_neg[i][j]) {\n                        int dist = abs(i - current_i) + abs(j - current_j);\n                        int cost = dist * (100 + load) + (-h_init[i][j]);\n                        if (cost < best_cost) {\n                            best_cost = cost;\n                            best_i = i;\n                            best_j = j;\n                        }\n                    }\n                }\n            }\n            if (best_i == -1) break;\n            vector<string> moves = get_moves(current_i, current_j, best_i, best_j);\n            operations.insert(operations.end(), moves.begin(), moves.end());\n            current_i = best_i;\n            current_j = best_j;\n        }\n    }\n\n    for (const string& op : operations) {\n        cout << op << endl;\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <functional>\n\nusing namespace std;\n\nint main() {\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 cell importance (center cells are more important)\n    vector<vector<int>> cell_importance(N, vector<int>(N, 0));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            // Distance from center\n            double di = abs(i - (N-1)/2.0);\n            double dj = abs(j - (N-1)/2.0);\n            cell_importance[i][j] = round(100 * (1.0 - (di + dj) / (N-1)));\n        }\n    }\n\n    for (int t = 0; t < T; t++) {\n        vector<int> values(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            values[i] = accumulate(seeds[i].begin(), seeds[i].end(), 0);\n        }\n\n        // Find maximum per criterion across all seeds\n        vector<int> max_per_criterion(M, 0);\n        for (int l = 0; l < M; l++) {\n            int max_val = 0;\n            for (int i = 0; i < seed_count; i++) {\n                if (seeds[i][l] > max_val) {\n                    max_val = seeds[i][l];\n                }\n            }\n            max_per_criterion[l] = max_val;\n        }\n\n        // Select seeds using a combination of quality and diversity\n        vector<int> indices(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            indices[i] = i;\n        }\n\n        // Sort by value first\n        sort(indices.begin(), indices.end(), [&](int a, int b) {\n            return values[a] > values[b];\n        });\n\n        // Take top seeds but ensure some diversity\n        vector<int> plant_indices;\n        vector<bool> used(seed_count, false);\n        \n        // Take the absolute best seeds\n        int top_count = min(20, N * N);\n        for (int i = 0; i < top_count; i++) {\n            plant_indices.push_back(indices[i]);\n            used[indices[i]] = true;\n        }\n\n        // Add diverse seeds to fill remaining slots\n        for (int i = top_count; plant_indices.size() < N * N && i < seed_count; i++) {\n            int candidate = indices[i];\n            \n            // Check if this seed brings diversity\n            bool is_diverse = false;\n            for (int l = 0; l < M; l++) {\n                if (seeds[candidate][l] > max_per_criterion[l] * 0.7) {\n                    is_diverse = true;\n                    break;\n                }\n            }\n            \n            if (is_diverse || plant_indices.size() < N * N - 2) {\n                plant_indices.push_back(candidate);\n                used[candidate] = true;\n            }\n        }\n\n        // If we still need more seeds, take the next best\n        for (int i = 0; plant_indices.size() < N * N && i < seed_count; i++) {\n            if (!used[indices[i]]) {\n                plant_indices.push_back(indices[i]);\n                used[indices[i]] = true;\n            }\n        }\n\n        // Strategic placement: spiral from center outward\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        vector<bool> assigned(plant_indices.size(), false);\n        \n        // Create spiral order of cells (center first)\n        vector<pair<int, int>> spiral_order;\n        int center_i = N / 2, center_j = N / 2;\n        spiral_order.push_back({center_i, center_j});\n        \n        // Generate spiral pattern\n        int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        int step = 1, dir = 0;\n        int i = center_i, j = center_j;\n        \n        while (spiral_order.size() < N * N) {\n            for (int s = 0; s < 2; s++) {\n                for (int k = 0; k < step && spiral_order.size() < N * N; k++) {\n                    i += directions[dir][0];\n                    j += directions[dir][1];\n                    if (i >= 0 && i < N && j >= 0 && j < N) {\n                        spiral_order.push_back({i, j});\n                    }\n                }\n                dir = (dir + 1) % 4;\n            }\n            step++;\n        }\n\n        // Assign seeds to cells in spiral order\n        for (auto [i, j] : spiral_order) {\n            vector<int> neighbor_seeds;\n            \n            // Check all four neighbors\n            int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n            for (auto [di, dj] : directions) {\n                int ni = i + di, nj = j + dj;\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && A[ni][nj] != -1) {\n                    neighbor_seeds.push_back(A[ni][nj]);\n                }\n            }\n\n            if (neighbor_seeds.empty()) {\n                // No neighbors assigned yet - use the best available seed\n                int best_seed = -1;\n                int best_value = -1;\n                for (int k = 0; k < plant_indices.size(); k++) {\n                    if (!assigned[k] && values[plant_indices[k]] > best_value) {\n                        best_value = values[plant_indices[k]];\n                        best_seed = k;\n                    }\n                }\n                if (best_seed != -1) {\n                    A[i][j] = plant_indices[best_seed];\n                    assigned[best_seed] = true;\n                }\n            } else {\n                // Calculate deficiencies considering all neighbors\n                vector<double> weighted_deficiency(M, 0.0);\n                for (int l = 0; l < M; l++) {\n                    for (int n_index : neighbor_seeds) {\n                        weighted_deficiency[l] += (max_per_criterion[l] - seeds[n_index][l]) * 1.0;\n                    }\n                    // Normalize by number of neighbors\n                    weighted_deficiency[l] /= neighbor_seeds.size();\n                    // Apply non-linear weighting to emphasize larger deficiencies\n                    weighted_deficiency[l] = pow(weighted_deficiency[l], 1.2);\n                }\n\n                // Find best seed for this position\n                int best_seed_index = -1;\n                double best_score = -1e9;\n                \n                for (int k = 0; k < plant_indices.size(); k++) {\n                    if (assigned[k]) continue;\n                    \n                    int s_index = plant_indices[k];\n                    double score = 0;\n                    \n                    // Complementarity component\n                    for (int l = 0; l < M; l++) {\n                        score += seeds[s_index][l] * weighted_deficiency[l];\n                    }\n                    \n                    // Value component (weighted by cell importance)\n                    score += values[s_index] * cell_importance[i][j] * 0.01;\n                    \n                    // Diversity bonus for criteria where this seed is strong\n                    for (int l = 0; l < M; l++) {\n                        if (seeds[s_index][l] > max_per_criterion[l] * 0.8) {\n                            score += max_per_criterion[l] * 0.1;\n                        }\n                    }\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_seed_index = k;\n                    }\n                }\n                \n                if (best_seed_index != -1) {\n                    A[i][j] = plant_indices[best_seed_index];\n                    assigned[best_seed_index] = true;\n                } else {\n                    // Fallback: use first available seed\n                    for (int k = 0; k < plant_indices.size(); k++) {\n                        if (!assigned[k]) {\n                            A[i][j] = plant_indices[k];\n                            assigned[k] = true;\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        // Output the assignment\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << A[i][j];\n                if (j < N - 1) {\n                    cout << \" \";\n                }\n            }\n            cout << endl;\n        }\n        cout.flush();\n\n        // Read new seeds for next generation\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 <set>\n#include <map>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <random>\n\nusing namespace std;\n\nconst int MAX_N = 30;\nconst int MAX_V = 15;\n\n// Directions: 0=right, 1=down, 2=left, 3=up\nconst int dx[4] = {0, 1, 0, -1};\nconst int dy[4] = {1, 0, -1, 0};\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    \n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    \n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n    \n    int manhattan(const Point& other) const {\n        return abs(x - other.x) + abs(y - other.y);\n    }\n};\n\nclass RoboticArm {\nprivate:\n    int N, M, V;\n    vector<string> s, t;\n    Point root;\n    vector<int> parent;\n    vector<int> length;\n    vector<int> dirs; // direction for each vertex (except root)\n    vector<bool> holding;\n    set<Point> initial_set;\n    set<Point> target_set;\n    vector<vector<bool>> grid;\n    int turns;\n    mt19937 rng;\n    \n    // Check if point is within grid\n    bool in_grid(int x, int y) {\n        return x >= 0 && x < N && y >= 0 && y < N;\n    }\n    \n    // Get position of a vertex\n    Point get_position(int vertex) {\n        if (vertex == 0) return root;\n        \n        Point pos = root;\n        int current = vertex;\n        vector<int> path;\n        \n        // Get path from root to vertex\n        while (current != 0) {\n            path.push_back(current);\n            current = parent[current];\n        }\n        \n        // Reverse to go from root to vertex\n        for (int i = path.size() - 1; i >= 0; i--) {\n            int v = path[i];\n            int d = dirs[v];\n            pos.x += dx[d] * length[v];\n            pos.y += dy[d] * length[v];\n        }\n        \n        return pos;\n    }\n    \n    // Evaluate a move and rotation\n    double evaluate_action(int move, int rotation, const vector<Point>& desired_pos) {\n        Point new_root = root;\n        vector<int> new_dirs = dirs;\n        \n        // Apply move\n        if (move == 1) new_root.y++; // U\n        else if (move == 2) new_root.y--; // D\n        else if (move == 3) new_root.x--; // L\n        else if (move == 4) new_root.x++; // R\n        \n        if (!in_grid(new_root.x, new_root.y)) return numeric_limits<double>::max();\n        \n        // Apply rotation to vertex 1 (the only joint in our star design)\n        if (rotation != 0) {\n            for (int i = 1; i < V; i++) {\n                if (rotation == 1) new_dirs[i] = (new_dirs[i] + 1) % 4; // clockwise\n                else new_dirs[i] = (new_dirs[i] + 3) % 4; // counterclockwise\n            }\n        }\n        \n        // Calculate new positions and score\n        double score = 0;\n        for (int i = 2; i < V; i++) { // leaves are vertices 2 to V-1\n            Point leaf_pos = new_root;\n            int d = new_dirs[i];\n            leaf_pos.x += dx[d] * length[i];\n            leaf_pos.y += dy[d] * length[i];\n            \n            if (!desired_pos[i].x == -1) {\n                score += leaf_pos.manhattan(desired_pos[i]);\n            }\n        }\n        \n        return score;\n    }\n\npublic:\n    RoboticArm(int N, int M, int V, const vector<string>& s, const vector<string>& t) \n        : N(N), M(M), V(V), s(s), t(t), turns(0), rng(42) {\n        \n        // Initialize grid and sets\n        grid.assign(N, vector<bool>(N, false));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (s[i][j] == '1') {\n                    grid[i][j] = true;\n                    initial_set.insert(Point(i, j));\n                }\n                if (t[i][j] == '1') {\n                    target_set.insert(Point(i, j));\n                }\n            }\n        }\n        \n        // Initialize tree structure (star design)\n        parent.resize(V);\n        length.resize(V);\n        dirs.resize(V, 0); // all directions initially right\n        holding.resize(V, false);\n        \n        // Root at center\n        root = Point(N / 2, N / 2);\n        \n        // All vertices except root are children of root\n        for (int i = 1; i < V; i++) {\n            parent[i] = 0;\n            length[i] = N - 1;\n        }\n    }\n    \n    void output_tree() {\n        cout << V << endl;\n        for (int i = 1; i < V; i++) {\n            cout << parent[i] << \" \" << length[i] << endl;\n        }\n        cout << root.x << \" \" << root.y << endl;\n    }\n    \n    void solve() {\n        output_tree();\n        \n        while (turns < 100000) {\n            // Check if all takoyaki are placed\n            bool all_placed = true;\n            for (const auto& p : target_set) {\n                if (!grid[p.x][p.y]) {\n                    all_placed = false;\n                    break;\n                }\n            }\n            if (all_placed) break;\n            \n            // Assign desired positions for each leaf\n            vector<Point> desired_pos(V, Point(-1, -1));\n            set<Point> available_initial = initial_set;\n            set<Point> available_target = target_set;\n            \n            // Remove already placed takoyaki from available targets\n            for (const auto& p : target_set) {\n                if (grid[p.x][p.y]) {\n                    available_target.erase(p);\n                }\n            }\n            \n            // Greedy assignment\n            for (int i = 2; i < V; i++) {\n                if (!holding[i]) {\n                    // Find closest available initial position\n                    Point best_pos(-1, -1);\n                    int best_dist = numeric_limits<int>::max();\n                    Point current_pos = get_position(i);\n                    \n                    for (const auto& p : available_initial) {\n                        if (grid[p.x][p.y]) {\n                            int dist = current_pos.manhattan(p);\n                            if (dist < best_dist) {\n                                best_dist = dist;\n                                best_pos = p;\n                            }\n                        }\n                    }\n                    \n                    if (best_dist < numeric_limits<int>::max()) {\n                        desired_pos[i] = best_pos;\n                        available_initial.erase(best_pos);\n                    }\n                } else {\n                    // Find closest available target position\n                    Point best_pos(-1, -1);\n                    int best_dist = numeric_limits<int>::max();\n                    Point current_pos = get_position(i);\n                    \n                    for (const auto& p : available_target) {\n                        if (!grid[p.x][p.y]) {\n                            int dist = current_pos.manhattan(p);\n                            if (dist < best_dist) {\n                                best_dist = dist;\n                                best_pos = p;\n                            }\n                        }\n                    }\n                    \n                    if (best_dist < numeric_limits<int>::max()) {\n                        desired_pos[i] = best_pos;\n                        available_target.erase(best_pos);\n                    }\n                }\n            }\n            \n            // Evaluate all possible actions\n            int best_move = 0; // 0=no move, 1=U, 2=D, 3=L, 4=R\n            int best_rotation = 0; // 0=no rotation, 1=clockwise, 2=counterclockwise\n            double best_score = numeric_limits<double>::max();\n            \n            for (int move = 0; move <= 4; move++) {\n                for (int rotation = 0; rotation <= 2; rotation++) {\n                    double score = evaluate_action(move, rotation, desired_pos);\n                    if (score < best_score) {\n                        best_score = score;\n                        best_move = move;\n                        best_rotation = rotation;\n                    }\n                }\n            }\n            \n            // Apply best action\n            string operation;\n            operation.resize(2 * V, '.');\n            \n            // Move\n            if (best_move == 1) { // U\n                root.y++;\n                operation[0] = 'U';\n            } else if (best_move == 2) { // D\n                root.y--;\n                operation[0] = 'D';\n            } else if (best_move == 3) { // L\n                root.x--;\n                operation[0] = 'L';\n            } else if (best_move == 4) { // R\n                root.x++;\n                operation[0] = 'R';\n            }\n            \n            // Rotation\n            if (best_rotation == 1) { // clockwise\n                for (int i = 1; i < V; i++) {\n                    dirs[i] = (dirs[i] + 1) % 4;\n                    operation[i] = 'R';\n                }\n            } else if (best_rotation == 2) { // counterclockwise\n                for (int i = 1; i < V; i++) {\n                    dirs[i] = (dirs[i] + 3) % 4;\n                    operation[i] = 'L';\n                }\n            }\n            \n            // Pick/place operations\n            for (int i = 2; i < V; i++) {\n                Point pos = get_position(i);\n                if (in_grid(pos.x, pos.y)) {\n                    if (!holding[i] && initial_set.find(pos) != initial_set.end() && grid[pos.x][pos.y]) {\n                        // Pick up takoyaki\n                        grid[pos.x][pos.y] = false;\n                        holding[i] = true;\n                        operation[V + i] = 'P';\n                    } else if (holding[i] && target_set.find(pos) != target_set.end() && !grid[pos.x][pos.y]) {\n                        // Place takoyaki\n                        grid[pos.x][pos.y] = true;\n                        holding[i] = false;\n                        operation[V + i] = 'P';\n                    }\n                }\n            }\n            \n            cout << operation << endl;\n            turns++;\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, V;\n    cin >> N >> M >> V;\n    \n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; i++) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> t[i];\n    }\n    \n    RoboticArm arm(N, M, V, s, t);\n    arm.solve();\n    \n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    int type; // 0 for mackerel, 1 for sardine\n};\n\npair<int, int> optimize_axis(const vector<Point>& points_sorted, int fixed_min, int fixed_max, bool is_x_fixed) {\n    auto cmp_lower = [is_x_fixed](const Point& p, int val) {\n        if (is_x_fixed) return p.x < val;\n        else return p.y < val;\n    };\n    auto cmp_upper = [is_x_fixed](int val, const Point& p) {\n        if (is_x_fixed) return val < p.x;\n        else return val < p.y;\n    };\n\n    auto start_it = lower_bound(points_sorted.begin(), points_sorted.end(), fixed_min, cmp_lower);\n    auto end_it = upper_bound(points_sorted.begin(), points_sorted.end(), fixed_max, cmp_upper);\n\n    vector<int> value(100001, 0);\n    for (auto it = start_it; it != end_it; ++it) {\n        int coord;\n        if (is_x_fixed) {\n            coord = it->y;\n        } else {\n            coord = it->x;\n        }\n        if (it->type == 0) {\n            value[coord] += 1;\n        } else {\n            value[coord] -= 1;\n        }\n    }\n\n    vector<int> cum_net(100001);\n    cum_net[0] = value[0];\n    for (int i = 1; i <= 100000; i++) {\n        cum_net[i] = cum_net[i-1] + value[i];\n    }\n\n    int min_cum = 0;\n    int min_index = -1;\n    int best_diff = INT_MIN;\n    int best_a = 0, best_b = 0;\n\n    for (int i = 0; i <= 100000; i++) {\n        int diff = cum_net[i] - min_cum;\n        if (diff > best_diff) {\n            best_diff = diff;\n            best_a = min_index + 1;\n            best_b = i;\n        }\n        if (cum_net[i] < min_cum) {\n            min_cum = cum_net[i];\n            min_index = i;\n        }\n    }\n\n    if (best_a > best_b) {\n        swap(best_a, best_b);\n    }\n    if (best_a == best_b) {\n        if (best_b < 100000) {\n            best_b++;\n        } else if (best_a > 0) {\n            best_a--;\n        } else {\n            best_b++;\n        }\n    }\n\n    return {best_a, best_b};\n}\n\nint compute_score(const vector<Point>& points, int x1, int x2, int y1, int y2) {\n    int a = 0, b = 0;\n    for (const Point& p : points) {\n        if (p.x >= x1 && p.x <= x2 && p.y >= y1 && p.y <= y2) {\n            if (p.type == 0) a++;\n            else b++;\n        }\n    }\n    return a - b + 1;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n\n    int N;\n    cin >> N;\n    vector<Point> points(2 * N);\n    for (int i = 0; i < 2 * N; i++) {\n        cin >> points[i].x >> points[i].y;\n        points[i].type = (i < N) ? 0 : 1;\n    }\n\n    vector<Point> mackerels(points.begin(), points.begin() + N);\n\n    // Sort points for optimize_axis\n    vector<Point> points_by_x = points;\n    sort(points_by_x.begin(), points_by_x.end(), [](const Point& a, const Point& b) {\n        return a.x < b.x;\n    });\n    vector<Point> points_by_y = points;\n    sort(points_by_y.begin(), points_by_y.end(), [](const Point& a, const Point& b) {\n        return a.y < b.y;\n    });\n\n    // Compute initial rectangles\n    int min_x = INT_MAX, max_x = INT_MIN;\n    int min_y = INT_MAX, max_y = INT_MIN;\n    for (const Point& p : mackerels) {\n        min_x = min(min_x, p.x);\n        max_x = max(max_x, p.x);\n        min_y = min(min_y, p.y);\n        max_y = max(max_y, p.y);\n    }\n\n    vector<int> mackerels_x, mackerels_y;\n    for (const Point& p : mackerels) {\n        mackerels_x.push_back(p.x);\n        mackerels_y.push_back(p.y);\n    }\n    sort(mackerels_x.begin(), mackerels_x.end());\n    sort(mackerels_y.begin(), mackerels_y.end());\n\n    int Q1_x = mackerels_x[N/4];\n    int Q3_x = mackerels_x[3*N/4];\n    int Q1_y = mackerels_y[N/4];\n    int Q3_y = mackerels_y[3*N/4];\n\n    int Q10_x = mackerels_x[N/10];\n    int Q90_x = mackerels_x[9*N/10];\n    int Q10_y = mackerels_y[N/10];\n    int Q90_y = mackerels_y[9*N/10];\n\n    vector<pair<int, int>> initial_rectangles;\n    initial_rectangles.push_back({min_x, max_x}); // x1, x2 for init1\n    initial_rectangles.push_back({min_y, max_y}); // y1, y2 for init1\n\n    initial_rectangles.push_back({Q1_x, Q3_x}); // for init2\n    initial_rectangles.push_back({Q1_y, Q3_y});\n\n    initial_rectangles.push_back({Q10_x, Q90_x}); // for init3\n    initial_rectangles.push_back({Q10_y, Q90_y});\n\n    int best_score = INT_MIN;\n    int best_x1, best_x2, best_y1, best_y2;\n\n    for (int i = 0; i < 3; i++) {\n        int x1 = initial_rectangles[2*i].first;\n        int x2 = initial_rectangles[2*i].second;\n        int y1 = initial_rectangles[2*i+1].first;\n        int y2 = initial_rectangles[2*i+1].second;\n\n        for (int iter = 0; iter < 10; iter++) {\n            auto new_y = optimize_axis(points_by_x, x1, x2, true);\n            y1 = new_y.first;\n            y2 = new_y.second;\n\n            auto new_x = optimize_axis(points_by_y, y1, y2, false);\n            x1 = new_x.first;\n            x2 = new_x.second;\n        }\n\n        int score = compute_score(points, x1, x2, y1, y2);\n        if (score > best_score) {\n            best_score = score;\n            best_x1 = x1;\n            best_x2 = x2;\n            best_y1 = y1;\n            best_y2 = y2;\n        }\n    }\n\n    cout << 4 << endl;\n    cout << best_x1 << \" \" << best_y1 << endl;\n    cout << best_x2 << \" \" << best_y1 << endl;\n    cout << best_x2 << \" \" << best_y2 << endl;\n    cout << best_x1 << \" \" << best_y2 << endl;\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <tuple>\n\nusing namespace std;\n\nint main() {\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n    vector<int> w_meas(N), h_meas(N);\n    for (int i = 0; i < N; i++) {\n        cin >> w_meas[i] >> h_meas[i];\n    }\n\n    vector<long long> sum_w(N, 0), sum_h(N, 0);\n    vector<int> count(N, 0);\n\n    for (int t = 0; t < T; t++) {\n        if (t < N) {\n            int i = t;\n            int r = 0;\n            char d = 'U';\n            int b = -1;\n            cout << 1 << endl;\n            cout << i << \" \" << r << \" \" << d << \" \" << b << endl;\n            cout.flush();\n\n            int Wp, Hp;\n            cin >> Wp >> Hp;\n            sum_w[i] += Wp;\n            sum_h[i] += Hp;\n            count[i]++;\n        } else {\n            vector<int> est_w(N), est_h(N);\n            for (int i = 0; i < N; i++) {\n                if (count[i] > 0) {\n                    est_w[i] = sum_w[i] / count[i];\n                    est_h[i] = sum_h[i] / count[i];\n                } else {\n                    est_w[i] = w_meas[i];\n                    est_h[i] = h_meas[i];\n                }\n            }\n\n            int W = 0, H = 0;\n            vector<tuple<int, int, char, int>> actions;\n            for (int i = 0; i < N; i++) {\n                int best_r = 0;\n                char best_d = 'U';\n                int best_score = 1e9;\n                int w0 = est_w[i];\n                int h0 = est_h[i];\n                for (int r = 0; r <= 1; r++) {\n                    int w, h;\n                    if (r == 0) {\n                        w = w0;\n                        h = h0;\n                    } else {\n                        w = h0;\n                        h = w0;\n                    }\n                    for (char d : {'U', 'L'}) {\n                        int new_W, new_H;\n                        if (d == 'U') {\n                            new_W = (W > w) ? W : w;\n                            new_H = H + h;\n                        } else {\n                            new_W = W + w;\n                            new_H = (H > h) ? H : h;\n                        }\n                        int new_score = new_W + new_H;\n                        if (new_score < best_score) {\n                            best_score = new_score;\n                            best_r = r;\n                            best_d = d;\n                        }\n                    }\n                }\n                actions.push_back({i, best_r, best_d, -1});\n                int w, h;\n                if (best_r == 0) {\n                    w = est_w[i];\n                    h = est_h[i];\n                } else {\n                    w = est_h[i];\n                    h = est_w[i];\n                }\n                if (best_d == 'U') {\n                    W = (W > w) ? W : w;\n                    H = H + h;\n                } else {\n                    W = W + w;\n                    H = (H > h) ? H : h;\n                }\n            }\n\n            cout << N << endl;\n            for (const auto& action : actions) {\n                int i, r, b;\n                char d;\n                tie(i, r, d, b) = action;\n                cout << i << \" \" << r << \" \" << d << \" \" << b << endl;\n            }\n            cout.flush();\n\n            int Wp, Hp;\n            cin >> Wp >> Hp;\n        }\n    }\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    int index;\n    int beauty;\n};\n\ndouble distance(const Point& a, const Point& b) {\n    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, H;\n    cin >> N >> M >> H;\n    \n    vector<int> A(N);\n    for (int i = 0; i < N; i++) {\n        cin >> A[i];\n    }\n    \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    vector<Point> points(N);\n    Point center = {500, 500, -1, 0}; // Circle center\n    for (int i = 0; i < N; i++) {\n        cin >> points[i].x >> points[i].y;\n        points[i].index = i;\n        points[i].beauty = A[i];\n    }\n    \n    // Sort points by distance from center (ascending) and beauty (ascending)\n    // Prefer points near center with low beauty as roots\n    vector<int> point_indices(N);\n    iota(point_indices.begin(), point_indices.end(), 0);\n    sort(point_indices.begin(), point_indices.end(), [&](int i, int j) {\n        double dist_i = distance(points[i], center);\n        double dist_j = distance(points[j], center);\n        if (abs(dist_i - dist_j) < 1e-9) {\n            return A[i] < A[j]; // Lower beauty first if same distance\n        }\n        return dist_i < dist_j;\n    });\n    \n    vector<int> parent(N, -1);\n    vector<int> depth(N, -1);\n    vector<bool> assigned(N, false);\n    \n    // Priority queue for BFS: (depth, -beauty, vertex)\n    // We want to process vertices with higher depth first, and for same depth,\n    // process lower beauty vertices first (to reserve high beauty for deeper positions)\n    auto cmp = [](const tuple<int, int, int>& a, const tuple<int, int, int>& b) {\n        if (get<0>(a) != get<0>(b)) return get<0>(a) < get<0>(b);\n        return get<1>(a) > get<1>(b); // Higher beauty has lower negative value\n    };\n    priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, decltype(cmp)> pq(cmp);\n    \n    // Assign roots starting from points near center with low beauty\n    for (int idx : point_indices) {\n        if (!assigned[idx] && depth[idx] == -1) {\n            // Make this point a root\n            parent[idx] = -1;\n            depth[idx] = 0;\n            assigned[idx] = true;\n            pq.push({0, -A[idx], idx});\n        }\n    }\n    \n    // Process vertices in BFS order with depth constraint\n    while (!pq.empty()) {\n        auto [current_depth, neg_beauty, u] = pq.top();\n        pq.pop();\n        \n        if (current_depth >= H) continue;\n        \n        // Sort neighbors by beauty descending (we want to assign high beauty vertices first)\n        vector<pair<int, int>> neighbors; // (beauty, vertex)\n        for (int v : adj[u]) {\n            if (!assigned[v]) {\n                neighbors.push_back({A[v], v});\n            }\n        }\n        \n        sort(neighbors.begin(), neighbors.end(), greater<pair<int, int>>());\n        \n        for (auto [beauty, v] : neighbors) {\n            if (!assigned[v] && depth[v] == -1) {\n                parent[v] = u;\n                depth[v] = current_depth + 1;\n                assigned[v] = true;\n                pq.push({depth[v], -A[v], v});\n            }\n        }\n    }\n    \n    // Output the parent array\n    for (int i = 0; i < N; i++) {\n        cout << parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n    const int N = 20;\n    vector<string> board(N);\n    for (int i = 0; i < N; i++) {\n        cin >> board[i];\n    }\n\n    vector<char> directions;\n    vector<int> indices;\n\n    for (int j = 0; j < N; j++) {\n        int max_r = -1;\n        int min_r = N;\n        bool has_oni = false;\n        for (int i = 0; i < N; i++) {\n            if (board[i][j] == 'x') {\n                has_oni = true;\n                if (i > max_r) max_r = i;\n                if (i < min_r) min_r = i;\n            }\n        }\n        if (!has_oni) continue;\n\n        bool safe_up = true;\n        for (int i = 0; i < max_r; i++) {\n            if (board[i][j] == 'o') {\n                safe_up = false;\n                break;\n            }\n        }\n\n        bool safe_down = true;\n        for (int i = min_r + 1; i < N; i++) {\n            if (board[i][j] == 'o') {\n                safe_down = false;\n                break;\n            }\n        }\n\n        int shifts_up = max_r + 1;\n        int shifts_down = N - min_r;\n\n        char dir;\n        int shifts;\n        if (safe_up && safe_down) {\n            if (shifts_up <= shifts_down) {\n                dir = 'U';\n                shifts = shifts_up;\n            } else {\n                dir = 'D';\n                shifts = shifts_down;\n            }\n        } else if (safe_up) {\n            dir = 'U';\n            shifts = shifts_up;\n        } else if (safe_down) {\n            dir = 'D';\n            shifts = shifts_down;\n        } else {\n            dir = 'U';\n            shifts = shifts_up;\n        }\n\n        for (int k = 0; k < shifts; k++) {\n            directions.push_back(dir);\n            indices.push_back(j);\n        }\n    }\n\n    for (size_t i = 0; i < directions.size(); i++) {\n        cout << directions[i] << \" \" << indices[i] << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <random>\n\nusing namespace std;\n\nint main() {\n    int N, L;\n    cin >> N >> L;\n    vector<int> T(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n\n    // Calculate desired frequencies relative to total\n    vector<double> desired_ratio(N);\n    double total = accumulate(T.begin(), T.end(), 0.0);\n    for (int i = 0; i < N; i++) {\n        desired_ratio[i] = T[i] / total;\n    }\n\n    // Create a more sophisticated allocation\n    vector<int> a(N), b(N);\n    \n    // First, ensure the graph is well-connected\n    // Create a cycle to ensure all employees are reachable\n    for (int i = 0; i < N; i++) {\n        a[i] = (i + 1) % N;\n        b[i] = (i + N - 1) % N;\n    }\n\n    // Now adjust pointers to better match desired frequencies\n    // Employees with higher T[i] should have more incoming pointers\n    vector<int> incoming_count(N, 0);\n    \n    // Calculate how many pointers should point to each employee\n    vector<int> target_incoming(N);\n    int total_pointers = 2 * N;\n    for (int i = 0; i < N; i++) {\n        target_incoming[i] = max(1, (int)round(desired_ratio[i] * total_pointers));\n    }\n    \n    // Adjust to ensure sum equals 2N\n    int current_total = accumulate(target_incoming.begin(), target_incoming.end(), 0);\n    while (current_total != total_pointers) {\n        if (current_total < total_pointers) {\n            // Find employee with largest T[i] that's below target\n            int best_idx = -1;\n            double best_ratio = -1;\n            for (int i = 0; i < N; i++) {\n                if (target_incoming[i] < total_pointers) {\n                    double ratio = desired_ratio[i] / (target_incoming[i] + 1);\n                    if (ratio > best_ratio) {\n                        best_ratio = ratio;\n                        best_idx = i;\n                    }\n                }\n            }\n            if (best_idx != -1) {\n                target_incoming[best_idx]++;\n                current_total++;\n            } else {\n                break;\n            }\n        } else {\n            // Find employee with smallest T[i] that's above minimum\n            int best_idx = -1;\n            double best_ratio = 1e9;\n            for (int i = 0; i < N; i++) {\n                if (target_incoming[i] > 1) {\n                    double ratio = desired_ratio[i] / target_incoming[i];\n                    if (ratio < best_ratio) {\n                        best_ratio = ratio;\n                        best_idx = i;\n                    }\n                }\n            }\n            if (best_idx != -1) {\n                target_incoming[best_idx]--;\n                current_total--;\n            } else {\n                break;\n            }\n        }\n    }\n\n    // Distribute pointers to achieve target_incoming\n    vector<vector<int>> outgoing(N);\n    \n    // First pass: assign pointers based on desired frequencies\n    for (int i = 0; i < N; i++) {\n        // Calculate how many pointers from employee i should go to each target\n        // Prefer to point to employees with high desired frequency\n        vector<pair<double, int>> targets;\n        for (int j = 0; j < N; j++) {\n            if (j != i) { // Avoid self-pointers initially\n                targets.push_back({desired_ratio[j], j});\n            }\n        }\n        sort(targets.begin(), targets.end(), greater<pair<double, int>>());\n        \n        // Assign a_i and b_i to the two most desirable targets\n        if (!targets.empty()) {\n            a[i] = targets[0].second;\n            if (targets.size() > 1) {\n                b[i] = targets[1].second;\n            } else {\n                b[i] = targets[0].second;\n            }\n        } else {\n            a[i] = (i + 1) % N;\n            b[i] = (i + N - 1) % N;\n        }\n    }\n\n    // Second pass: adjust to better match target_incoming\n    vector<int> actual_incoming(N, 0);\n    for (int i = 0; i < N; i++) {\n        actual_incoming[a[i]]++;\n        actual_incoming[b[i]]++;\n    }\n\n    // Make local improvements\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> emp_dist(0, N-1);\n    uniform_int_distribution<> choice_dist(0, 1);\n    \n    const int iterations = 10000;\n    for (int iter = 0; iter < iterations; iter++) {\n        int emp = emp_dist(gen);\n        int old_target, new_target;\n        \n        if (choice_dist(gen) == 0) {\n            old_target = a[emp];\n            new_target = emp_dist(gen);\n            if (new_target == old_target) continue;\n            \n            // Check if change would improve the distribution\n            int old_error = abs(actual_incoming[old_target] - target_incoming[old_target]) +\n                           abs(actual_incoming[new_target] - target_incoming[new_target]);\n            int new_error = abs((actual_incoming[old_target] - 1) - target_incoming[old_target]) +\n                           abs((actual_incoming[new_target] + 1) - target_incoming[new_target]);\n            \n            if (new_error < old_error) {\n                a[emp] = new_target;\n                actual_incoming[old_target]--;\n                actual_incoming[new_target]++;\n            }\n        } else {\n            old_target = b[emp];\n            new_target = emp_dist(gen);\n            if (new_target == old_target) continue;\n            \n            int old_error = abs(actual_incoming[old_target] - target_incoming[old_target]) +\n                           abs(actual_incoming[new_target] - target_incoming[new_target]);\n            int new_error = abs((actual_incoming[old_target] - 1) - target_incoming[old_target]) +\n                           abs((actual_incoming[new_target] + 1) - target_incoming[new_target]);\n            \n            if (new_error < old_error) {\n                b[emp] = new_target;\n                actual_incoming[old_target]--;\n                actual_incoming[new_target]++;\n            }\n        }\n    }\n\n    // Output the final assignment\n    for (int i = 0; i < N; i++) {\n        cout << a[i] << \" \" << b[i] << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <random>\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n};\n\n// Function to compute Morton code for two integers\nuint32_t morton_code(int x, int y) {\n    uint32_t code = 0;\n    for (int i = 0; i < 16; i++) {\n        code |= (x & 1) << (2 * i);\n        code |= (y & 1) << (2 * i + 1);\n        x >>= 1;\n        y >>= 1;\n    }\n    return code;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (int i = 0; i < M; i++) {\n        cin >> G[i];\n    }\n    vector<City> cities(N);\n    for (int i = 0; i < N; i++) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].id = i;\n    }\n\n    // Precompute centers and Morton codes for each city\n    vector<int> x_center(N), y_center(N);\n    vector<uint32_t> morton_codes(N);\n    for (int i = 0; i < N; i++) {\n        int sum_x = cities[i].lx + cities[i].rx;\n        int sum_y = cities[i].ly + cities[i].ry;\n        x_center[i] = sum_x / 2;\n        if (sum_x % 2 == 1) x_center[i]++;\n        y_center[i] = sum_y / 2;\n        if (sum_y % 2 == 1) y_center[i]++;\n        morton_codes[i] = morton_code(x_center[i], y_center[i]);\n    }\n\n    // Sort cities by Morton code\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n    sort(indices.begin(), indices.end(), [&](int i, int j) {\n        return morton_codes[i] < morton_codes[j];\n    });\n\n    // Group cities based on sorted order\n    vector<vector<int>> groups(M);\n    int start_idx = 0;\n    for (int i = 0; i < M; i++) {\n        int g_size = G[i];\n        groups[i].resize(g_size);\n        for (int j = 0; j < g_size; j++) {\n            groups[i][j] = indices[start_idx + j];\n        }\n        start_idx += g_size;\n    }\n\n    vector<pair<int, int>> collected_edges;\n    int queries_used = 0;\n\n    // Perform initial queries for each group\n    for (int i = 0; i < M; i++) {\n        if (queries_used >= Q) break;\n        int g = groups[i].size();\n        if (g < 2) continue;\n        int num_chunks = ceil((g - 1) / double(L - 1));\n        for (int j = 0; j < num_chunks; j++) {\n            if (queries_used >= Q) break;\n            int start_index = j * (L - 1);\n            int end_index = min(start_index + L, g);\n            int size = end_index - start_index;\n            if (size < 2) break;\n            cout << \"? \" << size;\n            for (int k = start_index; k < end_index; k++) {\n                cout << \" \" << groups[i][k];\n            }\n            cout << endl;\n            cout.flush();\n            for (int k = 0; k < size - 1; k++) {\n                int a, b;\n                cin >> a >> b;\n                if (a > b) swap(a, b);\n                collected_edges.push_back({a, b});\n            }\n            queries_used++;\n        }\n    }\n\n    // Use leftover queries for large groups\n    int leftover = Q - queries_used;\n    if (leftover > 0) {\n        vector<int> large_group_indices;\n        for (int i = 0; i < M; i++) {\n            if (groups[i].size() > L) {\n                large_group_indices.push_back(i);\n            }\n        }\n        if (!large_group_indices.empty()) {\n            sort(large_group_indices.begin(), large_group_indices.end(), [&](int i, int j) {\n                return groups[i].size() > groups[j].size();\n            });\n            int seed = 0;\n            for (int i = 0; i < N; i++) {\n                seed += cities[i].lx + cities[i].rx + cities[i].ly + cities[i].ry;\n            }\n            mt19937 rng(seed);\n            int current_index = 0;\n            while (leftover > 0) {\n                int group_idx = large_group_indices[current_index];\n                int g = groups[group_idx].size();\n                uniform_int_distribution<int> dist(0, g - L);\n                int start = dist(rng);\n                cout << \"? \" << L;\n                for (int k = start; k < start + L; k++) {\n                    cout << \" \" << groups[group_idx][k];\n                }\n                cout << endl;\n                cout.flush();\n                for (int k = 0; k < L - 1; k++) {\n                    int a, b;\n                    cin >> a >> b;\n                    if (a > b) swap(a, b);\n                    collected_edges.push_back({a, b});\n                }\n                leftover--;\n                current_index = (current_index + 1) % large_group_indices.size();\n            }\n        }\n    }\n\n    // Output the final answer\n    cout << \"!\" << endl;\n    for (int i = 0; i < M; i++) {\n        vector<int> &group = groups[i];\n        int g = group.size();\n        for (int j = 0; j < g; j++) {\n            if (j > 0) cout << \" \";\n            cout << group[j];\n        }\n        cout << endl;\n        if (g == 1) continue;\n\n        // Create a set of collected edges for this group\n        set<pair<int, int>> group_edges;\n        for (auto &e : collected_edges) {\n            int u = e.first, v = e.second;\n            if (find(group.begin(), group.end(), u) != group.end() &&\n                find(group.begin(), group.end(), v) != group.end()) {\n                group_edges.insert({u, v});\n            }\n        }\n\n        // Create all possible edges within the group with priorities\n        vector<tuple<int, long long, int, int>> edges;\n        map<int, int> id_to_index;\n        for (int idx = 0; idx < g; idx++) {\n            id_to_index[group[idx]] = idx;\n        }\n        for (int a = 0; a < g; a++) {\n            for (int b = a + 1; b < g; b++) {\n                int u = group[a], v = group[b];\n                long long dx = x_center[u] - x_center[v];\n                long long dy = y_center[u] - y_center[v];\n                long long d_sq = dx * dx + dy * dy;\n                bool is_collected = group_edges.count({u, v});\n                int priority = is_collected ? 0 : 1;\n                edges.push_back({priority, d_sq, u, v});\n            }\n        }\n        sort(edges.begin(), edges.end(), [](const auto &a, const auto &b) {\n            if (get<0>(a) != get<0>(b)) return get<0>(a) < get<0>(b);\n            if (get<1>(a) != get<1>(b)) return get<1>(a) < get<1>(b);\n            if (get<2>(a) != get<2>(b)) return get<2>(a) < get<2>(b);\n            return get<3>(a) < get<3>(b);\n        });\n\n        // Kruskal's algorithm to build MST\n        vector<int> parent(g);\n        iota(parent.begin(), parent.end(), 0);\n        function<int(int)> find = [&](int x) {\n            while (parent[x] != x) {\n                parent[x] = parent[parent[x]];\n                x = parent[x];\n            }\n            return x;\n        };\n\n        vector<pair<int, int>> selected_edges;\n        for (auto &edge : edges) {\n            int u = get<2>(edge), v = get<3>(edge);\n            int u_idx = id_to_index[u], v_idx = id_to_index[v];\n            int root_u = find(u_idx), root_v = find(v_idx);\n            if (root_u != root_v) {\n                selected_edges.push_back({u, v});\n                parent[root_u] = root_v;\n                if (selected_edges.size() == g - 1) break;\n            }\n        }\n\n        for (auto &e : selected_edges) {\n            cout << e.first << \" \" << e.second << endl;\n        }\n    }\n    cout.flush();\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<pair<int, int>> points;\n    for (int i = 0; i < M; i++) {\n        int i_val, j_val;\n        cin >> i_val >> j_val;\n        points.push_back({i_val, j_val});\n    }\n\n    int cur_i = points[0].first;\n    int cur_j = points[0].second;\n    \n    // Track block positions (initially no blocks)\n    vector<vector<bool>> blocks(N, vector<bool>(N, false));\n\n    for (int idx = 1; idx < M; idx++) {\n        int target_i = points[idx].first;\n        int target_j = points[idx].second;\n\n        // Horizontal movement\n        while (cur_j != target_j) {\n            int dj = target_j - cur_j;\n            char dir = (dj > 0) ? 'R' : 'L';\n            int k = abs(dj);\n            \n            // Calculate slide distance\n            int slide_dist = 0;\n            int temp_j = cur_j;\n            while (true) {\n                int next_j = temp_j + (dj > 0 ? 1 : -1);\n                if (next_j < 0 || next_j >= N) break;\n                if (blocks[cur_i][next_j]) break;\n                slide_dist++;\n                temp_j = next_j;\n            }\n            \n            // Use slide if beneficial and possible\n            if (k <= slide_dist && \n                ((dj > 0 && target_j == N-1) || (dj < 0 && target_j == 0)) && \n                k >= 2) {\n                cout << \"S \" << dir << endl;\n                cur_j = target_j;\n            } else {\n                cout << \"M \" << dir << endl;\n                cur_j += (dj > 0 ? 1 : -1);\n            }\n        }\n\n        // Vertical movement\n        while (cur_i != target_i) {\n            int di = target_i - cur_i;\n            char dir = (di > 0) ? 'D' : 'U';\n            int k = abs(di);\n            \n            // Calculate slide distance\n            int slide_dist = 0;\n            int temp_i = cur_i;\n            while (true) {\n                int next_i = temp_i + (di > 0 ? 1 : -1);\n                if (next_i < 0 || next_i >= N) break;\n                if (blocks[next_i][cur_j]) break;\n                slide_dist++;\n                temp_i = next_i;\n            }\n            \n            // Use slide if beneficial and possible\n            if (k <= slide_dist && \n                ((di > 0 && target_i == N-1) || (di < 0 && target_i == 0)) && \n                k >= 2) {\n                cout << \"S \" << dir << endl;\n                cur_i = target_i;\n            } else {\n                cout << \"M \" << dir << endl;\n                cur_i += (di > 0 ? 1 : -1);\n            }\n        }\n    }\n\n    return 0;\n}"},"4":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <cmath>\n#include <tuple>\n#include <functional>\n\nusing namespace std;\n\nconst int GRID_SIZE = 10000;\n\nstruct Company {\n    int id;\n    int x, y, r;\n    int a, b, c, d;\n    int area() const { return (c - a) * (d - b); }\n    double satisfaction() const {\n        int s = area();\n        if (s == 0) return 0.0;\n        double ratio = min(r, s) / (double)max(r, s);\n        return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n    }\n};\n\nstruct Rectangle {\n    int a, b, c, d;\n    Rectangle(int a, int b, int c, int d) : a(a), b(b), c(c), d(d) {}\n    bool contains(int x, int y) const {\n        return a <= x && x < c && b <= y && y < d;\n    }\n    bool overlaps(const Rectangle& other) const {\n        return !(c <= other.a || other.c <= a || d <= other.b || other.d <= b);\n    }\n    int area() const { return (c - a) * (d - b); }\n};\n\nclass RobustRectanglePacker {\nprivate:\n    vector<Company> companies;\n    vector<Rectangle> rectangles;\n    \n    bool hasOverlap(const Rectangle& rect, int exclude_idx) const {\n        for (int i = 0; i < rectangles.size(); i++) {\n            if (i == exclude_idx) continue;\n            if (rect.overlaps(rectangles[i])) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    bool isValidRectangle(const Rectangle& rect, int exclude_idx) const {\n        // Check bounds\n        if (rect.a < 0 || rect.b < 0 || rect.c > GRID_SIZE || rect.d > GRID_SIZE ||\n            rect.a >= rect.c || rect.b >= rect.d) {\n            return false;\n        }\n        \n        // Check overlaps\n        return !hasOverlap(rect, exclude_idx);\n    }\n    \n    bool validateSolution() const {\n        // Check all rectangles for validity and point containment\n        for (int i = 0; i < companies.size(); i++) {\n            const Company& company = companies[i];\n            const Rectangle& rect = rectangles[i];\n            \n            // Check bounds\n            if (rect.a < 0 || rect.b < 0 || rect.c > GRID_SIZE || rect.d > GRID_SIZE ||\n                rect.a >= rect.c || rect.b >= rect.d) {\n                return false;\n            }\n            \n            // Check point containment\n            if (!rect.contains(company.x, company.y)) {\n                return false;\n            }\n            \n            // Check overlaps\n            for (int j = i + 1; j < companies.size(); j++) {\n                if (rect.overlaps(rectangles[j])) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    void expandRectangles() {\n        vector<bool> fixed(companies.size(), false);\n        int rounds = 0;\n        const int MAX_ROUNDS = 10000;\n        \n        while (rounds < MAX_ROUNDS) {\n            bool any_expansion = false;\n            \n            for (int i = 0; i < companies.size(); i++) {\n                if (fixed[i]) continue;\n                \n                Company& company = companies[i];\n                Rectangle& rect = rectangles[i];\n                int deficit = company.r - rect.area();\n                \n                if (deficit <= 0) {\n                    fixed[i] = true;\n                    continue;\n                }\n                \n                // Try expansion in each direction\n                vector<tuple<Rectangle, int>> expansions; // rectangle and area difference\n                \n                // Expand left\n                if (rect.a > 0) {\n                    Rectangle new_rect(rect.a - 1, rect.b, rect.c, rect.d);\n                    if (isValidRectangle(new_rect, i) && new_rect.contains(company.x, company.y)) {\n                        int new_area = new_rect.area();\n                        expansions.emplace_back(new_rect, abs(new_area - company.r));\n                    }\n                }\n                \n                // Expand right\n                if (rect.c < GRID_SIZE) {\n                    Rectangle new_rect(rect.a, rect.b, rect.c + 1, rect.d);\n                    if (isValidRectangle(new_rect, i) && new_rect.contains(company.x, company.y)) {\n                        int new_area = new_rect.area();\n                        expansions.emplace_back(new_rect, abs(new_area - company.r));\n                    }\n                }\n                \n                // Expand down\n                if (rect.b > 0) {\n                    Rectangle new_rect(rect.a, rect.b - 1, rect.c, rect.d);\n                    if (isValidRectangle(new_rect, i) && new_rect.contains(company.x, company.y)) {\n                        int new_area = new_rect.area();\n                        expansions.emplace_back(new_rect, abs(new_area - company.r));\n                    }\n                }\n                \n                // Expand up\n                if (rect.d < GRID_SIZE) {\n                    Rectangle new_rect(rect.a, rect.b, rect.c, rect.d + 1);\n                    if (isValidRectangle(new_rect, i) && new_rect.contains(company.x, company.y)) {\n                        int new_area = new_rect.area();\n                        expansions.emplace_back(new_rect, abs(new_area - company.r));\n                    }\n                }\n                \n                if (expansions.empty()) {\n                    fixed[i] = true;\n                    continue;\n                }\n                \n                // Choose expansion that minimizes area difference\n                auto best_expansion = min_element(expansions.begin(), expansions.end(),\n                    [](const auto& a, const auto& b) { return get<1>(a) < get<1>(b); });\n                \n                Rectangle new_rect = get<0>(*best_expansion);\n                rectangles[i] = new_rect;\n                company.a = new_rect.a;\n                company.b = new_rect.b;\n                company.c = new_rect.c;\n                company.d = new_rect.d;\n                \n                any_expansion = true;\n            }\n            \n            if (!any_expansion) break;\n            rounds++;\n        }\n    }\n    \n    void improveSatisfaction() {\n        // Try to adjust rectangles to improve satisfaction\n        for (int iter = 0; iter < 100; iter++) {\n            bool improved = false;\n            \n            for (int i = 0; i < companies.size(); i++) {\n                Company& company = companies[i];\n                Rectangle& rect = rectangles[i];\n                double current_sat = company.satisfaction();\n                \n                if (current_sat > 0.95) continue; // Already good enough\n                \n                // Try small adjustments in all directions\n                for (int dx = -5; dx <= 5; dx++) {\n                    for (int dy = -5; dy <= 5; dy++) {\n                        if (dx == 0 && dy == 0) continue;\n                        \n                        int new_a = max(0, company.a + dx);\n                        int new_b = max(0, company.b + dy);\n                        int new_c = min(GRID_SIZE, company.c + dx);\n                        int new_d = min(GRID_SIZE, company.d + dy);\n                        \n                        if (new_a >= new_c || new_b >= new_d) continue;\n                        \n                        Rectangle new_rect(new_a, new_b, new_c, new_d);\n                        if (isValidRectangle(new_rect, i) && \n                            new_rect.contains(company.x, company.y)) {\n                            \n                            Company temp = company;\n                            temp.a = new_a; temp.b = new_b;\n                            temp.c = new_c; temp.d = new_d;\n                            double new_sat = temp.satisfaction();\n                            \n                            if (new_sat > current_sat) {\n                                rectangles[i] = new_rect;\n                                company = temp;\n                                improved = true;\n                                break;\n                            }\n                        }\n                    }\n                    if (improved) break;\n                }\n            }\n            \n            if (!improved) break;\n        }\n    }\n    \n    void ensureValidity() {\n        // Final pass to ensure all rectangles are valid\n        for (int i = 0; i < companies.size(); i++) {\n            Company& company = companies[i];\n            Rectangle& rect = rectangles[i];\n            \n            // Reset to minimal valid rectangle if needed\n            if (!rect.contains(company.x, company.y) || rect.a >= rect.c || rect.b >= rect.d) {\n                rect = Rectangle(company.x, company.y, company.x + 1, company.y + 1);\n                company.a = rect.a;\n                company.b = rect.b;\n                company.c = rect.c;\n                company.d = rect.d;\n            }\n            \n            // Ensure bounds\n            company.a = max(0, min(company.a, GRID_SIZE - 1));\n            company.b = max(0, min(company.b, GRID_SIZE - 1));\n            company.c = max(1, min(company.c, GRID_SIZE));\n            company.d = max(1, min(company.d, GRID_SIZE));\n            \n            if (company.a >= company.c) company.c = company.a + 1;\n            if (company.b >= company.d) company.d = company.b + 1;\n            \n            rectangles[i] = Rectangle(company.a, company.b, company.c, company.d);\n        }\n    }\n    \npublic:\n    RobustRectanglePacker(int n, const vector<tuple<int, int, int>>& input) {\n        companies.resize(n);\n        for (int i = 0; i < n; i++) {\n            auto [x, y, r] = input[i];\n            companies[i] = {i, x, y, r, x, y, x + 1, y + 1};\n            rectangles.emplace_back(x, y, x + 1, y + 1);\n        }\n    }\n    \n    void solve() {\n        // Sort by desired area (larger areas first)\n        sort(companies.begin(), companies.end(), [](const Company& a, const Company& b) {\n            return a.r > b.r;\n        });\n        \n        // Reinitialize rectangles after sorting\n        rectangles.clear();\n        for (const auto& company : companies) {\n            rectangles.emplace_back(company.a, company.b, company.c, company.d);\n        }\n        \n        // Main expansion phase\n        expandRectangles();\n        \n        // Improvement phase\n        improveSatisfaction();\n        \n        // Final validation and correction\n        ensureValidity();\n        \n        // If solution is still invalid, fallback to minimal rectangles\n        if (!validateSolution()) {\n            for (int i = 0; i < companies.size(); i++) {\n                companies[i].a = companies[i].x;\n                companies[i].b = companies[i].y;\n                companies[i].c = companies[i].x + 1;\n                companies[i].d = companies[i].y + 1;\n                rectangles[i] = Rectangle(companies[i].a, companies[i].b, companies[i].c, companies[i].d);\n            }\n        }\n    }\n    \n    vector<tuple<int, int, int, int>> getSolution() const {\n        vector<tuple<int, int, int, int>> result;\n        result.reserve(companies.size());\n        \n        for (const auto& company : companies) {\n            result.emplace_back(company.a, company.b, company.c, company.d);\n        }\n        \n        return result;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    vector<tuple<int, int, int>> input;\n    for (int i = 0; i < n; i++) {\n        int x, y, r;\n        cin >> x >> y >> r;\n        input.emplace_back(x, y, r);\n    }\n    \n    RobustRectanglePacker packer(n, input);\n    packer.solve();\n    \n    auto solution = packer.getSolution();\n    for (const auto& [a, b, c, d] : solution) {\n        cout << a << \" \" << b << \" \" << c << \" \" << d << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <array>\n#include <algorithm>\n#include <string>\n\nusing namespace std;\n\nconst int GRID_SIZE = 50;\nconst int MAX_BEAM_WIDTH = 150; // Increased beam width\nconst int MAX_PATH_LENGTH = 2000;\n\nstruct State {\n    int i, j;\n    int score;\n    string path;\n    vector<bool> visited_tiles;\n    \n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n    \n    bool operator>(const State& other) const {\n        return score > other.score;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<vector<int>> tile_id(GRID_SIZE, vector<int>(GRID_SIZE));\n    vector<vector<int>> values(GRID_SIZE, vector<int>(GRID_SIZE));\n    \n    // Read tile IDs\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            cin >> tile_id[i][j];\n        }\n    }\n    \n    // Read square values\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            cin >> values[i][j];\n        }\n    }\n    \n    // Find maximum tile ID\n    int max_tile = 0;\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            max_tile = max(max_tile, tile_id[i][j]);\n        }\n    }\n    int tile_count = max_tile + 1;\n    \n    // Movement directions: Up, Down, Left, Right\n    array<pair<int, int>, 4> directions = {{\n        {-1, 0}, {1, 0}, {0, -1}, {0, 1}\n    }};\n    array<char, 4> dir_chars = {'U', 'D', 'L', 'R'};\n    \n    // Precompute tile information for better heuristics\n    vector<int> tile_values(tile_count, 0);\n    vector<int> tile_sizes(tile_count, 0);\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            int tid = tile_id[i][j];\n            tile_values[tid] += values[i][j];\n            tile_sizes[tid]++;\n        }\n    }\n    \n    // Initial state\n    State initial;\n    initial.i = si;\n    initial.j = sj;\n    initial.score = values[si][sj];\n    initial.path = \"\";\n    initial.visited_tiles = vector<bool>(tile_count, false);\n    initial.visited_tiles[tile_id[si][sj]] = true;\n    \n    // Beam search with priority queue (min-heap for max score)\n    priority_queue<State, vector<State>, greater<State>> current_beam;\n    current_beam.push(initial);\n    \n    State best_state = initial;\n    \n    for (int step = 0; step < MAX_PATH_LENGTH && !current_beam.empty(); step++) {\n        vector<State> next_states;\n        \n        // Process current beam\n        while (!current_beam.empty()) {\n            State current = current_beam.top();\n            current_beam.pop();\n            \n            // Try all possible moves\n            for (int d = 0; d < 4; d++) {\n                int ni = current.i + directions[d].first;\n                int nj = current.j + directions[d].second;\n                \n                // Check bounds\n                if (ni < 0 || ni >= GRID_SIZE || nj < 0 || nj >= GRID_SIZE) {\n                    continue;\n                }\n                \n                // Check if tile already visited\n                int next_tile = tile_id[ni][nj];\n                if (current.visited_tiles[next_tile]) {\n                    continue;\n                }\n                \n                // Create new state\n                State new_state = current;\n                new_state.i = ni;\n                new_state.j = nj;\n                new_state.score += values[ni][nj];\n                new_state.path += dir_chars[d];\n                new_state.visited_tiles[next_tile] = true;\n                \n                next_states.push_back(new_state);\n                \n                // Update best state\n                if (new_state.score > best_state.score) {\n                    best_state = new_state;\n                }\n            }\n        }\n        \n        // If no moves possible, break\n        if (next_states.empty()) {\n            break;\n        }\n        \n        // Sort by score and keep top states\n        sort(next_states.begin(), next_states.end(), greater<State>());\n        \n        // Use adaptive beam width - favor longer paths in early stages\n        int beam_width = MAX_BEAM_WIDTH;\n        if (step < 100) {\n            beam_width = 200; // Wider beam early to explore more\n        } else if (step < 500) {\n            beam_width = 150;\n        }\n        \n        if (next_states.size() > beam_width) {\n            next_states.resize(beam_width);\n        }\n        \n        // Add to next beam\n        for (const auto& state : next_states) {\n            current_beam.push(state);\n        }\n    }\n    \n    // Final extension attempt - try to extend the best path greedily\n    State final_state = best_state;\n    bool improved = true;\n    int extension_steps = 0;\n    const int MAX_EXTENSION = 100;\n    \n    while (improved && extension_steps < MAX_EXTENSION) {\n        improved = false;\n        vector<State> candidates;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = final_state.i + directions[d].first;\n            int nj = final_state.j + directions[d].second;\n            \n            if (ni < 0 || ni >= GRID_SIZE || nj < 0 || nj >= GRID_SIZE) {\n                continue;\n            }\n            \n            int next_tile = tile_id[ni][nj];\n            if (final_state.visited_tiles[next_tile]) {\n                continue;\n            }\n            \n            State candidate = final_state;\n            candidate.i = ni;\n            candidate.j = nj;\n            candidate.score += values[ni][nj];\n            candidate.path += dir_chars[d];\n            candidate.visited_tiles[next_tile] = true;\n            candidates.push_back(candidate);\n        }\n        \n        if (!candidates.empty()) {\n            // Find the candidate with highest score\n            auto best_candidate = max_element(candidates.begin(), candidates.end(),\n                                            [](const State& a, const State& b) {\n                                                return a.score < b.score;\n                                            });\n            \n            if (best_candidate->score > final_state.score) {\n                final_state = *best_candidate;\n                improved = true;\n                extension_steps++;\n            }\n        }\n    }\n    \n    if (final_state.score > best_state.score) {\n        best_state = final_state;\n    }\n    \n    cout << best_state.path << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nconst double INIT_WEIGHT = 5000.0;\nconst double MIN_WEIGHT = 1000.0;\nconst double MAX_WEIGHT = 9000.0;\n\ndouble horizontal[N][N-1];\ndouble vertical[N-1][N];\nint horizontal_count[N][N-1] = {0};\nint vertical_count[N-1][N] = {0};\ndouble horizontal_confidence[N][N-1] = {0};\ndouble vertical_confidence[N-1][N] = {0};\n\nstruct Node {\n    int i, j;\n    double cost;\n    bool operator<(const Node& other) const {\n        return cost > other.cost;\n    }\n};\n\nstring reconstruct_path(pair<int,int> parent[N][N], int si, int sj, int ti, int tj) {\n    string path = \"\";\n    int i = ti, j = tj;\n    \n    while (i != si || j != sj) {\n        int pi = parent[i][j].first;\n        int pj = parent[i][j].second;\n        \n        if (pi == i) {\n            if (pj < j) path += 'R';\n            else path += 'L';\n        } else {\n            if (pi < i) path += 'D';\n            else path += 'U';\n        }\n        i = pi;\n        j = pj;\n    }\n    \n    reverse(path.begin(), path.end());\n    return path;\n}\n\nstring find_path(int si, int sj, int ti, int tj) {\n    double dist[N][N];\n    pair<int,int> parent[N][N];\n    bool visited[N][N] = {false};\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            dist[i][j] = 1e18;\n        }\n    }\n    \n    dist[si][sj] = 0;\n    priority_queue<Node> pq;\n    pq.push({si, sj, 0});\n    \n    int dx[4] = {-1, 1, 0, 0};\n    int dy[4] = {0, 0, -1, 1};\n    \n    while (!pq.empty()) {\n        auto [i, j, cost] = pq.top();\n        pq.pop();\n        \n        if (visited[i][j]) continue;\n        visited[i][j] = true;\n        \n        if (i == ti && j == tj) break;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + dx[d];\n            int nj = j + dy[d];\n            \n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            \n            double edge_cost;\n            if (dx[d] != 0) { // vertical move\n                int edge_i = min(i, ni);\n                edge_cost = vertical[edge_i][j];\n            } else { // horizontal move\n                int edge_j = min(j, nj);\n                edge_cost = horizontal[i][edge_j];\n            }\n            \n            double new_cost = dist[i][j] + edge_cost;\n            if (new_cost < dist[ni][nj]) {\n                dist[ni][nj] = new_cost;\n                parent[ni][nj] = {i, j};\n                double heuristic = abs(ni - ti) + abs(nj - tj);\n                pq.push({ni, nj, new_cost + heuristic * MIN_WEIGHT});\n            }\n        }\n    }\n    \n    return reconstruct_path(parent, si, sj, ti, tj);\n}\n\nstring find_exploratory_path(int si, int sj, int ti, int tj, int query_index) {\n    // Occasionally take slightly longer paths to explore untraversed edges\n    if (query_index % 20 == 0) {\n        double dist[N][N];\n        pair<int,int> parent[N][N];\n        bool visited[N][N] = {false};\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                dist[i][j] = 1e18;\n            }\n        }\n        \n        dist[si][sj] = 0;\n        priority_queue<Node> pq;\n        pq.push({si, sj, 0});\n        \n        int dx[4] = {-1, 1, 0, 0};\n        int dy[4] = {0, 0, -1, 1};\n        \n        while (!pq.empty()) {\n            auto [i, j, cost] = pq.top();\n            pq.pop();\n            \n            if (visited[i][j]) continue;\n            visited[i][j] = true;\n            \n            if (i == ti && j == tj) break;\n            \n            for (int d = 0; d < 4; d++) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                \n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                \n                double edge_cost;\n                double exploration_bonus = 0.0;\n                \n                if (dx[d] != 0) { // vertical move\n                    int edge_i = min(i, ni);\n                    edge_cost = vertical[edge_i][j];\n                    exploration_bonus = (vertical_count[edge_i][j] == 0) ? 2000.0 : 0.0;\n                } else { // horizontal move\n                    int edge_j = min(j, nj);\n                    edge_cost = horizontal[i][edge_j];\n                    exploration_bonus = (horizontal_count[i][edge_j] == 0) ? 2000.0 : 0.0;\n                }\n                \n                double new_cost = dist[i][j] + edge_cost - exploration_bonus;\n                if (new_cost < dist[ni][nj]) {\n                    dist[ni][nj] = new_cost;\n                    parent[ni][nj] = {i, j};\n                    double heuristic = abs(ni - ti) + abs(nj - tj);\n                    pq.push({ni, nj, new_cost + heuristic * MIN_WEIGHT});\n                }\n            }\n        }\n        \n        return reconstruct_path(parent, si, sj, ti, tj);\n    }\n    \n    return find_path(si, sj, ti, tj);\n}\n\ndouble calculate_estimated_length(const string& path, int si, int sj) {\n    double length = 0;\n    int i = si, j = sj;\n    \n    for (char move : path) {\n        if (move == 'U') {\n            length += vertical[i-1][j];\n            i--;\n        } else if (move == 'D') {\n            length += vertical[i][j];\n            i++;\n        } else if (move == 'L') {\n            length += horizontal[i][j-1];\n            j--;\n        } else if (move == 'R') {\n            length += horizontal[i][j];\n            j++;\n        }\n    }\n    \n    return length;\n}\n\nvoid detect_patterns() {\n    // Detect M=1 vs M=2 patterns by analyzing variance within rows/columns\n    for (int i = 0; i < N; i++) {\n        vector<double> row_weights;\n        for (int j = 0; j < N-1; j++) {\n            row_weights.push_back(horizontal[i][j]);\n        }\n        \n        // Simple variance-based pattern detection\n        double mean = accumulate(row_weights.begin(), row_weights.end(), 0.0) / row_weights.size();\n        double variance = 0.0;\n        for (double w : row_weights) {\n            variance += (w - mean) * (w - mean);\n        }\n        variance /= row_weights.size();\n        \n        // If high variance, likely M=2 pattern\n        if (variance > 500000) { // Threshold tuned empirically\n            // Apply stronger smoothing within suspected segments\n            double seg1_avg = 0, seg2_avg = 0;\n            int seg1_count = 0, seg2_count = 0;\n            \n            // Simple segmentation: first half vs second half\n            for (int j = 0; j < (N-1)/2; j++) {\n                seg1_avg += horizontal[i][j];\n                seg1_count++;\n            }\n            for (int j = (N-1)/2; j < N-1; j++) {\n                seg2_avg += horizontal[i][j];\n                seg2_count++;\n            }\n            \n            seg1_avg /= seg1_count;\n            seg2_avg /= seg2_count;\n            \n            for (int j = 0; j < (N-1)/2; j++) {\n                horizontal[i][j] = 0.9 * horizontal[i][j] + 0.1 * seg1_avg;\n            }\n            for (int j = (N-1)/2; j < N-1; j++) {\n                horizontal[i][j] = 0.9 * horizontal[i][j] + 0.1 * seg2_avg;\n            }\n        } else {\n            // M=1 pattern - smooth across entire row\n            double row_avg = mean;\n            for (int j = 0; j < N-1; j++) {\n                horizontal[i][j] = 0.95 * horizontal[i][j] + 0.05 * row_avg;\n            }\n        }\n    }\n    \n    // Repeat for vertical edges\n    for (int j = 0; j < N; j++) {\n        vector<double> col_weights;\n        for (int i = 0; i < N-1; i++) {\n            col_weights.push_back(vertical[i][j]);\n        }\n        \n        double mean = accumulate(col_weights.begin(), col_weights.end(), 0.0) / col_weights.size();\n        double variance = 0.0;\n        for (double w : col_weights) {\n            variance += (w - mean) * (w - mean);\n        }\n        variance /= col_weights.size();\n        \n        if (variance > 500000) {\n            double seg1_avg = 0, seg2_avg = 0;\n            int seg1_count = 0, seg2_count = 0;\n            \n            for (int i = 0; i < (N-1)/2; i++) {\n                seg1_avg += vertical[i][j];\n                seg1_count++;\n            }\n            for (int i = (N-1)/2; i < N-1; i++) {\n                seg2_avg += vertical[i][j];\n                seg2_count++;\n            }\n            \n            seg1_avg /= seg1_count;\n            seg2_avg /= seg2_count;\n            \n            for (int i = 0; i < (N-1)/2; i++) {\n                vertical[i][j] = 0.9 * vertical[i][j] + 0.1 * seg1_avg;\n            }\n            for (int i = (N-1)/2; i < N-1; i++) {\n                vertical[i][j] = 0.9 * vertical[i][j] + 0.1 * seg2_avg;\n            }\n        } else {\n            double col_avg = mean;\n            for (int i = 0; i < N-1; i++) {\n                vertical[i][j] = 0.95 * vertical[i][j] + 0.05 * col_avg;\n            }\n        }\n    }\n}\n\nvoid update_weights(const string& path, int si, int sj, double observed_length, int query_index) {\n    double estimated_length = calculate_estimated_length(path, si, sj);\n    double ratio = observed_length / estimated_length;\n    \n    // Adaptive learning rate based on query progress\n    double base_learning_rate = 0.15 * (1.0 - query_index / 2000.0) + 0.05;\n    \n    int i = si, j = sj;\n    for (char move : path) {\n        if (move == 'U') {\n            int edge_i = i-1;\n            vertical_count[edge_i][j]++;\n            double confidence = min(1.0, vertical_count[edge_i][j] / 10.0);\n            double alpha = base_learning_rate / (1 + vertical_count[edge_i][j] * 0.5);\n            vertical[edge_i][j] *= (1 + alpha * (ratio - 1));\n            vertical[edge_i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[edge_i][j]));\n            vertical_confidence[edge_i][j] = confidence;\n            i--;\n        } else if (move == 'D') {\n            int edge_i = i;\n            vertical_count[edge_i][j]++;\n            double confidence = min(1.0, vertical_count[edge_i][j] / 10.0);\n            double alpha = base_learning_rate / (1 + vertical_count[edge_i][j] * 0.5);\n            vertical[edge_i][j] *= (1 + alpha * (ratio - 1));\n            vertical[edge_i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[edge_i][j]));\n            vertical_confidence[edge_i][j] = confidence;\n            i++;\n        } else if (move == 'L') {\n            int edge_j = j-1;\n            horizontal_count[i][edge_j]++;\n            double confidence = min(1.0, horizontal_count[i][edge_j] / 10.0);\n            double alpha = base_learning_rate / (1 + horizontal_count[i][edge_j] * 0.5);\n            horizontal[i][edge_j] *= (1 + alpha * (ratio - 1));\n            horizontal[i][edge_j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][edge_j]));\n            horizontal_confidence[i][edge_j] = confidence;\n            j--;\n        } else if (move == 'R') {\n            int edge_j = j;\n            horizontal_count[i][edge_j]++;\n            double confidence = min(1.0, horizontal_count[i][edge_j] / 10.0);\n            double alpha = base_learning_rate / (1 + horizontal_count[i][edge_j] * 0.5);\n            horizontal[i][edge_j] *= (1 + alpha * (ratio - 1));\n            horizontal[i][edge_j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][edge_j]));\n            horizontal_confidence[i][edge_j] = confidence;\n            j++;\n        }\n    }\n    \n    // Apply pattern-aware smoothing every 50 queries\n    if (query_index % 50 == 0) {\n        detect_patterns();\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Initialize edge weights\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N-1; j++) {\n            horizontal[i][j] = INIT_WEIGHT;\n        }\n    }\n    for (int i = 0; i < N-1; i++) {\n        for (int j = 0; j < N; j++) {\n            vertical[i][j] = INIT_WEIGHT;\n        }\n    }\n    \n    for (int k = 0; k < 1000; k++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        string path = find_exploratory_path(si, sj, ti, tj, k);\n        cout << path << endl;\n        cout.flush();\n        \n        int observed_length;\n        cin >> observed_length;\n        \n        update_weights(path, si, sj, observed_length, k);\n    }\n    \n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nbool is_substring_circular(const string& str, const string& sub) {\n    int n = str.size();\n    int L = sub.size();\n    for (int start = 0; start < n; start++) {\n        bool match = true;\n        for (int p = 0; p < L; p++) {\n            if (str[(start + p) % n] != sub[p]) {\n                match = false;\n                break;\n            }\n        }\n        if (match) return true;\n    }\n    return false;\n}\n\nvector<bool> get_matched_sequences_horizontal(const vector<string>& matrix, int i, const vector<string>& sequences) {\n    int n = matrix.size();\n    string row_str;\n    for (int j = 0; j < n; j++) {\n        row_str += matrix[i][j];\n    }\n    vector<bool> matched(sequences.size(), false);\n    for (int idx = 0; idx < sequences.size(); idx++) {\n        matched[idx] = is_substring_circular(row_str, sequences[idx]);\n    }\n    return matched;\n}\n\nvector<bool> get_matched_sequences_vertical(const vector<string>& matrix, int j, const vector<string>& sequences) {\n    int n = matrix.size();\n    string col_str;\n    for (int i = 0; i < n; i++) {\n        col_str += matrix[i][j];\n    }\n    vector<bool> matched(sequences.size(), false);\n    for (int idx = 0; idx < sequences.size(); idx++) {\n        matched[idx] = is_substring_circular(col_str, sequences[idx]);\n    }\n    return matched;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    cin >> N >> M;\n    vector<string> sequences(M);\n    for (int i = 0; i < M; i++) {\n        cin >> sequences[i];\n    }\n    \n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> char_dist(0, 7);\n    uniform_int_distribution<int> pos_dist(0, N-1);\n    uniform_real_distribution<double> prob_dist(0.0, 1.0);\n    \n    vector<int> freq(8, 0);\n    int total_chars = 0;\n    for (const auto& s : sequences) {\n        for (char c : s) {\n            freq[c - 'A']++;\n            total_chars++;\n        }\n    }\n    \n    vector<char> char_pool;\n    for (int i = 0; i < 8; i++) {\n        int count = (freq[i] * N * N) / total_chars;\n        for (int j = 0; j < count; j++) {\n            char_pool.push_back('A' + i);\n        }\n    }\n    \n    while (char_pool.size() < N * N) {\n        int max_freq = 0;\n        int max_idx = 0;\n        for (int i = 0; i < 8; i++) {\n            if (freq[i] > max_freq) {\n                max_freq = freq[i];\n                max_idx = i;\n            }\n        }\n        char_pool.push_back('A' + max_idx);\n    }\n    \n    shuffle(char_pool.begin(), char_pool.end(), gen);\n    \n    vector<string> matrix(N, string(N, ' '));\n    int idx = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            matrix[i][j] = char_pool[idx++];\n        }\n    }\n    \n    vector<int> horiz_count(M, 0);\n    vector<int> vert_count(M, 0);\n    int c = 0;\n    \n    for (int i = 0; i < N; i++) {\n        vector<bool> matched = get_matched_sequences_horizontal(matrix, i, sequences);\n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (matched[s_idx]) {\n                horiz_count[s_idx]++;\n            }\n        }\n    }\n    \n    for (int j = 0; j < N; j++) {\n        vector<bool> matched = get_matched_sequences_vertical(matrix, j, sequences);\n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (matched[s_idx]) {\n                vert_count[s_idx]++;\n            }\n        }\n    }\n    \n    for (int s_idx = 0; s_idx < M; s_idx++) {\n        if (horiz_count[s_idx] > 0 || vert_count[s_idx] > 0) {\n            c++;\n        }\n    }\n    \n    int iterations = 5000;\n    double initial_temp = 1.0;\n    double cooling_rate = 0.999;\n    \n    for (int iter = 0; iter < iterations; iter++) {\n        double temp = initial_temp * pow(cooling_rate, iter);\n        \n        int i = pos_dist(gen);\n        int j = pos_dist(gen);\n        char old_ch = matrix[i][j];\n        char new_ch;\n        do {\n            new_ch = 'A' + char_dist(gen);\n        } while (new_ch == old_ch);\n        \n        vector<int> saved_horiz_count = horiz_count;\n        vector<int> saved_vert_count = vert_count;\n        int saved_c = c;\n        \n        vector<bool> S_old_row = get_matched_sequences_horizontal(matrix, i, sequences);\n        vector<bool> S_old_col = get_matched_sequences_vertical(matrix, j, sequences);\n        \n        matrix[i][j] = new_ch;\n        \n        vector<bool> S_new_row = get_matched_sequences_horizontal(matrix, i, sequences);\n        vector<bool> S_new_col = get_matched_sequences_vertical(matrix, j, sequences);\n        \n        int new_c = saved_c;\n        \n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (S_old_row[s_idx] && !S_new_row[s_idx]) {\n                if (horiz_count[s_idx] == 1 && vert_count[s_idx] == 0) {\n                    new_c--;\n                }\n                horiz_count[s_idx]--;\n            }\n            if (!S_old_row[s_idx] && S_new_row[s_idx]) {\n                horiz_count[s_idx]++;\n                if (horiz_count[s_idx] == 1 && vert_count[s_idx] == 0) {\n                    new_c++;\n                }\n            }\n        }\n        \n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (S_old_col[s_idx] && !S_new_col[s_idx]) {\n                if (vert_count[s_idx] == 1 && horiz_count[s_idx] == 0) {\n                    new_c--;\n                }\n                vert_count[s_idx]--;\n            }\n            if (!S_old_col[s_idx] && S_new_col[s_idx]) {\n                vert_count[s_idx]++;\n                if (vert_count[s_idx] == 1 && horiz_count[s_idx] == 0) {\n                    new_c++;\n                }\n            }\n        }\n        \n        double delta_c = new_c - saved_c;\n        if (delta_c > 0 || prob_dist(gen) < exp(delta_c / temp)) {\n            c = new_c;\n        } else {\n            matrix[i][j] = old_ch;\n            horiz_count = saved_horiz_count;\n            vert_count = saved_vert_count;\n            c = saved_c;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << matrix[i] << '\\n';\n    }\n    \n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <stack>\n#include <queue>\n#include <string>\n#include <tuple>\n\nusing namespace std;\n\nclass UnionFind {\npublic:\n    vector<int> parent;\n    UnionFind(int n) {\n        parent.resize(n);\n        for (int i = 0; i < n; i++) {\n            parent[i] = i;\n        }\n    }\n    int find(int x) {\n        if (parent[x] != x) {\n            parent[x] = find(parent[x]);\n        }\n        return parent[x];\n    }\n    void unite(int x, int y) {\n        x = find(x);\n        y = find(y);\n        if (x != y) {\n            parent[x] = y;\n        }\n    }\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n\n    vector<pair<int, int>> points;\n    map<pair<int, int>, int> point_to_index;\n    vector<int> costs;\n    int index = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                points.push_back({i, j});\n                int cost = grid[i][j] - '0';\n                costs.push_back(cost);\n                point_to_index[{i, j}] = index;\n                index++;\n            }\n        }\n    }\n    int V = points.size();\n    if (V == 0) {\n        cout << \"\" << endl;\n        return 0;\n    }\n\n    vector<tuple<int, int, int>> edges;\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    for (int i = 0; i < V; i++) {\n        int x = points[i].first;\n        int y = points[i].second;\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d];\n            int ny = y + dy[d];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] != '#') {\n                int j = point_to_index[{nx, ny}];\n                int w = costs[i] + costs[j];\n                edges.push_back({i, j, w});\n            }\n        }\n    }\n\n    sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {\n        return get<2>(a) < get<2>(b);\n    });\n\n    UnionFind uf(V);\n    vector<vector<int>> mst_graph(V);\n    for (const auto& edge : edges) {\n        int u = get<0>(edge);\n        int v = get<1>(edge);\n        if (!uf.same(u, v)) {\n            uf.unite(u, v);\n            mst_graph[u].push_back(v);\n            mst_graph[v].push_back(u);\n        }\n    }\n\n    int start_index = point_to_index[{si, sj}];\n    vector<vector<int>> children(V);\n    vector<bool> visited(V, false);\n    queue<int> q;\n    q.push(start_index);\n    visited[start_index] = true;\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        for (int v : mst_graph[u]) {\n            if (!visited[v]) {\n                visited[v] = true;\n                children[u].push_back(v);\n                q.push(v);\n            }\n        }\n    }\n\n    vector<int> nextChild(V, 0);\n    stack<int> st;\n    string path;\n    int current = start_index;\n    while (true) {\n        if (nextChild[current] < children[current].size()) {\n            int child = children[current][nextChild[current]];\n            nextChild[current]++;\n            int x1 = points[current].first;\n            int y1 = points[current].second;\n            int x2 = points[child].first;\n            int y2 = points[child].second;\n            if (x2 == x1 - 1) path += 'U';\n            else if (x2 == x1 + 1) path += 'D';\n            else if (y2 == y1 - 1) path += 'L';\n            else if (y2 == y1 + 1) path += 'R';\n            st.push(current);\n            current = child;\n        } else {\n            if (st.empty()) break;\n            int parent = st.top();\n            st.pop();\n            int x1 = points[current].first;\n            int y1 = points[current].second;\n            int x2 = points[parent].first;\n            int y2 = points[parent].second;\n            if (x2 == x1 - 1) path += 'U';\n            else if (x2 == x1 + 1) path += 'D';\n            else if (y2 == y1 - 1) path += 'L';\n            else if (y2 == y1 + 1) path += 'R';\n            current = parent;\n        }\n    }\n\n    cout << path << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nenum Status {\n    NOT_STARTED = 0,\n    ASSIGNED = 1,\n    COMPLETED = 2\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<vector<int>> task_difficulty(N+1, vector<int>(K));\n    for (int i=1; i<=N; i++) {\n        for (int j=0; j<K; j++) {\n            cin >> task_difficulty[i][j];\n        }\n    }\n\n    vector<vector<int>> succ_graph(N+1);\n    vector<vector<int>> prereqs(N+1);\n    for (int i=0; i<R; i++) {\n        int u, v;\n        cin >> u >> v;\n        succ_graph[u].push_back(v);\n        prereqs[v].push_back(u);\n    }\n\n    // Precompute descendant counts\n    vector<int> desc_count(N+1, 0);\n    for (int i=1; i<=N; i++) {\n        vector<bool> visited(N+1, false);\n        queue<int> q;\n        q.push(i);\n        visited[i] = true;\n        int count = 0;\n        while (!q.empty()) {\n            int u = q.front(); q.pop();\n            count++;\n            for (int v : succ_graph[u]) {\n                if (!visited[v]) {\n                    visited[v] = true;\n                    q.push(v);\n                }\n            }\n        }\n        desc_count[i] = count;\n    }\n\n    // Initialize arrays\n    vector<Status> task_status(N+1, NOT_STARTED);\n    vector<int> member_task(M+1, -1); // -1 means idle\n    vector<int> member_start_day(M+1, 0);\n    vector<vector<double>> s_est(M+1, vector<double>(K, 40.0)); // initial skill estimate 40\n\n    vector<int> unfinished_prereqs(N+1, 0);\n    for (int i=1; i<=N; i++) {\n        unfinished_prereqs[i] = prereqs[i].size();\n    }\n\n    int current_day = 1;\n    while (true) {\n        // Identify available tasks and members\n        vector<int> available_tasks;\n        for (int i=1; i<=N; i++) {\n            if (task_status[i] == NOT_STARTED && unfinished_prereqs[i] == 0) {\n                available_tasks.push_back(i);\n            }\n        }\n\n        vector<int> available_members;\n        for (int j=1; j<=M; j++) {\n            if (member_task[j] == -1) {\n                available_members.push_back(j);\n            }\n        }\n\n        // Sort available tasks by descendant count descending\n        sort(available_tasks.begin(), available_tasks.end(), [&](int a, int b) {\n            return desc_count[a] > desc_count[b];\n        });\n\n        vector<pair<int, int>> assignments;\n        for (int task : available_tasks) {\n            if (available_members.empty()) break;\n            int best_member = -1;\n            double best_est_t = 1e9;\n\n            // Function to compute estimated time for task and member\n            auto compute_est_t = [&](int t, int m) {\n                double w = 0.0;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[t][k] > s_est[m][k]) {\n                        w += task_difficulty[t][k] - s_est[m][k];\n                    }\n                }\n                if (w == 0) return 1.0;\n                else return w;\n            };\n\n            for (int member : available_members) {\n                double est_t = compute_est_t(task, member);\n                if (est_t < best_est_t) {\n                    best_est_t = est_t;\n                    best_member = member;\n                }\n            }\n\n            if (best_member != -1) {\n                assignments.push_back({best_member, task});\n                task_status[task] = ASSIGNED;\n                member_task[best_member] = task;\n                member_start_day[best_member] = current_day;\n                // Remove the member from available_members\n                auto it = find(available_members.begin(), available_members.end(), best_member);\n                available_members.erase(it);\n            }\n        }\n\n        // Output assignments\n        cout << assignments.size();\n        for (auto& ass : assignments) {\n            cout << \" \" << ass.first << \" \" << ass.second;\n        }\n        cout << endl;\n        cout.flush();\n\n        // Read input for the day\n        int n;\n        cin >> n;\n        if (n == -1) {\n            break;\n        }\n\n        vector<int> completed_members(n);\n        for (int i=0; i<n; i++) {\n            cin >> completed_members[i];\n        }\n\n        // Process completed members\n        for (int j : completed_members) {\n            int task = member_task[j];\n            if (task == -1) continue; // Should not happen\n            int start_day = member_start_day[j];\n            int t = current_day - start_day + 1;\n\n            // Update skill estimates\n            if (t == 1) {\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        s_est[j][k] = task_difficulty[task][k];\n                    }\n                }\n            } else {\n                double w_pred = 0.0;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        w_pred += task_difficulty[task][k] - s_est[j][k];\n                    }\n                }\n                double e = t - w_pred;\n                double alpha = 0.01;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        s_est[j][k] += 2 * alpha * e;\n                        if (s_est[j][k] < 0) s_est[j][k] = 0;\n                    }\n                }\n            }\n\n            // Update task and member status\n            task_status[task] = COMPLETED;\n            member_task[j] = -1;\n\n            // Update unfinished prerequisites for successors\n            for (int v : succ_graph[task]) {\n                unfinished_prereqs[v]--;\n            }\n        }\n\n        current_day++;\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <climits>\n\nusing namespace std;\n\nstruct RoutePoint {\n    int x, y;\n    int order_id; // -1 for depot\n    bool is_pickup; // true for pickup, false for dropoff\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint manhattan_pair(pair<int, int> p1, pair<int, int> p2) {\n    return abs(p1.first - p2.first) + abs(p1.second - p2.second);\n}\n\nint calculate_cost(const vector<RoutePoint>& route) {\n    int cost = 0;\n    for (int i = 0; i < route.size() - 1; i++) {\n        cost += manhattan(route[i].x, route[i].y, route[i+1].x, route[i+1].y);\n    }\n    return cost;\n}\n\nvector<RoutePoint> remove_order(const vector<RoutePoint>& route, int order_id) {\n    vector<RoutePoint> new_route;\n    for (const auto& point : route) {\n        if (point.order_id != order_id) {\n            new_route.push_back(point);\n        }\n    }\n    return new_route;\n}\n\nint main() {\n    int a[1000], b[1000], c[1000], d[1000];\n    for (int i = 0; i < 1000; i++) {\n        cin >> a[i] >> b[i] >> c[i] >> d[i];\n    }\n\n    vector<RoutePoint> route;\n    route.push_back({400, 400, -1, false});\n    route.push_back({400, 400, -1, false});\n\n    vector<bool> selected(1000, false);\n    int selected_count = 0;\n\n    while (selected_count < 50) {\n        int best_order = -1;\n        int best_i = -1, best_j = -1;\n        int best_cost_increase = INT_MAX;\n        int n = route.size();\n\n        for (int k = 0; k < 1000; k++) {\n            if (selected[k]) continue;\n            pair<int, int> P = {a[k], b[k]};\n            pair<int, int> Q = {c[k], d[k]};\n\n            for (int i = 0; i < n-1; i++) {\n                for (int j = i; j < n-1; j++) {\n                    int cost_increase = 0;\n                    if (i < j) {\n                        cost_increase = manhattan_pair(P, {route[i].x, route[i].y}) \n                                      + manhattan_pair(P, {route[i+1].x, route[i+1].y}) \n                                      - manhattan_pair({route[i].x, route[i].y}, {route[i+1].x, route[i+1].y})\n                                      + manhattan_pair(Q, {route[j].x, route[j].y}) \n                                      + manhattan_pair(Q, {route[j+1].x, route[j+1].y}) \n                                      - manhattan_pair({route[j].x, route[j].y}, {route[j+1].x, route[j+1].y});\n                    } else {\n                        cost_increase = manhattan_pair({route[i].x, route[i].y}, P) \n                                      + manhattan_pair(P, Q) \n                                      + manhattan_pair(Q, {route[i+1].x, route[i+1].y}) \n                                      - manhattan_pair({route[i].x, route[i].y}, {route[i+1].x, route[i+1].y});\n                    }\n                    if (cost_increase < best_cost_increase) {\n                        best_cost_increase = cost_increase;\n                        best_order = k;\n                        best_i = i;\n                        best_j = j;\n                    }\n                }\n            }\n        }\n\n        if (best_order == -1) break;\n\n        RoutePoint pickup = {a[best_order], b[best_order], best_order, true};\n        RoutePoint dropoff = {c[best_order], d[best_order], best_order, false};\n\n        vector<RoutePoint> new_route;\n        for (int i = 0; i <= best_i; i++) {\n            new_route.push_back(route[i]);\n        }\n        new_route.push_back(pickup);\n        for (int i = best_i+1; i <= best_j; i++) {\n            new_route.push_back(route[i]);\n        }\n        new_route.push_back(dropoff);\n        for (int i = best_j+1; i < n; i++) {\n            new_route.push_back(route[i]);\n        }\n        route = new_route;\n        selected[best_order] = true;\n        selected_count++;\n    }\n\n    int n = route.size();\n    int total_dist = calculate_cost(route);\n\n    vector<int> pickup_index(1000, -1);\n    vector<int> dropoff_index(1000, -1);\n    for (int i = 0; i < n; i++) {\n        int order_id = route[i].order_id;\n        if (order_id == -1) continue;\n        if (route[i].is_pickup) {\n            pickup_index[order_id] = i;\n        } else {\n            dropoff_index[order_id] = i;\n        }\n    }\n\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 0; i <= n-3; i++) {\n            for (int j = i+1; j <= n-2; j++) {\n                bool valid = true;\n                for (int k = 0; k < 1000; k++) {\n                    if (selected[k]) {\n                        int pi = pickup_index[k];\n                        int di = dropoff_index[k];\n                        if (pi >= i+1 && pi <= j && di >= i+1 && di <= j) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                }\n                if (!valid) continue;\n\n                int dist_before = manhattan(route[i].x, route[i].y, route[i+1].x, route[i+1].y)\n                                + manhattan(route[j].x, route[j].y, route[j+1].x, route[j+1].y);\n                int dist_after = manhattan(route[i].x, route[i].y, route[j].x, route[j].y)\n                               + manhattan(route[i+1].x, route[i+1].y, route[j+1].x, route[j+1].y);\n                if (dist_after < dist_before) {\n                    reverse(route.begin() + i + 1, route.begin() + j + 1);\n                    total_dist += dist_after - dist_before;\n                    improved = true;\n                    for (int idx = 0; idx < route.size(); idx++) {\n                        int order_id = route[idx].order_id;\n                        if (order_id == -1) continue;\n                        if (route[idx].is_pickup) {\n                            pickup_index[order_id] = idx;\n                        } else {\n                            dropoff_index[order_id] = idx;\n                        }\n                    }\n                }\n            }\n        }\n        n = route.size();\n    }\n\n    int max_reinsert_iter = 2;\n    improved = true;\n    for (int iter = 0; iter < max_reinsert_iter && improved; iter++) {\n        improved = false;\n        for (int k = 0; k < 1000; k++) {\n            if (!selected[k]) continue;\n            vector<RoutePoint> route_without = remove_order(route, k);\n            int cost_without = calculate_cost(route_without);\n            int best_cost = INT_MAX;\n            int best_i = -1, best_j = -1;\n            int n_new = route_without.size();\n            for (int i = 0; i < n_new - 1; i++) {\n                for (int j = i; j < n_new - 1; j++) {\n                    int cost_increase = 0;\n                    if (i < j) {\n                        cost_increase = manhattan(route_without[i].x, route_without[i].y, a[k], b[k])\n                                      + manhattan(a[k], b[k], route_without[i+1].x, route_without[i+1].y)\n                                      - manhattan(route_without[i].x, route_without[i].y, route_without[i+1].x, route_without[i+1].y)\n                                      + manhattan(route_without[j].x, route_without[j].y, c[k], d[k])\n                                      + manhattan(c[k], d[k], route_without[j+1].x, route_without[j+1].y)\n                                      - manhattan(route_without[j].x, route_without[j].y, route_without[j+1].x, route_without[j+1].y);\n                    } else {\n                        cost_increase = manhattan(route_without[i].x, route_without[i].y, a[k], b[k])\n                                      + manhattan(a[k], b[k], c[k], d[k])\n                                      + manhattan(c[k], d[k], route_without[i+1].x, route_without[i+1].y)\n                                      - manhattan(route_without[i].x, route_without[i].y, route_without[i+1].x, route_without[i+1].y);\n                    }\n                    int total_cost = cost_without + cost_increase;\n                    if (total_cost < best_cost) {\n                        best_cost = total_cost;\n                        best_i = i;\n                        best_j = j;\n                    }\n                }\n            }\n            if (best_cost < total_dist) {\n                RoutePoint pickup = {a[k], b[k], k, true};\n                RoutePoint dropoff = {c[k], d[k], k, false};\n                vector<RoutePoint> new_route = route_without;\n                if (best_i < best_j) {\n                    new_route.insert(new_route.begin() + best_i + 1, pickup);\n                    new_route.insert(new_route.begin() + best_j + 2, dropoff);\n                } else {\n                    new_route.insert(new_route.begin() + best_i + 1, pickup);\n                    new_route.insert(new_route.begin() + best_i + 2, dropoff);\n                }\n                route = new_route;\n                total_dist = best_cost;\n                improved = true;\n                for (int i = 0; i < route.size(); i++) {\n                    int order_id = route[i].order_id;\n                    if (order_id == -1) continue;\n                    if (route[i].is_pickup) {\n                        pickup_index[order_id] = i;\n                    } else {\n                        dropoff_index[order_id] = i;\n                    }\n                }\n            }\n        }\n        if (improved) {\n            n = route.size();\n            bool opt_improved = true;\n            while (opt_improved) {\n                opt_improved = false;\n                for (int i = 0; i <= n-3; i++) {\n                    for (int j = i+1; j <= n-2; j++) {\n                        bool valid = true;\n                        for (int k = 0; k < 1000; k++) {\n                            if (selected[k]) {\n                                int pi = pickup_index[k];\n                                int di = dropoff_index[k];\n                                if (pi >= i+1 && pi <= j && di >= i+1 && di <= j) {\n                                    valid = false;\n                                    break;\n                                }\n                            }\n                        }\n                        if (!valid) continue;\n                        int dist_before = manhattan(route[i].x, route[i].y, route[i+1].x, route[i+1].y)\n                                        + manhattan(route[j].x, route[j].y, route[j+1].x, route[j+1].y);\n                        int dist_after = manhattan(route[i].x, route[i].y, route[j].x, route[j].y)\n                                       + manhattan(route[i+1].x, route[i+1].y, route[j+1].x, route[j+1].y);\n                        if (dist_after < dist_before) {\n                            reverse(route.begin() + i + 1, route.begin() + j + 1);\n                            total_dist += dist_after - dist_before;\n                            opt_improved = true;\n                            for (int idx = 0; idx < route.size(); idx++) {\n                                int order_id = route[idx].order_id;\n                                if (order_id == -1) continue;\n                                if (route[idx].is_pickup) {\n                                    pickup_index[order_id] = idx;\n                                } else {\n                                    dropoff_index[order_id] = idx;\n                                }\n                            }\n                        }\n                    }\n                }\n                n = route.size();\n            }\n        }\n    }\n\n    cout << 50 << \" \";\n    for (int i = 0; i < 1000; i++) {\n        if (selected[i]) {\n            cout << i+1 << \" \";\n        }\n    }\n    cout << endl;\n\n    cout << route.size() << \" \";\n    for (auto &p : route) {\n        cout << p.x << \" \" << p.y << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <functional>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\nconst int N = 400;\nconst int M = 1995;\n\nint main() {\n    vector<double> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<pair<int, int>> edge_pairs(M);\n    for (int i = 0; i < M; i++) {\n        int u, v;\n        cin >> u >> v;\n        edge_pairs[i] = {u, v};\n    }\n\n    vector<int> d(M);\n    for (int i = 0; i < M; i++) {\n        int u = edge_pairs[i].first;\n        int v = edge_pairs[i].second;\n        double dx = x[u] - x[v];\n        double dy = y[u] - y[v];\n        double dist = sqrt(dx*dx + dy*dy);\n        d[i] = static_cast<int>(round(dist));\n    }\n\n    vector<tuple<int, int, int, int>> edges_for_mst;\n    for (int i = 0; i < M; i++) {\n        edges_for_mst.push_back({d[i], edge_pairs[i].first, edge_pairs[i].second, i});\n    }\n\n    sort(edges_for_mst.begin(), edges_for_mst.end());\n\n    vector<int> parent_mst(N);\n    for (int i = 0; i < N; i++) {\n        parent_mst[i] = i;\n    }\n\n    function<int(int)> find_mst = [&](int a) {\n        if (parent_mst[a] == a) return a;\n        return parent_mst[a] = find_mst(parent_mst[a]);\n    };\n\n    vector<bool> in_mst(M, false);\n    for (auto& edge : edges_for_mst) {\n        int d_val = get<0>(edge);\n        int u = get<1>(edge);\n        int v = get<2>(edge);\n        int idx = get<3>(edge);\n        int pu = find_mst(u);\n        int pv = find_mst(v);\n        if (pu != pv) {\n            in_mst[idx] = true;\n            parent_mst[pu] = pv;\n        }\n    }\n\n    vector<int> parent(N);\n    for (int i = 0; i < N; i++) {\n        parent[i] = i;\n    }\n\n    function<int(int)> find = [&](int a) {\n        if (parent[a] == a) return a;\n        return parent[a] = find(parent[a]);\n    };\n\n    int num_components = N;\n\n    auto unite = [&](int a, int b) {\n        a = find(a);\n        b = find(b);\n        if (a != b) {\n            parent[a] = b;\n            num_components--;\n            return true;\n        }\n        return false;\n    };\n\n    for (int i = 0; i < M; i++) {\n        int l_i;\n        cin >> l_i;\n\n        int u = edge_pairs[i].first;\n        int v = edge_pairs[i].second;\n\n        if (find(u) == find(v)) {\n            cout << 0 << endl;\n        } else {\n            if (in_mst[i] || l_i <= 2 * d[i] || (M - i - 1) < (num_components - 1)) {\n                cout << 1 << endl;\n                unite(u, v);\n            } else {\n                cout << 0 << endl;\n            }\n        }\n        cout.flush();\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int MAX_TURNS = 300;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<tuple<int, int, int>> pets;\n    for (int i = 0; i < N; i++) {\n        int x, y, t;\n        cin >> x >> y >> t;\n        pets.push_back({x, y, t});\n    }\n    int M;\n    cin >> M;\n    vector<pair<int, int>> humans;\n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        humans.push_back({x, y});\n    }\n\n    vector<vector<bool>> blocked(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n    vector<pair<int, int>> wall_squares;\n    vector<pair<int, int>> base_squares;\n\n    for (int i = 1; i <= 20; i++) {\n        wall_squares.push_back({20, i});\n        base_squares.push_back({19, i});\n    }\n    for (int i = 1; i <= 19; i++) {\n        wall_squares.push_back({i, 20});\n        base_squares.push_back({i, 19});\n    }\n\n    int total_walls = wall_squares.size();\n    vector<vector<pair<int, int>>> human_wall_squares(M);\n    vector<vector<pair<int, int>>> human_base_squares(M);\n\n    for (int i = 0; i < total_walls; i++) {\n        int human_idx = i % M;\n        human_wall_squares[human_idx].push_back(wall_squares[i]);\n        human_base_squares[human_idx].push_back(base_squares[i]);\n    }\n\n    vector<int> human_target_index(M, 0);\n    vector<vector<bool>> wall_built(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n\n    for (int turn = 1; turn <= MAX_TURNS; turn++) {\n        vector<char> actions(M, '.');\n        set<pair<int, int>> blocks_this_turn;\n\n        // First pass: Decide block actions\n        for (int i = 0; i < M; i++) {\n            if (human_target_index[i] >= human_wall_squares[i].size()) {\n                continue;\n            }\n\n            pair<int, int> target_wall = human_wall_squares[i][human_target_index[i]];\n            pair<int, int> target_base = human_base_squares[i][human_target_index[i]];\n\n            if (wall_built[target_wall.first][target_wall.second]) {\n                human_target_index[i]++;\n                if (human_target_index[i] < human_wall_squares[i].size()) {\n                    target_wall = human_wall_squares[i][human_target_index[i]];\n                    target_base = human_base_squares[i][human_target_index[i]];\n                } else {\n                    continue;\n                }\n            }\n\n            if (humans[i] == target_base) {\n                bool can_block = true;\n\n                // Check if wall square is empty\n                for (auto& pet : pets) {\n                    if (get<0>(pet) == target_wall.first && get<1>(pet) == target_wall.second) {\n                        can_block = false;\n                        break;\n                    }\n                }\n                if (can_block) {\n                    for (int j = 0; j < M; j++) {\n                        if (humans[j].first == target_wall.first && humans[j].second == target_wall.second) {\n                            can_block = false;\n                            break;\n                        }\n                    }\n                }\n\n                // Check adjacent squares for pets\n                if (can_block) {\n                    int dx[] = {1, -1, 0, 0};\n                    int dy[] = {0, 0, 1, -1};\n                    for (int d = 0; d < 4; d++) {\n                        int nx = target_wall.first + dx[d];\n                        int ny = target_wall.second + dy[d];\n                        if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                        for (auto& pet : pets) {\n                            if (get<0>(pet) == nx && get<1>(pet) == ny) {\n                                can_block = false;\n                                break;\n                            }\n                        }\n                        if (!can_block) break;\n                    }\n                }\n\n                if (can_block) {\n                    int dx = target_wall.first - target_base.first;\n                    int dy = target_wall.second - target_base.second;\n                    char action;\n                    if (dx == 1) action = 'd';\n                    else if (dx == -1) action = 'u';\n                    else if (dy == 1) action = 'r';\n                    else if (dy == -1) action = 'l';\n                    else action = '.';\n                    actions[i] = action;\n                    blocks_this_turn.insert(target_wall);\n                }\n            }\n        }\n\n        // Second pass: Decide movement actions\n        for (int i = 0; i < M; i++) {\n            if (actions[i] != '.') continue; // Skip if already decided (block action)\n\n            if (human_target_index[i] >= human_wall_squares[i].size()) {\n                continue;\n            }\n\n            pair<int, int> target_wall = human_wall_squares[i][human_target_index[i]];\n            pair<int, int> target_base = human_base_squares[i][human_target_index[i]];\n\n            if (wall_built[target_wall.first][target_wall.second]) {\n                human_target_index[i]++;\n                if (human_target_index[i] < human_wall_squares[i].size()) {\n                    target_wall = human_wall_squares[i][human_target_index[i]];\n                    target_base = human_base_squares[i][human_target_index[i]];\n                } else {\n                    continue;\n                }\n            }\n\n            if (humans[i] != target_base) {\n                vector<vector<bool>> obstacles(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n                // Mark static obstacles\n                for (int x = 1; x <= GRID_SIZE; x++) {\n                    for (int y = 1; y <= GRID_SIZE; y++) {\n                        if (blocked[x][y]) obstacles[x][y] = true;\n                    }\n                }\n                // Mark blocks that will be placed this turn\n                for (auto& block : blocks_this_turn) {\n                    obstacles[block.first][block.second] = true;\n                }\n\n                queue<pair<int, int>> q;\n                vector<vector<int>> dist(GRID_SIZE + 1, vector<int>(GRID_SIZE + 1, -1));\n                vector<vector<pair<int, int>>> prev(GRID_SIZE + 1, vector<pair<int, int>>(GRID_SIZE + 1, {-1, -1}));\n                int start_x = humans[i].first;\n                int start_y = humans[i].second;\n                dist[start_x][start_y] = 0;\n                q.push({start_x, start_y});\n\n                int dx[] = {1, -1, 0, 0};\n                int dy[] = {0, 0, 1, -1};\n\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d];\n                        int ny = y + dy[d];\n                        if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                        if (obstacles[nx][ny]) continue;\n                        if (dist[nx][ny] == -1) {\n                            dist[nx][ny] = dist[x][y] + 1;\n                            prev[nx][ny] = {x, y};\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n\n                if (dist[target_base.first][target_base.second] != -1) {\n                    vector<pair<int, int>> path;\n                    pair<int, int> cur = target_base;\n                    while (cur != make_pair(start_x, start_y)) {\n                        path.push_back(cur);\n                        cur = prev[cur.first][cur.second];\n                    }\n                    reverse(path.begin(), path.end());\n                    if (!path.empty()) {\n                        pair<int, int> first_step = path[0];\n                        int dx = first_step.first - start_x;\n                        int dy = first_step.second - start_y;\n                        char action;\n                        if (dx == 1) action = 'D';\n                        else if (dx == -1) action = 'U';\n                        else if (dy == 1) action = 'R';\n                        else if (dy == -1) action = 'L';\n                        else action = '.';\n                        actions[i] = action;\n                    }\n                }\n            }\n        }\n\n        string action_str;\n        for (int i = 0; i < M; i++) {\n            action_str += actions[i];\n        }\n        cout << action_str << endl;\n        cout.flush();\n\n        // Update state based on actions\n        for (int i = 0; i < M; i++) {\n            char action = actions[i];\n            if (action == 'u' || action == 'd' || action == 'l' || action == 'r') {\n                int x = humans[i].first;\n                int y = humans[i].second;\n                int block_x, block_y;\n                if (action == 'u') block_x = x - 1, block_y = y;\n                else if (action == 'd') block_x = x + 1, block_y = y;\n                else if (action == 'l') block_x = x, block_y = y - 1;\n                else if (action == 'r') block_x = x, block_y = y + 1;\n\n                if (block_x >= 1 && block_x <= GRID_SIZE && block_y >= 1 && block_y <= GRID_SIZE) {\n                    blocked[block_x][block_y] = true;\n                    wall_built[block_x][block_y] = true;\n                }\n            }\n        }\n\n        // Update human positions\n        for (int i = 0; i < M; i++) {\n            char action = actions[i];\n            if (action == 'U') humans[i].first--;\n            else if (action == 'D') humans[i].first++;\n            else if (action == 'L') humans[i].second--;\n            else if (action == 'R') humans[i].second++;\n        }\n\n        // Read and update pet positions\n        vector<string> pet_movements(N);\n        for (int i = 0; i < N; i++) {\n            cin >> pet_movements[i];\n        }\n\n        for (int i = 0; i < N; i++) {\n            string moves = pet_movements[i];\n            int x = get<0>(pets[i]);\n            int y = get<1>(pets[i]);\n            for (char move : moves) {\n                if (move == 'U') x--;\n                else if (move == 'D') x++;\n                else if (move == 'L') y--;\n                else if (move == 'R') y++;\n            }\n            get<0>(pets[i]) = x;\n            get<1>(pets[i]) = y;\n        }\n    }\n\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <string>\n#include <utility>\n#include <map>\n\nusing namespace std;\n\nconst int GRID_SIZE = 20;\n\n// Directions: Up, Down, Left, Right\nconst int dx[4] = {-1, 1, 0, 0};\nconst int dy[4] = {0, 0, -1, 1};\nconst char dir_char[4] = {'U', 'D', 'L', 'R'};\n\nstruct Cell {\n    int i, j;\n    Cell(int i = 0, int j = 0) : i(i), j(j) {}\n    bool operator==(const Cell& other) const {\n        return i == other.i && j == other.j;\n    }\n    bool operator<(const Cell& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nclass Grid {\npublic:\n    Grid(int si, int sj, int ti, int tj, double p, \n         const vector<string>& h, const vector<string>& v) \n        : si(si), sj(sj), ti(ti), tj(tj), p(p) {\n        this->h = h;\n        this->v = v;\n    }\n\n    bool is_move_allowed(int i, int j, int d) const {\n        if (d == 0) { // Up\n            return i > 0 && v[i-1][j] == '0';\n        } else if (d == 1) { // Down\n            return i < GRID_SIZE - 1 && v[i][j] == '0';\n        } else if (d == 2) { // Left\n            return j > 0 && h[i][j-1] == '0';\n        } else if (d == 3) { // Right\n            return j < GRID_SIZE - 1 && h[i][j] == '0';\n        }\n        return false;\n    }\n\n    string find_shortest_path() const {\n        Cell start(si, sj);\n        Cell end(ti, tj);\n\n        map<Cell, Cell> parent;\n        map<Cell, int> move_dir;\n        queue<Cell> q;\n        q.push(start);\n        parent[start] = start;\n        move_dir[start] = -1;\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            if (current == end) {\n                break;\n            }\n            for (int d = 0; d < 4; d++) {\n                if (is_move_allowed(current.i, current.j, d)) {\n                    Cell next(current.i + dx[d], current.j + dy[d]);\n                    if (parent.find(next) == parent.end()) {\n                        parent[next] = current;\n                        move_dir[next] = d;\n                        q.push(next);\n                    }\n                }\n            }\n        }\n\n        string path;\n        Cell current = end;\n        while (current != start) {\n            int d = move_dir[current];\n            path.push_back(dir_char[d]);\n            current = parent[current];\n        }\n        reverse(path.begin(), path.end());\n        return path;\n    }\n\n    string find_cycle() const {\n        if (is_move_allowed(ti, tj, 0) && is_move_allowed(ti-1, tj, 1)) {\n            return \"UD\";\n        }\n        if (is_move_allowed(ti, tj, 2) && is_move_allowed(ti, tj-1, 3)) {\n            return \"LR\";\n        }\n        return \"UD\";\n    }\n\nprivate:\n    int si, sj, ti, tj;\n    double p;\n    vector<string> h;\n    vector<string> v;\n};\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    vector<string> h(GRID_SIZE);\n    for (int i = 0; i < GRID_SIZE; i++) {\n        cin >> h[i];\n    }\n\n    vector<string> v(GRID_SIZE - 1);\n    for (int i = 0; i < GRID_SIZE - 1; i++) {\n        cin >> v[i];\n    }\n\n    Grid grid(si, sj, ti, tj, p, h, v);\n    string path = grid.find_shortest_path();\n    string cycle = grid.find_cycle();\n\n    int L = path.size();\n    int K = 200 / L;  // Maximum repetitions without exceeding 200 moves\n    string result;\n    for (int i = 0; i < K; i++) {\n        result += path;\n    }\n    int remaining = 200 - result.size();\n    if (remaining > 0) {\n        int cycle_len = cycle.size();\n        int num_cycles = remaining / cycle_len;\n        for (int i = 0; i < num_cycles; i++) {\n            result += cycle;\n        }\n        int extra = remaining % cycle_len;\n        if (extra > 0) {\n            result += cycle.substr(0, extra);\n        }\n    }\n\n    // Ensure the string length is exactly 200 by truncating if necessary\n    if (result.size() > 200) {\n        result = result.substr(0, 200);\n    }\n\n    cout << result << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int to[8][4] = {\n        {1, 0, -1, -1}, // type 0\n        {3, -1, -1, 0}, // type 1\n        {-1, -1, 3, 2}, // type 2\n        {-1, 2, 1, -1}, // type 3\n        {1, 0, 3, 2}, // type 4\n        {3, 2, 1, 0}, // type 5\n        {2, -1, 0, -1}, // type 6\n        {-1, 3, -1, 1}  // type 7\n    };\n\n    for (int t = 0; t < 100; t++) {\n        vector<string> grid;\n        for (int i = 0; i < 30; i++) {\n            string line;\n            cin >> line;\n            grid.push_back(line);\n        }\n\n        string result(900, '0');\n        for (int i = 0; i < 30; i++) {\n            for (int j = 0; j < 30; j++) {\n                int T = grid[i][j] - '0';\n                bool has_neighbor[4] = {false};\n                if (j > 0) has_neighbor[0] = true;\n                if (i > 0) has_neighbor[1] = true;\n                if (j < 29) has_neighbor[2] = true;\n                if (i < 29) has_neighbor[3] = true;\n\n                int best_R = 0;\n                int best_score = 1000000;\n\n                for (int R = 0; R < 4; R++) {\n                    int score = 0;\n                    for (int d = 0; d < 4; d++) {\n                        if (!has_neighbor[d]) continue;\n                        int d_local = (d - R + 4) % 4;\n                        int e_local = to[T][d_local];\n                        if (e_local == -1) {\n                            score++;\n                        } else {\n                            int e = (e_local + R) % 4;\n                            if (!has_neighbor[e]) {\n                                score++;\n                            }\n                        }\n                    }\n                    if (score < best_score) {\n                        best_score = score;\n                        best_R = R;\n                    }\n                }\n                result[i * 30 + j] = '0' + best_R;\n            }\n        }\n        cout << result << endl;\n    }\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <queue>\n#include <utility>\n\nusing namespace std;\n\nint compute_cost(vector<vector<int>> &grid, int N) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    int sum_squares = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == 0) continue;\n            if (visited[i][j]) continue;\n            int size = 0;\n            queue<pair<int, int>> q;\n            q.push({i, j});\n            visited[i][j] = true;\n            while (!q.empty()) {\n                auto [r, c] = q.front();\n                q.pop();\n                size++;\n                int dr[4] = {-1, 1, 0, 0};\n                int dc[4] = {0, 0, -1, 1};\n                int self_line[4] = {2, 8, 1, 4};\n                int neighbor_line[4] = {8, 2, 4, 1};\n                for (int d = 0; d < 4; d++) {\n                    int nr = r + dr[d];\n                    int nc = c + dc[d];\n                    if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                    if (grid[nr][nc] == 0) continue;\n                    if (visited[nr][nc]) continue;\n                    if (grid[r][c] & self_line[d] && grid[nr][nc] & neighbor_line[d]) {\n                        q.push({nr, nc});\n                        visited[nr][nc] = true;\n                    }\n                }\n            }\n            sum_squares += size * size;\n        }\n    }\n    return sum_squares;\n}\n\nvoid make_move(char D, vector<vector<int>> &grid, int &er, int &ec) {\n    int pr, pc;\n    if (D == 'U') {\n        pr = er - 1;\n        pc = ec;\n    } else if (D == 'D') {\n        pr = er + 1;\n        pc = ec;\n    } else if (D == 'L') {\n        pr = er;\n        pc = ec - 1;\n    } else if (D == 'R') {\n        pr = er;\n        pc = ec + 1;\n    } else {\n        return;\n    }\n    swap(grid[er][ec], grid[pr][pc]);\n    er = pr;\n    ec = pc;\n}\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n\n    vector<vector<int>> grid(N, vector<int>(N));\n    int empty_row = 0, empty_col = 0;\n\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            char c = s[j];\n            if (c >= '0' && c <= '9') {\n                grid[i][j] = c - '0';\n            } else if (c >= 'a' && c <= 'f') {\n                grid[i][j] = 10 + (c - 'a');\n            } else {\n                grid[i][j] = 0;\n            }\n            if (grid[i][j] == 0) {\n                empty_row = i;\n                empty_col = j;\n            }\n        }\n    }\n\n    vector<vector<int>> current_grid = grid;\n    int er = empty_row, ec = empty_col;\n    int current_cost = compute_cost(current_grid, N);\n    string moves = \"\";\n    double T0 = 100.0;\n    srand(time(0));\n\n    for (int t = 0; t < T; t++) {\n        int max_cost = (N * N - 1) * (N * N - 1);\n        if (current_cost == max_cost) {\n            break;\n        }\n\n        double temp = T0 * (1.0 - static_cast<double>(t) / T);\n        if (temp < 1e-9) temp = 1e-9;\n\n        vector<char> directions;\n        if (er > 0) directions.push_back('U');\n        if (er < N - 1) directions.push_back('D');\n        if (ec > 0) directions.push_back('L');\n        if (ec < N - 1) directions.push_back('R');\n\n        if (directions.empty()) break;\n\n        vector<double> weights;\n        vector<char> dirs;\n        vector<int> new_costs;\n\n        for (char D : directions) {\n            vector<vector<int>> temp_grid = current_grid;\n            int temp_er = er, temp_ec = ec;\n            make_move(D, temp_grid, temp_er, temp_ec);\n            int new_cost = compute_cost(temp_grid, N);\n            int delta = new_cost - current_cost;\n            double weight = (delta >= 0) ? 1.0 : exp(delta / temp);\n            weights.push_back(weight);\n            dirs.push_back(D);\n            new_costs.push_back(new_cost);\n        }\n\n        double total_weight = 0.0;\n        for (double w : weights) total_weight += w;\n        if (total_weight == 0.0) {\n            weights.assign(weights.size(), 1.0);\n            total_weight = weights.size();\n        }\n\n        double r = static_cast<double>(rand()) / RAND_MAX * total_weight;\n        double cumulative = 0.0;\n        int index = 0;\n        for (int i = 0; i < weights.size(); i++) {\n            cumulative += weights[i];\n            if (r < cumulative) {\n                index = i;\n                break;\n            }\n        }\n\n        char chosen_D = dirs[index];\n        int chosen_new_cost = new_costs[index];\n        make_move(chosen_D, current_grid, er, ec);\n        current_cost = chosen_new_cost;\n        moves += chosen_D;\n    }\n\n    cout << moves << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <climits>\n\nusing namespace std;\n\nint main() {\n    int N, K;\n    cin >> N >> K;\n    int a[10];\n    for (int i = 0; i < 10; i++) {\n        cin >> a[i];\n    }\n    vector<pair<int, int>> points;\n    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n        points.push_back({x, y});\n    }\n\n    int S = 0;\n    for (int i = 0; i < 10; i++) {\n        S += a[i];\n    }\n\n    int best_diff = INT_MAX;\n    int best_R = 1, best_C = 1;\n    for (int R = 1; R <= K + 2; R++) {\n        for (int C = 1; C <= K + 2 - R; C++) {\n            if (R + C - 2 > K) continue;\n            int product = R * C;\n            int diff = abs(product - S);\n            int balance = abs(R - C);\n            if (diff < best_diff || (diff == best_diff && balance < abs(best_R - best_C))) {\n                best_diff = diff;\n                best_R = R;\n                best_C = C;\n            }\n        }\n    }\n\n    int cuts_needed = best_R + best_C - 2;\n    cout << cuts_needed << endl;\n\n    const int min_coord = -10000;\n    const int max_coord = 10000;\n\n    double step_x = (max_coord - min_coord) / static_cast<double>(best_C);\n    for (int i = 1; i < best_C; i++) {\n        int x = min_coord + round(i * step_x);\n        cout << x << \" \" << -1000000000 << \" \" << x << \" \" << 1000000000 << endl;\n    }\n\n    double step_y = (max_coord - min_coord) / static_cast<double>(best_R);\n    for (int i = 1; i < best_R; i++) {\n        int y = min_coord + round(i * step_y);\n        cout << -1000000000 << \" \" << y << \" \" << 1000000000 << \" \" << y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const { return x == other.x && y == other.y; }\n    bool operator<(const Point& other) const {\n        return x < other.x || (x == other.x && y < other.y);\n    }\n};\n\nstruct Segment {\n    Point a, b;\n    Segment(Point a, Point b) : a(a), b(b) {}\n    bool operator<(const Segment& other) const {\n        if (a.x != other.a.x) return a.x < other.a.x;\n        if (a.y != other.a.y) return a.y < other.a.y;\n        if (b.x != other.b.x) return b.x < other.b.x;\n        return b.y < other.b.y;\n    }\n};\n\nclass RectJoinSolver {\nprivate:\n    int N, M;\n    set<Point> dots;\n    set<Segment> used_segments;\n    vector<vector<Point>> operations;\n    Point center;\n    \n    bool is_valid_point(int x, int y) {\n        return x >= 0 && x < N && y >= 0 && y < N;\n    }\n    \n    bool has_dot(const Point& p) {\n        return dots.count(p);\n    }\n    \n    // Simple axis-aligned rectangle check\n    bool is_axis_aligned(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        set<int> xs, ys;\n        xs.insert(p1.x); xs.insert(p2.x); xs.insert(p3.x); xs.insert(p4.x);\n        ys.insert(p1.y); ys.insert(p2.y); ys.insert(p3.y); ys.insert(p4.y);\n        return xs.size() == 2 && ys.size() == 2;\n    }\n    \n    // Simple 45-degree rotated rectangle check (diamond)\n    bool is_rotated(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        // Check if all points are on a diamond shape\n        vector<Point> points = {p1, p2, p3, p4};\n        \n        // Check if it's a square rotated by 45 degrees\n        // The center should be the average of all points\n        double cx = 0, cy = 0;\n        for (const auto& p : points) {\n            cx += p.x;\n            cy += p.y;\n        }\n        cx /= 4;\n        cy /= 4;\n        \n        // All points should be at the same distance from center\n        vector<double> distances;\n        for (const auto& p : points) {\n            double dx = p.x - cx;\n            double dy = p.y - cy;\n            distances.push_back(dx*dx + dy*dy);\n        }\n        \n        // Check if all distances are equal (within tolerance)\n        if (distances.size() != 4) return false;\n        for (int i = 1; i < 4; i++) {\n            if (abs(distances[i] - distances[0]) > 1e-9) return false;\n        }\n        \n        // Check if points form 90 degree angles (diamond)\n        return true;\n    }\n    \n    vector<Point> get_points_on_segment(const Point& a, const Point& b) {\n        vector<Point> points;\n        if (a.x == b.x) {\n            int y1 = min(a.y, b.y), y2 = max(a.y, b.y);\n            for (int y = y1; y <= y2; y++) {\n                points.push_back(Point(a.x, y));\n            }\n        } else if (a.y == b.y) {\n            int x1 = min(a.x, b.x), x2 = max(a.x, b.x);\n            for (int x = x1; x <= x2; x++) {\n                points.push_back(Point(x, a.y));\n            }\n        } else if (abs(a.x - b.x) == abs(a.y - b.y)) {\n            int dx = (b.x > a.x) ? 1 : -1;\n            int dy = (b.y > a.y) ? 1 : -1;\n            int steps = abs(a.x - b.x);\n            for (int i = 0; i <= steps; i++) {\n                points.push_back(Point(a.x + i*dx, a.y + i*dy));\n            }\n        }\n        return points;\n    }\n    \n    bool check_no_other_dots(const vector<Point>& corners, const Point& new_dot) {\n        set<Point> allowed_dots;\n        for (int i = 1; i < 4; i++) {\n            allowed_dots.insert(corners[i]);\n        }\n        \n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            auto segment_points = get_points_on_segment(a, b);\n            \n            for (const Point& p : segment_points) {\n                if (p == a || p == b) continue; // Endpoints are allowed\n                if (has_dot(p) && !allowed_dots.count(p)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    bool check_no_overlapping_segments(const vector<Point>& corners) {\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            auto segment_points = get_points_on_segment(a, b);\n            \n            for (int j = 0; j < (int)segment_points.size() - 1; j++) {\n                Point p1 = segment_points[j];\n                Point p2 = segment_points[j+1];\n                Segment seg(p1, p2);\n                \n                if (used_segments.count(seg)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    void mark_segments_used(const vector<Point>& corners) {\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            auto segment_points = get_points_on_segment(a, b);\n            \n            for (int j = 0; j < (int)segment_points.size() - 1; j++) {\n                Point p1 = segment_points[j];\n                Point p2 = segment_points[j+1];\n                Segment seg(p1, p2);\n                used_segments.insert(seg);\n            }\n        }\n    }\n    \n    vector<Point> order_points_clockwise(const vector<Point>& points) {\n        if (points.size() != 4) return points;\n        \n        // Find centroid\n        double cx = 0, cy = 0;\n        for (const auto& p : points) {\n            cx += p.x;\n            cy += p.y;\n        }\n        cx /= 4;\n        cy /= 4;\n        \n        // Sort by angle\n        vector<Point> ordered = points;\n        sort(ordered.begin(), ordered.end(), [cx, cy](const Point& a, const Point& b) {\n            return atan2(a.y - cy, a.x - cx) < atan2(b.y - cy, b.x - cx);\n        });\n        \n        return ordered;\n    }\n    \n    vector<vector<Point>> generate_simple_candidates() {\n        vector<vector<Point>> candidates;\n        vector<Point> dot_list(dots.begin(), dots.end());\n        \n        // Try simple axis-aligned rectangles first\n        for (int i = 0; i < dot_list.size(); i++) {\n            for (int j = i + 1; j < dot_list.size(); j++) {\n                for (int k = j + 1; k < dot_list.size(); k++) {\n                    Point p2 = dot_list[i];\n                    Point p3 = dot_list[j];\n                    Point p4 = dot_list[k];\n                    \n                    // Try to find p1 for axis-aligned rectangle\n                    // Check if p2, p3, p4 can form three corners of a rectangle\n                    set<int> xs, ys;\n                    xs.insert(p2.x); xs.insert(p3.x); xs.insert(p4.x);\n                    ys.insert(p2.y); ys.insert(p3.y); ys.insert(p4.y);\n                    \n                    if (xs.size() == 2 && ys.size() == 2) {\n                        // Find the missing corner\n                        int x1 = *xs.begin(), x2 = *xs.rbegin();\n                        int y1 = *ys.begin(), y2 = *ys.rbegin();\n                        \n                        vector<Point> missing_corners;\n                        missing_corners.push_back(Point(x1, y1));\n                        missing_corners.push_back(Point(x1, y2));\n                        missing_corners.push_back(Point(x2, y1));\n                        missing_corners.push_back(Point(x2, y2));\n                        \n                        for (const Point& candidate : missing_corners) {\n                            if (!is_valid_point(candidate.x, candidate.y)) continue;\n                            if (has_dot(candidate)) continue;\n                            \n                            // Check if this point completes the rectangle with the three existing dots\n                            vector<Point> corners = {candidate, p2, p3, p4};\n                            set<Point> corner_set(corners.begin(), corners.end());\n                            if (corner_set.size() != 4) continue;\n                            \n                            if (is_axis_aligned(corners[0], corners[1], corners[2], corners[3])) {\n                                // Reorder points clockwise with new dot first\n                                vector<Point> ordered = order_points_clockwise(corners);\n                                // Find new dot position and make it first\n                                auto it = find(ordered.begin(), ordered.end(), candidate);\n                                if (it != ordered.end()) {\n                                    rotate(ordered.begin(), it, ordered.end());\n                                    candidates.push_back(ordered);\n                                }\n                            }\n                        }\n                    }\n                    \n                    // Try simple 45-degree rectangles (diamonds)\n                    // This is more complex, so we'll focus on axis-aligned for now\n                }\n            }\n        }\n        \n        return candidates;\n    }\n    \npublic:\n    RectJoinSolver(int N, int M, const vector<Point>& initial_dots) : N(N), M(M) {\n        center = Point((N-1)/2, (N-1)/2);\n        for (const Point& p : initial_dots) {\n            dots.insert(p);\n        }\n    }\n    \n    void solve() {\n        auto start_time = chrono::steady_clock::now();\n        \n        while (true) {\n            auto current_time = chrono::steady_clock::now();\n            auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time);\n            if (elapsed.count() > 4500) break;\n            \n            auto candidates = generate_simple_candidates();\n            if (candidates.empty()) break;\n            \n            vector<Point> best_candidate;\n            int best_weight = -1;\n            \n            for (const auto& candidate : candidates) {\n                if (candidate.size() != 4) continue;\n                \n                Point new_dot = candidate[0];\n                vector<Point> corners = candidate;\n                \n                if (check_no_other_dots(corners, new_dot) && \n                    check_no_overlapping_segments(corners)) {\n                    \n                    int weight = (new_dot.x - center.x)*(new_dot.x - center.x) + \n                                (new_dot.y - center.y)*(new_dot.y - center.y);\n                    \n                    if (weight > best_weight) {\n                        best_weight = weight;\n                        best_candidate = candidate;\n                    }\n                }\n            }\n            \n            if (best_weight == -1) break;\n            \n            operations.push_back(best_candidate);\n            dots.insert(best_candidate[0]);\n            mark_segments_used(best_candidate);\n        }\n    }\n    \n    void output() {\n        cout << operations.size() << endl;\n        for (const auto& op : operations) {\n            cout << op[0].x << \" \" << op[0].y << \" \"\n                 << op[1].x << \" \" << op[1].y << \" \"\n                 << op[2].x << \" \" << op[2].y << \" \"\n                 << op[3].x << \" \" << op[3].y << endl;\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    cin >> N >> M;\n    \n    vector<Point> initial_dots(M);\n    for (int i = 0; i < M; i++) {\n        cin >> initial_dots[i].x >> initial_dots[i].y;\n    }\n    \n    RectJoinSolver solver(N, M, initial_dots);\n    solver.solve();\n    solver.output();\n    \n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n#include <cstring>\nusing namespace std;\n\nconst int N = 10;\nvector<vector<int>> tilt_grid(const vector<vector<int>>& state, char direction) {\n    vector<vector<int>> new_state(N+1, vector<int>(N+1, 0));\n    if (direction == 'L') {\n        for (int i = 1; i <= N; i++) {\n            vector<int> non_empty;\n            for (int j = 1; j <= N; j++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int j = 1; j <= k; j++) {\n                new_state[i][j] = non_empty[j-1];\n            }\n            for (int j = k+1; j <= N; j++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'R') {\n        for (int i = 1; i <= N; i++) {\n            vector<int> non_empty;\n            for (int j = 1; j <= N; j++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int j = 1; j <= k; j++) {\n                new_state[i][N - k + j] = non_empty[j-1];\n            }\n            for (int j = 1; j <= N-k; j++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'F') {\n        for (int j = 1; j <= N; j++) {\n            vector<int> non_empty;\n            for (int i = 1; i <= N; i++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int i = 1; i <= k; i++) {\n                new_state[i][j] = non_empty[i-1];\n            }\n            for (int i = k+1; i <= N; i++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'B') {\n        for (int j = 1; j <= N; j++) {\n            vector<int> non_empty;\n            for (int i = 1; i <= N; i++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int i = 1; i <= k; i++) {\n                new_state[N - k + i][j] = non_empty[i-1];\n            }\n            for (int i = 1; i <= N-k; i++) {\n                new_state[i][j] = 0;\n            }\n        }\n    }\n    return new_state;\n}\n\nint compute_score(const vector<vector<int>>& grid, vector<vector<bool>>& visited) {\n    int score = 0;\n    for (int i = 1; i <= N; i++) {\n        for (int j = 1; j <= N; j++) {\n            visited[i][j] = false;\n        }\n    }\n    for (int i = 1; i <= N; i++) {\n        for (int j = 1; j <= N; j++) {\n            if (!visited[i][j] && grid[i][j] != 0) {\n                int flavor = grid[i][j];\n                int size = 0;\n                queue<pair<int, int>> q;\n                q.push({i, j});\n                visited[i][j] = true;\n                while (!q.empty()) {\n                    pair<int, int> pos = q.front();\n                    q.pop();\n                    int x = pos.first, y = pos.second;\n                    size++;\n                    int dx[] = {1, -1, 0, 0};\n                    int dy[] = {0, 0, 1, -1};\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d], ny = y + dy[d];\n                        if (nx >= 1 && nx <= N && ny >= 1 && ny <= N && !visited[nx][ny] && grid[nx][ny] == flavor) {\n                            visited[nx][ny] = true;\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n                score += size * size;\n            }\n        }\n    }\n    return score;\n}\n\nint main() {\n    int f[101];\n    for (int i = 1; i <= 100; i++) {\n        cin >> f[i];\n    }\n\n    vector<vector<int>> grid(N+1, vector<int>(N+1, 0));\n    vector<vector<bool>> visited(N+1, vector<bool>(N+1, false));\n    vector<char> directions = {'F', 'B', 'L', 'R'};\n\n    for (int t = 1; t <= 100; t++) {\n        int p;\n        cin >> p;\n\n        int count = 0;\n        int i_place = 0, j_place = 0;\n        for (int i = 1; i <= N; i++) {\n            for (int j = 1; j <= N; j++) {\n                if (grid[i][j] == 0) {\n                    count++;\n                    if (count == p) {\n                        i_place = i;\n                        j_place = j;\n                        break;\n                    }\n                }\n            }\n            if (j_place != 0) break;\n        }\n\n        grid[i_place][j_place] = f[t];\n\n        if (t == 100) {\n            // For the last candy, use greedy since no next candy\n            int best_score = -1;\n            char best_dir = 'F';\n            for (char dir : directions) {\n                vector<vector<int>> new_grid = tilt_grid(grid, dir);\n                int score = compute_score(new_grid, visited);\n                if (score > best_score) {\n                    best_score = score;\n                    best_dir = dir;\n                }\n            }\n            cout << best_dir << endl;\n            cout.flush();\n            grid = tilt_grid(grid, best_dir);\n            continue;\n        }\n\n        int best_avg_score = -1;\n        char best_dir = 'F';\n        for (char dir : directions) {\n            vector<vector<int>> grid_after_tilt = tilt_grid(grid, dir);\n            int empty_count = 0;\n            double total_score = 0.0;\n\n            for (int i = 1; i <= N; i++) {\n                for (int j = 1; j <= N; j++) {\n                    if (grid_after_tilt[i][j] == 0) {\n                        empty_count++;\n                        vector<vector<int>> grid_with_next = grid_after_tilt;\n                        grid_with_next[i][j] = f[t+1];\n                        int best_next_score = -1;\n                        for (char dir2 : directions) {\n                            vector<vector<int>> grid_after_tilt2 = tilt_grid(grid_with_next, dir2);\n                            int score = compute_score(grid_after_tilt2, visited);\n                            if (score > best_next_score) {\n                                best_next_score = score;\n                            }\n                        }\n                        total_score += best_next_score;\n                    }\n                }\n            }\n\n            double avg_score = total_score / empty_count;\n            if (avg_score > best_avg_score) {\n                best_avg_score = avg_score;\n                best_dir = dir;\n            }\n        }\n\n        cout << best_dir << endl;\n        cout.flush();\n        grid = tilt_grid(grid, best_dir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <cstdlib>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\nusing namespace std;\n\nint main() {\n    int M;\n    double eps;\n    cin >> M >> eps;\n\n    double requiredN = sqrt(2.0 * M) + 10.0 * eps;\n    int N = min(100, max(4, (int)ceil(requiredN)));\n    int T = N * (N - 1) / 2;\n\n    vector<int> offset(N);\n    offset[0] = 0;\n    for (int i = 1; i < N; i++) {\n        offset[i] = offset[i-1] + (N - i);\n    }\n\n    cout << N << endl;\n\n    int D = min(M, T + 1);\n    vector<int> m_values(D);\n    if (D > 1) {\n        for (int i = 0; i < D; i++) {\n            m_values[i] = round((i * T) / (D - 1.0));\n        }\n    } else {\n        m_values[0] = 0;\n    }\n\n    vector<int> m_list(M);\n    int quotient = M / D;\n    int remainder = M % D;\n    int index = 0;\n    for (int j = 0; j < D; j++) {\n        int count = quotient + (j < remainder ? 1 : 0);\n        for (int c = 0; c < count; c++) {\n            m_list[index++] = m_values[j];\n        }\n    }\n\n    vector<vector<double>> eigenvals(M);\n    for (int k = 0; k < M; k++) {\n        int m_k = m_list[k];\n        vector<bool> edge_flag(T, false);\n        vector<int> indices(T);\n        for (int i = 0; i < T; i++) {\n            indices[i] = i;\n        }\n        for (int i = T - 1; i > 0; i--) {\n            int j = rand() % (i + 1);\n            swap(indices[i], indices[j]);\n        }\n        for (int i = 0; i < m_k; i++) {\n            edge_flag[indices[i]] = true;\n        }\n\n        Eigen::MatrixXd A = Eigen::MatrixXd::Zero(N, N);\n        for (int pos = 0; pos < T; pos++) {\n            if (edge_flag[pos]) {\n                int i = 0;\n                while (i < N - 1 && pos >= offset[i + 1]) {\n                    i++;\n                }\n                int j = i + 1 + (pos - offset[i]);\n                A(i, j) = 1;\n                A(j, i) = 1;\n            }\n        }\n\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(A);\n        Eigen::VectorXd evals = solver.eigenvalues();\n        vector<double> eval_vec(evals.data(), evals.data() + evals.size());\n        sort(eval_vec.begin(), eval_vec.end());\n        eigenvals[k] = eval_vec;\n\n        string g_str;\n        for (int pos = 0; pos < T; pos++) {\n            g_str += edge_flag[pos] ? '1' : '0';\n        }\n        cout << g_str << endl;\n    }\n\n    for (int q = 0; q < 100; q++) {\n        string H_str;\n        cin >> H_str;\n\n        Eigen::MatrixXd H_mat = Eigen::MatrixXd::Zero(N, N);\n        for (int pos = 0; pos < T; pos++) {\n            if (H_str[pos] == '1') {\n                int i = 0;\n                while (i < N - 1 && pos >= offset[i + 1]) {\n                    i++;\n                }\n                int j = i + 1 + (pos - offset[i]);\n                H_mat(i, j) = 1;\n                H_mat(j, i) = 1;\n            }\n        }\n\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver_H(H_mat);\n        Eigen::VectorXd evals_H = solver_H.eigenvalues();\n        vector<double> eval_vec_H(evals_H.data(), evals_H.data() + evals_H.size());\n        sort(eval_vec_H.begin(), eval_vec_H.end());\n\n        int best_k = 0;\n        double min_dist = 1e9;\n        for (int k = 0; k < M; k++) {\n            double dist = 0.0;\n            for (int i = 0; i < N; i++) {\n                double diff = eval_vec_H[i] - eigenvals[k][i];\n                dist += diff * diff;\n            }\n            dist = sqrt(dist);\n            if (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 <algorithm>\n#include <queue>\n#include <limits>\n#include <tuple>\n\nusing namespace std;\n\nconst int INF = 1000000000;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    vector<tuple<int, int, int>> edges;\n    for (int i = 0; i < M; i++) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges.push_back({u, v, w});\n    }\n\n    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n        // Coordinates are read but not used in this solution\n    }\n\n    vector<vector<pair<int, int>>> graph(N + 1);\n    vector<vector<int>> edge_index(N + 1, vector<int>(N + 1, -1));\n\n    for (int i = 0; i < M; i++) {\n        int u = get<0>(edges[i]);\n        int v = get<1>(edges[i]);\n        int w = get<2>(edges[i]);\n        graph[u].emplace_back(v, w);\n        graph[v].emplace_back(u, w);\n        edge_index[u][v] = i;\n        edge_index[v][u] = i;\n    }\n\n    vector<double> betweenness(M, 0.0);\n\n    for (int s = 1; s <= N; s++) {\n        vector<int> dist(N + 1, INF);\n        dist[s] = 0;\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n        pq.push({0, s});\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            for (auto [v, w] : graph[u]) {\n                int new_d = d + w;\n                if (new_d < dist[v]) {\n                    dist[v] = new_d;\n                    pq.push({new_d, v});\n                }\n            }\n        }\n\n        vector<double> sigma(N + 1, 0.0);\n        sigma[s] = 1.0;\n\n        vector<int> vertices(N);\n        for (int i = 0; i < N; i++) {\n            vertices[i] = i + 1;\n        }\n        sort(vertices.begin(), vertices.end(), [&](int a, int b) {\n            return dist[a] < dist[b];\n        });\n\n        for (int v : vertices) {\n            if (v == s) continue;\n            for (auto [u, w] : graph[v]) {\n                if (dist[u] + w == dist[v]) {\n                    sigma[v] += sigma[u];\n                }\n            }\n        }\n\n        vector<double> delta(N + 1, 0.0);\n        sort(vertices.begin(), vertices.end(), [&](int a, int b) {\n            return dist[a] > dist[b];\n        });\n\n        for (int v : vertices) {\n            if (v == s) continue;\n            for (auto [u, w] : graph[v]) {\n                if (dist[u] + w == dist[v]) {\n                    double c = sigma[u] / sigma[v] * (1.0 + delta[v]);\n                    int idx = edge_index[u][v];\n                    if (idx != -1) {\n                        betweenness[idx] += c;\n                    }\n                    delta[u] += c;\n                }\n            }\n        }\n    }\n\n    vector<int> edge_indices(M);\n    for (int i = 0; i < M; i++) {\n        edge_indices[i] = i;\n    }\n    sort(edge_indices.begin(), edge_indices.end(), [&](int a, int b) {\n        return betweenness[a] > betweenness[b];\n    });\n\n    vector<int> assignment(M);\n    for (int i = 0; i < M; i++) {\n        assignment[edge_indices[i]] = (i % D) + 1;\n    }\n\n    for (int i = 0; i < M; i++) {\n        cout << assignment[i];\n        if (i < M - 1) {\n            cout << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <queue>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\nint main() {\n    int D;\n    cin >> D;\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 required positions for each silhouette\n    set<tuple<int, int, int>> M1, M2;\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 (f1[z][x] == '1' && r1[z][y] == '1') {\n                    M1.insert({x, y, z});\n                }\n                if (f2[z][x] == '1' && r2[z][y] == '1') {\n                    M2.insert({x, y, z});\n                }\n            }\n        }\n    }\n\n    // Find intersection of required positions\n    set<tuple<int, int, int>> I;\n    set_intersection(M1.begin(), M1.end(), M2.begin(), M2.end(),\n                    inserter(I, I.begin()));\n\n    // 6-directional neighbors\n    vector<tuple<int, int, int>> directions = {\n        {1, 0, 0}, {-1, 0, 0},\n        {0, 1, 0}, {0, -1, 0},\n        {0, 0, 1}, {0, 0, -1}\n    };\n\n    // Find connected components in intersection\n    map<tuple<int, int, int>, int> comp_id;\n    int comp_count = 0;\n    \n    for (const auto& coord : I) {\n        if (comp_id.count(coord)) continue;\n        \n        comp_count++;\n        queue<tuple<int, int, int>> q;\n        q.push(coord);\n        comp_id[coord] = comp_count;\n        \n        while (!q.empty()) {\n            auto [x, y, z] = q.front();\n            q.pop();\n            \n            for (auto [dx, dy, dz] : directions) {\n                int nx = x + dx, ny = y + dy, nz = z + dz;\n                tuple<int, int, int> neighbor = {nx, ny, nz};\n                \n                if (I.count(neighbor) && !comp_id.count(neighbor)) {\n                    comp_id[neighbor] = comp_count;\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n\n    // Calculate total blocks\n    int n = comp_count + (M1.size() - I.size()) + (M2.size() - I.size());\n    \n    // Create output arrays\n    vector<int> arr1(D * D * D, 0), arr2(D * D * D, 0);\n    \n    // Assign blocks for first arrangement\n    int id_counter = comp_count + 1;\n    map<tuple<int, int, int>, int> id_map1;\n    \n    for (const auto& coord : M1) {\n        auto [x, y, z] = coord;\n        int idx = x * D * D + y * D + z;\n        \n        if (I.count(coord)) {\n            arr1[idx] = comp_id[coord];\n        } else {\n            if (!id_map1.count(coord)) {\n                id_map1[coord] = id_counter++;\n            }\n            arr1[idx] = id_map1[coord];\n        }\n    }\n    \n    // Assign blocks for second arrangement\n    map<tuple<int, int, int>, int> id_map2;\n    \n    for (const auto& coord : M2) {\n        auto [x, y, z] = coord;\n        int idx = x * D * D + y * D + z;\n        \n        if (I.count(coord)) {\n            arr2[idx] = comp_id[coord];\n        } else {\n            if (!id_map2.count(coord)) {\n                id_map2[coord] = id_counter++;\n            }\n            arr2[idx] = id_map2[coord];\n        }\n    }\n    \n    // Output results\n    cout << n << endl;\n    \n    for (int i = 0; i < D * D * D; i++) {\n        cout << arr1[i] << (i == D * D * D - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    for (int i = 0; i < D * D * D; i++) {\n        cout << arr2[i] << (i == D * D * D - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read input\n    int N, M, K;\n    cin >> N >> M >> K;\n    \n    vector<ll> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<tuple<int, int, ll>> edges(M);\n    map<pair<int, int>, int> edge_index_map;\n    for (int i = 0; i < M; i++) {\n        int u, v;\n        ll w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edges[i] = {u, v, w};\n        if (u > v) swap(u, v);\n        edge_index_map[{u, v}] = i;\n    }\n    \n    vector<ll> a(K), b(K);\n    for (int i = 0; i < K; i++) {\n        cin >> a[i] >> b[i];\n    }\n    \n    // Precompute squared distances from stations to residents\n    vector<vector<ll>> dist_sq(N, vector<ll>(K));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < K; j++) {\n            ll dx = x[i] - a[j];\n            ll dy = y[i] - b[j];\n            dist_sq[i][j] = dx * dx + dy * dy;\n        }\n    }\n    \n    // Precompute shortest paths between stations using Floyd-Warshall\n    vector<vector<ll>> dist_station(N, vector<ll>(N, 1e18));\n    vector<vector<int>> next_hop(N, vector<int>(N, -1));\n    for (int i = 0; i < N; i++) {\n        dist_station[i][i] = 0;\n        next_hop[i][i] = i;\n    }\n    for (int i = 0; i < M; i++) {\n        auto [u, v, w] = edges[i];\n        if (w < dist_station[u][v]) {\n            dist_station[u][v] = w;\n            dist_station[v][u] = w;\n            next_hop[u][v] = v;\n            next_hop[v][u] = u;\n        }\n    }\n    for (int k = 0; k < N; k++) {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (dist_station[i][k] < 1e18 && dist_station[k][j] < 1e18) {\n                    if (dist_station[i][j] > dist_station[i][k] + dist_station[k][j]) {\n                        dist_station[i][j] = dist_station[i][k] + dist_station[k][j];\n                        next_hop[i][j] = next_hop[i][k];\n                    }\n                }\n            }\n        }\n    }\n    \n    // Initial assignment: assign each resident to the nearest station\n    vector<int> assignment(K);\n    vector<multiset<ll>> station_residents(N);\n    for (int j = 0; j < K; j++) {\n        int best_station = 0;\n        ll min_d_sq = dist_sq[0][j];\n        for (int i = 1; i < N; i++) {\n            if (dist_sq[i][j] < min_d_sq) {\n                min_d_sq = dist_sq[i][j];\n                best_station = i;\n            }\n        }\n        assignment[j] = best_station;\n        station_residents[best_station].insert(dist_sq[best_station][j]);\n    }\n    \n    // Function to compute P_i from a multiset of squared distances\n    auto compute_P = [](const multiset<ll>& residents) -> ll {\n        if (residents.empty()) return 0;\n        ll max_d_sq = *residents.rbegin();\n        ll P = sqrt(max_d_sq);\n        if (P * P < max_d_sq) P++;\n        return min(P, 5000LL);\n    };\n    \n    // Function to build MST on a set of stations\n    auto build_mst = [&](const set<int>& S) -> tuple<ll, set<pair<int, int>>> {\n        if (S.empty()) return {0, {}};\n        // Create a list of stations in S\n        vector<int> stations(S.begin(), S.end());\n        int n_s = stations.size();\n        // Map station index to index in the list\n        map<int, int> station_index;\n        for (int i = 0; i < n_s; i++) {\n            station_index[stations[i]] = i;\n        }\n        // Build complete graph on stations\n        vector<vector<ll>> dist_s(n_s, vector<ll>(n_s, 1e18));\n        for (int i = 0; i < n_s; i++) {\n            for (int j = i+1; j < n_s; j++) {\n                int u = stations[i], v = stations[j];\n                dist_s[i][j] = dist_station[u][v];\n                dist_s[j][i] = dist_station[u][v];\n            }\n        }\n        // Prim's algorithm\n        vector<ll> key(n_s, 1e18);\n        vector<int> parent(n_s, -1);\n        vector<bool> in_mst(n_s, false);\n        key[0] = 0;\n        priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n        pq.push({0, 0});\n        while (!pq.empty()) {\n            int u = pq.top().second;\n            pq.pop();\n            if (in_mst[u]) continue;\n            in_mst[u] = true;\n            for (int v = 0; v < n_s; v++) {\n                if (!in_mst[v] && dist_s[u][v] < key[v]) {\n                    key[v] = dist_s[u][v];\n                    parent[v] = u;\n                    pq.push({key[v], v});\n                }\n            }\n        }\n        // Collect MST edges\n        set<pair<int, int>> mst_edges;\n        ll total_cost = 0;\n        for (int i = 1; i < n_s; i++) {\n            int u = stations[i], v = stations[parent[i]];\n            if (u > v) swap(u, v);\n            mst_edges.insert({u, v});\n            total_cost += dist_station[u][v];\n        }\n        return {total_cost, mst_edges};\n    };\n    \n    // Function to get the path between two stations and mark edges\n    auto mark_path_edges = [&](int u, int v, vector<bool>& edge_on) {\n        if (u == v) return;\n        int current = u;\n        while (current != v) {\n            int next = next_hop[current][v];\n            int u1 = current, v1 = next;\n            if (u1 > v1) swap(u1, v1);\n            auto it = edge_index_map.find({u1, v1});\n            if (it != edge_index_map.end()) {\n                edge_on[it->second] = true;\n            }\n            current = next;\n        }\n    };\n    \n    // Initial set S: stations with at least one resident\n    set<int> S;\n    for (int i = 0; i < N; i++) {\n        if (!station_residents[i].empty()) {\n            S.insert(i);\n        }\n    }\n    \n    // Build initial MST\n    auto [current_edge_cost, mst_edges] = build_mst(S);\n    \n    // Compute initial power cost\n    ll current_power_cost = 0;\n    vector<ll> P(N, 0);\n    for (int i = 0; i < N; i++) {\n        P[i] = compute_P(station_residents[i]);\n        current_power_cost += P[i] * P[i];\n    }\n    ll current_total_cost = current_power_cost + current_edge_cost;\n    \n    // Local search improvement\n    bool improved = true;\n    int max_iter = 10;\n    for (int iter = 0; iter < max_iter && improved; iter++) {\n        improved = false;\n        // Create a list of residents in random order\n        vector<int> residents(K);\n        iota(residents.begin(), residents.end(), 0);\n        random_shuffle(residents.begin(), residents.end());\n        \n        for (int j : residents) {\n            int old_station = assignment[j];\n            ll old_d_sq = dist_sq[old_station][j];\n            // Remove j from old_station\n            station_residents[old_station].erase(station_residents[old_station].find(old_d_sq));\n            ll old_P_old = P[old_station];\n            P[old_station] = compute_P(station_residents[old_station]);\n            ll power_cost_without_j = current_power_cost - old_P_old * old_P_old + P[old_station] * P[old_station];\n            \n            // Try reassigning to other stations in S\n            for (int new_station : S) {\n                if (new_station == old_station) continue;\n                ll new_d_sq = dist_sq[new_station][j];\n                ll old_P_new = P[new_station];\n                station_residents[new_station].insert(new_d_sq);\n                P[new_station] = compute_P(station_residents[new_station]);\n                ll new_power_cost = power_cost_without_j - old_P_new * old_P_new + P[new_station] * P[new_station];\n                \n                // Check if power cost improves\n                if (new_power_cost < current_power_cost) {\n                    // Accept reassignment\n                    assignment[j] = new_station;\n                    current_power_cost = new_power_cost;\n                    improved = true;\n                    // Update S if old_station becomes empty\n                    if (station_residents[old_station].empty()) {\n                        S.erase(old_station);\n                    }\n                    // new_station is already in S\n                    break;\n                } else {\n                    // Revert changes to new_station\n                    station_residents[new_station].erase(station_residents[new_station].find(new_d_sq));\n                    P[new_station] = old_P_new;\n                }\n            }\n            // If not reassigned, revert old_station\n            if (assignment[j] == old_station) {\n                station_residents[old_station].insert(old_d_sq);\n                P[old_station] = old_P_old;\n            }\n        }\n        \n        // After reassignment, update S and rebuild MST\n        S.clear();\n        for (int i = 0; i < N; i++) {\n            if (!station_residents[i].empty()) {\n                S.insert(i);\n            }\n        }\n        tie(current_edge_cost, mst_edges) = build_mst(S);\n        current_total_cost = current_power_cost + current_edge_cost;\n    }\n    \n    // Final output preparation\n    // Compute final P values\n    for (int i = 0; i < N; i++) {\n        P[i] = compute_P(station_residents[i]);\n    }\n    \n    // Mark edges for MST\n    vector<bool> edge_on(M, false);\n    for (auto [u, v] : mst_edges) {\n        mark_path_edges(u, v, edge_on);\n    }\n    \n    // Output P and B\n    for (int i = 0; i < N; i++) {\n        cout << P[i];\n        if (i < N-1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    for (int i = 0; i < M; i++) {\n        cout << (edge_on[i] ? 1 : 0);\n        if (i < M-1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <tuple>\n#include <algorithm>\nusing namespace std;\n\nconst int N = 30;\n\nint main() {\n    vector<vector<int>> pyramid(N);\n    for (int x = 0; x < N; x++) {\n        for (int y = 0; y <= x; y++) {\n            int num;\n            cin >> num;\n            pyramid[x].push_back(num);\n        }\n    }\n\n    vector<tuple<int, int, int, int>> swaps;\n\n    for (int x = N-2; x >= 0; x--) {\n        vector<pair<int, int>> nodes; // (value, y)\n        for (int y = 0; y <= x; y++) {\n            nodes.push_back({pyramid[x][y], y});\n        }\n        sort(nodes.begin(), nodes.end(), [](const pair<int, int> &a, const pair<int, int> &b) {\n            return a.first > b.first; // Sort by value descending\n        });\n\n        for (auto &node : nodes) {\n            int y = node.second;\n            int current_x = x;\n            int current_y = y;\n            while (current_x < N-1) {\n                int child1_x = current_x + 1;\n                int child1_y = current_y;\n                int child2_x = current_x + 1;\n                int child2_y = current_y + 1;\n\n                int current_val = pyramid[current_x][current_y];\n                int child1_val = pyramid[child1_x][child1_y];\n                int child2_val = pyramid[child2_x][child2_y];\n\n                if (current_val <= child1_val && current_val <= child2_val) {\n                    break;\n                }\n\n                int swap_x, swap_y;\n                if (child1_val <= child2_val) {\n                    swap_x = child1_x;\n                    swap_y = child1_y;\n                } else {\n                    swap_x = child2_x;\n                    swap_y = child2_y;\n                }\n\n                swap(pyramid[current_x][current_y], pyramid[swap_x][swap_y]);\n                swaps.push_back({current_x, current_y, swap_x, swap_y});\n\n                current_x = swap_x;\n                current_y = swap_y;\n            }\n        }\n    }\n\n    cout << swaps.size() << endl;\n    for (const auto& swap : swaps) {\n        cout << get<0>(swap) << \" \" << get<1>(swap) << \" \" << get<2>(swap) << \" \" << get<3>(swap) << endl;\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = 4;\n\nvector<vector<int>> grid;\nvector<pair<int, int>> container_positions;\n\n// Directions: up, down, left, right\nconst int di[] = {-1, 1, 0, 0};\nconst int dj[] = {0, 0, -1, 1};\n\n// Check if a position is valid and empty\nbool is_valid(int i, int j) {\n    return i >= 0 && i < D && j >= 0 && j < D && grid[i][j] == -1;\n}\n\n// BFS to find reachable positions from entrance\nvector<pair<int, int>> get_reachable_positions() {\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> reachable;\n    \n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            \n            if (ni >= 0 && ni < D && nj >= 0 && nj < D && \n                !visited[ni][nj] && grid[ni][nj] == -1) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                reachable.push_back({ni, nj});\n            }\n        }\n    }\n    \n    return reachable;\n}\n\n// Calculate Manhattan distance from entrance\nint distance_from_entrance(int i, int j) {\n    return abs(i - ENTRANCE_I) + abs(j - ENTRANCE_J);\n}\n\n// Find best position for placement based on container number\npair<int, int> find_best_position(int container_num, int total_containers) {\n    auto reachable = get_reachable_positions();\n    \n    if (reachable.empty()) {\n        // Should not happen if grid is properly connected\n        for (int i = 0; i < D; i++) {\n            for (int j = 0; j < D; j++) {\n                if (grid[i][j] == -1) {\n                    return {i, j};\n                }\n            }\n        }\n    }\n    \n    // Sort positions by distance from entrance\n    sort(reachable.begin(), reachable.end(), [](const pair<int, int>& a, const pair<int, int>& b) {\n        int dist_a = distance_from_entrance(a.first, a.second);\n        int dist_b = distance_from_entrance(b.first, b.second);\n        return dist_a < dist_b;\n    });\n    \n    // Use container number to determine placement strategy\n    // Lower numbers should be placed closer to exit for easier retrieval\n    int idx = (container_num * reachable.size()) / total_containers;\n    idx = min(idx, (int)reachable.size() - 1);\n    \n    return reachable[idx];\n}\n\n// Get accessible containers for retrieval\nvector<pair<int, int>> get_accessible_containers() {\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> accessible;\n    \n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        // Check if current position has a container\n        if (grid[i][j] >= 0) {\n            accessible.push_back({i, j});\n        }\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            \n            if (ni >= 0 && ni < D && nj >= 0 && nj < D && \n                !visited[ni][nj] && grid[ni][nj] != -2) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    return accessible;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read warehouse configuration\n    int N;\n    cin >> D >> N;\n    \n    // Initialize grid: -2 = obstacle, -1 = empty, >=0 = container number\n    grid.assign(D, vector<int>(D, -1));\n    container_positions.clear();\n    \n    // Mark entrance and adjacent squares\n    grid[ENTRANCE_I][ENTRANCE_J] = -3; // Entrance\n    grid[ENTRANCE_I][ENTRANCE_J-1] = -1;\n    grid[ENTRANCE_I][ENTRANCE_J+1] = -1;\n    grid[ENTRANCE_I+1][ENTRANCE_J] = -1;\n    \n    // Read obstacles\n    for (int k = 0; k < N; k++) {\n        int ri, rj;\n        cin >> ri >> rj;\n        grid[ri][rj] = -2; // Obstacle\n    }\n    \n    int total_containers = D * D - 1 - N;\n    \n    // Process container arrivals\n    for (int d = 0; d < total_containers; d++) {\n        int container_num;\n        cin >> container_num;\n        \n        // Find best position for this container\n        auto [pi, pj] = find_best_position(container_num, total_containers);\n        \n        // Place container\n        grid[pi][pj] = container_num;\n        container_positions.push_back({pi, pj});\n        \n        // Output placement\n        cout << pi << \" \" << pj << endl;\n        cout.flush();\n    }\n    \n    // Determine retrieval order using greedy strategy\n    vector<pair<int, int>> retrieval_order;\n    \n    while (retrieval_order.size() < total_containers) {\n        auto accessible = get_accessible_containers();\n        \n        if (accessible.empty()) {\n            break; // Should not happen\n        }\n        \n        // Find container with smallest number\n        int best_idx = 0;\n        int best_num = grid[accessible[0].first][accessible[0].second];\n        \n        for (int i = 1; i < accessible.size(); i++) {\n            int current_num = grid[accessible[i].first][accessible[i].second];\n            if (current_num < best_num) {\n                best_num = current_num;\n                best_idx = i;\n            }\n        }\n        \n        auto [qi, qj] = accessible[best_idx];\n        retrieval_order.push_back({qi, qj});\n        grid[qi][qj] = -1; // Remove container\n    }\n    \n    // Output retrieval order\n    for (auto [qi, qj] : retrieval_order) {\n        cout << qi << \" \" << qj << endl;\n    }\n    cout.flush();\n    \n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> grid(n, vector<int>(n));\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> grid[i][j];\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cout << grid[i][j];\n            if (j < n - 1) cout << \" \";\n        }\n        cout << endl;\n    }\n    \n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n\n    vector<double> ratings(N, 1000.0);\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n\n    int p = 0;\n\n    for (int q = 0; q < Q; q++) {\n        sort(indices.begin(), indices.end(), [&ratings](int a, int b) {\n            return ratings[a] > ratings[b];\n        });\n\n        int i = indices[p];\n        int j = indices[p + 1];\n\n        cout << \"1 1 \" << i << \" \" << j << endl;\n        cout.flush();\n\n        string result;\n        cin >> result;\n\n        double outcome_i, outcome_j;\n        if (result == \">\") {\n            outcome_i = 1.0;\n            outcome_j = 0.0;\n        } else if (result == \"<\") {\n            outcome_i = 0.0;\n            outcome_j = 1.0;\n        } else {\n            outcome_i = 0.5;\n            outcome_j = 0.5;\n        }\n\n        const double K = 32.0;\n        double diff = ratings[j] - ratings[i];\n        double expected_i = 1.0 / (1.0 + pow(10.0, diff / 400.0));\n        double expected_j = 1.0 - expected_i;\n\n        ratings[i] += K * (outcome_i - expected_i);\n        ratings[j] += K * (outcome_j - expected_j);\n\n        p++;\n        if (p >= N - 1) {\n            p = 0;\n        }\n    }\n\n    vector<int> sorted_indices(N);\n    iota(sorted_indices.begin(), sorted_indices.end(), 0);\n    sort(sorted_indices.begin(), sorted_indices.end(), [&ratings](int a, int b) {\n        return ratings[a] > ratings[b];\n    });\n\n    vector<double> bin_sums(D, 0.0);\n    vector<int> assignment(N);\n    for (int idx : sorted_indices) {\n        int min_bin = 0;\n        for (int b = 1; b < D; b++) {\n            if (bin_sums[b] < bin_sums[min_bin]) {\n                min_bin = b;\n            }\n        }\n        assignment[idx] = min_bin;\n        bin_sums[min_bin] += ratings[idx];\n    }\n\n    for (int i = 0; i < N; i++) {\n        cout << assignment[i];\n        if (i < N - 1) {\n            cout << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <queue>\n#include <functional>\n#include <set>\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    \n    vector<vector<int>> stacks(m + 1);\n    vector<int> box_pos(n + 1, -1);\n    vector<int> box_height(n + 1, -1);\n    \n    // Read initial configuration\n    for (int i = 1; i <= m; i++) {\n        for (int j = 0; j < n / m; j++) {\n            int box;\n            cin >> box;\n            stacks[i].push_back(box);\n            box_pos[box] = i;\n            box_height[box] = j + 1;\n        }\n    }\n    \n    vector<pair<int, int>> operations;\n    int next_box = 1;\n    vector<bool> carried_out(n + 1, false);\n    \n    int boxes_per_stack = n / m;\n    \n    // Function to check if a box is at top\n    auto is_top = [&](int box) {\n        int stack_idx = box_pos[box];\n        return !stacks[stack_idx].empty() && stacks[stack_idx].back() == box;\n    };\n    \n    // Function to find boxes above a given box\n    auto get_boxes_above = [&](int box) -> vector<int> {\n        int stack_idx = box_pos[box];\n        auto it = find(stacks[stack_idx].begin(), stacks[stack_idx].end(), box);\n        if (it == stacks[stack_idx].end()) return {};\n        return vector<int>(it + 1, stacks[stack_idx].end());\n    };\n    \n    // Function to find the cost of making a box accessible\n    auto accessibility_cost = [&](int box) {\n        if (is_top(box)) return 0;\n        vector<int> above = get_boxes_above(box);\n        return (int)above.size();\n    };\n    \n    // Function to find the best box to move to free next_box\n    auto find_best_box_to_move = [&]() -> pair<int, int> {\n        int current_stack = box_pos[next_box];\n        vector<int> boxes_above = get_boxes_above(next_box);\n        \n        if (boxes_above.empty()) {\n            return {-1, -1}; // Shouldn't happen\n        }\n        \n        // Try to find a box that when moved, will help future moves\n        int best_box = -1;\n        int best_dest = -1;\n        double best_score = -1e9;\n        \n        for (int box : boxes_above) {\n            // For each box above next_box, try different destinations\n            for (int dest = 1; dest <= m; dest++) {\n                if (dest == current_stack) continue;\n                \n                double score = 0.0;\n                \n                // Prefer moving boxes that are far from their ideal position\n                int ideal_stack = (box - 1) / boxes_per_stack + 1;\n                if (dest == ideal_stack) {\n                    score += 100.0;\n                }\n                \n                // Prefer destinations that are empty or have large boxes on top\n                if (stacks[dest].empty()) {\n                    score += 50.0;\n                } else {\n                    int top_box = stacks[dest].back();\n                    if (top_box > box) {\n                        score += 30.0;\n                    }\n                }\n                \n                // Penalize moving boxes that are close to being carried out\n                if (box - next_box < 10) {\n                    score -= (10 - (box - next_box)) * 5.0;\n                }\n                \n                // Prefer moves that minimize future blockage\n                bool will_block_small = false;\n                for (int b : stacks[dest]) {\n                    if (b < next_box && !carried_out[b]) {\n                        will_block_small = true;\n                        break;\n                    }\n                }\n                if (will_block_small) {\n                    score -= 100.0;\n                }\n                \n                // Consider the number of boxes that would need to be moved after this\n                vector<int> new_boxes_above;\n                for (int b : boxes_above) {\n                    if (b != box) new_boxes_above.push_back(b);\n                }\n                \n                // Estimate future cost reduction\n                if (new_boxes_above.size() < boxes_above.size()) {\n                    score += 20.0;\n                }\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_box = box;\n                    best_dest = dest;\n                }\n            }\n        }\n        \n        return {best_box, best_dest};\n    };\n    \n    // Function to find an empty stack\n    auto find_empty_stack = [&]() {\n        for (int i = 1; i <= m; i++) {\n            if (stacks[i].empty()) return i;\n        }\n        return -1;\n    };\n    \n    // Function to find a stack with large boxes on top\n    auto find_good_temporary_stack = [&]() {\n        int best_stack = -1;\n        int best_top = -1;\n        \n        for (int i = 1; i <= m; i++) {\n            if (!stacks[i].empty()) {\n                int top_box = stacks[i].back();\n                if (top_box > best_top) {\n                    best_top = top_box;\n                    best_stack = i;\n                }\n            }\n        }\n        \n        // If all stacks are empty, use stack 1\n        if (best_stack == -1) return 1;\n        return best_stack;\n    };\n    \n    // Main loop\n    while (next_box <= n) {\n        // Check if we can carry out next_box\n        if (is_top(next_box)) {\n            operations.push_back({next_box, 0});\n            carried_out[next_box] = true;\n            int stack_idx = box_pos[next_box];\n            stacks[stack_idx].pop_back();\n            next_box++;\n            continue;\n        }\n        \n        // If next_box is blocked, we need to move boxes\n        auto [box_to_move, best_dest] = find_best_box_to_move();\n        \n        if (box_to_move == -1) {\n            // Fallback: move the first box above next_box to an empty stack\n            int current_stack = box_pos[next_box];\n            vector<int> boxes_above = get_boxes_above(next_box);\n            if (boxes_above.empty()) {\n                next_box++;\n                continue;\n            }\n            \n            box_to_move = boxes_above[0];\n            best_dest = find_empty_stack();\n            if (best_dest == -1) {\n                best_dest = find_good_temporary_stack();\n                if (best_dest == current_stack) {\n                    best_dest = (current_stack % m) + 1; // Avoid same stack\n                }\n            }\n        }\n        \n        // Perform the move\n        operations.push_back({box_to_move, best_dest});\n        \n        // Update stack configuration\n        int current_stack = box_pos[box_to_move];\n        auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), box_to_move);\n        if (it != stacks[current_stack].end()) {\n            vector<int> moving_boxes(it, stacks[current_stack].end());\n            stacks[current_stack].erase(it, stacks[current_stack].end());\n            stacks[best_dest].insert(stacks[best_dest].end(), moving_boxes.begin(), moving_boxes.end());\n            \n            // Update positions\n            for (int i = 0; i < moving_boxes.size(); i++) {\n                box_pos[moving_boxes[i]] = best_dest;\n                box_height[moving_boxes[i]] = stacks[best_dest].size() - moving_boxes.size() + i + 1;\n            }\n        }\n        \n        // Safety check\n        if (operations.size() > 4800) {\n            // Emergency: try to carry out any available boxes\n            for (int i = next_box; i <= n; i++) {\n                if (!carried_out[i] && is_top(i)) {\n                    operations.push_back({i, 0});\n                    carried_out[i] = true;\n                    stacks[box_pos[i]].pop_back();\n                    if (i == next_box) next_box++;\n                }\n            }\n            if (next_box > n) break;\n        }\n    }\n    \n    // Output operations\n    for (auto op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n    \n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nvector<string> h, v;\nvector<vector<bool>> visited;\nint N;\nstring moves;\n\nconst int di[] = {0, 1, 0, -1};\nconst int dj[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\n\nvoid dfs(int i, int j) {\n    visited[i][j] = true;\n    for (int k = 0; k < 4; k++) {\n        int ni = i + di[k];\n        int nj = j + dj[k];\n        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n        if (visited[ni][nj]) continue;\n        if (di[k] == 0) {\n            int col = min(j, nj);\n            if (v[i][col] == '1') continue;\n        } else {\n            int row = min(i, ni);\n            if (h[row][j] == '1') continue;\n        }\n        moves += dir[k];\n        dfs(ni, nj);\n        moves += dir[(k + 2) % 4];\n    }\n}\n\nint main() {\n    cin >> N;\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; i++) {\n        cin >> h[i];\n    }\n    v.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\n    }\n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n        }\n    }\n\n    visited.resize(N, vector<bool>(N, false));\n    moves = \"\";\n    dfs(0, 0);\n    cout << moves << endl;\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <map>\n#include <limits>\n#include <cmath>\n#include <utility>\n\nusing namespace std;\n\nconst int INF = numeric_limits<int>::max();\n\nint dist(pair<int, int> a, pair<int, int> b) {\n    return abs(a.first - b.first) + abs(a.second - b.second);\n}\n\npair<int, pair<int, int>> cost_to_type(const string& str, const pair<int, int>& start, const map<char, vector<pair<int, int>>>& letter_points) {\n    int L = str.length();\n    if (L == 0) return {0, start};\n\n    vector<map<pair<int, int>, int>> dp(L);\n    vector<map<pair<int, int>, pair<int, int>>> prev(L);\n\n    char c0 = str[0];\n    if (letter_points.find(c0) == letter_points.end()) return {INF, {0,0}};\n    for (auto p : letter_points.at(c0)) {\n        int cost = dist(start, p) + 1;\n        dp[0][p] = cost;\n        prev[0][p] = start;\n    }\n\n    for (int i = 1; i < L; i++) {\n        char c = str[i];\n        if (letter_points.find(c) == letter_points.end()) return {INF, {0,0}};\n        for (auto p : letter_points.at(c)) {\n            int best_cost = INF;\n            pair<int, int> best_prev;\n            char prev_c = str[i-1];\n            if (letter_points.find(prev_c) == letter_points.end()) return {INF, {0,0}};\n            for (auto q : letter_points.at(prev_c)) {\n                if (dp[i-1].find(q) == dp[i-1].end()) continue;\n                int cost = dp[i-1][q] + dist(q, p) + 1;\n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_prev = q;\n                }\n            }\n            if (best_cost < INF) {\n                dp[i][p] = best_cost;\n                prev[i][p] = best_prev;\n            }\n        }\n    }\n\n    int min_cost = INF;\n    pair<int, int> end_pos = start;\n    char last_c = str[L-1];\n    if (letter_points.find(last_c) == letter_points.end()) return {INF, {0,0}};\n    for (auto p : letter_points.at(last_c)) {\n        if (dp[L-1].find(p) != dp[L-1].end() && dp[L-1][p] < min_cost) {\n            min_cost = dp[L-1][p];\n            end_pos = p;\n        }\n    }\n    if (min_cost == INF) return {INF, start};\n    return {min_cost, end_pos};\n}\n\nint compute_overlap(const string& S, const string& B) {\n    int max_possible = min(S.length(), B.length());\n    for (int l = max_possible; l > 0; l--) {\n        if (S.substr(S.length() - l) == B.substr(0, l)) {\n            return l;\n        }\n    }\n    return 0;\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int s_i, s_j;\n    cin >> s_i >> s_j;\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    vector<string> words(M);\n    for (int i = 0; i < M; i++) {\n        cin >> words[i];\n    }\n\n    map<char, vector<pair<int, int>>> letter_points;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            char c = grid[i][j];\n            letter_points[c].push_back({i, j});\n        }\n    }\n\n    pair<int, int> current_pos = {s_i, s_j};\n    vector<string> uncovered = words;\n    string S = \"\";\n\n    const int BEAM_WIDTH = 10;\n\n    while (!uncovered.empty()) {\n        if (uncovered.size() == 1) {\n            string B = uncovered[0];\n            int k1 = compute_overlap(S, B);\n            string suffix_B = B.substr(k1);\n            auto [cost_B, pos_B] = cost_to_type(suffix_B, current_pos, letter_points);\n            S += suffix_B;\n            current_pos = pos_B;\n            uncovered.clear();\n        } else {\n            vector<pair<int, string>> overlaps;\n            for (string B : uncovered) {\n                int ov = compute_overlap(S, B);\n                overlaps.push_back({ov, B});\n            }\n            sort(overlaps.begin(), overlaps.end(), [](const pair<int, string>& a, const pair<int, string>& b) {\n                return a.first > b.first;\n            });\n            int K = min(BEAM_WIDTH, (int)uncovered.size());\n            vector<string> top_B;\n            for (int i = 0; i < K; i++) {\n                top_B.push_back(overlaps[i].second);\n            }\n\n            int best_total_cost = INF;\n            string best_B;\n\n            for (string B : top_B) {\n                int k1 = compute_overlap(S, B);\n                string suffix_B = B.substr(k1);\n                auto [cost_B, pos_B] = cost_to_type(suffix_B, current_pos, letter_points);\n                string new_S = S + suffix_B;\n\n                vector<pair<int, string>> overlaps2;\n                for (string C : uncovered) {\n                    if (C == B) continue;\n                    int ov2 = compute_overlap(new_S, C);\n                    overlaps2.push_back({ov2, C});\n                }\n                sort(overlaps2.begin(), overlaps2.end(), [](const pair<int, string>& a, const pair<int, string>& b) {\n                    return a.first > b.first;\n                });\n                int L = min(BEAM_WIDTH, (int)overlaps2.size());\n                if (L == 0) continue;\n                for (int j = 0; j < L; j++) {\n                    string C = overlaps2[j].second;\n                    int k2 = compute_overlap(new_S, C);\n                    string suffix_C = C.substr(k2);\n                    auto [cost_C, pos_C] = cost_to_type(suffix_C, pos_B, letter_points);\n                    int total_cost = cost_B + cost_C;\n                    if (total_cost < best_total_cost) {\n                        best_total_cost = total_cost;\n                        best_B = B;\n                    }\n                }\n            }\n\n            if (best_total_cost == INF) {\n                best_B = uncovered[0];\n            }\n            int k1 = compute_overlap(S, best_B);\n            string suffix_B = best_B.substr(k1);\n            auto [cost_B, pos_B] = cost_to_type(suffix_B, current_pos, letter_points);\n            S += suffix_B;\n            current_pos = pos_B;\n            uncovered.erase(find(uncovered.begin(), uncovered.end(), best_B));\n        }\n    }\n\n    int L = S.size();\n    vector<vector<pair<int, int>>> points_for_S(L);\n    for (int i = 0; i < L; i++) {\n        points_for_S[i] = letter_points[S[i]];\n    }\n\n    pair<int, int> initial = {s_i, s_j};\n    vector<map<pair<int, int>, int>> dp(L);\n    vector<map<pair<int, int>, pair<int, int>>> prev(L);\n\n    for (auto p : points_for_S[0]) {\n        int cost = dist(initial, p) + 1;\n        dp[0][p] = cost;\n        prev[0][p] = initial;\n    }\n\n    for (int i = 1; i < L; i++) {\n        for (auto p : points_for_S[i]) {\n            int best_cost = INF;\n            pair<int, int> best_prev;\n            for (auto q : points_for_S[i-1]) {\n                if (dp[i-1].find(q) == dp[i-1].end()) continue;\n                int cost = dp[i-1][q] + dist(q, p) + 1;\n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_prev = q;\n                }\n            }\n            if (best_cost < INF) {\n                dp[i][p] = best_cost;\n                prev[i][p] = best_prev;\n            }\n        }\n    }\n\n    int min_cost = INF;\n    pair<int, int> best_point;\n    for (auto p : points_for_S[L-1]) {\n        if (dp[L-1].find(p) != dp[L-1].end() && dp[L-1][p] < min_cost) {\n            min_cost = dp[L-1][p];\n            best_point = p;\n        }\n    }\n\n    vector<pair<int, int>> sequence;\n    pair<int, int> current = best_point;\n    for (int i = L-1; i >= 0; i--) {\n        sequence.push_back(current);\n        if (i > 0) {\n            current = prev[i][current];\n        }\n    }\n    reverse(sequence.begin(), sequence.end());\n\n    for (auto p : sequence) {\n        cout << p.first << \" \" << p.second << endl;\n    }\n\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <tuple>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n\n    vector<vector<pair<int, int>>> fields(M);\n    int S = 0;\n    \n    for (int k = 0; k < M; k++) {\n        int d;\n        cin >> d;\n        S += d;\n        for (int i = 0; i < d; i++) {\n            int x, y;\n            cin >> x >> y;\n            fields[k].push_back(make_pair(x, y));\n        }\n    }\n\n    // Precompute expected oil reserves for each square\n    vector<vector<double>> weight(N, vector<double>(N, 0.0));\n    \n    for (const auto& shape : fields) {\n        int max_i = 0, max_j = 0;\n        for (auto p : shape) {\n            max_i = max(max_i, p.first);\n            max_j = max(max_j, p.second);\n        }\n        \n        int total_placements = (N - max_i) * (N - max_j);\n        if (total_placements <= 0) continue;\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                int count = 0;\n                for (auto p : shape) {\n                    int di = i - p.first;\n                    int dj = j - p.second;\n                    if (di >= 0 && di < N - max_i && dj >= 0 && dj < N - max_j) {\n                        count++;\n                    }\n                }\n                weight[i][j] += (double)count / total_placements;\n            }\n        }\n    }\n\n    // Create and sort squares by expected oil reserves\n    vector<tuple<double, int, int>> squares;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            squares.push_back(make_tuple(weight[i][j], i, j));\n        }\n    }\n    \n    sort(squares.begin(), squares.end(), [](const tuple<double, int, int>& a, const tuple<double, int, int>& b) {\n        return get<0>(a) > get<0>(b);\n    });\n\n    // Drill squares in priority order until we find all oil\n    vector<pair<int, int>> oil_squares;\n    int cumulative_sum = 0;\n    \n    for (const auto& square : squares) {\n        double w = get<0>(square);\n        int i = get<1>(square);\n        int j = get<2>(square);\n        \n        cout << \"q 1 \" << i << \" \" << j << endl;\n        int resp;\n        cin >> resp;\n        \n        if (resp > 0) {\n            oil_squares.push_back(make_pair(i, j));\n            cumulative_sum += resp;\n        }\n        \n        if (cumulative_sum >= S) {\n            break;\n        }\n    }\n\n    // Output final answer\n    cout << \"a \" << oil_squares.size();\n    for (auto p : oil_squares) {\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << endl;\n\n    int result;\n    cin >> result;\n    \n    return 0;\n}","ahc031":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nint main() {\n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    // Store strip boundaries for each day to maintain partition stability\n    vector<vector<int>> strip_boundaries(D, vector<int>(N + 1, 0));\n    \n    // Process each day\n    for (int d = 0; d < D; d++) {\n        // Sort areas while preserving original indices\n        vector<pair<int, int>> sorted_areas;\n        for (int k = 0; k < N; k++) {\n            sorted_areas.push_back({a[d][k], k});\n        }\n        sort(sorted_areas.begin(), sorted_areas.end());\n        \n        // Calculate total desired area\n        int total_desired = 0;\n        for (int k = 0; k < N; k++) {\n            total_desired += a[d][k];\n        }\n        \n        // Set strip boundaries\n        if (d == 0) {\n            // First day: distribute strips proportionally to area requirements\n            int cumulative_height = 0;\n            for (int k = 0; k < N; k++) {\n                double proportion = (double)sorted_areas[k].first / total_desired;\n                int strip_height = max(1, (int)round(proportion * W));\n                \n                strip_boundaries[d][k] = cumulative_height;\n                cumulative_height += strip_height;\n            }\n            strip_boundaries[d][N] = W;\n            \n            // Adjust if we exceeded W\n            if (cumulative_height > W) {\n                strip_boundaries[d][N] = cumulative_height;\n                // Redistribute proportionally\n                cumulative_height = 0;\n                for (int k = 0; k < N; k++) {\n                    double proportion = (double)sorted_areas[k].first / total_desired;\n                    int strip_height = max(1, (int)(proportion * W));\n                    strip_boundaries[d][k] = cumulative_height;\n                    cumulative_height += strip_height;\n                }\n                strip_boundaries[d][N] = W;\n            }\n        } else {\n            // Subsequent days: maintain similar partition structure\n            // Start with previous day's boundaries\n            strip_boundaries[d] = strip_boundaries[d-1];\n            \n            // Adjust boundaries slightly to meet new area requirements\n            // while minimizing changes from previous day\n            int cumulative_height = 0;\n            for (int k = 0; k < N; k++) {\n                double proportion = (double)sorted_areas[k].first / total_desired;\n                int target_height = max(1, (int)round(proportion * W));\n                \n                // Smooth adjustment: blend previous boundary with new target\n                int current_height = strip_boundaries[d][k+1] - strip_boundaries[d][k];\n                int new_height = (current_height + target_height) / 2;\n                \n                strip_boundaries[d][k] = cumulative_height;\n                cumulative_height += new_height;\n            }\n            strip_boundaries[d][N] = W;\n        }\n        \n        // Ensure boundaries are valid and non-decreasing\n        for (int k = 0; k <= N; k++) {\n            strip_boundaries[d][k] = max(0, min(W, strip_boundaries[d][k]));\n        }\n        for (int k = 1; k <= N; k++) {\n            if (strip_boundaries[d][k] <= strip_boundaries[d][k-1]) {\n                strip_boundaries[d][k] = strip_boundaries[d][k-1] + 1;\n            }\n        }\n        strip_boundaries[d][N] = W;\n        \n        // Assign rectangles to strips (maintain original order for output)\n        vector<int> strip_assignment(N);\n        for (int k = 0; k < N; k++) {\n            strip_assignment[sorted_areas[k].second] = k;\n        }\n        \n        // Output rectangles\n        for (int k = 0; k < N; k++) {\n            int strip_idx = strip_assignment[k];\n            int i0 = strip_boundaries[d][strip_idx];\n            int i1 = strip_boundaries[d][strip_idx + 1];\n            int j0 = 0;\n            int j1 = W;\n            \n            // Ensure valid rectangle\n            if (i0 >= i1) {\n                i1 = i0 + 1;\n            }\n            if (i1 > W) {\n                i1 = W;\n            }\n            \n            cout << i0 << \" \" << j0 << \" \" << i1 << \" \" << j1 << endl;\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <tuple>\n#include <set>\n#include <map>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <chrono>\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\n\nint main() {\n    auto start_time = chrono::high_resolution_clock::now();\n    srand(time(0));\n\n    int n, m, k;\n    cin >> n >> m >> k;\n    \n    int a[N][N];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> a[i][j];\n        }\n    }\n    \n    int stamps[M][3][3];\n    for (int mm = 0; mm < m; mm++) {\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                cin >> stamps[mm][i][j];\n            }\n        }\n    }\n    \n    int u[N][N];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            u[i][j] = a[i][j] % MOD;\n        }\n    }\n    \n    vector<tuple<int, int, int>> operations;\n    int max_p = n - 3;\n    int max_q = n - 3;\n    \n    // Greedy phase\n    for (int step = 0; step < k; step++) {\n        int best_delta = -1000000000;\n        int best_m = -1, best_p = -1, best_q = -1;\n        \n        for (int mm = 0; mm < m; mm++) {\n            for (int p = 0; p <= max_p; p++) {\n                for (int q = 0; q <= max_q; q++) {\n                    int delta = 0;\n                    for (int i = 0; i < 3; i++) {\n                        for (int j = 0; j < 3; j++) {\n                            int x = p + i;\n                            int y = q + j;\n                            int current_u = u[x][y];\n                            int s_val = stamps[mm][i][j];\n                            int new_u = (current_u + s_val) % MOD;\n                            if (new_u < 0) new_u += MOD;\n                            delta += new_u - current_u;\n                        }\n                    }\n                    if (delta > best_delta) {\n                        best_delta = delta;\n                        best_m = mm;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n        \n        if (best_delta <= 0) {\n            break;\n        }\n        \n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = best_p + i;\n                int y = best_q + j;\n                int s_val = stamps[best_m][i][j];\n                u[x][y] = (u[x][y] + s_val) % MOD;\n                if (u[x][y] < 0) u[x][y] += MOD;\n            }\n        }\n        \n        operations.push_back(make_tuple(best_m, best_p, best_q));\n    }\n    \n    // Simulated annealing with time-based termination\n    double temperature = 1000.0;\n    double cooling_rate = 0.95;\n    int max_iterations = 10000;\n    \n    for (int iter = 0; iter < max_iterations; iter++) {\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1900) break; // Stop if we're close to time limit\n        \n        if (operations.empty()) break;\n        \n        temperature *= cooling_rate;\n        if (temperature < 1e-5) break;\n        \n        int idx = rand() % operations.size();\n        int old_m, old_p, old_q;\n        tie(old_m, old_p, old_q) = operations[idx];\n        \n        int new_m = rand() % M;\n        int new_p = rand() % (max_p + 1);\n        int new_q = rand() % (max_q + 1);\n        \n        if (old_m == new_m && old_p == new_p && old_q == new_q) {\n            continue;\n        }\n        \n        // Calculate delta\n        int delta_score = 0;\n        set<pair<int, int>> affected_cells;\n        \n        // Remove old operation\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = old_p + i;\n                int y = old_q + j;\n                affected_cells.insert({x, y});\n            }\n        }\n        \n        // Add new operation\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = new_p + i;\n                int y = new_q + j;\n                affected_cells.insert({x, y});\n            }\n        }\n        \n        // Calculate effect on each affected cell\n        for (auto cell : affected_cells) {\n            int x = cell.first, y = cell.second;\n            int current_u = u[x][y];\n            \n            // Calculate what the value would be without old operation and with new operation\n            int old_contribution = 0;\n            if (x >= old_p && x < old_p + 3 && y >= old_q && y < old_q + 3) {\n                old_contribution = stamps[old_m][x - old_p][y - old_q];\n            }\n            \n            int new_contribution = 0;\n            if (x >= new_p && x < new_p + 3 && y >= new_q && y < new_q + 3) {\n                new_contribution = stamps[new_m][x - new_p][y - new_q];\n            }\n            \n            int new_val = current_u - old_contribution + new_contribution;\n            int new_u = new_val % MOD;\n            if (new_u < 0) new_u += MOD;\n            \n            delta_score += new_u - current_u;\n        }\n        \n        // Accept with probability based on temperature\n        if (delta_score > 0 || (double)rand() / RAND_MAX < exp(delta_score / temperature)) {\n            // Apply the change\n            for (auto cell : affected_cells) {\n                int x = cell.first, y = cell.second;\n                \n                int old_contribution = 0;\n                if (x >= old_p && x < old_p + 3 && y >= old_q && y < old_q + 3) {\n                    old_contribution = stamps[old_m][x - old_p][y - old_q];\n                }\n                \n                int new_contribution = 0;\n                if (x >= new_p && x < new_p + 3 && y >= new_q && y < new_q + 3) {\n                    new_contribution = stamps[new_m][x - new_p][y - new_q];\n                }\n                \n                u[x][y] = (u[x][y] - old_contribution + new_contribution) % MOD;\n                if (u[x][y] < 0) u[x][y] += MOD;\n            }\n            \n            operations[idx] = make_tuple(new_m, new_p, new_q);\n        }\n    }\n    \n    cout << operations.size() << endl;\n    for (auto op : operations) {\n        int m, p, q;\n        tie(m, p, q) = op;\n        cout << m << \" \" << p << \" \" << q << endl;\n    }\n    \n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <array>\n#include <algorithm>\nusing namespace std;\n\nconst int N = 5;\n\narray<array<int, N>, N> grid;\narray<int, N> brought = {0};\narray<int, N> dispatched = {0};\narray<array<int, N>, N> A;\n\nstruct Crane {\n    int i, j;\n    bool carrying;\n    int container;\n    bool active;\n    bool is_large;\n};\n\nvector<Crane> cranes;\nvector<string> actions(N);\n\nvoid init_cranes() {\n    cranes.resize(N);\n    for (int i = 0; i < N; i++) {\n        cranes[i].i = i;\n        cranes[i].j = 0;\n        cranes[i].carrying = false;\n        cranes[i].active = true;\n        cranes[i].is_large = (i == 0);\n    }\n}\n\nbool is_crane_on(int i, int j) {\n    for (const Crane& crane : cranes) {\n        if (crane.active && crane.i == i && crane.j == j) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> A[i][j];\n        }\n    }\n\n    init_cranes();\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            grid[i][j] = -1;\n        }\n    }\n\n    int turns = 0;\n    const int max_turns = 10000;\n\n    while (turns < max_turns) {\n        for (int i = 0; i < N; i++) {\n            if (brought[i] < N && grid[i][0] == -1 && !is_crane_on(i, 0)) {\n                grid[i][0] = A[i][brought[i]];\n                brought[i]++;\n            }\n        }\n\n        for (int idx = 0; idx < N; idx++) {\n            Crane& crane = cranes[idx];\n            if (!crane.active) {\n                actions[idx] += '.';\n                continue;\n            }\n\n            if (!crane.is_large) {\n                if (turns == 0) {\n                    if (crane.j < N-1) {\n                        actions[idx] += 'R';\n                        crane.j++;\n                    } else {\n                        actions[idx] += '.';\n                    }\n                } else if (turns == 1) {\n                    if (!crane.carrying) {\n                        actions[idx] += 'B';\n                        crane.active = false;\n                    } else {\n                        actions[idx] += '.';\n                    }\n                } else {\n                    actions[idx] += '.';\n                }\n            } else {\n                if (!crane.carrying) {\n                    if (grid[crane.i][crane.j] != -1) {\n                        actions[idx] += 'P';\n                        crane.carrying = true;\n                        crane.container = grid[crane.i][crane.j];\n                        grid[crane.i][crane.j] = -1;\n                    } else {\n                        int target_i = -1, target_j = -1;\n                        for (int i = 0; i < N; i++) {\n                            if (grid[i][0] != -1) {\n                                target_i = i;\n                                target_j = 0;\n                                break;\n                            }\n                        }\n                        if (target_i == -1) {\n                            for (int i = 0; i < N; i++) {\n                                for (int j = 0; j < N-1; j++) {\n                                    if (grid[i][j] != -1) {\n                                        target_i = i;\n                                        target_j = j;\n                                        break;\n                                    }\n                                }\n                                if (target_i != -1) break;\n                            }\n                        }\n                        if (target_i != -1) {\n                            if (crane.i != target_i) {\n                                if (crane.i < target_i) {\n                                    actions[idx] += 'D';\n                                    crane.i++;\n                                } else {\n                                    actions[idx] += 'U';\n                                    crane.i--;\n                                }\n                            } else if (crane.j != target_j) {\n                                if (crane.j < target_j) {\n                                    actions[idx] += 'R';\n                                    crane.j++;\n                                } else {\n                                    actions[idx] += 'L';\n                                    crane.j--;\n                                }\n                            } else {\n                                actions[idx] += '.';\n                            }\n                        } else {\n                            actions[idx] += '.';\n                        }\n                    }\n                } else {\n                    int b = crane.container;\n                    int target_i = b / N;\n                    if (crane.i != target_i) {\n                        if (crane.i < target_i) {\n                            actions[idx] += 'D';\n                            crane.i++;\n                        } else {\n                            actions[idx] += 'U';\n                            crane.i--;\n                        }\n                    } else {\n                        if (crane.j != N-1) {\n                            if (crane.j < N-1) {\n                                actions[idx] += 'R';\n                                crane.j++;\n                            } else {\n                                actions[idx] += 'L';\n                                crane.j--;\n                            }\n                        } else {\n                            if (grid[target_i][N-1] == -1) {\n                                actions[idx] += 'Q';\n                                grid[target_i][N-1] = b;\n                                crane.carrying = false;\n                            } else {\n                                actions[idx] += '.';\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        for (int i = 0; i < N; i++) {\n            if (grid[i][N-1] != -1) {\n                int b = grid[i][N-1];\n                grid[i][N-1] = -1;\n                if (b >= i * N && b < i * N + N) {\n                    dispatched[i]++;\n                }\n            }\n        }\n\n        turns++;\n        bool all_brought = true;\n        for (int i = 0; i < N; i++) {\n            if (brought[i] < N) {\n                all_brought = false;\n                break;\n            }\n        }\n        if (all_brought) {\n            bool grid_empty = true;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] != -1) {\n                        grid_empty = false;\n                        break;\n                    }\n                }\n                if (!grid_empty) break;\n            }\n            if (grid_empty && !cranes[0].carrying) {\n                break;\n            }\n        }\n    }\n\n    size_t max_len = 0;\n    for (int i = 0; i < N; i++) {\n        if (actions[i].size() > max_len) {\n            max_len = actions[i].size();\n        }\n    }\n    for (int i = 0; i < N; i++) {\n        string s = actions[i];\n        s.resize(max_len, '.');\n        cout << s << endl;\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\nvector<string> get_moves(int from_i, int from_j, int to_i, int to_j) {\n    vector<string> moves;\n    int di = to_i - from_i;\n    int dj = to_j - from_j;\n    if (di > 0) {\n        for (int i = 0; i < di; i++) {\n            moves.push_back(\"D\");\n        }\n    } else if (di < 0) {\n        for (int i = 0; i < -di; i++) {\n            moves.push_back(\"U\");\n        }\n    }\n    if (dj > 0) {\n        for (int j = 0; j < dj; j++) {\n            moves.push_back(\"R\");\n        }\n    } else if (dj < 0) {\n        for (int j = 0; j < -dj; j++) {\n            moves.push_back(\"L\");\n        }\n    }\n    return moves;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<vector<int>> h_current(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h_current[i][j];\n        }\n    }\n\n    int current_i = 0, current_j = 0;\n    int load = 0;\n    vector<string> operations;\n\n    while (true) {\n        bool all_zero = true;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (h_current[i][j] != 0) {\n                    all_zero = false;\n                    break;\n                }\n            }\n            if (!all_zero) break;\n        }\n        if (all_zero && load == 0) {\n            break;\n        }\n\n        bool operation_done = false;\n        if (h_current[current_i][current_j] > 0 && load == 0) {\n            int d = h_current[current_i][current_j];\n            operations.push_back(\"+\" + to_string(d));\n            load += d;\n            h_current[current_i][current_j] = 0;\n            operation_done = true;\n        } else if (h_current[current_i][current_j] < 0 && load > 0) {\n            int d = min(load, -h_current[current_i][current_j]);\n            operations.push_back(\"-\" + to_string(d));\n            load -= d;\n            h_current[current_i][current_j] += d;\n            operation_done = true;\n        }\n\n        if (operation_done) {\n            continue;\n        }\n\n        if (load == 0) {\n            int best_dist = 1e9;\n            int best_i = -1, best_j = -1;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h_current[i][j] > 0) {\n                        int dist = abs(i - current_i) + abs(j - current_j);\n                        if (dist < best_dist) {\n                            best_dist = dist;\n                            best_i = i;\n                            best_j = j;\n                        }\n                    }\n                }\n            }\n            if (best_i == -1) {\n                break;\n            }\n            vector<string> moves = get_moves(current_i, current_j, best_i, best_j);\n            operations.insert(operations.end(), moves.begin(), moves.end());\n            current_i = best_i;\n            current_j = best_j;\n        } else if (load > 0) {\n            int best_dist = 1e9;\n            int best_i = -1, best_j = -1;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h_current[i][j] < 0) {\n                        int dist = abs(i - current_i) + abs(j - current_j);\n                        if (dist < best_dist) {\n                            best_dist = dist;\n                            best_i = i;\n                            best_j = j;\n                        }\n                    }\n                }\n            }\n            if (best_i == -1) {\n                break;\n            }\n            vector<string> moves = get_moves(current_i, current_j, best_i, best_j);\n            operations.insert(operations.end(), moves.begin(), moves.end());\n            current_i = best_i;\n            current_j = best_j;\n        } else {\n            break;\n        }\n    }\n\n    for (const string& op : operations) {\n        cout << op << endl;\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <functional>\n#include <random>\n\nusing namespace std;\n\nint main() {\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 cell importance with more emphasis on center\n    vector<vector<int>> cell_importance(N, vector<int>(N, 0));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            double di = abs(i - (N-1)/2.0);\n            double dj = abs(j - (N-1)/2.0);\n            double dist = sqrt(di*di + dj*dj);\n            cell_importance[i][j] = round(100 * (1.0 - dist / (N * 0.7)));\n        }\n    }\n\n    for (int t = 0; t < T; t++) {\n        vector<int> values(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            values[i] = accumulate(seeds[i].begin(), seeds[i].end(), 0);\n        }\n\n        // Find maximum per criterion across all seeds\n        vector<int> max_per_criterion(M, 0);\n        for (int l = 0; l < M; l++) {\n            int max_val = 0;\n            for (int i = 0; i < seed_count; i++) {\n                if (seeds[i][l] > max_val) {\n                    max_val = seeds[i][l];\n                }\n            }\n            max_per_criterion[l] = max_val;\n        }\n\n        // More sophisticated seed selection\n        vector<int> indices(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            indices[i] = i;\n        }\n\n        // Sort by value first\n        sort(indices.begin(), indices.end(), [&](int a, int b) {\n            return values[a] > values[b];\n        });\n\n        // Calculate criterion strengths for each seed\n        vector<vector<bool>> is_strong(seed_count, vector<bool>(M, false));\n        for (int i = 0; i < seed_count; i++) {\n            for (int l = 0; l < M; l++) {\n                if (seeds[i][l] >= max_per_criterion[l] * 0.75) {\n                    is_strong[i][l] = true;\n                }\n            }\n        }\n\n        // Select seeds: more aggressive approach\n        vector<int> plant_indices;\n        vector<bool> used(seed_count, false);\n        \n        // Take absolute top seeds (more than before)\n        int top_count = min(25, N * N);\n        for (int i = 0; i < top_count; i++) {\n            plant_indices.push_back(indices[i]);\n            used[indices[i]] = true;\n        }\n\n        // Find seeds that excel in underrepresented criteria\n        vector<int> criterion_coverage(M, 0);\n        for (int idx : plant_indices) {\n            for (int l = 0; l < M; l++) {\n                if (is_strong[idx][l]) {\n                    criterion_coverage[l]++;\n                }\n            }\n        }\n\n        // Add seeds to improve criterion coverage\n        for (int l = 0; l < M && plant_indices.size() < N * N; l++) {\n            if (criterion_coverage[l] < 2) { // Need at least 2 strong seeds per criterion\n                for (int i = top_count; i < seed_count && plant_indices.size() < N * N; i++) {\n                    int candidate = indices[i];\n                    if (!used[candidate] && is_strong[candidate][l]) {\n                        plant_indices.push_back(candidate);\n                        used[candidate] = true;\n                        criterion_coverage[l]++;\n                        break;\n                    }\n                }\n            }\n        }\n\n        // Fill remaining slots with best available seeds\n        for (int i = 0; plant_indices.size() < N * N && i < seed_count; i++) {\n            if (!used[indices[i]]) {\n                plant_indices.push_back(indices[i]);\n                used[indices[i]] = true;\n            }\n        }\n\n        // Enhanced spiral placement with better neighbor consideration\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        vector<bool> assigned(plant_indices.size(), false);\n        \n        // Generate optimized spiral pattern\n        vector<pair<int, int>> spiral_order;\n        int center_i = N / 2, center_j = N / 2;\n        \n        // Create a more strategic pattern that maximizes neighbor connections\n        vector<vector<bool>> visited(N, vector<bool>(N, false));\n        spiral_order.push_back({center_i, center_j});\n        visited[center_i][center_j] = true;\n        \n        int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        int step = 1;\n        int dir = 0;\n        \n        while (spiral_order.size() < N * N) {\n            for (int s = 0; s < 2; s++) {\n                for (int k = 0; k < step; k++) {\n                    center_i += directions[dir][0];\n                    center_j += directions[dir][1];\n                    if (center_i >= 0 && center_i < N && center_j >= 0 && center_j < N && \n                        !visited[center_i][center_j]) {\n                        spiral_order.push_back({center_i, center_j});\n                        visited[center_i][center_j] = true;\n                    }\n                    if (spiral_order.size() >= N * N) break;\n                }\n                dir = (dir + 1) % 4;\n                if (spiral_order.size() >= N * N) break;\n            }\n            step++;\n        }\n\n        // Assign seeds with enhanced scoring\n        for (auto [i, j] : spiral_order) {\n            vector<int> neighbor_seeds;\n            int neighbor_count = 0;\n            \n            // Check all four neighbors with weights\n            vector<pair<int, double>> weighted_neighbors;\n            int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n            for (auto [di, dj] : directions) {\n                int ni = i + di, nj = j + dj;\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && A[ni][nj] != -1) {\n                    neighbor_seeds.push_back(A[ni][nj]);\n                    // Weight by cell importance of neighbor\n                    double weight = cell_importance[ni][nj] / 100.0;\n                    weighted_neighbors.push_back({A[ni][nj], weight});\n                    neighbor_count++;\n                }\n            }\n\n            if (neighbor_seeds.empty()) {\n                // Place one of the best seeds in important cells\n                int best_seed = -1;\n                double best_score = -1;\n                for (int k = 0; k < plant_indices.size(); k++) {\n                    if (assigned[k]) continue;\n                    int seed_idx = plant_indices[k];\n                    double score = values[seed_idx] * (cell_importance[i][j] / 100.0);\n                    \n                    // Bonus for seeds strong in many criteria\n                    int strong_count = 0;\n                    for (int l = 0; l < M; l++) {\n                        if (is_strong[seed_idx][l]) strong_count++;\n                    }\n                    score *= (1.0 + strong_count * 0.1);\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_seed = k;\n                    }\n                }\n                if (best_seed != -1) {\n                    A[i][j] = plant_indices[best_seed];\n                    assigned[best_seed] = true;\n                }\n            } else {\n                // Enhanced complementarity scoring\n                vector<double> weighted_deficiency(M, 0.0);\n                for (int l = 0; l < M; l++) {\n                    for (auto [n_index, weight] : weighted_neighbors) {\n                        weighted_deficiency[l] += (max_per_criterion[l] - seeds[n_index][l]) * weight;\n                    }\n                    if (!weighted_neighbors.empty()) {\n                        weighted_deficiency[l] /= weighted_neighbors.size();\n                    }\n                    // More aggressive non-linear weighting\n                    weighted_deficiency[l] = pow(weighted_deficiency[l] + 1, 1.5) - 1;\n                }\n\n                // Find optimal seed for this position\n                int best_seed_index = -1;\n                double best_score = -1e9;\n                \n                for (int k = 0; k < plant_indices.size(); k++) {\n                    if (assigned[k]) continue;\n                    \n                    int s_index = plant_indices[k];\n                    double score = 0;\n                    \n                    // Enhanced complementarity component\n                    for (int l = 0; l < M; l++) {\n                        score += seeds[s_index][l] * weighted_deficiency[l] * 0.1;\n                    }\n                    \n                    // Value component with cell importance\n                    score += values[s_index] * (cell_importance[i][j] / 100.0) * 0.8;\n                    \n                    // Diversity bonus for underrepresented criteria\n                    for (int l = 0; l < M; l++) {\n                        if (seeds[s_index][l] > max_per_criterion[l] * 0.85 && \n                            criterion_coverage[l] < 3) {\n                            score += max_per_criterion[l] * 0.15;\n                        }\n                    }\n                    \n                    // Bonus for seeds that are strong in many criteria\n                    int strong_count = 0;\n                    for (int l = 0; l < M; l++) {\n                        if (is_strong[s_index][l]) strong_count++;\n                    }\n                    score *= (1.0 + strong_count * 0.05);\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_seed_index = k;\n                    }\n                }\n                \n                if (best_seed_index != -1) {\n                    A[i][j] = plant_indices[best_seed_index];\n                    assigned[best_seed_index] = true;\n                } else {\n                    // Fallback with better selection\n                    for (int k = 0; k < plant_indices.size(); k++) {\n                        if (!assigned[k]) {\n                            A[i][j] = plant_indices[k];\n                            assigned[k] = true;\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        // Output the assignment\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << A[i][j];\n                if (j < N - 1) {\n                    cout << \" \";\n                }\n            }\n            cout << endl;\n        }\n        cout.flush();\n\n        // Read new seeds for next generation\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 <set>\n#include <map>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <random>\n\nusing namespace std;\n\nconst int MAX_N = 30;\nconst int MAX_V = 15;\n\n// Directions: 0=right, 1=down, 2=left, 3=up\nconst int dx[4] = {0, 1, 0, -1};\nconst int dy[4] = {1, 0, -1, 0};\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    \n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    \n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n    \n    int manhattan(const Point& other) const {\n        return abs(x - other.x) + abs(y - other.y);\n    }\n};\n\nclass RoboticArm {\nprivate:\n    int N, M, V;\n    vector<string> s, t;\n    Point root;\n    vector<int> parent;\n    vector<int> length;\n    vector<int> dirs; // direction for each vertex (except root)\n    vector<bool> holding;\n    set<Point> initial_set;\n    set<Point> target_set;\n    vector<vector<bool>> grid;\n    int turns;\n    mt19937 rng;\n    \n    // Check if point is within grid\n    bool in_grid(int x, int y) {\n        return x >= 0 && x < N && y >= 0 && y < N;\n    }\n    \n    // Get position of a vertex\n    Point get_position(int vertex) {\n        if (vertex == 0) return root;\n        \n        Point pos = root;\n        int current = vertex;\n        vector<int> path;\n        \n        // Get path from root to vertex\n        while (current != 0) {\n            path.push_back(current);\n            current = parent[current];\n        }\n        \n        // Reverse to go from root to vertex\n        for (int i = path.size() - 1; i >= 0; i--) {\n            int v = path[i];\n            int d = dirs[v];\n            pos.x += dx[d] * length[v];\n            pos.y += dy[d] * length[v];\n        }\n        \n        return pos;\n    }\n    \n    // Evaluate a move and rotation\n    double evaluate_action(int move, int rotation, const vector<Point>& desired_pos) {\n        Point new_root = root;\n        vector<int> new_dirs = dirs;\n        \n        // Apply move\n        if (move == 1) new_root.y++; // U\n        else if (move == 2) new_root.y--; // D\n        else if (move == 3) new_root.x--; // L\n        else if (move == 4) new_root.x++; // R\n        \n        if (!in_grid(new_root.x, new_root.y)) return numeric_limits<double>::max();\n        \n        // Apply rotation to vertex 1 (the only joint in our star design)\n        if (rotation != 0) {\n            for (int i = 1; i < V; i++) {\n                if (rotation == 1) new_dirs[i] = (new_dirs[i] + 1) % 4; // clockwise\n                else new_dirs[i] = (new_dirs[i] + 3) % 4; // counterclockwise\n            }\n        }\n        \n        // Calculate new positions and score\n        double score = 0;\n        for (int i = 2; i < V; i++) { // leaves are vertices 2 to V-1\n            Point leaf_pos = new_root;\n            int d = new_dirs[i];\n            leaf_pos.x += dx[d] * length[i];\n            leaf_pos.y += dy[d] * length[i];\n            \n            if (!desired_pos[i].x == -1) {\n                score += leaf_pos.manhattan(desired_pos[i]);\n            }\n        }\n        \n        return score;\n    }\n\npublic:\n    RoboticArm(int N, int M, int V, const vector<string>& s, const vector<string>& t) \n        : N(N), M(M), V(V), s(s), t(t), turns(0), rng(42) {\n        \n        // Initialize grid and sets\n        grid.assign(N, vector<bool>(N, false));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (s[i][j] == '1') {\n                    grid[i][j] = true;\n                    initial_set.insert(Point(i, j));\n                }\n                if (t[i][j] == '1') {\n                    target_set.insert(Point(i, j));\n                }\n            }\n        }\n        \n        // Initialize tree structure (star design)\n        parent.resize(V);\n        length.resize(V);\n        dirs.resize(V, 0); // all directions initially right\n        holding.resize(V, false);\n        \n        // Root at center\n        root = Point(N / 2, N / 2);\n        \n        // All vertices except root are children of root\n        for (int i = 1; i < V; i++) {\n            parent[i] = 0;\n            length[i] = N - 1;\n        }\n    }\n    \n    void output_tree() {\n        cout << V << endl;\n        for (int i = 1; i < V; i++) {\n            cout << parent[i] << \" \" << length[i] << endl;\n        }\n        cout << root.x << \" \" << root.y << endl;\n    }\n    \n    void solve() {\n        output_tree();\n        \n        while (turns < 100000) {\n            // Check if all takoyaki are placed\n            bool all_placed = true;\n            for (const auto& p : target_set) {\n                if (!grid[p.x][p.y]) {\n                    all_placed = false;\n                    break;\n                }\n            }\n            if (all_placed) break;\n            \n            // Assign desired positions for each leaf\n            vector<Point> desired_pos(V, Point(-1, -1));\n            set<Point> available_initial = initial_set;\n            set<Point> available_target = target_set;\n            \n            // Remove already placed takoyaki from available targets\n            for (const auto& p : target_set) {\n                if (grid[p.x][p.y]) {\n                    available_target.erase(p);\n                }\n            }\n            \n            // Greedy assignment\n            for (int i = 2; i < V; i++) {\n                if (!holding[i]) {\n                    // Find closest available initial position\n                    Point best_pos(-1, -1);\n                    int best_dist = numeric_limits<int>::max();\n                    Point current_pos = get_position(i);\n                    \n                    for (const auto& p : available_initial) {\n                        if (grid[p.x][p.y]) {\n                            int dist = current_pos.manhattan(p);\n                            if (dist < best_dist) {\n                                best_dist = dist;\n                                best_pos = p;\n                            }\n                        }\n                    }\n                    \n                    if (best_dist < numeric_limits<int>::max()) {\n                        desired_pos[i] = best_pos;\n                        available_initial.erase(best_pos);\n                    }\n                } else {\n                    // Find closest available target position\n                    Point best_pos(-1, -1);\n                    int best_dist = numeric_limits<int>::max();\n                    Point current_pos = get_position(i);\n                    \n                    for (const auto& p : available_target) {\n                        if (!grid[p.x][p.y]) {\n                            int dist = current_pos.manhattan(p);\n                            if (dist < best_dist) {\n                                best_dist = dist;\n                                best_pos = p;\n                            }\n                        }\n                    }\n                    \n                    if (best_dist < numeric_limits<int>::max()) {\n                        desired_pos[i] = best_pos;\n                        available_target.erase(best_pos);\n                    }\n                }\n            }\n            \n            // Evaluate all possible actions\n            int best_move = 0; // 0=no move, 1=U, 2=D, 3=L, 4=R\n            int best_rotation = 0; // 0=no rotation, 1=clockwise, 2=counterclockwise\n            double best_score = numeric_limits<double>::max();\n            \n            for (int move = 0; move <= 4; move++) {\n                for (int rotation = 0; rotation <= 2; rotation++) {\n                    double score = evaluate_action(move, rotation, desired_pos);\n                    if (score < best_score) {\n                        best_score = score;\n                        best_move = move;\n                        best_rotation = rotation;\n                    }\n                }\n            }\n            \n            // Apply best action\n            string operation;\n            operation.resize(2 * V, '.');\n            \n            // Move\n            if (best_move == 1) { // U\n                root.y++;\n                operation[0] = 'U';\n            } else if (best_move == 2) { // D\n                root.y--;\n                operation[0] = 'D';\n            } else if (best_move == 3) { // L\n                root.x--;\n                operation[0] = 'L';\n            } else if (best_move == 4) { // R\n                root.x++;\n                operation[0] = 'R';\n            }\n            \n            // Rotation\n            if (best_rotation == 1) { // clockwise\n                for (int i = 1; i < V; i++) {\n                    dirs[i] = (dirs[i] + 1) % 4;\n                    operation[i] = 'R';\n                }\n            } else if (best_rotation == 2) { // counterclockwise\n                for (int i = 1; i < V; i++) {\n                    dirs[i] = (dirs[i] + 3) % 4;\n                    operation[i] = 'L';\n                }\n            }\n            \n            // Pick/place operations\n            for (int i = 2; i < V; i++) {\n                Point pos = get_position(i);\n                if (in_grid(pos.x, pos.y)) {\n                    if (!holding[i] && initial_set.find(pos) != initial_set.end() && grid[pos.x][pos.y]) {\n                        // Pick up takoyaki\n                        grid[pos.x][pos.y] = false;\n                        holding[i] = true;\n                        operation[V + i] = 'P';\n                    } else if (holding[i] && target_set.find(pos) != target_set.end() && !grid[pos.x][pos.y]) {\n                        // Place takoyaki\n                        grid[pos.x][pos.y] = true;\n                        holding[i] = false;\n                        operation[V + i] = 'P';\n                    }\n                }\n            }\n            \n            cout << operation << endl;\n            turns++;\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, V;\n    cin >> N >> M >> V;\n    \n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; i++) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> t[i];\n    }\n    \n    RoboticArm arm(N, M, V, s, t);\n    arm.solve();\n    \n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    int type; // 0 for mackerel, 1 for sardine\n};\n\npair<int, int> optimize_axis(const vector<Point>& points_sorted, int fixed_min, int fixed_max, bool is_x_fixed) {\n    auto cmp_lower = [is_x_fixed](const Point& p, int val) {\n        if (is_x_fixed) return p.x < val;\n        else return p.y < val;\n    };\n    auto cmp_upper = [is_x_fixed](int val, const Point& p) {\n        if (is_x_fixed) return val < p.x;\n        else return val < p.y;\n    };\n\n    auto start_it = lower_bound(points_sorted.begin(), points_sorted.end(), fixed_min, cmp_lower);\n    auto end_it = upper_bound(points_sorted.begin(), points_sorted.end(), fixed_max, cmp_upper);\n\n    vector<int> value(100001, 0);\n    for (auto it = start_it; it != end_it; ++it) {\n        int coord;\n        if (is_x_fixed) {\n            coord = it->y;\n        } else {\n            coord = it->x;\n        }\n        if (it->type == 0) {\n            value[coord] += 1;\n        } else {\n            value[coord] -= 1;\n        }\n    }\n\n    vector<int> cum_net(100001);\n    cum_net[0] = value[0];\n    for (int i = 1; i <= 100000; i++) {\n        cum_net[i] = cum_net[i-1] + value[i];\n    }\n\n    int min_cum = 0;\n    int min_index = -1;\n    int best_diff = INT_MIN;\n    int best_a = 0, best_b = 0;\n\n    for (int i = 0; i <= 100000; i++) {\n        int diff = cum_net[i] - min_cum;\n        if (diff > best_diff) {\n            best_diff = diff;\n            best_a = min_index + 1;\n            best_b = i;\n        }\n        if (cum_net[i] < min_cum) {\n            min_cum = cum_net[i];\n            min_index = i;\n        }\n    }\n\n    if (best_a > best_b) {\n        swap(best_a, best_b);\n    }\n    if (best_a == best_b) {\n        if (best_b < 100000) {\n            best_b++;\n        } else if (best_a > 0) {\n            best_a--;\n        } else {\n            best_b++;\n        }\n    }\n\n    return {best_a, best_b};\n}\n\nint compute_score(const vector<Point>& points, int x1, int x2, int y1, int y2) {\n    int a = 0, b = 0;\n    for (const Point& p : points) {\n        if (p.x >= x1 && p.x <= x2 && p.y >= y1 && p.y <= y2) {\n            if (p.type == 0) a++;\n            else b++;\n        }\n    }\n    return a - b + 1;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n\n    int N;\n    cin >> N;\n    vector<Point> points(2 * N);\n    for (int i = 0; i < 2 * N; i++) {\n        cin >> points[i].x >> points[i].y;\n        points[i].type = (i < N) ? 0 : 1;\n    }\n\n    vector<Point> mackerels(points.begin(), points.begin() + N);\n\n    // Sort points for optimize_axis\n    vector<Point> points_by_x = points;\n    sort(points_by_x.begin(), points_by_x.end(), [](const Point& a, const Point& b) {\n        return a.x < b.x;\n    });\n    vector<Point> points_by_y = points;\n    sort(points_by_y.begin(), points_by_y.end(), [](const Point& a, const Point& b) {\n        return a.y < b.y;\n    });\n\n    // Compute initial rectangles\n    int min_x = INT_MAX, max_x = INT_MIN;\n    int min_y = INT_MAX, max_y = INT_MIN;\n    for (const Point& p : mackerels) {\n        min_x = min(min_x, p.x);\n        max_x = max(max_x, p.x);\n        min_y = min(min_y, p.y);\n        max_y = max(max_y, p.y);\n    }\n\n    vector<int> mackerels_x, mackerels_y;\n    for (const Point& p : mackerels) {\n        mackerels_x.push_back(p.x);\n        mackerels_y.push_back(p.y);\n    }\n    sort(mackerels_x.begin(), mackerels_x.end());\n    sort(mackerels_y.begin(), mackerels_y.end());\n\n    int Q1_x = mackerels_x[N/4];\n    int Q3_x = mackerels_x[3*N/4];\n    int Q1_y = mackerels_y[N/4];\n    int Q3_y = mackerels_y[3*N/4];\n\n    int Q10_x = mackerels_x[N/10];\n    int Q90_x = mackerels_x[9*N/10];\n    int Q10_y = mackerels_y[N/10];\n    int Q90_y = mackerels_y[9*N/10];\n\n    vector<pair<int, int>> initial_rectangles;\n    initial_rectangles.push_back({min_x, max_x}); // x1, x2 for init1\n    initial_rectangles.push_back({min_y, max_y}); // y1, y2 for init1\n\n    initial_rectangles.push_back({Q1_x, Q3_x}); // for init2\n    initial_rectangles.push_back({Q1_y, Q3_y});\n\n    initial_rectangles.push_back({Q10_x, Q90_x}); // for init3\n    initial_rectangles.push_back({Q10_y, Q90_y});\n\n    int best_score = INT_MIN;\n    int best_x1, best_x2, best_y1, best_y2;\n\n    for (int i = 0; i < 3; i++) {\n        int x1 = initial_rectangles[2*i].first;\n        int x2 = initial_rectangles[2*i].second;\n        int y1 = initial_rectangles[2*i+1].first;\n        int y2 = initial_rectangles[2*i+1].second;\n\n        for (int iter = 0; iter < 10; iter++) {\n            auto new_y = optimize_axis(points_by_x, x1, x2, true);\n            y1 = new_y.first;\n            y2 = new_y.second;\n\n            auto new_x = optimize_axis(points_by_y, y1, y2, false);\n            x1 = new_x.first;\n            x2 = new_x.second;\n        }\n\n        int score = compute_score(points, x1, x2, y1, y2);\n        if (score > best_score) {\n            best_score = score;\n            best_x1 = x1;\n            best_x2 = x2;\n            best_y1 = y1;\n            best_y2 = y2;\n        }\n    }\n\n    cout << 4 << endl;\n    cout << best_x1 << \" \" << best_y1 << endl;\n    cout << best_x2 << \" \" << best_y1 << endl;\n    cout << best_x2 << \" \" << best_y2 << endl;\n    cout << best_x1 << \" \" << best_y2 << endl;\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <tuple>\n\nusing namespace std;\n\nstruct Rectangle {\n    int index;\n    long long w, h;\n    long long area;\n    long long estimated_w, estimated_h;\n};\n\nbool compare_by_area(const Rectangle& a, const Rectangle& b) {\n    return a.area > b.area;\n}\n\nint main() {\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n    \n    vector<Rectangle> rects(N);\n    for (int i = 0; i < N; i++) {\n        cin >> rects[i].estimated_w >> rects[i].estimated_h;\n        rects[i].index = i;\n        rects[i].w = rects[i].estimated_w;\n        rects[i].h = rects[i].estimated_h;\n        rects[i].area = rects[i].estimated_w * rects[i].estimated_h;\n    }\n\n    // Use all rectangles in each turn to avoid penalty\n    for (int t = 0; t < T; t++) {\n        vector<tuple<int, int, char, int>> actions;\n        \n        // Sort by area (largest first) for better packing\n        vector<Rectangle> sorted_rects = rects;\n        sort(sorted_rects.begin(), sorted_rects.end(), compare_by_area);\n        \n        // Try different strategies based on turn number\n        if (t < T / 2) {\n            // Early turns: simple upward packing with optimized rotation\n            long long current_height = 0;\n            long long max_width = 0;\n            \n            for (const auto& rect : sorted_rects) {\n                // Choose rotation that minimizes width increase\n                long long width_no_rotate = rect.estimated_w;\n                long long width_rotate = rect.estimated_h;\n                \n                long long height_no_rotate = rect.estimated_h;\n                long long height_rotate = rect.estimated_w;\n                \n                // Calculate the cost for both orientations\n                long long new_width1 = max(max_width, width_no_rotate);\n                long long new_height1 = current_height + height_no_rotate;\n                long long cost1 = new_width1 + new_height1;\n                \n                long long new_width2 = max(max_width, width_rotate);\n                long long new_height2 = current_height + height_rotate;\n                long long cost2 = new_width2 + new_height2;\n                \n                // Choose the better orientation\n                int rotation = (cost2 < cost1) ? 1 : 0;\n                char direction = 'U';\n                int reference = -1;\n                \n                actions.push_back(make_tuple(rect.index, rotation, direction, reference));\n                \n                // Update current dimensions\n                if (rotation == 0) {\n                    max_width = max(max_width, width_no_rotate);\n                    current_height += height_no_rotate;\n                } else {\n                    max_width = max(max_width, width_rotate);\n                    current_height += height_rotate;\n                }\n            }\n        } else {\n            // Later turns: try mixed strategy with some leftward placement\n            long long current_width = 0, current_height = 0;\n            bool use_width_strategy = (t % 2 == 0); // Alternate strategies\n            \n            for (const auto& rect : sorted_rects) {\n                // Try both rotations\n                long long w1 = rect.estimated_w, h1 = rect.estimated_h;\n                long long w2 = rect.estimated_h, h2 = rect.estimated_w;\n                \n                // Calculate costs for different strategies\n                long long cost_up1 = max(current_width, w1) + (current_height + h1);\n                long long cost_up2 = max(current_width, w2) + (current_height + h2);\n                long long cost_left1 = (current_width + w1) + max(current_height, h1);\n                long long cost_left2 = (current_width + w2) + max(current_height, h2);\n                \n                // Find the best combination\n                long long min_cost = min({cost_up1, cost_up2, cost_left1, cost_left2});\n                \n                int rotation, reference;\n                char direction;\n                \n                if (min_cost == cost_up1) {\n                    rotation = 0; direction = 'U';\n                } else if (min_cost == cost_up2) {\n                    rotation = 1; direction = 'U';\n                } else if (min_cost == cost_left1) {\n                    rotation = 0; direction = 'L';\n                } else {\n                    rotation = 1; direction = 'L';\n                }\n                \n                reference = -1;\n                actions.push_back(make_tuple(rect.index, rotation, direction, reference));\n                \n                // Update dimensions\n                long long w = (rotation == 0) ? rect.estimated_w : rect.estimated_h;\n                long long h = (rotation == 0) ? rect.estimated_h : rect.estimated_w;\n                \n                if (direction == 'U') {\n                    current_width = max(current_width, w);\n                    current_height += h;\n                } else {\n                    current_width += w;\n                    current_height = max(current_height, h);\n                }\n            }\n        }\n        \n        // Sort actions by index to satisfy constraint\n        sort(actions.begin(), actions.end(), \n            [](const auto& a, const auto& b) { \n                return get<0>(a) < get<0>(b); \n            });\n        \n        // Output the placement plan\n        cout << actions.size() << endl;\n        for (const auto& action : actions) {\n            cout << get<0>(action) << \" \" << get<1>(action) << \" \" \n                 << get<2>(action) << \" \" << get<3>(action) << endl;\n        }\n        cout.flush();\n        \n        // Read measurement result\n        long long Wp, Hp;\n        cin >> Wp >> Hp;\n    }\n    \n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    int index;\n    int beauty;\n};\n\ndouble distance(const Point& a, const Point& b) {\n    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, H;\n    cin >> N >> M >> H;\n    \n    vector<int> A(N);\n    for (int i = 0; i < N; i++) {\n        cin >> A[i];\n    }\n    \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    vector<Point> points(N);\n    Point center = {500, 500, -1, 0}; // Circle center\n    for (int i = 0; i < N; i++) {\n        cin >> points[i].x >> points[i].y;\n        points[i].index = i;\n        points[i].beauty = A[i];\n    }\n    \n    // Sort points by distance from center (ascending) and beauty (ascending)\n    // Prefer points near center with low beauty as roots\n    vector<int> point_indices(N);\n    iota(point_indices.begin(), point_indices.end(), 0);\n    sort(point_indices.begin(), point_indices.end(), [&](int i, int j) {\n        double dist_i = distance(points[i], center);\n        double dist_j = distance(points[j], center);\n        if (abs(dist_i - dist_j) < 1e-9) {\n            return A[i] < A[j]; // Lower beauty first if same distance\n        }\n        return dist_i < dist_j;\n    });\n    \n    vector<int> parent(N, -1);\n    vector<int> depth(N, -1);\n    vector<bool> assigned(N, false);\n    \n    // Priority queue for BFS: (depth, -beauty, vertex)\n    // We want to process vertices with higher depth first, and for same depth,\n    // process lower beauty vertices first (to reserve high beauty for deeper positions)\n    auto cmp = [](const tuple<int, int, int>& a, const tuple<int, int, int>& b) {\n        if (get<0>(a) != get<0>(b)) return get<0>(a) < get<0>(b);\n        return get<1>(a) > get<1>(b); // Higher beauty has lower negative value\n    };\n    priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, decltype(cmp)> pq(cmp);\n    \n    // Assign roots starting from points near center with low beauty\n    for (int idx : point_indices) {\n        if (!assigned[idx] && depth[idx] == -1) {\n            // Make this point a root\n            parent[idx] = -1;\n            depth[idx] = 0;\n            assigned[idx] = true;\n            pq.push({0, -A[idx], idx});\n        }\n    }\n    \n    // Process vertices in BFS order with depth constraint\n    while (!pq.empty()) {\n        auto [current_depth, neg_beauty, u] = pq.top();\n        pq.pop();\n        \n        if (current_depth >= H) continue;\n        \n        // Sort neighbors by beauty descending (we want to assign high beauty vertices first)\n        vector<pair<int, int>> neighbors; // (beauty, vertex)\n        for (int v : adj[u]) {\n            if (!assigned[v]) {\n                neighbors.push_back({A[v], v});\n            }\n        }\n        \n        sort(neighbors.begin(), neighbors.end(), greater<pair<int, int>>());\n        \n        for (auto [beauty, v] : neighbors) {\n            if (!assigned[v] && depth[v] == -1) {\n                parent[v] = u;\n                depth[v] = current_depth + 1;\n                assigned[v] = true;\n                pq.push({depth[v], -A[v], v});\n            }\n        }\n    }\n    \n    // Output the parent array\n    for (int i = 0; i < N; i++) {\n        cout << parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n    const int N = 20;\n    vector<string> board(N);\n    for (int i = 0; i < N; i++) {\n        cin >> board[i];\n    }\n\n    vector<char> directions;\n    vector<int> indices;\n\n    for (int j = 0; j < N; j++) {\n        int max_r = -1;\n        int min_r = N;\n        bool has_oni = false;\n        for (int i = 0; i < N; i++) {\n            if (board[i][j] == 'x') {\n                has_oni = true;\n                if (i > max_r) max_r = i;\n                if (i < min_r) min_r = i;\n            }\n        }\n        if (!has_oni) continue;\n\n        bool safe_up = true;\n        for (int i = 0; i < max_r; i++) {\n            if (board[i][j] == 'o') {\n                safe_up = false;\n                break;\n            }\n        }\n\n        bool safe_down = true;\n        for (int i = min_r + 1; i < N; i++) {\n            if (board[i][j] == 'o') {\n                safe_down = false;\n                break;\n            }\n        }\n\n        int shifts_up = max_r + 1;\n        int shifts_down = N - min_r;\n\n        char dir;\n        int shifts;\n        if (safe_up && safe_down) {\n            if (shifts_up <= shifts_down) {\n                dir = 'U';\n                shifts = shifts_up;\n            } else {\n                dir = 'D';\n                shifts = shifts_down;\n            }\n        } else if (safe_up) {\n            dir = 'U';\n            shifts = shifts_up;\n        } else if (safe_down) {\n            dir = 'D';\n            shifts = shifts_down;\n        } else {\n            dir = 'U';\n            shifts = shifts_up;\n        }\n\n        for (int k = 0; k < shifts; k++) {\n            directions.push_back(dir);\n            indices.push_back(j);\n        }\n    }\n\n    for (size_t i = 0; i < directions.size(); i++) {\n        cout << directions[i] << \" \" << indices[i] << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\n// Function to simulate the sequence and compute the counts and error\nvoid simulate(const vector<int>& a, const vector<int>& b, int L, vector<int>& t, int& error, const vector<int>& T) {\n    t.assign(a.size(), 0);\n    int current = 0;\n    vector<int> count(a.size(), 0);\n    for (int week = 0; week < L; week++) {\n        t[current]++;\n        int times = count[current];\n        count[current]++;\n        if (times % 2 == 1) { // odd\n            current = a[current];\n        } else { // even\n            current = b[current];\n        }\n    }\n    error = 0;\n    for (int i = 0; i < a.size(); i++) {\n        error += abs(t[i] - T[i]);\n    }\n}\n\nint main() {\n    int N, L;\n    cin >> N >> L;\n    vector<int> T(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n\n    auto start_time = chrono::high_resolution_clock::now();\n    \n    // Multiple strategies for initial solution\n    vector<vector<int>> initial_a(3, vector<int>(N));\n    vector<vector<int>> initial_b(3, vector<int>(N));\n    vector<int> initial_errors(3);\n    \n    // Strategy 1: Simple cycle\n    for (int i = 0; i < N; i++) {\n        initial_a[0][i] = (i + 1) % N;\n        initial_b[0][i] = (i + N - 1) % N;\n    }\n    \n    // Strategy 2: Proportional allocation based on T values\n    vector<double> desired_ratio(N);\n    double total_T = accumulate(T.begin(), T.end(), 0.0);\n    for (int i = 0; i < N; i++) {\n        desired_ratio[i] = T[i] / total_T;\n    }\n    \n    // Calculate target incoming counts\n    vector<int> target_incoming(N);\n    int total_pointers = 2 * N;\n    for (int i = 0; i < N; i++) {\n        target_incoming[i] = max(1, (int)round(desired_ratio[i] * total_pointers));\n    }\n    \n    // Adjust to ensure sum equals 2N\n    int current_total = accumulate(target_incoming.begin(), target_incoming.end(), 0);\n    while (current_total != total_pointers) {\n        if (current_total < total_pointers) {\n            int best_idx = -1;\n            double best_ratio = -1;\n            for (int i = 0; i < N; i++) {\n                if (target_incoming[i] < total_pointers) {\n                    double ratio = desired_ratio[i] / (target_incoming[i] + 1);\n                    if (ratio > best_ratio) {\n                        best_ratio = ratio;\n                        best_idx = i;\n                    }\n                }\n            }\n            if (best_idx != -1) {\n                target_incoming[best_idx]++;\n                current_total++;\n            } else {\n                break;\n            }\n        } else {\n            int best_idx = -1;\n            double best_ratio = 1e9;\n            for (int i = 0; i < N; i++) {\n                if (target_incoming[i] > 1) {\n                    double ratio = desired_ratio[i] / target_incoming[i];\n                    if (ratio < best_ratio) {\n                        best_ratio = ratio;\n                        best_idx = i;\n                    }\n                }\n            }\n            if (best_idx != -1) {\n                target_incoming[best_idx]--;\n                current_total--;\n            } else {\n                break;\n            }\n        }\n    }\n    \n    // Create pointer allocation based on target_incoming\n    vector<int> pointers;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < target_incoming[i]; j++) {\n            pointers.push_back(i);\n        }\n    }\n    \n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(pointers.begin(), pointers.end(), gen);\n    \n    for (int j = 0; j < N; j++) {\n        initial_a[1][j] = pointers[2 * j];\n        initial_b[1][j] = pointers[2 * j + 1];\n    }\n    \n    // Strategy 3: Greedy assignment based on T values\n    vector<pair<int, int>> employees;\n    for (int i = 0; i < N; i++) {\n        employees.push_back({T[i], i});\n    }\n    sort(employees.begin(), employees.end(), greater<pair<int, int>>());\n    \n    // Assign pointers from high-T to high-T employees\n    for (int i = 0; i < N; i++) {\n        int emp = employees[i].second;\n        // Find two employees with highest T values (excluding self)\n        int best1 = -1, best2 = -1;\n        int maxT1 = -1, maxT2 = -1;\n        for (int j = 0; j < N; j++) {\n            if (j == emp) continue;\n            if (T[j] > maxT1) {\n                maxT2 = maxT1;\n                best2 = best1;\n                maxT1 = T[j];\n                best1 = j;\n            } else if (T[j] > maxT2) {\n                maxT2 = T[j];\n                best2 = j;\n            }\n        }\n        initial_a[2][emp] = best1;\n        initial_b[2][emp] = best2;\n    }\n    \n    // Evaluate all initial strategies\n    vector<int> t(N);\n    for (int s = 0; s < 3; s++) {\n        simulate(initial_a[s], initial_b[s], L, t, initial_errors[s], T);\n    }\n    \n    // Choose the best initial solution\n    int best_strategy = 0;\n    for (int s = 1; s < 3; s++) {\n        if (initial_errors[s] < initial_errors[best_strategy]) {\n            best_strategy = s;\n        }\n    }\n    \n    vector<int> a = initial_a[best_strategy];\n    vector<int> b = initial_b[best_strategy];\n    int current_error = initial_errors[best_strategy];\n    \n    // Enhanced local search with more iterations and better acceptance criteria\n    vector<int> best_a = a;\n    vector<int> best_b = b;\n    int best_error = current_error;\n    \n    uniform_int_distribution<> emp_dist(0, N-1);\n    uniform_int_distribution<> pointer_dist(0, 1);\n    uniform_real_distribution<> prob_dist(0.0, 1.0);\n    \n    const int MAX_ITER = 2000;\n    double temperature = 1000.0;\n    const double cooling_rate = 0.995;\n    \n    for (int iter = 0; iter < MAX_ITER; iter++) {\n        // Occasionally make a more significant change\n        if (iter % 100 == 0) {\n            // Reset to best solution found so far\n            a = best_a;\n            b = best_b;\n            current_error = best_error;\n        }\n        \n        int i = emp_dist(gen);\n        int pointer_type = pointer_dist(gen);\n        int old_value;\n        if (pointer_type == 0) {\n            old_value = a[i];\n        } else {\n            old_value = b[i];\n        }\n        \n        int j = emp_dist(gen);\n        if (j == old_value) continue;\n        \n        // Change the pointer\n        if (pointer_type == 0) {\n            a[i] = j;\n        } else {\n            b[i] = j;\n        }\n        \n        // Simulate with the change\n        int new_error;\n        simulate(a, b, L, t, new_error, T);\n        \n        // Simulated annealing acceptance\n        if (new_error < current_error || \n            prob_dist(gen) < exp((current_error - new_error) / temperature)) {\n            current_error = new_error;\n            if (new_error < best_error) {\n                best_error = new_error;\n                best_a = a;\n                best_b = b;\n            }\n        } else {\n            // Revert the change\n            if (pointer_type == 0) {\n                a[i] = old_value;\n            } else {\n                b[i] = old_value;\n            }\n        }\n        \n        // Cool the temperature\n        temperature *= cooling_rate;\n        \n        // Check time limit\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1800) { // Leave 200ms buffer\n            break;\n        }\n    }\n    \n    // Final output\n    a = best_a;\n    b = best_b;\n    for (int i = 0; i < N; i++) {\n        cout << a[i] << \" \" << b[i] << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <random>\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n};\n\nuint32_t morton_code(int x, int y) {\n    uint32_t code = 0;\n    for (int i = 0; i < 16; i++) {\n        code |= (x & 1) << (2 * i);\n        code |= (y & 1) << (2 * i + 1);\n        x >>= 1;\n        y >>= 1;\n    }\n    return code;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (int i = 0; i < M; i++) {\n        cin >> G[i];\n    }\n    vector<City> cities(N);\n    for (int i = 0; i < N; i++) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].id = i;\n    }\n\n    // Calculate center points for each city\n    vector<int> x_center(N), y_center(N);\n    for (int i = 0; i < N; i++) {\n        x_center[i] = (cities[i].lx + cities[i].rx) / 2;\n        y_center[i] = (cities[i].ly + cities[i].ry) / 2;\n    }\n\n    // Sort by Morton code for spatial coherence\n    vector<uint32_t> morton_codes(N);\n    for (int i = 0; i < N; i++) {\n        morton_codes[i] = morton_code(x_center[i], y_center[i]);\n    }\n\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n    sort(indices.begin(), indices.end(), [&](int i, int j) {\n        return morton_codes[i] < morton_codes[j];\n    });\n\n    // Create groups based on sorted order\n    vector<vector<int>> groups(M);\n    int start_idx = 0;\n    for (int i = 0; i < M; i++) {\n        int g_size = G[i];\n        groups[i].resize(g_size);\n        for (int j = 0; j < g_size; j++) {\n            groups[i][j] = indices[start_idx + j];\n        }\n        start_idx += g_size;\n    }\n\n    vector<pair<int, int>> collected_edges;\n    int queries_used = 0;\n\n    // Phase 1: Query each group to get MST edges\n    for (int i = 0; i < M; i++) {\n        if (queries_used >= Q) break;\n        int g = groups[i].size();\n        if (g < 2) continue;\n        \n        // For groups that fit in one query, query the entire group\n        if (g <= L) {\n            cout << \"? \" << g;\n            for (int city_id : groups[i]) {\n                cout << \" \" << city_id;\n            }\n            cout << endl;\n            cout.flush();\n            \n            for (int j = 0; j < g - 1; j++) {\n                int a, b;\n                cin >> a >> b;\n                if (a > b) swap(a, b);\n                collected_edges.push_back({a, b});\n            }\n            queries_used++;\n        } else {\n            // For large groups, query in overlapping chunks\n            int step = max(2, L - 2); // Allow overlap for better connectivity\n            for (int start = 0; start < g - 1 && queries_used < Q; start += step) {\n                int end = min(start + L, g);\n                int size = end - start;\n                if (size < 2) break;\n                \n                cout << \"? \" << size;\n                for (int k = start; k < end; k++) {\n                    cout << \" \" << groups[i][k];\n                }\n                cout << endl;\n                cout.flush();\n                \n                for (int k = 0; k < size - 1; k++) {\n                    int a, b;\n                    cin >> a >> b;\n                    if (a > b) swap(a, b);\n                    collected_edges.push_back({a, b});\n                }\n                queries_used++;\n            }\n        }\n    }\n\n    // Phase 2: Use remaining queries to sample random groups\n    int remaining_queries = Q - queries_used;\n    if (remaining_queries > 0) {\n        mt19937 rng(42);\n        vector<int> group_indices(M);\n        iota(group_indices.begin(), group_indices.end(), 0);\n        shuffle(group_indices.begin(), group_indices.end(), rng);\n        \n        for (int i = 0; i < M && remaining_queries > 0; i++) {\n            int group_idx = group_indices[i];\n            int g = groups[group_idx].size();\n            if (g < 3) continue;\n            \n            // Sample a random subset of size min(L, g)\n            int sample_size = min(L, g);\n            vector<int> sample_indices(g);\n            iota(sample_indices.begin(), sample_indices.end(), 0);\n            shuffle(sample_indices.begin(), sample_indices.end(), rng);\n            \n            vector<int> sample(sample_size);\n            for (int j = 0; j < sample_size; j++) {\n                sample[j] = groups[group_idx][sample_indices[j]];\n            }\n            sort(sample.begin(), sample.end());\n            \n            cout << \"? \" << sample_size;\n            for (int city_id : sample) {\n                cout << \" \" << city_id;\n            }\n            cout << endl;\n            cout.flush();\n            \n            for (int j = 0; j < sample_size - 1; j++) {\n                int a, b;\n                cin >> a >> b;\n                if (a > b) swap(a, b);\n                collected_edges.push_back({a, b});\n            }\n            remaining_queries--;\n        }\n    }\n\n    // Output final answer\n    cout << \"!\" << endl;\n    \n    // Create a set of collected edges for faster lookup\n    set<pair<int, int>> collected_set;\n    for (auto& edge : collected_edges) {\n        collected_set.insert(edge);\n    }\n\n    for (int i = 0; i < M; i++) {\n        vector<int>& group = groups[i];\n        int g = group.size();\n        \n        // Output group cities\n        for (int j = 0; j < g; j++) {\n            if (j > 0) cout << \" \";\n            cout << group[j];\n        }\n        cout << endl;\n        \n        if (g == 1) continue;\n\n        // Build MST for this group\n        vector<tuple<int, long long, int, int>> edges;\n        map<int, int> id_to_index;\n        for (int idx = 0; idx < g; idx++) {\n            id_to_index[group[idx]] = idx;\n        }\n\n        // Create all possible edges with priorities\n        for (int a = 0; a < g; a++) {\n            for (int b = a + 1; b < g; b++) {\n                int u = group[a], v = group[b];\n                long long dx = x_center[u] - x_center[v];\n                long long dy = y_center[u] - y_center[v];\n                long long dist_sq = dx * dx + dy * dy;\n                \n                // Priority: 0 for queried edges, 1 for non-queried\n                int priority = collected_set.count({u, v}) ? 0 : 1;\n                edges.push_back({priority, dist_sq, u, v});\n            }\n        }\n\n        // Sort by priority then by estimated distance\n        sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {\n            if (get<0>(a) != get<0>(b)) return get<0>(a) < get<0>(b);\n            if (get<1>(a) != get<1>(b)) return get<1>(a) < get<1>(b);\n            if (get<2>(a) != get<2>(b)) return get<2>(a) < get<2>(b);\n            return get<3>(a) < get<3>(b);\n        });\n\n        // Kruskal's algorithm\n        vector<int> parent(g);\n        iota(parent.begin(), parent.end(), 0);\n        \n        function<int(int)> find = [&](int x) {\n            while (parent[x] != x) {\n                parent[x] = parent[parent[x]];\n                x = parent[x];\n            }\n            return x;\n        };\n\n        vector<pair<int, int>> selected_edges;\n        for (auto& edge : edges) {\n            int u = get<2>(edge), v = get<3>(edge);\n            int u_idx = id_to_index[u], v_idx = id_to_index[v];\n            int root_u = find(u_idx), root_v = find(v_idx);\n            \n            if (root_u != root_v) {\n                selected_edges.push_back({u, v});\n                parent[root_u] = root_v;\n                if (selected_edges.size() == g - 1) break;\n            }\n        }\n\n        // Output selected edges\n        for (auto& e : selected_edges) {\n            cout << e.first << \" \" << e.second << endl;\n        }\n    }\n    \n    cout.flush();\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<pair<int, int>> points;\n    for (int i = 0; i < M; i++) {\n        int i_val, j_val;\n        cin >> i_val >> j_val;\n        points.push_back({i_val, j_val});\n    }\n\n    int cur_i = points[0].first;\n    int cur_j = points[0].second;\n    \n    // Track block positions (initially no blocks)\n    vector<vector<bool>> blocks(N, vector<bool>(N, false));\n\n    for (int idx = 1; idx < M; idx++) {\n        int target_i = points[idx].first;\n        int target_j = points[idx].second;\n\n        // Horizontal movement\n        while (cur_j != target_j) {\n            int dj = target_j - cur_j;\n            char dir = (dj > 0) ? 'R' : 'L';\n            int k = abs(dj);\n            \n            // Calculate slide distance\n            int slide_dist = 0;\n            int temp_j = cur_j;\n            while (true) {\n                int next_j = temp_j + (dj > 0 ? 1 : -1);\n                if (next_j < 0 || next_j >= N) break;\n                if (blocks[cur_i][next_j]) break;\n                slide_dist++;\n                temp_j = next_j;\n            }\n            \n            // Use slide if beneficial and possible\n            if (k <= slide_dist && \n                ((dj > 0 && target_j == N-1) || (dj < 0 && target_j == 0)) && \n                k >= 2) {\n                cout << \"S \" << dir << endl;\n                cur_j = target_j;\n            } else {\n                cout << \"M \" << dir << endl;\n                cur_j += (dj > 0 ? 1 : -1);\n            }\n        }\n\n        // Vertical movement\n        while (cur_i != target_i) {\n            int di = target_i - cur_i;\n            char dir = (di > 0) ? 'D' : 'U';\n            int k = abs(di);\n            \n            // Calculate slide distance\n            int slide_dist = 0;\n            int temp_i = cur_i;\n            while (true) {\n                int next_i = temp_i + (di > 0 ? 1 : -1);\n                if (next_i < 0 || next_i >= N) break;\n                if (blocks[next_i][cur_j]) break;\n                slide_dist++;\n                temp_i = next_i;\n            }\n            \n            // Use slide if beneficial and possible\n            if (k <= slide_dist && \n                ((di > 0 && target_i == N-1) || (di < 0 && target_i == 0)) && \n                k >= 2) {\n                cout << \"S \" << dir << endl;\n                cur_i = target_i;\n            } else {\n                cout << \"M \" << dir << endl;\n                cur_i += (di > 0 ? 1 : -1);\n            }\n        }\n    }\n\n    return 0;\n}"},"8":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <tuple>\n#include <cmath>\n#include <queue>\n#include <set>\n\nusing namespace std;\n\nconst int GRID_SIZE = 10000;\n\nstruct Company {\n    int id;\n    int x, y, r;\n    int a, b, c, d;\n    int area() const { return (c - a) * (d - b); }\n    double satisfaction() const {\n        int s = area();\n        if (s == 0) return 0.0;\n        double ratio = min(r, s) / (double)max(r, s);\n        return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n    }\n};\n\nstruct Rectangle {\n    int a, b, c, d;\n    Rectangle(int a, int b, int c, int d) : a(a), b(b), c(c), d(d) {}\n    bool contains(int x, int y) const {\n        return a <= x && x < c && b <= y && y < d;\n    }\n    bool overlaps(const Rectangle& other) const {\n        return !(c <= other.a || other.c <= a || d <= other.b || other.d <= b);\n    }\n    int area() const { return (c - a) * (d - b); }\n};\n\nclass AdaptiveRectanglePacker {\nprivate:\n    vector<Company> companies;\n    vector<Rectangle> rectangles;\n    \n    bool hasOverlap(const Rectangle& rect, int exclude_idx) const {\n        for (size_t i = 0; i < rectangles.size(); i++) {\n            if (static_cast<int>(i) == exclude_idx) continue;\n            if (rect.overlaps(rectangles[i])) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    bool isValidExpansion(const Company& company, int da, int db, int dc, int dd, int exclude_idx) const {\n        int new_a = max(0, company.a + da);\n        int new_b = max(0, company.b + db);\n        int new_c = min(GRID_SIZE, company.c + dc);\n        int new_d = min(GRID_SIZE, company.d + dd);\n        \n        if (new_a >= new_c || new_b >= new_d) return false;\n        \n        Rectangle new_rect(new_a, new_b, new_c, new_d);\n        return !hasOverlap(new_rect, exclude_idx) && new_rect.contains(company.x, company.y);\n    }\n    \n    int calculateExpansionStep(const Company& company) {\n        int deficit = company.r - company.area();\n        if (deficit <= 0) return 0;\n        \n        // Adaptive step size based on deficit and available space\n        int step = 1;\n        if (deficit > 1000000) step = 100;\n        else if (deficit > 100000) step = 50;\n        else if (deficit > 10000) step = 10;\n        else if (deficit > 1000) step = 5;\n        \n        return min(step, deficit / 1000 + 1);\n    }\n    \n    bool tryExpansion(Company& company, int idx) {\n        int current_area = company.area();\n        int deficit = company.r - current_area;\n        \n        if (deficit <= 0) return false;\n        \n        int step = calculateExpansionStep(company);\n        vector<tuple<int, int, int, int, int>> expansions; // da, db, dc, dd, area_diff\n        \n        // Try different expansion strategies\n        for (int s = step; s >= 1; s /= 2) {\n            if (s == 0) break;\n            \n            // Try symmetric expansion (best for satisfaction)\n            if (isValidExpansion(company, -s, -s, s, s, idx)) {\n                int new_area = (company.c + s - company.a + s) * (company.d + s - company.b + s);\n                expansions.emplace_back(-s, -s, s, s, abs(new_area - company.r));\n            }\n            \n            // Try individual directions with larger steps\n            if (isValidExpansion(company, -s, 0, 0, 0, idx)) {\n                int new_area = (company.c - company.a + s) * (company.d - company.b);\n                expansions.emplace_back(-s, 0, 0, 0, abs(new_area - company.r));\n            }\n            if (isValidExpansion(company, 0, 0, s, 0, idx)) {\n                int new_area = (company.c + s - company.a) * (company.d - company.b);\n                expansions.emplace_back(0, 0, s, 0, abs(new_area - company.r));\n            }\n            if (isValidExpansion(company, 0, -s, 0, 0, idx)) {\n                int new_area = (company.c - company.a) * (company.d - company.b + s);\n                expansions.emplace_back(0, -s, 0, 0, abs(new_area - company.r));\n            }\n            if (isValidExpansion(company, 0, 0, 0, s, idx)) {\n                int new_area = (company.c - company.a) * (company.d + s - company.b);\n                expansions.emplace_back(0, 0, 0, s, abs(new_area - company.r));\n            }\n            \n            if (!expansions.empty()) break;\n        }\n        \n        if (expansions.empty()) return false;\n        \n        // Choose best expansion (minimizes area difference)\n        auto best = *min_element(expansions.begin(), expansions.end(),\n            [](const auto& a, const auto& b) { return get<4>(a) < get<4>(b); });\n        \n        auto [da, db, dc, dd, _] = best;\n        company.a += da; company.b += db;\n        company.c += dc; company.d += dd;\n        rectangles[idx] = Rectangle(company.a, company.b, company.c, company.d);\n        \n        return true;\n    }\n    \n    void expandRectangles() {\n        // Sort by desired area (largest first)\n        vector<int> indices(companies.size());\n        for (size_t i = 0; i < companies.size(); i++) indices[i] = i;\n        sort(indices.begin(), indices.end(), [this](int i, int j) {\n            return companies[i].r > companies[j].r;\n        });\n        \n        // Expansion rounds with different strategies\n        for (int round = 0; round < 3; round++) {\n            bool any_expansion = false;\n            \n            for (int idx : indices) {\n                Company& company = companies[idx];\n                if (company.area() >= company.r) continue;\n                \n                if (tryExpansion(company, idx)) {\n                    any_expansion = true;\n                }\n            }\n            \n            if (!any_expansion) break;\n        }\n    }\n    \n    void improveSatisfaction() {\n        // Try to adjust rectangles to improve satisfaction\n        for (int iter = 0; iter < 20; iter++) {\n            bool improved = false;\n            \n            for (size_t i = 0; i < companies.size(); i++) {\n                Company& company = companies[i];\n                double current_sat = company.satisfaction();\n                \n                if (current_sat > 0.98) continue;\n                \n                // Try small adjustments in a smarter order\n                vector<tuple<int, int, int, int>> adjustments;\n                for (int dx = -2; dx <= 2; dx++) {\n                    for (int dy = -2; dy <= 2; dy++) {\n                        if (dx == 0 && dy == 0) continue;\n                        adjustments.emplace_back(dx, dy, dx, dy);\n                    }\n                }\n                \n                // Sort adjustments by potential improvement\n                sort(adjustments.begin(), adjustments.end(),\n                    [&](const tuple<int, int, int, int>& a, const tuple<int, int, int, int>& b) {\n                        int dx1 = get<0>(a), dy1 = get<1>(a), dcx1 = get<2>(a), dcy1 = get<3>(a);\n                        int dx2 = get<0>(b), dy2 = get<1>(b), dcx2 = get<2>(b), dcy2 = get<3>(b);\n                        \n                        int area1 = (company.c + dcx1 - company.a - dx1) * \n                                   (company.d + dcy1 - company.b - dy1);\n                        int area2 = (company.c + dcx2 - company.a - dx2) * \n                                   (company.d + dcy2 - company.b - dy2);\n                        return abs(area1 - company.r) < abs(area2 - company.r);\n                    });\n                \n                for (const auto& adjustment : adjustments) {\n                    int dx = get<0>(adjustment);\n                    int dy = get<1>(adjustment);\n                    int dcx = get<2>(adjustment);\n                    int dcy = get<3>(adjustment);\n                    \n                    int new_a = max(0, company.a + dx);\n                    int new_b = max(0, company.b + dy);\n                    int new_c = min(GRID_SIZE, company.c + dcx);\n                    int new_d = min(GRID_SIZE, company.d + dcy);\n                    \n                    if (new_a >= new_c || new_b >= new_d) continue;\n                    \n                    if (isValidExpansion(company, dx, dy, dcx, dcy, static_cast<int>(i))) {\n                        Company temp = company;\n                        temp.a = new_a; temp.b = new_b;\n                        temp.c = new_c; temp.d = new_d;\n                        double new_sat = temp.satisfaction();\n                        \n                        if (new_sat > current_sat) {\n                            company = temp;\n                            rectangles[i] = Rectangle(company.a, company.b, company.c, company.d);\n                            improved = true;\n                            break;\n                        }\n                    }\n                }\n            }\n            \n            if (!improved) break;\n        }\n    }\n    \n    void ensureValidity() {\n        // Final validation and correction\n        for (size_t i = 0; i < companies.size(); i++) {\n            Company& company = companies[i];\n            \n            // Ensure point containment\n            if (!(company.a <= company.x && company.x < company.c && \n                  company.b <= company.y && company.y < company.d)) {\n                company.a = company.x;\n                company.b = company.y;\n                company.c = company.x + 1;\n                company.d = company.y + 1;\n            }\n            \n            // Ensure valid bounds and positive area\n            company.a = max(0, min(company.a, GRID_SIZE - 1));\n            company.b = max(0, min(company.b, GRID_SIZE - 1));\n            company.c = max(1, min(company.c, GRID_SIZE));\n            company.d = max(1, min(company.d, GRID_SIZE));\n            \n            if (company.a >= company.c) company.c = company.a + 1;\n            if (company.b >= company.d) company.d = company.b + 1;\n            \n            rectangles[i] = Rectangle(company.a, company.b, company.c, company.d);\n        }\n        \n        // Resolve overlaps with a more sophisticated approach\n        resolveOverlaps();\n    }\n    \n    void resolveOverlaps() {\n        // Multi-pass overlap resolution\n        for (int pass = 0; pass < 3; pass++) {\n            bool overlap_found = false;\n            \n            for (size_t i = 0; i < companies.size(); i++) {\n                for (size_t j = i + 1; j < companies.size(); j++) {\n                    Company& rect1 = companies[i];\n                    Company& rect2 = companies[j];\n                    Rectangle r1(rect1.a, rect1.b, rect1.c, rect1.d);\n                    Rectangle r2(rect2.a, rect2.b, rect2.c, rect2.d);\n                    \n                    if (r1.overlaps(r2)) {\n                        overlap_found = true;\n                        \n                        // Calculate overlap area\n                        int overlap_left = max(rect1.a, rect2.a);\n                        int overlap_right = min(rect1.c, rect2.c);\n                        int overlap_bottom = max(rect1.b, rect2.b);\n                        int overlap_top = min(rect1.d, rect2.d);\n                        \n                        if (overlap_left >= overlap_right || overlap_bottom >= overlap_top) continue;\n                        \n                        // Resolve by shrinking the rectangle that's further from its desired area\n                        double sat1 = rect1.satisfaction();\n                        double sat2 = rect2.satisfaction();\n                        \n                        if (sat1 < sat2) {\n                            // Shrink rect1\n                            if (rect1.a < rect2.c && rect1.a >= rect2.a) rect1.a = rect2.c;\n                            if (rect1.c > rect2.a && rect1.c <= rect2.c) rect1.c = rect2.a;\n                            if (rect1.b < rect2.d && rect1.b >= rect2.b) rect1.b = rect2.d;\n                            if (rect1.d > rect2.b && rect1.d <= rect2.d) rect1.d = rect2.b;\n                        } else {\n                            // Shrink rect2\n                            if (rect2.a < rect1.c && rect2.a >= rect1.a) rect2.a = rect1.c;\n                            if (rect2.c > rect1.a && rect2.c <= rect1.c) rect2.c = rect1.a;\n                            if (rect2.b < rect1.d && rect2.b >= rect1.b) rect2.b = rect1.d;\n                            if (rect2.d > rect1.b && rect2.d <= rect1.d) rect2.d = rect1.b;\n                        }\n                        \n                        // Ensure point containment after shrinking\n                        if (!(rect1.a <= rect1.x && rect1.x < rect1.c && \n                              rect1.b <= rect1.y && rect1.y < rect1.d)) {\n                            rect1.a = rect1.x; rect1.b = rect1.y;\n                            rect1.c = rect1.x + 1; rect1.d = rect1.y + 1;\n                        }\n                        if (!(rect2.a <= rect2.x && rect2.x < rect2.c && \n                              rect2.b <= rect2.y && rect2.y < rect2.d)) {\n                            rect2.a = rect2.x; rect2.b = rect2.y;\n                            rect2.c = rect2.x + 1; rect2.d = rect2.y + 1;\n                        }\n                        \n                        rectangles[i] = Rectangle(rect1.a, rect1.b, rect1.c, rect1.d);\n                        rectangles[j] = Rectangle(rect2.a, rect2.b, rect2.c, rect2.d);\n                    }\n                }\n            }\n            \n            if (!overlap_found) break;\n        }\n    }\n    \n    bool validateSolution() {\n        // Comprehensive validation\n        for (size_t i = 0; i < companies.size(); i++) {\n            const Company& company = companies[i];\n            const Rectangle& rect = rectangles[i];\n            \n            // Check bounds\n            if (rect.a < 0 || rect.b < 0 || rect.c > GRID_SIZE || rect.d > GRID_SIZE ||\n                rect.a >= rect.c || rect.b >= rect.d) {\n                return false;\n            }\n            \n            // Check point containment\n            if (!rect.contains(company.x, company.y)) {\n                return false;\n            }\n            \n            // Check overlaps\n            for (size_t j = i + 1; j < companies.size(); j++) {\n                if (rect.overlaps(rectangles[j])) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \npublic:\n    AdaptiveRectanglePacker(int n, const vector<tuple<int, int, int>>& input) {\n        companies.resize(n);\n        for (int i = 0; i < n; i++) {\n            auto [x, y, r] = input[i];\n            companies[i] = {i, x, y, r, x, y, x + 1, y + 1};\n            rectangles.emplace_back(x, y, x + 1, y + 1);\n        }\n    }\n    \n    void solve() {\n        // Try the main algorithm\n        expandRectangles();\n        improveSatisfaction();\n        ensureValidity();\n        \n        // If solution is invalid, use a fallback strategy\n        if (!validateSolution()) {\n            // Fallback: minimal valid rectangles\n            for (size_t i = 0; i < companies.size(); i++) {\n                companies[i].a = companies[i].x;\n                companies[i].b = companies[i].y;\n                companies[i].c = companies[i].x + 1;\n                companies[i].d = companies[i].y + 1;\n                rectangles[i] = Rectangle(companies[i].a, companies[i].b, companies[i].c, companies[i].d);\n            }\n        }\n        \n        // Final validation to ensure we output valid solution\n        ensureValidity();\n    }\n    \n    vector<tuple<int, int, int, int>> getSolution() {\n        vector<tuple<int, int, int, int>> result;\n        result.reserve(companies.size());\n        \n        for (const auto& company : companies) {\n            result.emplace_back(company.a, company.b, company.c, company.d);\n        }\n        \n        return result;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    vector<tuple<int, int, int>> input;\n    for (int i = 0; i < n; i++) {\n        int x, y, r;\n        cin >> x >> y >> r;\n        input.emplace_back(x, y, r);\n    }\n    \n    AdaptiveRectanglePacker packer(n, input);\n    packer.solve();\n    \n    auto solution = packer.getSolution();\n    for (const auto& [a, b, c, d] : solution) {\n        cout << a << \" \" << b << \" \" << c << \" \" << d << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <array>\n#include <algorithm>\n#include <string>\n\nusing namespace std;\n\nconst int GRID_SIZE = 50;\nconst int MAX_PATH_LENGTH = 3000;\n\nstruct State {\n    int i, j;\n    int score;\n    string path;\n    vector<bool> visited_tiles;\n    \n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n    \n    bool operator>(const State& other) const {\n        return score > other.score;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<vector<int>> tile_id(GRID_SIZE, vector<int>(GRID_SIZE));\n    vector<vector<int>> values(GRID_SIZE, vector<int>(GRID_SIZE));\n    \n    // Read tile IDs\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            cin >> tile_id[i][j];\n        }\n    }\n    \n    // Read square values\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            cin >> values[i][j];\n        }\n    }\n    \n    // Find maximum tile ID\n    int max_tile = 0;\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            max_tile = max(max_tile, tile_id[i][j]);\n        }\n    }\n    int tile_count = max_tile + 1;\n    \n    // Precompute tile information\n    vector<int> tile_total_values(tile_count, 0);\n    vector<int> tile_sizes(tile_count, 0);\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            int tid = tile_id[i][j];\n            tile_total_values[tid] += values[i][j];\n            tile_sizes[tid]++;\n        }\n    }\n    \n    // Movement directions: Up, Down, Left, Right\n    array<pair<int, int>, 4> directions = {{\n        {-1, 0}, {1, 0}, {0, -1}, {0, 1}\n    }};\n    array<char, 4> dir_chars = {'U', 'D', 'L', 'R'};\n    \n    State best_overall;\n    best_overall.i = si;\n    best_overall.j = sj;\n    best_overall.score = values[si][sj];\n    best_overall.path = \"\";\n    best_overall.visited_tiles = vector<bool>(tile_count, false);\n    best_overall.visited_tiles[tile_id[si][sj]] = true;\n    \n    // Multiple strategies with optimized parameters\n    vector<pair<int, string>> strategies = {\n        {250, \"basic\"},      // Wide beam, basic search\n        {180, \"tile_value\"}, // Medium beam, tile value focus\n        {150, \"exploration\"} // Narrow beam, exploration focus\n    };\n    \n    for (const auto& [beam_width, strategy] : strategies) {\n        // Initial state\n        State initial;\n        initial.i = si;\n        initial.j = sj;\n        initial.score = values[si][sj];\n        initial.path = \"\";\n        initial.visited_tiles = vector<bool>(tile_count, false);\n        initial.visited_tiles[tile_id[si][sj]] = true;\n        \n        priority_queue<State, vector<State>, greater<State>> current_beam;\n        current_beam.push(initial);\n        \n        for (int step = 0; step < MAX_PATH_LENGTH && !current_beam.empty(); step++) {\n            vector<State> next_states;\n            \n            // Process current beam\n            while (!current_beam.empty()) {\n                State current = current_beam.top();\n                current_beam.pop();\n                \n                // Try all possible moves\n                for (int d = 0; d < 4; d++) {\n                    int ni = current.i + directions[d].first;\n                    int nj = current.j + directions[d].second;\n                    \n                    // Check bounds\n                    if (ni < 0 || ni >= GRID_SIZE || nj < 0 || nj >= GRID_SIZE) {\n                        continue;\n                    }\n                    \n                    // Check if tile already visited\n                    int next_tile = tile_id[ni][nj];\n                    if (current.visited_tiles[next_tile]) {\n                        continue;\n                    }\n                    \n                    // Create new state\n                    State new_state = current;\n                    new_state.i = ni;\n                    new_state.j = nj;\n                    new_state.score += values[ni][nj];\n                    new_state.path += dir_chars[d];\n                    new_state.visited_tiles[next_tile] = true;\n                    \n                    // Apply strategy-specific prioritization (temporary for beam selection)\n                    int temp_score_boost = 0;\n                    if (strategy == \"tile_value\") {\n                        // Prefer moves that lead to high-value tiles\n                        temp_score_boost = tile_total_values[next_tile] / (100 * max(1, tile_sizes[next_tile]));\n                    } else if (strategy == \"exploration\") {\n                        // Prefer moves that explore new areas\n                        int unvisited_neighbors = 0;\n                        for (int d2 = 0; d2 < 4; d2++) {\n                            int nni = ni + directions[d2].first;\n                            int nnj = nj + directions[d2].second;\n                            if (nni >= 0 && nni < GRID_SIZE && nnj >= 0 && nnj < GRID_SIZE) {\n                                int neighbor_tile = tile_id[nni][nnj];\n                                if (!new_state.visited_tiles[neighbor_tile]) {\n                                    unvisited_neighbors++;\n                                }\n                            }\n                        }\n                        temp_score_boost = unvisited_neighbors * 2;\n                    }\n                    \n                    // Store temporary boosted score for beam selection\n                    new_state.score += temp_score_boost;\n                    next_states.push_back(new_state);\n                    \n                    // Update best overall state with actual score\n                    State best_candidate = new_state;\n                    best_candidate.score -= temp_score_boost;\n                    if (best_candidate.score > best_overall.score) {\n                        best_overall = best_candidate;\n                    }\n                }\n            }\n            \n            // If no moves possible, break\n            if (next_states.empty()) {\n                break;\n            }\n            \n            // Remove temporary boosts before final selection\n            for (auto& state : next_states) {\n                int temp_score_boost = 0;\n                if (strategy == \"tile_value\") {\n                    int current_tile = tile_id[state.i][state.j];\n                    temp_score_boost = tile_total_values[current_tile] / (100 * max(1, tile_sizes[current_tile]));\n                } else if (strategy == \"exploration\") {\n                    int unvisited_neighbors = 0;\n                    for (int d2 = 0; d2 < 4; d2++) {\n                        int nni = state.i + directions[d2].first;\n                        int nnj = state.j + directions[d2].second;\n                        if (nni >= 0 && nni < GRID_SIZE && nnj >= 0 && nnj < GRID_SIZE) {\n                            int neighbor_tile = tile_id[nni][nnj];\n                            if (!state.visited_tiles[neighbor_tile]) {\n                                unvisited_neighbors++;\n                            }\n                        }\n                    }\n                    temp_score_boost = unvisited_neighbors * 2;\n                }\n                state.score -= temp_score_boost;\n            }\n            \n            // Sort by actual score and keep top states\n            sort(next_states.begin(), next_states.end(), greater<State>());\n            \n            if (next_states.size() > beam_width) {\n                next_states.resize(beam_width);\n            }\n            \n            // Re-apply boosts for next beam selection\n            for (auto& state : next_states) {\n                int temp_score_boost = 0;\n                if (strategy == \"tile_value\") {\n                    int current_tile = tile_id[state.i][state.j];\n                    temp_score_boost = tile_total_values[current_tile] / (100 * max(1, tile_sizes[current_tile]));\n                } else if (strategy == \"exploration\") {\n                    int unvisited_neighbors = 0;\n                    for (int d2 = 0; d2 < 4; d2++) {\n                        int nni = state.i + directions[d2].first;\n                        int nnj = state.j + directions[d2].second;\n                        if (nni >= 0 && nni < GRID_SIZE && nnj >= 0 && nnj < GRID_SIZE) {\n                            int neighbor_tile = tile_id[nni][nnj];\n                            if (!state.visited_tiles[neighbor_tile]) {\n                                unvisited_neighbors++;\n                            }\n                        }\n                    }\n                    temp_score_boost = unvisited_neighbors * 2;\n                }\n                state.score += temp_score_boost;\n            }\n            \n            // Add to next beam\n            for (const auto& state : next_states) {\n                current_beam.push(state);\n            }\n        }\n    }\n    \n    // Final extension with simple greedy approach\n    State final_state = best_overall;\n    bool improved = true;\n    int extension_steps = 0;\n    const int MAX_EXTENSION = 200;\n    \n    while (improved && extension_steps < MAX_EXTENSION) {\n        improved = false;\n        vector<State> candidates;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = final_state.i + directions[d].first;\n            int nj = final_state.j + directions[d].second;\n            \n            if (ni < 0 || ni >= GRID_SIZE || nj < 0 || nj >= GRID_SIZE) {\n                continue;\n            }\n            \n            int next_tile = tile_id[ni][nj];\n            if (final_state.visited_tiles[next_tile]) {\n                continue;\n            }\n            \n            State candidate = final_state;\n            candidate.i = ni;\n            candidate.j = nj;\n            candidate.score += values[ni][nj];\n            candidate.path += dir_chars[d];\n            candidate.visited_tiles[next_tile] = true;\n            candidates.push_back(candidate);\n        }\n        \n        if (!candidates.empty()) {\n            // Find the candidate with highest score\n            auto best_candidate = max_element(candidates.begin(), candidates.end(),\n                                            [](const State& a, const State& b) {\n                                                return a.score < b.score;\n                                            });\n            \n            if (best_candidate->score > final_state.score) {\n                final_state = *best_candidate;\n                improved = true;\n                extension_steps++;\n            }\n        }\n    }\n    \n    if (final_state.score > best_overall.score) {\n        best_overall = final_state;\n    }\n    \n    cout << best_overall.path << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nconst double INIT_WEIGHT = 5000.0;\nconst double MIN_WEIGHT = 1000.0;\nconst double MAX_WEIGHT = 9000.0;\n\ndouble horizontal[N][N-1];\ndouble vertical[N-1][N];\nint horizontal_count[N][N-1] = {0};\nint vertical_count[N-1][N] = {0};\n\nstruct Node {\n    int i, j;\n    double cost;\n    bool operator<(const Node& other) const {\n        return cost > other.cost;\n    }\n};\n\nstring reconstruct_path(pair<int,int> parent[N][N], int si, int sj, int ti, int tj) {\n    string path = \"\";\n    int i = ti, j = tj;\n    \n    while (i != si || j != sj) {\n        int pi = parent[i][j].first;\n        int pj = parent[i][j].second;\n        \n        if (pi == i) {\n            if (pj < j) path += 'R';\n            else path += 'L';\n        } else {\n            if (pi < i) path += 'D';\n            else path += 'U';\n        }\n        i = pi;\n        j = pj;\n    }\n    \n    reverse(path.begin(), path.end());\n    return path;\n}\n\nstring find_path(int si, int sj, int ti, int tj) {\n    double dist[N][N];\n    pair<int,int> parent[N][N];\n    bool visited[N][N] = {false};\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            dist[i][j] = 1e18;\n        }\n    }\n    \n    dist[si][sj] = 0;\n    priority_queue<Node> pq;\n    pq.push({si, sj, 0});\n    \n    int dx[4] = {-1, 1, 0, 0};\n    int dy[4] = {0, 0, -1, 1};\n    \n    while (!pq.empty()) {\n        auto [i, j, cost] = pq.top();\n        pq.pop();\n        \n        if (visited[i][j]) continue;\n        visited[i][j] = true;\n        \n        if (i == ti && j == tj) break;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + dx[d];\n            int nj = j + dy[d];\n            \n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            \n            double edge_cost;\n            if (dx[d] != 0) { // vertical move\n                int edge_i = min(i, ni);\n                edge_cost = vertical[edge_i][j];\n            } else { // horizontal move\n                int edge_j = min(j, nj);\n                edge_cost = horizontal[i][edge_j];\n            }\n            \n            double new_cost = dist[i][j] + edge_cost;\n            if (new_cost < dist[ni][nj]) {\n                dist[ni][nj] = new_cost;\n                parent[ni][nj] = {i, j};\n                double heuristic = abs(ni - ti) + abs(nj - tj);\n                pq.push({ni, nj, new_cost + heuristic * MIN_WEIGHT});\n            }\n        }\n    }\n    \n    return reconstruct_path(parent, si, sj, ti, tj);\n}\n\nstring find_exploratory_path(int si, int sj, int ti, int tj, int query_index) {\n    // Final fine-tuned exploration strategy\n    bool should_explore = false;\n    if (query_index < 360) {\n        should_explore = (query_index % 6 == 0) || (query_index < 190 && query_index % 3 == 0);\n    } else if (query_index < 660) {\n        should_explore = (query_index % 11 == 0);\n    } else {\n        should_explore = (query_index % 18 == 0);\n    }\n    \n    if (should_explore) {\n        double dist[N][N];\n        pair<int,int> parent[N][N];\n        bool visited[N][N] = {false};\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                dist[i][j] = 1e18;\n            }\n        }\n        \n        dist[si][sj] = 0;\n        priority_queue<Node> pq;\n        pq.push({si, sj, 0});\n        \n        int dx[4] = {-1, 1, 0, 0};\n        int dy[4] = {0, 0, -1, 1};\n        \n        while (!pq.empty()) {\n            auto [i, j, cost] = pq.top();\n            pq.pop();\n            \n            if (visited[i][j]) continue;\n            visited[i][j] = true;\n            \n            if (i == ti && j == tj) break;\n            \n            for (int d = 0; d < 4; d++) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                \n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                \n                double edge_cost;\n                double exploration_bonus = 0.0;\n                \n                if (dx[d] != 0) { // vertical move\n                    int edge_i = min(i, ni);\n                    edge_cost = vertical[edge_i][j];\n                    if (vertical_count[edge_i][j] < 11) {\n                        exploration_bonus = 1150.0 * (1.0 - vertical_count[edge_i][j] / 13.0);\n                    }\n                } else { // horizontal move\n                    int edge_j = min(j, nj);\n                    edge_cost = horizontal[i][edge_j];\n                    if (horizontal_count[i][edge_j] < 11) {\n                        exploration_bonus = 1150.0 * (1.0 - horizontal_count[i][edge_j] / 13.0);\n                    }\n                }\n                \n                double new_cost = dist[i][j] + edge_cost - exploration_bonus;\n                if (new_cost < dist[ni][nj]) {\n                    dist[ni][nj] = new_cost;\n                    parent[ni][nj] = {i, j};\n                    double heuristic = abs(ni - ti) + abs(nj - tj);\n                    pq.push({ni, nj, new_cost + heuristic * MIN_WEIGHT});\n                }\n            }\n        }\n        \n        return reconstruct_path(parent, si, sj, ti, tj);\n    }\n    \n    return find_path(si, sj, ti, tj);\n}\n\ndouble calculate_estimated_length(const string& path, int si, int sj) {\n    double length = 0;\n    int i = si, j = sj;\n    \n    for (char move : path) {\n        if (move == 'U') {\n            length += vertical[i-1][j];\n            i--;\n        } else if (move == 'D') {\n            length += vertical[i][j];\n            i++;\n        } else if (move == 'L') {\n            length += horizontal[i][j-1];\n            j--;\n        } else if (move == 'R') {\n            length += horizontal[i][j];\n            j++;\n        }\n    }\n    \n    return length;\n}\n\nvoid ultra_smoothing(int query_index) {\n    // Ultra-fine-tuned smoothing parameters\n    double smoothing_strength;\n    if (query_index < 470) {\n        smoothing_strength = 0.105;\n    } else if (query_index < 770) {\n        smoothing_strength = 0.068;\n    } else {\n        smoothing_strength = 0.042;\n    }\n    \n    // Horizontal edges - row-wise smoothing\n    for (int i = 0; i < N; i++) {\n        double row_sum = 0.0;\n        int valid_count = 0;\n        for (int j = 0; j < N-1; j++) {\n            if (horizontal_count[i][j] > 0) {\n                row_sum += horizontal[i][j];\n                valid_count++;\n            }\n        }\n        \n        if (valid_count > 5) {\n            double row_avg = row_sum / valid_count;\n            for (int j = 0; j < N-1; j++) {\n                double confidence = min(1.0, horizontal_count[i][j] / 14.0);\n                double effective_smoothing = smoothing_strength * (1.0 - confidence * 0.55);\n                horizontal[i][j] = (1 - effective_smoothing) * horizontal[i][j] + effective_smoothing * row_avg;\n                horizontal[i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][j]));\n            }\n        }\n    }\n    \n    // Vertical edges - column-wise smoothing\n    for (int j = 0; j < N; j++) {\n        double col_sum = 0.0;\n        int valid_count = 0;\n        for (int i = 0; i < N-1; i++) {\n            if (vertical_count[i][j] > 0) {\n                col_sum += vertical[i][j];\n                valid_count++;\n            }\n        }\n        \n        if (valid_count > 5) {\n            double col_avg = col_sum / valid_count;\n            for (int i = 0; i < N-1; i++) {\n                double confidence = min(1.0, vertical_count[i][j] / 14.0);\n                double effective_smoothing = smoothing_strength * (1.0 - confidence * 0.55);\n                vertical[i][j] = (1 - effective_smoothing) * vertical[i][j] + effective_smoothing * col_avg;\n                vertical[i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[i][j]));\n            }\n        }\n    }\n}\n\nvoid update_weights(const string& path, int si, int sj, double observed_length, int query_index) {\n    double estimated_length = calculate_estimated_length(path, si, sj);\n    double ratio = observed_length / estimated_length;\n    \n    // Ultra-fine-tuned learning rate schedule\n    double base_learning_rate;\n    if (query_index < 290) {\n        base_learning_rate = 0.265;\n    } else if (query_index < 540) {\n        base_learning_rate = 0.192;\n    } else if (query_index < 790) {\n        base_learning_rate = 0.128;\n    } else {\n        base_learning_rate = 0.088;\n    }\n    \n    int i = si, j = sj;\n    for (char move : path) {\n        if (move == 'U') {\n            int edge_i = i-1;\n            vertical_count[edge_i][j]++;\n            double alpha = base_learning_rate / (1 + sqrt(vertical_count[edge_i][j] * 0.62));\n            vertical[edge_i][j] *= (1 + alpha * (ratio - 1));\n            vertical[edge_i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[edge_i][j]));\n            i--;\n        } else if (move == 'D') {\n            int edge_i = i;\n            vertical_count[edge_i][j]++;\n            double alpha = base_learning_rate / (1 + sqrt(vertical_count[edge_i][j] * 0.62));\n            vertical[edge_i][j] *= (1 + alpha * (ratio - 1));\n            vertical[edge_i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[edge_i][j]));\n            i++;\n        } else if (move == 'L') {\n            int edge_j = j-1;\n            horizontal_count[i][edge_j]++;\n            double alpha = base_learning_rate / (1 + sqrt(horizontal_count[i][edge_j] * 0.62));\n            horizontal[i][edge_j] *= (1 + alpha * (ratio - 1));\n            horizontal[i][edge_j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][edge_j]));\n            j--;\n        } else if (move == 'R') {\n            int edge_j = j;\n            horizontal_count[i][edge_j]++;\n            double alpha = base_learning_rate / (1 + sqrt(horizontal_count[i][edge_j] * 0.62));\n            horizontal[i][edge_j] *= (1 + alpha * (ratio - 1));\n            horizontal[i][edge_j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][edge_j]));\n            j++;\n        }\n    }\n    \n    // Apply ultra smoothing\n    if (query_index % 13 == 0) {\n        ultra_smoothing(query_index);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Initialize edge weights\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N-1; j++) {\n            horizontal[i][j] = INIT_WEIGHT;\n        }\n    }\n    for (int i = 0; i < N-1; i++) {\n        for (int j = 0; j < N; j++) {\n            vertical[i][j] = INIT_WEIGHT;\n        }\n    }\n    \n    for (int k = 0; k < 1000; k++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        string path = find_exploratory_path(si, sj, ti, tj, k);\n        cout << path << endl;\n        cout.flush();\n        \n        int observed_length;\n        cin >> observed_length;\n        \n        update_weights(path, si, sj, observed_length, k);\n    }\n    \n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nbool is_substring_circular(const string& str, const string& sub) {\n    int n = str.size();\n    int L = sub.size();\n    for (int start = 0; start < n; start++) {\n        bool match = true;\n        for (int p = 0; p < L; p++) {\n            if (str[(start + p) % n] != sub[p]) {\n                match = false;\n                break;\n            }\n        }\n        if (match) return true;\n    }\n    return false;\n}\n\nvector<bool> get_matched_sequences_horizontal(const vector<string>& matrix, int i, const vector<string>& sequences) {\n    int n = matrix.size();\n    string row_str;\n    for (int j = 0; j < n; j++) {\n        row_str += matrix[i][j];\n    }\n    vector<bool> matched(sequences.size(), false);\n    for (int idx = 0; idx < sequences.size(); idx++) {\n        matched[idx] = is_substring_circular(row_str, sequences[idx]);\n    }\n    return matched;\n}\n\nvector<bool> get_matched_sequences_vertical(const vector<string>& matrix, int j, const vector<string>& sequences) {\n    int n = matrix.size();\n    string col_str;\n    for (int i = 0; i < n; i++) {\n        col_str += matrix[i][j];\n    }\n    vector<bool> matched(sequences.size(), false);\n    for (int idx = 0; idx < sequences.size(); idx++) {\n        matched[idx] = is_substring_circular(col_str, sequences[idx]);\n    }\n    return matched;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    cin >> N >> M;\n    vector<string> sequences(M);\n    for (int i = 0; i < M; i++) {\n        cin >> sequences[i];\n    }\n    \n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> char_dist(0, 7);\n    uniform_int_distribution<int> pos_dist(0, N-1);\n    uniform_real_distribution<double> prob_dist(0.0, 1.0);\n    \n    vector<int> freq(8, 0);\n    int total_chars = 0;\n    for (const auto& s : sequences) {\n        for (char c : s) {\n            freq[c - 'A']++;\n            total_chars++;\n        }\n    }\n    \n    vector<char> char_pool;\n    for (int i = 0; i < 8; i++) {\n        int count = (freq[i] * N * N) / total_chars;\n        for (int j = 0; j < count; j++) {\n            char_pool.push_back('A' + i);\n        }\n    }\n    \n    while (char_pool.size() < N * N) {\n        int max_freq = 0;\n        int max_idx = 0;\n        for (int i = 0; i < 8; i++) {\n            if (freq[i] > max_freq) {\n                max_freq = freq[i];\n                max_idx = i;\n            }\n        }\n        char_pool.push_back('A' + max_idx);\n    }\n    \n    shuffle(char_pool.begin(), char_pool.end(), gen);\n    \n    vector<string> matrix(N, string(N, ' '));\n    int idx = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            matrix[i][j] = char_pool[idx++];\n        }\n    }\n    \n    vector<int> horiz_count(M, 0);\n    vector<int> vert_count(M, 0);\n    int c = 0;\n    \n    for (int i = 0; i < N; i++) {\n        vector<bool> matched = get_matched_sequences_horizontal(matrix, i, sequences);\n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (matched[s_idx]) {\n                horiz_count[s_idx]++;\n            }\n        }\n    }\n    \n    for (int j = 0; j < N; j++) {\n        vector<bool> matched = get_matched_sequences_vertical(matrix, j, sequences);\n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (matched[s_idx]) {\n                vert_count[s_idx]++;\n            }\n        }\n    }\n    \n    for (int s_idx = 0; s_idx < M; s_idx++) {\n        if (horiz_count[s_idx] > 0 || vert_count[s_idx] > 0) {\n            c++;\n        }\n    }\n    \n    int iterations = 5000;\n    double initial_temp = 1.0;\n    double cooling_rate = 0.999;\n    \n    for (int iter = 0; iter < iterations; iter++) {\n        double temp = initial_temp * pow(cooling_rate, iter);\n        \n        int i = pos_dist(gen);\n        int j = pos_dist(gen);\n        char old_ch = matrix[i][j];\n        char new_ch;\n        do {\n            new_ch = 'A' + char_dist(gen);\n        } while (new_ch == old_ch);\n        \n        vector<int> saved_horiz_count = horiz_count;\n        vector<int> saved_vert_count = vert_count;\n        int saved_c = c;\n        \n        vector<bool> S_old_row = get_matched_sequences_horizontal(matrix, i, sequences);\n        vector<bool> S_old_col = get_matched_sequences_vertical(matrix, j, sequences);\n        \n        matrix[i][j] = new_ch;\n        \n        vector<bool> S_new_row = get_matched_sequences_horizontal(matrix, i, sequences);\n        vector<bool> S_new_col = get_matched_sequences_vertical(matrix, j, sequences);\n        \n        int new_c = saved_c;\n        \n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (S_old_row[s_idx] && !S_new_row[s_idx]) {\n                if (horiz_count[s_idx] == 1 && vert_count[s_idx] == 0) {\n                    new_c--;\n                }\n                horiz_count[s_idx]--;\n            }\n            if (!S_old_row[s_idx] && S_new_row[s_idx]) {\n                horiz_count[s_idx]++;\n                if (horiz_count[s_idx] == 1 && vert_count[s_idx] == 0) {\n                    new_c++;\n                }\n            }\n        }\n        \n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (S_old_col[s_idx] && !S_new_col[s_idx]) {\n                if (vert_count[s_idx] == 1 && horiz_count[s_idx] == 0) {\n                    new_c--;\n                }\n                vert_count[s_idx]--;\n            }\n            if (!S_old_col[s_idx] && S_new_col[s_idx]) {\n                vert_count[s_idx]++;\n                if (vert_count[s_idx] == 1 && horiz_count[s_idx] == 0) {\n                    new_c++;\n                }\n            }\n        }\n        \n        double delta_c = new_c - saved_c;\n        if (delta_c > 0 || prob_dist(gen) < exp(delta_c / temp)) {\n            c = new_c;\n        } else {\n            matrix[i][j] = old_ch;\n            horiz_count = saved_horiz_count;\n            vert_count = saved_vert_count;\n            c = saved_c;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << matrix[i] << '\\n';\n    }\n    \n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <stack>\n#include <queue>\n#include <string>\n#include <tuple>\n\nusing namespace std;\n\nclass UnionFind {\npublic:\n    vector<int> parent;\n    UnionFind(int n) {\n        parent.resize(n);\n        for (int i = 0; i < n; i++) {\n            parent[i] = i;\n        }\n    }\n    int find(int x) {\n        if (parent[x] != x) {\n            parent[x] = find(parent[x]);\n        }\n        return parent[x];\n    }\n    void unite(int x, int y) {\n        x = find(x);\n        y = find(y);\n        if (x != y) {\n            parent[x] = y;\n        }\n    }\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n\n    vector<pair<int, int>> points;\n    map<pair<int, int>, int> point_to_index;\n    vector<int> costs;\n    int index = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                points.push_back({i, j});\n                int cost = grid[i][j] - '0';\n                costs.push_back(cost);\n                point_to_index[{i, j}] = index;\n                index++;\n            }\n        }\n    }\n    int V = points.size();\n    if (V == 0) {\n        cout << \"\" << endl;\n        return 0;\n    }\n\n    vector<tuple<int, int, int>> edges;\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    for (int i = 0; i < V; i++) {\n        int x = points[i].first;\n        int y = points[i].second;\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d];\n            int ny = y + dy[d];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] != '#') {\n                int j = point_to_index[{nx, ny}];\n                int w = costs[i] + costs[j];\n                edges.push_back({i, j, w});\n            }\n        }\n    }\n\n    sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {\n        return get<2>(a) < get<2>(b);\n    });\n\n    UnionFind uf(V);\n    vector<vector<int>> mst_graph(V);\n    for (const auto& edge : edges) {\n        int u = get<0>(edge);\n        int v = get<1>(edge);\n        if (!uf.same(u, v)) {\n            uf.unite(u, v);\n            mst_graph[u].push_back(v);\n            mst_graph[v].push_back(u);\n        }\n    }\n\n    int start_index = point_to_index[{si, sj}];\n    vector<vector<int>> children(V);\n    vector<bool> visited(V, false);\n    queue<int> q;\n    q.push(start_index);\n    visited[start_index] = true;\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        for (int v : mst_graph[u]) {\n            if (!visited[v]) {\n                visited[v] = true;\n                children[u].push_back(v);\n                q.push(v);\n            }\n        }\n    }\n\n    vector<int> nextChild(V, 0);\n    stack<int> st;\n    string path;\n    int current = start_index;\n    while (true) {\n        if (nextChild[current] < children[current].size()) {\n            int child = children[current][nextChild[current]];\n            nextChild[current]++;\n            int x1 = points[current].first;\n            int y1 = points[current].second;\n            int x2 = points[child].first;\n            int y2 = points[child].second;\n            if (x2 == x1 - 1) path += 'U';\n            else if (x2 == x1 + 1) path += 'D';\n            else if (y2 == y1 - 1) path += 'L';\n            else if (y2 == y1 + 1) path += 'R';\n            st.push(current);\n            current = child;\n        } else {\n            if (st.empty()) break;\n            int parent = st.top();\n            st.pop();\n            int x1 = points[current].first;\n            int y1 = points[current].second;\n            int x2 = points[parent].first;\n            int y2 = points[parent].second;\n            if (x2 == x1 - 1) path += 'U';\n            else if (x2 == x1 + 1) path += 'D';\n            else if (y2 == y1 - 1) path += 'L';\n            else if (y2 == y1 + 1) path += 'R';\n            current = parent;\n        }\n    }\n\n    cout << path << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nenum Status {\n    NOT_STARTED = 0,\n    ASSIGNED = 1,\n    COMPLETED = 2\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<vector<int>> task_difficulty(N+1, vector<int>(K));\n    for (int i=1; i<=N; i++) {\n        for (int j=0; j<K; j++) {\n            cin >> task_difficulty[i][j];\n        }\n    }\n\n    vector<vector<int>> succ_graph(N+1);\n    vector<vector<int>> prereqs(N+1);\n    for (int i=0; i<R; i++) {\n        int u, v;\n        cin >> u >> v;\n        succ_graph[u].push_back(v);\n        prereqs[v].push_back(u);\n    }\n\n    // Precompute descendant counts\n    vector<int> desc_count(N+1, 0);\n    for (int i=1; i<=N; i++) {\n        vector<bool> visited(N+1, false);\n        queue<int> q;\n        q.push(i);\n        visited[i] = true;\n        int count = 0;\n        while (!q.empty()) {\n            int u = q.front(); q.pop();\n            count++;\n            for (int v : succ_graph[u]) {\n                if (!visited[v]) {\n                    visited[v] = true;\n                    q.push(v);\n                }\n            }\n        }\n        desc_count[i] = count;\n    }\n\n    // Initialize arrays\n    vector<Status> task_status(N+1, NOT_STARTED);\n    vector<int> member_task(M+1, -1); // -1 means idle\n    vector<int> member_start_day(M+1, 0);\n    vector<vector<double>> s_est(M+1, vector<double>(K, 40.0)); // initial skill estimate 40\n\n    vector<int> unfinished_prereqs(N+1, 0);\n    for (int i=1; i<=N; i++) {\n        unfinished_prereqs[i] = prereqs[i].size();\n    }\n\n    int current_day = 1;\n    while (true) {\n        // Identify available tasks and members\n        vector<int> available_tasks;\n        for (int i=1; i<=N; i++) {\n            if (task_status[i] == NOT_STARTED && unfinished_prereqs[i] == 0) {\n                available_tasks.push_back(i);\n            }\n        }\n\n        vector<int> available_members;\n        for (int j=1; j<=M; j++) {\n            if (member_task[j] == -1) {\n                available_members.push_back(j);\n            }\n        }\n\n        // Sort available tasks by descendant count descending\n        sort(available_tasks.begin(), available_tasks.end(), [&](int a, int b) {\n            return desc_count[a] > desc_count[b];\n        });\n\n        vector<pair<int, int>> assignments;\n        for (int task : available_tasks) {\n            if (available_members.empty()) break;\n            int best_member = -1;\n            double best_est_t = 1e9;\n\n            // Function to compute estimated time for task and member\n            auto compute_est_t = [&](int t, int m) {\n                double w = 0.0;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[t][k] > s_est[m][k]) {\n                        w += task_difficulty[t][k] - s_est[m][k];\n                    }\n                }\n                if (w == 0) return 1.0;\n                else return w;\n            };\n\n            for (int member : available_members) {\n                double est_t = compute_est_t(task, member);\n                if (est_t < best_est_t) {\n                    best_est_t = est_t;\n                    best_member = member;\n                }\n            }\n\n            if (best_member != -1) {\n                assignments.push_back({best_member, task});\n                task_status[task] = ASSIGNED;\n                member_task[best_member] = task;\n                member_start_day[best_member] = current_day;\n                // Remove the member from available_members\n                auto it = find(available_members.begin(), available_members.end(), best_member);\n                available_members.erase(it);\n            }\n        }\n\n        // Output assignments\n        cout << assignments.size();\n        for (auto& ass : assignments) {\n            cout << \" \" << ass.first << \" \" << ass.second;\n        }\n        cout << endl;\n        cout.flush();\n\n        // Read input for the day\n        int n;\n        cin >> n;\n        if (n == -1) {\n            break;\n        }\n\n        vector<int> completed_members(n);\n        for (int i=0; i<n; i++) {\n            cin >> completed_members[i];\n        }\n\n        // Process completed members\n        for (int j : completed_members) {\n            int task = member_task[j];\n            if (task == -1) continue; // Should not happen\n            int start_day = member_start_day[j];\n            int t = current_day - start_day + 1;\n\n            // Update skill estimates\n            if (t == 1) {\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        s_est[j][k] = task_difficulty[task][k];\n                    }\n                }\n            } else {\n                double w_pred = 0.0;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        w_pred += task_difficulty[task][k] - s_est[j][k];\n                    }\n                }\n                double e = t - w_pred;\n                double alpha = 0.01;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        s_est[j][k] += 2 * alpha * e;\n                        if (s_est[j][k] < 0) s_est[j][k] = 0;\n                    }\n                }\n            }\n\n            // Update task and member status\n            task_status[task] = COMPLETED;\n            member_task[j] = -1;\n\n            // Update unfinished prerequisites for successors\n            for (int v : succ_graph[task]) {\n                unfinished_prereqs[v]--;\n            }\n        }\n\n        current_day++;\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <climits>\n\nusing namespace std;\n\nstruct RoutePoint {\n    int x, y;\n    int order_id; // -1 for depot\n    bool is_pickup; // true for pickup, false for dropoff\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint manhattan_pair(pair<int, int> p1, pair<int, int> p2) {\n    return abs(p1.first - p2.first) + abs(p1.second - p2.second);\n}\n\nint calculate_cost(const vector<RoutePoint>& route) {\n    int cost = 0;\n    for (int i = 0; i < route.size() - 1; i++) {\n        cost += manhattan(route[i].x, route[i].y, route[i+1].x, route[i+1].y);\n    }\n    return cost;\n}\n\nvector<RoutePoint> remove_order(const vector<RoutePoint>& route, int order_id) {\n    vector<RoutePoint> new_route;\n    for (const auto& point : route) {\n        if (point.order_id != order_id) {\n            new_route.push_back(point);\n        }\n    }\n    return new_route;\n}\n\nint main() {\n    int a[1000], b[1000], c[1000], d[1000];\n    for (int i = 0; i < 1000; i++) {\n        cin >> a[i] >> b[i] >> c[i] >> d[i];\n    }\n\n    vector<RoutePoint> route;\n    route.push_back({400, 400, -1, false});\n    route.push_back({400, 400, -1, false});\n\n    vector<bool> selected(1000, false);\n    int selected_count = 0;\n\n    while (selected_count < 50) {\n        int best_order = -1;\n        int best_i = -1, best_j = -1;\n        int best_cost_increase = INT_MAX;\n        int n = route.size();\n\n        for (int k = 0; k < 1000; k++) {\n            if (selected[k]) continue;\n            pair<int, int> P = {a[k], b[k]};\n            pair<int, int> Q = {c[k], d[k]};\n\n            for (int i = 0; i < n-1; i++) {\n                for (int j = i; j < n-1; j++) {\n                    int cost_increase = 0;\n                    if (i < j) {\n                        cost_increase = manhattan_pair(P, {route[i].x, route[i].y}) \n                                      + manhattan_pair(P, {route[i+1].x, route[i+1].y}) \n                                      - manhattan_pair({route[i].x, route[i].y}, {route[i+1].x, route[i+1].y})\n                                      + manhattan_pair(Q, {route[j].x, route[j].y}) \n                                      + manhattan_pair(Q, {route[j+1].x, route[j+1].y}) \n                                      - manhattan_pair({route[j].x, route[j].y}, {route[j+1].x, route[j+1].y});\n                    } else {\n                        cost_increase = manhattan_pair({route[i].x, route[i].y}, P) \n                                      + manhattan_pair(P, Q) \n                                      + manhattan_pair(Q, {route[i+1].x, route[i+1].y}) \n                                      - manhattan_pair({route[i].x, route[i].y}, {route[i+1].x, route[i+1].y});\n                    }\n                    if (cost_increase < best_cost_increase) {\n                        best_cost_increase = cost_increase;\n                        best_order = k;\n                        best_i = i;\n                        best_j = j;\n                    }\n                }\n            }\n        }\n\n        if (best_order == -1) break;\n\n        RoutePoint pickup = {a[best_order], b[best_order], best_order, true};\n        RoutePoint dropoff = {c[best_order], d[best_order], best_order, false};\n\n        vector<RoutePoint> new_route;\n        for (int i = 0; i <= best_i; i++) {\n            new_route.push_back(route[i]);\n        }\n        new_route.push_back(pickup);\n        for (int i = best_i+1; i <= best_j; i++) {\n            new_route.push_back(route[i]);\n        }\n        new_route.push_back(dropoff);\n        for (int i = best_j+1; i < n; i++) {\n            new_route.push_back(route[i]);\n        }\n        route = new_route;\n        selected[best_order] = true;\n        selected_count++;\n    }\n\n    int n = route.size();\n    int total_dist = calculate_cost(route);\n\n    vector<int> pickup_index(1000, -1);\n    vector<int> dropoff_index(1000, -1);\n    for (int i = 0; i < n; i++) {\n        int order_id = route[i].order_id;\n        if (order_id == -1) continue;\n        if (route[i].is_pickup) {\n            pickup_index[order_id] = i;\n        } else {\n            dropoff_index[order_id] = i;\n        }\n    }\n\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 0; i <= n-3; i++) {\n            for (int j = i+1; j <= n-2; j++) {\n                bool valid = true;\n                for (int k = 0; k < 1000; k++) {\n                    if (selected[k]) {\n                        int pi = pickup_index[k];\n                        int di = dropoff_index[k];\n                        if (pi >= i+1 && pi <= j && di >= i+1 && di <= j) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                }\n                if (!valid) continue;\n\n                int dist_before = manhattan(route[i].x, route[i].y, route[i+1].x, route[i+1].y)\n                                + manhattan(route[j].x, route[j].y, route[j+1].x, route[j+1].y);\n                int dist_after = manhattan(route[i].x, route[i].y, route[j].x, route[j].y)\n                               + manhattan(route[i+1].x, route[i+1].y, route[j+1].x, route[j+1].y);\n                if (dist_after < dist_before) {\n                    reverse(route.begin() + i + 1, route.begin() + j + 1);\n                    total_dist += dist_after - dist_before;\n                    improved = true;\n                    for (int idx = 0; idx < route.size(); idx++) {\n                        int order_id = route[idx].order_id;\n                        if (order_id == -1) continue;\n                        if (route[idx].is_pickup) {\n                            pickup_index[order_id] = idx;\n                        } else {\n                            dropoff_index[order_id] = idx;\n                        }\n                    }\n                }\n            }\n        }\n        n = route.size();\n    }\n\n    int max_reinsert_iter = 5;\n    improved = true;\n    for (int iter = 0; iter < max_reinsert_iter && improved; iter++) {\n        improved = false;\n        for (int k = 0; k < 1000; k++) {\n            if (!selected[k]) continue;\n            vector<RoutePoint> route_without = remove_order(route, k);\n            int cost_without = calculate_cost(route_without);\n            int best_cost = INT_MAX;\n            int best_i = -1, best_j = -1;\n            int n_new = route_without.size();\n            for (int i = 0; i < n_new - 1; i++) {\n                for (int j = i; j < n_new - 1; j++) {\n                    int cost_increase = 0;\n                    if (i < j) {\n                        cost_increase = manhattan(route_without[i].x, route_without[i].y, a[k], b[k])\n                                      + manhattan(a[k], b[k], route_without[i+1].x, route_without[i+1].y)\n                                      - manhattan(route_without[i].x, route_without[i].y, route_without[i+1].x, route_without[i+1].y)\n                                      + manhattan(route_without[j].x, route_without[j].y, c[k], d[k])\n                                      + manhattan(c[k], d[k], route_without[j+1].x, route_without[j+1].y)\n                                      - manhattan(route_without[j].x, route_without[j].y, route_without[j+1].x, route_without[j+1].y);\n                    } else {\n                        cost_increase = manhattan(route_without[i].x, route_without[i].y, a[k], b[k])\n                                      + manhattan(a[k], b[k], c[k], d[k])\n                                      + manhattan(c[k], d[k], route_without[i+1].x, route_without[i+1].y)\n                                      - manhattan(route_without[i].x, route_without[i].y, route_without[i+1].x, route_without[i+1].y);\n                    }\n                    int total_cost = cost_without + cost_increase;\n                    if (total_cost < best_cost) {\n                        best_cost = total_cost;\n                        best_i = i;\n                        best_j = j;\n                    }\n                }\n            }\n            if (best_cost < total_dist) {\n                RoutePoint pickup = {a[k], b[k], k, true};\n                RoutePoint dropoff = {c[k], d[k], k, false};\n                vector<RoutePoint> new_route = route_without;\n                if (best_i < best_j) {\n                    new_route.insert(new_route.begin() + best_i + 1, pickup);\n                    new_route.insert(new_route.begin() + best_j + 2, dropoff);\n                } else {\n                    new_route.insert(new_route.begin() + best_i + 1, pickup);\n                    new_route.insert(new_route.begin() + best_i + 2, dropoff);\n                }\n                route = new_route;\n                total_dist = best_cost;\n                improved = true;\n                for (int i = 0; i < route.size(); i++) {\n                    int order_id = route[i].order_id;\n                    if (order_id == -1) continue;\n                    if (route[i].is_pickup) {\n                        pickup_index[order_id] = i;\n                    } else {\n                        dropoff_index[order_id] = i;\n                    }\n                }\n            }\n        }\n        if (improved) {\n            n = route.size();\n            bool opt_improved = true;\n            while (opt_improved) {\n                opt_improved = false;\n                for (int i = 0; i <= n-3; i++) {\n                    for (int j = i+1; j <= n-2; j++) {\n                        bool valid = true;\n                        for (int k = 0; k < 1000; k++) {\n                            if (selected[k]) {\n                                int pi = pickup_index[k];\n                                int di = dropoff_index[k];\n                                if (pi >= i+1 && pi <= j && di >= i+1 && di <= j) {\n                                    valid = false;\n                                    break;\n                                }\n                            }\n                        }\n                        if (!valid) continue;\n                        int dist_before = manhattan(route[i].x, route[i].y, route[i+1].x, route[i+1].y)\n                                        + manhattan(route[j].x, route[j].y, route[j+1].x, route[j+1].y);\n                        int dist_after = manhattan(route[i].x, route[i].y, route[j].x, route[j].y)\n                                       + manhattan(route[i+1].x, route[i+1].y, route[j+1].x, route[j+1].y);\n                        if (dist_after < dist_before) {\n                            reverse(route.begin() + i + 1, route.begin() + j + 1);\n                            total_dist += dist_after - dist_before;\n                            opt_improved = true;\n                            for (int idx = 0; idx < route.size(); idx++) {\n                                int order_id = route[idx].order_id;\n                                if (order_id == -1) continue;\n                                if (route[idx].is_pickup) {\n                                    pickup_index[order_id] = idx;\n                                } else {\n                                    dropoff_index[order_id] = idx;\n                                }\n                            }\n                        }\n                    }\n                }\n                n = route.size();\n            }\n        }\n    }\n\n    cout << 50 << \" \";\n    for (int i = 0; i < 1000; i++) {\n        if (selected[i]) {\n            cout << i+1 << \" \";\n        }\n    }\n    cout << endl;\n\n    cout << route.size() << \" \";\n    for (auto &p : route) {\n        cout << p.x << \" \" << p.y << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <functional>\n#include <algorithm>\n#include <tuple>\n#include <numeric>\n\nusing namespace std;\n\nconst int N = 400;\nconst int M = 1995;\n\nint main() {\n    vector<double> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<pair<int, int>> edges(M);\n    for (int i = 0; i < M; i++) {\n        int u, v;\n        cin >> u >> v;\n        edges[i] = {u, v};\n    }\n\n    vector<int> d(M);\n    for (int i = 0; i < M; i++) {\n        int u = edges[i].first;\n        int v = edges[i].second;\n        double dx = x[u] - x[v];\n        double dy = y[u] - y[v];\n        double dist = sqrt(dx*dx + dy*dy);\n        d[i] = static_cast<int>(round(dist));\n    }\n\n    // Precompute MST based on Euclidean distances\n    vector<tuple<int, int, int, int>> edges_for_mst;\n    for (int i = 0; i < M; i++) {\n        edges_for_mst.push_back({d[i], edges[i].first, edges[i].second, i});\n    }\n    \n    sort(edges_for_mst.begin(), edges_for_mst.end());\n\n    vector<int> parent_mst(N);\n    iota(parent_mst.begin(), parent_mst.end(), 0);\n    \n    function<int(int)> find_mst = [&](int a) {\n        if (parent_mst[a] == a) return a;\n        return parent_mst[a] = find_mst(parent_mst[a]);\n    };\n\n    vector<bool> in_mst(M, false);\n    for (auto& edge : edges_for_mst) {\n        int u = get<1>(edge);\n        int v = get<2>(edge);\n        int idx = get<3>(edge);\n        \n        int pu = find_mst(u);\n        int pv = find_mst(v);\n        if (pu != pv) {\n            in_mst[idx] = true;\n            parent_mst[pu] = pv;\n        }\n    }\n\n    // Online processing\n    vector<int> parent(N);\n    iota(parent.begin(), parent.end(), 0);\n    \n    function<int(int)> find = [&](int a) {\n        if (parent[a] == a) return a;\n        return parent[a] = find(parent[a]);\n    };\n\n    auto unite = [&](int a, int b) {\n        a = find(a);\n        b = find(b);\n        if (a != b) {\n            parent[a] = b;\n            return true;\n        }\n        return false;\n    };\n\n    int num_components = N;\n\n    for (int i = 0; i < M; i++) {\n        int l_i;\n        cin >> l_i;\n\n        int u = edges[i].first;\n        int v = edges[i].second;\n\n        if (find(u) == find(v)) {\n            cout << 0 << endl;\n        } else {\n            bool adopt = false;\n            int remaining_edges = M - i - 1;\n            int needed_connections = num_components - 1;\n            \n            // Adaptive threshold calculation\n            double progress_ratio = (double)i / M;\n            double edge_supply_ratio = (remaining_edges > 0 && needed_connections > 0) \n                ? (double)remaining_edges / needed_connections \n                : 1.0;\n            \n            // Dynamic threshold: more selective when many edges remain\n            double adaptive_threshold = 2.0;\n            if (edge_supply_ratio > 2.0) {\n                // Many edges available - be more selective\n                adaptive_threshold = 1.8 + 0.2 * (1.0 / edge_supply_ratio);\n            } else if (edge_supply_ratio < 1.5) {\n                // Few edges available - be less selective\n                adaptive_threshold = 2.2;\n            }\n            \n            // Progress-based adjustment\n            adaptive_threshold += 0.1 * progress_ratio;\n            \n            // Decision criteria\n            if (in_mst[i]) {\n                adopt = true;\n            } else if (remaining_edges < needed_connections) {\n                adopt = true;\n            } else if (l_i <= adaptive_threshold * d[i]) {\n                adopt = true;\n            }\n            \n            if (adopt) {\n                cout << 1 << endl;\n                if (unite(u, v)) {\n                    num_components--;\n                }\n            } else {\n                cout << 0 << endl;\n            }\n        }\n        cout.flush();\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int MAX_TURNS = 300;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<tuple<int, int, int>> pets;\n    for (int i = 0; i < N; i++) {\n        int x, y, t;\n        cin >> x >> y >> t;\n        pets.push_back({x, y, t});\n    }\n    int M;\n    cin >> M;\n    vector<pair<int, int>> humans;\n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        humans.push_back({x, y});\n    }\n\n    vector<vector<bool>> blocked(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n    vector<pair<int, int>> wall_squares;\n    vector<pair<int, int>> base_squares;\n\n    for (int i = 1; i <= 20; i++) {\n        wall_squares.push_back({20, i});\n        base_squares.push_back({19, i});\n    }\n    for (int i = 1; i <= 19; i++) {\n        wall_squares.push_back({i, 20});\n        base_squares.push_back({i, 19});\n    }\n\n    int total_walls = wall_squares.size();\n    vector<vector<pair<int, int>>> human_wall_squares(M);\n    vector<vector<pair<int, int>>> human_base_squares(M);\n\n    for (int i = 0; i < total_walls; i++) {\n        int human_idx = i % M;\n        human_wall_squares[human_idx].push_back(wall_squares[i]);\n        human_base_squares[human_idx].push_back(base_squares[i]);\n    }\n\n    vector<int> human_target_index(M, 0);\n    vector<vector<bool>> wall_built(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n\n    for (int turn = 1; turn <= MAX_TURNS; turn++) {\n        vector<char> actions(M, '.');\n        set<pair<int, int>> blocks_this_turn;\n\n        // First pass: Decide block actions\n        for (int i = 0; i < M; i++) {\n            if (human_target_index[i] >= human_wall_squares[i].size()) {\n                continue;\n            }\n\n            pair<int, int> target_wall = human_wall_squares[i][human_target_index[i]];\n            pair<int, int> target_base = human_base_squares[i][human_target_index[i]];\n\n            if (wall_built[target_wall.first][target_wall.second]) {\n                human_target_index[i]++;\n                if (human_target_index[i] < human_wall_squares[i].size()) {\n                    target_wall = human_wall_squares[i][human_target_index[i]];\n                    target_base = human_base_squares[i][human_target_index[i]];\n                } else {\n                    continue;\n                }\n            }\n\n            if (humans[i] == target_base) {\n                bool can_block = true;\n\n                // Check if wall square is empty\n                for (auto& pet : pets) {\n                    if (get<0>(pet) == target_wall.first && get<1>(pet) == target_wall.second) {\n                        can_block = false;\n                        break;\n                    }\n                }\n                if (can_block) {\n                    for (int j = 0; j < M; j++) {\n                        if (humans[j].first == target_wall.first && humans[j].second == target_wall.second) {\n                            can_block = false;\n                            break;\n                        }\n                    }\n                }\n\n                // Check adjacent squares for pets\n                if (can_block) {\n                    int dx[] = {1, -1, 0, 0};\n                    int dy[] = {0, 0, 1, -1};\n                    for (int d = 0; d < 4; d++) {\n                        int nx = target_wall.first + dx[d];\n                        int ny = target_wall.second + dy[d];\n                        if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                        for (auto& pet : pets) {\n                            if (get<0>(pet) == nx && get<1>(pet) == ny) {\n                                can_block = false;\n                                break;\n                            }\n                        }\n                        if (!can_block) break;\n                    }\n                }\n\n                if (can_block) {\n                    int dx = target_wall.first - target_base.first;\n                    int dy = target_wall.second - target_base.second;\n                    char action;\n                    if (dx == 1) action = 'd';\n                    else if (dx == -1) action = 'u';\n                    else if (dy == 1) action = 'r';\n                    else if (dy == -1) action = 'l';\n                    else action = '.';\n                    actions[i] = action;\n                    blocks_this_turn.insert(target_wall);\n                }\n            }\n        }\n\n        // Second pass: Decide movement actions\n        for (int i = 0; i < M; i++) {\n            if (actions[i] != '.') continue; // Skip if already decided (block action)\n\n            if (human_target_index[i] >= human_wall_squares[i].size()) {\n                continue;\n            }\n\n            pair<int, int> target_wall = human_wall_squares[i][human_target_index[i]];\n            pair<int, int> target_base = human_base_squares[i][human_target_index[i]];\n\n            if (wall_built[target_wall.first][target_wall.second]) {\n                human_target_index[i]++;\n                if (human_target_index[i] < human_wall_squares[i].size()) {\n                    target_wall = human_wall_squares[i][human_target_index[i]];\n                    target_base = human_base_squares[i][human_target_index[i]];\n                } else {\n                    continue;\n                }\n            }\n\n            if (humans[i] != target_base) {\n                vector<vector<bool>> obstacles(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n                // Mark static obstacles\n                for (int x = 1; x <= GRID_SIZE; x++) {\n                    for (int y = 1; y <= GRID_SIZE; y++) {\n                        if (blocked[x][y]) obstacles[x][y] = true;\n                    }\n                }\n                // Mark blocks that will be placed this turn\n                for (auto& block : blocks_this_turn) {\n                    obstacles[block.first][block.second] = true;\n                }\n\n                queue<pair<int, int>> q;\n                vector<vector<int>> dist(GRID_SIZE + 1, vector<int>(GRID_SIZE + 1, -1));\n                vector<vector<pair<int, int>>> prev(GRID_SIZE + 1, vector<pair<int, int>>(GRID_SIZE + 1, {-1, -1}));\n                int start_x = humans[i].first;\n                int start_y = humans[i].second;\n                dist[start_x][start_y] = 0;\n                q.push({start_x, start_y});\n\n                int dx[] = {1, -1, 0, 0};\n                int dy[] = {0, 0, 1, -1};\n\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d];\n                        int ny = y + dy[d];\n                        if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                        if (obstacles[nx][ny]) continue;\n                        if (dist[nx][ny] == -1) {\n                            dist[nx][ny] = dist[x][y] + 1;\n                            prev[nx][ny] = {x, y};\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n\n                if (dist[target_base.first][target_base.second] != -1) {\n                    vector<pair<int, int>> path;\n                    pair<int, int> cur = target_base;\n                    while (cur != make_pair(start_x, start_y)) {\n                        path.push_back(cur);\n                        cur = prev[cur.first][cur.second];\n                    }\n                    reverse(path.begin(), path.end());\n                    if (!path.empty()) {\n                        pair<int, int> first_step = path[0];\n                        int dx = first_step.first - start_x;\n                        int dy = first_step.second - start_y;\n                        char action;\n                        if (dx == 1) action = 'D';\n                        else if (dx == -1) action = 'U';\n                        else if (dy == 1) action = 'R';\n                        else if (dy == -1) action = 'L';\n                        else action = '.';\n                        actions[i] = action;\n                    }\n                }\n            }\n        }\n\n        string action_str;\n        for (int i = 0; i < M; i++) {\n            action_str += actions[i];\n        }\n        cout << action_str << endl;\n        cout.flush();\n\n        // Update state based on actions\n        for (int i = 0; i < M; i++) {\n            char action = actions[i];\n            if (action == 'u' || action == 'd' || action == 'l' || action == 'r') {\n                int x = humans[i].first;\n                int y = humans[i].second;\n                int block_x, block_y;\n                if (action == 'u') block_x = x - 1, block_y = y;\n                else if (action == 'd') block_x = x + 1, block_y = y;\n                else if (action == 'l') block_x = x, block_y = y - 1;\n                else if (action == 'r') block_x = x, block_y = y + 1;\n\n                if (block_x >= 1 && block_x <= GRID_SIZE && block_y >= 1 && block_y <= GRID_SIZE) {\n                    blocked[block_x][block_y] = true;\n                    wall_built[block_x][block_y] = true;\n                }\n            }\n        }\n\n        // Update human positions\n        for (int i = 0; i < M; i++) {\n            char action = actions[i];\n            if (action == 'U') humans[i].first--;\n            else if (action == 'D') humans[i].first++;\n            else if (action == 'L') humans[i].second--;\n            else if (action == 'R') humans[i].second++;\n        }\n\n        // Read and update pet positions\n        vector<string> pet_movements(N);\n        for (int i = 0; i < N; i++) {\n            cin >> pet_movements[i];\n        }\n\n        for (int i = 0; i < N; i++) {\n            string moves = pet_movements[i];\n            int x = get<0>(pets[i]);\n            int y = get<1>(pets[i]);\n            for (char move : moves) {\n                if (move == 'U') x--;\n                else if (move == 'D') x++;\n                else if (move == 'L') y--;\n                else if (move == 'R') y++;\n            }\n            get<0>(pets[i]) = x;\n            get<1>(pets[i]) = y;\n        }\n    }\n\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <string>\n#include <utility>\n#include <map>\n\nusing namespace std;\n\nconst int GRID_SIZE = 20;\n\n// Directions: Up, Down, Left, Right\nconst int dx[4] = {-1, 1, 0, 0};\nconst int dy[4] = {0, 0, -1, 1};\nconst char dir_char[4] = {'U', 'D', 'L', 'R'};\n\nstruct Cell {\n    int i, j;\n    Cell(int i = 0, int j = 0) : i(i), j(j) {}\n    bool operator==(const Cell& other) const {\n        return i == other.i && j == other.j;\n    }\n    bool operator<(const Cell& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nclass Grid {\npublic:\n    Grid(int si, int sj, int ti, int tj, double p, \n         const vector<string>& h, const vector<string>& v) \n        : si(si), sj(sj), ti(ti), tj(tj), p(p) {\n        this->h = h;\n        this->v = v;\n    }\n\n    bool is_move_allowed(int i, int j, int d) const {\n        if (d == 0) { // Up\n            return i > 0 && v[i-1][j] == '0';\n        } else if (d == 1) { // Down\n            return i < GRID_SIZE - 1 && v[i][j] == '0';\n        } else if (d == 2) { // Left\n            return j > 0 && h[i][j-1] == '0';\n        } else if (d == 3) { // Right\n            return j < GRID_SIZE - 1 && h[i][j] == '0';\n        }\n        return false;\n    }\n\n    string find_shortest_path() const {\n        Cell start(si, sj);\n        Cell end(ti, tj);\n\n        map<Cell, Cell> parent;\n        map<Cell, int> move_dir;\n        queue<Cell> q;\n        q.push(start);\n        parent[start] = start;\n        move_dir[start] = -1;\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            if (current == end) {\n                break;\n            }\n            for (int d = 0; d < 4; d++) {\n                if (is_move_allowed(current.i, current.j, d)) {\n                    Cell next(current.i + dx[d], current.j + dy[d]);\n                    if (parent.find(next) == parent.end()) {\n                        parent[next] = current;\n                        move_dir[next] = d;\n                        q.push(next);\n                    }\n                }\n            }\n        }\n\n        string path;\n        Cell current = end;\n        while (current != start) {\n            int d = move_dir[current];\n            path.push_back(dir_char[d]);\n            current = parent[current];\n        }\n        reverse(path.begin(), path.end());\n        return path;\n    }\n\n    string find_cycle() const {\n        if (is_move_allowed(ti, tj, 0) && is_move_allowed(ti-1, tj, 1)) {\n            return \"UD\";\n        }\n        if (is_move_allowed(ti, tj, 2) && is_move_allowed(ti, tj-1, 3)) {\n            return \"LR\";\n        }\n        return \"UD\";\n    }\n\nprivate:\n    int si, sj, ti, tj;\n    double p;\n    vector<string> h;\n    vector<string> v;\n};\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    vector<string> h(GRID_SIZE);\n    for (int i = 0; i < GRID_SIZE; i++) {\n        cin >> h[i];\n    }\n\n    vector<string> v(GRID_SIZE - 1);\n    for (int i = 0; i < GRID_SIZE - 1; i++) {\n        cin >> v[i];\n    }\n\n    Grid grid(si, sj, ti, tj, p, h, v);\n    string path = grid.find_shortest_path();\n    string cycle = grid.find_cycle();\n\n    int L = path.size();\n    int K = 200 / L;  // Maximum repetitions without exceeding 200 moves\n    string result;\n    for (int i = 0; i < K; i++) {\n        result += path;\n    }\n    int remaining = 200 - result.size();\n    if (remaining > 0) {\n        int cycle_len = cycle.size();\n        int num_cycles = remaining / cycle_len;\n        for (int i = 0; i < num_cycles; i++) {\n            result += cycle;\n        }\n        int extra = remaining % cycle_len;\n        if (extra > 0) {\n            result += cycle.substr(0, extra);\n        }\n    }\n\n    // Ensure the string length is exactly 200 by truncating if necessary\n    if (result.size() > 200) {\n        result = result.substr(0, 200);\n    }\n\n    cout << result << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    // Precompute global_exit table\n    int to[8][4] = {\n        {1, 0, -1, -1},\n        {3, -1, -1, 0},\n        {-1, -1, 3, 2},\n        {-1, 2, 1, -1},\n        {1, 0, 3, 2},\n        {3, 2, 1, 0},\n        {2, -1, 0, -1},\n        {-1, 3, -1, 1}\n    };\n\n    bool E[8][4] = {false};\n    for (int T = 0; T < 8; T++) {\n        for (int d = 0; d < 4; d++) {\n            int e = to[T][d];\n            if (e != -1) {\n                E[T][e] = true;\n            }\n        }\n    }\n\n    bool global_exit[8][4][4] = {false};\n    for (int T = 0; T < 8; T++) {\n        for (int R = 0; R < 4; R++) {\n            for (int e_local = 0; e_local < 4; e_local++) {\n                if (E[T][e_local]) {\n                    int e_global = (e_local + R) % 4;\n                    global_exit[T][R][e_global] = true;\n                }\n            }\n        }\n    }\n\n    // Process each test case\n    for (int t = 0; t < 100; t++) {\n        vector<string> grid;\n        for (int i = 0; i < 30; i++) {\n            string line;\n            cin >> line;\n            grid.push_back(line);\n        }\n\n        vector<vector<int>> rot(30, vector<int>(30, 0));\n\n        // Simple iterative approach with moderate iterations\n        for (int iter = 0; iter < 5; iter++) {\n            vector<vector<int>> old_rot = rot;\n\n            for (int i = 0; i < 30; i++) {\n                for (int j = 0; j < 30; j++) {\n                    int T = grid[i][j] - '0';\n                    int best_score = -1;\n                    int best_R = 0;\n\n                    for (int R = 0; R < 4; R++) {\n                        int score = 0;\n\n                        // Check all four directions\n                        for (int d = 0; d < 4; d++) {\n                            int ni = i, nj = j;\n                            if (d == 0) nj = j - 1;\n                            else if (d == 1) ni = i - 1;\n                            else if (d == 2) nj = j + 1;\n                            else if (d == 3) ni = i + 1;\n\n                            if (ni < 0 || ni >= 30 || nj < 0 || nj >= 30) {\n                                continue;\n                            }\n\n                            int T_B = grid[ni][nj] - '0';\n                            int R_B = old_rot[ni][nj];\n                            int d_b = (d + 2) % 4;\n\n                            bool A_has_exit = global_exit[T][R][d];\n                            bool B_has_exit = global_exit[T_B][R_B][d_b];\n\n                            if (A_has_exit && B_has_exit) {\n                                score += 10;  // Strong reward for bidirectional connections\n                            } else if (A_has_exit || B_has_exit) {\n                                score += 1;   // Small reward for unidirectional connections\n                            }\n                        }\n\n                        if (score > best_score) {\n                            best_score = score;\n                            best_R = R;\n                        }\n                    }\n\n                    rot[i][j] = best_R;\n                }\n            }\n        }\n\n        string s;\n        for (int i = 0; i < 30; i++) {\n            for (int j = 0; j < 30; j++) {\n                s += char('0' + rot[i][j]);\n            }\n        }\n        cout << s << endl;\n    }\n\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <queue>\n#include <utility>\n#include <algorithm>\n\nusing namespace std;\n\nint compute_cost(vector<vector<int>> &grid, int N) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    int sum_squares = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == 0) continue;\n            if (visited[i][j]) continue;\n            int size = 0;\n            queue<pair<int, int>> q;\n            q.push({i, j});\n            visited[i][j] = true;\n            while (!q.empty()) {\n                auto [r, c] = q.front();\n                q.pop();\n                size++;\n                int dr[4] = {-1, 1, 0, 0};\n                int dc[4] = {0, 0, -1, 1};\n                int self_line[4] = {2, 8, 1, 4};\n                int neighbor_line[4] = {8, 2, 4, 1};\n                for (int d = 0; d < 4; d++) {\n                    int nr = r + dr[d];\n                    int nc = c + dc[d];\n                    if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                    if (grid[nr][nc] == 0) continue;\n                    if (visited[nr][nc]) continue;\n                    if (grid[r][c] & self_line[d] && grid[nr][nc] & neighbor_line[d]) {\n                        q.push({nr, nc});\n                        visited[nr][nc] = true;\n                    }\n                }\n            }\n            sum_squares += size * size;\n        }\n    }\n    return sum_squares;\n}\n\nvoid make_move(char D, vector<vector<int>> &grid, int &er, int &ec) {\n    int pr, pc;\n    if (D == 'U') {\n        pr = er - 1;\n        pc = ec;\n    } else if (D == 'D') {\n        pr = er + 1;\n        pc = ec;\n    } else if (D == 'L') {\n        pr = er;\n        pc = ec - 1;\n    } else if (D == 'R') {\n        pr = er;\n        pc = ec + 1;\n    } else {\n        return;\n    }\n    swap(grid[er][ec], grid[pr][pc]);\n    er = pr;\n    ec = pc;\n}\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n\n    vector<vector<int>> grid(N, vector<int>(N));\n    int empty_row = 0, empty_col = 0;\n\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            char c = s[j];\n            if (c >= '0' && c <= '9') {\n                grid[i][j] = c - '0';\n            } else if (c >= 'a' && c <= 'f') {\n                grid[i][j] = 10 + (c - 'a');\n            } else {\n                grid[i][j] = 0;\n            }\n            if (grid[i][j] == 0) {\n                empty_row = i;\n                empty_col = j;\n            }\n        }\n    }\n\n    vector<vector<int>> best_grid = grid;\n    vector<vector<int>> current_grid = grid;\n    int best_er = empty_row, best_ec = empty_col;\n    int current_er = empty_row, current_ec = empty_col;\n    int best_cost = compute_cost(current_grid, N);\n    int current_cost = best_cost;\n    string best_moves = \"\";\n    string current_moves = \"\";\n    \n    double T0 = 150.0;\n    double adaptive_T = T0;\n    srand(time(0));\n    \n    int no_improvement_steps = 0;\n    int improvement_count = 0;\n    const int MAX_NO_IMPROVEMENT = min(2000, T / 3);\n    const int ADAPTIVE_WINDOW = 100;\n\n    for (int t = 0; t < T; t++) {\n        int max_cost = (N * N - 1) * (N * N - 1);\n        if (best_cost == max_cost) {\n            break;\n        }\n\n        // Adaptive temperature scheduling\n        double temp;\n        if (t < T * 0.7) {\n            // Linear decay for first 70% of moves\n            temp = T0 * (1.0 - static_cast<double>(t) / (T * 0.7));\n        } else {\n            // Slower decay for the remaining 30%\n            temp = T0 * 0.3 * (1.0 - static_cast<double>(t - T * 0.7) / (T * 0.3));\n        }\n        \n        // Adaptive adjustment based on recent improvements\n        if (improvement_count > ADAPTIVE_WINDOW * 0.3) {\n            temp *= 1.2; // Increase temperature if we're finding improvements\n        } else if (no_improvement_steps > MAX_NO_IMPROVEMENT / 2) {\n            temp *= 0.8; // Decrease temperature if stuck\n        }\n        \n        temp = max(temp, 0.1);\n\n        vector<char> directions;\n        if (current_er > 0) directions.push_back('U');\n        if (current_er < N - 1) directions.push_back('D');\n        if (current_ec > 0) directions.push_back('L');\n        if (current_ec < N - 1) directions.push_back('R');\n\n        if (directions.empty()) break;\n\n        // Prefer moves that connect to existing components\n        vector<double> weights;\n        vector<char> dirs;\n        vector<int> new_costs;\n\n        for (char D : directions) {\n            vector<vector<int>> temp_grid = current_grid;\n            int temp_er = current_er, temp_ec = current_ec;\n            make_move(D, temp_grid, temp_er, temp_ec);\n            int new_cost = compute_cost(temp_grid, N);\n            int delta = new_cost - current_cost;\n            double weight = exp(delta / temp);\n            weights.push_back(weight);\n            dirs.push_back(D);\n            new_costs.push_back(new_cost);\n        }\n\n        double total_weight = 0.0;\n        for (double w : weights) total_weight += w;\n\n        double r = static_cast<double>(rand()) / RAND_MAX * total_weight;\n        double cumulative = 0.0;\n        int index = 0;\n        for (int i = 0; i < weights.size(); i++) {\n            cumulative += weights[i];\n            if (r < cumulative) {\n                index = i;\n                break;\n            }\n        }\n\n        char chosen_D = dirs[index];\n        int chosen_new_cost = new_costs[index];\n        make_move(chosen_D, current_grid, current_er, current_ec);\n        current_cost = chosen_new_cost;\n        current_moves += chosen_D;\n\n        if (current_cost > best_cost) {\n            best_cost = current_cost;\n            best_grid = current_grid;\n            best_er = current_er;\n            best_ec = current_ec;\n            best_moves = current_moves;\n            no_improvement_steps = 0;\n            improvement_count++;\n        } else {\n            no_improvement_steps++;\n            \n            if (no_improvement_steps > MAX_NO_IMPROVEMENT) {\n                // Reset to best solution but add some randomness\n                current_grid = best_grid;\n                current_er = best_er;\n                current_ec = best_ec;\n                current_cost = best_cost;\n                current_moves = best_moves;\n                \n                // Add a few random moves to escape local optimum\n                for (int i = 0; i < 5 && current_moves.length() < T; i++) {\n                    vector<char> possible_dirs;\n                    if (current_er > 0) possible_dirs.push_back('U');\n                    if (current_er < N - 1) possible_dirs.push_back('D');\n                    if (current_ec > 0) possible_dirs.push_back('L');\n                    if (current_ec < N - 1) possible_dirs.push_back('R');\n                    \n                    if (!possible_dirs.empty()) {\n                        char random_dir = possible_dirs[rand() % possible_dirs.size()];\n                        make_move(random_dir, current_grid, current_er, current_ec);\n                        current_moves += random_dir;\n                        current_cost = compute_cost(current_grid, N);\n                    }\n                }\n                \n                no_improvement_steps = 0;\n                improvement_count = max(0, improvement_count - 10);\n            }\n        }\n        \n        // Reset improvement count periodically\n        if (t % ADAPTIVE_WINDOW == 0) {\n            improvement_count = 0;\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 <map>\n\nusing namespace std;\n\nint main() {\n    int N, K;\n    cin >> N >> K;\n    int a[10];\n    for (int i = 0; i < 10; i++) {\n        cin >> a[i];\n    }\n    vector<pair<int, int>> points;\n    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n        points.push_back({x, y});\n    }\n\n    // Calculate target piece sizes based on a_d distribution\n    vector<int> target_sizes;\n    for (int d = 1; d <= 10; d++) {\n        for (int i = 0; i < a[d-1]; i++) {\n            target_sizes.push_back(d);\n        }\n    }\n    sort(target_sizes.begin(), target_sizes.end());\n    \n    // Use density-based grid partitioning\n    // More lines in dense areas, fewer in sparse areas\n    int grid_size = 10; // Start with 10x10 grid for density analysis\n    \n    // Analyze strawberry density\n    vector<int> x_coords, y_coords;\n    for (auto& p : points) {\n        x_coords.push_back(p.first);\n        y_coords.push_back(p.second);\n    }\n    sort(x_coords.begin(), x_coords.end());\n    sort(y_coords.begin(), y_coords.end());\n    \n    // Create adaptive grid lines based on quantiles\n    int cuts_used = 0;\n    vector<pair<int, int>> vertical_cuts, horizontal_cuts;\n    \n    // Vertical cuts based on x-coordinate quantiles\n    for (int i = 1; i < grid_size && cuts_used < K; i++) {\n        int idx = (i * N) / grid_size;\n        if (idx < N) {\n            int x = x_coords[idx];\n            vertical_cuts.push_back({x, -1000000000});\n            vertical_cuts.push_back({x, 1000000000});\n            cuts_used++;\n        }\n    }\n    \n    // Horizontal cuts based on y-coordinate quantiles  \n    for (int i = 1; i < grid_size && cuts_used < K; i++) {\n        int idx = (i * N) / grid_size;\n        if (idx < N) {\n            int y = y_coords[idx];\n            horizontal_cuts.push_back({-1000000000, y});\n            horizontal_cuts.push_back({1000000000, y});\n            cuts_used++;\n        }\n    }\n    \n    // Use remaining cuts for finer partitioning in dense areas\n    int remaining_cuts = K - cuts_used;\n    if (remaining_cuts > 0) {\n        // Add more vertical cuts in areas with high strawberry density\n        int additional_vertical = min(remaining_cuts / 2, 20);\n        for (int i = 1; i <= additional_vertical && cuts_used < K; i++) {\n            int segment = N / (additional_vertical + 1);\n            int idx = i * segment;\n            if (idx < N) {\n                int x = x_coords[idx];\n                vertical_cuts.push_back({x, -1000000000});\n                vertical_cuts.push_back({x, 1000000000});\n                cuts_used++;\n            }\n        }\n        \n        // Add more horizontal cuts\n        int additional_horizontal = min(remaining_cuts - additional_vertical, 20);\n        for (int i = 1; i <= additional_horizontal && cuts_used < K; i++) {\n            int segment = N / (additional_horizontal + 1);\n            int idx = i * segment;\n            if (idx < N) {\n                int y = y_coords[idx];\n                horizontal_cuts.push_back({-1000000000, y});\n                horizontal_cuts.push_back({1000000000, y});\n                cuts_used++;\n            }\n        }\n    }\n    \n    // Output all cuts\n    cout << cuts_used << endl;\n    \n    // Output vertical cuts\n    for (int i = 0; i < vertical_cuts.size(); i += 2) {\n        cout << vertical_cuts[i].first << \" \" << vertical_cuts[i].second << \" \"\n             << vertical_cuts[i+1].first << \" \" << vertical_cuts[i+1].second << endl;\n    }\n    \n    // Output horizontal cuts\n    for (int i = 0; i < horizontal_cuts.size(); i += 2) {\n        cout << horizontal_cuts[i].first << \" \" << horizontal_cuts[i].second << \" \"\n             << horizontal_cuts[i+1].first << \" \" << horizontal_cuts[i+1].second << endl;\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const { return x == other.x && y == other.y; }\n    bool operator<(const Point& other) const {\n        return x < other.x || (x == other.x && y < other.y);\n    }\n};\n\nstruct Segment {\n    Point a, b;\n    Segment(Point a, Point b) : a(a), b(b) {}\n    bool operator<(const Segment& other) const {\n        if (a.x != other.a.x) return a.x < other.a.x;\n        if (a.y != other.a.y) return a.y < other.a.y;\n        if (b.x != other.b.x) return b.x < other.b.x;\n        return b.y < other.b.y;\n    }\n};\n\nclass RectJoinSolver {\nprivate:\n    int N, M;\n    set<Point> dots;\n    set<Segment> used_segments;\n    vector<vector<Point>> operations;\n    Point center;\n    vector<vector<int>> weight;\n    \n    bool is_valid_point(int x, int y) {\n        return x >= 0 && x < N && y >= 0 && y < N;\n    }\n    \n    bool has_dot(const Point& p) {\n        return dots.count(p);\n    }\n    \n    vector<Point> get_points_on_segment(const Point& a, const Point& b) {\n        vector<Point> points;\n        if (a.x == b.x) {\n            int y1 = min(a.y, b.y), y2 = max(a.y, b.y);\n            for (int y = y1; y <= y2; y++) {\n                points.push_back(Point(a.x, y));\n            }\n        } else if (a.y == b.y) {\n            int x1 = min(a.x, b.x), x2 = max(a.x, b.x);\n            for (int x = x1; x <= x2; x++) {\n                points.push_back(Point(x, a.y));\n            }\n        }\n        return points;\n    }\n    \n    bool check_no_other_dots(const vector<Point>& corners, const Point& new_dot) {\n        set<Point> allowed_dots;\n        for (int i = 1; i < 4; i++) {\n            allowed_dots.insert(corners[i]);\n        }\n        \n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            auto segment_points = get_points_on_segment(a, b);\n            \n            for (const Point& p : segment_points) {\n                if (p == a || p == b) continue;\n                if (has_dot(p) && !allowed_dots.count(p)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    bool check_no_overlapping_segments(const vector<Point>& corners) {\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            auto segment_points = get_points_on_segment(a, b);\n            \n            for (int j = 0; j < (int)segment_points.size() - 1; j++) {\n                Point p1 = segment_points[j];\n                Point p2 = segment_points[j+1];\n                Segment seg(p1, p2);\n                \n                if (used_segments.count(seg)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    void mark_segments_used(const vector<Point>& corners) {\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            auto segment_points = get_points_on_segment(a, b);\n            \n            for (int j = 0; j < (int)segment_points.size() - 1; j++) {\n                Point p1 = segment_points[j];\n                Point p2 = segment_points[j+1];\n                Segment seg(p1, p2);\n                used_segments.insert(seg);\n            }\n        }\n    }\n    \n    vector<Point> order_points_clockwise(const vector<Point>& points) {\n        if (points.size() != 4) return points;\n        \n        double cx = 0, cy = 0;\n        for (const auto& p : points) {\n            cx += p.x;\n            cy += p.y;\n        }\n        cx /= 4;\n        cy /= 4;\n        \n        vector<Point> ordered = points;\n        sort(ordered.begin(), ordered.end(), [cx, cy](const Point& a, const Point& b) {\n            return atan2(a.y - cy, a.x - cx) < atan2(b.y - cy, b.x - cx);\n        });\n        \n        return ordered;\n    }\n    \n    void precompute_weights() {\n        weight.resize(N, vector<int>(N, 0));\n        center = Point((N-1)/2, (N-1)/2);\n        for (int x = 0; x < N; x++) {\n            for (int y = 0; y < N; y++) {\n                int dx = x - center.x;\n                int dy = y - center.y;\n                weight[x][y] = dx*dx + dy*dy + 1;\n            }\n        }\n    }\n    \n    vector<vector<Point>> generate_candidates() {\n        vector<vector<Point>> candidates;\n        vector<Point> dot_list(dots.begin(), dots.end());\n        \n        // Use a more efficient approach: iterate through possible rectangle dimensions\n        for (int width = 1; width < N; width++) {\n            for (int height = 1; height < N; height++) {\n                // Try all possible top-left corners\n                for (int x = 0; x < N - width; x++) {\n                    for (int y = 0; y < N - height; y++) {\n                        Point tl(x, y);\n                        Point tr(x + width, y);\n                        Point bl(x, y + height);\n                        Point br(x + width, y + height);\n                        \n                        // Count how many corners have dots\n                        int dot_count = 0;\n                        Point missing_corner;\n                        vector<Point> existing_corners;\n                        \n                        if (has_dot(tl)) { dot_count++; existing_corners.push_back(tl); }\n                        else { missing_corner = tl; }\n                        \n                        if (has_dot(tr)) { dot_count++; existing_corners.push_back(tr); }\n                        else { missing_corner = tr; }\n                        \n                        if (has_dot(bl)) { dot_count++; existing_corners.push_back(bl); }\n                        else { missing_corner = bl; }\n                        \n                        if (has_dot(br)) { dot_count++; existing_corners.push_back(br); }\n                        else { missing_corner = br; }\n                        \n                        // We need exactly 3 dots and 1 free corner\n                        if (dot_count == 3) {\n                            vector<Point> corners = {missing_corner, existing_corners[0], \n                                                   existing_corners[1], existing_corners[2]};\n                            set<Point> corner_set(corners.begin(), corners.end());\n                            if (corner_set.size() == 4) {\n                                vector<Point> ordered = order_points_clockwise(corners);\n                                auto it = find(ordered.begin(), ordered.end(), missing_corner);\n                                if (it != ordered.end()) {\n                                    rotate(ordered.begin(), it, ordered.end());\n                                    candidates.push_back(ordered);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        return candidates;\n    }\n    \npublic:\n    RectJoinSolver(int N, int M, const vector<Point>& initial_dots) : N(N), M(M) {\n        precompute_weights();\n        center = Point((N-1)/2, (N-1)/2);\n        for (const Point& p : initial_dots) {\n            dots.insert(p);\n        }\n    }\n    \n    void solve() {\n        auto start_time = chrono::steady_clock::now();\n        \n        while (true) {\n            auto current_time = chrono::steady_clock::now();\n            auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time);\n            if (elapsed.count() > 4500) break;\n            \n            auto candidates = generate_candidates();\n            if (candidates.empty()) break;\n            \n            vector<Point> best_candidate;\n            int best_score = -1;\n            \n            for (const auto& candidate : candidates) {\n                if (candidate.size() != 4) continue;\n                \n                Point new_dot = candidate[0];\n                vector<Point> corners = candidate;\n                \n                if (check_no_other_dots(corners, new_dot) && \n                    check_no_overlapping_segments(corners)) {\n                    \n                    int score = weight[new_dot.x][new_dot.y];\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_candidate = candidate;\n                    }\n                }\n            }\n            \n            if (best_score == -1) break;\n            \n            operations.push_back(best_candidate);\n            dots.insert(best_candidate[0]);\n            mark_segments_used(best_candidate);\n        }\n    }\n    \n    void output() {\n        cout << operations.size() << endl;\n        for (const auto& op : operations) {\n            cout << op[0].x << \" \" << op[0].y << \" \"\n                 << op[1].x << \" \" << op[1].y << \" \"\n                 << op[2].x << \" \" << op[2].y << \" \"\n                 << op[3].x << \" \" << op[3].y << endl;\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    cin >> N >> M;\n    \n    vector<Point> initial_dots(M);\n    for (int i = 0; i < M; i++) {\n        cin >> initial_dots[i].x >> initial_dots[i].y;\n    }\n    \n    RectJoinSolver solver(N, M, initial_dots);\n    solver.solve();\n    solver.output();\n    \n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n#include <algorithm>\n#include <cmath>\nusing namespace std;\n\nconst int N = 10;\n\nvector<vector<int>> tilt_grid(const vector<vector<int>>& state, char direction) {\n    vector<vector<int>> new_state(N+1, vector<int>(N+1, 0));\n    if (direction == 'L') {\n        for (int i = 1; i <= N; i++) {\n            vector<int> non_empty;\n            for (int j = 1; j <= N; j++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int j = 1; j <= k; j++) {\n                new_state[i][j] = non_empty[j-1];\n            }\n            for (int j = k+1; j <= N; j++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'R') {\n        for (int i = 1; i <= N; i++) {\n            vector<int> non_empty;\n            for (int j = 1; j <= N; j++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int j = 1; j <= k; j++) {\n                new_state[i][N - k + j] = non_empty[j-1];\n            }\n            for (int j = 1; j <= N-k; j++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'F') {\n        for (int j = 1; j <= N; j++) {\n            vector<int> non_empty;\n            for (int i = 1; i <= N; i++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int i = 1; i <= k; i++) {\n                new_state[i][j] = non_empty[i-1];\n            }\n            for (int i = k+1; i <= N; i++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'B') {\n        for (int j = 1; j <= N; j++) {\n            vector<int> non_empty;\n            for (int i = 1; i <= N; i++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int i = 1; i <= k; i++) {\n                new_state[N - k + i][j] = non_empty[i-1];\n            }\n            for (int i = 1; i <= N-k; i++) {\n                new_state[i][j] = 0;\n            }\n        }\n    }\n    return new_state;\n}\n\nint compute_score(const vector<vector<int>>& grid, vector<vector<bool>>& visited) {\n    int score = 0;\n    for (int i = 1; i <= N; i++) {\n        for (int j = 1; j <= N; j++) {\n            visited[i][j] = false;\n        }\n    }\n    for (int i = 1; i <= N; i++) {\n        for (int j = 1; j <= N; j++) {\n            if (!visited[i][j] && grid[i][j] != 0) {\n                int flavor = grid[i][j];\n                int size = 0;\n                queue<pair<int, int>> q;\n                q.push({i, j});\n                visited[i][j] = true;\n                while (!q.empty()) {\n                    pair<int, int> pos = q.front();\n                    q.pop();\n                    int x = pos.first, y = pos.second;\n                    size++;\n                    int dx[] = {1, -1, 0, 0};\n                    int dy[] = {0, 0, 1, -1};\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d], ny = y + dy[d];\n                        if (nx >= 1 && nx <= N && ny >= 1 && ny <= N && !visited[nx][ny] && grid[nx][ny] == flavor) {\n                            visited[nx][ny] = true;\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n                score += size * size;\n            }\n        }\n    }\n    return score;\n}\n\nint main() {\n    int f[101];\n    int flavor_counts[4] = {0};\n    for (int i = 1; i <= 100; i++) {\n        cin >> f[i];\n        flavor_counts[f[i]]++;\n    }\n\n    // Pre-assign regions to flavors based on their counts\n    // Divide the grid into 3 regions with sizes proportional to flavor counts\n    vector<pair<int, int>> regions[4]; // regions[1], regions[2], regions[3]\n    \n    // Simple region assignment: flavors 1, 2, 3 get left, middle, right thirds\n    // Adjust based on actual counts for better balance\n    int total = 100;\n    int target1 = flavor_counts[1];\n    int target2 = flavor_counts[2];\n    int target3 = flavor_counts[3];\n    \n    // Assign cells to flavors based on a spiral pattern from the center\n    // This encourages natural clustering\n    vector<pair<int, int>> spiral_order;\n    int center_i = 5, center_j = 5;\n    spiral_order.push_back({center_i, center_j});\n    \n    int directions[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};\n    int step = 1;\n    int dir = 0;\n    int x = center_i, y = center_j;\n    \n    while (spiral_order.size() < 100) {\n        for (int i = 0; i < 2; i++) {\n            for (int j = 0; j < step; j++) {\n                x += directions[dir][0];\n                y += directions[dir][1];\n                if (x >= 1 && x <= N && y >= 1 && y <= N) {\n                    spiral_order.push_back({x, y});\n                }\n                if (spiral_order.size() >= 100) break;\n            }\n            if (spiral_order.size() >= 100) break;\n            dir = (dir + 1) % 4;\n        }\n        step++;\n    }\n    \n    // Assign the spiral order positions to flavors based on their counts\n    int assigned = 0;\n    for (int flavor = 1; flavor <= 3; flavor++) {\n        for (int i = 0; i < flavor_counts[flavor]; i++) {\n            if (assigned < spiral_order.size()) {\n                regions[flavor].push_back(spiral_order[assigned++]);\n            }\n        }\n    }\n\n    vector<vector<int>> grid(N+1, vector<int>(N+1, 0));\n    vector<vector<bool>> visited(N+1, vector<bool>(N+1, false));\n    vector<char> directions_tilt = {'F', 'B', 'L', 'R'};\n\n    for (int t = 1; t <= 100; t++) {\n        int p;\n        cin >> p;\n\n        int count = 0;\n        int i_place = 0, j_place = 0;\n        for (int i = 1; i <= N; i++) {\n            for (int j = 1; j <= N; j++) {\n                if (grid[i][j] == 0) {\n                    count++;\n                    if (count == p) {\n                        i_place = i;\n                        j_place = j;\n                        break;\n                    }\n                }\n            }\n            if (j_place != 0) break;\n        }\n\n        grid[i_place][j_place] = f[t];\n\n        if (t == 100) {\n            int best_score = -1;\n            char best_dir = 'F';\n            for (char dir : directions_tilt) {\n                vector<vector<int>> new_grid = tilt_grid(grid, dir);\n                int score = compute_score(new_grid, visited);\n                if (score > best_score) {\n                    best_score = score;\n                    best_dir = dir;\n                }\n            }\n            cout << best_dir << endl;\n            cout.flush();\n            grid = tilt_grid(grid, best_dir);\n            continue;\n        }\n\n        // Enhanced lookahead with strategic positioning\n        double best_avg_score = -1;\n        char best_dir = 'F';\n        \n        for (char dir : directions_tilt) {\n            vector<vector<int>> grid_after_tilt = tilt_grid(grid, dir);\n            \n            double total_score = 0.0;\n            int empty_count = 0;\n            \n            for (int i = 1; i <= N; i++) {\n                for (int j = 1; j <= N; j++) {\n                    if (grid_after_tilt[i][j] == 0) {\n                        empty_count++;\n                        vector<vector<int>> grid_with_next = grid_after_tilt;\n                        grid_with_next[i][j] = f[t+1];\n                        \n                        // Strategic bonus: reward placements near the ideal region for this flavor\n                        double strategic_bonus = 0.0;\n                        for (auto& target : regions[f[t+1]]) {\n                            double distance = sqrt(pow(i - target.first, 2) + pow(j - target.second, 2));\n                            strategic_bonus += 1.0 / (1.0 + distance);\n                        }\n                        \n                        int best_next_score = -1;\n                        for (char dir2 : directions_tilt) {\n                            vector<vector<int>> grid_after_tilt2 = tilt_grid(grid_with_next, dir2);\n                            int score = compute_score(grid_after_tilt2, visited);\n                            if (score > best_next_score) {\n                                best_next_score = score;\n                            }\n                        }\n                        \n                        total_score += best_next_score + strategic_bonus * 10; // Weight the strategic bonus\n                    }\n                }\n            }\n            \n            if (empty_count > 0) {\n                double avg_score = total_score / empty_count;\n                if (avg_score > best_avg_score) {\n                    best_avg_score = avg_score;\n                    best_dir = dir;\n                }\n            }\n        }\n\n        cout << best_dir << endl;\n        cout.flush();\n        grid = tilt_grid(grid, best_dir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <cstdlib>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\nusing namespace std;\n\nint main() {\n    int M;\n    double eps;\n    cin >> M >> eps;\n\n    double requiredN = sqrt(2.0 * M) + 10.0 * eps;\n    int N = min(100, max(4, (int)ceil(requiredN)));\n    int T = N * (N - 1) / 2;\n\n    vector<int> offset(N);\n    offset[0] = 0;\n    for (int i = 1; i < N; i++) {\n        offset[i] = offset[i-1] + (N - i);\n    }\n\n    cout << N << endl;\n\n    int D = min(M, T + 1);\n    vector<int> m_values(D);\n    if (D > 1) {\n        for (int i = 0; i < D; i++) {\n            m_values[i] = round((i * T) / (D - 1.0));\n        }\n    } else {\n        m_values[0] = 0;\n    }\n\n    vector<int> m_list(M);\n    int quotient = M / D;\n    int remainder = M % D;\n    int index = 0;\n    for (int j = 0; j < D; j++) {\n        int count = quotient + (j < remainder ? 1 : 0);\n        for (int c = 0; c < count; c++) {\n            m_list[index++] = m_values[j];\n        }\n    }\n\n    vector<vector<double>> eigenvals(M);\n    for (int k = 0; k < M; k++) {\n        int m_k = m_list[k];\n        vector<bool> edge_flag(T, false);\n        vector<int> indices(T);\n        for (int i = 0; i < T; i++) {\n            indices[i] = i;\n        }\n        for (int i = T - 1; i > 0; i--) {\n            int j = rand() % (i + 1);\n            swap(indices[i], indices[j]);\n        }\n        for (int i = 0; i < m_k; i++) {\n            edge_flag[indices[i]] = true;\n        }\n\n        Eigen::MatrixXd A = Eigen::MatrixXd::Zero(N, N);\n        for (int pos = 0; pos < T; pos++) {\n            if (edge_flag[pos]) {\n                int i = 0;\n                while (i < N - 1 && pos >= offset[i + 1]) {\n                    i++;\n                }\n                int j = i + 1 + (pos - offset[i]);\n                A(i, j) = 1;\n                A(j, i) = 1;\n            }\n        }\n\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(A);\n        Eigen::VectorXd evals = solver.eigenvalues();\n        vector<double> eval_vec(evals.data(), evals.data() + evals.size());\n        sort(eval_vec.begin(), eval_vec.end());\n        eigenvals[k] = eval_vec;\n\n        string g_str;\n        for (int pos = 0; pos < T; pos++) {\n            g_str += edge_flag[pos] ? '1' : '0';\n        }\n        cout << g_str << endl;\n    }\n\n    for (int q = 0; q < 100; q++) {\n        string H_str;\n        cin >> H_str;\n\n        Eigen::MatrixXd H_mat = Eigen::MatrixXd::Zero(N, N);\n        for (int pos = 0; pos < T; pos++) {\n            if (H_str[pos] == '1') {\n                int i = 0;\n                while (i < N - 1 && pos >= offset[i + 1]) {\n                    i++;\n                }\n                int j = i + 1 + (pos - offset[i]);\n                H_mat(i, j) = 1;\n                H_mat(j, i) = 1;\n            }\n        }\n\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver_H(H_mat);\n        Eigen::VectorXd evals_H = solver_H.eigenvalues();\n        vector<double> eval_vec_H(evals_H.data(), evals_H.data() + evals_H.size());\n        sort(eval_vec_H.begin(), eval_vec_H.end());\n\n        int best_k = 0;\n        double min_dist = 1e9;\n        for (int k = 0; k < M; k++) {\n            double dist = 0.0;\n            for (int i = 0; i < N; i++) {\n                double diff = eval_vec_H[i] - eigenvals[k][i];\n                dist += diff * diff;\n            }\n            dist = sqrt(dist);\n            if (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 <algorithm>\n#include <queue>\n#include <limits>\n#include <tuple>\n#include <cmath>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nconst int INF = 1000000000;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    vector<tuple<int, int, int>> edges;\n    for (int i = 0; i < M; i++) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges.push_back({u, v, w});\n    }\n\n    vector<pair<int, int>> points(N + 1);\n    for (int i = 1; i <= N; i++) {\n        cin >> points[i].first >> points[i].second;\n    }\n\n    // Build graph\n    vector<vector<pair<int, int>>> graph(N + 1);\n    vector<map<int, int>> edge_map(N + 1);\n    for (int i = 0; i < M; i++) {\n        int u = get<0>(edges[i]);\n        int v = get<1>(edges[i]);\n        int w = get<2>(edges[i]);\n        graph[u].emplace_back(v, w);\n        graph[v].emplace_back(u, w);\n        edge_map[u][v] = i;\n        edge_map[v][u] = i;\n    }\n\n    // Calculate edge betweenness centrality\n    vector<double> betweenness(M, 0.0);\n    \n    for (int s = 1; s <= N; s++) {\n        // Dijkstra from source s\n        vector<int> dist(N + 1, INF);\n        vector<int> sigma(N + 1, 0);\n        vector<vector<int>> pred(N + 1);\n        dist[s] = 0;\n        sigma[s] = 1;\n        \n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n        pq.push({0, s});\n        \n        vector<int> order;\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            \n            order.push_back(u);\n            for (auto [v, w] : graph[u]) {\n                if (dist[v] > dist[u] + w) {\n                    dist[v] = dist[u] + w;\n                    sigma[v] = sigma[u];\n                    pred[v].clear();\n                    pred[v].push_back(u);\n                    pq.push({dist[v], v});\n                } else if (dist[v] == dist[u] + w) {\n                    sigma[v] += sigma[u];\n                    pred[v].push_back(u);\n                }\n            }\n        }\n        \n        // Backward pass to accumulate betweenness\n        vector<double> delta(N + 1, 0.0);\n        reverse(order.begin(), order.end());\n        \n        for (int u : order) {\n            for (int v : pred[u]) {\n                double coeff = (1.0 + delta[u]) * sigma[v] / sigma[u];\n                delta[v] += coeff;\n                \n                // Find edge between u and v\n                int edge_idx = edge_map[u][v];\n                betweenness[edge_idx] += coeff;\n            }\n        }\n    }\n\n    // Sort edges by betweenness\n    vector<int> edge_order(M);\n    for (int i = 0; i < M; i++) {\n        edge_order[i] = i;\n    }\n    sort(edge_order.begin(), edge_order.end(), [&](int a, int b) {\n        return betweenness[a] > betweenness[b];\n    });\n\n    // Group edges by their endpoints to avoid removing adjacent edges on the same day\n    vector<set<int>> vertex_days(N + 1);\n    vector<int> assignment(M, 0);\n    vector<int> day_count(D + 1, 0);\n    \n    // Assign edges strategically\n    for (int i = 0; i < M; i++) {\n        int edge_idx = edge_order[i];\n        int u = get<0>(edges[edge_idx]);\n        int v = get<1>(edges[edge_idx]);\n        \n        // Find the best day that minimizes conflicts with adjacent edges\n        vector<int> day_scores(D + 1, 0);\n        for (int d = 1; d <= D; d++) {\n            if (day_count[d] >= K) {\n                day_scores[d] = INF;\n                continue;\n            }\n            \n            // Penalize days that already have edges adjacent to u or v\n            if (vertex_days[u].count(d)) day_scores[d] += 10;\n            if (vertex_days[v].count(d)) day_scores[d] += 10;\n            \n            // Prefer days with fewer assignments\n            day_scores[d] += day_count[d];\n        }\n        \n        // Find the best day\n        int best_day = 1;\n        for (int d = 2; d <= D; d++) {\n            if (day_scores[d] < day_scores[best_day]) {\n                best_day = d;\n            }\n        }\n        \n        assignment[edge_idx] = best_day;\n        day_count[best_day]++;\n        vertex_days[u].insert(best_day);\n        vertex_days[v].insert(best_day);\n    }\n\n    // Output the assignment\n    for (int i = 0; i < M; i++) {\n        cout << assignment[i];\n        if (i < M - 1) cout << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <queue>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\nint main() {\n    int D;\n    cin >> D;\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 required positions for each silhouette\n    set<tuple<int, int, int>> M1, M2;\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 (f1[z][x] == '1' && r1[z][y] == '1') {\n                    M1.insert({x, y, z});\n                }\n                if (f2[z][x] == '1' && r2[z][y] == '1') {\n                    M2.insert({x, y, z});\n                }\n            }\n        }\n    }\n\n    // Find intersection of required positions\n    set<tuple<int, int, int>> I;\n    set_intersection(M1.begin(), M1.end(), M2.begin(), M2.end(),\n                    inserter(I, I.begin()));\n\n    // 6-directional neighbors\n    vector<tuple<int, int, int>> directions = {\n        {1, 0, 0}, {-1, 0, 0},\n        {0, 1, 0}, {0, -1, 0},\n        {0, 0, 1}, {0, 0, -1}\n    };\n\n    // Find connected components in intersection\n    map<tuple<int, int, int>, int> comp_id;\n    int comp_count = 0;\n    \n    for (const auto& coord : I) {\n        if (comp_id.count(coord)) continue;\n        \n        comp_count++;\n        queue<tuple<int, int, int>> q;\n        q.push(coord);\n        comp_id[coord] = comp_count;\n        \n        while (!q.empty()) {\n            auto [x, y, z] = q.front();\n            q.pop();\n            \n            for (auto [dx, dy, dz] : directions) {\n                int nx = x + dx, ny = y + dy, nz = z + dz;\n                tuple<int, int, int> neighbor = {nx, ny, nz};\n                \n                if (I.count(neighbor) && !comp_id.count(neighbor)) {\n                    comp_id[neighbor] = comp_count;\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n\n    // Calculate total blocks\n    int n = comp_count + (M1.size() - I.size()) + (M2.size() - I.size());\n    \n    // Create output arrays\n    vector<int> arr1(D * D * D, 0), arr2(D * D * D, 0);\n    \n    // Assign blocks for first arrangement\n    int id_counter = comp_count + 1;\n    map<tuple<int, int, int>, int> id_map1;\n    \n    for (const auto& coord : M1) {\n        auto [x, y, z] = coord;\n        int idx = x * D * D + y * D + z;\n        \n        if (I.count(coord)) {\n            arr1[idx] = comp_id[coord];\n        } else {\n            if (!id_map1.count(coord)) {\n                id_map1[coord] = id_counter++;\n            }\n            arr1[idx] = id_map1[coord];\n        }\n    }\n    \n    // Assign blocks for second arrangement\n    map<tuple<int, int, int>, int> id_map2;\n    \n    for (const auto& coord : M2) {\n        auto [x, y, z] = coord;\n        int idx = x * D * D + y * D + z;\n        \n        if (I.count(coord)) {\n            arr2[idx] = comp_id[coord];\n        } else {\n            if (!id_map2.count(coord)) {\n                id_map2[coord] = id_counter++;\n            }\n            arr2[idx] = id_map2[coord];\n        }\n    }\n    \n    // Output results\n    cout << n << endl;\n    \n    for (int i = 0; i < D * D * D; i++) {\n        cout << arr1[i] << (i == D * D * D - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    for (int i = 0; i < D * D * D; i++) {\n        cout << arr2[i] << (i == D * D * D - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read input\n    int N, M, K;\n    cin >> N >> M >> K;\n    \n    vector<ll> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<tuple<int, int, ll>> edges(M);\n    map<pair<int, int>, int> edge_index_map;\n    for (int i = 0; i < M; i++) {\n        int u, v;\n        ll w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edges[i] = {u, v, w};\n        if (u > v) swap(u, v);\n        edge_index_map[{u, v}] = i;\n    }\n    \n    vector<ll> a(K), b(K);\n    for (int i = 0; i < K; i++) {\n        cin >> a[i] >> b[i];\n    }\n    \n    // Precompute squared distances from stations to residents\n    vector<vector<ll>> dist_sq(N, vector<ll>(K));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < K; j++) {\n            ll dx = x[i] - a[j];\n            ll dy = y[i] - b[j];\n            dist_sq[i][j] = dx * dx + dy * dy;\n        }\n    }\n    \n    // Precompute shortest paths between stations using Floyd-Warshall\n    vector<vector<ll>> dist_station(N, vector<ll>(N, 1e18));\n    vector<vector<int>> next_hop(N, vector<int>(N, -1));\n    for (int i = 0; i < N; i++) {\n        dist_station[i][i] = 0;\n        next_hop[i][i] = i;\n    }\n    for (int i = 0; i < M; i++) {\n        auto [u, v, w] = edges[i];\n        if (w < dist_station[u][v]) {\n            dist_station[u][v] = w;\n            dist_station[v][u] = w;\n            next_hop[u][v] = v;\n            next_hop[v][u] = u;\n        }\n    }\n    for (int k = 0; k < N; k++) {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (dist_station[i][k] < 1e18 && dist_station[k][j] < 1e18) {\n                    if (dist_station[i][j] > dist_station[i][k] + dist_station[k][j]) {\n                        dist_station[i][j] = dist_station[i][k] + dist_station[k][j];\n                        next_hop[i][j] = next_hop[i][k];\n                    }\n                }\n            }\n        }\n    }\n    \n    // Initial assignment: assign each resident to the nearest station\n    vector<int> assignment(K);\n    vector<multiset<ll>> station_residents(N);\n    for (int j = 0; j < K; j++) {\n        int best_station = 0;\n        ll min_d_sq = dist_sq[0][j];\n        for (int i = 1; i < N; i++) {\n            if (dist_sq[i][j] < min_d_sq) {\n                min_d_sq = dist_sq[i][j];\n                best_station = i;\n            }\n        }\n        assignment[j] = best_station;\n        station_residents[best_station].insert(dist_sq[best_station][j]);\n    }\n    \n    // Function to compute P_i from a multiset of squared distances\n    auto compute_P = [](const multiset<ll>& residents) -> ll {\n        if (residents.empty()) return 0;\n        ll max_d_sq = *residents.rbegin();\n        ll P = sqrt(max_d_sq);\n        if (P * P < max_d_sq) P++;\n        return min(P, 5000LL);\n    };\n    \n    // Function to build MST on a set of stations\n    auto build_mst = [&](const set<int>& S) -> tuple<ll, set<pair<int, int>>> {\n        if (S.empty()) return {0, {}};\n        // Create a list of stations in S\n        vector<int> stations(S.begin(), S.end());\n        int n_s = stations.size();\n        // Map station index to index in the list\n        map<int, int> station_index;\n        for (int i = 0; i < n_s; i++) {\n            station_index[stations[i]] = i;\n        }\n        // Build complete graph on stations\n        vector<vector<ll>> dist_s(n_s, vector<ll>(n_s, 1e18));\n        for (int i = 0; i < n_s; i++) {\n            for (int j = i+1; j < n_s; j++) {\n                int u = stations[i], v = stations[j];\n                dist_s[i][j] = dist_station[u][v];\n                dist_s[j][i] = dist_station[u][v];\n            }\n        }\n        // Prim's algorithm\n        vector<ll> key(n_s, 1e18);\n        vector<int> parent(n_s, -1);\n        vector<bool> in_mst(n_s, false);\n        key[0] = 0;\n        priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n        pq.push({0, 0});\n        while (!pq.empty()) {\n            int u = pq.top().second;\n            pq.pop();\n            if (in_mst[u]) continue;\n            in_mst[u] = true;\n            for (int v = 0; v < n_s; v++) {\n                if (!in_mst[v] && dist_s[u][v] < key[v]) {\n                    key[v] = dist_s[u][v];\n                    parent[v] = u;\n                    pq.push({key[v], v});\n                }\n            }\n        }\n        // Collect MST edges\n        set<pair<int, int>> mst_edges;\n        ll total_cost = 0;\n        for (int i = 1; i < n_s; i++) {\n            int u = stations[i], v = stations[parent[i]];\n            if (u > v) swap(u, v);\n            mst_edges.insert({u, v});\n            total_cost += dist_station[u][v];\n        }\n        return {total_cost, mst_edges};\n    };\n    \n    // Function to get the path between two stations and mark edges\n    auto mark_path_edges = [&](int u, int v, vector<bool>& edge_on) {\n        if (u == v) return;\n        int current = u;\n        while (current != v) {\n            int next = next_hop[current][v];\n            int u1 = current, v1 = next;\n            if (u1 > v1) swap(u1, v1);\n            auto it = edge_index_map.find({u1, v1});\n            if (it != edge_index_map.end()) {\n                edge_on[it->second] = true;\n            }\n            current = next;\n        }\n    };\n    \n    // Initial set S: stations with at least one resident\n    set<int> S;\n    for (int i = 0; i < N; i++) {\n        if (!station_residents[i].empty()) {\n            S.insert(i);\n        }\n    }\n    \n    // Build initial MST\n    auto [current_edge_cost, mst_edges] = build_mst(S);\n    \n    // Compute initial power cost\n    ll current_power_cost = 0;\n    vector<ll> P(N, 0);\n    for (int i = 0; i < N; i++) {\n        P[i] = compute_P(station_residents[i]);\n        current_power_cost += P[i] * P[i];\n    }\n    ll current_total_cost = current_power_cost + current_edge_cost;\n    \n    // Local search improvement\n    bool improved = true;\n    int max_iter = 10;\n    for (int iter = 0; iter < max_iter && improved; iter++) {\n        improved = false;\n        // Create a list of residents in random order\n        vector<int> residents(K);\n        iota(residents.begin(), residents.end(), 0);\n        random_shuffle(residents.begin(), residents.end());\n        \n        for (int j : residents) {\n            int old_station = assignment[j];\n            ll old_d_sq = dist_sq[old_station][j];\n            // Remove j from old_station\n            station_residents[old_station].erase(station_residents[old_station].find(old_d_sq));\n            ll old_P_old = P[old_station];\n            P[old_station] = compute_P(station_residents[old_station]);\n            ll power_cost_without_j = current_power_cost - old_P_old * old_P_old + P[old_station] * P[old_station];\n            \n            // Try reassigning to other stations in S\n            for (int new_station : S) {\n                if (new_station == old_station) continue;\n                ll new_d_sq = dist_sq[new_station][j];\n                ll old_P_new = P[new_station];\n                station_residents[new_station].insert(new_d_sq);\n                P[new_station] = compute_P(station_residents[new_station]);\n                ll new_power_cost = power_cost_without_j - old_P_new * old_P_new + P[new_station] * P[new_station];\n                \n                // Check if power cost improves\n                if (new_power_cost < current_power_cost) {\n                    // Accept reassignment\n                    assignment[j] = new_station;\n                    current_power_cost = new_power_cost;\n                    improved = true;\n                    // Update S if old_station becomes empty\n                    if (station_residents[old_station].empty()) {\n                        S.erase(old_station);\n                    }\n                    // new_station is already in S\n                    break;\n                } else {\n                    // Revert changes to new_station\n                    station_residents[new_station].erase(station_residents[new_station].find(new_d_sq));\n                    P[new_station] = old_P_new;\n                }\n            }\n            // If not reassigned, revert old_station\n            if (assignment[j] == old_station) {\n                station_residents[old_station].insert(old_d_sq);\n                P[old_station] = old_P_old;\n            }\n        }\n        \n        // After reassignment, update S and rebuild MST\n        S.clear();\n        for (int i = 0; i < N; i++) {\n            if (!station_residents[i].empty()) {\n                S.insert(i);\n            }\n        }\n        tie(current_edge_cost, mst_edges) = build_mst(S);\n        current_total_cost = current_power_cost + current_edge_cost;\n    }\n    \n    // Final output preparation\n    // Compute final P values\n    for (int i = 0; i < N; i++) {\n        P[i] = compute_P(station_residents[i]);\n    }\n    \n    // Mark edges for MST\n    vector<bool> edge_on(M, false);\n    for (auto [u, v] : mst_edges) {\n        mark_path_edges(u, v, edge_on);\n    }\n    \n    // Output P and B\n    for (int i = 0; i < N; i++) {\n        cout << P[i];\n        if (i < N-1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    for (int i = 0; i < M; i++) {\n        cout << (edge_on[i] ? 1 : 0);\n        if (i < M-1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <tuple>\nusing namespace std;\n\nconst int N = 30;\n\nbool violates(const vector<vector<int>>& pyramid, int x, int y) {\n    if (x >= N - 1) return false;\n    int current_val = pyramid[x][y];\n    int child1_val = pyramid[x+1][y];\n    int child2_val = pyramid[x+1][y+1];\n    return (current_val > child1_val) || (current_val > child2_val);\n}\n\nint main() {\n    vector<vector<int>> pyramid(N);\n    for (int x = 0; x < N; x++) {\n        for (int y = 0; y <= x; y++) {\n            int num;\n            cin >> num;\n            pyramid[x].push_back(num);\n        }\n    }\n\n    vector<tuple<int, int, int, int>> swaps;\n\n    while (true) {\n        int max_val = -1;\n        int max_x = -1;\n        int max_y = -1;\n        bool found_violation = false;\n\n        for (int x = 0; x < N - 1; x++) {\n            for (int y = 0; y <= x; y++) {\n                if (violates(pyramid, x, y)) {\n                    int val = pyramid[x][y];\n                    if (val > max_val) {\n                        max_val = val;\n                        max_x = x;\n                        max_y = y;\n                        found_violation = true;\n                    }\n                }\n            }\n        }\n\n        if (!found_violation) {\n            break;\n        }\n\n        int x = max_x;\n        int y = max_y;\n        int child1_x = x + 1;\n        int child1_y = y;\n        int child2_x = x + 1;\n        int child2_y = y + 1;\n\n        int child1_val = pyramid[child1_x][child1_y];\n        int child2_val = pyramid[child2_x][child2_y];\n\n        int swap_x, swap_y;\n        if (child1_val <= child2_val) {\n            swap_x = child1_x;\n            swap_y = child1_y;\n        } else {\n            swap_x = child2_x;\n            swap_y = child2_y;\n        }\n\n        swap(pyramid[x][y], pyramid[swap_x][swap_y]);\n        swaps.push_back({x, y, swap_x, swap_y});\n    }\n\n    cout << swaps.size() << endl;\n    for (const auto& op : swaps) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << endl;\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = 4;\n\nvector<vector<int>> grid;\nvector<pair<int, int>> container_positions;\n\n// Directions: up, down, left, right\nconst int di[] = {-1, 1, 0, 0};\nconst int dj[] = {0, 0, -1, 1};\n\n// Check if a position is valid and empty\nbool is_valid(int i, int j) {\n    return i >= 0 && i < D && j >= 0 && j < D && grid[i][j] == -1;\n}\n\n// BFS to find reachable positions from entrance\nvector<pair<int, int>> get_reachable_positions() {\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> reachable;\n    \n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            \n            if (ni >= 0 && ni < D && nj >= 0 && nj < D && \n                !visited[ni][nj] && grid[ni][nj] == -1) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                reachable.push_back({ni, nj});\n            }\n        }\n    }\n    \n    return reachable;\n}\n\n// Calculate Manhattan distance from entrance\nint distance_from_entrance(int i, int j) {\n    return abs(i - ENTRANCE_I) + abs(j - ENTRANCE_J);\n}\n\n// Find best position for placement based on container number\npair<int, int> find_best_position(int container_num, int total_containers) {\n    auto reachable = get_reachable_positions();\n    \n    if (reachable.empty()) {\n        // Should not happen if grid is properly connected\n        for (int i = 0; i < D; i++) {\n            for (int j = 0; j < D; j++) {\n                if (grid[i][j] == -1) {\n                    return {i, j};\n                }\n            }\n        }\n    }\n    \n    // Sort positions by distance from entrance\n    sort(reachable.begin(), reachable.end(), [](const pair<int, int>& a, const pair<int, int>& b) {\n        int dist_a = distance_from_entrance(a.first, a.second);\n        int dist_b = distance_from_entrance(b.first, b.second);\n        return dist_a < dist_b;\n    });\n    \n    // Use container number to determine placement strategy\n    // Lower numbers should be placed closer to exit for easier retrieval\n    int idx = (container_num * reachable.size()) / total_containers;\n    idx = min(idx, (int)reachable.size() - 1);\n    \n    return reachable[idx];\n}\n\n// Get accessible containers for retrieval\nvector<pair<int, int>> get_accessible_containers() {\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> accessible;\n    \n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        // Check if current position has a container\n        if (grid[i][j] >= 0) {\n            accessible.push_back({i, j});\n        }\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            \n            if (ni >= 0 && ni < D && nj >= 0 && nj < D && \n                !visited[ni][nj] && grid[ni][nj] != -2) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    return accessible;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read warehouse configuration\n    int N;\n    cin >> D >> N;\n    \n    // Initialize grid: -2 = obstacle, -1 = empty, >=0 = container number\n    grid.assign(D, vector<int>(D, -1));\n    container_positions.clear();\n    \n    // Mark entrance and adjacent squares\n    grid[ENTRANCE_I][ENTRANCE_J] = -3; // Entrance\n    grid[ENTRANCE_I][ENTRANCE_J-1] = -1;\n    grid[ENTRANCE_I][ENTRANCE_J+1] = -1;\n    grid[ENTRANCE_I+1][ENTRANCE_J] = -1;\n    \n    // Read obstacles\n    for (int k = 0; k < N; k++) {\n        int ri, rj;\n        cin >> ri >> rj;\n        grid[ri][rj] = -2; // Obstacle\n    }\n    \n    int total_containers = D * D - 1 - N;\n    \n    // Process container arrivals\n    for (int d = 0; d < total_containers; d++) {\n        int container_num;\n        cin >> container_num;\n        \n        // Find best position for this container\n        auto [pi, pj] = find_best_position(container_num, total_containers);\n        \n        // Place container\n        grid[pi][pj] = container_num;\n        container_positions.push_back({pi, pj});\n        \n        // Output placement\n        cout << pi << \" \" << pj << endl;\n        cout.flush();\n    }\n    \n    // Determine retrieval order using greedy strategy\n    vector<pair<int, int>> retrieval_order;\n    \n    while (retrieval_order.size() < total_containers) {\n        auto accessible = get_accessible_containers();\n        \n        if (accessible.empty()) {\n            break; // Should not happen\n        }\n        \n        // Find container with smallest number\n        int best_idx = 0;\n        int best_num = grid[accessible[0].first][accessible[0].second];\n        \n        for (int i = 1; i < accessible.size(); i++) {\n            int current_num = grid[accessible[i].first][accessible[i].second];\n            if (current_num < best_num) {\n                best_num = current_num;\n                best_idx = i;\n            }\n        }\n        \n        auto [qi, qj] = accessible[best_idx];\n        retrieval_order.push_back({qi, qj});\n        grid[qi][qj] = -1; // Remove container\n    }\n    \n    // Output retrieval order\n    for (auto [qi, qj] : retrieval_order) {\n        cout << qi << \" \" << qj << endl;\n    }\n    cout.flush();\n    \n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> grid(n, vector<int>(n));\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> grid[i][j];\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cout << grid[i][j];\n            if (j < n - 1) cout << \" \";\n        }\n        cout << endl;\n    }\n    \n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n\n    vector<double> ratings(N, 1000.0);\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n\n    int p = 0;\n\n    for (int q = 0; q < Q; q++) {\n        sort(indices.begin(), indices.end(), [&ratings](int a, int b) {\n            return ratings[a] > ratings[b];\n        });\n\n        int i = indices[p];\n        int j = indices[p + 1];\n\n        cout << \"1 1 \" << i << \" \" << j << endl;\n        cout.flush();\n\n        string result;\n        cin >> result;\n\n        double outcome_i, outcome_j;\n        if (result == \">\") {\n            outcome_i = 1.0;\n            outcome_j = 0.0;\n        } else if (result == \"<\") {\n            outcome_i = 0.0;\n            outcome_j = 1.0;\n        } else {\n            outcome_i = 0.5;\n            outcome_j = 0.5;\n        }\n\n        const double K = 32.0;\n        double diff = ratings[j] - ratings[i];\n        double expected_i = 1.0 / (1.0 + pow(10.0, diff / 400.0));\n        double expected_j = 1.0 - expected_i;\n\n        ratings[i] += K * (outcome_i - expected_i);\n        ratings[j] += K * (outcome_j - expected_j);\n\n        p++;\n        if (p >= N - 1) {\n            p = 0;\n        }\n    }\n\n    vector<int> sorted_indices(N);\n    iota(sorted_indices.begin(), sorted_indices.end(), 0);\n    sort(sorted_indices.begin(), sorted_indices.end(), [&ratings](int a, int b) {\n        return ratings[a] > ratings[b];\n    });\n\n    vector<double> bin_sums(D, 0.0);\n    vector<int> assignment(N);\n    for (int idx : sorted_indices) {\n        int min_bin = 0;\n        for (int b = 1; b < D; b++) {\n            if (bin_sums[b] < bin_sums[min_bin]) {\n                min_bin = b;\n            }\n        }\n        assignment[idx] = min_bin;\n        bin_sums[min_bin] += ratings[idx];\n    }\n\n    for (int i = 0; i < N; i++) {\n        cout << assignment[i];\n        if (i < N - 1) {\n            cout << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <queue>\n#include <functional>\n#include <set>\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    \n    vector<vector<int>> stacks(m + 1);\n    vector<int> box_pos(n + 1, -1);\n    vector<int> box_height(n + 1, -1);\n    \n    // Read initial configuration\n    for (int i = 1; i <= m; i++) {\n        for (int j = 0; j < n / m; j++) {\n            int box;\n            cin >> box;\n            stacks[i].push_back(box);\n            box_pos[box] = i;\n            box_height[box] = j + 1;\n        }\n    }\n    \n    vector<pair<int, int>> operations;\n    int next_box = 1;\n    vector<bool> carried_out(n + 1, false);\n    \n    int boxes_per_stack = n / m;\n    \n    // Function to check if a box is at top\n    auto is_top = [&](int box) {\n        int stack_idx = box_pos[box];\n        return !stacks[stack_idx].empty() && stacks[stack_idx].back() == box;\n    };\n    \n    // Function to find boxes above a given box\n    auto get_boxes_above = [&](int box) -> vector<int> {\n        int stack_idx = box_pos[box];\n        auto it = find(stacks[stack_idx].begin(), stacks[stack_idx].end(), box);\n        if (it == stacks[stack_idx].end()) return {};\n        return vector<int>(it + 1, stacks[stack_idx].end());\n    };\n    \n    // Function to find an empty stack\n    auto find_empty_stack = [&]() {\n        for (int i = 1; i <= m; i++) {\n            if (stacks[i].empty()) return i;\n        }\n        return -1;\n    };\n    \n    // Optimized function to find the best temporary stack\n    auto find_temporary_stack = [&](int avoid_stack, const vector<int>& boxes_above) {\n        int best_stack = -1;\n        int best_score = -1000000;\n        \n        int segment_min = *min_element(boxes_above.begin(), boxes_above.end());\n        int segment_max = *max_element(boxes_above.begin(), boxes_above.end());\n        \n        for (int i = 1; i <= m; i++) {\n            if (i == avoid_stack) continue;\n            \n            int score = 0;\n            \n            // Strong preference for empty stacks\n            if (stacks[i].empty()) {\n                score += 1000;\n            } else {\n                int top_box = stacks[i].back();\n                \n                // Prefer stacks where top box is much larger than segment\n                if (top_box > segment_max + 10) {\n                    score += 400;\n                } else if (top_box > segment_max) {\n                    score += 200;\n                }\n                \n                // Penalize stacks that contain boxes we'll need soon\n                for (int box_in_stack : stacks[i]) {\n                    if (box_in_stack >= next_box && box_in_stack <= next_box + 15) {\n                        score -= 300;\n                    }\n                    // Strong penalty for blocking boxes smaller than segment\n                    if (box_in_stack < segment_min && !carried_out[box_in_stack]) {\n                        score -= 600;\n                    }\n                }\n                \n                // Bonus if this stack's boxes are mostly larger than what we're moving\n                int larger_count = 0;\n                for (int box_in_stack : stacks[i]) {\n                    if (box_in_stack > segment_max) larger_count++;\n                }\n                score += larger_count * 10;\n            }\n            \n            // Small bonus for stacks that have been used less recently\n            score += (i % 3); // Simple rotation to avoid bias\n            \n            if (score > best_score) {\n                best_score = score;\n                best_stack = i;\n            }\n        }\n        \n        return best_stack;\n    };\n    \n    // Function to check if we should carry out multiple boxes at once\n    auto carry_out_available_boxes = [&]() {\n        bool carried_any = false;\n        // Only carry out boxes in strict sequential order\n        while (next_box <= n && !carried_out[next_box] && is_top(next_box)) {\n            operations.push_back({next_box, 0});\n            carried_out[next_box] = true;\n            int stack_idx = box_pos[next_box];\n            stacks[stack_idx].pop_back();\n            next_box++;\n            carried_any = true;\n            \n            // After carrying out, check if we can carry out more immediately\n            if (operations.size() % 5 == 0) break; // Limit to prevent missing optimization opportunities\n        }\n        return carried_any;\n    };\n    \n    // Function to check if we can optimize by moving a different box\n    auto check_optimization_opportunity = [&]() -> bool {\n        // Look ahead a few boxes to see if we can free multiple boxes with one move\n        for (int lookahead = next_box + 1; lookahead <= min(next_box + 5, n); lookahead++) {\n            if (carried_out[lookahead]) continue;\n            \n            int lookahead_stack = box_pos[lookahead];\n            if (lookahead_stack == box_pos[next_box] && is_top(lookahead)) {\n                // If this box is in the same stack as next_box and is at top,\n                // we might be able to optimize by moving a box that blocks both\n                vector<int> boxes_above_next = get_boxes_above(next_box);\n                if (boxes_above_next.size() > 1) {\n                    // Check if moving a different box would be more optimal\n                    for (int i = 1; i < boxes_above_next.size(); i++) {\n                        int candidate_box = boxes_above_next[i];\n                        if (candidate_box > lookahead) {\n                            // This box blocks both next_box and lookahead\n                            int temp_stack = find_temporary_stack(box_pos[next_box], {candidate_box});\n                            if (temp_stack != -1) {\n                                operations.push_back({candidate_box, temp_stack});\n                                \n                                // Update stack configuration\n                                int current_stack = box_pos[candidate_box];\n                                auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), candidate_box);\n                                if (it != stacks[current_stack].end()) {\n                                    vector<int> moving_boxes(it, stacks[current_stack].end());\n                                    stacks[current_stack].erase(it, stacks[current_stack].end());\n                                    stacks[temp_stack].insert(stacks[temp_stack].end(), moving_boxes.begin(), moving_boxes.end());\n                                    \n                                    for (int j = 0; j < moving_boxes.size(); j++) {\n                                        box_pos[moving_boxes[j]] = temp_stack;\n                                        box_height[moving_boxes[j]] = stacks[temp_stack].size() - moving_boxes.size() + j + 1;\n                                    }\n                                }\n                                return true;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        return false;\n    };\n    \n    // Main loop\n    while (next_box <= n) {\n        // First, try to carry out any available boxes in order\n        if (carry_out_available_boxes()) {\n            continue;\n        }\n        \n        // Check for optimization opportunities\n        if (operations.size() % 10 == 0 && check_optimization_opportunity()) {\n            continue;\n        }\n        \n        // If next_box is blocked, we need to move boxes above it\n        int current_stack = box_pos[next_box];\n        vector<int> boxes_above = get_boxes_above(next_box);\n        \n        if (boxes_above.empty()) {\n            next_box++;\n            continue;\n        }\n        \n        // Find the best temporary stack for this segment\n        int temp_stack = find_temporary_stack(current_stack, boxes_above);\n        \n        if (temp_stack == -1) {\n            // Fallback: use first available stack\n            for (int i = 1; i <= m; i++) {\n                if (i != current_stack) {\n                    temp_stack = i;\n                    break;\n                }\n            }\n            if (temp_stack == -1) temp_stack = 1;\n        }\n        \n        // Move the entire segment by moving its bottom box\n        int box_to_move = boxes_above[0];\n        operations.push_back({box_to_move, temp_stack});\n        \n        // Update stack configuration\n        auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), box_to_move);\n        if (it != stacks[current_stack].end()) {\n            vector<int> moving_boxes(it, stacks[current_stack].end());\n            stacks[current_stack].erase(it, stacks[current_stack].end());\n            stacks[temp_stack].insert(stacks[temp_stack].end(), moving_boxes.begin(), moving_boxes.end());\n            \n            // Update positions\n            for (int i = 0; i < moving_boxes.size(); i++) {\n                box_pos[moving_boxes[i]] = temp_stack;\n                box_height[moving_boxes[i]] = stacks[temp_stack].size() - moving_boxes.size() + i + 1;\n            }\n        }\n        \n        // Aggressive safety check\n        if (operations.size() > 4950) {\n            // Emergency: try to carry out as many boxes as possible\n            for (int i = next_box; i <= n; i++) {\n                if (!carried_out[i] && is_top(i)) {\n                    operations.push_back({i, 0});\n                    carried_out[i] = true;\n                    stacks[box_pos[i]].pop_back();\n                    if (i == next_box) next_box++;\n                }\n            }\n            if (next_box > n) break;\n        }\n    }\n    \n    // Output operations\n    for (auto op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n    \n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nvector<string> h, v;\nvector<vector<bool>> visited;\nint N;\nstring moves;\n\nconst int di[] = {0, 1, 0, -1};\nconst int dj[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\n\nvoid dfs(int i, int j) {\n    visited[i][j] = true;\n    for (int k = 0; k < 4; k++) {\n        int ni = i + di[k];\n        int nj = j + dj[k];\n        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n        if (visited[ni][nj]) continue;\n        if (di[k] == 0) {\n            int col = min(j, nj);\n            if (v[i][col] == '1') continue;\n        } else {\n            int row = min(i, ni);\n            if (h[row][j] == '1') continue;\n        }\n        moves += dir[k];\n        dfs(ni, nj);\n        moves += dir[(k + 2) % 4];\n    }\n}\n\nint main() {\n    cin >> N;\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; i++) {\n        cin >> h[i];\n    }\n    v.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\n    }\n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n        }\n    }\n\n    visited.resize(N, vector<bool>(N, false));\n    moves = \"\";\n    dfs(0, 0);\n    cout << moves << endl;\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <map>\n#include <limits>\n#include <cmath>\n#include <utility>\n\nusing namespace std;\n\nconst int INF = numeric_limits<int>::max();\n\nint dist(pair<int, int> a, pair<int, int> b) {\n    return abs(a.first - b.first) + abs(a.second - b.second);\n}\n\npair<int, pair<int, int>> cost_to_type(const string& str, const pair<int, int>& start, const map<char, vector<pair<int, int>>>& letter_points) {\n    int L = str.length();\n    if (L == 0) return {0, start};\n\n    vector<map<pair<int, int>, int>> dp(L);\n    vector<map<pair<int, int>, pair<int, int>>> prev(L);\n\n    char c0 = str[0];\n    if (letter_points.find(c0) == letter_points.end()) return {INF, {0,0}};\n    for (auto p : letter_points.at(c0)) {\n        int cost = dist(start, p) + 1;\n        dp[0][p] = cost;\n        prev[0][p] = start;\n    }\n\n    for (int i = 1; i < L; i++) {\n        char c = str[i];\n        if (letter_points.find(c) == letter_points.end()) return {INF, {0,0}};\n        for (auto p : letter_points.at(c)) {\n            int best_cost = INF;\n            pair<int, int> best_prev;\n            char prev_c = str[i-1];\n            if (letter_points.find(prev_c) == letter_points.end()) return {INF, {0,0}};\n            for (auto q : letter_points.at(prev_c)) {\n                if (dp[i-1].find(q) == dp[i-1].end()) continue;\n                int cost = dp[i-1][q] + dist(q, p) + 1;\n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_prev = q;\n                }\n            }\n            if (best_cost < INF) {\n                dp[i][p] = best_cost;\n                prev[i][p] = best_prev;\n            }\n        }\n    }\n\n    int min_cost = INF;\n    pair<int, int> end_pos = start;\n    char last_c = str[L-1];\n    if (letter_points.find(last_c) == letter_points.end()) return {INF, {0,0}};\n    for (auto p : letter_points.at(last_c)) {\n        if (dp[L-1].find(p) != dp[L-1].end() && dp[L-1][p] < min_cost) {\n            min_cost = dp[L-1][p];\n            end_pos = p;\n        }\n    }\n    if (min_cost == INF) return {INF, start};\n    return {min_cost, end_pos};\n}\n\nint compute_overlap(const string& S, const string& B) {\n    int max_possible = min(S.length(), B.length());\n    for (int l = max_possible; l > 0; l--) {\n        if (S.substr(S.length() - l) == B.substr(0, l)) {\n            return l;\n        }\n    }\n    return 0;\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int s_i, s_j;\n    cin >> s_i >> s_j;\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    vector<string> words(M);\n    for (int i = 0; i < M; i++) {\n        cin >> words[i];\n    }\n\n    map<char, vector<pair<int, int>>> letter_points;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            char c = grid[i][j];\n            letter_points[c].push_back({i, j});\n        }\n    }\n\n    pair<int, int> current_pos = {s_i, s_j};\n    vector<string> uncovered = words;\n    string S = \"\";\n\n    const int BEAM_WIDTH = 10;\n\n    while (!uncovered.empty()) {\n        if (uncovered.size() == 1) {\n            string B = uncovered[0];\n            int k1 = compute_overlap(S, B);\n            string suffix_B = B.substr(k1);\n            auto [cost_B, pos_B] = cost_to_type(suffix_B, current_pos, letter_points);\n            S += suffix_B;\n            current_pos = pos_B;\n            uncovered.clear();\n        } else {\n            vector<pair<int, string>> overlaps;\n            for (string B : uncovered) {\n                int ov = compute_overlap(S, B);\n                overlaps.push_back({ov, B});\n            }\n            sort(overlaps.begin(), overlaps.end(), [](const pair<int, string>& a, const pair<int, string>& b) {\n                return a.first > b.first;\n            });\n            int K = min(BEAM_WIDTH, (int)uncovered.size());\n            vector<string> top_B;\n            for (int i = 0; i < K; i++) {\n                top_B.push_back(overlaps[i].second);\n            }\n\n            int best_total_cost = INF;\n            string best_B;\n\n            for (string B : top_B) {\n                int k1 = compute_overlap(S, B);\n                string suffix_B = B.substr(k1);\n                auto [cost_B, pos_B] = cost_to_type(suffix_B, current_pos, letter_points);\n                string new_S = S + suffix_B;\n\n                vector<pair<int, string>> overlaps2;\n                for (string C : uncovered) {\n                    if (C == B) continue;\n                    int ov2 = compute_overlap(new_S, C);\n                    overlaps2.push_back({ov2, C});\n                }\n                sort(overlaps2.begin(), overlaps2.end(), [](const pair<int, string>& a, const pair<int, string>& b) {\n                    return a.first > b.first;\n                });\n                int L = min(BEAM_WIDTH, (int)overlaps2.size());\n                if (L == 0) continue;\n                for (int j = 0; j < L; j++) {\n                    string C = overlaps2[j].second;\n                    int k2 = compute_overlap(new_S, C);\n                    string suffix_C = C.substr(k2);\n                    auto [cost_C, pos_C] = cost_to_type(suffix_C, pos_B, letter_points);\n                    int total_cost = cost_B + cost_C;\n                    if (total_cost < best_total_cost) {\n                        best_total_cost = total_cost;\n                        best_B = B;\n                    }\n                }\n            }\n\n            if (best_total_cost == INF) {\n                best_B = uncovered[0];\n            }\n            int k1 = compute_overlap(S, best_B);\n            string suffix_B = best_B.substr(k1);\n            auto [cost_B, pos_B] = cost_to_type(suffix_B, current_pos, letter_points);\n            S += suffix_B;\n            current_pos = pos_B;\n            uncovered.erase(find(uncovered.begin(), uncovered.end(), best_B));\n        }\n    }\n\n    int L = S.size();\n    vector<vector<pair<int, int>>> points_for_S(L);\n    for (int i = 0; i < L; i++) {\n        points_for_S[i] = letter_points[S[i]];\n    }\n\n    pair<int, int> initial = {s_i, s_j};\n    vector<map<pair<int, int>, int>> dp(L);\n    vector<map<pair<int, int>, pair<int, int>>> prev(L);\n\n    for (auto p : points_for_S[0]) {\n        int cost = dist(initial, p) + 1;\n        dp[0][p] = cost;\n        prev[0][p] = initial;\n    }\n\n    for (int i = 1; i < L; i++) {\n        for (auto p : points_for_S[i]) {\n            int best_cost = INF;\n            pair<int, int> best_prev;\n            for (auto q : points_for_S[i-1]) {\n                if (dp[i-1].find(q) == dp[i-1].end()) continue;\n                int cost = dp[i-1][q] + dist(q, p) + 1;\n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_prev = q;\n                }\n            }\n            if (best_cost < INF) {\n                dp[i][p] = best_cost;\n                prev[i][p] = best_prev;\n            }\n        }\n    }\n\n    int min_cost = INF;\n    pair<int, int> best_point;\n    for (auto p : points_for_S[L-1]) {\n        if (dp[L-1].find(p) != dp[L-1].end() && dp[L-1][p] < min_cost) {\n            min_cost = dp[L-1][p];\n            best_point = p;\n        }\n    }\n\n    vector<pair<int, int>> sequence;\n    pair<int, int> current = best_point;\n    for (int i = L-1; i >= 0; i--) {\n        sequence.push_back(current);\n        if (i > 0) {\n            current = prev[i][current];\n        }\n    }\n    reverse(sequence.begin(), sequence.end());\n\n    for (auto p : sequence) {\n        cout << p.first << \" \" << p.second << endl;\n    }\n\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <tuple>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n\n    vector<vector<pair<int, int>>> fields(M);\n    int S = 0;\n    \n    for (int k = 0; k < M; k++) {\n        int d;\n        cin >> d;\n        S += d;\n        for (int i = 0; i < d; i++) {\n            int x, y;\n            cin >> x >> y;\n            fields[k].push_back(make_pair(x, y));\n        }\n    }\n\n    // Precompute expected oil reserves for each square\n    vector<vector<double>> weight(N, vector<double>(N, 0.0));\n    \n    for (const auto& shape : fields) {\n        int max_i = 0, max_j = 0;\n        for (auto p : shape) {\n            max_i = max(max_i, p.first);\n            max_j = max(max_j, p.second);\n        }\n        \n        int total_placements = (N - max_i) * (N - max_j);\n        if (total_placements <= 0) continue;\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                int count = 0;\n                for (auto p : shape) {\n                    int di = i - p.first;\n                    int dj = j - p.second;\n                    if (di >= 0 && di < N - max_i && dj >= 0 && dj < N - max_j) {\n                        count++;\n                    }\n                }\n                weight[i][j] += (double)count / total_placements;\n            }\n        }\n    }\n\n    // Create and sort squares by expected oil reserves\n    vector<tuple<double, int, int>> squares;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            squares.push_back(make_tuple(weight[i][j], i, j));\n        }\n    }\n    \n    sort(squares.begin(), squares.end(), [](const tuple<double, int, int>& a, const tuple<double, int, int>& b) {\n        return get<0>(a) > get<0>(b);\n    });\n\n    // Drill squares in priority order until we find all oil\n    vector<pair<int, int>> oil_squares;\n    int cumulative_sum = 0;\n    \n    for (const auto& square : squares) {\n        double w = get<0>(square);\n        int i = get<1>(square);\n        int j = get<2>(square);\n        \n        cout << \"q 1 \" << i << \" \" << j << endl;\n        int resp;\n        cin >> resp;\n        \n        if (resp > 0) {\n            oil_squares.push_back(make_pair(i, j));\n            cumulative_sum += resp;\n        }\n        \n        if (cumulative_sum >= S) {\n            break;\n        }\n    }\n\n    // Output final answer\n    cout << \"a \" << oil_squares.size();\n    for (auto p : oil_squares) {\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << endl;\n\n    int result;\n    cin >> result;\n    \n    return 0;\n}","ahc031":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <climits>\n\nusing namespace std;\n\nint main() {\n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    // Store strip boundaries for each day\n    vector<vector<int>> strip_boundaries(D, vector<int>(N + 1, 0));\n    vector<vector<int>> strip_assignments(D, vector<int>(N, 0));\n    \n    // Process each day\n    for (int d = 0; d < D; d++) {\n        // Calculate total desired area\n        int total_desired = 0;\n        for (int k = 0; k < N; k++) {\n            total_desired += a[d][k];\n        }\n        \n        // Sort areas while preserving original indices\n        vector<pair<int, int>> sorted_areas;\n        for (int k = 0; k < N; k++) {\n            sorted_areas.push_back({a[d][k], k});\n        }\n        sort(sorted_areas.begin(), sorted_areas.end());\n        \n        // Try to reuse previous day's layout if it's reasonably good\n        bool reuse_layout = false;\n        if (d > 0) {\n            int total_deficit = 0;\n            for (int k = 0; k < N; k++) {\n                int strip_height = strip_boundaries[d-1][k+1] - strip_boundaries[d-1][k];\n                int strip_area = strip_height * W;\n                total_deficit += max(0, a[d][k] - strip_area);\n            }\n            \n            // Reuse if deficit is acceptable (heuristic threshold)\n            if (total_deficit * 100 < W * 5) {\n                strip_boundaries[d] = strip_boundaries[d-1];\n                strip_assignments[d] = strip_assignments[d-1];\n                reuse_layout = true;\n            }\n        }\n        \n        if (!reuse_layout) {\n            // Calculate new strip boundaries proportionally to area requirements\n            int cumulative_height = 0;\n            for (int k = 0; k < N; k++) {\n                double proportion = (double)sorted_areas[k].first / total_desired;\n                int strip_height = max(1, (int)round(proportion * W));\n                \n                strip_boundaries[d][k] = cumulative_height;\n                cumulative_height += strip_height;\n                \n                // Store assignment mapping\n                strip_assignments[d][sorted_areas[k].second] = k;\n            }\n            strip_boundaries[d][N] = W;\n            \n            // Adjust if we exceeded W\n            if (cumulative_height > W) {\n                // Redistribute proportionally with integer rounding\n                cumulative_height = 0;\n                for (int k = 0; k < N; k++) {\n                    double proportion = (double)sorted_areas[k].first / total_desired;\n                    int strip_height = max(1, (int)(proportion * W));\n                    strip_boundaries[d][k] = cumulative_height;\n                    cumulative_height += strip_height;\n                    \n                    // Update assignment mapping\n                    strip_assignments[d][sorted_areas[k].second] = k;\n                }\n                strip_boundaries[d][N] = W;\n            }\n        }\n        \n        // Ensure boundaries are valid and non-overlapping\n        for (int k = 0; k <= N; k++) {\n            strip_boundaries[d][k] = max(0, min(W, strip_boundaries[d][k]));\n        }\n        \n        // Ensure boundaries are strictly increasing\n        for (int k = 1; k <= N; k++) {\n            if (strip_boundaries[d][k] <= strip_boundaries[d][k-1]) {\n                strip_boundaries[d][k] = strip_boundaries[d][k-1] + 1;\n            }\n        }\n        strip_boundaries[d][N] = W;\n    }\n    \n    // Output rectangles\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            int strip_idx = strip_assignments[d][k];\n            int i0 = strip_boundaries[d][strip_idx];\n            int i1 = strip_boundaries[d][strip_idx + 1];\n            int j0 = 0;\n            int j1 = W;\n            \n            // Ensure valid rectangle (non-zero area)\n            if (i0 >= i1) {\n                i1 = i0 + 1;\n            }\n            if (i1 > W) {\n                i1 = W;\n            }\n            \n            cout << i0 << \" \" << j0 << \" \" << i1 << \" \" << j1 << endl;\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <tuple>\n#include <set>\n#include <map>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <chrono>\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\n\nint main() {\n    auto start_time = chrono::high_resolution_clock::now();\n    srand(time(0));\n\n    int n, m, k;\n    cin >> n >> m >> k;\n    \n    int a[N][N];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> a[i][j];\n        }\n    }\n    \n    int stamps[M][3][3];\n    for (int mm = 0; mm < m; mm++) {\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                cin >> stamps[mm][i][j];\n            }\n        }\n    }\n    \n    int u[N][N];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            u[i][j] = a[i][j] % MOD;\n        }\n    }\n    \n    vector<tuple<int, int, int>> operations;\n    int max_p = n - 3;\n    int max_q = n - 3;\n    \n    // Phase 1: Aggressive greedy initialization\n    for (int step = 0; step < k; step++) {\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1100) break; // Leave more time for annealing\n        \n        int best_delta = -1000000000;\n        int best_m = -1, best_p = -1, best_q = -1;\n        \n        // Increased sampling for better exploration\n        int samples = min(120, m * (max_p + 1) * (max_q + 1));\n        for (int s = 0; s < samples; s++) {\n            int mm = rand() % m;\n            int p = rand() % (max_p + 1);\n            int q = rand() % (max_q + 1);\n            \n            int delta = 0;\n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    int x = p + i;\n                    int y = q + j;\n                    int current_u = u[x][y];\n                    int s_val = stamps[mm][i][j];\n                    int new_u = (current_u + s_val) % MOD;\n                    if (new_u < 0) new_u += MOD;\n                    delta += new_u - current_u;\n                }\n            }\n            \n            if (delta > best_delta) {\n                best_delta = delta;\n                best_m = mm;\n                best_p = p;\n                best_q = q;\n            }\n        }\n        \n        // More aggressive: add operations even with small negative delta in early stages\n        if (best_delta > 0 || operations.size() < k * 0.75) {\n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    int x = best_p + i;\n                    int y = best_q + j;\n                    int s_val = stamps[best_m][i][j];\n                    u[x][y] = (u[x][y] + s_val) % MOD;\n                    if (u[x][y] < 0) u[x][y] += MOD;\n                }\n            }\n            operations.push_back(make_tuple(best_m, best_p, best_q));\n        } else {\n            break;\n        }\n    }\n    \n    // Phase 2: More aggressive simulated annealing\n    double temperature = 8000.0; // Higher initial temperature\n    double cooling_rate = 0.94; // Slower cooling\n    int iterations = 0;\n    const int max_iterations = 8000; // More iterations\n    \n    while (iterations < max_iterations) {\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1950) break;\n        \n        if (operations.empty()) break;\n        \n        int idx = rand() % operations.size();\n        int old_m, old_p, old_q;\n        tie(old_m, old_p, old_q) = operations[idx];\n        \n        int new_m = rand() % M;\n        int new_p = rand() % (max_p + 1);\n        int new_q = rand() % (max_q + 1);\n        \n        if (old_m == new_m && old_p == new_p && old_q == new_q) {\n            iterations++;\n            continue;\n        }\n        \n        // Calculate delta efficiently\n        int delta_score = 0;\n        set<pair<int, int>> affected_cells;\n        map<pair<int, int>, int> changes;\n        \n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = old_p + i;\n                int y = old_q + j;\n                affected_cells.insert({x, y});\n                changes[{x, y}] -= stamps[old_m][i][j];\n            }\n        }\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = new_p + i;\n                int y = new_q + j;\n                affected_cells.insert({x, y});\n                changes[{x, y}] += stamps[new_m][i][j];\n            }\n        }\n        \n        for (auto cell : affected_cells) {\n            int x = cell.first, y = cell.second;\n            int current_u = u[x][y];\n            int change = changes[cell];\n            int new_val = current_u + change;\n            int new_u = new_val % MOD;\n            if (new_u < 0) new_u += MOD;\n            delta_score += new_u - current_u;\n        }\n        \n        // More accepting of worse moves early on\n        if (delta_score > 0 || (double)rand() / RAND_MAX < exp(delta_score / temperature)) {\n            for (auto cell : affected_cells) {\n                int x = cell.first, y = cell.second;\n                u[x][y] = (u[x][y] + changes[cell]) % MOD;\n                if (u[x][y] < 0) u[x][y] += MOD;\n            }\n            operations[idx] = make_tuple(new_m, new_p, new_q);\n        }\n        \n        temperature *= cooling_rate;\n        iterations++;\n        \n        // Adaptive cooling: if temperature gets too low, reset to explore more\n        if (temperature < 1e-5 && iterations < max_iterations / 2) {\n            temperature = 1000.0; // Reset temperature to continue exploration\n            cooling_rate = 0.97; // Slower cooling after reset\n        }\n    }\n    \n    // Phase 3: Final optimization with focused sampling\n    while (operations.size() < k) {\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1990) break;\n        \n        int best_delta = -1000000000;\n        int best_m = -1, best_p = -1, best_q = -1;\n        \n        // Focused sampling on promising areas\n        int samples = min(80, m * (max_p + 1) * (max_q + 1));\n        for (int s = 0; s < samples; s++) {\n            int mm = rand() % m;\n            int p = rand() % (max_p + 1);\n            int q = rand() % (max_q + 1);\n            \n            int delta = 0;\n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    int x = p + i;\n                    int y = q + j;\n                    int current_u = u[x][y];\n                    int s_val = stamps[mm][i][j];\n                    int new_u = (current_u + s_val) % MOD;\n                    if (new_u < 0) new_u += MOD;\n                    delta += new_u - current_u;\n                }\n            }\n            \n            if (delta > best_delta) {\n                best_delta = delta;\n                best_m = mm;\n                best_p = p;\n                best_q = q;\n            }\n        }\n        \n        // Always add in final phase to use all available operations\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = best_p + i;\n                int y = best_q + j;\n                int s_val = stamps[best_m][i][j];\n                u[x][y] = (u[x][y] + s_val) % MOD;\n                if (u[x][y] < 0) u[x][y] += MOD;\n            }\n        }\n        \n        operations.push_back(make_tuple(best_m, best_p, best_q));\n    }\n    \n    cout << operations.size() << endl;\n    for (auto op : operations) {\n        int m, p, q;\n        tie(m, p, q) = op;\n        cout << m << \" \" << p << \" \" << q << endl;\n    }\n    \n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <array>\n#include <algorithm>\nusing namespace std;\n\nconst int N = 5;\n\narray<array<int, N>, N> grid;\narray<int, N> brought = {0};\narray<int, N> dispatched = {0};\narray<array<int, N>, N> A;\n\nstruct Crane {\n    int i, j;\n    bool carrying;\n    int container;\n    bool active;\n    bool is_large;\n};\n\nvector<Crane> cranes;\nvector<string> actions(N);\n\nvoid init_cranes() {\n    cranes.resize(N);\n    for (int i = 0; i < N; i++) {\n        cranes[i].i = i;\n        cranes[i].j = 0;\n        cranes[i].carrying = false;\n        cranes[i].active = true;\n        cranes[i].is_large = (i == 0);\n    }\n}\n\nbool is_crane_on(int i, int j) {\n    for (const Crane& crane : cranes) {\n        if (crane.active && crane.i == i && crane.j == j) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> A[i][j];\n        }\n    }\n\n    init_cranes();\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            grid[i][j] = -1;\n        }\n    }\n\n    int turns = 0;\n    const int max_turns = 10000;\n\n    while (turns < max_turns) {\n        for (int i = 0; i < N; i++) {\n            if (brought[i] < N && grid[i][0] == -1 && !is_crane_on(i, 0)) {\n                grid[i][0] = A[i][brought[i]];\n                brought[i]++;\n            }\n        }\n\n        for (int idx = 0; idx < N; idx++) {\n            Crane& crane = cranes[idx];\n            if (!crane.active) {\n                actions[idx] += '.';\n                continue;\n            }\n\n            if (!crane.is_large) {\n                if (turns == 0) {\n                    if (crane.j < N-1) {\n                        actions[idx] += 'R';\n                        crane.j++;\n                    } else {\n                        actions[idx] += '.';\n                    }\n                } else if (turns == 1) {\n                    if (!crane.carrying) {\n                        actions[idx] += 'B';\n                        crane.active = false;\n                    } else {\n                        actions[idx] += '.';\n                    }\n                } else {\n                    actions[idx] += '.';\n                }\n            } else {\n                if (!crane.carrying) {\n                    if (grid[crane.i][crane.j] != -1) {\n                        actions[idx] += 'P';\n                        crane.carrying = true;\n                        crane.container = grid[crane.i][crane.j];\n                        grid[crane.i][crane.j] = -1;\n                    } else {\n                        int target_i = -1, target_j = -1;\n                        for (int i = 0; i < N; i++) {\n                            if (grid[i][0] != -1) {\n                                target_i = i;\n                                target_j = 0;\n                                break;\n                            }\n                        }\n                        if (target_i == -1) {\n                            for (int i = 0; i < N; i++) {\n                                for (int j = 0; j < N-1; j++) {\n                                    if (grid[i][j] != -1) {\n                                        target_i = i;\n                                        target_j = j;\n                                        break;\n                                    }\n                                }\n                                if (target_i != -1) break;\n                            }\n                        }\n                        if (target_i != -1) {\n                            if (crane.i != target_i) {\n                                if (crane.i < target_i) {\n                                    actions[idx] += 'D';\n                                    crane.i++;\n                                } else {\n                                    actions[idx] += 'U';\n                                    crane.i--;\n                                }\n                            } else if (crane.j != target_j) {\n                                if (crane.j < target_j) {\n                                    actions[idx] += 'R';\n                                    crane.j++;\n                                } else {\n                                    actions[idx] += 'L';\n                                    crane.j--;\n                                }\n                            } else {\n                                actions[idx] += '.';\n                            }\n                        } else {\n                            actions[idx] += '.';\n                        }\n                    }\n                } else {\n                    int b = crane.container;\n                    int target_i = b / N;\n                    if (crane.i != target_i) {\n                        if (crane.i < target_i) {\n                            actions[idx] += 'D';\n                            crane.i++;\n                        } else {\n                            actions[idx] += 'U';\n                            crane.i--;\n                        }\n                    } else {\n                        if (crane.j != N-1) {\n                            if (crane.j < N-1) {\n                                actions[idx] += 'R';\n                                crane.j++;\n                            } else {\n                                actions[idx] += 'L';\n                                crane.j--;\n                            }\n                        } else {\n                            if (grid[target_i][N-1] == -1) {\n                                actions[idx] += 'Q';\n                                grid[target_i][N-1] = b;\n                                crane.carrying = false;\n                            } else {\n                                actions[idx] += '.';\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        for (int i = 0; i < N; i++) {\n            if (grid[i][N-1] != -1) {\n                int b = grid[i][N-1];\n                grid[i][N-1] = -1;\n                if (b >= i * N && b < i * N + N) {\n                    dispatched[i]++;\n                }\n            }\n        }\n\n        turns++;\n        bool all_brought = true;\n        for (int i = 0; i < N; i++) {\n            if (brought[i] < N) {\n                all_brought = false;\n                break;\n            }\n        }\n        if (all_brought) {\n            bool grid_empty = true;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] != -1) {\n                        grid_empty = false;\n                        break;\n                    }\n                }\n                if (!grid_empty) break;\n            }\n            if (grid_empty && !cranes[0].carrying) {\n                break;\n            }\n        }\n    }\n\n    size_t max_len = 0;\n    for (int i = 0; i < N; i++) {\n        if (actions[i].size() > max_len) {\n            max_len = actions[i].size();\n        }\n    }\n    for (int i = 0; i < N; i++) {\n        string s = actions[i];\n        s.resize(max_len, '.');\n        cout << s << endl;\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\nvector<string> get_moves(int from_i, int from_j, int to_i, int to_j) {\n    vector<string> moves;\n    int di = to_i - from_i;\n    int dj = to_j - from_j;\n    if (di > 0) {\n        for (int i = 0; i < di; i++) {\n            moves.push_back(\"D\");\n        }\n    } else if (di < 0) {\n        for (int i = 0; i < -di; i++) {\n            moves.push_back(\"U\");\n        }\n    }\n    if (dj > 0) {\n        for (int j = 0; j < dj; j++) {\n            moves.push_back(\"R\");\n        }\n    } else if (dj < 0) {\n        for (int j = 0; j < -dj; j++) {\n            moves.push_back(\"L\");\n        }\n    }\n    return moves;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<vector<int>> h_current(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h_current[i][j];\n        }\n    }\n\n    int current_i = 0, current_j = 0;\n    int load = 0;\n    vector<string> operations;\n\n    while (true) {\n        bool all_zero = true;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (h_current[i][j] != 0) {\n                    all_zero = false;\n                    break;\n                }\n            }\n            if (!all_zero) break;\n        }\n        if (all_zero && load == 0) {\n            break;\n        }\n\n        bool operation_done = false;\n        if (h_current[current_i][current_j] > 0 && load == 0) {\n            int d = h_current[current_i][current_j];\n            operations.push_back(\"+\" + to_string(d));\n            load += d;\n            h_current[current_i][current_j] = 0;\n            operation_done = true;\n        } else if (h_current[current_i][current_j] < 0 && load > 0) {\n            int d = min(load, -h_current[current_i][current_j]);\n            operations.push_back(\"-\" + to_string(d));\n            load -= d;\n            h_current[current_i][current_j] += d;\n            operation_done = true;\n        }\n\n        if (operation_done) {\n            continue;\n        }\n\n        if (load == 0) {\n            int best_dist = 1e9;\n            int best_i = -1, best_j = -1;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h_current[i][j] > 0) {\n                        int dist = abs(i - current_i) + abs(j - current_j);\n                        if (dist < best_dist) {\n                            best_dist = dist;\n                            best_i = i;\n                            best_j = j;\n                        }\n                    }\n                }\n            }\n            if (best_i == -1) {\n                break;\n            }\n            vector<string> moves = get_moves(current_i, current_j, best_i, best_j);\n            operations.insert(operations.end(), moves.begin(), moves.end());\n            current_i = best_i;\n            current_j = best_j;\n        } else if (load > 0) {\n            int best_dist = 1e9;\n            int best_i = -1, best_j = -1;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h_current[i][j] < 0) {\n                        int dist = abs(i - current_i) + abs(j - current_j);\n                        if (dist < best_dist) {\n                            best_dist = dist;\n                            best_i = i;\n                            best_j = j;\n                        }\n                    }\n                }\n            }\n            if (best_i == -1) {\n                break;\n            }\n            vector<string> moves = get_moves(current_i, current_j, best_i, best_j);\n            operations.insert(operations.end(), moves.begin(), moves.end());\n            current_i = best_i;\n            current_j = best_j;\n        } else {\n            break;\n        }\n    }\n\n    for (const string& op : operations) {\n        cout << op << endl;\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\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    // Store initial max values for scoring reference\n    vector<int> initial_max_per_criterion(M, 0);\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i][j];\n            if (seeds[i][j] > initial_max_per_criterion[j]) {\n                initial_max_per_criterion[j] = seeds[i][j];\n            }\n        }\n    }\n\n    for (int t = 0; t < T; t++) {\n        vector<int> values(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            values[i] = accumulate(seeds[i].begin(), seeds[i].end(), 0);\n        }\n\n        // Enhanced seed selection: balance quality and diversity\n        vector<int> indices(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            indices[i] = i;\n        }\n        \n        // Sort by value with diversity consideration\n        sort(indices.begin(), indices.end(), [&](int a, int b) {\n            if (values[a] != values[b]) return values[a] > values[b];\n            // Tie-breaker: prefer seeds with more above-average criteria\n            int above_avg_a = 0, above_avg_b = 0;\n            for (int l = 0; l < M; l++) {\n                if (seeds[a][l] > initial_max_per_criterion[l] * 0.7) above_avg_a++;\n                if (seeds[b][l] > initial_max_per_criterion[l] * 0.7) above_avg_b++;\n            }\n            return above_avg_a > above_avg_b;\n        });\n\n        // Select seeds: take top 25, then ensure diversity\n        vector<int> plant_indices;\n        vector<bool> used(seed_count, false);\n        \n        // Take top 25 seeds\n        for (int i = 0; i < min(25, N * N); i++) {\n            plant_indices.push_back(indices[i]);\n            used[indices[i]] = true;\n        }\n\n        // Ensure each criterion has at least one strong representative\n        vector<int> criterion_covered(M, 0);\n        for (int idx : plant_indices) {\n            for (int l = 0; l < M; l++) {\n                if (seeds[idx][l] > initial_max_per_criterion[l] * 0.8) {\n                    criterion_covered[l]++;\n                }\n            }\n        }\n\n        // Add seeds to cover missing criteria\n        for (int l = 0; l < M && plant_indices.size() < N * N; l++) {\n            if (criterion_covered[l] == 0) {\n                for (int i = 25; i < seed_count && plant_indices.size() < N * N; i++) {\n                    int candidate = indices[i];\n                    if (!used[candidate] && seeds[candidate][l] > initial_max_per_criterion[l] * 0.8) {\n                        plant_indices.push_back(candidate);\n                        used[candidate] = true;\n                        criterion_covered[l]++;\n                        break;\n                    }\n                }\n            }\n        }\n\n        // Fill remaining slots with best available seeds\n        for (int i = 0; plant_indices.size() < N * N && i < seed_count; i++) {\n            if (!used[indices[i]]) {\n                plant_indices.push_back(indices[i]);\n                used[indices[i]] = true;\n            }\n        }\n\n        // Enhanced spiral placement with strategic positioning\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        vector<bool> assigned(plant_indices.size(), false);\n        \n        // Generate spiral order starting from center\n        vector<pair<int, int>> spiral_order;\n        int center_i = N / 2, center_j = N / 2;\n        spiral_order.push_back({center_i, center_j});\n        \n        int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        int step = 1, dir = 0;\n        int i = center_i, j = center_j;\n        \n        while (spiral_order.size() < N * N) {\n            for (int s = 0; s < 2; s++) {\n                for (int k = 0; k < step && spiral_order.size() < N * N; k++) {\n                    i += directions[dir][0];\n                    j += directions[dir][1];\n                    if (i >= 0 && i < N && j >= 0 && j < N) {\n                        spiral_order.push_back({i, j});\n                    }\n                }\n                dir = (dir + 1) % 4;\n            }\n            step++;\n        }\n\n        // Precompute cell importance for strategic placement\n        vector<vector<double>> cell_importance(N, vector<double>(N, 0.0));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                double di = abs(i - (N-1)/2.0);\n                double dj = abs(j - (N-1)/2.0);\n                double dist = sqrt(di*di + dj*dj);\n                cell_importance[i][j] = 1.0 - dist / (N * 0.7);\n            }\n        }\n\n        // Assign seeds with enhanced scoring\n        for (auto [i, j] : spiral_order) {\n            vector<int> neighbor_seeds;\n            \n            // Check all four neighbors\n            int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n            for (auto [di, dj] : directions) {\n                int ni = i + di, nj = j + dj;\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && A[ni][nj] != -1) {\n                    neighbor_seeds.push_back(A[ni][nj]);\n                }\n            }\n\n            if (neighbor_seeds.empty()) {\n                // For isolated cells, prioritize high-value seeds in important positions\n                int best_seed = -1;\n                double best_score = -1;\n                for (int k = 0; k < plant_indices.size(); k++) {\n                    if (assigned[k]) continue;\n                    \n                    int seed_idx = plant_indices[k];\n                    double score = values[seed_idx] * cell_importance[i][j];\n                    \n                    // Bonus for well-rounded seeds\n                    int strong_criteria = 0;\n                    for (int l = 0; l < M; l++) {\n                        if (seeds[seed_idx][l] > initial_max_per_criterion[l] * 0.7) {\n                            strong_criteria++;\n                        }\n                    }\n                    score *= (1.0 + strong_criteria * 0.05);\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_seed = k;\n                    }\n                }\n                if (best_seed != -1) {\n                    A[i][j] = plant_indices[best_seed];\n                    assigned[best_seed] = true;\n                }\n            } else {\n                // Calculate deficiencies relative to initial maximums\n                vector<int> max_neighbor_values(M, 0);\n                for (int n_index : neighbor_seeds) {\n                    for (int l = 0; l < M; l++) {\n                        if (seeds[n_index][l] > max_neighbor_values[l]) {\n                            max_neighbor_values[l] = seeds[n_index][l];\n                        }\n                    }\n                }\n                \n                vector<int> deficiencies(M, 0);\n                for (int l = 0; l < M; l++) {\n                    deficiencies[l] = initial_max_per_criterion[l] - max_neighbor_values[l];\n                }\n\n                // Enhanced scoring with balanced weights\n                int best_seed_index = -1;\n                double best_score = -1e9;\n                \n                for (int k = 0; k < plant_indices.size(); k++) {\n                    if (assigned[k]) continue;\n                    \n                    int s_index = plant_indices[k];\n                    double score = values[s_index] * 0.6; // Base value weight\n                    \n                    // Complementarity component\n                    for (int l = 0; l < M; l++) {\n                        if (deficiencies[l] > 0) {\n                            score += seeds[s_index][l] * deficiencies[l] * 0.15;\n                        }\n                    }\n                    \n                    // Strategic bonus for filling critical gaps\n                    for (int l = 0; l < M; l++) {\n                        if (seeds[s_index][l] > initial_max_per_criterion[l] * 0.85 && deficiencies[l] > 10) {\n                            score += deficiencies[l] * 0.8;\n                        }\n                    }\n                    \n                    // Cell importance weighting\n                    score *= cell_importance[i][j];\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_seed_index = k;\n                    }\n                }\n                \n                if (best_seed_index != -1) {\n                    A[i][j] = plant_indices[best_seed_index];\n                    assigned[best_seed_index] = true;\n                } else {\n                    for (int k = 0; k < plant_indices.size(); k++) {\n                        if (!assigned[k]) {\n                            A[i][j] = plant_indices[k];\n                            assigned[k] = true;\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        // Output the assignment\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << A[i][j];\n                if (j < N - 1) {\n                    cout << \" \";\n                }\n            }\n            cout << endl;\n        }\n        cout.flush();\n\n        // Read new seeds for next generation\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 <set>\n#include <map>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <random>\n\nusing namespace std;\n\nconst int MAX_N = 30;\nconst int MAX_V = 15;\n\n// Directions: 0=right, 1=down, 2=left, 3=up\nconst int dx[4] = {0, 1, 0, -1};\nconst int dy[4] = {1, 0, -1, 0};\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    \n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    \n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n    \n    int manhattan(const Point& other) const {\n        return abs(x - other.x) + abs(y - other.y);\n    }\n};\n\nclass RoboticArm {\nprivate:\n    int N, M, V;\n    vector<string> s, t;\n    Point root;\n    vector<int> parent;\n    vector<int> length;\n    vector<int> dirs; // direction for each vertex (except root)\n    vector<bool> holding;\n    set<Point> initial_set;\n    set<Point> target_set;\n    vector<vector<bool>> grid;\n    int turns;\n    mt19937 rng;\n    \n    // Check if point is within grid\n    bool in_grid(int x, int y) {\n        return x >= 0 && x < N && y >= 0 && y < N;\n    }\n    \n    // Get position of a vertex\n    Point get_position(int vertex) {\n        if (vertex == 0) return root;\n        \n        Point pos = root;\n        int current = vertex;\n        vector<int> path;\n        \n        // Get path from root to vertex\n        while (current != 0) {\n            path.push_back(current);\n            current = parent[current];\n        }\n        \n        // Reverse to go from root to vertex\n        for (int i = path.size() - 1; i >= 0; i--) {\n            int v = path[i];\n            int d = dirs[v];\n            pos.x += dx[d] * length[v];\n            pos.y += dy[d] * length[v];\n        }\n        \n        return pos;\n    }\n    \n    // Evaluate a move and rotation\n    double evaluate_action(int move, int rotation, const vector<Point>& desired_pos) {\n        Point new_root = root;\n        vector<int> new_dirs = dirs;\n        \n        // Apply move\n        if (move == 1) new_root.y++; // U\n        else if (move == 2) new_root.y--; // D\n        else if (move == 3) new_root.x--; // L\n        else if (move == 4) new_root.x++; // R\n        \n        if (!in_grid(new_root.x, new_root.y)) return numeric_limits<double>::max();\n        \n        // Apply rotation to vertex 1 (the only joint in our star design)\n        if (rotation != 0) {\n            for (int i = 1; i < V; i++) {\n                if (rotation == 1) new_dirs[i] = (new_dirs[i] + 1) % 4; // clockwise\n                else new_dirs[i] = (new_dirs[i] + 3) % 4; // counterclockwise\n            }\n        }\n        \n        // Calculate new positions and score\n        double score = 0;\n        for (int i = 2; i < V; i++) { // leaves are vertices 2 to V-1\n            Point leaf_pos = new_root;\n            int d = new_dirs[i];\n            leaf_pos.x += dx[d] * length[i];\n            leaf_pos.y += dy[d] * length[i];\n            \n            if (!desired_pos[i].x == -1) {\n                score += leaf_pos.manhattan(desired_pos[i]);\n            }\n        }\n        \n        return score;\n    }\n\npublic:\n    RoboticArm(int N, int M, int V, const vector<string>& s, const vector<string>& t) \n        : N(N), M(M), V(V), s(s), t(t), turns(0), rng(42) {\n        \n        // Initialize grid and sets\n        grid.assign(N, vector<bool>(N, false));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (s[i][j] == '1') {\n                    grid[i][j] = true;\n                    initial_set.insert(Point(i, j));\n                }\n                if (t[i][j] == '1') {\n                    target_set.insert(Point(i, j));\n                }\n            }\n        }\n        \n        // Initialize tree structure (star design)\n        parent.resize(V);\n        length.resize(V);\n        dirs.resize(V, 0); // all directions initially right\n        holding.resize(V, false);\n        \n        // Root at center\n        root = Point(N / 2, N / 2);\n        \n        // All vertices except root are children of root\n        for (int i = 1; i < V; i++) {\n            parent[i] = 0;\n            length[i] = N - 1;\n        }\n    }\n    \n    void output_tree() {\n        cout << V << endl;\n        for (int i = 1; i < V; i++) {\n            cout << parent[i] << \" \" << length[i] << endl;\n        }\n        cout << root.x << \" \" << root.y << endl;\n    }\n    \n    void solve() {\n        output_tree();\n        \n        while (turns < 100000) {\n            // Check if all takoyaki are placed\n            bool all_placed = true;\n            for (const auto& p : target_set) {\n                if (!grid[p.x][p.y]) {\n                    all_placed = false;\n                    break;\n                }\n            }\n            if (all_placed) break;\n            \n            // Assign desired positions for each leaf\n            vector<Point> desired_pos(V, Point(-1, -1));\n            set<Point> available_initial = initial_set;\n            set<Point> available_target = target_set;\n            \n            // Remove already placed takoyaki from available targets\n            for (const auto& p : target_set) {\n                if (grid[p.x][p.y]) {\n                    available_target.erase(p);\n                }\n            }\n            \n            // Greedy assignment\n            for (int i = 2; i < V; i++) {\n                if (!holding[i]) {\n                    // Find closest available initial position\n                    Point best_pos(-1, -1);\n                    int best_dist = numeric_limits<int>::max();\n                    Point current_pos = get_position(i);\n                    \n                    for (const auto& p : available_initial) {\n                        if (grid[p.x][p.y]) {\n                            int dist = current_pos.manhattan(p);\n                            if (dist < best_dist) {\n                                best_dist = dist;\n                                best_pos = p;\n                            }\n                        }\n                    }\n                    \n                    if (best_dist < numeric_limits<int>::max()) {\n                        desired_pos[i] = best_pos;\n                        available_initial.erase(best_pos);\n                    }\n                } else {\n                    // Find closest available target position\n                    Point best_pos(-1, -1);\n                    int best_dist = numeric_limits<int>::max();\n                    Point current_pos = get_position(i);\n                    \n                    for (const auto& p : available_target) {\n                        if (!grid[p.x][p.y]) {\n                            int dist = current_pos.manhattan(p);\n                            if (dist < best_dist) {\n                                best_dist = dist;\n                                best_pos = p;\n                            }\n                        }\n                    }\n                    \n                    if (best_dist < numeric_limits<int>::max()) {\n                        desired_pos[i] = best_pos;\n                        available_target.erase(best_pos);\n                    }\n                }\n            }\n            \n            // Evaluate all possible actions\n            int best_move = 0; // 0=no move, 1=U, 2=D, 3=L, 4=R\n            int best_rotation = 0; // 0=no rotation, 1=clockwise, 2=counterclockwise\n            double best_score = numeric_limits<double>::max();\n            \n            for (int move = 0; move <= 4; move++) {\n                for (int rotation = 0; rotation <= 2; rotation++) {\n                    double score = evaluate_action(move, rotation, desired_pos);\n                    if (score < best_score) {\n                        best_score = score;\n                        best_move = move;\n                        best_rotation = rotation;\n                    }\n                }\n            }\n            \n            // Apply best action\n            string operation;\n            operation.resize(2 * V, '.');\n            \n            // Move\n            if (best_move == 1) { // U\n                root.y++;\n                operation[0] = 'U';\n            } else if (best_move == 2) { // D\n                root.y--;\n                operation[0] = 'D';\n            } else if (best_move == 3) { // L\n                root.x--;\n                operation[0] = 'L';\n            } else if (best_move == 4) { // R\n                root.x++;\n                operation[0] = 'R';\n            }\n            \n            // Rotation\n            if (best_rotation == 1) { // clockwise\n                for (int i = 1; i < V; i++) {\n                    dirs[i] = (dirs[i] + 1) % 4;\n                    operation[i] = 'R';\n                }\n            } else if (best_rotation == 2) { // counterclockwise\n                for (int i = 1; i < V; i++) {\n                    dirs[i] = (dirs[i] + 3) % 4;\n                    operation[i] = 'L';\n                }\n            }\n            \n            // Pick/place operations\n            for (int i = 2; i < V; i++) {\n                Point pos = get_position(i);\n                if (in_grid(pos.x, pos.y)) {\n                    if (!holding[i] && initial_set.find(pos) != initial_set.end() && grid[pos.x][pos.y]) {\n                        // Pick up takoyaki\n                        grid[pos.x][pos.y] = false;\n                        holding[i] = true;\n                        operation[V + i] = 'P';\n                    } else if (holding[i] && target_set.find(pos) != target_set.end() && !grid[pos.x][pos.y]) {\n                        // Place takoyaki\n                        grid[pos.x][pos.y] = true;\n                        holding[i] = false;\n                        operation[V + i] = 'P';\n                    }\n                }\n            }\n            \n            cout << operation << endl;\n            turns++;\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, V;\n    cin >> N >> M >> V;\n    \n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; i++) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> t[i];\n    }\n    \n    RoboticArm arm(N, M, V, s, t);\n    arm.solve();\n    \n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n#include <random>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    int type; // 0 for mackerel, 1 for sardine\n};\n\npair<int, int> optimize_axis(const vector<Point>& points_sorted, int fixed_min, int fixed_max, bool is_x_fixed) {\n    auto cmp_lower = [is_x_fixed](const Point& p, int val) {\n        if (is_x_fixed) return p.x < val;\n        else return p.y < val;\n    };\n    auto cmp_upper = [is_x_fixed](int val, const Point& p) {\n        if (is_x_fixed) return val < p.x;\n        else return val < p.y;\n    };\n\n    auto start_it = lower_bound(points_sorted.begin(), points_sorted.end(), fixed_min, cmp_lower);\n    auto end_it = upper_bound(points_sorted.begin(), points_sorted.end(), fixed_max, cmp_upper);\n\n    vector<int> value(100001, 0);\n    for (auto it = start_it; it != end_it; ++it) {\n        int coord;\n        if (is_x_fixed) {\n            coord = it->y;\n        } else {\n            coord = it->x;\n        }\n        if (it->type == 0) {\n            value[coord] += 1;\n        } else {\n            value[coord] -= 1;\n        }\n    }\n\n    vector<int> cum_net(100001);\n    cum_net[0] = value[0];\n    for (int i = 1; i <= 100000; i++) {\n        cum_net[i] = cum_net[i-1] + value[i];\n    }\n\n    int min_cum = 0;\n    int min_index = -1;\n    int best_diff = INT_MIN;\n    int best_a = 0, best_b = 0;\n\n    for (int i = 0; i <= 100000; i++) {\n        int diff = cum_net[i] - min_cum;\n        if (diff > best_diff) {\n            best_diff = diff;\n            best_a = min_index + 1;\n            best_b = i;\n        }\n        if (cum_net[i] < min_cum) {\n            min_cum = cum_net[i];\n            min_index = i;\n        }\n    }\n\n    if (best_a > best_b) {\n        swap(best_a, best_b);\n    }\n    if (best_a == best_b) {\n        if (best_b < 100000) {\n            best_b++;\n        } else if (best_a > 0) {\n            best_a--;\n        } else {\n            best_b++;\n        }\n    }\n\n    return {best_a, best_b};\n}\n\nint compute_score(const vector<Point>& points, int x1, int x2, int y1, int y2) {\n    int a = 0, b = 0;\n    for (const Point& p : points) {\n        if (p.x >= x1 && p.x <= x2 && p.y >= y1 && p.y <= y2) {\n            if (p.type == 0) a++;\n            else b++;\n        }\n    }\n    return a - b + 1;\n}\n\nvoid gradient_descent_refinement(const vector<Point>& points, int& x1, int& x2, int& y1, int& y2, int max_iterations) {\n    int current_score = compute_score(points, x1, x2, y1, y2);\n    \n    vector<int> steps = {1000, 500, 100, 50, 10, 5, 1};\n    \n    for (int step_size : steps) {\n        bool improved = true;\n        int iterations = 0;\n        \n        while (improved && iterations < max_iterations) {\n            improved = false;\n            iterations++;\n            \n            // Try all possible single-boundary moves\n            vector<pair<int*, int>> moves = {\n                {&x1, -step_size}, {&x1, step_size},\n                {&x2, -step_size}, {&x2, step_size},\n                {&y1, -step_size}, {&y1, step_size},\n                {&y2, -step_size}, {&y2, step_size}\n            };\n            \n            // Shuffle moves to avoid bias\n            random_device rd;\n            mt19937 g(rd());\n            shuffle(moves.begin(), moves.end(), g);\n            \n            for (auto& move : moves) {\n                int original = *move.first;\n                *move.first = original + move.second;\n                \n                // Check constraints\n                if (x1 >= x2 || y1 >= y2 || x1 < 0 || x2 > 100000 || y1 < 0 || y2 > 100000) {\n                    *move.first = original;\n                    continue;\n                }\n                \n                int perimeter = 2 * ((x2 - x1) + (y2 - y1));\n                if (perimeter > 400000) {\n                    *move.first = original;\n                    continue;\n                }\n                \n                int new_score = compute_score(points, x1, x2, y1, y2);\n                if (new_score > current_score) {\n                    current_score = new_score;\n                    improved = true;\n                } else {\n                    *move.first = original; // Revert if no improvement\n                }\n            }\n        }\n    }\n}\n\nvoid simulated_annealing_refinement(const vector<Point>& points, int& x1, int& x2, int& y1, int& y2, int iterations) {\n    int current_score = compute_score(points, x1, x2, y1, y2);\n    int best_score = current_score;\n    int best_x1 = x1, best_x2 = x2, best_y1 = y1, best_y2 = y2;\n    \n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> step_dis(-50, 50);\n    \n    double temperature = 1000.0;\n    double cooling_rate = 0.95;\n    \n    for (int i = 0; i < iterations; i++) {\n        // Save current state\n        int old_x1 = x1, old_x2 = x2, old_y1 = y1, old_y2 = y2;\n        int old_score = current_score;\n        \n        // Make a random move\n        x1 = max(0, min(100000, x1 + step_dis(gen)));\n        x2 = max(0, min(100000, x2 + step_dis(gen)));\n        y1 = max(0, min(100000, y1 + step_dis(gen)));\n        y2 = max(0, min(100000, y2 + step_dis(gen)));\n        \n        // Ensure valid rectangle\n        if (x1 >= x2 || y1 >= y2) {\n            x1 = old_x1; x2 = old_x2; y1 = old_y1; y2 = old_y2;\n            continue;\n        }\n        \n        // Check perimeter constraint\n        int perimeter = 2 * ((x2 - x1) + (y2 - y1));\n        if (perimeter > 400000) {\n            x1 = old_x1; x2 = old_x2; y1 = old_y1; y2 = old_y2;\n            continue;\n        }\n        \n        current_score = compute_score(points, x1, x2, y1, y2);\n        \n        // Always accept improving moves\n        if (current_score > old_score) {\n            if (current_score > best_score) {\n                best_score = current_score;\n                best_x1 = x1; best_x2 = x2; best_y1 = y1; best_y2 = y2;\n            }\n        } else {\n            // Accept worse moves with probability based on temperature\n            double acceptance_prob = exp((current_score - old_score) / temperature);\n            if (dis(gen) > acceptance_prob) {\n                // Revert move\n                x1 = old_x1; x2 = old_x2; y1 = old_y1; y2 = old_y2;\n                current_score = old_score;\n            }\n        }\n        \n        // Cool down\n        temperature *= cooling_rate;\n    }\n    \n    // Restore best found solution\n    x1 = best_x1; x2 = best_x2; y1 = best_y1; y2 = best_y2;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n\n    int N;\n    cin >> N;\n    vector<Point> points(2 * N);\n    for (int i = 0; i < 2 * N; i++) {\n        cin >> points[i].x >> points[i].y;\n        points[i].type = (i < N) ? 0 : 1;\n    }\n\n    vector<Point> mackerels(points.begin(), points.begin() + N);\n\n    // Sort points for optimize_axis\n    vector<Point> points_by_x = points;\n    sort(points_by_x.begin(), points_by_x.end(), [](const Point& a, const Point& b) {\n        return a.x < b.x;\n    });\n    vector<Point> points_by_y = points;\n    sort(points_by_y.begin(), points_by_y.end(), [](const Point& a, const Point& b) {\n        return a.y < b.y;\n    });\n\n    // Compute initial rectangles from different percentiles\n    vector<int> mackerels_x, mackerels_y;\n    for (const Point& p : mackerels) {\n        mackerels_x.push_back(p.x);\n        mackerels_y.push_back(p.y);\n    }\n    sort(mackerels_x.begin(), mackerels_x.end());\n    sort(mackerels_y.begin(), mackerels_y.end());\n\n    vector<pair<int, int>> initial_rectangles;\n    \n    // Min-max\n    initial_rectangles.push_back({mackerels_x[0], mackerels_x.back()});\n    initial_rectangles.push_back({mackerels_y[0], mackerels_y.back()});\n    \n    // Quartiles\n    initial_rectangles.push_back({mackerels_x[N/4], mackerels_x[3*N/4]});\n    initial_rectangles.push_back({mackerels_y[N/4], mackerels_y[3*N/4]});\n    \n    // 10th-90th percentiles\n    initial_rectangles.push_back({mackerels_x[N/10], mackerels_x[9*N/10]});\n    initial_rectangles.push_back({mackerels_y[N/10], mackerels_y[9*N/10]});\n    \n    // 5th-95th percentiles\n    initial_rectangles.push_back({mackerels_x[N/20], mackerels_x[19*N/20]});\n    initial_rectangles.push_back({mackerels_y[N/20], mackerels_y[19*N/20]});\n    \n    // 15th-85th percentiles\n    initial_rectangles.push_back({mackerels_x[3*N/20], mackerels_x[17*N/20]});\n    initial_rectangles.push_back({mackerels_y[3*N/20], mackerels_y[17*N/20]});\n\n    int best_score = INT_MIN;\n    int best_x1, best_x2, best_y1, best_y2;\n\n    for (int i = 0; i < 5; i++) {\n        int x1 = initial_rectangles[2*i].first;\n        int x2 = initial_rectangles[2*i].second;\n        int y1 = initial_rectangles[2*i+1].first;\n        int y2 = initial_rectangles[2*i+1].second;\n\n        // Extended optimization iterations\n        for (int iter = 0; iter < 15; iter++) {\n            auto new_y = optimize_axis(points_by_x, x1, x2, true);\n            y1 = new_y.first;\n            y2 = new_y.second;\n\n            auto new_x = optimize_axis(points_by_y, y1, y2, false);\n            x1 = new_x.first;\n            x2 = new_x.second;\n        }\n\n        // Apply gradient descent refinement\n        gradient_descent_refinement(points, x1, x2, y1, y2, 100);\n        \n        // Apply simulated annealing for final refinement\n        simulated_annealing_refinement(points, x1, x2, y1, y2, 500);\n\n        int score = compute_score(points, x1, x2, y1, y2);\n        if (score > best_score) {\n            best_score = score;\n            best_x1 = x1;\n            best_x2 = x2;\n            best_y1 = y1;\n            best_y2 = y2;\n        }\n    }\n\n    // Final refinement on the best rectangle\n    gradient_descent_refinement(points, best_x1, best_x2, best_y1, best_y2, 200);\n    simulated_annealing_refinement(points, best_x1, best_x2, best_y1, best_y2, 1000);\n\n    cout << 4 << endl;\n    cout << best_x1 << \" \" << best_y1 << endl;\n    cout << best_x2 << \" \" << best_y1 << endl;\n    cout << best_x2 << \" \" << best_y2 << endl;\n    cout << best_x1 << \" \" << best_y2 << endl;\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <tuple>\n\nusing namespace std;\n\nstruct Rectangle {\n    int index;\n    long long w, h;\n    long long area;\n    long long estimated_w, estimated_h;\n};\n\nbool compare_by_area(const Rectangle& a, const Rectangle& b) {\n    return a.area > b.area;\n}\n\nbool compare_by_perimeter(const Rectangle& a, const Rectangle& b) {\n    return (a.estimated_w + a.estimated_h) > (b.estimated_w + b.estimated_h);\n}\n\nbool compare_by_max_side(const Rectangle& a, const Rectangle& b) {\n    return max(a.estimated_w, a.estimated_h) > max(b.estimated_w, b.estimated_h);\n}\n\nint main() {\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n    \n    vector<Rectangle> rects(N);\n    for (int i = 0; i < N; i++) {\n        cin >> rects[i].estimated_w >> rects[i].estimated_h;\n        rects[i].index = i;\n        rects[i].w = rects[i].estimated_w;\n        rects[i].h = rects[i].estimated_h;\n        rects[i].area = rects[i].estimated_w * rects[i].estimated_h;\n    }\n\n    // Track best score across turns\n    long long best_score = numeric_limits<long long>::max();\n    vector<tuple<int, int, char, int>> best_actions;\n    \n    for (int t = 0; t < T; t++) {\n        vector<tuple<int, int, char, int>> actions;\n        \n        // Occasionally use the best strategy found so far\n        if (t > T / 2 && t % 5 == 0 && !best_actions.empty()) {\n            actions = best_actions;\n        } else {\n            // Vary the sorting strategy based on turn number\n            vector<Rectangle> sorted_rects = rects;\n            \n            if (t % 3 == 0) {\n                sort(sorted_rects.begin(), sorted_rects.end(), compare_by_area);\n            } else if (t % 3 == 1) {\n                sort(sorted_rects.begin(), sorted_rects.end(), compare_by_perimeter);\n            } else {\n                sort(sorted_rects.begin(), sorted_rects.end(), compare_by_max_side);\n            }\n            \n            long long current_width = 0, current_height = 0;\n            \n            for (const auto& rect : sorted_rects) {\n                // Try both orientations\n                long long w1 = rect.estimated_w, h1 = rect.estimated_h;\n                long long w2 = rect.estimated_h, h2 = rect.estimated_w;\n                \n                // Calculate costs for different strategies\n                long long cost_up1 = max(current_width, w1) + (current_height + h1);\n                long long cost_up2 = max(current_width, w2) + (current_height + h2);\n                long long cost_left1 = (current_width + w1) + max(current_height, h1);\n                long long cost_left2 = (current_width + w2) + max(current_height, h2);\n                \n                // Also consider balanced placement (minimize max dimension)\n                long long balanced_up1 = max(max(current_width, w1), current_height + h1);\n                long long balanced_up2 = max(max(current_width, w2), current_height + h2);\n                long long balanced_left1 = max(current_width + w1, max(current_height, h1));\n                long long balanced_left2 = max(current_width + w2, max(current_height, h2));\n                \n                // Combine both metrics\n                long long combined_up1 = cost_up1 + balanced_up1;\n                long long combined_up2 = cost_up2 + balanced_up2;\n                long long combined_left1 = cost_left1 + balanced_left1;\n                long long combined_left2 = cost_left2 + balanced_left2;\n                \n                // Find the best combination\n                long long min_cost = min({combined_up1, combined_up2, combined_left1, combined_left2});\n                \n                int rotation, reference;\n                char direction;\n                \n                if (min_cost == combined_up1) {\n                    rotation = 0; direction = 'U';\n                } else if (min_cost == combined_up2) {\n                    rotation = 1; direction = 'U';\n                } else if (min_cost == combined_left1) {\n                    rotation = 0; direction = 'L';\n                } else {\n                    rotation = 1; direction = 'L';\n                }\n                \n                reference = -1;\n                actions.push_back(make_tuple(rect.index, rotation, direction, reference));\n                \n                // Update dimensions\n                long long w = (rotation == 0) ? rect.estimated_w : rect.estimated_h;\n                long long h = (rotation == 0) ? rect.estimated_h : rect.estimated_w;\n                \n                if (direction == 'U') {\n                    current_width = max(current_width, w);\n                    current_height += h;\n                } else {\n                    current_width += w;\n                    current_height = max(current_height, h);\n                }\n            }\n        }\n        \n        // Sort actions by index to satisfy constraint\n        sort(actions.begin(), actions.end(), \n            [](const auto& a, const auto& b) { \n                return get<0>(a) < get<0>(b); \n            });\n        \n        // Output the placement plan\n        cout << actions.size() << endl;\n        for (const auto& action : actions) {\n            cout << get<0>(action) << \" \" << get<1>(action) << \" \" \n                 << get<2>(action) << \" \" << get<3>(action) << endl;\n        }\n        cout.flush();\n        \n        // Read measurement result\n        long long Wp, Hp;\n        cin >> Wp >> Hp;\n        \n        // Calculate current score (W + H) and track best\n        // Note: We don't know the exact W and H due to measurement error,\n        // but we can estimate based on the placement strategy\n        long long estimated_width = 0, estimated_height = 0;\n        for (const auto& action : actions) {\n            int rotation = get<1>(action);\n            char direction = get<2>(action);\n            const auto& rect = rects[get<0>(action)];\n            \n            long long w = (rotation == 0) ? rect.estimated_w : rect.estimated_h;\n            long long h = (rotation == 0) ? rect.estimated_h : rect.estimated_w;\n            \n            if (direction == 'U') {\n                estimated_width = max(estimated_width, w);\n                estimated_height += h;\n            } else {\n                estimated_width += w;\n                estimated_height = max(estimated_height, h);\n            }\n        }\n        \n        long long current_score = estimated_width + estimated_height;\n        if (current_score < best_score) {\n            best_score = current_score;\n            best_actions = actions;\n        }\n    }\n    \n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    int index;\n    int beauty;\n};\n\ndouble distance(const Point& a, const Point& b) {\n    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, H;\n    cin >> N >> M >> H;\n    \n    vector<int> A(N);\n    for (int i = 0; i < N; i++) {\n        cin >> A[i];\n    }\n    \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    vector<Point> points(N);\n    Point center = {500, 500, -1, 0}; // Circle center\n    for (int i = 0; i < N; i++) {\n        cin >> points[i].x >> points[i].y;\n        points[i].index = i;\n        points[i].beauty = A[i];\n    }\n    \n    // Sort points by distance from center (ascending) and beauty (ascending)\n    // Prefer points near center with low beauty as roots\n    vector<int> point_indices(N);\n    iota(point_indices.begin(), point_indices.end(), 0);\n    sort(point_indices.begin(), point_indices.end(), [&](int i, int j) {\n        double dist_i = distance(points[i], center);\n        double dist_j = distance(points[j], center);\n        if (abs(dist_i - dist_j) < 1e-9) {\n            return A[i] < A[j]; // Lower beauty first if same distance\n        }\n        return dist_i < dist_j;\n    });\n    \n    vector<int> parent(N, -1);\n    vector<int> depth(N, -1);\n    vector<bool> assigned(N, false);\n    \n    // Priority queue for BFS: (depth, -beauty, vertex)\n    // We want to process vertices with higher depth first, and for same depth,\n    // process lower beauty vertices first (to reserve high beauty for deeper positions)\n    auto cmp = [](const tuple<int, int, int>& a, const tuple<int, int, int>& b) {\n        if (get<0>(a) != get<0>(b)) return get<0>(a) < get<0>(b);\n        return get<1>(a) > get<1>(b); // Higher beauty has lower negative value\n    };\n    priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, decltype(cmp)> pq(cmp);\n    \n    // Assign roots starting from points near center with low beauty\n    for (int idx : point_indices) {\n        if (!assigned[idx] && depth[idx] == -1) {\n            // Make this point a root\n            parent[idx] = -1;\n            depth[idx] = 0;\n            assigned[idx] = true;\n            pq.push({0, -A[idx], idx});\n        }\n    }\n    \n    // Process vertices in BFS order with depth constraint\n    while (!pq.empty()) {\n        auto [current_depth, neg_beauty, u] = pq.top();\n        pq.pop();\n        \n        if (current_depth >= H) continue;\n        \n        // Sort neighbors by beauty descending (we want to assign high beauty vertices first)\n        vector<pair<int, int>> neighbors; // (beauty, vertex)\n        for (int v : adj[u]) {\n            if (!assigned[v]) {\n                neighbors.push_back({A[v], v});\n            }\n        }\n        \n        sort(neighbors.begin(), neighbors.end(), greater<pair<int, int>>());\n        \n        for (auto [beauty, v] : neighbors) {\n            if (!assigned[v] && depth[v] == -1) {\n                parent[v] = u;\n                depth[v] = current_depth + 1;\n                assigned[v] = true;\n                pq.push({depth[v], -A[v], v});\n            }\n        }\n    }\n    \n    // Output the parent array\n    for (int i = 0; i < N; i++) {\n        cout << parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n    const int N = 20;\n    vector<string> board(N);\n    for (int i = 0; i < N; i++) {\n        cin >> board[i];\n    }\n\n    vector<char> directions;\n    vector<int> indices;\n\n    for (int j = 0; j < N; j++) {\n        int max_r = -1;\n        int min_r = N;\n        bool has_oni = false;\n        for (int i = 0; i < N; i++) {\n            if (board[i][j] == 'x') {\n                has_oni = true;\n                if (i > max_r) max_r = i;\n                if (i < min_r) min_r = i;\n            }\n        }\n        if (!has_oni) continue;\n\n        bool safe_up = true;\n        for (int i = 0; i < max_r; i++) {\n            if (board[i][j] == 'o') {\n                safe_up = false;\n                break;\n            }\n        }\n\n        bool safe_down = true;\n        for (int i = min_r + 1; i < N; i++) {\n            if (board[i][j] == 'o') {\n                safe_down = false;\n                break;\n            }\n        }\n\n        int shifts_up = max_r + 1;\n        int shifts_down = N - min_r;\n\n        char dir;\n        int shifts;\n        if (safe_up && safe_down) {\n            if (shifts_up <= shifts_down) {\n                dir = 'U';\n                shifts = shifts_up;\n            } else {\n                dir = 'D';\n                shifts = shifts_down;\n            }\n        } else if (safe_up) {\n            dir = 'U';\n            shifts = shifts_up;\n        } else if (safe_down) {\n            dir = 'D';\n            shifts = shifts_down;\n        } else {\n            dir = 'U';\n            shifts = shifts_up;\n        }\n\n        for (int k = 0; k < shifts; k++) {\n            directions.push_back(dir);\n            indices.push_back(j);\n        }\n    }\n\n    for (size_t i = 0; i < directions.size(); i++) {\n        cout << directions[i] << \" \" << indices[i] << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Fast simulation that estimates the error without running all 500,000 steps\nvoid fast_simulate(const vector<int>& a, const vector<int>& b, int L, vector<int>& t, int& error, const vector<int>& T, int steps = 10000) {\n    t.assign(a.size(), 0);\n    int current = 0;\n    vector<int> count(a.size(), 0);\n    int actual_steps = min(L, steps);\n    for (int week = 0; week < actual_steps; week++) {\n        t[current]++;\n        int times = count[current];\n        count[current]++;\n        if (times % 2 == 1) {\n            current = a[current];\n        } else {\n            current = b[current];\n        }\n    }\n    \n    // Scale the results to estimate the full simulation\n    if (actual_steps < L) {\n        double scale_factor = (double)L / actual_steps;\n        for (int i = 0; i < a.size(); i++) {\n            t[i] = round(t[i] * scale_factor);\n        }\n    }\n    \n    error = 0;\n    for (int i = 0; i < a.size(); i++) {\n        error += abs(t[i] - T[i]);\n    }\n}\n\nint main() {\n    int N, L;\n    cin >> N >> L;\n    vector<int> T(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n\n    auto start_time = chrono::high_resolution_clock::now();\n    \n    // Phase 1: Fast proportional allocation (like previous solution)\n    vector<double> target_ratio(N);\n    double total_T = accumulate(T.begin(), T.end(), 0.0);\n    for (int i = 0; i < N; i++) {\n        target_ratio[i] = T[i] / total_T;\n    }\n\n    vector<int> a(N), b(N);\n    for (int i = 0; i < N; i++) {\n        a[i] = (i + 1) % N;\n        b[i] = (i + N - 1) % N;\n    }\n\n    vector<int> desired_incoming(N);\n    int total_edges = 2 * N;\n    for (int i = 0; i < N; i++) {\n        desired_incoming[i] = round(target_ratio[i] * total_edges);\n    }\n    \n    int current_total = accumulate(desired_incoming.begin(), desired_incoming.end(), 0);\n    while (current_total != total_edges) {\n        if (current_total < total_edges) {\n            int best_idx = -1;\n            double best_ratio = -1;\n            for (int i = 0; i < N; i++) {\n                if (desired_incoming[i] < total_edges) {\n                    if (target_ratio[i] > best_ratio) {\n                        best_ratio = target_ratio[i];\n                        best_idx = i;\n                    }\n                }\n            }\n            if (best_idx != -1) {\n                desired_incoming[best_idx]++;\n                current_total++;\n            } else {\n                break;\n            }\n        } else {\n            int best_idx = -1;\n            double best_ratio = 2.0;\n            for (int i = 0; i < N; i++) {\n                if (desired_incoming[i] > 1) {\n                    if (target_ratio[i] < best_ratio) {\n                        best_ratio = target_ratio[i];\n                        best_idx = i;\n                    }\n                }\n            }\n            if (best_idx != -1) {\n                desired_incoming[best_idx]--;\n                current_total--;\n            } else {\n                break;\n            }\n        }\n    }\n\n    vector<int> pointer_targets;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < desired_incoming[i]; j++) {\n            pointer_targets.push_back(i);\n        }\n    }\n    \n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(pointer_targets.begin(), pointer_targets.end(), gen);\n    \n    for (int i = 0; i < N; i++) {\n        a[i] = pointer_targets[2 * i];\n        b[i] = pointer_targets[2 * i + 1];\n    }\n\n    // Phase 2: Limited optimization using fast simulations\n    vector<int> best_a = a;\n    vector<int> best_b = b;\n    vector<int> t(N);\n    int best_error;\n    fast_simulate(best_a, best_b, L, t, best_error, T, 20000);\n    \n    const int MAX_ITER = 500;\n    double temperature = 100.0;\n    const double cooling_rate = 0.95;\n    \n    for (int iter = 0; iter < MAX_ITER; iter++) {\n        // Make a small change\n        int i = gen() % N;\n        int pointer_type = gen() % 2;\n        int old_value = (pointer_type == 0) ? a[i] : b[i];\n        int new_value = gen() % N;\n        \n        if (new_value == old_value) continue;\n        \n        // Apply change\n        if (pointer_type == 0) {\n            a[i] = new_value;\n        } else {\n            b[i] = new_value;\n        }\n        \n        // Evaluate with fast simulation\n        int current_error;\n        fast_simulate(a, b, L, t, current_error, T, 10000);\n        \n        // Simulated annealing acceptance\n        if (current_error < best_error || \n            exp((best_error - current_error) / temperature) > (gen() % 1000) / 1000.0) {\n            best_error = current_error;\n            best_a = a;\n            best_b = b;\n        } else {\n            // Revert change\n            if (pointer_type == 0) {\n                a[i] = old_value;\n            } else {\n                b[i] = old_value;\n            }\n        }\n        \n        // Cool temperature\n        temperature *= cooling_rate;\n        \n        // Check time limit\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1800) {\n            break;\n        }\n    }\n    \n    // Phase 3: Final refinement with slightly longer simulation for the best solution\n    vector<int> final_t(N);\n    int final_error;\n    fast_simulate(best_a, best_b, L, final_t, final_error, T, 50000);\n    \n    // Output the best solution found\n    for (int i = 0; i < N; i++) {\n        cout << best_a[i] << \" \" << best_b[i] << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <random>\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (int i = 0; i < M; i++) {\n        cin >> G[i];\n    }\n    vector<City> cities(N);\n    for (int i = 0; i < N; i++) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].id = i;\n    }\n\n    // Calculate center points and use Morton code for spatial grouping\n    vector<int> x_center(N), y_center(N);\n    for (int i = 0; i < N; i++) {\n        x_center[i] = (cities[i].lx + cities[i].rx) / 2;\n        y_center[i] = (cities[i].ly + cities[i].ry) / 2;\n    }\n\n    // Improved Morton code calculation\n    vector<uint64_t> morton_codes(N);\n    for (int i = 0; i < N; i++) {\n        uint64_t code = 0;\n        for (int j = 0; j < 16; j++) {\n            code |= (uint64_t)((x_center[i] >> j) & 1) << (2 * j);\n            code |= (uint64_t)((y_center[i] >> j) & 1) << (2 * j + 1);\n        }\n        morton_codes[i] = code;\n    }\n\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n    sort(indices.begin(), indices.end(), [&](int i, int j) {\n        return morton_codes[i] < morton_codes[j];\n    });\n\n    // Create groups\n    vector<vector<int>> groups(M);\n    int start_idx = 0;\n    for (int i = 0; i < M; i++) {\n        int g_size = G[i];\n        groups[i].resize(g_size);\n        for (int j = 0; j < g_size; j++) {\n            groups[i][j] = indices[start_idx + j];\n        }\n        start_idx += g_size;\n    }\n\n    vector<pair<int, int>> collected_edges;\n    int queries_used = 0;\n\n    // Improved query strategy: prioritize larger groups and use overlapping windows\n    for (int i = 0; i < M; i++) {\n        if (queries_used >= Q) break;\n        int g = groups[i].size();\n        if (g < 2) continue;\n        \n        if (g <= L) {\n            // Query entire group if it fits\n            cout << \"? \" << g;\n            for (int city_id : groups[i]) {\n                cout << \" \" << city_id;\n            }\n            cout << endl;\n            cout.flush();\n            \n            for (int j = 0; j < g - 1; j++) {\n                int a, b;\n                cin >> a >> b;\n                collected_edges.push_back({min(a, b), max(a, b)});\n            }\n            queries_used++;\n        } else {\n            // Use overlapping windows for better connectivity\n            int window_size = L;\n            int step = max(1, L / 2); // 50% overlap\n            for (int start = 0; start < g - 1 && queries_used < Q; start += step) {\n                int end = min(start + window_size, g);\n                int size = end - start;\n                if (size < 2) break;\n                \n                cout << \"? \" << size;\n                for (int k = start; k < end; k++) {\n                    cout << \" \" << groups[i][k];\n                }\n                cout << endl;\n                cout.flush();\n                \n                for (int k = 0; k < size - 1; k++) {\n                    int a, b;\n                    cin >> a >> b;\n                    collected_edges.push_back({min(a, b), max(a, b)});\n                }\n                queries_used++;\n            }\n        }\n    }\n\n    // Use remaining queries to sample from the largest groups\n    int remaining_queries = Q - queries_used;\n    if (remaining_queries > 0) {\n        // Sort groups by size (descending)\n        vector<int> group_indices(M);\n        iota(group_indices.begin(), group_indices.end(), 0);\n        sort(group_indices.begin(), group_indices.end(), [&](int i, int j) {\n            return groups[i].size() > groups[j].size();\n        });\n        \n        mt19937 rng(42);\n        for (int i = 0; i < M && remaining_queries > 0; i++) {\n            int group_idx = group_indices[i];\n            int g = groups[group_idx].size();\n            if (g < 3) continue;\n            \n            // Sample a random subset\n            vector<int> sample_indices(g);\n            iota(sample_indices.begin(), sample_indices.end(), 0);\n            shuffle(sample_indices.begin(), sample_indices.end(), rng);\n            \n            int sample_size = min(L, g);\n            cout << \"? \" << sample_size;\n            for (int j = 0; j < sample_size; j++) {\n                cout << \" \" << groups[group_idx][sample_indices[j]];\n            }\n            cout << endl;\n            cout.flush();\n            \n            for (int j = 0; j < sample_size - 1; j++) {\n                int a, b;\n                cin >> a >> b;\n                collected_edges.push_back({min(a, b), max(a, b)});\n            }\n            remaining_queries--;\n        }\n    }\n\n    // Output final answer\n    cout << \"!\" << endl;\n    \n    // Create a set for fast lookup of queried edges\n    set<pair<int, int>> queried_edges;\n    for (auto& edge : collected_edges) {\n        queried_edges.insert(edge);\n    }\n\n    for (int i = 0; i < M; i++) {\n        vector<int>& group = groups[i];\n        int g = group.size();\n        \n        // Output group cities\n        for (int j = 0; j < g; j++) {\n            if (j > 0) cout << \" \";\n            cout << group[j];\n        }\n        cout << endl;\n        \n        if (g == 1) continue;\n\n        // Build MST using Kruskal's algorithm with priority for queried edges\n        vector<tuple<int, long long, int, int>> edges;\n        \n        for (int a = 0; a < g; a++) {\n            for (int b = a + 1; b < g; b++) {\n                int u = group[a], v = group[b];\n                pair<int, int> edge_key = {min(u, v), max(u, v)};\n                \n                // Calculate estimated distance using center points\n                long long dx = x_center[u] - x_center[v];\n                long long dy = y_center[u] - y_center[v];\n                long long dist_sq = dx * dx + dy * dy;\n                \n                // Priority: 0 for queried edges, 1 for non-queried\n                int priority = queried_edges.count(edge_key) ? 0 : 1;\n                edges.push_back({priority, dist_sq, u, v});\n            }\n        }\n\n        // Sort by priority then by estimated distance\n        sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {\n            if (get<0>(a) != get<0>(b)) return get<0>(a) < get<0>(b);\n            if (get<1>(a) != get<1>(b)) return get<1>(a) < get<1>(b);\n            if (get<2>(a) != get<2>(b)) return get<2>(a) < get<2>(b);\n            return get<3>(a) < get<3>(b);\n        });\n\n        // Union-Find for Kruskal's algorithm\n        vector<int> parent(g);\n        iota(parent.begin(), parent.end(), 0);\n        \n        function<int(int)> find = [&](int x) {\n            while (parent[x] != x) {\n                parent[x] = parent[parent[x]];\n                x = parent[x];\n            }\n            return x;\n        };\n\n        vector<pair<int, int>> selected_edges;\n        for (auto& edge : edges) {\n            int u = get<2>(edge), v = get<3>(edge);\n            \n            // Find indices of u and v in the group\n            int u_idx = -1, v_idx = -1;\n            for (int k = 0; k < g; k++) {\n                if (group[k] == u) u_idx = k;\n                if (group[k] == v) v_idx = k;\n                if (u_idx != -1 && v_idx != -1) break;\n            }\n            \n            int root_u = find(u_idx), root_v = find(v_idx);\n            if (root_u != root_v) {\n                selected_edges.push_back({u, v});\n                parent[root_u] = root_v;\n                if (selected_edges.size() == g - 1) break;\n            }\n        }\n\n        for (auto& e : selected_edges) {\n            cout << e.first << \" \" << e.second << endl;\n        }\n    }\n    \n    cout.flush();\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<pair<int, int>> points;\n    for (int i = 0; i < M; i++) {\n        int i_val, j_val;\n        cin >> i_val >> j_val;\n        points.push_back({i_val, j_val});\n    }\n\n    int cur_i = points[0].first;\n    int cur_j = points[0].second;\n    \n    // Track block positions (initially no blocks)\n    vector<vector<bool>> blocks(N, vector<bool>(N, false));\n\n    for (int idx = 1; idx < M; idx++) {\n        int target_i = points[idx].first;\n        int target_j = points[idx].second;\n\n        // Horizontal movement\n        while (cur_j != target_j) {\n            int dj = target_j - cur_j;\n            char dir = (dj > 0) ? 'R' : 'L';\n            int k = abs(dj);\n            \n            // Calculate slide distance\n            int slide_dist = 0;\n            int temp_j = cur_j;\n            while (true) {\n                int next_j = temp_j + (dj > 0 ? 1 : -1);\n                if (next_j < 0 || next_j >= N) break;\n                if (blocks[cur_i][next_j]) break;\n                slide_dist++;\n                temp_j = next_j;\n            }\n            \n            // Use slide if beneficial and possible\n            if (k <= slide_dist && \n                ((dj > 0 && target_j == N-1) || (dj < 0 && target_j == 0)) && \n                k >= 2) {\n                cout << \"S \" << dir << endl;\n                cur_j = target_j;\n            } else {\n                cout << \"M \" << dir << endl;\n                cur_j += (dj > 0 ? 1 : -1);\n            }\n        }\n\n        // Vertical movement\n        while (cur_i != target_i) {\n            int di = target_i - cur_i;\n            char dir = (di > 0) ? 'D' : 'U';\n            int k = abs(di);\n            \n            // Calculate slide distance\n            int slide_dist = 0;\n            int temp_i = cur_i;\n            while (true) {\n                int next_i = temp_i + (di > 0 ? 1 : -1);\n                if (next_i < 0 || next_i >= N) break;\n                if (blocks[next_i][cur_j]) break;\n                slide_dist++;\n                temp_i = next_i;\n            }\n            \n            // Use slide if beneficial and possible\n            if (k <= slide_dist && \n                ((di > 0 && target_i == N-1) || (di < 0 && target_i == 0)) && \n                k >= 2) {\n                cout << \"S \" << dir << endl;\n                cur_i = target_i;\n            } else {\n                cout << \"M \" << dir << endl;\n                cur_i += (di > 0 ? 1 : -1);\n            }\n        }\n    }\n\n    return 0;\n}"},"16":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <tuple>\n#include <cmath>\n\nusing namespace std;\n\nconst int GRID_SIZE = 10000;\n\nstruct Company {\n    int id;\n    int x, y, r;\n    int a, b, c, d;\n    int area() const { return (c - a) * (d - b); }\n    double satisfaction() const {\n        int s = area();\n        if (s == 0) return 0.0;\n        double ratio = min(r, s) / (double)max(r, s);\n        return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n    }\n};\n\nstruct Rectangle {\n    int a, b, c, d;\n    Rectangle(int a, int b, int c, int d) : a(a), b(b), c(c), d(d) {}\n    bool contains(int x, int y) const {\n        return a <= x && x < c && b <= y && y < d;\n    }\n    bool overlaps(const Rectangle& other) const {\n        return !(c <= other.a || other.c <= a || d <= other.b || other.d <= b);\n    }\n    int area() const { return (c - a) * (d - b); }\n};\n\nclass FinalOptimizedRectanglePacker {\nprivate:\n    vector<Company> companies;\n    vector<Rectangle> rectangles;\n    \n    bool hasOverlap(const Rectangle& rect, int exclude_idx) const {\n        for (size_t i = 0; i < rectangles.size(); i++) {\n            if (static_cast<int>(i) == exclude_idx) continue;\n            if (rect.overlaps(rectangles[i])) {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    bool isValidExpansion(const Company& company, int da, int db, int dc, int dd, int exclude_idx) const {\n        int new_a = max(0, company.a + da);\n        int new_b = max(0, company.b + db);\n        int new_c = min(GRID_SIZE, company.c + dc);\n        int new_d = min(GRID_SIZE, company.d + dd);\n        \n        if (new_a >= new_c || new_b >= new_d) return false;\n        \n        Rectangle new_rect(new_a, new_b, new_c, new_d);\n        return !hasOverlap(new_rect, exclude_idx) && new_rect.contains(company.x, company.y);\n    }\n    \n    void expandRectangles() {\n        // Sort by area deficit (largest first) for more aggressive expansion\n        vector<int> indices(companies.size());\n        for (size_t i = 0; i < companies.size(); i++) indices[i] = i;\n        sort(indices.begin(), indices.end(), [this](int i, int j) {\n            return (companies[i].r - companies[i].area()) > (companies[j].r - companies[j].area());\n        });\n        \n        vector<bool> fixed(companies.size(), false);\n        int rounds = 0;\n        const int MAX_ROUNDS = 250;  // Increased for more thorough expansion\n        \n        while (rounds < MAX_ROUNDS) {\n            bool any_expansion = false;\n            \n            for (int idx : indices) {\n                if (fixed[idx]) continue;\n                \n                Company& company = companies[idx];\n                int current_area = company.area();\n                int deficit = company.r - current_area;\n                \n                if (deficit <= 0) {\n                    fixed[idx] = true;\n                    continue;\n                }\n                \n                // More aggressive step sizes for large deficits\n                vector<tuple<int, int, int, int, int>> expansions;\n                \n                int max_step = 1;\n                if (deficit > 10000000) max_step = 400;\n                else if (deficit > 5000000) max_step = 200;\n                else if (deficit > 1000000) max_step = 100;\n                else if (deficit > 100000) max_step = 50;\n                else if (deficit > 10000) max_step = 20;\n                else if (deficit > 1000) max_step = 10;\n                \n                for (int step = max_step; step >= 1; step = (step > 1) ? step / 2 : 0) {\n                    if (step == 0) break;\n                    \n                    // Try symmetric expansion first (best for satisfaction)\n                    if (isValidExpansion(company, -step, -step, step, step, idx)) {\n                        int new_area = (company.c + step - company.a + step) * \n                                      (company.d + step - company.b + step);\n                        expansions.emplace_back(-step, -step, step, step, abs(new_area - company.r));\n                    }\n                    \n                    // Try larger individual expansions\n                    if (isValidExpansion(company, -step*2, 0, 0, 0, idx)) {\n                        int new_area = (company.c - company.a + step*2) * (company.d - company.b);\n                        expansions.emplace_back(-step*2, 0, 0, 0, abs(new_area - company.r));\n                    }\n                    if (isValidExpansion(company, 0, 0, step*2, 0, idx)) {\n                        int new_area = (company.c + step*2 - company.a) * (company.d - company.b);\n                        expansions.emplace_back(0, 0, step*2, 0, abs(new_area - company.r));\n                    }\n                    if (isValidExpansion(company, 0, -step*2, 0, 0, idx)) {\n                        int new_area = (company.c - company.a) * (company.d - company.b + step*2);\n                        expansions.emplace_back(0, -step*2, 0, 0, abs(new_area - company.r));\n                    }\n                    if (isValidExpansion(company, 0, 0, 0, step*2, idx)) {\n                        int new_area = (company.c - company.a) * (company.d + step*2 - company.b);\n                        expansions.emplace_back(0, 0, 0, step*2, abs(new_area - company.r));\n                    }\n                    \n                    // Also try regular individual expansions\n                    if (isValidExpansion(company, -step, 0, 0, 0, idx)) {\n                        int new_area = (company.c - company.a + step) * (company.d - company.b);\n                        expansions.emplace_back(-step, 0, 0, 0, abs(new_area - company.r));\n                    }\n                    if (isValidExpansion(company, 0, 0, step, 0, idx)) {\n                        int new_area = (company.c + step - company.a) * (company.d - company.b);\n                        expansions.emplace_back(0, 0, step, 0, abs(new_area - company.r));\n                    }\n                    if (isValidExpansion(company, 0, -step, 0, 0, idx)) {\n                        int new_area = (company.c - company.a) * (company.d - company.b + step);\n                        expansions.emplace_back(0, -step, 0, 0, abs(new_area - company.r));\n                    }\n                    if (isValidExpansion(company, 0, 0, 0, step, idx)) {\n                        int new_area = (company.c - company.a) * (company.d + step - company.b);\n                        expansions.emplace_back(0, 0, 0, step, abs(new_area - company.r));\n                    }\n                    \n                    if (!expansions.empty()) break;\n                }\n                \n                if (expansions.empty()) {\n                    fixed[idx] = true;\n                    continue;\n                }\n                \n                // Choose expansion that minimizes area difference\n                auto best = *min_element(expansions.begin(), expansions.end(),\n                    [](const auto& a, const auto& b) { return get<4>(a) < get<4>(b); });\n                \n                auto [da, db, dc, dd, _] = best;\n                company.a += da; company.b += db;\n                company.c += dc; company.d += dd;\n                rectangles[idx] = Rectangle(company.a, company.b, company.c, company.d);\n                \n                any_expansion = true;\n                \n                // More lenient stopping condition\n                if (abs(company.area() - company.r) < max(2000, company.r / 20)) {\n                    fixed[idx] = true;\n                }\n            }\n            \n            if (!any_expansion) break;\n            rounds++;\n        }\n    }\n    \n    void improveSatisfaction() {\n        // More thorough improvement phase\n        for (int iter = 0; iter < 50; iter++) {\n            bool improved = false;\n            \n            // Sort by satisfaction (lowest first) to prioritize improvements\n            vector<size_t> indices(companies.size());\n            for (size_t i = 0; i < companies.size(); i++) indices[i] = i;\n            sort(indices.begin(), indices.end(), [this](size_t i, size_t j) {\n                return companies[i].satisfaction() < companies[j].satisfaction();\n            });\n            \n            for (size_t idx : indices) {\n                Company& company = companies[idx];\n                double current_sat = company.satisfaction();\n                if (current_sat > 0.998) continue;  // More aggressive threshold\n                \n                // Try larger adjustments first\n                for (int delta = 10; delta >= 1; delta--) {\n                    bool local_improved = false;\n                    \n                    for (int dx = -delta; dx <= delta; dx += (delta > 5) ? 2 : 1) {\n                        for (int dy = -delta; dy <= delta; dy += (delta > 5) ? 2 : 1) {\n                            if (dx == 0 && dy == 0) continue;\n                            \n                            int new_a = max(0, company.a + dx);\n                            int new_b = max(0, company.b + dy);\n                            int new_c = min(GRID_SIZE, company.c + dx);\n                            int new_d = min(GRID_SIZE, company.d + dy);\n                            \n                            if (new_a >= new_c || new_b >= new_d) continue;\n                            \n                            if (isValidExpansion(company, dx, dy, dx, dy, static_cast<int>(idx))) {\n                                Company temp = company;\n                                temp.a = new_a; temp.b = new_b;\n                                temp.c = new_c; temp.d = new_d;\n                                double new_sat = temp.satisfaction();\n                                \n                                if (new_sat > current_sat + 0.0005) {  // Lower threshold for improvement\n                                    company = temp;\n                                    rectangles[idx] = Rectangle(company.a, company.b, company.c, company.d);\n                                    improved = true;\n                                    local_improved = true;\n                                    break;\n                                }\n                            }\n                        }\n                        if (local_improved) break;\n                    }\n                    if (local_improved) break;\n                }\n            }\n            \n            if (!improved) break;\n        }\n    }\n    \n    void ensureValidity() {\n        // Final validation pass\n        for (size_t i = 0; i < companies.size(); i++) {\n            Company& company = companies[i];\n            \n            // Ensure point containment\n            if (!(company.a <= company.x && company.x < company.c && \n                  company.b <= company.y && company.y < company.d)) {\n                company.a = company.x;\n                company.b = company.y;\n                company.c = company.x + 1;\n                company.d = company.y + 1;\n            }\n            \n            // Ensure valid bounds\n            company.a = max(0, company.a);\n            company.b = max(0, company.b);\n            company.c = min(GRID_SIZE, company.c);\n            company.d = min(GRID_SIZE, company.d);\n            \n            if (company.a >= company.c) company.c = company.a + 1;\n            if (company.b >= company.d) company.d = company.b + 1;\n            \n            rectangles[i] = Rectangle(company.a, company.b, company.c, company.d);\n        }\n        \n        resolveOverlaps();\n    }\n    \n    void resolveOverlaps() {\n        for (int pass = 0; pass < 3; pass++) {\n            bool overlap_found = false;\n            \n            for (size_t i = 0; i < companies.size(); i++) {\n                for (size_t j = i + 1; j < companies.size(); j++) {\n                    Company& rect1 = companies[i];\n                    Company& rect2 = companies[j];\n                    \n                    if (rect1.c > rect2.a && rect2.c > rect1.a &&\n                        rect1.d > rect2.b && rect2.d > rect1.b) {\n                        overlap_found = true;\n                        \n                        // Resolve by shrinking the rectangle with worse satisfaction\n                        double sat1 = rect1.satisfaction();\n                        double sat2 = rect2.satisfaction();\n                        \n                        if (sat1 < sat2) {\n                            if (rect1.a < rect2.c && rect1.a >= rect2.a) rect1.a = rect2.c;\n                            if (rect1.c > rect2.a && rect1.c <= rect2.c) rect1.c = rect2.a;\n                            if (rect1.b < rect2.d && rect1.b >= rect2.b) rect1.b = rect2.d;\n                            if (rect1.d > rect2.b && rect1.d <= rect2.d) rect1.d = rect2.b;\n                        } else {\n                            if (rect2.a < rect1.c && rect2.a >= rect1.a) rect2.a = rect1.c;\n                            if (rect2.c > rect1.a && rect2.c <= rect1.c) rect2.c = rect1.a;\n                            if (rect2.b < rect1.d && rect2.b >= rect1.b) rect2.b = rect1.d;\n                            if (rect2.d > rect1.b && rect2.d <= rect1.d) rect2.d = rect1.b;\n                        }\n                        \n                        // Ensure point containment\n                        if (!(rect1.a <= rect1.x && rect1.x < rect1.c)) {\n                            rect1.a = rect1.x; rect1.c = rect1.x + 1;\n                        }\n                        if (!(rect1.b <= rect1.y && rect1.y < rect1.d)) {\n                            rect1.b = rect1.y; rect1.d = rect1.y + 1;\n                        }\n                        if (!(rect2.a <= rect2.x && rect2.x < rect2.c)) {\n                            rect2.a = rect2.x; rect2.c = rect2.x + 1;\n                        }\n                        if (!(rect2.b <= rect2.y && rect2.y < rect2.d)) {\n                            rect2.b = rect2.y; rect2.d = rect2.y + 1;\n                        }\n                        \n                        rectangles[i] = Rectangle(rect1.a, rect1.b, rect1.c, rect1.d);\n                        rectangles[j] = Rectangle(rect2.a, rect2.b, rect2.c, rect2.d);\n                    }\n                }\n            }\n            \n            if (!overlap_found) break;\n        }\n    }\n    \npublic:\n    FinalOptimizedRectanglePacker(int n, const vector<tuple<int, int, int>>& input) {\n        companies.resize(n);\n        for (int i = 0; i < n; i++) {\n            auto [x, y, r] = input[i];\n            companies[i] = {i, x, y, r, x, y, x + 1, y + 1};\n            rectangles.emplace_back(x, y, x + 1, y + 1);\n        }\n    }\n    \n    void solve() {\n        expandRectangles();\n        improveSatisfaction();\n        ensureValidity();\n    }\n    \n    vector<tuple<int, int, int, int>> getSolution() {\n        vector<tuple<int, int, int, int>> result;\n        for (const auto& company : companies) {\n            result.emplace_back(company.a, company.b, company.c, company.d);\n        }\n        return result;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    vector<tuple<int, int, int>> input;\n    for (int i = 0; i < n; i++) {\n        int x, y, r;\n        cin >> x >> y >> r;\n        input.emplace_back(x, y, r);\n    }\n    \n    FinalOptimizedRectanglePacker packer(n, input);\n    packer.solve();\n    \n    auto solution = packer.getSolution();\n    for (const auto& [a, b, c, d] : solution) {\n        cout << a << \" \" << b << \" \" << c << \" \" << d << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <array>\n#include <algorithm>\n#include <string>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nconst int GRID_SIZE = 50;\nconst int MAX_PATH_LENGTH = 4000; // Increased for longer paths\n\nstruct State {\n    int i, j;\n    int score;\n    string path;\n    vector<bool> visited_tiles;\n    \n    bool operator<(const State& other) const {\n        return score < other.score;\n    }\n    \n    bool operator>(const State& other) const {\n        return score > other.score;\n    }\n};\n\n// Enhanced potential calculation with distance weighting\nint calculate_potential(const vector<vector<int>>& values, int i, int j, const vector<bool>& visited, const vector<vector<int>>& tile_id) {\n    int potential = 0;\n    for (int di = -3; di <= 3; di++) {\n        for (int dj = -3; dj <= 3; dj++) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < GRID_SIZE && nj >= 0 && nj < GRID_SIZE) {\n                int tid = tile_id[ni][nj];\n                if (!visited[tid]) {\n                    // Distance-based weighting: closer tiles have higher influence\n                    double distance = sqrt(di*di + dj*dj);\n                    double weight = max(0.1, 1.0 - distance/5.0); // Weight decreases with distance\n                    potential += static_cast<int>(values[ni][nj] * weight);\n                }\n            }\n        }\n    }\n    return potential;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<vector<int>> tile_id(GRID_SIZE, vector<int>(GRID_SIZE));\n    vector<vector<int>> values(GRID_SIZE, vector<int>(GRID_SIZE));\n    \n    // Read tile IDs\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            cin >> tile_id[i][j];\n        }\n    }\n    \n    // Read square values\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            cin >> values[i][j];\n        }\n    }\n    \n    // Find maximum tile ID\n    int max_tile = 0;\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            max_tile = max(max_tile, tile_id[i][j]);\n        }\n    }\n    int tile_count = max_tile + 1;\n    \n    // Precompute tile information\n    vector<int> tile_total_values(tile_count, 0);\n    vector<int> tile_sizes(tile_count, 0);\n    for (int i = 0; i < GRID_SIZE; i++) {\n        for (int j = 0; j < GRID_SIZE; j++) {\n            int tid = tile_id[i][j];\n            tile_total_values[tid] += values[i][j];\n            tile_sizes[tid]++;\n        }\n    }\n    \n    // Movement directions: Up, Down, Left, Right\n    array<pair<int, int>, 4> directions = {{\n        {-1, 0}, {1, 0}, {0, -1}, {0, 1}\n    }};\n    array<char, 4> dir_chars = {'U', 'D', 'L', 'R'};\n    \n    State best_overall;\n    best_overall.i = si;\n    best_overall.j = sj;\n    best_overall.score = values[si][sj];\n    best_overall.path = \"\";\n    best_overall.visited_tiles = vector<bool>(tile_count, false);\n    best_overall.visited_tiles[tile_id[si][sj]] = true;\n    \n    mt19937 rng(42); // Fixed seed for reproducibility\n    \n    // Optimized strategy set based on breakthrough performance\n    vector<pair<int, string>> strategies = {\n        {350, \"basic\"},           // Very wide beam for broad exploration\n        {280, \"tile_value\"},      // Focus on high-value tiles\n        {220, \"exploration\"},     // Exploration-focused\n        {300, \"potential\"}        // Potential-based heuristic (proven effective)\n    };\n    \n    for (const auto& [beam_width, strategy] : strategies) {\n        State initial;\n        initial.i = si;\n        initial.j = sj;\n        initial.score = values[si][sj];\n        initial.path = \"\";\n        initial.visited_tiles = vector<bool>(tile_count, false);\n        initial.visited_tiles[tile_id[si][sj]] = true;\n        \n        priority_queue<State, vector<State>, greater<State>> current_beam;\n        current_beam.push(initial);\n        \n        for (int step = 0; step < MAX_PATH_LENGTH && !current_beam.empty(); step++) {\n            vector<State> next_states;\n            \n            while (!current_beam.empty()) {\n                State current = current_beam.top();\n                current_beam.pop();\n                \n                for (int d = 0; d < 4; d++) {\n                    int ni = current.i + directions[d].first;\n                    int nj = current.j + directions[d].second;\n                    \n                    if (ni < 0 || ni >= GRID_SIZE || nj < 0 || nj >= GRID_SIZE) {\n                        continue;\n                    }\n                    \n                    int next_tile = tile_id[ni][nj];\n                    if (current.visited_tiles[next_tile]) {\n                        continue;\n                    }\n                    \n                    State new_state = current;\n                    new_state.i = ni;\n                    new_state.j = nj;\n                    new_state.score += values[ni][nj];\n                    new_state.path += dir_chars[d];\n                    new_state.visited_tiles[next_tile] = true;\n                    \n                    // Enhanced heuristic system with optimized weights\n                    int temp_score_boost = 0;\n                    if (strategy == \"tile_value\") {\n                        temp_score_boost = tile_total_values[next_tile] / (70 * max(1, tile_sizes[next_tile]));\n                    } else if (strategy == \"exploration\") {\n                        int unvisited_neighbors = 0;\n                        for (int d2 = 0; d2 < 4; d2++) {\n                            int nni = ni + directions[d2].first;\n                            int nnj = nj + directions[d2].second;\n                            if (nni >= 0 && nni < GRID_SIZE && nnj >= 0 && nnj < GRID_SIZE) {\n                                int neighbor_tile = tile_id[nni][nnj];\n                                if (!new_state.visited_tiles[neighbor_tile]) {\n                                    unvisited_neighbors++;\n                                }\n                            }\n                        }\n                        temp_score_boost = unvisited_neighbors * 4; // Increased weight\n                    } else if (strategy == \"potential\") {\n                        // Use enhanced potential-based heuristic\n                        temp_score_boost = calculate_potential(values, ni, nj, new_state.visited_tiles, tile_id) / 40;\n                    }\n                    \n                    // Adaptive randomness: higher chance early, decreases over time\n                    if (step < 800) {\n                        uniform_int_distribution<int> dist(0, 99);\n                        int random_chance = max(5, 15 - step/100); // Decreases from 15% to 5%\n                        if (dist(rng) < random_chance) {\n                            temp_score_boost += dist(rng) * 3;\n                        }\n                    }\n                    \n                    new_state.score += temp_score_boost;\n                    next_states.push_back(new_state);\n                    \n                    State best_candidate = new_state;\n                    best_candidate.score -= temp_score_boost;\n                    if (best_candidate.score > best_overall.score) {\n                        best_overall = best_candidate;\n                    }\n                }\n            }\n            \n            if (next_states.empty()) break;\n            \n            // Remove temporary boosts before final selection\n            for (auto& state : next_states) {\n                int temp_score_boost = 0;\n                if (strategy == \"tile_value\") {\n                    int current_tile = tile_id[state.i][state.j];\n                    temp_score_boost = tile_total_values[current_tile] / (70 * max(1, tile_sizes[current_tile]));\n                } else if (strategy == \"exploration\") {\n                    int unvisited_neighbors = 0;\n                    for (int d2 = 0; d2 < 4; d2++) {\n                        int nni = state.i + directions[d2].first;\n                        int nnj = state.j + directions[d2].second;\n                        if (nni >= 0 && nni < GRID_SIZE && nnj >= 0 && nnj < GRID_SIZE) {\n                            int neighbor_tile = tile_id[nni][nnj];\n                            if (!state.visited_tiles[neighbor_tile]) {\n                                unvisited_neighbors++;\n                            }\n                        }\n                    }\n                    temp_score_boost = unvisited_neighbors * 4;\n                } else if (strategy == \"potential\") {\n                    temp_score_boost = calculate_potential(values, state.i, state.j, state.visited_tiles, tile_id) / 40;\n                }\n                state.score -= temp_score_boost;\n            }\n            \n            sort(next_states.begin(), next_states.end(), greater<State>());\n            \n            if (next_states.size() > beam_width) {\n                next_states.resize(beam_width);\n            }\n            \n            // Re-apply boosts for next beam selection\n            for (auto& state : next_states) {\n                int temp_score_boost = 0;\n                if (strategy == \"tile_value\") {\n                    int current_tile = tile_id[state.i][state.j];\n                    temp_score_boost = tile_total_values[current_tile] / (70 * max(1, tile_sizes[current_tile]));\n                } else if (strategy == \"exploration\") {\n                    int unvisited_neighbors = 0;\n                    for (int d2 = 0; d2 < 4; d2++) {\n                        int nni = state.i + directions[d2].first;\n                        int nnj = state.j + directions[d2].second;\n                        if (nni >= 0 && nni < GRID_SIZE && nnj >= 0 && nnj < GRID_SIZE) {\n                            int neighbor_tile = tile_id[nni][nnj];\n                            if (!state.visited_tiles[neighbor_tile]) {\n                                unvisited_neighbors++;\n                            }\n                        }\n                    }\n                    temp_score_boost = unvisited_neighbors * 4;\n                } else if (strategy == \"potential\") {\n                    temp_score_boost = calculate_potential(values, state.i, state.j, state.visited_tiles, tile_id) / 40;\n                }\n                state.score += temp_score_boost;\n            }\n            \n            for (const auto& state : next_states) {\n                current_beam.push(state);\n            }\n        }\n    }\n    \n    // Enhanced final extension with 3-step lookahead\n    State final_state = best_overall;\n    bool improved = true;\n    int extension_steps = 0;\n    const int MAX_EXTENSION = 400;\n    \n    while (improved && extension_steps < MAX_EXTENSION) {\n        improved = false;\n        vector<State> candidates;\n        \n        // Generate 3-step lookahead candidates for better optimization\n        for (int d1 = 0; d1 < 4; d1++) {\n            int ni1 = final_state.i + directions[d1].first;\n            int nj1 = final_state.j + directions[d1].second;\n            \n            if (ni1 < 0 || ni1 >= GRID_SIZE || nj1 < 0 || nj1 >= GRID_SIZE) {\n                continue;\n            }\n            \n            int tile1 = tile_id[ni1][nj1];\n            if (final_state.visited_tiles[tile1]) {\n                continue;\n            }\n            \n            State candidate1 = final_state;\n            candidate1.i = ni1;\n            candidate1.j = nj1;\n            candidate1.score += values[ni1][nj1];\n            candidate1.path += dir_chars[d1];\n            candidate1.visited_tiles[tile1] = true;\n            \n            // Second step\n            for (int d2 = 0; d2 < 4; d2++) {\n                int ni2 = ni1 + directions[d2].first;\n                int nj2 = nj1 + directions[d2].second;\n                \n                if (ni2 < 0 || ni2 >= GRID_SIZE || nj2 < 0 || nj2 >= GRID_SIZE) {\n                    candidates.push_back(candidate1);\n                    continue;\n                }\n                \n                int tile2 = tile_id[ni2][nj2];\n                if (candidate1.visited_tiles[tile2]) {\n                    candidates.push_back(candidate1);\n                    continue;\n                }\n                \n                State candidate2 = candidate1;\n                candidate2.i = ni2;\n                candidate2.j = nj2;\n                candidate2.score += values[ni2][nj2];\n                candidate2.path += dir_chars[d2];\n                candidate2.visited_tiles[tile2] = true;\n                \n                // Third step\n                for (int d3 = 0; d3 < 4; d3++) {\n                    int ni3 = ni2 + directions[d3].first;\n                    int nj3 = nj2 + directions[d3].second;\n                    \n                    if (ni3 < 0 || ni3 >= GRID_SIZE || nj3 < 0 || nj3 >= GRID_SIZE) {\n                        candidates.push_back(candidate2);\n                        continue;\n                    }\n                    \n                    int tile3 = tile_id[ni3][nj3];\n                    if (candidate2.visited_tiles[tile3]) {\n                        candidates.push_back(candidate2);\n                        continue;\n                    }\n                    \n                    State candidate3 = candidate2;\n                    candidate3.i = ni3;\n                    candidate3.j = nj3;\n                    candidate3.score += values[ni3][nj3];\n                    candidate3.path += dir_chars[d3];\n                    candidate3.visited_tiles[tile3] = true;\n                    candidates.push_back(candidate3);\n                }\n            }\n        }\n        \n        if (!candidates.empty()) {\n            auto best_candidate = max_element(candidates.begin(), candidates.end(),\n                                            [](const State& a, const State& b) {\n                                                return a.score < b.score;\n                                            });\n            \n            if (best_candidate->score > final_state.score) {\n                final_state = *best_candidate;\n                improved = true;\n                extension_steps++;\n                \n                if (final_state.score > best_overall.score) {\n                    best_overall = final_state;\n                }\n            }\n        }\n    }\n    \n    cout << best_overall.path << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nconst double INIT_WEIGHT = 5000.0;\nconst double MIN_WEIGHT = 1000.0;\nconst double MAX_WEIGHT = 9000.0;\n\ndouble horizontal[N][N-1];\ndouble vertical[N-1][N];\nint horizontal_count[N][N-1] = {0};\nint vertical_count[N-1][N] = {0};\n\nstruct Node {\n    int i, j;\n    double cost;\n    bool operator<(const Node& other) const {\n        return cost > other.cost;\n    }\n};\n\nstring reconstruct_path(pair<int,int> parent[N][N], int si, int sj, int ti, int tj) {\n    string path = \"\";\n    int i = ti, j = tj;\n    \n    while (i != si || j != sj) {\n        int pi = parent[i][j].first;\n        int pj = parent[i][j].second;\n        \n        if (pi == i) {\n            if (pj < j) path += 'R';\n            else path += 'L';\n        } else {\n            if (pi < i) path += 'D';\n            else path += 'U';\n        }\n        i = pi;\n        j = pj;\n    }\n    \n    reverse(path.begin(), path.end());\n    return path;\n}\n\nstring find_path(int si, int sj, int ti, int tj) {\n    double dist[N][N];\n    pair<int,int> parent[N][N];\n    bool visited[N][N] = {false};\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            dist[i][j] = 1e18;\n        }\n    }\n    \n    dist[si][sj] = 0;\n    priority_queue<Node> pq;\n    pq.push({si, sj, 0});\n    \n    int dx[4] = {-1, 1, 0, 0};\n    int dy[4] = {0, 0, -1, 1};\n    \n    while (!pq.empty()) {\n        auto [i, j, cost] = pq.top();\n        pq.pop();\n        \n        if (visited[i][j]) continue;\n        visited[i][j] = true;\n        \n        if (i == ti && j == tj) break;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + dx[d];\n            int nj = j + dy[d];\n            \n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            \n            double edge_cost;\n            if (dx[d] != 0) { // vertical move\n                int edge_i = min(i, ni);\n                edge_cost = vertical[edge_i][j];\n            } else { // horizontal move\n                int edge_j = min(j, nj);\n                edge_cost = horizontal[i][edge_j];\n            }\n            \n            double new_cost = dist[i][j] + edge_cost;\n            if (new_cost < dist[ni][nj]) {\n                dist[ni][nj] = new_cost;\n                parent[ni][nj] = {i, j};\n                double heuristic = abs(ni - ti) + abs(nj - tj);\n                pq.push({ni, nj, new_cost + heuristic * MIN_WEIGHT});\n            }\n        }\n    }\n    \n    return reconstruct_path(parent, si, sj, ti, tj);\n}\n\nstring find_exploratory_path(int si, int sj, int ti, int tj, int query_index) {\n    // Final optimized exploration strategy\n    bool should_explore = false;\n    if (query_index < 380) {\n        should_explore = (query_index % 2 == 0) || (query_index < 210 && query_index % 1 == 0);\n    } else if (query_index < 680) {\n        should_explore = (query_index % 7 == 0);\n    } else {\n        should_explore = (query_index % 13 == 0);\n    }\n    \n    if (should_explore) {\n        double dist[N][N];\n        pair<int,int> parent[N][N];\n        bool visited[N][N] = {false};\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                dist[i][j] = 1e18;\n            }\n        }\n        \n        dist[si][sj] = 0;\n        priority_queue<Node> pq;\n        pq.push({si, sj, 0});\n        \n        int dx[4] = {-1, 1, 0, 0};\n        int dy[4] = {0, 0, -1, 1};\n        \n        while (!pq.empty()) {\n            auto [i, j, cost] = pq.top();\n            pq.pop();\n            \n            if (visited[i][j]) continue;\n            visited[i][j] = true;\n            \n            if (i == ti && j == tj) break;\n            \n            for (int d = 0; d < 4; d++) {\n                int ni = i + dx[d];\n                int nj = j + dy[d];\n                \n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                \n                double edge_cost;\n                double exploration_bonus = 0.0;\n                \n                if (dx[d] != 0) { // vertical move\n                    int edge_i = min(i, ni);\n                    edge_cost = vertical[edge_i][j];\n                    if (vertical_count[edge_i][j] < 15) {\n                        exploration_bonus = 1250.0 * (1.0 - vertical_count[edge_i][j] / 17.0);\n                    }\n                } else { // horizontal move\n                    int edge_j = min(j, nj);\n                    edge_cost = horizontal[i][edge_j];\n                    if (horizontal_count[i][edge_j] < 15) {\n                        exploration_bonus = 1250.0 * (1.0 - horizontal_count[i][edge_j] / 17.0);\n                    }\n                }\n                \n                double new_cost = dist[i][j] + edge_cost - exploration_bonus;\n                if (new_cost < dist[ni][nj]) {\n                    dist[ni][nj] = new_cost;\n                    parent[ni][nj] = {i, j};\n                    double heuristic = abs(ni - ti) + abs(nj - tj);\n                    pq.push({ni, nj, new_cost + heuristic * MIN_WEIGHT});\n                }\n            }\n        }\n        \n        return reconstruct_path(parent, si, sj, ti, tj);\n    }\n    \n    return find_path(si, sj, ti, tj);\n}\n\ndouble calculate_estimated_length(const string& path, int si, int sj) {\n    double length = 0;\n    int i = si, j = sj;\n    \n    for (char move : path) {\n        if (move == 'U') {\n            length += vertical[i-1][j];\n            i--;\n        } else if (move == 'D') {\n            length += vertical[i][j];\n            i++;\n        } else if (move == 'L') {\n            length += horizontal[i][j-1];\n            j--;\n        } else if (move == 'R') {\n            length += horizontal[i][j];\n            j++;\n        }\n    }\n    \n    return length;\n}\n\nvoid final_smoothing(int query_index) {\n    // Final optimized smoothing parameters\n    double smoothing_strength;\n    if (query_index < 490) {\n        smoothing_strength = 0.108;\n    } else if (query_index < 790) {\n        smoothing_strength = 0.071;\n    } else {\n        smoothing_strength = 0.045;\n    }\n    \n    // Horizontal edges - row-wise smoothing\n    for (int i = 0; i < N; i++) {\n        double row_sum = 0.0;\n        int valid_count = 0;\n        for (int j = 0; j < N-1; j++) {\n            if (horizontal_count[i][j] > 0) {\n                row_sum += horizontal[i][j];\n                valid_count++;\n            }\n        }\n        \n        if (valid_count > 9) {\n            double row_avg = row_sum / valid_count;\n            for (int j = 0; j < N-1; j++) {\n                double confidence = min(1.0, horizontal_count[i][j] / 18.0);\n                double effective_smoothing = smoothing_strength * (1.0 - confidence * 0.48);\n                horizontal[i][j] = (1 - effective_smoothing) * horizontal[i][j] + effective_smoothing * row_avg;\n                horizontal[i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][j]));\n            }\n        }\n    }\n    \n    // Vertical edges - column-wise smoothing\n    for (int j = 0; j < N; j++) {\n        double col_sum = 0.0;\n        int valid_count = 0;\n        for (int i = 0; i < N-1; i++) {\n            if (vertical_count[i][j] > 0) {\n                col_sum += vertical[i][j];\n                valid_count++;\n            }\n        }\n        \n        if (valid_count > 9) {\n            double col_avg = col_sum / valid_count;\n            for (int i = 0; i < N-1; i++) {\n                double confidence = min(1.0, vertical_count[i][j] / 18.0);\n                double effective_smoothing = smoothing_strength * (1.0 - confidence * 0.48);\n                vertical[i][j] = (1 - effective_smoothing) * vertical[i][j] + effective_smoothing * col_avg;\n                vertical[i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[i][j]));\n            }\n        }\n    }\n}\n\nvoid update_weights(const string& path, int si, int sj, double observed_length, int query_index) {\n    double estimated_length = calculate_estimated_length(path, si, sj);\n    double ratio = observed_length / estimated_length;\n    \n    // Final optimized learning rate schedule\n    double base_learning_rate;\n    if (query_index < 310) {\n        base_learning_rate = 0.28;\n    } else if (query_index < 560) {\n        base_learning_rate = 0.202;\n    } else if (query_index < 810) {\n        base_learning_rate = 0.138;\n    } else {\n        base_learning_rate = 0.098;\n    }\n    \n    int i = si, j = sj;\n    for (char move : path) {\n        if (move == 'U') {\n            int edge_i = i-1;\n            vertical_count[edge_i][j]++;\n            double alpha = base_learning_rate / (1 + sqrt(vertical_count[edge_i][j] * 0.58));\n            vertical[edge_i][j] *= (1 + alpha * (ratio - 1));\n            vertical[edge_i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[edge_i][j]));\n            i--;\n        } else if (move == 'D') {\n            int edge_i = i;\n            vertical_count[edge_i][j]++;\n            double alpha = base_learning_rate / (1 + sqrt(vertical_count[edge_i][j] * 0.58));\n            vertical[edge_i][j] *= (1 + alpha * (ratio - 1));\n            vertical[edge_i][j] = max(MIN_WEIGHT, min(MAX_WEIGHT, vertical[edge_i][j]));\n            i++;\n        } else if (move == 'L') {\n            int edge_j = j-1;\n            horizontal_count[i][edge_j]++;\n            double alpha = base_learning_rate / (1 + sqrt(horizontal_count[i][edge_j] * 0.58));\n            horizontal[i][edge_j] *= (1 + alpha * (ratio - 1));\n            horizontal[i][edge_j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][edge_j]));\n            j--;\n        } else if (move == 'R') {\n            int edge_j = j;\n            horizontal_count[i][edge_j]++;\n            double alpha = base_learning_rate / (1 + sqrt(horizontal_count[i][edge_j] * 0.58));\n            horizontal[i][edge_j] *= (1 + alpha * (ratio - 1));\n            horizontal[i][edge_j] = max(MIN_WEIGHT, min(MAX_WEIGHT, horizontal[i][edge_j]));\n            j++;\n        }\n    }\n    \n    // Apply final smoothing\n    if (query_index % 9 == 0) {\n        final_smoothing(query_index);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Initialize edge weights\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N-1; j++) {\n            horizontal[i][j] = INIT_WEIGHT;\n        }\n    }\n    for (int i = 0; i < N-1; i++) {\n        for (int j = 0; j < N; j++) {\n            vertical[i][j] = INIT_WEIGHT;\n        }\n    }\n    \n    for (int k = 0; k < 1000; k++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        string path = find_exploratory_path(si, sj, ti, tj, k);\n        cout << path << endl;\n        cout.flush();\n        \n        int observed_length;\n        cin >> observed_length;\n        \n        update_weights(path, si, sj, observed_length, k);\n    }\n    \n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nbool is_substring_circular(const string& str, const string& sub) {\n    int n = str.size();\n    int L = sub.size();\n    for (int start = 0; start < n; start++) {\n        bool match = true;\n        for (int p = 0; p < L; p++) {\n            if (str[(start + p) % n] != sub[p]) {\n                match = false;\n                break;\n            }\n        }\n        if (match) return true;\n    }\n    return false;\n}\n\nvector<bool> get_matched_sequences_horizontal(const vector<string>& matrix, int i, const vector<string>& sequences) {\n    int n = matrix.size();\n    string row_str;\n    for (int j = 0; j < n; j++) {\n        row_str += matrix[i][j];\n    }\n    vector<bool> matched(sequences.size(), false);\n    for (int idx = 0; idx < sequences.size(); idx++) {\n        matched[idx] = is_substring_circular(row_str, sequences[idx]);\n    }\n    return matched;\n}\n\nvector<bool> get_matched_sequences_vertical(const vector<string>& matrix, int j, const vector<string>& sequences) {\n    int n = matrix.size();\n    string col_str;\n    for (int i = 0; i < n; i++) {\n        col_str += matrix[i][j];\n    }\n    vector<bool> matched(sequences.size(), false);\n    for (int idx = 0; idx < sequences.size(); idx++) {\n        matched[idx] = is_substring_circular(col_str, sequences[idx]);\n    }\n    return matched;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    cin >> N >> M;\n    vector<string> sequences(M);\n    for (int i = 0; i < M; i++) {\n        cin >> sequences[i];\n    }\n    \n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> char_dist(0, 7);\n    uniform_int_distribution<int> pos_dist(0, N-1);\n    uniform_real_distribution<double> prob_dist(0.0, 1.0);\n    \n    vector<int> freq(8, 0);\n    int total_chars = 0;\n    for (const auto& s : sequences) {\n        for (char c : s) {\n            freq[c - 'A']++;\n            total_chars++;\n        }\n    }\n    \n    vector<char> char_pool;\n    for (int i = 0; i < 8; i++) {\n        int count = (freq[i] * N * N) / total_chars;\n        for (int j = 0; j < count; j++) {\n            char_pool.push_back('A' + i);\n        }\n    }\n    \n    while (char_pool.size() < N * N) {\n        int max_freq = 0;\n        int max_idx = 0;\n        for (int i = 0; i < 8; i++) {\n            if (freq[i] > max_freq) {\n                max_freq = freq[i];\n                max_idx = i;\n            }\n        }\n        char_pool.push_back('A' + max_idx);\n    }\n    \n    shuffle(char_pool.begin(), char_pool.end(), gen);\n    \n    vector<string> matrix(N, string(N, ' '));\n    int idx = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            matrix[i][j] = char_pool[idx++];\n        }\n    }\n    \n    vector<int> horiz_count(M, 0);\n    vector<int> vert_count(M, 0);\n    int c = 0;\n    \n    for (int i = 0; i < N; i++) {\n        vector<bool> matched = get_matched_sequences_horizontal(matrix, i, sequences);\n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (matched[s_idx]) {\n                horiz_count[s_idx]++;\n            }\n        }\n    }\n    \n    for (int j = 0; j < N; j++) {\n        vector<bool> matched = get_matched_sequences_vertical(matrix, j, sequences);\n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (matched[s_idx]) {\n                vert_count[s_idx]++;\n            }\n        }\n    }\n    \n    for (int s_idx = 0; s_idx < M; s_idx++) {\n        if (horiz_count[s_idx] > 0 || vert_count[s_idx] > 0) {\n            c++;\n        }\n    }\n    \n    int iterations = 5000;\n    double initial_temp = 1.0;\n    double cooling_rate = 0.999;\n    \n    for (int iter = 0; iter < iterations; iter++) {\n        double temp = initial_temp * pow(cooling_rate, iter);\n        \n        int i = pos_dist(gen);\n        int j = pos_dist(gen);\n        char old_ch = matrix[i][j];\n        char new_ch;\n        do {\n            new_ch = 'A' + char_dist(gen);\n        } while (new_ch == old_ch);\n        \n        vector<int> saved_horiz_count = horiz_count;\n        vector<int> saved_vert_count = vert_count;\n        int saved_c = c;\n        \n        vector<bool> S_old_row = get_matched_sequences_horizontal(matrix, i, sequences);\n        vector<bool> S_old_col = get_matched_sequences_vertical(matrix, j, sequences);\n        \n        matrix[i][j] = new_ch;\n        \n        vector<bool> S_new_row = get_matched_sequences_horizontal(matrix, i, sequences);\n        vector<bool> S_new_col = get_matched_sequences_vertical(matrix, j, sequences);\n        \n        int new_c = saved_c;\n        \n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (S_old_row[s_idx] && !S_new_row[s_idx]) {\n                if (horiz_count[s_idx] == 1 && vert_count[s_idx] == 0) {\n                    new_c--;\n                }\n                horiz_count[s_idx]--;\n            }\n            if (!S_old_row[s_idx] && S_new_row[s_idx]) {\n                horiz_count[s_idx]++;\n                if (horiz_count[s_idx] == 1 && vert_count[s_idx] == 0) {\n                    new_c++;\n                }\n            }\n        }\n        \n        for (int s_idx = 0; s_idx < M; s_idx++) {\n            if (S_old_col[s_idx] && !S_new_col[s_idx]) {\n                if (vert_count[s_idx] == 1 && horiz_count[s_idx] == 0) {\n                    new_c--;\n                }\n                vert_count[s_idx]--;\n            }\n            if (!S_old_col[s_idx] && S_new_col[s_idx]) {\n                vert_count[s_idx]++;\n                if (vert_count[s_idx] == 1 && horiz_count[s_idx] == 0) {\n                    new_c++;\n                }\n            }\n        }\n        \n        double delta_c = new_c - saved_c;\n        if (delta_c > 0 || prob_dist(gen) < exp(delta_c / temp)) {\n            c = new_c;\n        } else {\n            matrix[i][j] = old_ch;\n            horiz_count = saved_horiz_count;\n            vert_count = saved_vert_count;\n            c = saved_c;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << matrix[i] << '\\n';\n    }\n    \n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <stack>\n#include <queue>\n#include <string>\n#include <tuple>\n\nusing namespace std;\n\nclass UnionFind {\npublic:\n    vector<int> parent;\n    UnionFind(int n) {\n        parent.resize(n);\n        for (int i = 0; i < n; i++) {\n            parent[i] = i;\n        }\n    }\n    int find(int x) {\n        if (parent[x] != x) {\n            parent[x] = find(parent[x]);\n        }\n        return parent[x];\n    }\n    void unite(int x, int y) {\n        x = find(x);\n        y = find(y);\n        if (x != y) {\n            parent[x] = y;\n        }\n    }\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n\n    vector<pair<int, int>> points;\n    map<pair<int, int>, int> point_to_index;\n    vector<int> costs;\n    int index = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                points.push_back({i, j});\n                int cost = grid[i][j] - '0';\n                costs.push_back(cost);\n                point_to_index[{i, j}] = index;\n                index++;\n            }\n        }\n    }\n    int V = points.size();\n    if (V == 0) {\n        cout << \"\" << endl;\n        return 0;\n    }\n\n    vector<tuple<int, int, int>> edges;\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    for (int i = 0; i < V; i++) {\n        int x = points[i].first;\n        int y = points[i].second;\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d];\n            int ny = y + dy[d];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] != '#') {\n                int j = point_to_index[{nx, ny}];\n                int w = costs[i] + costs[j];\n                edges.push_back({i, j, w});\n            }\n        }\n    }\n\n    sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {\n        return get<2>(a) < get<2>(b);\n    });\n\n    UnionFind uf(V);\n    vector<vector<int>> mst_graph(V);\n    for (const auto& edge : edges) {\n        int u = get<0>(edge);\n        int v = get<1>(edge);\n        if (!uf.same(u, v)) {\n            uf.unite(u, v);\n            mst_graph[u].push_back(v);\n            mst_graph[v].push_back(u);\n        }\n    }\n\n    int start_index = point_to_index[{si, sj}];\n    vector<vector<int>> children(V);\n    vector<bool> visited(V, false);\n    queue<int> q;\n    q.push(start_index);\n    visited[start_index] = true;\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        for (int v : mst_graph[u]) {\n            if (!visited[v]) {\n                visited[v] = true;\n                children[u].push_back(v);\n                q.push(v);\n            }\n        }\n    }\n\n    vector<int> nextChild(V, 0);\n    stack<int> st;\n    string path;\n    int current = start_index;\n    while (true) {\n        if (nextChild[current] < children[current].size()) {\n            int child = children[current][nextChild[current]];\n            nextChild[current]++;\n            int x1 = points[current].first;\n            int y1 = points[current].second;\n            int x2 = points[child].first;\n            int y2 = points[child].second;\n            if (x2 == x1 - 1) path += 'U';\n            else if (x2 == x1 + 1) path += 'D';\n            else if (y2 == y1 - 1) path += 'L';\n            else if (y2 == y1 + 1) path += 'R';\n            st.push(current);\n            current = child;\n        } else {\n            if (st.empty()) break;\n            int parent = st.top();\n            st.pop();\n            int x1 = points[current].first;\n            int y1 = points[current].second;\n            int x2 = points[parent].first;\n            int y2 = points[parent].second;\n            if (x2 == x1 - 1) path += 'U';\n            else if (x2 == x1 + 1) path += 'D';\n            else if (y2 == y1 - 1) path += 'L';\n            else if (y2 == y1 + 1) path += 'R';\n            current = parent;\n        }\n    }\n\n    cout << path << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nenum Status {\n    NOT_STARTED = 0,\n    ASSIGNED = 1,\n    COMPLETED = 2\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<vector<int>> task_difficulty(N+1, vector<int>(K));\n    for (int i=1; i<=N; i++) {\n        for (int j=0; j<K; j++) {\n            cin >> task_difficulty[i][j];\n        }\n    }\n\n    vector<vector<int>> succ_graph(N+1);\n    vector<vector<int>> prereqs(N+1);\n    for (int i=0; i<R; i++) {\n        int u, v;\n        cin >> u >> v;\n        succ_graph[u].push_back(v);\n        prereqs[v].push_back(u);\n    }\n\n    // Precompute descendant counts\n    vector<int> desc_count(N+1, 0);\n    for (int i=1; i<=N; i++) {\n        vector<bool> visited(N+1, false);\n        queue<int> q;\n        q.push(i);\n        visited[i] = true;\n        int count = 0;\n        while (!q.empty()) {\n            int u = q.front(); q.pop();\n            count++;\n            for (int v : succ_graph[u]) {\n                if (!visited[v]) {\n                    visited[v] = true;\n                    q.push(v);\n                }\n            }\n        }\n        desc_count[i] = count;\n    }\n\n    // Initialize arrays\n    vector<Status> task_status(N+1, NOT_STARTED);\n    vector<int> member_task(M+1, -1); // -1 means idle\n    vector<int> member_start_day(M+1, 0);\n    vector<vector<double>> s_est(M+1, vector<double>(K, 40.0)); // initial skill estimate 40\n\n    vector<int> unfinished_prereqs(N+1, 0);\n    for (int i=1; i<=N; i++) {\n        unfinished_prereqs[i] = prereqs[i].size();\n    }\n\n    int current_day = 1;\n    while (true) {\n        // Identify available tasks and members\n        vector<int> available_tasks;\n        for (int i=1; i<=N; i++) {\n            if (task_status[i] == NOT_STARTED && unfinished_prereqs[i] == 0) {\n                available_tasks.push_back(i);\n            }\n        }\n\n        vector<int> available_members;\n        for (int j=1; j<=M; j++) {\n            if (member_task[j] == -1) {\n                available_members.push_back(j);\n            }\n        }\n\n        // Sort available tasks by descendant count descending\n        sort(available_tasks.begin(), available_tasks.end(), [&](int a, int b) {\n            return desc_count[a] > desc_count[b];\n        });\n\n        vector<pair<int, int>> assignments;\n        for (int task : available_tasks) {\n            if (available_members.empty()) break;\n            int best_member = -1;\n            double best_est_t = 1e9;\n\n            // Function to compute estimated time for task and member\n            auto compute_est_t = [&](int t, int m) {\n                double w = 0.0;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[t][k] > s_est[m][k]) {\n                        w += task_difficulty[t][k] - s_est[m][k];\n                    }\n                }\n                if (w == 0) return 1.0;\n                else return w;\n            };\n\n            for (int member : available_members) {\n                double est_t = compute_est_t(task, member);\n                if (est_t < best_est_t) {\n                    best_est_t = est_t;\n                    best_member = member;\n                }\n            }\n\n            if (best_member != -1) {\n                assignments.push_back({best_member, task});\n                task_status[task] = ASSIGNED;\n                member_task[best_member] = task;\n                member_start_day[best_member] = current_day;\n                // Remove the member from available_members\n                auto it = find(available_members.begin(), available_members.end(), best_member);\n                available_members.erase(it);\n            }\n        }\n\n        // Output assignments\n        cout << assignments.size();\n        for (auto& ass : assignments) {\n            cout << \" \" << ass.first << \" \" << ass.second;\n        }\n        cout << endl;\n        cout.flush();\n\n        // Read input for the day\n        int n;\n        cin >> n;\n        if (n == -1) {\n            break;\n        }\n\n        vector<int> completed_members(n);\n        for (int i=0; i<n; i++) {\n            cin >> completed_members[i];\n        }\n\n        // Process completed members\n        for (int j : completed_members) {\n            int task = member_task[j];\n            if (task == -1) continue; // Should not happen\n            int start_day = member_start_day[j];\n            int t = current_day - start_day + 1;\n\n            // Update skill estimates\n            if (t == 1) {\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        s_est[j][k] = task_difficulty[task][k];\n                    }\n                }\n            } else {\n                double w_pred = 0.0;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        w_pred += task_difficulty[task][k] - s_est[j][k];\n                    }\n                }\n                double e = t - w_pred;\n                double alpha = 0.01;\n                for (int k=0; k<K; k++) {\n                    if (task_difficulty[task][k] > s_est[j][k]) {\n                        s_est[j][k] += 2 * alpha * e;\n                        if (s_est[j][k] < 0) s_est[j][k] = 0;\n                    }\n                }\n            }\n\n            // Update task and member status\n            task_status[task] = COMPLETED;\n            member_task[j] = -1;\n\n            // Update unfinished prerequisites for successors\n            for (int v : succ_graph[task]) {\n                unfinished_prereqs[v]--;\n            }\n        }\n\n        current_day++;\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <climits>\n\nusing namespace std;\n\nstruct RoutePoint {\n    int x, y;\n    int order_id; // -1 for depot\n    bool is_pickup; // true for pickup, false for dropoff\n};\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint manhattan_pair(pair<int, int> p1, pair<int, int> p2) {\n    return abs(p1.first - p2.first) + abs(p1.second - p2.second);\n}\n\nint calculate_cost(const vector<RoutePoint>& route) {\n    int cost = 0;\n    for (int i = 0; i < route.size() - 1; i++) {\n        cost += manhattan(route[i].x, route[i].y, route[i+1].x, route[i+1].y);\n    }\n    return cost;\n}\n\nvector<RoutePoint> remove_order(const vector<RoutePoint>& route, int order_id) {\n    vector<RoutePoint> new_route;\n    for (const auto& point : route) {\n        if (point.order_id != order_id) {\n            new_route.push_back(point);\n        }\n    }\n    return new_route;\n}\n\nint main() {\n    int a[1000], b[1000], c[1000], d[1000];\n    for (int i = 0; i < 1000; i++) {\n        cin >> a[i] >> b[i] >> c[i] >> d[i];\n    }\n\n    vector<RoutePoint> route;\n    route.push_back({400, 400, -1, false});\n    route.push_back({400, 400, -1, false});\n\n    vector<bool> selected(1000, false);\n    int selected_count = 0;\n\n    while (selected_count < 50) {\n        int best_order = -1;\n        int best_i = -1, best_j = -1;\n        int best_cost_increase = INT_MAX;\n        int n = route.size();\n\n        for (int k = 0; k < 1000; k++) {\n            if (selected[k]) continue;\n            pair<int, int> P = {a[k], b[k]};\n            pair<int, int> Q = {c[k], d[k]};\n\n            for (int i = 0; i < n-1; i++) {\n                for (int j = i; j < n-1; j++) {\n                    int cost_increase = 0;\n                    if (i < j) {\n                        cost_increase = manhattan_pair(P, {route[i].x, route[i].y}) \n                                      + manhattan_pair(P, {route[i+1].x, route[i+1].y}) \n                                      - manhattan_pair({route[i].x, route[i].y}, {route[i+1].x, route[i+1].y})\n                                      + manhattan_pair(Q, {route[j].x, route[j].y}) \n                                      + manhattan_pair(Q, {route[j+1].x, route[j+1].y}) \n                                      - manhattan_pair({route[j].x, route[j].y}, {route[j+1].x, route[j+1].y});\n                    } else {\n                        cost_increase = manhattan_pair({route[i].x, route[i].y}, P) \n                                      + manhattan_pair(P, Q) \n                                      + manhattan_pair(Q, {route[i+1].x, route[i+1].y}) \n                                      - manhattan_pair({route[i].x, route[i].y}, {route[i+1].x, route[i+1].y});\n                    }\n                    if (cost_increase < best_cost_increase) {\n                        best_cost_increase = cost_increase;\n                        best_order = k;\n                        best_i = i;\n                        best_j = j;\n                    }\n                }\n            }\n        }\n\n        if (best_order == -1) break;\n\n        RoutePoint pickup = {a[best_order], b[best_order], best_order, true};\n        RoutePoint dropoff = {c[best_order], d[best_order], best_order, false};\n\n        vector<RoutePoint> new_route;\n        for (int i = 0; i <= best_i; i++) {\n            new_route.push_back(route[i]);\n        }\n        new_route.push_back(pickup);\n        for (int i = best_i+1; i <= best_j; i++) {\n            new_route.push_back(route[i]);\n        }\n        new_route.push_back(dropoff);\n        for (int i = best_j+1; i < n; i++) {\n            new_route.push_back(route[i]);\n        }\n        route = new_route;\n        selected[best_order] = true;\n        selected_count++;\n    }\n\n    int n = route.size();\n    int total_dist = calculate_cost(route);\n\n    vector<int> pickup_index(1000, -1);\n    vector<int> dropoff_index(1000, -1);\n    for (int i = 0; i < n; i++) {\n        int order_id = route[i].order_id;\n        if (order_id == -1) continue;\n        if (route[i].is_pickup) {\n            pickup_index[order_id] = i;\n        } else {\n            dropoff_index[order_id] = i;\n        }\n    }\n\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 0; i <= n-3; i++) {\n            for (int j = i+1; j <= n-2; j++) {\n                bool valid = true;\n                for (int k = 0; k < 1000; k++) {\n                    if (selected[k]) {\n                        int pi = pickup_index[k];\n                        int di = dropoff_index[k];\n                        if (pi >= i+1 && pi <= j && di >= i+1 && di <= j) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                }\n                if (!valid) continue;\n\n                int dist_before = manhattan(route[i].x, route[i].y, route[i+1].x, route[i+1].y)\n                                + manhattan(route[j].x, route[j].y, route[j+1].x, route[j+1].y);\n                int dist_after = manhattan(route[i].x, route[i].y, route[j].x, route[j].y)\n                               + manhattan(route[i+1].x, route[i+1].y, route[j+1].x, route[j+1].y);\n                if (dist_after < dist_before) {\n                    reverse(route.begin() + i + 1, route.begin() + j + 1);\n                    total_dist += dist_after - dist_before;\n                    improved = true;\n                    for (int idx = 0; idx < route.size(); idx++) {\n                        int order_id = route[idx].order_id;\n                        if (order_id == -1) continue;\n                        if (route[idx].is_pickup) {\n                            pickup_index[order_id] = idx;\n                        } else {\n                            dropoff_index[order_id] = idx;\n                        }\n                    }\n                }\n            }\n        }\n        n = route.size();\n    }\n\n    int max_reinsert_iter = 5;\n    improved = true;\n    for (int iter = 0; iter < max_reinsert_iter && improved; iter++) {\n        improved = false;\n        for (int k = 0; k < 1000; k++) {\n            if (!selected[k]) continue;\n            vector<RoutePoint> route_without = remove_order(route, k);\n            int cost_without = calculate_cost(route_without);\n            int best_cost = INT_MAX;\n            int best_i = -1, best_j = -1;\n            int n_new = route_without.size();\n            for (int i = 0; i < n_new - 1; i++) {\n                for (int j = i; j < n_new - 1; j++) {\n                    int cost_increase = 0;\n                    if (i < j) {\n                        cost_increase = manhattan(route_without[i].x, route_without[i].y, a[k], b[k])\n                                      + manhattan(a[k], b[k], route_without[i+1].x, route_without[i+1].y)\n                                      - manhattan(route_without[i].x, route_without[i].y, route_without[i+1].x, route_without[i+1].y)\n                                      + manhattan(route_without[j].x, route_without[j].y, c[k], d[k])\n                                      + manhattan(c[k], d[k], route_without[j+1].x, route_without[j+1].y)\n                                      - manhattan(route_without[j].x, route_without[j].y, route_without[j+1].x, route_without[j+1].y);\n                    } else {\n                        cost_increase = manhattan(route_without[i].x, route_without[i].y, a[k], b[k])\n                                      + manhattan(a[k], b[k], c[k], d[k])\n                                      + manhattan(c[k], d[k], route_without[i+1].x, route_without[i+1].y)\n                                      - manhattan(route_without[i].x, route_without[i].y, route_without[i+1].x, route_without[i+1].y);\n                    }\n                    int total_cost = cost_without + cost_increase;\n                    if (total_cost < best_cost) {\n                        best_cost = total_cost;\n                        best_i = i;\n                        best_j = j;\n                    }\n                }\n            }\n            if (best_cost < total_dist) {\n                RoutePoint pickup = {a[k], b[k], k, true};\n                RoutePoint dropoff = {c[k], d[k], k, false};\n                vector<RoutePoint> new_route = route_without;\n                if (best_i < best_j) {\n                    new_route.insert(new_route.begin() + best_i + 1, pickup);\n                    new_route.insert(new_route.begin() + best_j + 2, dropoff);\n                } else {\n                    new_route.insert(new_route.begin() + best_i + 1, pickup);\n                    new_route.insert(new_route.begin() + best_i + 2, dropoff);\n                }\n                route = new_route;\n                total_dist = best_cost;\n                improved = true;\n                for (int i = 0; i < route.size(); i++) {\n                    int order_id = route[i].order_id;\n                    if (order_id == -1) continue;\n                    if (route[i].is_pickup) {\n                        pickup_index[order_id] = i;\n                    } else {\n                        dropoff_index[order_id] = i;\n                    }\n                }\n            }\n        }\n        if (improved) {\n            n = route.size();\n            bool opt_improved = true;\n            while (opt_improved) {\n                opt_improved = false;\n                for (int i = 0; i <= n-3; i++) {\n                    for (int j = i+1; j <= n-2; j++) {\n                        bool valid = true;\n                        for (int k = 0; k < 1000; k++) {\n                            if (selected[k]) {\n                                int pi = pickup_index[k];\n                                int di = dropoff_index[k];\n                                if (pi >= i+1 && pi <= j && di >= i+1 && di <= j) {\n                                    valid = false;\n                                    break;\n                                }\n                            }\n                        }\n                        if (!valid) continue;\n                        int dist_before = manhattan(route[i].x, route[i].y, route[i+1].x, route[i+1].y)\n                                        + manhattan(route[j].x, route[j].y, route[j+1].x, route[j+1].y);\n                        int dist_after = manhattan(route[i].x, route[i].y, route[j].x, route[j].y)\n                                       + manhattan(route[i+1].x, route[i+1].y, route[j+1].x, route[j+1].y);\n                        if (dist_after < dist_before) {\n                            reverse(route.begin() + i + 1, route.begin() + j + 1);\n                            total_dist += dist_after - dist_before;\n                            opt_improved = true;\n                            for (int idx = 0; idx < route.size(); idx++) {\n                                int order_id = route[idx].order_id;\n                                if (order_id == -1) continue;\n                                if (route[idx].is_pickup) {\n                                    pickup_index[order_id] = idx;\n                                } else {\n                                    dropoff_index[order_id] = idx;\n                                }\n                            }\n                        }\n                    }\n                }\n                n = route.size();\n            }\n        }\n    }\n\n    cout << 50 << \" \";\n    for (int i = 0; i < 1000; i++) {\n        if (selected[i]) {\n            cout << i+1 << \" \";\n        }\n    }\n    cout << endl;\n\n    cout << route.size() << \" \";\n    for (auto &p : route) {\n        cout << p.x << \" \" << p.y << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <functional>\n#include <algorithm>\n#include <tuple>\n#include <numeric>\n\nusing namespace std;\n\nconst int N = 400;\nconst int M = 1995;\n\nint main() {\n    vector<double> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<pair<int, int>> edges(M);\n    for (int i = 0; i < M; i++) {\n        int u, v;\n        cin >> u >> v;\n        edges[i] = {u, v};\n    }\n\n    vector<int> d(M);\n    for (int i = 0; i < M; i++) {\n        int u = edges[i].first;\n        int v = edges[i].second;\n        double dx = x[u] - x[v];\n        double dy = y[u] - y[v];\n        double dist = sqrt(dx*dx + dy*dy);\n        d[i] = static_cast<int>(round(dist));\n    }\n\n    // Precompute MST based on Euclidean distances\n    vector<tuple<int, int, int, int>> edges_for_mst;\n    for (int i = 0; i < M; i++) {\n        edges_for_mst.push_back({d[i], edges[i].first, edges[i].second, i});\n    }\n    \n    sort(edges_for_mst.begin(), edges_for_mst.end());\n\n    vector<int> parent_mst(N);\n    iota(parent_mst.begin(), parent_mst.end(), 0);\n    \n    function<int(int)> find_mst = [&](int a) {\n        if (parent_mst[a] == a) return a;\n        return parent_mst[a] = find_mst(parent_mst[a]);\n    };\n\n    vector<bool> in_mst(M, false);\n    for (auto& edge : edges_for_mst) {\n        int u = get<1>(edge);\n        int v = get<2>(edge);\n        int idx = get<3>(edge);\n        \n        int pu = find_mst(u);\n        int pv = find_mst(v);\n        if (pu != pv) {\n            in_mst[idx] = true;\n            parent_mst[pu] = pv;\n        }\n    }\n\n    // Online processing\n    vector<int> parent(N);\n    iota(parent.begin(), parent.end(), 0);\n    \n    function<int(int)> find = [&](int a) {\n        if (parent[a] == a) return a;\n        return parent[a] = find(parent[a]);\n    };\n\n    auto unite = [&](int a, int b) {\n        a = find(a);\n        b = find(b);\n        if (a != b) {\n            parent[a] = b;\n            return true;\n        }\n        return false;\n    };\n\n    int num_components = N;\n\n    for (int i = 0; i < M; i++) {\n        int l_i;\n        cin >> l_i;\n\n        int u = edges[i].first;\n        int v = edges[i].second;\n\n        if (find(u) == find(v)) {\n            cout << 0 << endl;\n        } else {\n            bool adopt = false;\n            int remaining_edges = M - i - 1;\n            int needed_connections = num_components - 1;\n            \n            // Final optimized adaptive threshold calculation\n            double progress_ratio = (double)i / M;\n            double edge_supply_ratio = (remaining_edges > 0 && needed_connections > 0) \n                ? (double)remaining_edges / needed_connections \n                : 1.0;\n            \n            // Highly tuned dynamic threshold\n            double adaptive_threshold = 1.72; // Optimal base threshold\n            \n            // Adjust based on edge supply\n            if (edge_supply_ratio > 3.6) {\n                // Many edges available - be more selective\n                adaptive_threshold = 1.42 + 0.3 * (1.0 / edge_supply_ratio);\n            } else if (edge_supply_ratio < 1.04) {\n                // Few edges available - be less selective\n                adaptive_threshold = 2.38;\n            }\n            \n            // Progress-based adjustment\n            adaptive_threshold -= 0.04 * progress_ratio;\n            \n            // Ensure threshold stays within optimal bounds\n            adaptive_threshold = max(1.38, min(2.22, adaptive_threshold));\n            \n            // Decision criteria (priority order)\n            if (in_mst[i]) {\n                adopt = true;\n            } else if (remaining_edges < needed_connections) {\n                adopt = true;\n            } else if (l_i <= adaptive_threshold * d[i]) {\n                adopt = true;\n            }\n            \n            if (adopt) {\n                cout << 1 << endl;\n                if (unite(u, v)) {\n                    num_components--;\n                }\n            } else {\n                cout << 0 << endl;\n            }\n        }\n        cout.flush();\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int MAX_TURNS = 300;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<tuple<int, int, int>> pets;\n    for (int i = 0; i < N; i++) {\n        int x, y, t;\n        cin >> x >> y >> t;\n        pets.push_back({x, y, t});\n    }\n    int M;\n    cin >> M;\n    vector<pair<int, int>> humans;\n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        humans.push_back({x, y});\n    }\n\n    vector<vector<bool>> blocked(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n    vector<vector<bool>> wall_built(GRID_SIZE + 1, vector<bool>(GRID_SIZE + 1, false));\n\n    // Create 4 smaller enclosures in different areas\n    vector<vector<pair<int, int>>> enclosure_walls;\n    vector<vector<pair<int, int>>> enclosure_bases;\n    \n    // Enclosure 1: Top-left (rows 1-14, cols 1-14)\n    vector<pair<int, int>> walls1, bases1;\n    for (int i = 1; i <= 14; i++) {\n        walls1.push_back({15, i});\n        bases1.push_back({14, i});\n    }\n    for (int i = 1; i <= 14; i++) {\n        walls1.push_back({i, 15});\n        bases1.push_back({i, 14});\n    }\n    enclosure_walls.push_back(walls1);\n    enclosure_bases.push_back(bases1);\n    \n    // Enclosure 2: Top-right (rows 1-14, cols 16-29)\n    vector<pair<int, int>> walls2, bases2;\n    for (int i = 16; i <= 29; i++) {\n        walls2.push_back({15, i});\n        bases2.push_back({14, i});\n    }\n    for (int i = 1; i <= 14; i++) {\n        walls2.push_back({i, 15});\n        bases2.push_back({i, 16});\n    }\n    enclosure_walls.push_back(walls2);\n    enclosure_bases.push_back(bases2);\n    \n    // Enclosure 3: Bottom-left (rows 16-29, cols 1-14)\n    vector<pair<int, int>> walls3, bases3;\n    for (int i = 1; i <= 14; i++) {\n        walls3.push_back({15, i});\n        bases3.push_back({16, i});\n    }\n    for (int i = 16; i <= 29; i++) {\n        walls3.push_back({i, 15});\n        bases3.push_back({i, 14});\n    }\n    enclosure_walls.push_back(walls3);\n    enclosure_bases.push_back(bases3);\n    \n    // Enclosure 4: Bottom-right (rows 16-29, cols 16-29)\n    vector<pair<int, int>> walls4, bases4;\n    for (int i = 16; i <= 29; i++) {\n        walls4.push_back({15, i});\n        bases4.push_back({16, i});\n    }\n    for (int i = 16; i <= 29; i++) {\n        walls4.push_back({i, 15});\n        bases4.push_back({i, 16});\n    }\n    enclosure_walls.push_back(walls4);\n    enclosure_bases.push_back(bases4);\n\n    // Assign humans to enclosures based on proximity and balance\n    vector<int> human_enclosure(M, -1);\n    vector<int> human_wall_index(M, 0);\n    vector<int> enclosure_human_count(4, 0);\n    vector<int> enclosure_completion(4, 0);\n    \n    // First, assign humans to balance the workload\n    for (int i = 0; i < M; i++) {\n        int best_enclosure = -1;\n        double best_score = 1e9;\n        \n        for (int j = 0; j < 4; j++) {\n            int dist = abs(humans[i].first - enclosure_bases[j][0].first) + \n                      abs(humans[i].second - enclosure_bases[j][0].second);\n            double score = dist + enclosure_human_count[j] * 10.0;\n            \n            if (score < best_score) {\n                best_score = score;\n                best_enclosure = j;\n            }\n        }\n        \n        if (best_enclosure != -1) {\n            human_enclosure[i] = best_enclosure;\n            enclosure_human_count[best_enclosure]++;\n        }\n    }\n\n    for (int turn = 1; turn <= MAX_TURNS; turn++) {\n        vector<char> actions(M, '.');\n        set<pair<int, int>> blocks_this_turn;\n        set<pair<int, int>> planned_positions;\n\n        // Update enclosure completion percentages\n        for (int j = 0; j < 4; j++) {\n            int built_walls = 0;\n            for (auto& wall : enclosure_walls[j]) {\n                if (wall_built[wall.first][wall.second]) built_walls++;\n            }\n            enclosure_completion[j] = built_walls * 100 / enclosure_walls[j].size();\n        }\n\n        // First pass: Plan block actions\n        for (int i = 0; i < M; i++) {\n            int enclosure = human_enclosure[i];\n            if (enclosure == -1 || human_wall_index[i] >= enclosure_walls[enclosure].size()) {\n                continue;\n            }\n\n            pair<int, int> target_wall = enclosure_walls[enclosure][human_wall_index[i]];\n            pair<int, int> base_position = enclosure_bases[enclosure][human_wall_index[i]];\n            \n            if (wall_built[target_wall.first][target_wall.second]) {\n                human_wall_index[i]++;\n                continue;\n            }\n\n            // Check if we can build this wall block\n            bool can_block = true;\n\n            // Check if wall square contains pets or humans\n            for (auto& pet : pets) {\n                if (get<0>(pet) == target_wall.first && get<1>(pet) == target_wall.second) {\n                    can_block = false;\n                    break;\n                }\n            }\n            if (can_block) {\n                for (int j = 0; j < M; j++) {\n                    if (humans[j].first == target_wall.first && humans[j].second == target_wall.second) {\n                        can_block = false;\n                        break;\n                    }\n                }\n            }\n\n            // Check ALL adjacent squares (including diagonals) for pets\n            if (can_block) {\n                int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};\n                int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};\n                for (int d = 0; d < 8; d++) {\n                    int nx = target_wall.first + dx[d];\n                    int ny = target_wall.second + dy[d];\n                    if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                    for (auto& pet : pets) {\n                        if (get<0>(pet) == nx && get<1>(pet) == ny) {\n                            can_block = false;\n                            break;\n                        }\n                    }\n                    if (!can_block) break;\n                }\n            }\n\n            if (can_block && humans[i] == base_position) {\n                // We're in position to build the wall\n                int dx = target_wall.first - base_position.first;\n                int dy = target_wall.second - base_position.second;\n                char action;\n                if (dx == 1) action = 'd';\n                else if (dx == -1) action = 'u';\n                else if (dy == 1) action = 'r';\n                else if (dy == -1) action = 'l';\n                else action = '.';\n                \n                actions[i] = action;\n                blocks_this_turn.insert(target_wall);\n                planned_positions.insert(humans[i]); // Human stays in place\n            }\n        }\n\n        // Second pass: Plan movement actions with improved helping strategy\n        for (int i = 0; i < M; i++) {\n            if (actions[i] != '.') continue; // Skip if already doing a block action\n\n            int enclosure = human_enclosure[i];\n            if (enclosure == -1 || human_wall_index[i] >= enclosure_walls[enclosure].size()) {\n                // Try to help other humans who are still working\n                int best_help_enclosure = -1;\n                int best_help_score = -1;\n                \n                for (int j = 0; j < 4; j++) {\n                    if (enclosure_completion[j] >= 100) continue; // Skip completed enclosures\n                    \n                    // Calculate helping score: prioritize less complete enclosures with fewer humans\n                    int remaining_walls = enclosure_walls[j].size();\n                    for (auto& wall : enclosure_walls[j]) {\n                        if (wall_built[wall.first][wall.second]) remaining_walls--;\n                    }\n                    \n                    int humans_on_enclosure = 0;\n                    for (int k = 0; k < M; k++) {\n                        if (human_enclosure[k] == j && human_wall_index[k] < enclosure_walls[j].size()) {\n                            humans_on_enclosure++;\n                        }\n                    }\n                    \n                    int help_score = remaining_walls * 10 - humans_on_enclosure * 5;\n                    \n                    if (help_score > best_help_score) {\n                        best_help_score = help_score;\n                        best_help_enclosure = j;\n                    }\n                }\n                \n                if (best_help_enclosure != -1) {\n                    // Find the next wall to build in the target enclosure\n                    int next_wall_index = -1;\n                    for (int j = 0; j < enclosure_walls[best_help_enclosure].size(); j++) {\n                        if (!wall_built[enclosure_walls[best_help_enclosure][j].first][enclosure_walls[best_help_enclosure][j].second]) {\n                            next_wall_index = j;\n                            break;\n                        }\n                    }\n                    \n                    if (next_wall_index != -1) {\n                        pair<int, int> target_wall = enclosure_walls[best_help_enclosure][next_wall_index];\n                        pair<int, int> base_position = enclosure_bases[best_help_enclosure][next_wall_index];\n                        \n                        // Check if we can help build this wall\n                        bool can_block = true;\n                        \n                        // Check if wall square contains pets or humans\n                        for (auto& pet : pets) {\n                            if (get<0>(pet) == target_wall.first && get<1>(pet) == target_wall.second) {\n                                can_block = false;\n                                break;\n                            }\n                        }\n                        if (can_block) {\n                            for (int k = 0; k < M; k++) {\n                                if (humans[k].first == target_wall.first && humans[k].second == target_wall.second) {\n                                    can_block = false;\n                                    break;\n                                }\n                            }\n                        }\n\n                        // Check ALL adjacent squares (including diagonals) for pets\n                        if (can_block) {\n                            int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};\n                            int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};\n                            for (int d = 0; d < 8; d++) {\n                                int nx = target_wall.first + dx[d];\n                                int ny = target_wall.second + dy[d];\n                                if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                                for (auto& pet : pets) {\n                                    if (get<0>(pet) == nx && get<1>(pet) == ny) {\n                                        can_block = false;\n                                        break;\n                                    }\n                                }\n                                if (!can_block) break;\n                            }\n                        }\n\n                        if (can_block) {\n                            // Move toward the base position to help\n                            int best_dx = 0, best_dy = 0;\n                            int best_distance = INT_MAX;\n                            \n                            int dx[] = {1, -1, 0, 0};\n                            int dy[] = {0, 0, 1, -1};\n                            \n                            for (int d = 0; d < 4; d++) {\n                                int nx = humans[i].first + dx[d];\n                                int ny = humans[i].second + dy[d];\n                                \n                                // Check if this move is valid\n                                if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                                \n                                // Check if the square is blocked\n                                if (blocked[nx][ny]) continue;\n                                \n                                // Check if this square will be blocked this turn\n                                if (blocks_this_turn.find({nx, ny}) != blocks_this_turn.end()) continue;\n                                \n                                // Check if another human is already planning to move here\n                                if (planned_positions.find({nx, ny}) != planned_positions.end()) continue;\n                                \n                                // Check if the square contains pets\n                                bool has_pet = false;\n                                for (auto& pet : pets) {\n                                    if (get<0>(pet) == nx && get<1>(pet) == ny) {\n                                        has_pet = true;\n                                        break;\n                                    }\n                                }\n                                if (has_pet) continue;\n                                \n                                // Check if the square contains humans (at start of turn)\n                                bool has_human = false;\n                                for (int k = 0; k < M; k++) {\n                                    if (i != k && humans[k].first == nx && humans[k].second == ny) {\n                                        has_human = true;\n                                        break;\n                                    }\n                                }\n                                if (has_human) continue;\n                                \n                                // Calculate distance to target\n                                int distance = abs(nx - base_position.first) + abs(ny - base_position.second);\n                                if (distance < best_distance) {\n                                    best_distance = distance;\n                                    best_dx = dx[d];\n                                    best_dy = dy[d];\n                                }\n                            }\n                            \n                            if (best_dx != 0 || best_dy != 0) {\n                                char action;\n                                if (best_dx == 1) action = 'D';\n                                else if (best_dx == -1) action = 'U';\n                                else if (best_dy == 1) action = 'R';\n                                else if (best_dy == -1) action = 'L';\n                                else action = '.';\n                                \n                                actions[i] = action;\n                                planned_positions.insert({humans[i].first + best_dx, humans[i].second + best_dy});\n                            }\n                        }\n                    }\n                }\n                continue;\n            }\n\n            pair<int, int> target_wall = enclosure_walls[enclosure][human_wall_index[i]];\n            pair<int, int> base_position = enclosure_bases[enclosure][human_wall_index[i]];\n            \n            if (wall_built[target_wall.first][target_wall.second]) {\n                human_wall_index[i]++;\n                continue;\n            }\n\n            if (humans[i] != base_position) {\n                // Improved movement: consider multiple steps for better efficiency\n                int best_dx = 0, best_dy = 0;\n                int best_distance = INT_MAX;\n                \n                int dx[] = {1, -1, 0, 0};\n                int dy[] = {0, 0, 1, -1};\n                \n                for (int d = 0; d < 4; d++) {\n                    int nx = humans[i].first + dx[d];\n                    int ny = humans[i].second + dy[d];\n                    \n                    // Check if this move is valid\n                    if (nx < 1 || nx > GRID_SIZE || ny < 1 || ny > GRID_SIZE) continue;\n                    \n                    // Check if the square is blocked\n                    if (blocked[nx][ny]) continue;\n                    \n                    // Check if this square will be blocked this turn\n                    if (blocks_this_turn.find({nx, ny}) != blocks_this_turn.end()) continue;\n                    \n                    // Check if another human is already planning to move here\n                    if (planned_positions.find({nx, ny}) != planned_positions.end()) continue;\n                    \n                    // Check if the square contains pets\n                    bool has_pet = false;\n                    for (auto& pet : pets) {\n                        if (get<0>(pet) == nx && get<1>(pet) == ny) {\n                            has_pet = true;\n                            break;\n                        }\n                    }\n                    if (has_pet) continue;\n                    \n                    // Check if the square contains humans (at start of turn)\n                    bool has_human = false;\n                    for (int j = 0; j < M; j++) {\n                        if (i != j && humans[j].first == nx && humans[j].second == ny) {\n                            has_human = true;\n                            break;\n                        }\n                    }\n                    if (has_human) continue;\n                    \n                    // Calculate distance to target - prioritize moves that get us closer\n                    int distance = abs(nx - base_position.first) + abs(ny - base_position.second);\n                    if (distance < best_distance) {\n                        best_distance = distance;\n                        best_dx = dx[d];\n                        best_dy = dy[d];\n                    }\n                }\n                \n                if (best_dx != 0 || best_dy != 0) {\n                    char action;\n                    if (best_dx == 1) action = 'D';\n                    else if (best_dx == -1) action = 'U';\n                    else if (best_dy == 1) action = 'R';\n                    else if (best_dy == -1) action = 'L';\n                    else action = '.';\n                    \n                    actions[i] = action;\n                    planned_positions.insert({humans[i].first + best_dx, humans[i].second + best_dy});\n                }\n            }\n        }\n\n        string action_str;\n        for (int i = 0; i < M; i++) {\n            action_str += actions[i];\n        }\n        cout << action_str << endl;\n        cout.flush();\n\n        // Update blocked squares based on block actions\n        for (int i = 0; i < M; i++) {\n            char action = actions[i];\n            if (action == 'u' || action == 'd' || action == 'l' || action == 'r') {\n                int x = humans[i].first;\n                int y = humans[i].second;\n                int block_x, block_y;\n                if (action == 'u') block_x = x - 1, block_y = y;\n                else if (action == 'd') block_x = x + 1, block_y = y;\n                else if (action == 'l') block_x = x, block_y = y - 1;\n                else if (action == 'r') block_x = x, block_y = y + 1;\n\n                if (block_x >= 1 && block_x <= GRID_SIZE && block_y >= 1 && block_y <= GRID_SIZE) {\n                    blocked[block_x][block_y] = true;\n                    wall_built[block_x][block_y] = true;\n                }\n            }\n        }\n\n        // Update human positions\n        for (int i = 0; i < M; i++) {\n            char action = actions[i];\n            if (action == 'U') humans[i].first--;\n            else if (action == 'D') humans[i].first++;\n            else if (action == 'L') humans[i].second--;\n            else if (action == 'R') humans[i].second++;\n        }\n\n        // Read and update pet positions\n        vector<string> pet_movements(N);\n        for (int i = 0; i < N; i++) {\n            cin >> pet_movements[i];\n        }\n\n        for (int i = 0; i < N; i++) {\n            string moves = pet_movements[i];\n            int x = get<0>(pets[i]);\n            int y = get<1>(pets[i]);\n            for (char move : moves) {\n                if (move == 'U') x--;\n                else if (move == 'D') x++;\n                else if (move == 'L') y--;\n                else if (move == 'R') y++;\n            }\n            get<0>(pets[i]) = x;\n            get<1>(pets[i]) = y;\n        }\n    }\n\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <string>\n#include <utility>\n#include <map>\n\nusing namespace std;\n\nconst int GRID_SIZE = 20;\nconst int MAX_LENGTH = 200;\n\n// Directions: Up, Down, Left, Right\nconst int dx[4] = {-1, 1, 0, 0};\nconst int dy[4] = {0, 0, -1, 1};\nconst char dir_char[4] = {'U', 'D', 'L', 'R'};\n\nstruct Cell {\n    int i, j;\n    Cell(int i = 0, int j = 0) : i(i), j(j) {}\n    bool operator==(const Cell& other) const {\n        return i == other.i && j == other.j;\n    }\n    bool operator<(const Cell& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nclass Grid {\npublic:\n    Grid(int si, int sj, int ti, int tj, double p, \n         const vector<string>& h, const vector<string>& v) \n        : si(si), sj(sj), ti(ti), tj(tj), p(p) {\n        this->h = h;\n        this->v = v;\n    }\n\n    bool is_move_allowed(int i, int j, int d) const {\n        if (d == 0) { // Up\n            return i > 0 && v[i-1][j] == '0';\n        } else if (d == 1) { // Down\n            return i < GRID_SIZE - 1 && v[i][j] == '0';\n        } else if (d == 2) { // Left\n            return j > 0 && h[i][j-1] == '0';\n        } else if (d == 3) { // Right\n            return j < GRID_SIZE - 1 && h[i][j] == '0';\n        }\n        return false;\n    }\n\n    string find_shortest_path() const {\n        Cell start(si, sj);\n        Cell end(ti, tj);\n\n        map<Cell, Cell> parent;\n        map<Cell, int> move_dir;\n        queue<Cell> q;\n        q.push(start);\n        parent[start] = start;\n        move_dir[start] = -1;\n\n        while (!q.empty()) {\n            Cell current = q.front();\n            q.pop();\n            if (current == end) {\n                break;\n            }\n            for (int d = 0; d < 4; d++) {\n                if (is_move_allowed(current.i, current.j, d)) {\n                    Cell next(current.i + dx[d], current.j + dy[d]);\n                    if (parent.find(next) == parent.end()) {\n                        parent[next] = current;\n                        move_dir[next] = d;\n                        q.push(next);\n                    }\n                }\n            }\n        }\n\n        string path;\n        Cell current = end;\n        while (current != start) {\n            int d = move_dir[current];\n            path.push_back(dir_char[d]);\n            current = parent[current];\n        }\n        reverse(path.begin(), path.end());\n        return path;\n    }\n\n    string find_cycle() const {\n        // Try to find the most effective cycle pattern\n        // Prefer cycles that provide good coverage around the office\n        vector<pair<string, int>> cycle_candidates;\n        \n        // Basic 2-move cycles\n        if (is_move_allowed(ti, tj, 0) && is_move_allowed(ti-1, tj, 1)) {\n            cycle_candidates.push_back({\"UD\", 2});\n        }\n        if (is_move_allowed(ti, tj, 1) && is_move_allowed(ti+1, tj, 0)) {\n            cycle_candidates.push_back({\"DU\", 2});\n        }\n        if (is_move_allowed(ti, tj, 2) && is_move_allowed(ti, tj-1, 3)) {\n            cycle_candidates.push_back({\"LR\", 2});\n        }\n        if (is_move_allowed(ti, tj, 3) && is_move_allowed(ti, tj+1, 2)) {\n            cycle_candidates.push_back({\"RL\", 2});\n        }\n        \n        // 4-move cycles for better coverage\n        if (is_move_allowed(ti, tj, 0) && is_move_allowed(ti-1, tj, 3) && \n            is_move_allowed(ti-1, tj+1, 1) && is_move_allowed(ti, tj+1, 2)) {\n            cycle_candidates.push_back({\"URDL\", 4});\n        }\n        if (is_move_allowed(ti, tj, 0) && is_move_allowed(ti-1, tj, 2) && \n            is_move_allowed(ti-1, tj-1, 1) && is_move_allowed(ti, tj-1, 3)) {\n            cycle_candidates.push_back({\"ULDR\", 4});\n        }\n        \n        // Prefer longer cycles for better robustness\n        if (!cycle_candidates.empty()) {\n            // Sort by length descending, then by specific pattern\n            sort(cycle_candidates.begin(), cycle_candidates.end(), \n                 [](const pair<string, int>& a, const pair<string, int>& b) {\n                     return a.second > b.second;\n                 });\n            return cycle_candidates[0].first;\n        }\n        \n        return \"UD\"; // Default fallback\n    }\n\nprivate:\n    int si, sj, ti, tj;\n    double p;\n    vector<string> h;\n    vector<string> v;\n};\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    vector<string> h(GRID_SIZE);\n    for (int i = 0; i < GRID_SIZE; i++) {\n        cin >> h[i];\n    }\n\n    vector<string> v(GRID_SIZE - 1);\n    for (int i = 0; i < GRID_SIZE - 1; i++) {\n        cin >> v[i];\n    }\n\n    Grid grid(si, sj, ti, tj, p, h, v);\n    string path = grid.find_shortest_path();\n    string cycle = grid.find_cycle();\n    \n    int L = path.length();\n    string result;\n    \n    // Adaptive strategy based on path length and probability\n    if (L <= 8) {\n        // Very short paths: maximum repetitions\n        int repetitions = MAX_LENGTH / L;\n        for (int i = 0; i < repetitions; i++) {\n            result += path;\n        }\n    } else if (L <= 20) {\n        // Short paths: balance repetitions and cycling\n        int repetitions = max(2, min(5, MAX_LENGTH / L));\n        // Adjust based on probability\n        if (p > 0.3) repetitions++;\n        if (p > 0.4) repetitions++;\n        \n        for (int i = 0; i < repetitions; i++) {\n            result += path;\n        }\n    } else if (L <= 40) {\n        // Medium paths: fewer repetitions, more cycling\n        int repetitions = max(1, min(3, MAX_LENGTH / L));\n        if (p < 0.2) repetitions = max(repetitions, 2);\n        \n        for (int i = 0; i < repetitions; i++) {\n            result += path;\n        }\n    } else {\n        // Long paths: focus on robust cycling\n        result = path; // Include the path at least once\n    }\n    \n    // Use remaining moves for cycling\n    int remaining = MAX_LENGTH - result.length();\n    if (remaining > 0) {\n        // Use extended cycles for better coverage\n        string effective_cycle = cycle;\n        if (remaining >= 8 && cycle.length() <= 4) {\n            effective_cycle = cycle + cycle;\n        }\n        \n        int cycle_len = effective_cycle.length();\n        int num_cycles = remaining / cycle_len;\n        for (int i = 0; i < num_cycles; i++) {\n            result += effective_cycle;\n        }\n        int extra = remaining % cycle_len;\n        if (extra > 0) {\n            result += effective_cycle.substr(0, extra);\n        }\n    }\n    \n    // Ensure we don't exceed 200 characters\n    if (result.length() > MAX_LENGTH) {\n        result = result.substr(0, MAX_LENGTH);\n    }\n\n    cout << result << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    // Precompute global_exit table\n    int to[8][4] = {\n        {1, 0, -1, -1},\n        {3, -1, -1, 0},\n        {-1, -1, 3, 2},\n        {-1, 2, 1, -1},\n        {1, 0, 3, 2},\n        {3, 2, 1, 0},\n        {2, -1, 0, -1},\n        {-1, 3, -1, 1}\n    };\n\n    bool E[8][4] = {false};\n    for (int T = 0; T < 8; T++) {\n        for (int d = 0; d < 4; d++) {\n            int e = to[T][d];\n            if (e != -1) {\n                E[T][e] = true;\n            }\n        }\n    }\n\n    bool global_exit[8][4][4] = {false};\n    for (int T = 0; T < 8; T++) {\n        for (int R = 0; R < 4; R++) {\n            for (int e_local = 0; e_local < 4; e_local++) {\n                if (E[T][e_local]) {\n                    int e_global = (e_local + R) % 4;\n                    global_exit[T][R][e_global] = true;\n                }\n            }\n        }\n    }\n\n    // Process each test case\n    for (int t = 0; t < 100; t++) {\n        vector<string> grid;\n        for (int i = 0; i < 30; i++) {\n            string line;\n            cin >> line;\n            grid.push_back(line);\n        }\n\n        vector<vector<int>> rot(30, vector<int>(30, 0));\n\n        // Simple iterative approach with moderate iterations\n        for (int iter = 0; iter < 5; iter++) {\n            vector<vector<int>> old_rot = rot;\n\n            for (int i = 0; i < 30; i++) {\n                for (int j = 0; j < 30; j++) {\n                    int T = grid[i][j] - '0';\n                    int best_score = -1;\n                    int best_R = 0;\n\n                    for (int R = 0; R < 4; R++) {\n                        int score = 0;\n\n                        // Check all four directions\n                        for (int d = 0; d < 4; d++) {\n                            int ni = i, nj = j;\n                            if (d == 0) nj = j - 1;\n                            else if (d == 1) ni = i - 1;\n                            else if (d == 2) nj = j + 1;\n                            else if (d == 3) ni = i + 1;\n\n                            if (ni < 0 || ni >= 30 || nj < 0 || nj >= 30) {\n                                continue;\n                            }\n\n                            int T_B = grid[ni][nj] - '0';\n                            int R_B = old_rot[ni][nj];\n                            int d_b = (d + 2) % 4;\n\n                            bool A_has_exit = global_exit[T][R][d];\n                            bool B_has_exit = global_exit[T_B][R_B][d_b];\n\n                            if (A_has_exit && B_has_exit) {\n                                score += 10;  // Strong reward for bidirectional connections\n                            } else if (A_has_exit || B_has_exit) {\n                                score += 1;   // Small reward for unidirectional connections\n                            }\n                        }\n\n                        if (score > best_score) {\n                            best_score = score;\n                            best_R = R;\n                        }\n                    }\n\n                    rot[i][j] = best_R;\n                }\n            }\n        }\n\n        string s;\n        for (int i = 0; i < 30; i++) {\n            for (int j = 0; j < 30; j++) {\n                s += char('0' + rot[i][j]);\n            }\n        }\n        cout << s << endl;\n    }\n\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <queue>\n#include <utility>\n#include <algorithm>\n\nusing namespace std;\n\nint compute_cost(vector<vector<int>> &grid, int N) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    int sum_squares = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == 0) continue;\n            if (visited[i][j]) continue;\n            int size = 0;\n            queue<pair<int, int>> q;\n            q.push({i, j});\n            visited[i][j] = true;\n            while (!q.empty()) {\n                auto [r, c] = q.front();\n                q.pop();\n                size++;\n                int dr[4] = {-1, 1, 0, 0};\n                int dc[4] = {0, 0, -1, 1};\n                int self_line[4] = {2, 8, 1, 4};\n                int neighbor_line[4] = {8, 2, 4, 1};\n                for (int d = 0; d < 4; d++) {\n                    int nr = r + dr[d];\n                    int nc = c + dc[d];\n                    if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                    if (grid[nr][nc] == 0) continue;\n                    if (visited[nr][nc]) continue;\n                    if (grid[r][c] & self_line[d] && grid[nr][nc] & neighbor_line[d]) {\n                        q.push({nr, nc});\n                        visited[nr][nc] = true;\n                    }\n                }\n            }\n            sum_squares += size * size;\n        }\n    }\n    return sum_squares;\n}\n\nvoid make_move(char D, vector<vector<int>> &grid, int &er, int &ec) {\n    int pr, pc;\n    if (D == 'U') {\n        pr = er - 1;\n        pc = ec;\n    } else if (D == 'D') {\n        pr = er + 1;\n        pc = ec;\n    } else if (D == 'L') {\n        pr = er;\n        pc = ec - 1;\n    } else if (D == 'R') {\n        pr = er;\n        pc = ec + 1;\n    } else {\n        return;\n    }\n    \n    swap(grid[er][ec], grid[pr][pc]);\n    er = pr;\n    ec = pc;\n}\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n\n    vector<vector<int>> grid(N, vector<int>(N));\n    int empty_row = 0, empty_col = 0;\n\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            char c = s[j];\n            if (c >= '0' && c <= '9') {\n                grid[i][j] = c - '0';\n            } else if (c >= 'a' && c <= 'f') {\n                grid[i][j] = 10 + (c - 'a');\n            } else {\n                grid[i][j] = 0;\n            }\n            if (grid[i][j] == 0) {\n                empty_row = i;\n                empty_col = j;\n            }\n        }\n    }\n\n    vector<vector<int>> best_grid = grid;\n    vector<vector<int>> current_grid = grid;\n    int best_er = empty_row, best_ec = empty_col;\n    int current_er = empty_row, current_ec = empty_col;\n    int best_cost = compute_cost(current_grid, N);\n    int current_cost = best_cost;\n    string best_moves = \"\";\n    string current_moves = \"\";\n    \n    double T0 = 100.0;\n    srand(time(0));\n    \n    int no_improvement_steps = 0;\n    const int MAX_NO_IMPROVEMENT = min(2000, T / 2);\n    int improvement_count = 0;\n    const int IMPROVEMENT_WINDOW = 100;\n\n    for (int t = 0; t < T; t++) {\n        int max_cost = (N * N - 1) * (N * N - 1);\n        if (best_cost == max_cost) {\n            break;\n        }\n\n        // Adaptive temperature scheduling based on recent improvements\n        double progress = static_cast<double>(t) / T;\n        double temp = T0 * (1.0 - progress);\n        \n        // Adjust temperature based on recent improvement rate\n        if (improvement_count > IMPROVEMENT_WINDOW * 0.2) {\n            temp *= 1.1; // Slightly increase temperature if we're finding improvements\n        } else if (no_improvement_steps > MAX_NO_IMPROVEMENT / 2) {\n            temp *= 0.8; // Decrease temperature if stuck\n        }\n        \n        temp = max(temp, 0.5);\n\n        vector<char> directions;\n        if (current_er > 0) directions.push_back('U');\n        if (current_er < N - 1) directions.push_back('D');\n        if (current_ec > 0) directions.push_back('L');\n        if (current_ec < N - 1) directions.push_back('R');\n\n        if (directions.empty()) break;\n\n        vector<double> weights;\n        vector<char> dirs;\n        vector<int> new_costs;\n\n        for (char D : directions) {\n            vector<vector<int>> temp_grid = current_grid;\n            int temp_er = current_er, temp_ec = current_ec;\n            make_move(D, temp_grid, temp_er, temp_ec);\n            int new_cost = compute_cost(temp_grid, N);\n            int delta = new_cost - current_cost;\n            double weight = exp(delta / temp);\n            weights.push_back(weight);\n            dirs.push_back(D);\n            new_costs.push_back(new_cost);\n        }\n\n        double total_weight = 0.0;\n        for (double w : weights) total_weight += w;\n\n        double r = static_cast<double>(rand()) / RAND_MAX * total_weight;\n        double cumulative = 0.0;\n        int index = 0;\n        for (int i = 0; i < weights.size(); i++) {\n            cumulative += weights[i];\n            if (r < cumulative) {\n                index = i;\n                break;\n            }\n        }\n\n        char chosen_D = dirs[index];\n        int chosen_new_cost = new_costs[index];\n        make_move(chosen_D, current_grid, current_er, current_ec);\n        current_cost = chosen_new_cost;\n        current_moves += chosen_D;\n\n        if (current_cost > best_cost) {\n            best_cost = current_cost;\n            best_grid = current_grid;\n            best_er = current_er;\n            best_ec = current_ec;\n            best_moves = current_moves;\n            no_improvement_steps = 0;\n            improvement_count++;\n        } else {\n            no_improvement_steps++;\n            \n            // Only restart if we're truly stuck for a long time\n            if (no_improvement_steps > MAX_NO_IMPROVEMENT) {\n                // Reset to best solution but add minimal perturbation\n                current_grid = best_grid;\n                current_er = best_er;\n                current_ec = best_ec;\n                current_cost = best_cost;\n                current_moves = best_moves;\n                \n                // Add just 1-2 random moves to escape local optimum\n                for (int i = 0; i < 2 && current_moves.length() < T; i++) {\n                    vector<char> possible_dirs;\n                    if (current_er > 0) possible_dirs.push_back('U');\n                    if (current_er < N - 1) possible_dirs.push_back('D');\n                    if (current_ec > 0) possible_dirs.push_back('L');\n                    if (current_ec < N - 1) possible_dirs.push_back('R');\n                    \n                    if (!possible_dirs.empty()) {\n                        char random_dir = possible_dirs[rand() % possible_dirs.size()];\n                        make_move(random_dir, current_grid, current_er, current_ec);\n                        current_moves += random_dir;\n                        current_cost = compute_cost(current_grid, N);\n                    }\n                }\n                \n                no_improvement_steps = 0;\n                improvement_count = max(0, improvement_count - 5);\n            }\n        }\n        \n        // Reset improvement count periodically\n        if (t % IMPROVEMENT_WINDOW == 0) {\n            improvement_count = 0;\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 <map>\n\nusing namespace std;\n\nint main() {\n    int N, K;\n    cin >> N >> K;\n    int a[10];\n    for (int i = 0; i < 10; i++) {\n        cin >> a[i];\n    }\n    vector<pair<int, int>> points;\n    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n        points.push_back({x, y});\n    }\n\n    // Calculate target piece sizes based on a_d distribution\n    vector<int> target_sizes;\n    for (int d = 1; d <= 10; d++) {\n        for (int i = 0; i < a[d-1]; i++) {\n            target_sizes.push_back(d);\n        }\n    }\n    sort(target_sizes.begin(), target_sizes.end());\n    \n    // Use density-based grid partitioning\n    // More lines in dense areas, fewer in sparse areas\n    int grid_size = 10; // Start with 10x10 grid for density analysis\n    \n    // Analyze strawberry density\n    vector<int> x_coords, y_coords;\n    for (auto& p : points) {\n        x_coords.push_back(p.first);\n        y_coords.push_back(p.second);\n    }\n    sort(x_coords.begin(), x_coords.end());\n    sort(y_coords.begin(), y_coords.end());\n    \n    // Create adaptive grid lines based on quantiles\n    int cuts_used = 0;\n    vector<pair<int, int>> vertical_cuts, horizontal_cuts;\n    \n    // Vertical cuts based on x-coordinate quantiles\n    for (int i = 1; i < grid_size && cuts_used < K; i++) {\n        int idx = (i * N) / grid_size;\n        if (idx < N) {\n            int x = x_coords[idx];\n            vertical_cuts.push_back({x, -1000000000});\n            vertical_cuts.push_back({x, 1000000000});\n            cuts_used++;\n        }\n    }\n    \n    // Horizontal cuts based on y-coordinate quantiles  \n    for (int i = 1; i < grid_size && cuts_used < K; i++) {\n        int idx = (i * N) / grid_size;\n        if (idx < N) {\n            int y = y_coords[idx];\n            horizontal_cuts.push_back({-1000000000, y});\n            horizontal_cuts.push_back({1000000000, y});\n            cuts_used++;\n        }\n    }\n    \n    // Use remaining cuts for finer partitioning in dense areas\n    int remaining_cuts = K - cuts_used;\n    if (remaining_cuts > 0) {\n        // Add more vertical cuts in areas with high strawberry density\n        int additional_vertical = min(remaining_cuts / 2, 20);\n        for (int i = 1; i <= additional_vertical && cuts_used < K; i++) {\n            int segment = N / (additional_vertical + 1);\n            int idx = i * segment;\n            if (idx < N) {\n                int x = x_coords[idx];\n                vertical_cuts.push_back({x, -1000000000});\n                vertical_cuts.push_back({x, 1000000000});\n                cuts_used++;\n            }\n        }\n        \n        // Add more horizontal cuts\n        int additional_horizontal = min(remaining_cuts - additional_vertical, 20);\n        for (int i = 1; i <= additional_horizontal && cuts_used < K; i++) {\n            int segment = N / (additional_horizontal + 1);\n            int idx = i * segment;\n            if (idx < N) {\n                int y = y_coords[idx];\n                horizontal_cuts.push_back({-1000000000, y});\n                horizontal_cuts.push_back({1000000000, y});\n                cuts_used++;\n            }\n        }\n    }\n    \n    // Output all cuts\n    cout << cuts_used << endl;\n    \n    // Output vertical cuts\n    for (int i = 0; i < vertical_cuts.size(); i += 2) {\n        cout << vertical_cuts[i].first << \" \" << vertical_cuts[i].second << \" \"\n             << vertical_cuts[i+1].first << \" \" << vertical_cuts[i+1].second << endl;\n    }\n    \n    // Output horizontal cuts\n    for (int i = 0; i < horizontal_cuts.size(); i += 2) {\n        cout << horizontal_cuts[i].first << \" \" << horizontal_cuts[i].second << \" \"\n             << horizontal_cuts[i+1].first << \" \" << horizontal_cuts[i+1].second << endl;\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x = 0, int y = 0) : x(x), y(y) {}\n    bool operator==(const Point& other) const { return x == other.x && y == other.y; }\n    bool operator<(const Point& other) const {\n        return x < other.x || (x == other.x && y < other.y);\n    }\n};\n\nstruct Segment {\n    Point a, b;\n    Segment(Point a, Point b) : a(a), b(b) {}\n    bool operator<(const Segment& other) const {\n        if (a.x != other.a.x) return a.x < other.a.x;\n        if (a.y != other.a.y) return a.y < other.a.y;\n        if (b.x != other.b.x) return b.x < other.b.x;\n        return b.y < other.b.y;\n    }\n};\n\nclass RectJoinSolver {\nprivate:\n    int N, M;\n    set<Point> dots;\n    set<Segment> used_segments;\n    vector<vector<Point>> operations;\n    Point center;\n    vector<vector<int>> weight;\n    \n    bool is_valid_point(int x, int y) {\n        return x >= 0 && x < N && y >= 0 && y < N;\n    }\n    \n    bool has_dot(const Point& p) {\n        return dots.count(p);\n    }\n    \n    vector<Point> get_points_on_segment(const Point& a, const Point& b) {\n        vector<Point> points;\n        if (a.x == b.x) {\n            int y1 = min(a.y, b.y), y2 = max(a.y, b.y);\n            for (int y = y1; y <= y2; y++) {\n                points.push_back(Point(a.x, y));\n            }\n        } else if (a.y == b.y) {\n            int x1 = min(a.x, b.x), x2 = max(a.x, b.x);\n            for (int x = x1; x <= x2; x++) {\n                points.push_back(Point(x, a.y));\n            }\n        }\n        return points;\n    }\n    \n    bool check_no_other_dots(const vector<Point>& corners, const Point& new_dot) {\n        set<Point> allowed_dots;\n        for (int i = 1; i < 4; i++) {\n            allowed_dots.insert(corners[i]);\n        }\n        \n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            auto segment_points = get_points_on_segment(a, b);\n            \n            for (const Point& p : segment_points) {\n                if (p == a || p == b) continue;\n                if (has_dot(p) && !allowed_dots.count(p)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    bool check_no_overlapping_segments(const vector<Point>& corners) {\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            auto segment_points = get_points_on_segment(a, b);\n            \n            for (int j = 0; j < (int)segment_points.size() - 1; j++) {\n                Point p1 = segment_points[j];\n                Point p2 = segment_points[j+1];\n                Segment seg(p1, p2);\n                \n                if (used_segments.count(seg)) {\n                    return false;\n                }\n            }\n        }\n        return true;\n    }\n    \n    void mark_segments_used(const vector<Point>& corners) {\n        for (int i = 0; i < 4; i++) {\n            Point a = corners[i];\n            Point b = corners[(i+1)%4];\n            auto segment_points = get_points_on_segment(a, b);\n            \n            for (int j = 0; j < (int)segment_points.size() - 1; j++) {\n                Point p1 = segment_points[j];\n                Point p2 = segment_points[j+1];\n                Segment seg(p1, p2);\n                used_segments.insert(seg);\n            }\n        }\n    }\n    \n    vector<Point> order_points_clockwise(const vector<Point>& points) {\n        if (points.size() != 4) return points;\n        \n        double cx = 0, cy = 0;\n        for (const auto& p : points) {\n            cx += p.x;\n            cy += p.y;\n        }\n        cx /= 4;\n        cy /= 4;\n        \n        vector<Point> ordered = points;\n        sort(ordered.begin(), ordered.end(), [cx, cy](const Point& a, const Point& b) {\n            return atan2(a.y - cy, a.x - cx) < atan2(b.y - cy, b.x - cx);\n        });\n        \n        return ordered;\n    }\n    \n    void precompute_weights() {\n        weight.resize(N, vector<int>(N, 0));\n        center = Point((N-1)/2, (N-1)/2);\n        for (int x = 0; x < N; x++) {\n            for (int y = 0; y < N; y++) {\n                int dx = x - center.x;\n                int dy = y - center.y;\n                weight[x][y] = dx*dx + dy*dy + 1;\n            }\n        }\n    }\n    \n    vector<vector<Point>> generate_candidates() {\n        vector<vector<Point>> candidates;\n        vector<Point> dot_list(dots.begin(), dots.end());\n        \n        // Use a more efficient approach: iterate through possible rectangle dimensions\n        for (int width = 1; width < N; width++) {\n            for (int height = 1; height < N; height++) {\n                // Try all possible top-left corners\n                for (int x = 0; x < N - width; x++) {\n                    for (int y = 0; y < N - height; y++) {\n                        Point tl(x, y);\n                        Point tr(x + width, y);\n                        Point bl(x, y + height);\n                        Point br(x + width, y + height);\n                        \n                        // Count how many corners have dots\n                        int dot_count = 0;\n                        Point missing_corner;\n                        vector<Point> existing_corners;\n                        \n                        if (has_dot(tl)) { dot_count++; existing_corners.push_back(tl); }\n                        else { missing_corner = tl; }\n                        \n                        if (has_dot(tr)) { dot_count++; existing_corners.push_back(tr); }\n                        else { missing_corner = tr; }\n                        \n                        if (has_dot(bl)) { dot_count++; existing_corners.push_back(bl); }\n                        else { missing_corner = bl; }\n                        \n                        if (has_dot(br)) { dot_count++; existing_corners.push_back(br); }\n                        else { missing_corner = br; }\n                        \n                        // We need exactly 3 dots and 1 free corner\n                        if (dot_count == 3) {\n                            vector<Point> corners = {missing_corner, existing_corners[0], \n                                                   existing_corners[1], existing_corners[2]};\n                            set<Point> corner_set(corners.begin(), corners.end());\n                            if (corner_set.size() == 4) {\n                                vector<Point> ordered = order_points_clockwise(corners);\n                                auto it = find(ordered.begin(), ordered.end(), missing_corner);\n                                if (it != ordered.end()) {\n                                    rotate(ordered.begin(), it, ordered.end());\n                                    candidates.push_back(ordered);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        return candidates;\n    }\n    \npublic:\n    RectJoinSolver(int N, int M, const vector<Point>& initial_dots) : N(N), M(M) {\n        precompute_weights();\n        center = Point((N-1)/2, (N-1)/2);\n        for (const Point& p : initial_dots) {\n            dots.insert(p);\n        }\n    }\n    \n    void solve() {\n        auto start_time = chrono::steady_clock::now();\n        \n        while (true) {\n            auto current_time = chrono::steady_clock::now();\n            auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time);\n            if (elapsed.count() > 4500) break;\n            \n            auto candidates = generate_candidates();\n            if (candidates.empty()) break;\n            \n            vector<Point> best_candidate;\n            int best_score = -1;\n            \n            for (const auto& candidate : candidates) {\n                if (candidate.size() != 4) continue;\n                \n                Point new_dot = candidate[0];\n                vector<Point> corners = candidate;\n                \n                if (check_no_other_dots(corners, new_dot) && \n                    check_no_overlapping_segments(corners)) {\n                    \n                    int score = weight[new_dot.x][new_dot.y];\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_candidate = candidate;\n                    }\n                }\n            }\n            \n            if (best_score == -1) break;\n            \n            operations.push_back(best_candidate);\n            dots.insert(best_candidate[0]);\n            mark_segments_used(best_candidate);\n        }\n    }\n    \n    void output() {\n        cout << operations.size() << endl;\n        for (const auto& op : operations) {\n            cout << op[0].x << \" \" << op[0].y << \" \"\n                 << op[1].x << \" \" << op[1].y << \" \"\n                 << op[2].x << \" \" << op[2].y << \" \"\n                 << op[3].x << \" \" << op[3].y << endl;\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    cin >> N >> M;\n    \n    vector<Point> initial_dots(M);\n    for (int i = 0; i < M; i++) {\n        cin >> initial_dots[i].x >> initial_dots[i].y;\n    }\n    \n    RectJoinSolver solver(N, M, initial_dots);\n    solver.solve();\n    solver.output();\n    \n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n#include <algorithm>\n#include <cmath>\n#include <map>\nusing namespace std;\n\nconst int N = 10;\n\nvector<vector<int>> tilt_grid(const vector<vector<int>>& state, char direction) {\n    vector<vector<int>> new_state(N+1, vector<int>(N+1, 0));\n    if (direction == 'L') {\n        for (int i = 1; i <= N; i++) {\n            vector<int> non_empty;\n            for (int j = 1; j <= N; j++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int j = 1; j <= k; j++) {\n                new_state[i][j] = non_empty[j-1];\n            }\n            for (int j = k+1; j <= N; j++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'R') {\n        for (int i = 1; i <= N; i++) {\n            vector<int> non_empty;\n            for (int j = 1; j <= N; j++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int j = 1; j <= k; j++) {\n                new_state[i][N - k + j] = non_empty[j-1];\n            }\n            for (int j = 1; j <= N-k; j++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'F') {\n        for (int j = 1; j <= N; j++) {\n            vector<int> non_empty;\n            for (int i = 1; i <= N; i++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int i = 1; i <= k; i++) {\n                new_state[i][j] = non_empty[i-1];\n            }\n            for (int i = k+1; i <= N; i++) {\n                new_state[i][j] = 0;\n            }\n        }\n    } else if (direction == 'B') {\n        for (int j = 1; j <= N; j++) {\n            vector<int> non_empty;\n            for (int i = 1; i <= N; i++) {\n                if (state[i][j] != 0) {\n                    non_empty.push_back(state[i][j]);\n                }\n            }\n            int k = non_empty.size();\n            for (int i = 1; i <= k; i++) {\n                new_state[N - k + i][j] = non_empty[i-1];\n            }\n            for (int i = 1; i <= N-k; i++) {\n                new_state[i][j] = 0;\n            }\n        }\n    }\n    return new_state;\n}\n\nint compute_score(const vector<vector<int>>& grid, vector<vector<bool>>& visited) {\n    int score = 0;\n    for (int i = 1; i <= N; i++) {\n        for (int j = 1; j <= N; j++) {\n            visited[i][j] = false;\n        }\n    }\n    for (int i = 1; i <= N; i++) {\n        for (int j = 1; j <= N; j++) {\n            if (!visited[i][j] && grid[i][j] != 0) {\n                int flavor = grid[i][j];\n                int size = 0;\n                queue<pair<int, int>> q;\n                q.push({i, j});\n                visited[i][j] = true;\n                while (!q.empty()) {\n                    pair<int, int> pos = q.front();\n                    q.pop();\n                    int x = pos.first, y = pos.second;\n                    size++;\n                    int dx[] = {1, -1, 0, 0};\n                    int dy[] = {0, 0, 1, -1};\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d], ny = y + dy[d];\n                        if (nx >= 1 && nx <= N && ny >= 1 && ny <= N && !visited[nx][ny] && grid[nx][ny] == flavor) {\n                            visited[nx][ny] = true;\n                            q.push({nx, ny});\n                        }\n                    }\n                }\n                score += size * size;\n            }\n        }\n    }\n    return score;\n}\n\nint main() {\n    int f[101];\n    int flavor_counts[4] = {0};\n    for (int i = 1; i <= 100; i++) {\n        cin >> f[i];\n        flavor_counts[f[i]]++;\n    }\n\n    // Improved region assignment: divide grid into regions proportional to flavor counts\n    // Use a more balanced approach that considers both count and spatial distribution\n    map<int, vector<pair<int, int>>> regions;\n    \n    // Calculate optimal region sizes based on flavor counts\n    vector<pair<int, int>> region_sizes;\n    int total_cells = 100;\n    int remaining_cells = total_cells;\n    \n    for (int flavor = 1; flavor <= 3; flavor++) {\n        int ideal_size = (flavor_counts[flavor] * total_cells) / 100;\n        region_sizes.push_back({flavor, ideal_size});\n    }\n    \n    // Sort by size to assign larger regions first\n    sort(region_sizes.begin(), region_sizes.end(), \n         [](const pair<int, int>& a, const pair<int, int>& b) {\n             return a.second > b.second;\n         });\n    \n    // Assign regions in a grid pattern (e.g., 3x3 subgrids)\n    int current_row = 1, current_col = 1;\n    for (auto& [flavor, size] : region_sizes) {\n        int cells_assigned = 0;\n        int rows_needed = (size + 9) / 10; // ceil division\n        int cols_needed = min(10, size);\n        \n        for (int i = current_row; i <= min(N, current_row + rows_needed - 1); i++) {\n            for (int j = current_col; j <= min(N, current_col + cols_needed - 1); j++) {\n                if (cells_assigned < size) {\n                    regions[flavor].push_back({i, j});\n                    cells_assigned++;\n                }\n            }\n        }\n        \n        current_col += cols_needed;\n        if (current_col > N) {\n            current_col = 1;\n            current_row += rows_needed;\n        }\n    }\n\n    vector<vector<int>> grid(N+1, vector<int>(N+1, 0));\n    vector<vector<bool>> visited(N+1, vector<bool>(N+1, false));\n    vector<char> directions_tilt = {'F', 'B', 'L', 'R'};\n\n    for (int t = 1; t <= 100; t++) {\n        int p;\n        cin >> p;\n\n        int count = 0;\n        int i_place = 0, j_place = 0;\n        for (int i = 1; i <= N; i++) {\n            for (int j = 1; j <= N; j++) {\n                if (grid[i][j] == 0) {\n                    count++;\n                    if (count == p) {\n                        i_place = i;\n                        j_place = j;\n                        break;\n                    }\n                }\n            }\n            if (j_place != 0) break;\n        }\n\n        grid[i_place][j_place] = f[t];\n\n        if (t == 100) {\n            int best_score = -1;\n            char best_dir = 'F';\n            for (char dir : directions_tilt) {\n                vector<vector<int>> new_grid = tilt_grid(grid, dir);\n                int score = compute_score(new_grid, visited);\n                if (score > best_score) {\n                    best_score = score;\n                    best_dir = dir;\n                }\n            }\n            cout << best_dir << endl;\n            cout.flush();\n            grid = tilt_grid(grid, best_dir);\n            continue;\n        }\n\n        // Enhanced lookahead with improved strategic positioning\n        double best_avg_score = -1e9;\n        char best_dir = 'F';\n        \n        for (char dir : directions_tilt) {\n            vector<vector<int>> grid_after_tilt = tilt_grid(grid, dir);\n            \n            double total_score = 0.0;\n            int empty_count = 0;\n            \n            for (int i = 1; i <= N; i++) {\n                for (int j = 1; j <= N; j++) {\n                    if (grid_after_tilt[i][j] == 0) {\n                        empty_count++;\n                        vector<vector<int>> grid_with_next = grid_after_tilt;\n                        grid_with_next[i][j] = f[t+1];\n                        \n                        // Improved strategic bonus: use Manhattan distance and consider connectivity\n                        double strategic_bonus = 0.0;\n                        for (auto& target : regions[f[t+1]]) {\n                            // Use Manhattan distance for better alignment with grid movement\n                            double distance = abs(i - target.first) + abs(j - target.second);\n                            strategic_bonus += 1.0 / (1.0 + distance);\n                        }\n                        \n                        // Additional bonus for placements adjacent to same flavor\n                        int same_neighbor_bonus = 0;\n                        int dx[] = {1, -1, 0, 0};\n                        int dy[] = {0, 0, 1, -1};\n                        for (int d = 0; d < 4; d++) {\n                            int ni = i + dx[d], nj = j + dy[d];\n                            if (ni >= 1 && ni <= N && nj >= 1 && nj <= N && \n                                grid_after_tilt[ni][nj] == f[t+1]) {\n                                same_neighbor_bonus++;\n                            }\n                        }\n                        strategic_bonus += same_neighbor_bonus * 0.5;\n                        \n                        int best_next_score = -1;\n                        for (char dir2 : directions_tilt) {\n                            vector<vector<int>> grid_after_tilt2 = tilt_grid(grid_with_next, dir2);\n                            int score = compute_score(grid_after_tilt2, visited);\n                            if (score > best_next_score) {\n                                best_next_score = score;\n                            }\n                        }\n                        \n                        // Adaptive weighting: more aggressive early, more conservative late\n                        double weight = 15.0 * (1.0 - t/100.0) + 5.0;\n                        total_score += best_next_score + strategic_bonus * weight;\n                    }\n                }\n            }\n            \n            if (empty_count > 0) {\n                double avg_score = total_score / empty_count;\n                if (avg_score > best_avg_score) {\n                    best_avg_score = avg_score;\n                    best_dir = dir;\n                }\n            }\n        }\n\n        cout << best_dir << endl;\n        cout.flush();\n        grid = tilt_grid(grid, best_dir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <cstdlib>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\nusing namespace std;\n\nint main() {\n    int M;\n    double eps;\n    cin >> M >> eps;\n\n    double requiredN = sqrt(2.0 * M) + 10.0 * eps;\n    int N = min(100, max(4, (int)ceil(requiredN)));\n    int T = N * (N - 1) / 2;\n\n    vector<int> offset(N);\n    offset[0] = 0;\n    for (int i = 1; i < N; i++) {\n        offset[i] = offset[i-1] + (N - i);\n    }\n\n    cout << N << endl;\n\n    int D = min(M, T + 1);\n    vector<int> m_values(D);\n    if (D > 1) {\n        for (int i = 0; i < D; i++) {\n            m_values[i] = round((i * T) / (D - 1.0));\n        }\n    } else {\n        m_values[0] = 0;\n    }\n\n    vector<int> m_list(M);\n    int quotient = M / D;\n    int remainder = M % D;\n    int index = 0;\n    for (int j = 0; j < D; j++) {\n        int count = quotient + (j < remainder ? 1 : 0);\n        for (int c = 0; c < count; c++) {\n            m_list[index++] = m_values[j];\n        }\n    }\n\n    vector<vector<double>> eigenvals(M);\n    for (int k = 0; k < M; k++) {\n        int m_k = m_list[k];\n        vector<bool> edge_flag(T, false);\n        vector<int> indices(T);\n        for (int i = 0; i < T; i++) {\n            indices[i] = i;\n        }\n        for (int i = T - 1; i > 0; i--) {\n            int j = rand() % (i + 1);\n            swap(indices[i], indices[j]);\n        }\n        for (int i = 0; i < m_k; i++) {\n            edge_flag[indices[i]] = true;\n        }\n\n        Eigen::MatrixXd A = Eigen::MatrixXd::Zero(N, N);\n        for (int pos = 0; pos < T; pos++) {\n            if (edge_flag[pos]) {\n                int i = 0;\n                while (i < N - 1 && pos >= offset[i + 1]) {\n                    i++;\n                }\n                int j = i + 1 + (pos - offset[i]);\n                A(i, j) = 1;\n                A(j, i) = 1;\n            }\n        }\n\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(A);\n        Eigen::VectorXd evals = solver.eigenvalues();\n        vector<double> eval_vec(evals.data(), evals.data() + evals.size());\n        sort(eval_vec.begin(), eval_vec.end());\n        eigenvals[k] = eval_vec;\n\n        string g_str;\n        for (int pos = 0; pos < T; pos++) {\n            g_str += edge_flag[pos] ? '1' : '0';\n        }\n        cout << g_str << endl;\n    }\n\n    for (int q = 0; q < 100; q++) {\n        string H_str;\n        cin >> H_str;\n\n        Eigen::MatrixXd H_mat = Eigen::MatrixXd::Zero(N, N);\n        for (int pos = 0; pos < T; pos++) {\n            if (H_str[pos] == '1') {\n                int i = 0;\n                while (i < N - 1 && pos >= offset[i + 1]) {\n                    i++;\n                }\n                int j = i + 1 + (pos - offset[i]);\n                H_mat(i, j) = 1;\n                H_mat(j, i) = 1;\n            }\n        }\n\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver_H(H_mat);\n        Eigen::VectorXd evals_H = solver_H.eigenvalues();\n        vector<double> eval_vec_H(evals_H.data(), evals_H.data() + evals_H.size());\n        sort(eval_vec_H.begin(), eval_vec_H.end());\n\n        int best_k = 0;\n        double min_dist = 1e9;\n        for (int k = 0; k < M; k++) {\n            double dist = 0.0;\n            for (int i = 0; i < N; i++) {\n                double diff = eval_vec_H[i] - eigenvals[k][i];\n                dist += diff * diff;\n            }\n            dist = sqrt(dist);\n            if (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 <algorithm>\n#include <queue>\n#include <limits>\n#include <tuple>\n#include <cmath>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nconst int INF = 1000000000;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    vector<tuple<int, int, int>> edges;\n    for (int i = 0; i < M; i++) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges.push_back({u, v, w});\n    }\n\n    vector<pair<int, int>> points(N + 1);\n    for (int i = 1; i <= N; i++) {\n        cin >> points[i].first >> points[i].second;\n    }\n\n    // Build graph\n    vector<vector<pair<int, int>>> graph(N + 1);\n    vector<map<int, int>> edge_map(N + 1);\n    for (int i = 0; i < M; i++) {\n        int u = get<0>(edges[i]);\n        int v = get<1>(edges[i]);\n        int w = get<2>(edges[i]);\n        graph[u].emplace_back(v, w);\n        graph[v].emplace_back(u, w);\n        edge_map[u][v] = i;\n        edge_map[v][u] = i;\n    }\n\n    // Calculate edge betweenness centrality\n    vector<double> betweenness(M, 0.0);\n    \n    for (int s = 1; s <= N; s++) {\n        // Dijkstra from source s\n        vector<int> dist(N + 1, INF);\n        vector<int> sigma(N + 1, 0);\n        vector<vector<int>> pred(N + 1);\n        dist[s] = 0;\n        sigma[s] = 1;\n        \n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;\n        pq.push({0, s});\n        \n        vector<int> order;\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            \n            order.push_back(u);\n            for (auto [v, w] : graph[u]) {\n                if (dist[v] > dist[u] + w) {\n                    dist[v] = dist[u] + w;\n                    sigma[v] = sigma[u];\n                    pred[v].clear();\n                    pred[v].push_back(u);\n                    pq.push({dist[v], v});\n                } else if (dist[v] == dist[u] + w) {\n                    sigma[v] += sigma[u];\n                    pred[v].push_back(u);\n                }\n            }\n        }\n        \n        // Backward pass to accumulate betweenness\n        vector<double> delta(N + 1, 0.0);\n        reverse(order.begin(), order.end());\n        \n        for (int u : order) {\n            for (int v : pred[u]) {\n                double coeff = (1.0 + delta[u]) * sigma[v] / sigma[u];\n                delta[v] += coeff;\n                \n                // Find edge between u and v\n                int edge_idx = edge_map[u][v];\n                betweenness[edge_idx] += coeff;\n            }\n        }\n    }\n\n    // Sort edges by betweenness\n    vector<int> edge_order(M);\n    for (int i = 0; i < M; i++) {\n        edge_order[i] = i;\n    }\n    sort(edge_order.begin(), edge_order.end(), [&](int a, int b) {\n        return betweenness[a] > betweenness[b];\n    });\n\n    // Group edges by their endpoints to avoid removing adjacent edges on the same day\n    vector<set<int>> vertex_days(N + 1);\n    vector<int> assignment(M, 0);\n    vector<int> day_count(D + 1, 0);\n    \n    // Assign edges strategically\n    for (int i = 0; i < M; i++) {\n        int edge_idx = edge_order[i];\n        int u = get<0>(edges[edge_idx]);\n        int v = get<1>(edges[edge_idx]);\n        \n        // Find the best day that minimizes conflicts with adjacent edges\n        vector<int> day_scores(D + 1, 0);\n        for (int d = 1; d <= D; d++) {\n            if (day_count[d] >= K) {\n                day_scores[d] = INF;\n                continue;\n            }\n            \n            // Penalize days that already have edges adjacent to u or v\n            if (vertex_days[u].count(d)) day_scores[d] += 10;\n            if (vertex_days[v].count(d)) day_scores[d] += 10;\n            \n            // Prefer days with fewer assignments\n            day_scores[d] += day_count[d];\n        }\n        \n        // Find the best day\n        int best_day = 1;\n        for (int d = 2; d <= D; d++) {\n            if (day_scores[d] < day_scores[best_day]) {\n                best_day = d;\n            }\n        }\n        \n        assignment[edge_idx] = best_day;\n        day_count[best_day]++;\n        vertex_days[u].insert(best_day);\n        vertex_days[v].insert(best_day);\n    }\n\n    // Output the assignment\n    for (int i = 0; i < M; i++) {\n        cout << assignment[i];\n        if (i < M - 1) cout << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <queue>\n#include <algorithm>\n#include <tuple>\n\nusing namespace std;\n\nint main() {\n    int D;\n    cin >> D;\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 required positions for each silhouette\n    set<tuple<int, int, int>> M1, M2;\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 (f1[z][x] == '1' && r1[z][y] == '1') {\n                    M1.insert({x, y, z});\n                }\n                if (f2[z][x] == '1' && r2[z][y] == '1') {\n                    M2.insert({x, y, z});\n                }\n            }\n        }\n    }\n\n    // Find intersection of required positions\n    set<tuple<int, int, int>> I;\n    set_intersection(M1.begin(), M1.end(), M2.begin(), M2.end(),\n                    inserter(I, I.begin()));\n\n    // 6-directional neighbors\n    vector<tuple<int, int, int>> directions = {\n        {1, 0, 0}, {-1, 0, 0},\n        {0, 1, 0}, {0, -1, 0},\n        {0, 0, 1}, {0, 0, -1}\n    };\n\n    // Find connected components in intersection\n    map<tuple<int, int, int>, int> comp_id;\n    int comp_count = 0;\n    \n    for (const auto& coord : I) {\n        if (comp_id.count(coord)) continue;\n        \n        comp_count++;\n        queue<tuple<int, int, int>> q;\n        q.push(coord);\n        comp_id[coord] = comp_count;\n        \n        while (!q.empty()) {\n            auto [x, y, z] = q.front();\n            q.pop();\n            \n            for (auto [dx, dy, dz] : directions) {\n                int nx = x + dx, ny = y + dy, nz = z + dz;\n                tuple<int, int, int> neighbor = {nx, ny, nz};\n                \n                if (I.count(neighbor) && !comp_id.count(neighbor)) {\n                    comp_id[neighbor] = comp_count;\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n\n    // Calculate total blocks\n    int n = comp_count + (M1.size() - I.size()) + (M2.size() - I.size());\n    \n    // Create output arrays\n    vector<int> arr1(D * D * D, 0), arr2(D * D * D, 0);\n    \n    // Assign blocks for first arrangement\n    int id_counter = comp_count + 1;\n    map<tuple<int, int, int>, int> id_map1;\n    \n    for (const auto& coord : M1) {\n        auto [x, y, z] = coord;\n        int idx = x * D * D + y * D + z;\n        \n        if (I.count(coord)) {\n            arr1[idx] = comp_id[coord];\n        } else {\n            if (!id_map1.count(coord)) {\n                id_map1[coord] = id_counter++;\n            }\n            arr1[idx] = id_map1[coord];\n        }\n    }\n    \n    // Assign blocks for second arrangement\n    map<tuple<int, int, int>, int> id_map2;\n    \n    for (const auto& coord : M2) {\n        auto [x, y, z] = coord;\n        int idx = x * D * D + y * D + z;\n        \n        if (I.count(coord)) {\n            arr2[idx] = comp_id[coord];\n        } else {\n            if (!id_map2.count(coord)) {\n                id_map2[coord] = id_counter++;\n            }\n            arr2[idx] = id_map2[coord];\n        }\n    }\n    \n    // Output results\n    cout << n << endl;\n    \n    for (int i = 0; i < D * D * D; i++) {\n        cout << arr1[i] << (i == D * D * D - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    for (int i = 0; i < D * D * D; i++) {\n        cout << arr2[i] << (i == D * D * D - 1 ? \"\" : \" \");\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read input\n    int N, M, K;\n    cin >> N >> M >> K;\n    \n    vector<ll> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<tuple<int, int, ll>> edges(M);\n    map<pair<int, int>, int> edge_index_map;\n    for (int i = 0; i < M; i++) {\n        int u, v;\n        ll w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edges[i] = {u, v, w};\n        if (u > v) swap(u, v);\n        edge_index_map[{u, v}] = i;\n    }\n    \n    vector<ll> a(K), b(K);\n    for (int i = 0; i < K; i++) {\n        cin >> a[i] >> b[i];\n    }\n    \n    // Precompute squared distances from stations to residents\n    vector<vector<ll>> dist_sq(N, vector<ll>(K));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < K; j++) {\n            ll dx = x[i] - a[j];\n            ll dy = y[i] - b[j];\n            dist_sq[i][j] = dx * dx + dy * dy;\n        }\n    }\n    \n    // Precompute shortest paths between stations using Floyd-Warshall\n    vector<vector<ll>> dist_station(N, vector<ll>(N, 1e18));\n    vector<vector<int>> next_hop(N, vector<int>(N, -1));\n    for (int i = 0; i < N; i++) {\n        dist_station[i][i] = 0;\n        next_hop[i][i] = i;\n    }\n    for (int i = 0; i < M; i++) {\n        auto [u, v, w] = edges[i];\n        if (w < dist_station[u][v]) {\n            dist_station[u][v] = w;\n            dist_station[v][u] = w;\n            next_hop[u][v] = v;\n            next_hop[v][u] = u;\n        }\n    }\n    for (int k = 0; k < N; k++) {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (dist_station[i][k] < 1e18 && dist_station[k][j] < 1e18) {\n                    if (dist_station[i][j] > dist_station[i][k] + dist_station[k][j]) {\n                        dist_station[i][j] = dist_station[i][k] + dist_station[k][j];\n                        next_hop[i][j] = next_hop[i][k];\n                    }\n                }\n            }\n        }\n    }\n    \n    // Initial assignment: assign each resident to the nearest station\n    vector<int> assignment(K);\n    vector<multiset<ll>> station_residents(N);\n    for (int j = 0; j < K; j++) {\n        int best_station = 0;\n        ll min_d_sq = dist_sq[0][j];\n        for (int i = 1; i < N; i++) {\n            if (dist_sq[i][j] < min_d_sq) {\n                min_d_sq = dist_sq[i][j];\n                best_station = i;\n            }\n        }\n        assignment[j] = best_station;\n        station_residents[best_station].insert(dist_sq[best_station][j]);\n    }\n    \n    // Function to compute P_i from a multiset of squared distances\n    auto compute_P = [](const multiset<ll>& residents) -> ll {\n        if (residents.empty()) return 0;\n        ll max_d_sq = *residents.rbegin();\n        ll P = sqrt(max_d_sq);\n        if (P * P < max_d_sq) P++;\n        return min(P, 5000LL);\n    };\n    \n    // Function to build MST on a set of stations\n    auto build_mst = [&](const set<int>& S) -> tuple<ll, set<pair<int, int>>> {\n        if (S.empty()) return {0, {}};\n        // Create a list of stations in S\n        vector<int> stations(S.begin(), S.end());\n        int n_s = stations.size();\n        // Map station index to index in the list\n        map<int, int> station_index;\n        for (int i = 0; i < n_s; i++) {\n            station_index[stations[i]] = i;\n        }\n        // Build complete graph on stations\n        vector<vector<ll>> dist_s(n_s, vector<ll>(n_s, 1e18));\n        for (int i = 0; i < n_s; i++) {\n            for (int j = i+1; j < n_s; j++) {\n                int u = stations[i], v = stations[j];\n                dist_s[i][j] = dist_station[u][v];\n                dist_s[j][i] = dist_station[u][v];\n            }\n        }\n        // Prim's algorithm\n        vector<ll> key(n_s, 1e18);\n        vector<int> parent(n_s, -1);\n        vector<bool> in_mst(n_s, false);\n        key[0] = 0;\n        priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n        pq.push({0, 0});\n        while (!pq.empty()) {\n            int u = pq.top().second;\n            pq.pop();\n            if (in_mst[u]) continue;\n            in_mst[u] = true;\n            for (int v = 0; v < n_s; v++) {\n                if (!in_mst[v] && dist_s[u][v] < key[v]) {\n                    key[v] = dist_s[u][v];\n                    parent[v] = u;\n                    pq.push({key[v], v});\n                }\n            }\n        }\n        // Collect MST edges\n        set<pair<int, int>> mst_edges;\n        ll total_cost = 0;\n        for (int i = 1; i < n_s; i++) {\n            int u = stations[i], v = stations[parent[i]];\n            if (u > v) swap(u, v);\n            mst_edges.insert({u, v});\n            total_cost += dist_station[u][v];\n        }\n        return {total_cost, mst_edges};\n    };\n    \n    // Function to get the path between two stations and mark edges\n    auto mark_path_edges = [&](int u, int v, vector<bool>& edge_on) {\n        if (u == v) return;\n        int current = u;\n        while (current != v) {\n            int next = next_hop[current][v];\n            int u1 = current, v1 = next;\n            if (u1 > v1) swap(u1, v1);\n            auto it = edge_index_map.find({u1, v1});\n            if (it != edge_index_map.end()) {\n                edge_on[it->second] = true;\n            }\n            current = next;\n        }\n    };\n    \n    // Initial set S: stations with at least one resident\n    set<int> S;\n    for (int i = 0; i < N; i++) {\n        if (!station_residents[i].empty()) {\n            S.insert(i);\n        }\n    }\n    \n    // Build initial MST\n    auto [current_edge_cost, mst_edges] = build_mst(S);\n    \n    // Compute initial power cost\n    ll current_power_cost = 0;\n    vector<ll> P(N, 0);\n    for (int i = 0; i < N; i++) {\n        P[i] = compute_P(station_residents[i]);\n        current_power_cost += P[i] * P[i];\n    }\n    ll current_total_cost = current_power_cost + current_edge_cost;\n    \n    // Local search improvement\n    bool improved = true;\n    int max_iter = 10;\n    for (int iter = 0; iter < max_iter && improved; iter++) {\n        improved = false;\n        // Create a list of residents in random order\n        vector<int> residents(K);\n        iota(residents.begin(), residents.end(), 0);\n        random_shuffle(residents.begin(), residents.end());\n        \n        for (int j : residents) {\n            int old_station = assignment[j];\n            ll old_d_sq = dist_sq[old_station][j];\n            // Remove j from old_station\n            station_residents[old_station].erase(station_residents[old_station].find(old_d_sq));\n            ll old_P_old = P[old_station];\n            P[old_station] = compute_P(station_residents[old_station]);\n            ll power_cost_without_j = current_power_cost - old_P_old * old_P_old + P[old_station] * P[old_station];\n            \n            // Try reassigning to other stations in S\n            for (int new_station : S) {\n                if (new_station == old_station) continue;\n                ll new_d_sq = dist_sq[new_station][j];\n                ll old_P_new = P[new_station];\n                station_residents[new_station].insert(new_d_sq);\n                P[new_station] = compute_P(station_residents[new_station]);\n                ll new_power_cost = power_cost_without_j - old_P_new * old_P_new + P[new_station] * P[new_station];\n                \n                // Check if power cost improves\n                if (new_power_cost < current_power_cost) {\n                    // Accept reassignment\n                    assignment[j] = new_station;\n                    current_power_cost = new_power_cost;\n                    improved = true;\n                    // Update S if old_station becomes empty\n                    if (station_residents[old_station].empty()) {\n                        S.erase(old_station);\n                    }\n                    // new_station is already in S\n                    break;\n                } else {\n                    // Revert changes to new_station\n                    station_residents[new_station].erase(station_residents[new_station].find(new_d_sq));\n                    P[new_station] = old_P_new;\n                }\n            }\n            // If not reassigned, revert old_station\n            if (assignment[j] == old_station) {\n                station_residents[old_station].insert(old_d_sq);\n                P[old_station] = old_P_old;\n            }\n        }\n        \n        // After reassignment, update S and rebuild MST\n        S.clear();\n        for (int i = 0; i < N; i++) {\n            if (!station_residents[i].empty()) {\n                S.insert(i);\n            }\n        }\n        tie(current_edge_cost, mst_edges) = build_mst(S);\n        current_total_cost = current_power_cost + current_edge_cost;\n    }\n    \n    // Final output preparation\n    // Compute final P values\n    for (int i = 0; i < N; i++) {\n        P[i] = compute_P(station_residents[i]);\n    }\n    \n    // Mark edges for MST\n    vector<bool> edge_on(M, false);\n    for (auto [u, v] : mst_edges) {\n        mark_path_edges(u, v, edge_on);\n    }\n    \n    // Output P and B\n    for (int i = 0; i < N; i++) {\n        cout << P[i];\n        if (i < N-1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    for (int i = 0; i < M; i++) {\n        cout << (edge_on[i] ? 1 : 0);\n        if (i < M-1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <tuple>\nusing namespace std;\n\nconst int N = 30;\n\nbool violates(const vector<vector<int>>& pyramid, int x, int y) {\n    if (x >= N - 1) return false;\n    int current_val = pyramid[x][y];\n    int child1_val = pyramid[x+1][y];\n    int child2_val = pyramid[x+1][y+1];\n    return (current_val > child1_val) || (current_val > child2_val);\n}\n\nint main() {\n    vector<vector<int>> pyramid(N);\n    for (int x = 0; x < N; x++) {\n        for (int y = 0; y <= x; y++) {\n            int num;\n            cin >> num;\n            pyramid[x].push_back(num);\n        }\n    }\n\n    vector<tuple<int, int, int, int>> swaps;\n\n    while (true) {\n        int max_val = -1;\n        int max_x = -1;\n        int max_y = -1;\n        bool found_violation = false;\n\n        for (int x = 0; x < N - 1; x++) {\n            for (int y = 0; y <= x; y++) {\n                if (violates(pyramid, x, y)) {\n                    int val = pyramid[x][y];\n                    if (val > max_val) {\n                        max_val = val;\n                        max_x = x;\n                        max_y = y;\n                        found_violation = true;\n                    }\n                }\n            }\n        }\n\n        if (!found_violation) {\n            break;\n        }\n\n        int x = max_x;\n        int y = max_y;\n        int child1_x = x + 1;\n        int child1_y = y;\n        int child2_x = x + 1;\n        int child2_y = y + 1;\n\n        int child1_val = pyramid[child1_x][child1_y];\n        int child2_val = pyramid[child2_x][child2_y];\n\n        int swap_x, swap_y;\n        if (child1_val <= child2_val) {\n            swap_x = child1_x;\n            swap_y = child1_y;\n        } else {\n            swap_x = child2_x;\n            swap_y = child2_y;\n        }\n\n        swap(pyramid[x][y], pyramid[swap_x][swap_y]);\n        swaps.push_back({x, y, swap_x, swap_y});\n    }\n\n    cout << swaps.size() << endl;\n    for (const auto& op : swaps) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << endl;\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = 4;\n\nvector<vector<int>> grid;\nvector<pair<int, int>> container_positions;\n\n// Directions: up, down, left, right\nconst int di[] = {-1, 1, 0, 0};\nconst int dj[] = {0, 0, -1, 1};\n\n// Check if a position is valid and empty\nbool is_valid(int i, int j) {\n    return i >= 0 && i < D && j >= 0 && j < D && grid[i][j] == -1;\n}\n\n// BFS to find reachable positions from entrance\nvector<pair<int, int>> get_reachable_positions() {\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> reachable;\n    \n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            \n            if (ni >= 0 && ni < D && nj >= 0 && nj < D && \n                !visited[ni][nj] && grid[ni][nj] == -1) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                reachable.push_back({ni, nj});\n            }\n        }\n    }\n    \n    return reachable;\n}\n\n// Calculate Manhattan distance from entrance\nint distance_from_entrance(int i, int j) {\n    return abs(i - ENTRANCE_I) + abs(j - ENTRANCE_J);\n}\n\n// Find best position for placement based on container number\npair<int, int> find_best_position(int container_num, int total_containers) {\n    auto reachable = get_reachable_positions();\n    \n    if (reachable.empty()) {\n        // Should not happen if grid is properly connected\n        for (int i = 0; i < D; i++) {\n            for (int j = 0; j < D; j++) {\n                if (grid[i][j] == -1) {\n                    return {i, j};\n                }\n            }\n        }\n    }\n    \n    // Sort positions by distance from entrance\n    sort(reachable.begin(), reachable.end(), [](const pair<int, int>& a, const pair<int, int>& b) {\n        int dist_a = distance_from_entrance(a.first, a.second);\n        int dist_b = distance_from_entrance(b.first, b.second);\n        return dist_a < dist_b;\n    });\n    \n    // Use container number to determine placement strategy\n    // Lower numbers should be placed closer to exit for easier retrieval\n    int idx = (container_num * reachable.size()) / total_containers;\n    idx = min(idx, (int)reachable.size() - 1);\n    \n    return reachable[idx];\n}\n\n// Get accessible containers for retrieval\nvector<pair<int, int>> get_accessible_containers() {\n    vector<vector<bool>> visited(D, vector<bool>(D, false));\n    queue<pair<int, int>> q;\n    vector<pair<int, int>> accessible;\n    \n    q.push({ENTRANCE_I, ENTRANCE_J});\n    visited[ENTRANCE_I][ENTRANCE_J] = true;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        // Check if current position has a container\n        if (grid[i][j] >= 0) {\n            accessible.push_back({i, j});\n        }\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            \n            if (ni >= 0 && ni < D && nj >= 0 && nj < D && \n                !visited[ni][nj] && grid[ni][nj] != -2) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    return accessible;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Read warehouse configuration\n    int N;\n    cin >> D >> N;\n    \n    // Initialize grid: -2 = obstacle, -1 = empty, >=0 = container number\n    grid.assign(D, vector<int>(D, -1));\n    container_positions.clear();\n    \n    // Mark entrance and adjacent squares\n    grid[ENTRANCE_I][ENTRANCE_J] = -3; // Entrance\n    grid[ENTRANCE_I][ENTRANCE_J-1] = -1;\n    grid[ENTRANCE_I][ENTRANCE_J+1] = -1;\n    grid[ENTRANCE_I+1][ENTRANCE_J] = -1;\n    \n    // Read obstacles\n    for (int k = 0; k < N; k++) {\n        int ri, rj;\n        cin >> ri >> rj;\n        grid[ri][rj] = -2; // Obstacle\n    }\n    \n    int total_containers = D * D - 1 - N;\n    \n    // Process container arrivals\n    for (int d = 0; d < total_containers; d++) {\n        int container_num;\n        cin >> container_num;\n        \n        // Find best position for this container\n        auto [pi, pj] = find_best_position(container_num, total_containers);\n        \n        // Place container\n        grid[pi][pj] = container_num;\n        container_positions.push_back({pi, pj});\n        \n        // Output placement\n        cout << pi << \" \" << pj << endl;\n        cout.flush();\n    }\n    \n    // Determine retrieval order using greedy strategy\n    vector<pair<int, int>> retrieval_order;\n    \n    while (retrieval_order.size() < total_containers) {\n        auto accessible = get_accessible_containers();\n        \n        if (accessible.empty()) {\n            break; // Should not happen\n        }\n        \n        // Find container with smallest number\n        int best_idx = 0;\n        int best_num = grid[accessible[0].first][accessible[0].second];\n        \n        for (int i = 1; i < accessible.size(); i++) {\n            int current_num = grid[accessible[i].first][accessible[i].second];\n            if (current_num < best_num) {\n                best_num = current_num;\n                best_idx = i;\n            }\n        }\n        \n        auto [qi, qj] = accessible[best_idx];\n        retrieval_order.push_back({qi, qj});\n        grid[qi][qj] = -1; // Remove container\n    }\n    \n    // Output retrieval order\n    for (auto [qi, qj] : retrieval_order) {\n        cout << qi << \" \" << qj << endl;\n    }\n    cout.flush();\n    \n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> grid(n, vector<int>(n));\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> grid[i][j];\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cout << grid[i][j];\n            if (j < n - 1) cout << \" \";\n        }\n        cout << endl;\n    }\n    \n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n\nusing namespace std;\n\nint main() {\n    int N, D, Q;\n    cin >> N >> D >> Q;\n\n    vector<double> ratings(N, 1000.0);\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n\n    int p = 0;\n\n    for (int q = 0; q < Q; q++) {\n        sort(indices.begin(), indices.end(), [&ratings](int a, int b) {\n            return ratings[a] > ratings[b];\n        });\n\n        int i = indices[p];\n        int j = indices[p + 1];\n\n        cout << \"1 1 \" << i << \" \" << j << endl;\n        cout.flush();\n\n        string result;\n        cin >> result;\n\n        double outcome_i, outcome_j;\n        if (result == \">\") {\n            outcome_i = 1.0;\n            outcome_j = 0.0;\n        } else if (result == \"<\") {\n            outcome_i = 0.0;\n            outcome_j = 1.0;\n        } else {\n            outcome_i = 0.5;\n            outcome_j = 0.5;\n        }\n\n        const double K = 32.0;\n        double diff = ratings[j] - ratings[i];\n        double expected_i = 1.0 / (1.0 + pow(10.0, diff / 400.0));\n        double expected_j = 1.0 - expected_i;\n\n        ratings[i] += K * (outcome_i - expected_i);\n        ratings[j] += K * (outcome_j - expected_j);\n\n        p++;\n        if (p >= N - 1) {\n            p = 0;\n        }\n    }\n\n    vector<int> sorted_indices(N);\n    iota(sorted_indices.begin(), sorted_indices.end(), 0);\n    sort(sorted_indices.begin(), sorted_indices.end(), [&ratings](int a, int b) {\n        return ratings[a] > ratings[b];\n    });\n\n    vector<double> bin_sums(D, 0.0);\n    vector<int> assignment(N);\n    for (int idx : sorted_indices) {\n        int min_bin = 0;\n        for (int b = 1; b < D; b++) {\n            if (bin_sums[b] < bin_sums[min_bin]) {\n                min_bin = b;\n            }\n        }\n        assignment[idx] = min_bin;\n        bin_sums[min_bin] += ratings[idx];\n    }\n\n    for (int i = 0; i < N; i++) {\n        cout << assignment[i];\n        if (i < N - 1) {\n            cout << \" \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <queue>\n#include <functional>\n#include <set>\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    \n    vector<vector<int>> stacks(m + 1);\n    vector<int> box_pos(n + 1, -1);\n    vector<int> box_height(n + 1, -1);\n    \n    // Read initial configuration\n    for (int i = 1; i <= m; i++) {\n        for (int j = 0; j < n / m; j++) {\n            int box;\n            cin >> box;\n            stacks[i].push_back(box);\n            box_pos[box] = i;\n            box_height[box] = j + 1;\n        }\n    }\n    \n    vector<pair<int, int>> operations;\n    int next_box = 1;\n    vector<bool> carried_out(n + 1, false);\n    \n    int boxes_per_stack = n / m;\n    \n    // Function to check if a box is at top\n    auto is_top = [&](int box) {\n        int stack_idx = box_pos[box];\n        return !stacks[stack_idx].empty() && stacks[stack_idx].back() == box;\n    };\n    \n    // Function to find boxes above a given box\n    auto get_boxes_above = [&](int box) -> vector<int> {\n        int stack_idx = box_pos[box];\n        auto it = find(stacks[stack_idx].begin(), stacks[stack_idx].end(), box);\n        if (it == stacks[stack_idx].end()) return {};\n        return vector<int>(it + 1, stacks[stack_idx].end());\n    };\n    \n    // Function to find an empty stack\n    auto find_empty_stack = [&]() {\n        for (int i = 1; i <= m; i++) {\n            if (stacks[i].empty()) return i;\n        }\n        return -1;\n    };\n    \n    // Conservative function to find the best temporary stack\n    auto find_temporary_stack = [&](int avoid_stack, const vector<int>& boxes_above) {\n        int best_stack = -1;\n        int best_score = -1000000;\n        \n        int segment_min = *min_element(boxes_above.begin(), boxes_above.end());\n        int segment_max = *max_element(boxes_above.begin(), boxes_above.end());\n        \n        for (int i = 1; i <= m; i++) {\n            if (i == avoid_stack) continue;\n            \n            int score = 0;\n            \n            // Strong preference for empty stacks\n            if (stacks[i].empty()) {\n                score += 1000;\n            } else {\n                int top_box = stacks[i].back();\n                \n                // Prefer stacks where top box is larger than segment\n                if (top_box > segment_max + 10) {\n                    score += 400;\n                } else if (top_box > segment_max) {\n                    score += 200;\n                }\n                \n                // Penalize stacks that contain boxes we'll need soon\n                for (int box_in_stack : stacks[i]) {\n                    if (box_in_stack >= next_box && box_in_stack <= next_box + 15) {\n                        score -= 300;\n                    }\n                    // Strong penalty for blocking boxes smaller than segment\n                    if (box_in_stack < segment_min && !carried_out[box_in_stack]) {\n                        score -= 600;\n                    }\n                }\n                \n                // Bonus if this stack's boxes are mostly larger than what we're moving\n                int larger_count = 0;\n                for (int box_in_stack : stacks[i]) {\n                    if (box_in_stack > segment_max) larger_count++;\n                }\n                score += larger_count * 10;\n            }\n            \n            // Small bonus for stack diversity\n            score += (i % 3);\n            \n            if (score > best_score) {\n                best_score = score;\n                best_stack = i;\n            }\n        }\n        \n        return best_stack;\n    };\n    \n    // Function to carry out available boxes in strict order\n    auto carry_out_available_boxes = [&]() {\n        bool carried_any = false;\n        while (next_box <= n && !carried_out[next_box] && is_top(next_box)) {\n            operations.push_back({next_box, 0});\n            carried_out[next_box] = true;\n            int stack_idx = box_pos[next_box];\n            stacks[stack_idx].pop_back();\n            next_box++;\n            carried_any = true;\n        }\n        return carried_any;\n    };\n    \n    // Simple optimization check (less aggressive)\n    auto check_simple_optimization = [&]() -> bool {\n        // Only check if next_box+1 is in the same stack and at top\n        if (next_box < n) {\n            int next_plus_one = next_box + 1;\n            if (!carried_out[next_plus_one] && \n                box_pos[next_plus_one] == box_pos[next_box] && \n                is_top(next_plus_one)) {\n                \n                // If the next box is also blocked by the same segment, \n                // consider moving a box that's higher up\n                vector<int> boxes_above = get_boxes_above(next_box);\n                if (boxes_above.size() > 1) {\n                    // Move the second box instead of the first\n                    int box_to_move = boxes_above[1];\n                    int temp_stack = find_temporary_stack(box_pos[next_box], {box_to_move});\n                    \n                    if (temp_stack != -1) {\n                        operations.push_back({box_to_move, temp_stack});\n                        \n                        int current_stack = box_pos[box_to_move];\n                        auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), box_to_move);\n                        if (it != stacks[current_stack].end()) {\n                            vector<int> moving_boxes(it, stacks[current_stack].end());\n                            stacks[current_stack].erase(it, stacks[current_stack].end());\n                            stacks[temp_stack].insert(stacks[temp_stack].end(), moving_boxes.begin(), moving_boxes.end());\n                            \n                            for (int j = 0; j < moving_boxes.size(); j++) {\n                                box_pos[moving_boxes[j]] = temp_stack;\n                                box_height[moving_boxes[j]] = stacks[temp_stack].size() - moving_boxes.size() + j + 1;\n                            }\n                        }\n                        return true;\n                    }\n                }\n            }\n        }\n        return false;\n    };\n    \n    // Main loop\n    while (next_box <= n) {\n        // First, try to carry out any available boxes in order\n        if (carry_out_available_boxes()) {\n            continue;\n        }\n        \n        // Occasionally check for simple optimization opportunities\n        if (operations.size() % 15 == 0) {\n            if (check_simple_optimization()) {\n                continue;\n            }\n        }\n        \n        // If next_box is blocked, we need to move boxes above it\n        int current_stack = box_pos[next_box];\n        vector<int> boxes_above = get_boxes_above(next_box);\n        \n        if (boxes_above.empty()) {\n            next_box++;\n            continue;\n        }\n        \n        // Find the best temporary stack for this segment\n        int temp_stack = find_temporary_stack(current_stack, boxes_above);\n        \n        if (temp_stack == -1) {\n            // Fallback: use first available stack\n            for (int i = 1; i <= m; i++) {\n                if (i != current_stack) {\n                    temp_stack = i;\n                    break;\n                }\n            }\n            if (temp_stack == -1) temp_stack = 1;\n        }\n        \n        // Move the entire segment by moving its bottom box\n        int box_to_move = boxes_above[0];\n        operations.push_back({box_to_move, temp_stack});\n        \n        // Update stack configuration\n        auto it = find(stacks[current_stack].begin(), stacks[current_stack].end(), box_to_move);\n        if (it != stacks[current_stack].end()) {\n            vector<int> moving_boxes(it, stacks[current_stack].end());\n            stacks[current_stack].erase(it, stacks[current_stack].end());\n            stacks[temp_stack].insert(stacks[temp_stack].end(), moving_boxes.begin(), moving_boxes.end());\n            \n            // Update positions\n            for (int i = 0; i < moving_boxes.size(); i++) {\n                box_pos[moving_boxes[i]] = temp_stack;\n                box_height[moving_boxes[i]] = stacks[temp_stack].size() - moving_boxes.size() + i + 1;\n            }\n        }\n        \n        // Conservative safety check\n        if (operations.size() > 4950) {\n            // Emergency: try to carry out available boxes\n            for (int i = next_box; i <= n; i++) {\n                if (!carried_out[i] && is_top(i)) {\n                    operations.push_back({i, 0});\n                    carried_out[i] = true;\n                    stacks[box_pos[i]].pop_back();\n                    if (i == next_box) next_box++;\n                }\n            }\n            if (next_box > n) break;\n        }\n    }\n    \n    // Output operations\n    for (auto op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n    \n    return 0;\n}","ahc027":"#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n\nvector<string> h, v;\nvector<vector<bool>> visited;\nint N;\nstring moves;\n\nconst int di[] = {0, 1, 0, -1};\nconst int dj[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\n\nvoid dfs(int i, int j) {\n    visited[i][j] = true;\n    for (int k = 0; k < 4; k++) {\n        int ni = i + di[k];\n        int nj = j + dj[k];\n        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n        if (visited[ni][nj]) continue;\n        if (di[k] == 0) {\n            int col = min(j, nj);\n            if (v[i][col] == '1') continue;\n        } else {\n            int row = min(i, ni);\n            if (h[row][j] == '1') continue;\n        }\n        moves += dir[k];\n        dfs(ni, nj);\n        moves += dir[(k + 2) % 4];\n    }\n}\n\nint main() {\n    cin >> N;\n    h.resize(N - 1);\n    for (int i = 0; i < N - 1; i++) {\n        cin >> h[i];\n    }\n    v.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\n    }\n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n        }\n    }\n\n    visited.resize(N, vector<bool>(N, false));\n    moves = \"\";\n    dfs(0, 0);\n    cout << moves << endl;\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <map>\n#include <limits>\n#include <cmath>\n#include <utility>\n\nusing namespace std;\n\nconst int INF = numeric_limits<int>::max();\n\nint dist(pair<int, int> a, pair<int, int> b) {\n    return abs(a.first - b.first) + abs(a.second - b.second);\n}\n\npair<int, pair<int, int>> cost_to_type(const string& str, const pair<int, int>& start, const map<char, vector<pair<int, int>>>& letter_points) {\n    int L = str.length();\n    if (L == 0) return {0, start};\n\n    vector<map<pair<int, int>, int>> dp(L);\n    vector<map<pair<int, int>, pair<int, int>>> prev(L);\n\n    char c0 = str[0];\n    if (letter_points.find(c0) == letter_points.end()) return {INF, {0,0}};\n    for (auto p : letter_points.at(c0)) {\n        int cost = dist(start, p) + 1;\n        dp[0][p] = cost;\n        prev[0][p] = start;\n    }\n\n    for (int i = 1; i < L; i++) {\n        char c = str[i];\n        if (letter_points.find(c) == letter_points.end()) return {INF, {0,0}};\n        for (auto p : letter_points.at(c)) {\n            int best_cost = INF;\n            pair<int, int> best_prev;\n            char prev_c = str[i-1];\n            if (letter_points.find(prev_c) == letter_points.end()) return {INF, {0,0}};\n            for (auto q : letter_points.at(prev_c)) {\n                if (dp[i-1].find(q) == dp[i-1].end()) continue;\n                int cost = dp[i-1][q] + dist(q, p) + 1;\n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_prev = q;\n                }\n            }\n            if (best_cost < INF) {\n                dp[i][p] = best_cost;\n                prev[i][p] = best_prev;\n            }\n        }\n    }\n\n    int min_cost = INF;\n    pair<int, int> end_pos = start;\n    char last_c = str[L-1];\n    if (letter_points.find(last_c) == letter_points.end()) return {INF, {0,0}};\n    for (auto p : letter_points.at(last_c)) {\n        if (dp[L-1].find(p) != dp[L-1].end() && dp[L-1][p] < min_cost) {\n            min_cost = dp[L-1][p];\n            end_pos = p;\n        }\n    }\n    if (min_cost == INF) return {INF, start};\n    return {min_cost, end_pos};\n}\n\nint compute_overlap(const string& S, const string& B) {\n    int max_possible = min(S.length(), B.length());\n    for (int l = max_possible; l > 0; l--) {\n        if (S.substr(S.length() - l) == B.substr(0, l)) {\n            return l;\n        }\n    }\n    return 0;\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int s_i, s_j;\n    cin >> s_i >> s_j;\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    vector<string> words(M);\n    for (int i = 0; i < M; i++) {\n        cin >> words[i];\n    }\n\n    map<char, vector<pair<int, int>>> letter_points;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            char c = grid[i][j];\n            letter_points[c].push_back({i, j});\n        }\n    }\n\n    pair<int, int> current_pos = {s_i, s_j};\n    vector<string> uncovered = words;\n    string S = \"\";\n\n    const int BEAM_WIDTH = 10;\n\n    while (!uncovered.empty()) {\n        if (uncovered.size() == 1) {\n            string B = uncovered[0];\n            int k1 = compute_overlap(S, B);\n            string suffix_B = B.substr(k1);\n            auto [cost_B, pos_B] = cost_to_type(suffix_B, current_pos, letter_points);\n            S += suffix_B;\n            current_pos = pos_B;\n            uncovered.clear();\n        } else {\n            vector<pair<int, string>> overlaps;\n            for (string B : uncovered) {\n                int ov = compute_overlap(S, B);\n                overlaps.push_back({ov, B});\n            }\n            sort(overlaps.begin(), overlaps.end(), [](const pair<int, string>& a, const pair<int, string>& b) {\n                return a.first > b.first;\n            });\n            int K = min(BEAM_WIDTH, (int)uncovered.size());\n            vector<string> top_B;\n            for (int i = 0; i < K; i++) {\n                top_B.push_back(overlaps[i].second);\n            }\n\n            int best_total_cost = INF;\n            string best_B;\n\n            for (string B : top_B) {\n                int k1 = compute_overlap(S, B);\n                string suffix_B = B.substr(k1);\n                auto [cost_B, pos_B] = cost_to_type(suffix_B, current_pos, letter_points);\n                string new_S = S + suffix_B;\n\n                vector<pair<int, string>> overlaps2;\n                for (string C : uncovered) {\n                    if (C == B) continue;\n                    int ov2 = compute_overlap(new_S, C);\n                    overlaps2.push_back({ov2, C});\n                }\n                sort(overlaps2.begin(), overlaps2.end(), [](const pair<int, string>& a, const pair<int, string>& b) {\n                    return a.first > b.first;\n                });\n                int L = min(BEAM_WIDTH, (int)overlaps2.size());\n                if (L == 0) continue;\n                for (int j = 0; j < L; j++) {\n                    string C = overlaps2[j].second;\n                    int k2 = compute_overlap(new_S, C);\n                    string suffix_C = C.substr(k2);\n                    auto [cost_C, pos_C] = cost_to_type(suffix_C, pos_B, letter_points);\n                    int total_cost = cost_B + cost_C;\n                    if (total_cost < best_total_cost) {\n                        best_total_cost = total_cost;\n                        best_B = B;\n                    }\n                }\n            }\n\n            if (best_total_cost == INF) {\n                best_B = uncovered[0];\n            }\n            int k1 = compute_overlap(S, best_B);\n            string suffix_B = best_B.substr(k1);\n            auto [cost_B, pos_B] = cost_to_type(suffix_B, current_pos, letter_points);\n            S += suffix_B;\n            current_pos = pos_B;\n            uncovered.erase(find(uncovered.begin(), uncovered.end(), best_B));\n        }\n    }\n\n    int L = S.size();\n    vector<vector<pair<int, int>>> points_for_S(L);\n    for (int i = 0; i < L; i++) {\n        points_for_S[i] = letter_points[S[i]];\n    }\n\n    pair<int, int> initial = {s_i, s_j};\n    vector<map<pair<int, int>, int>> dp(L);\n    vector<map<pair<int, int>, pair<int, int>>> prev(L);\n\n    for (auto p : points_for_S[0]) {\n        int cost = dist(initial, p) + 1;\n        dp[0][p] = cost;\n        prev[0][p] = initial;\n    }\n\n    for (int i = 1; i < L; i++) {\n        for (auto p : points_for_S[i]) {\n            int best_cost = INF;\n            pair<int, int> best_prev;\n            for (auto q : points_for_S[i-1]) {\n                if (dp[i-1].find(q) == dp[i-1].end()) continue;\n                int cost = dp[i-1][q] + dist(q, p) + 1;\n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_prev = q;\n                }\n            }\n            if (best_cost < INF) {\n                dp[i][p] = best_cost;\n                prev[i][p] = best_prev;\n            }\n        }\n    }\n\n    int min_cost = INF;\n    pair<int, int> best_point;\n    for (auto p : points_for_S[L-1]) {\n        if (dp[L-1].find(p) != dp[L-1].end() && dp[L-1][p] < min_cost) {\n            min_cost = dp[L-1][p];\n            best_point = p;\n        }\n    }\n\n    vector<pair<int, int>> sequence;\n    pair<int, int> current = best_point;\n    for (int i = L-1; i >= 0; i--) {\n        sequence.push_back(current);\n        if (i > 0) {\n            current = prev[i][current];\n        }\n    }\n    reverse(sequence.begin(), sequence.end());\n\n    for (auto p : sequence) {\n        cout << p.first << \" \" << p.second << endl;\n    }\n\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <tuple>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n\n    vector<vector<pair<int, int>>> fields(M);\n    int S = 0;\n    \n    for (int k = 0; k < M; k++) {\n        int d;\n        cin >> d;\n        S += d;\n        for (int i = 0; i < d; i++) {\n            int x, y;\n            cin >> x >> y;\n            fields[k].push_back(make_pair(x, y));\n        }\n    }\n\n    // Precompute expected oil reserves for each square\n    vector<vector<double>> weight(N, vector<double>(N, 0.0));\n    \n    for (const auto& shape : fields) {\n        int max_i = 0, max_j = 0;\n        for (auto p : shape) {\n            max_i = max(max_i, p.first);\n            max_j = max(max_j, p.second);\n        }\n        \n        int total_placements = (N - max_i) * (N - max_j);\n        if (total_placements <= 0) continue;\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                int count = 0;\n                for (auto p : shape) {\n                    int di = i - p.first;\n                    int dj = j - p.second;\n                    if (di >= 0 && di < N - max_i && dj >= 0 && dj < N - max_j) {\n                        count++;\n                    }\n                }\n                weight[i][j] += (double)count / total_placements;\n            }\n        }\n    }\n\n    // Create and sort squares by expected oil reserves\n    vector<tuple<double, int, int>> squares;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            squares.push_back(make_tuple(weight[i][j], i, j));\n        }\n    }\n    \n    sort(squares.begin(), squares.end(), [](const tuple<double, int, int>& a, const tuple<double, int, int>& b) {\n        return get<0>(a) > get<0>(b);\n    });\n\n    // Drill squares in priority order until we find all oil\n    vector<pair<int, int>> oil_squares;\n    int cumulative_sum = 0;\n    \n    for (const auto& square : squares) {\n        double w = get<0>(square);\n        int i = get<1>(square);\n        int j = get<2>(square);\n        \n        cout << \"q 1 \" << i << \" \" << j << endl;\n        int resp;\n        cin >> resp;\n        \n        if (resp > 0) {\n            oil_squares.push_back(make_pair(i, j));\n            cumulative_sum += resp;\n        }\n        \n        if (cumulative_sum >= S) {\n            break;\n        }\n    }\n\n    // Output final answer\n    cout << \"a \" << oil_squares.size();\n    for (auto p : oil_squares) {\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << endl;\n\n    int result;\n    cin >> result;\n    \n    return 0;\n}","ahc031":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <climits>\n\nusing namespace std;\n\nint main() {\n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    // Store strip boundaries for each day\n    vector<vector<int>> strip_boundaries(D, vector<int>(N + 1, 0));\n    vector<vector<int>> strip_assignments(D, vector<int>(N, 0));\n    \n    // Process each day\n    for (int d = 0; d < D; d++) {\n        // Calculate total desired area\n        int total_desired = 0;\n        for (int k = 0; k < N; k++) {\n            total_desired += a[d][k];\n        }\n        \n        // Sort areas while preserving original indices\n        vector<pair<int, int>> sorted_areas;\n        for (int k = 0; k < N; k++) {\n            sorted_areas.push_back({a[d][k], k});\n        }\n        sort(sorted_areas.begin(), sorted_areas.end());\n        \n        // Try to reuse previous day's layout if it's reasonably good\n        bool reuse_layout = false;\n        if (d > 0) {\n            int total_deficit = 0;\n            for (int k = 0; k < N; k++) {\n                int strip_height = strip_boundaries[d-1][k+1] - strip_boundaries[d-1][k];\n                int strip_area = strip_height * W;\n                total_deficit += max(0, a[d][k] - strip_area);\n            }\n            \n            // Reuse if deficit is acceptable (heuristic threshold)\n            if (total_deficit * 100 < W * 5) {\n                strip_boundaries[d] = strip_boundaries[d-1];\n                strip_assignments[d] = strip_assignments[d-1];\n                reuse_layout = true;\n            }\n        }\n        \n        if (!reuse_layout) {\n            // Calculate new strip boundaries proportionally to area requirements\n            int cumulative_height = 0;\n            for (int k = 0; k < N; k++) {\n                double proportion = (double)sorted_areas[k].first / total_desired;\n                int strip_height = max(1, (int)round(proportion * W));\n                \n                strip_boundaries[d][k] = cumulative_height;\n                cumulative_height += strip_height;\n                \n                // Store assignment mapping\n                strip_assignments[d][sorted_areas[k].second] = k;\n            }\n            strip_boundaries[d][N] = W;\n            \n            // Adjust if we exceeded W\n            if (cumulative_height > W) {\n                // Redistribute proportionally with integer rounding\n                cumulative_height = 0;\n                for (int k = 0; k < N; k++) {\n                    double proportion = (double)sorted_areas[k].first / total_desired;\n                    int strip_height = max(1, (int)(proportion * W));\n                    strip_boundaries[d][k] = cumulative_height;\n                    cumulative_height += strip_height;\n                    \n                    // Update assignment mapping\n                    strip_assignments[d][sorted_areas[k].second] = k;\n                }\n                strip_boundaries[d][N] = W;\n            }\n        }\n        \n        // Ensure boundaries are valid and non-overlapping\n        for (int k = 0; k <= N; k++) {\n            strip_boundaries[d][k] = max(0, min(W, strip_boundaries[d][k]));\n        }\n        \n        // Ensure boundaries are strictly increasing\n        for (int k = 1; k <= N; k++) {\n            if (strip_boundaries[d][k] <= strip_boundaries[d][k-1]) {\n                strip_boundaries[d][k] = strip_boundaries[d][k-1] + 1;\n            }\n        }\n        strip_boundaries[d][N] = W;\n    }\n    \n    // Output rectangles\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            int strip_idx = strip_assignments[d][k];\n            int i0 = strip_boundaries[d][strip_idx];\n            int i1 = strip_boundaries[d][strip_idx + 1];\n            int j0 = 0;\n            int j1 = W;\n            \n            // Ensure valid rectangle (non-zero area)\n            if (i0 >= i1) {\n                i1 = i0 + 1;\n            }\n            if (i1 > W) {\n                i1 = W;\n            }\n            \n            cout << i0 << \" \" << j0 << \" \" << i1 << \" \" << j1 << endl;\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <tuple>\n#include <set>\n#include <map>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <chrono>\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\n\nint main() {\n    auto start_time = chrono::high_resolution_clock::now();\n    srand(time(0));\n\n    int n, m, k;\n    cin >> n >> m >> k;\n    \n    int a[N][N];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> a[i][j];\n        }\n    }\n    \n    int stamps[M][3][3];\n    for (int mm = 0; mm < m; mm++) {\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                cin >> stamps[mm][i][j];\n            }\n        }\n    }\n    \n    int u[N][N];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            u[i][j] = a[i][j] % MOD;\n        }\n    }\n    \n    vector<tuple<int, int, int>> operations;\n    int max_p = n - 3;\n    int max_q = n - 3;\n    \n    // Phase 1: Optimized greedy initialization\n    for (int step = 0; step < k; step++) {\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1000) break; // Adjusted time allocation\n        \n        int best_delta = -1000000000;\n        int best_m = -1, best_p = -1, best_q = -1;\n        \n        // Adaptive sampling based on remaining time\n        int base_samples = 100;\n        if (elapsed > 800) base_samples = 50; // Reduce samples if running out of time\n        int samples = min(base_samples, m * (max_p + 1) * (max_q + 1));\n        \n        for (int s = 0; s < samples; s++) {\n            int mm = rand() % m;\n            int p = rand() % (max_p + 1);\n            int q = rand() % (max_q + 1);\n            \n            int delta = 0;\n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    int x = p + i;\n                    int y = q + j;\n                    int current_u = u[x][y];\n                    int s_val = stamps[mm][i][j];\n                    int new_u = (current_u + s_val) % MOD;\n                    if (new_u < 0) new_u += MOD;\n                    delta += new_u - current_u;\n                }\n            }\n            \n            if (delta > best_delta) {\n                best_delta = delta;\n                best_m = mm;\n                best_p = p;\n                best_q = q;\n            }\n        }\n        \n        // Smarter operation addition strategy\n        if (best_delta > 0 || (operations.size() < k * 0.8 && best_delta > -1000000)) {\n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    int x = best_p + i;\n                    int y = best_q + j;\n                    int s_val = stamps[best_m][i][j];\n                    u[x][y] = (u[x][y] + s_val) % MOD;\n                    if (u[x][y] < 0) u[x][y] += MOD;\n                }\n            }\n            operations.push_back(make_tuple(best_m, best_p, best_q));\n        } else if (operations.size() < k / 3) {\n            // Add random operations early to create optimization opportunities\n            best_m = rand() % m;\n            best_p = rand() % (max_p + 1);\n            best_q = rand() % (max_q + 1);\n            \n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    int x = best_p + i;\n                    int y = best_q + j;\n                    int s_val = stamps[best_m][i][j];\n                    u[x][y] = (u[x][y] + s_val) % MOD;\n                    if (u[x][y] < 0) u[x][y] += MOD;\n                }\n            }\n            operations.push_back(make_tuple(best_m, best_p, best_q));\n        } else {\n            break;\n        }\n    }\n    \n    // Phase 2: Fine-tuned simulated annealing\n    double temperature = 10000.0; // Slightly higher initial temperature\n    double cooling_rate = 0.93; // Adjusted cooling rate\n    int iterations = 0;\n    const int max_iterations = 10000; // Increased iterations\n    \n    // Track improvement for adaptive cooling\n    int improvements = 0;\n    int total_moves = 0;\n    \n    while (iterations < max_iterations) {\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1950) break;\n        \n        if (operations.empty()) break;\n        \n        int idx = rand() % operations.size();\n        int old_m, old_p, old_q;\n        tie(old_m, old_p, old_q) = operations[idx];\n        \n        int new_m = rand() % M;\n        int new_p = rand() % (max_p + 1);\n        int new_q = rand() % (max_q + 1);\n        \n        if (old_m == new_m && old_p == new_p && old_q == new_q) {\n            iterations++;\n            continue;\n        }\n        \n        // Calculate delta efficiently\n        int delta_score = 0;\n        set<pair<int, int>> affected_cells;\n        map<pair<int, int>, int> changes;\n        \n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = old_p + i;\n                int y = old_q + j;\n                affected_cells.insert({x, y});\n                changes[{x, y}] -= stamps[old_m][i][j];\n            }\n        }\n        for (int i = 0; i < 3; i++) {\n            for (int j = 0; j < 3; j++) {\n                int x = new_p + i;\n                int y = new_q + j;\n                affected_cells.insert({x, y});\n                changes[{x, y}] += stamps[new_m][i][j];\n            }\n        }\n        \n        for (auto cell : affected_cells) {\n            int x = cell.first, y = cell.second;\n            int current_u = u[x][y];\n            int change = changes[cell];\n            int new_val = current_u + change;\n            int new_u = new_val % MOD;\n            if (new_u < 0) new_u += MOD;\n            delta_score += new_u - current_u;\n        }\n        \n        total_moves++;\n        \n        // Accept move\n        if (delta_score > 0 || (double)rand() / RAND_MAX < exp(delta_score / temperature)) {\n            for (auto cell : affected_cells) {\n                int x = cell.first, y = cell.second;\n                u[x][y] = (u[x][y] + changes[cell]) % MOD;\n                if (u[x][y] < 0) u[x][y] += MOD;\n            }\n            operations[idx] = make_tuple(new_m, new_p, new_q);\n            \n            if (delta_score > 0) improvements++;\n        }\n        \n        // Adaptive cooling based on improvement rate\n        if (total_moves > 100) {\n            double improvement_rate = (double)improvements / total_moves;\n            if (improvement_rate < 0.1) {\n                // Cool faster if improvement rate is low\n                cooling_rate = 0.97;\n            } else if (improvement_rate > 0.3) {\n                // Cool slower if improvement rate is high\n                cooling_rate = 0.90;\n            } else {\n                cooling_rate = 0.93;\n            }\n            improvements = 0;\n            total_moves = 0;\n        }\n        \n        temperature *= cooling_rate;\n        iterations++;\n        \n        // Reset temperature if it gets too low but we still have time\n        if (temperature < 1e-6 && elapsed < 1500) {\n            temperature = 5000.0;\n            cooling_rate = 0.95;\n        }\n    }\n    \n    // Phase 3: Intelligent final optimization\n    while (operations.size() < k) {\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1990) break;\n        \n        int best_delta = -1000000000;\n        int best_m = -1, best_p = -1, best_q = -1;\n        \n        // Focus on high-impact areas in the final phase\n        int samples = min(60, m * (max_p + 1) * (max_q + 1));\n        for (int s = 0; s < samples; s++) {\n            int mm = rand() % m;\n            int p = rand() % (max_p + 1);\n            int q = rand() % (max_q + 1);\n            \n            int delta = 0;\n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    int x = p + i;\n                    int y = q + j;\n                    int current_u = u[x][y];\n                    int s_val = stamps[mm][i][j];\n                    int new_u = (current_u + s_val) % MOD;\n                    if (new_u < 0) new_u += MOD;\n                    delta += new_u - current_u;\n                }\n            }\n            \n            if (delta > best_delta) {\n                best_delta = delta;\n                best_m = mm;\n                best_p = p;\n                best_q = q;\n            }\n        }\n        \n        // Always add in final phase, but prioritize better moves\n        if (best_delta > -5000000) { // Reasonable threshold\n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    int x = best_p + i;\n                    int y = best_q + j;\n                    int s_val = stamps[best_m][i][j];\n                    u[x][y] = (u[x][y] + s_val) % MOD;\n                    if (u[x][y] < 0) u[x][y] += MOD;\n                }\n            }\n            operations.push_back(make_tuple(best_m, best_p, best_q));\n        } else {\n            // Add a random operation if no good move found\n            best_m = rand() % m;\n            best_p = rand() % (max_p + 1);\n            best_q = rand() % (max_q + 1);\n            \n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    int x = best_p + i;\n                    int y = best_q + j;\n                    int s_val = stamps[best_m][i][j];\n                    u[x][y] = (u[x][y] + s_val) % MOD;\n                    if (u[x][y] < 0) u[x][y] += MOD;\n                }\n            }\n            operations.push_back(make_tuple(best_m, best_p, best_q));\n        }\n    }\n    \n    cout << operations.size() << endl;\n    for (auto op : operations) {\n        int m, p, q;\n        tie(m, p, q) = op;\n        cout << m << \" \" << p << \" \" << q << endl;\n    }\n    \n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <array>\n#include <algorithm>\nusing namespace std;\n\nconst int N = 5;\n\narray<array<int, N>, N> grid;\narray<int, N> brought = {0};\narray<int, N> dispatched = {0};\narray<array<int, N>, N> A;\n\nstruct Crane {\n    int i, j;\n    bool carrying;\n    int container;\n    bool active;\n    bool is_large;\n};\n\nvector<Crane> cranes;\nvector<string> actions(N);\n\nvoid init_cranes() {\n    cranes.resize(N);\n    for (int i = 0; i < N; i++) {\n        cranes[i].i = i;\n        cranes[i].j = 0;\n        cranes[i].carrying = false;\n        cranes[i].active = true;\n        cranes[i].is_large = (i == 0);\n    }\n}\n\nbool is_crane_on(int i, int j) {\n    for (const Crane& crane : cranes) {\n        if (crane.active && crane.i == i && crane.j == j) {\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> A[i][j];\n        }\n    }\n\n    init_cranes();\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            grid[i][j] = -1;\n        }\n    }\n\n    int turns = 0;\n    const int max_turns = 10000;\n\n    while (turns < max_turns) {\n        for (int i = 0; i < N; i++) {\n            if (brought[i] < N && grid[i][0] == -1 && !is_crane_on(i, 0)) {\n                grid[i][0] = A[i][brought[i]];\n                brought[i]++;\n            }\n        }\n\n        for (int idx = 0; idx < N; idx++) {\n            Crane& crane = cranes[idx];\n            if (!crane.active) {\n                actions[idx] += '.';\n                continue;\n            }\n\n            if (!crane.is_large) {\n                if (turns == 0) {\n                    if (crane.j < N-1) {\n                        actions[idx] += 'R';\n                        crane.j++;\n                    } else {\n                        actions[idx] += '.';\n                    }\n                } else if (turns == 1) {\n                    if (!crane.carrying) {\n                        actions[idx] += 'B';\n                        crane.active = false;\n                    } else {\n                        actions[idx] += '.';\n                    }\n                } else {\n                    actions[idx] += '.';\n                }\n            } else {\n                if (!crane.carrying) {\n                    if (grid[crane.i][crane.j] != -1) {\n                        actions[idx] += 'P';\n                        crane.carrying = true;\n                        crane.container = grid[crane.i][crane.j];\n                        grid[crane.i][crane.j] = -1;\n                    } else {\n                        int target_i = -1, target_j = -1;\n                        for (int i = 0; i < N; i++) {\n                            if (grid[i][0] != -1) {\n                                target_i = i;\n                                target_j = 0;\n                                break;\n                            }\n                        }\n                        if (target_i == -1) {\n                            for (int i = 0; i < N; i++) {\n                                for (int j = 0; j < N-1; j++) {\n                                    if (grid[i][j] != -1) {\n                                        target_i = i;\n                                        target_j = j;\n                                        break;\n                                    }\n                                }\n                                if (target_i != -1) break;\n                            }\n                        }\n                        if (target_i != -1) {\n                            if (crane.i != target_i) {\n                                if (crane.i < target_i) {\n                                    actions[idx] += 'D';\n                                    crane.i++;\n                                } else {\n                                    actions[idx] += 'U';\n                                    crane.i--;\n                                }\n                            } else if (crane.j != target_j) {\n                                if (crane.j < target_j) {\n                                    actions[idx] += 'R';\n                                    crane.j++;\n                                } else {\n                                    actions[idx] += 'L';\n                                    crane.j--;\n                                }\n                            } else {\n                                actions[idx] += '.';\n                            }\n                        } else {\n                            actions[idx] += '.';\n                        }\n                    }\n                } else {\n                    int b = crane.container;\n                    int target_i = b / N;\n                    if (crane.i != target_i) {\n                        if (crane.i < target_i) {\n                            actions[idx] += 'D';\n                            crane.i++;\n                        } else {\n                            actions[idx] += 'U';\n                            crane.i--;\n                        }\n                    } else {\n                        if (crane.j != N-1) {\n                            if (crane.j < N-1) {\n                                actions[idx] += 'R';\n                                crane.j++;\n                            } else {\n                                actions[idx] += 'L';\n                                crane.j--;\n                            }\n                        } else {\n                            if (grid[target_i][N-1] == -1) {\n                                actions[idx] += 'Q';\n                                grid[target_i][N-1] = b;\n                                crane.carrying = false;\n                            } else {\n                                actions[idx] += '.';\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        for (int i = 0; i < N; i++) {\n            if (grid[i][N-1] != -1) {\n                int b = grid[i][N-1];\n                grid[i][N-1] = -1;\n                if (b >= i * N && b < i * N + N) {\n                    dispatched[i]++;\n                }\n            }\n        }\n\n        turns++;\n        bool all_brought = true;\n        for (int i = 0; i < N; i++) {\n            if (brought[i] < N) {\n                all_brought = false;\n                break;\n            }\n        }\n        if (all_brought) {\n            bool grid_empty = true;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] != -1) {\n                        grid_empty = false;\n                        break;\n                    }\n                }\n                if (!grid_empty) break;\n            }\n            if (grid_empty && !cranes[0].carrying) {\n                break;\n            }\n        }\n    }\n\n    size_t max_len = 0;\n    for (int i = 0; i < N; i++) {\n        if (actions[i].size() > max_len) {\n            max_len = actions[i].size();\n        }\n    }\n    for (int i = 0; i < N; i++) {\n        string s = actions[i];\n        s.resize(max_len, '.');\n        cout << s << endl;\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\nvector<string> get_moves(int from_i, int from_j, int to_i, int to_j) {\n    vector<string> moves;\n    int di = to_i - from_i;\n    int dj = to_j - from_j;\n    if (di > 0) {\n        for (int i = 0; i < di; i++) {\n            moves.push_back(\"D\");\n        }\n    } else if (di < 0) {\n        for (int i = 0; i < -di; i++) {\n            moves.push_back(\"U\");\n        }\n    }\n    if (dj > 0) {\n        for (int j = 0; j < dj; j++) {\n            moves.push_back(\"R\");\n        }\n    } else if (dj < 0) {\n        for (int j = 0; j < -dj; j++) {\n            moves.push_back(\"L\");\n        }\n    }\n    return moves;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<vector<int>> h_current(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h_current[i][j];\n        }\n    }\n\n    int current_i = 0, current_j = 0;\n    int load = 0;\n    vector<string> operations;\n\n    while (true) {\n        bool all_zero = true;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (h_current[i][j] != 0) {\n                    all_zero = false;\n                    break;\n                }\n            }\n            if (!all_zero) break;\n        }\n        if (all_zero && load == 0) {\n            break;\n        }\n\n        bool operation_done = false;\n        if (h_current[current_i][current_j] > 0 && load == 0) {\n            int d = h_current[current_i][current_j];\n            operations.push_back(\"+\" + to_string(d));\n            load += d;\n            h_current[current_i][current_j] = 0;\n            operation_done = true;\n        } else if (h_current[current_i][current_j] < 0 && load > 0) {\n            int d = min(load, -h_current[current_i][current_j]);\n            operations.push_back(\"-\" + to_string(d));\n            load -= d;\n            h_current[current_i][current_j] += d;\n            operation_done = true;\n        }\n\n        if (operation_done) {\n            continue;\n        }\n\n        if (load == 0) {\n            int best_dist = 1e9;\n            int best_i = -1, best_j = -1;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h_current[i][j] > 0) {\n                        int dist = abs(i - current_i) + abs(j - current_j);\n                        if (dist < best_dist) {\n                            best_dist = dist;\n                            best_i = i;\n                            best_j = j;\n                        }\n                    }\n                }\n            }\n            if (best_i == -1) {\n                break;\n            }\n            vector<string> moves = get_moves(current_i, current_j, best_i, best_j);\n            operations.insert(operations.end(), moves.begin(), moves.end());\n            current_i = best_i;\n            current_j = best_j;\n        } else if (load > 0) {\n            int best_dist = 1e9;\n            int best_i = -1, best_j = -1;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h_current[i][j] < 0) {\n                        int dist = abs(i - current_i) + abs(j - current_j);\n                        if (dist < best_dist) {\n                            best_dist = dist;\n                            best_i = i;\n                            best_j = j;\n                        }\n                    }\n                }\n            }\n            if (best_i == -1) {\n                break;\n            }\n            vector<string> moves = get_moves(current_i, current_j, best_i, best_j);\n            operations.insert(operations.end(), moves.begin(), moves.end());\n            current_i = best_i;\n            current_j = best_j;\n        } else {\n            break;\n        }\n    }\n\n    for (const string& op : operations) {\n        cout << op << endl;\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\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    // Store initial max values for consistent reference\n    vector<int> initial_max_per_criterion(M, 0);\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i][j];\n            if (seeds[i][j] > initial_max_per_criterion[j]) {\n                initial_max_per_criterion[j] = seeds[i][j];\n            }\n        }\n    }\n\n    for (int t = 0; t < T; t++) {\n        vector<int> values(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            values[i] = accumulate(seeds[i].begin(), seeds[i].end(), 0);\n        }\n\n        // Further optimized seed selection\n        vector<int> indices(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            indices[i] = i;\n        }\n        \n        // Enhanced sorting with improved tie-breaking\n        sort(indices.begin(), indices.end(), [&](int a, int b) {\n            if (values[a] != values[b]) return values[a] > values[b];\n            \n            // More sophisticated tie-breaker\n            int strong_a = 0, strong_b = 0;\n            double balance_score_a = 0, balance_score_b = 0;\n            for (int l = 0; l < M; l++) {\n                double ratio_a = (double)seeds[a][l] / initial_max_per_criterion[l];\n                double ratio_b = (double)seeds[b][l] / initial_max_per_criterion[l];\n                if (ratio_a > 0.8) strong_a++;\n                if (ratio_b > 0.8) strong_b++;\n                balance_score_a += ratio_a;\n                balance_score_b += ratio_b;\n            }\n            balance_score_a /= M;\n            balance_score_b /= M;\n            \n            // Prioritize seeds with strong criteria, then balanced ones\n            if (strong_a != strong_b) return strong_a > strong_b;\n            return balance_score_a > balance_score_b;\n        });\n\n        // Adaptive seed selection based on turn\n        vector<int> plant_indices;\n        vector<bool> used(seed_count, false);\n        \n        // Dynamic top seed count based on turn\n        int top_count;\n        if (t < 4) {\n            top_count = 25; // More diversity in early turns\n        } else if (t < 8) {\n            top_count = 27; // Balanced approach\n        } else {\n            top_count = 29; // Focus on quality in late turns\n        }\n        top_count = min(top_count, N * N);\n\n        for (int i = 0; i < top_count; i++) {\n            plant_indices.push_back(indices[i]);\n            used[indices[i]] = true;\n        }\n\n        // Enhanced criterion coverage with turn-based adaptation\n        vector<int> criterion_covered(M, 0);\n        for (int idx : plant_indices) {\n            for (int l = 0; l < M; l++) {\n                if (seeds[idx][l] > initial_max_per_criterion[l] * 0.83) {\n                    criterion_covered[l]++;\n                }\n            }\n        }\n\n        // Adaptive gap filling\n        for (int l = 0; l < M && plant_indices.size() < N * N; l++) {\n            int target_coverage = (t < 5) ? 2 : 1; // More coverage in early turns\n            if (criterion_covered[l] < target_coverage) {\n                for (int i = top_count; i < seed_count && plant_indices.size() < N * N; i++) {\n                    int candidate = indices[i];\n                    if (!used[candidate] && seeds[candidate][l] > initial_max_per_criterion[l] * 0.76) {\n                        plant_indices.push_back(candidate);\n                        used[candidate] = true;\n                        criterion_covered[l]++;\n                        if (criterion_covered[l] >= target_coverage) break;\n                    }\n                }\n            }\n        }\n\n        // Fill remaining slots with best available seeds\n        for (int i = 0; plant_indices.size() < N * N && i < seed_count; i++) {\n            if (!used[indices[i]]) {\n                plant_indices.push_back(indices[i]);\n                used[indices[i]] = true;\n            }\n        }\n\n        // Optimized spiral placement\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        vector<bool> assigned(plant_indices.size(), false);\n        \n        // Generate spiral order starting from center\n        vector<pair<int, int>> spiral_order;\n        int center_i = N / 2, center_j = N / 2;\n        spiral_order.push_back({center_i, center_j});\n        \n        int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        int step = 1, dir = 0;\n        int i = center_i, j = center_j;\n        \n        while (spiral_order.size() < N * N) {\n            for (int s = 0; s < 2; s++) {\n                for (int k = 0; k < step && spiral_order.size() < N * N; k++) {\n                    i += directions[dir][0];\n                    j += directions[dir][1];\n                    if (i >= 0 && i < N && j >= 0 && j < N) {\n                        spiral_order.push_back({i, j});\n                    }\n                }\n                dir = (dir + 1) % 4;\n            }\n            step++;\n        }\n\n        // Fine-tuned cell importance\n        vector<vector<double>> cell_importance(N, vector<double>(N, 0.0));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                double di = abs(i - (N-1)/2.0);\n                double dj = abs(j - (N-1)/2.0);\n                double dist = sqrt(di*di + dj*dj);\n                cell_importance[i][j] = 1.0 - dist / (N * 0.66);\n            }\n        }\n\n        // Assign seeds with further optimized scoring\n        for (auto [i, j] : spiral_order) {\n            vector<int> neighbor_seeds;\n            \n            // Check all four neighbors\n            int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n            for (auto [di, dj] : directions) {\n                int ni = i + di, nj = j + dj;\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && A[ni][nj] != -1) {\n                    neighbor_seeds.push_back(A[ni][nj]);\n                }\n            }\n\n            if (neighbor_seeds.empty()) {\n                // Enhanced scoring for isolated cells\n                int best_seed = -1;\n                double best_score = -1;\n                for (int k = 0; k < plant_indices.size(); k++) {\n                    if (assigned[k]) continue;\n                    \n                    int seed_idx = plant_indices[k];\n                    double score = values[seed_idx] * cell_importance[i][j];\n                    \n                    // Bonus for balanced and strong seeds\n                    int strong_criteria = 0;\n                    double min_ratio = 1.0, avg_ratio = 0;\n                    for (int l = 0; l < M; l++) {\n                        double ratio = (double)seeds[seed_idx][l] / initial_max_per_criterion[l];\n                        if (ratio > 0.78) strong_criteria++;\n                        if (ratio < min_ratio) min_ratio = ratio;\n                        avg_ratio += ratio;\n                    }\n                    avg_ratio /= M;\n                    \n                    // Combined bonus for strength and balance\n                    double bonus = (strong_criteria * 0.04) + (min_ratio * 0.1) + (avg_ratio * 0.03);\n                    score *= (1.0 + bonus);\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_seed = k;\n                    }\n                }\n                if (best_seed != -1) {\n                    A[i][j] = plant_indices[best_seed];\n                    assigned[best_seed] = true;\n                }\n            } else {\n                // Calculate deficiencies\n                vector<int> max_neighbor_values(M, 0);\n                for (int n_index : neighbor_seeds) {\n                    for (int l = 0; l < M; l++) {\n                        if (seeds[n_index][l] > max_neighbor_values[l]) {\n                            max_neighbor_values[l] = seeds[n_index][l];\n                        }\n                    }\n                }\n                \n                vector<int> deficiencies(M, 0);\n                for (int l = 0; l < M; l++) {\n                    deficiencies[l] = initial_max_per_criterion[l] - max_neighbor_values[l];\n                }\n\n                // Further optimized scoring\n                int best_seed_index = -1;\n                double best_score = -1e9;\n                \n                for (int k = 0; k < plant_indices.size(); k++) {\n                    if (assigned[k]) continue;\n                    \n                    int s_index = plant_indices[k];\n                    double score = values[s_index] * 0.74; // Adjusted base weight\n                    \n                    // Enhanced complementarity component\n                    for (int l = 0; l < M; l++) {\n                        if (deficiencies[l] > 0) {\n                            // More refined deficiency scaling\n                            double scale_factor = 1.0 + log1p(deficiencies[l]) * 0.15;\n                            score += seeds[s_index][l] * deficiencies[l] * 0.105 * scale_factor;\n                        }\n                    }\n                    \n                    // Strategic bonus for critical criteria\n                    for (int l = 0; l < M; l++) {\n                        if (seeds[s_index][l] > initial_max_per_criterion[l] * 0.86 && deficiencies[l] > 15) {\n                            score += deficiencies[l] * 0.9;\n                        }\n                    }\n                    \n                    // Turn-based adaptation\n                    if (t > 6) {\n                        // Late turns: emphasize value more\n                        score *= 1.05;\n                    }\n                    \n                    // Cell importance weighting\n                    score *= cell_importance[i][j];\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_seed_index = k;\n                    }\n                }\n                \n                if (best_seed_index != -1) {\n                    A[i][j] = plant_indices[best_seed_index];\n                    assigned[best_seed_index] = true;\n                } else {\n                    for (int k = 0; k < plant_indices.size(); k++) {\n                        if (!assigned[k]) {\n                            A[i][j] = plant_indices[k];\n                            assigned[k] = true;\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        // Output the assignment\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << A[i][j];\n                if (j < N - 1) {\n                    cout << \" \";\n                }\n            }\n            cout << endl;\n        }\n        cout.flush();\n\n        // Read new seeds for next generation\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\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, V;\n    cin >> N >> M >> V;\n    \n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; i++) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> t[i];\n    }\n    \n    // Minimal tree design: just root and one fingertip\n    cout << \"2\" << endl;\n    cout << \"0 1\" << endl;\n    \n    // Start at a safe position\n    cout << N/2 << \" \" << N/2 << endl;\n    \n    // Output a sequence of no-operations\n    // This is a fallback solution that at least produces valid output\n    for (int i = 0; i < 100000; i++) {\n        cout << \"....\" << endl;\n    }\n    \n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n#include <random>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    int type; // 0 for mackerel, 1 for sardine\n};\n\npair<int, int> optimize_axis(const vector<Point>& points_sorted, int fixed_min, int fixed_max, bool is_x_fixed) {\n    auto cmp_lower = [is_x_fixed](const Point& p, int val) {\n        if (is_x_fixed) return p.x < val;\n        else return p.y < val;\n    };\n    auto cmp_upper = [is_x_fixed](int val, const Point& p) {\n        if (is_x_fixed) return val < p.x;\n        else return val < p.y;\n    };\n\n    auto start_it = lower_bound(points_sorted.begin(), points_sorted.end(), fixed_min, cmp_lower);\n    auto end_it = upper_bound(points_sorted.begin(), points_sorted.end(), fixed_max, cmp_upper);\n\n    vector<int> value(100001, 0);\n    for (auto it = start_it; it != end_it; ++it) {\n        int coord;\n        if (is_x_fixed) {\n            coord = it->y;\n        } else {\n            coord = it->x;\n        }\n        if (it->type == 0) {\n            value[coord] += 1;\n        } else {\n            value[coord] -= 1;\n        }\n    }\n\n    vector<int> cum_net(100001);\n    cum_net[0] = value[0];\n    for (int i = 1; i <= 100000; i++) {\n        cum_net[i] = cum_net[i-1] + value[i];\n    }\n\n    int min_cum = 0;\n    int min_index = -1;\n    int best_diff = INT_MIN;\n    int best_a = 0, best_b = 0;\n\n    for (int i = 0; i <= 100000; i++) {\n        int diff = cum_net[i] - min_cum;\n        if (diff > best_diff) {\n            best_diff = diff;\n            best_a = min_index + 1;\n            best_b = i;\n        }\n        if (cum_net[i] < min_cum) {\n            min_cum = cum_net[i];\n            min_index = i;\n        }\n    }\n\n    if (best_a > best_b) {\n        swap(best_a, best_b);\n    }\n    if (best_a == best_b) {\n        if (best_b < 100000) {\n            best_b++;\n        } else if (best_a > 0) {\n            best_a--;\n        } else {\n            best_b++;\n        }\n    }\n\n    return {best_a, best_b};\n}\n\nint compute_score(const vector<Point>& points, int x1, int x2, int y1, int y2) {\n    int a = 0, b = 0;\n    for (const Point& p : points) {\n        if (p.x >= x1 && p.x <= x2 && p.y >= y1 && p.y <= y2) {\n            if (p.type == 0) a++;\n            else b++;\n        }\n    }\n    return a - b + 1;\n}\n\nvoid gradient_descent_refinement(const vector<Point>& points, int& x1, int& x2, int& y1, int& y2, int max_iterations) {\n    int current_score = compute_score(points, x1, x2, y1, y2);\n    \n    vector<int> steps = {1000, 500, 100, 50, 10, 5, 1};\n    \n    for (int step_size : steps) {\n        bool improved = true;\n        int iterations = 0;\n        \n        while (improved && iterations < max_iterations) {\n            improved = false;\n            iterations++;\n            \n            // Try all possible single-boundary moves\n            vector<pair<int*, int>> moves = {\n                {&x1, -step_size}, {&x1, step_size},\n                {&x2, -step_size}, {&x2, step_size},\n                {&y1, -step_size}, {&y1, step_size},\n                {&y2, -step_size}, {&y2, step_size}\n            };\n            \n            // Shuffle moves to avoid bias\n            random_device rd;\n            mt19937 g(rd());\n            shuffle(moves.begin(), moves.end(), g);\n            \n            for (auto& move : moves) {\n                int original = *move.first;\n                *move.first = original + move.second;\n                \n                // Check constraints\n                if (x1 >= x2 || y1 >= y2 || x1 < 0 || x2 > 100000 || y1 < 0 || y2 > 100000) {\n                    *move.first = original;\n                    continue;\n                }\n                \n                int perimeter = 2 * ((x2 - x1) + (y2 - y1));\n                if (perimeter > 400000) {\n                    *move.first = original;\n                    continue;\n                }\n                \n                int new_score = compute_score(points, x1, x2, y1, y2);\n                if (new_score > current_score) {\n                    current_score = new_score;\n                    improved = true;\n                } else {\n                    *move.first = original; // Revert if no improvement\n                }\n            }\n        }\n    }\n}\n\nvoid simulated_annealing_refinement(const vector<Point>& points, int& x1, int& x2, int& y1, int& y2, int iterations) {\n    int current_score = compute_score(points, x1, x2, y1, y2);\n    int best_score = current_score;\n    int best_x1 = x1, best_x2 = x2, best_y1 = y1, best_y2 = y2;\n    \n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> step_dis(-50, 50);\n    \n    double temperature = 1000.0;\n    double cooling_rate = 0.95;\n    \n    for (int i = 0; i < iterations; i++) {\n        // Save current state\n        int old_x1 = x1, old_x2 = x2, old_y1 = y1, old_y2 = y2;\n        int old_score = current_score;\n        \n        // Make a random move\n        x1 = max(0, min(100000, x1 + step_dis(gen)));\n        x2 = max(0, min(100000, x2 + step_dis(gen)));\n        y1 = max(0, min(100000, y1 + step_dis(gen)));\n        y2 = max(0, min(100000, y2 + step_dis(gen)));\n        \n        // Ensure valid rectangle\n        if (x1 >= x2 || y1 >= y2) {\n            x1 = old_x1; x2 = old_x2; y1 = old_y1; y2 = old_y2;\n            continue;\n        }\n        \n        // Check perimeter constraint\n        int perimeter = 2 * ((x2 - x1) + (y2 - y1));\n        if (perimeter > 400000) {\n            x1 = old_x1; x2 = old_x2; y1 = old_y1; y2 = old_y2;\n            continue;\n        }\n        \n        current_score = compute_score(points, x1, x2, y1, y2);\n        \n        // Always accept improving moves\n        if (current_score > old_score) {\n            if (current_score > best_score) {\n                best_score = current_score;\n                best_x1 = x1; best_x2 = x2; best_y1 = y1; best_y2 = y2;\n            }\n        } else {\n            // Accept worse moves with probability based on temperature\n            double acceptance_prob = exp((current_score - old_score) / temperature);\n            if (dis(gen) > acceptance_prob) {\n                // Revert move\n                x1 = old_x1; x2 = old_x2; y1 = old_y1; y2 = old_y2;\n                current_score = old_score;\n            }\n        }\n        \n        // Cool down\n        temperature *= cooling_rate;\n    }\n    \n    // Restore best found solution\n    x1 = best_x1; x2 = best_x2; y1 = best_y1; y2 = best_y2;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n\n    int N;\n    cin >> N;\n    vector<Point> points(2 * N);\n    for (int i = 0; i < 2 * N; i++) {\n        cin >> points[i].x >> points[i].y;\n        points[i].type = (i < N) ? 0 : 1;\n    }\n\n    vector<Point> mackerels(points.begin(), points.begin() + N);\n\n    // Sort points for optimize_axis\n    vector<Point> points_by_x = points;\n    sort(points_by_x.begin(), points_by_x.end(), [](const Point& a, const Point& b) {\n        return a.x < b.x;\n    });\n    vector<Point> points_by_y = points;\n    sort(points_by_y.begin(), points_by_y.end(), [](const Point& a, const Point& b) {\n        return a.y < b.y;\n    });\n\n    // Compute initial rectangles from different percentiles\n    vector<int> mackerels_x, mackerels_y;\n    for (const Point& p : mackerels) {\n        mackerels_x.push_back(p.x);\n        mackerels_y.push_back(p.y);\n    }\n    sort(mackerels_x.begin(), mackerels_x.end());\n    sort(mackerels_y.begin(), mackerels_y.end());\n\n    vector<pair<int, int>> initial_rectangles;\n    \n    // Min-max\n    initial_rectangles.push_back({mackerels_x[0], mackerels_x.back()});\n    initial_rectangles.push_back({mackerels_y[0], mackerels_y.back()});\n    \n    // Quartiles\n    initial_rectangles.push_back({mackerels_x[N/4], mackerels_x[3*N/4]});\n    initial_rectangles.push_back({mackerels_y[N/4], mackerels_y[3*N/4]});\n    \n    // 10th-90th percentiles\n    initial_rectangles.push_back({mackerels_x[N/10], mackerels_x[9*N/10]});\n    initial_rectangles.push_back({mackerels_y[N/10], mackerels_y[9*N/10]});\n    \n    // 5th-95th percentiles\n    initial_rectangles.push_back({mackerels_x[N/20], mackerels_x[19*N/20]});\n    initial_rectangles.push_back({mackerels_y[N/20], mackerels_y[19*N/20]});\n    \n    // 15th-85th percentiles\n    initial_rectangles.push_back({mackerels_x[3*N/20], mackerels_x[17*N/20]});\n    initial_rectangles.push_back({mackerels_y[3*N/20], mackerels_y[17*N/20]});\n\n    int best_score = INT_MIN;\n    int best_x1, best_x2, best_y1, best_y2;\n\n    for (int i = 0; i < 5; i++) {\n        int x1 = initial_rectangles[2*i].first;\n        int x2 = initial_rectangles[2*i].second;\n        int y1 = initial_rectangles[2*i+1].first;\n        int y2 = initial_rectangles[2*i+1].second;\n\n        // Extended optimization iterations\n        for (int iter = 0; iter < 15; iter++) {\n            auto new_y = optimize_axis(points_by_x, x1, x2, true);\n            y1 = new_y.first;\n            y2 = new_y.second;\n\n            auto new_x = optimize_axis(points_by_y, y1, y2, false);\n            x1 = new_x.first;\n            x2 = new_x.second;\n        }\n\n        // Apply gradient descent refinement\n        gradient_descent_refinement(points, x1, x2, y1, y2, 100);\n        \n        // Apply simulated annealing for final refinement\n        simulated_annealing_refinement(points, x1, x2, y1, y2, 500);\n\n        int score = compute_score(points, x1, x2, y1, y2);\n        if (score > best_score) {\n            best_score = score;\n            best_x1 = x1;\n            best_x2 = x2;\n            best_y1 = y1;\n            best_y2 = y2;\n        }\n    }\n\n    // Final refinement on the best rectangle\n    gradient_descent_refinement(points, best_x1, best_x2, best_y1, best_y2, 200);\n    simulated_annealing_refinement(points, best_x1, best_x2, best_y1, best_y2, 1000);\n\n    cout << 4 << endl;\n    cout << best_x1 << \" \" << best_y1 << endl;\n    cout << best_x2 << \" \" << best_y1 << endl;\n    cout << best_x2 << \" \" << best_y2 << endl;\n    cout << best_x1 << \" \" << best_y2 << endl;\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <tuple>\n\nusing namespace std;\n\nstruct Rectangle {\n    int index;\n    long long w, h;\n    long long area;\n    long long estimated_w, estimated_h;\n    long long penalty;\n};\n\nbool compare_by_area(const Rectangle& a, const Rectangle& b) {\n    return a.area > b.area;\n}\n\nbool compare_by_penalty_area_ratio(const Rectangle& a, const Rectangle& b) {\n    // Prefer rectangles with high area relative to their penalty\n    double ratio_a = (double)a.area / (a.penalty);\n    double ratio_b = (double)b.area / (b.penalty);\n    return ratio_a > ratio_b;\n}\n\nint main() {\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n    \n    vector<Rectangle> rects(N);\n    for (int i = 0; i < N; i++) {\n        cin >> rects[i].estimated_w >> rects[i].estimated_h;\n        rects[i].index = i;\n        rects[i].w = rects[i].estimated_w;\n        rects[i].h = rects[i].estimated_h;\n        rects[i].area = rects[i].estimated_w * rects[i].estimated_h;\n        rects[i].penalty = rects[i].estimated_w + rects[i].estimated_h;\n    }\n\n    // Simple approach: Always use all rectangles with optimized packing\n    for (int t = 0; t < T; t++) {\n        vector<tuple<int, int, char, int>> actions;\n        \n        // Use a simple rotation of strategies\n        int strategy = t % 3;\n        \n        vector<Rectangle> sorted_rects = rects;\n        \n        if (strategy == 0) {\n            sort(sorted_rects.begin(), sorted_rects.end(), compare_by_area);\n        } else if (strategy == 1) {\n            sort(sorted_rects.begin(), sorted_rects.end(), compare_by_penalty_area_ratio);\n        } else {\n            // Shuffle for variety\n            random_shuffle(sorted_rects.begin(), sorted_rects.end());\n        }\n        \n        long long current_width = 0, current_height = 0;\n        \n        for (const auto& rect : sorted_rects) {\n            long long w1 = rect.estimated_w, h1 = rect.estimated_h;\n            long long w2 = rect.estimated_h, h2 = rect.estimated_w;\n            \n            long long cost_up1 = max(current_width, w1) + (current_height + h1);\n            long long cost_up2 = max(current_width, w2) + (current_height + h2);\n            long long cost_left1 = (current_width + w1) + max(current_height, h1);\n            long long cost_left2 = (current_width + w2) + max(current_height, h2);\n            \n            long long min_cost = min({cost_up1, cost_up2, cost_left1, cost_left2});\n            \n            int rotation, reference;\n            char direction;\n            \n            if (min_cost == cost_up1) {\n                rotation = 0; direction = 'U';\n            } else if (min_cost == cost_up2) {\n                rotation = 1; direction = 'U';\n            } else if (min_cost == cost_left1) {\n                rotation = 0; direction = 'L';\n            } else {\n                rotation = 1; direction = 'L';\n            }\n            \n            reference = -1;\n            actions.push_back(make_tuple(rect.index, rotation, direction, reference));\n            \n            long long w = (rotation == 0) ? rect.estimated_w : rect.estimated_h;\n            long long h = (rotation == 0) ? rect.estimated_h : rect.estimated_w;\n            \n            if (direction == 'U') {\n                current_width = max(current_width, w);\n                current_height += h;\n            } else {\n                current_width += w;\n                current_height = max(current_height, h);\n            }\n        }\n        \n        // Sort actions by index to satisfy constraint\n        sort(actions.begin(), actions.end(), \n            [](const auto& a, const auto& b) { \n                return get<0>(a) < get<0>(b); \n            });\n        \n        // Output the placement plan\n        cout << actions.size() << endl;\n        for (const auto& action : actions) {\n            cout << get<0>(action) << \" \" << get<1>(action) << \" \" \n                 << get<2>(action) << \" \" << get<3>(action) << endl;\n        }\n        cout.flush();\n        \n        // Read measurement result\n        long long Wp, Hp;\n        cin >> Wp >> Hp;\n    }\n    \n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    int index;\n    int beauty;\n};\n\ndouble distance(const Point& a, const Point& b) {\n    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, H;\n    cin >> N >> M >> H;\n    \n    vector<int> A(N);\n    for (int i = 0; i < N; i++) {\n        cin >> A[i];\n    }\n    \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    vector<Point> points(N);\n    Point center = {500, 500, -1, 0}; // Circle center\n    for (int i = 0; i < N; i++) {\n        cin >> points[i].x >> points[i].y;\n        points[i].index = i;\n        points[i].beauty = A[i];\n    }\n    \n    // Sort points by distance from center (ascending) and beauty (ascending)\n    // Prefer points near center with low beauty as roots\n    vector<int> point_indices(N);\n    iota(point_indices.begin(), point_indices.end(), 0);\n    sort(point_indices.begin(), point_indices.end(), [&](int i, int j) {\n        double dist_i = distance(points[i], center);\n        double dist_j = distance(points[j], center);\n        if (abs(dist_i - dist_j) < 1e-9) {\n            return A[i] < A[j]; // Lower beauty first if same distance\n        }\n        return dist_i < dist_j;\n    });\n    \n    vector<int> parent(N, -1);\n    vector<int> depth(N, -1);\n    vector<bool> assigned(N, false);\n    \n    // Priority queue for BFS: (depth, -beauty, vertex)\n    // We want to process vertices with higher depth first, and for same depth,\n    // process lower beauty vertices first (to reserve high beauty for deeper positions)\n    auto cmp = [](const tuple<int, int, int>& a, const tuple<int, int, int>& b) {\n        if (get<0>(a) != get<0>(b)) return get<0>(a) < get<0>(b);\n        return get<1>(a) > get<1>(b); // Higher beauty has lower negative value\n    };\n    priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, decltype(cmp)> pq(cmp);\n    \n    // Assign roots starting from points near center with low beauty\n    for (int idx : point_indices) {\n        if (!assigned[idx] && depth[idx] == -1) {\n            // Make this point a root\n            parent[idx] = -1;\n            depth[idx] = 0;\n            assigned[idx] = true;\n            pq.push({0, -A[idx], idx});\n        }\n    }\n    \n    // Process vertices in BFS order with depth constraint\n    while (!pq.empty()) {\n        auto [current_depth, neg_beauty, u] = pq.top();\n        pq.pop();\n        \n        if (current_depth >= H) continue;\n        \n        // Sort neighbors by beauty descending (we want to assign high beauty vertices first)\n        vector<pair<int, int>> neighbors; // (beauty, vertex)\n        for (int v : adj[u]) {\n            if (!assigned[v]) {\n                neighbors.push_back({A[v], v});\n            }\n        }\n        \n        sort(neighbors.begin(), neighbors.end(), greater<pair<int, int>>());\n        \n        for (auto [beauty, v] : neighbors) {\n            if (!assigned[v] && depth[v] == -1) {\n                parent[v] = u;\n                depth[v] = current_depth + 1;\n                assigned[v] = true;\n                pq.push({depth[v], -A[v], v});\n            }\n        }\n    }\n    \n    // Output the parent array\n    for (int i = 0; i < N; i++) {\n        cout << parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << endl;\n    \n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main() {\n    const int N = 20;\n    vector<string> board(N);\n    for (int i = 0; i < N; i++) {\n        cin >> board[i];\n    }\n\n    vector<char> directions;\n    vector<int> indices;\n\n    for (int j = 0; j < N; j++) {\n        int max_r = -1;\n        int min_r = N;\n        bool has_oni = false;\n        for (int i = 0; i < N; i++) {\n            if (board[i][j] == 'x') {\n                has_oni = true;\n                if (i > max_r) max_r = i;\n                if (i < min_r) min_r = i;\n            }\n        }\n        if (!has_oni) continue;\n\n        bool safe_up = true;\n        for (int i = 0; i < max_r; i++) {\n            if (board[i][j] == 'o') {\n                safe_up = false;\n                break;\n            }\n        }\n\n        bool safe_down = true;\n        for (int i = min_r + 1; i < N; i++) {\n            if (board[i][j] == 'o') {\n                safe_down = false;\n                break;\n            }\n        }\n\n        int shifts_up = max_r + 1;\n        int shifts_down = N - min_r;\n\n        char dir;\n        int shifts;\n        if (safe_up && safe_down) {\n            if (shifts_up <= shifts_down) {\n                dir = 'U';\n                shifts = shifts_up;\n            } else {\n                dir = 'D';\n                shifts = shifts_down;\n            }\n        } else if (safe_up) {\n            dir = 'U';\n            shifts = shifts_up;\n        } else if (safe_down) {\n            dir = 'D';\n            shifts = shifts_down;\n        } else {\n            dir = 'U';\n            shifts = shifts_up;\n        }\n\n        for (int k = 0; k < shifts; k++) {\n            directions.push_back(dir);\n            indices.push_back(j);\n        }\n    }\n\n    for (size_t i = 0; i < directions.size(); i++) {\n        cout << directions[i] << \" \" << indices[i] << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\n// Fast simulation that estimates the error without running all 500,000 steps\nvoid fast_simulate(const vector<int>& a, const vector<int>& b, int L, vector<int>& t, int& error, const vector<int>& T, int steps = 10000) {\n    t.assign(a.size(), 0);\n    int current = 0;\n    vector<int> count(a.size(), 0);\n    int actual_steps = min(L, steps);\n    for (int week = 0; week < actual_steps; week++) {\n        t[current]++;\n        int times = count[current];\n        count[current]++;\n        if (times % 2 == 1) {\n            current = a[current];\n        } else {\n            current = b[current];\n        }\n    }\n    \n    // Scale the results to estimate the full simulation\n    if (actual_steps < L) {\n        double scale_factor = (double)L / actual_steps;\n        for (int i = 0; i < a.size(); i++) {\n            t[i] = round(t[i] * scale_factor);\n        }\n    }\n    \n    error = 0;\n    for (int i = 0; i < a.size(); i++) {\n        error += abs(t[i] - T[i]);\n    }\n}\n\nint main() {\n    int N, L;\n    cin >> N >> L;\n    vector<int> T(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n\n    auto start_time = chrono::high_resolution_clock::now();\n    \n    // Analyze the target distribution to adapt parameters\n    double variance = 0;\n    double mean = accumulate(T.begin(), T.end(), 0.0) / N;\n    for (int i = 0; i < N; i++) {\n        variance += (T[i] - mean) * (T[i] - mean);\n    }\n    variance /= N;\n    \n    // Adaptive parameters based on distribution characteristics\n    int initial_sim_steps = 20000 + static_cast<int>(variance / 500);\n    int optimization_sim_steps = 15000 + static_cast<int>(variance / 1000);\n    int final_sim_steps = 40000 + static_cast<int>(variance / 500);\n    int max_iterations = 600 + static_cast<int>(variance / 2000);\n    \n    // Phase 1: Fast proportional allocation\n    vector<double> target_ratio(N);\n    double total_T = accumulate(T.begin(), T.end(), 0.0);\n    for (int i = 0; i < N; i++) {\n        target_ratio[i] = T[i] / total_T;\n    }\n\n    vector<int> a(N), b(N);\n    for (int i = 0; i < N; i++) {\n        a[i] = (i + 1) % N;\n        b[i] = (i + N - 1) % N;\n    }\n\n    vector<int> desired_incoming(N);\n    int total_edges = 2 * N;\n    for (int i = 0; i < N; i++) {\n        desired_incoming[i] = round(target_ratio[i] * total_edges);\n    }\n    \n    int current_total = accumulate(desired_incoming.begin(), desired_incoming.end(), 0);\n    while (current_total != total_edges) {\n        if (current_total < total_edges) {\n            int best_idx = -1;\n            double best_ratio = -1;\n            for (int i = 0; i < N; i++) {\n                if (desired_incoming[i] < total_edges) {\n                    if (target_ratio[i] > best_ratio) {\n                        best_ratio = target_ratio[i];\n                        best_idx = i;\n                    }\n                }\n            }\n            if (best_idx != -1) {\n                desired_incoming[best_idx]++;\n                current_total++;\n            } else {\n                break;\n            }\n        } else {\n            int best_idx = -1;\n            double best_ratio = 2.0;\n            for (int i = 0; i < N; i++) {\n                if (desired_incoming[i] > 1) {\n                    if (target_ratio[i] < best_ratio) {\n                        best_ratio = target_ratio[i];\n                        best_idx = i;\n                    }\n                }\n            }\n            if (best_idx != -1) {\n                desired_incoming[best_idx]--;\n                current_total--;\n            } else {\n                break;\n            }\n        }\n    }\n\n    vector<int> pointer_targets;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < desired_incoming[i]; j++) {\n            pointer_targets.push_back(i);\n        }\n    }\n    \n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(pointer_targets.begin(), pointer_targets.end(), gen);\n    \n    for (int i = 0; i < N; i++) {\n        a[i] = pointer_targets[2 * i];\n        b[i] = pointer_targets[2 * i + 1];\n    }\n\n    // Phase 2: Optimized simulated annealing with adaptive parameters\n    vector<int> best_a = a;\n    vector<int> best_b = b;\n    vector<int> t(N);\n    int best_error;\n    fast_simulate(best_a, best_b, L, t, best_error, T, initial_sim_steps);\n    \n    double temperature = 100.0 * (1.0 + variance / 1000000.0);\n    const double cooling_rate = 0.93 - (variance / 50000000.0);\n    int no_improve_count = 0;\n    const int max_no_improve = 50;\n    \n    for (int iter = 0; iter < max_iterations; iter++) {\n        // Adaptive temperature adjustment\n        if (no_improve_count > max_no_improve / 2) {\n            temperature *= 1.1; // Increase temperature to escape local minima\n        }\n        \n        if (no_improve_count > max_no_improve) {\n            // Reset to best solution\n            a = best_a;\n            b = best_b;\n            temperature = 100.0;\n            no_improve_count = 0;\n        }\n        \n        // Make a change\n        int i = gen() % N;\n        int pointer_type = gen() % 2;\n        int old_value = (pointer_type == 0) ? a[i] : b[i];\n        int new_value = gen() % N;\n        \n        if (new_value == old_value) continue;\n        \n        // Apply change\n        if (pointer_type == 0) {\n            a[i] = new_value;\n        } else {\n            b[i] = new_value;\n        }\n        \n        // Evaluate with fast simulation\n        int current_error;\n        fast_simulate(a, b, L, t, current_error, T, optimization_sim_steps);\n        \n        // Simulated annealing acceptance\n        if (current_error < best_error) {\n            best_error = current_error;\n            best_a = a;\n            best_b = b;\n            no_improve_count = 0;\n        } else if (exp((best_error - current_error) / temperature) > (gen() % 1000) / 1000.0) {\n            // Accept worse solution with some probability\n            no_improve_count++;\n        } else {\n            // Revert change\n            if (pointer_type == 0) {\n                a[i] = old_value;\n            } else {\n                b[i] = old_value;\n            }\n            no_improve_count++;\n        }\n        \n        // Cool temperature\n        temperature *= cooling_rate;\n        \n        // Check time limit\n        auto current_time = chrono::high_resolution_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1800) {\n            break;\n        }\n    }\n    \n    // Phase 3: Final refinement with longer simulation\n    vector<int> final_t(N);\n    int final_error;\n    fast_simulate(best_a, best_b, L, final_t, final_error, T, final_sim_steps);\n    \n    // Output the best solution found\n    for (int i = 0; i < N; i++) {\n        cout << best_a[i] << \" \" << best_b[i] << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\n#include <random>\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (int i = 0; i < M; i++) {\n        cin >> G[i];\n    }\n    vector<City> cities(N);\n    for (int i = 0; i < N; i++) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].id = i;\n    }\n\n    // Calculate center points and use Morton code for spatial grouping\n    vector<int> x_center(N), y_center(N);\n    for (int i = 0; i < N; i++) {\n        x_center[i] = (cities[i].lx + cities[i].rx) / 2;\n        y_center[i] = (cities[i].ly + cities[i].ry) / 2;\n    }\n\n    // Improved Morton code calculation\n    vector<uint64_t> morton_codes(N);\n    for (int i = 0; i < N; i++) {\n        uint64_t code = 0;\n        for (int j = 0; j < 16; j++) {\n            code |= (uint64_t)((x_center[i] >> j) & 1) << (2 * j);\n            code |= (uint64_t)((y_center[i] >> j) & 1) << (2 * j + 1);\n        }\n        morton_codes[i] = code;\n    }\n\n    vector<int> indices(N);\n    iota(indices.begin(), indices.end(), 0);\n    sort(indices.begin(), indices.end(), [&](int i, int j) {\n        return morton_codes[i] < morton_codes[j];\n    });\n\n    // Create groups\n    vector<vector<int>> groups(M);\n    int start_idx = 0;\n    for (int i = 0; i < M; i++) {\n        int g_size = G[i];\n        groups[i].resize(g_size);\n        for (int j = 0; j < g_size; j++) {\n            groups[i][j] = indices[start_idx + j];\n        }\n        start_idx += g_size;\n    }\n\n    vector<pair<int, int>> collected_edges;\n    int queries_used = 0;\n\n    // Improved query strategy: prioritize larger groups and use overlapping windows\n    for (int i = 0; i < M; i++) {\n        if (queries_used >= Q) break;\n        int g = groups[i].size();\n        if (g < 2) continue;\n        \n        if (g <= L) {\n            // Query entire group if it fits\n            cout << \"? \" << g;\n            for (int city_id : groups[i]) {\n                cout << \" \" << city_id;\n            }\n            cout << endl;\n            cout.flush();\n            \n            for (int j = 0; j < g - 1; j++) {\n                int a, b;\n                cin >> a >> b;\n                collected_edges.push_back({min(a, b), max(a, b)});\n            }\n            queries_used++;\n        } else {\n            // Use overlapping windows for better connectivity\n            int window_size = L;\n            int step = max(1, L / 2); // 50% overlap\n            for (int start = 0; start < g - 1 && queries_used < Q; start += step) {\n                int end = min(start + window_size, g);\n                int size = end - start;\n                if (size < 2) break;\n                \n                cout << \"? \" << size;\n                for (int k = start; k < end; k++) {\n                    cout << \" \" << groups[i][k];\n                }\n                cout << endl;\n                cout.flush();\n                \n                for (int k = 0; k < size - 1; k++) {\n                    int a, b;\n                    cin >> a >> b;\n                    collected_edges.push_back({min(a, b), max(a, b)});\n                }\n                queries_used++;\n            }\n        }\n    }\n\n    // Use remaining queries to sample from the largest groups\n    int remaining_queries = Q - queries_used;\n    if (remaining_queries > 0) {\n        // Sort groups by size (descending)\n        vector<int> group_indices(M);\n        iota(group_indices.begin(), group_indices.end(), 0);\n        sort(group_indices.begin(), group_indices.end(), [&](int i, int j) {\n            return groups[i].size() > groups[j].size();\n        });\n        \n        mt19937 rng(42);\n        for (int i = 0; i < M && remaining_queries > 0; i++) {\n            int group_idx = group_indices[i];\n            int g = groups[group_idx].size();\n            if (g < 3) continue;\n            \n            // Sample a random subset\n            vector<int> sample_indices(g);\n            iota(sample_indices.begin(), sample_indices.end(), 0);\n            shuffle(sample_indices.begin(), sample_indices.end(), rng);\n            \n            int sample_size = min(L, g);\n            cout << \"? \" << sample_size;\n            for (int j = 0; j < sample_size; j++) {\n                cout << \" \" << groups[group_idx][sample_indices[j]];\n            }\n            cout << endl;\n            cout.flush();\n            \n            for (int j = 0; j < sample_size - 1; j++) {\n                int a, b;\n                cin >> a >> b;\n                collected_edges.push_back({min(a, b), max(a, b)});\n            }\n            remaining_queries--;\n        }\n    }\n\n    // Output final answer\n    cout << \"!\" << endl;\n    \n    // Create a set for fast lookup of queried edges\n    set<pair<int, int>> queried_edges;\n    for (auto& edge : collected_edges) {\n        queried_edges.insert(edge);\n    }\n\n    for (int i = 0; i < M; i++) {\n        vector<int>& group = groups[i];\n        int g = group.size();\n        \n        // Output group cities\n        for (int j = 0; j < g; j++) {\n            if (j > 0) cout << \" \";\n            cout << group[j];\n        }\n        cout << endl;\n        \n        if (g == 1) continue;\n\n        // Build MST using Kruskal's algorithm with priority for queried edges\n        vector<tuple<int, long long, int, int>> edges;\n        \n        for (int a = 0; a < g; a++) {\n            for (int b = a + 1; b < g; b++) {\n                int u = group[a], v = group[b];\n                pair<int, int> edge_key = {min(u, v), max(u, v)};\n                \n                // Calculate estimated distance using center points\n                long long dx = x_center[u] - x_center[v];\n                long long dy = y_center[u] - y_center[v];\n                long long dist_sq = dx * dx + dy * dy;\n                \n                // Priority: 0 for queried edges, 1 for non-queried\n                int priority = queried_edges.count(edge_key) ? 0 : 1;\n                edges.push_back({priority, dist_sq, u, v});\n            }\n        }\n\n        // Sort by priority then by estimated distance\n        sort(edges.begin(), edges.end(), [](const auto& a, const auto& b) {\n            if (get<0>(a) != get<0>(b)) return get<0>(a) < get<0>(b);\n            if (get<1>(a) != get<1>(b)) return get<1>(a) < get<1>(b);\n            if (get<2>(a) != get<2>(b)) return get<2>(a) < get<2>(b);\n            return get<3>(a) < get<3>(b);\n        });\n\n        // Union-Find for Kruskal's algorithm\n        vector<int> parent(g);\n        iota(parent.begin(), parent.end(), 0);\n        \n        function<int(int)> find = [&](int x) {\n            while (parent[x] != x) {\n                parent[x] = parent[parent[x]];\n                x = parent[x];\n            }\n            return x;\n        };\n\n        vector<pair<int, int>> selected_edges;\n        for (auto& edge : edges) {\n            int u = get<2>(edge), v = get<3>(edge);\n            \n            // Find indices of u and v in the group\n            int u_idx = -1, v_idx = -1;\n            for (int k = 0; k < g; k++) {\n                if (group[k] == u) u_idx = k;\n                if (group[k] == v) v_idx = k;\n                if (u_idx != -1 && v_idx != -1) break;\n            }\n            \n            int root_u = find(u_idx), root_v = find(v_idx);\n            if (root_u != root_v) {\n                selected_edges.push_back({u, v});\n                parent[root_u] = root_v;\n                if (selected_edges.size() == g - 1) break;\n            }\n        }\n\n        for (auto& e : selected_edges) {\n            cout << e.first << \" \" << e.second << endl;\n        }\n    }\n    \n    cout.flush();\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<pair<int, int>> points;\n    for (int i = 0; i < M; i++) {\n        int i_val, j_val;\n        cin >> i_val >> j_val;\n        points.push_back({i_val, j_val});\n    }\n\n    int cur_i = points[0].first;\n    int cur_j = points[0].second;\n    \n    // Track block positions (initially no blocks)\n    vector<vector<bool>> blocks(N, vector<bool>(N, false));\n\n    for (int idx = 1; idx < M; idx++) {\n        int target_i = points[idx].first;\n        int target_j = points[idx].second;\n\n        // Horizontal movement\n        while (cur_j != target_j) {\n            int dj = target_j - cur_j;\n            char dir = (dj > 0) ? 'R' : 'L';\n            int k = abs(dj);\n            \n            // Calculate slide distance\n            int slide_dist = 0;\n            int temp_j = cur_j;\n            while (true) {\n                int next_j = temp_j + (dj > 0 ? 1 : -1);\n                if (next_j < 0 || next_j >= N) break;\n                if (blocks[cur_i][next_j]) break;\n                slide_dist++;\n                temp_j = next_j;\n            }\n            \n            // Use slide if beneficial and possible\n            if (k <= slide_dist && \n                ((dj > 0 && target_j == N-1) || (dj < 0 && target_j == 0)) && \n                k >= 2) {\n                cout << \"S \" << dir << endl;\n                cur_j = target_j;\n            } else {\n                cout << \"M \" << dir << endl;\n                cur_j += (dj > 0 ? 1 : -1);\n            }\n        }\n\n        // Vertical movement\n        while (cur_i != target_i) {\n            int di = target_i - cur_i;\n            char dir = (di > 0) ? 'D' : 'U';\n            int k = abs(di);\n            \n            // Calculate slide distance\n            int slide_dist = 0;\n            int temp_i = cur_i;\n            while (true) {\n                int next_i = temp_i + (di > 0 ? 1 : -1);\n                if (next_i < 0 || next_i >= N) break;\n                if (blocks[next_i][cur_j]) break;\n                slide_dist++;\n                temp_i = next_i;\n            }\n            \n            // Use slide if beneficial and possible\n            if (k <= slide_dist && \n                ((di > 0 && target_i == N-1) || (di < 0 && target_i == 0)) && \n                k >= 2) {\n                cout << \"S \" << dir << endl;\n                cur_i = target_i;\n            } else {\n                cout << \"M \" << dir << endl;\n                cur_i += (di > 0 ? 1 : -1);\n            }\n        }\n    }\n\n    return 0;\n}"}}}