{"model_name":"llama-4-maverick","codes":{"1":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n\nusing namespace std;\n\nstruct Company {\n    int x, y, r, idx;\n    bool operator<(const Company& other) const {\n        return r > other.r;\n    }\n};\n\nint main() {\n    int n;\n    cin >> n;\n\n    vector<Company> companies(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n        companies[i].idx = i;\n    }\n\n    sort(companies.begin(), companies.end());\n\n    vector<vector<int>> grid(10000, vector<int>(10000, 0));\n    vector<vector<int>> rect(10000, vector<int>(10000, -1));\n\n    priority_queue<Company> pq;\n    for (const auto& company : companies) {\n        pq.push(company);\n    }\n\n    vector<vector<int>> ans(n, vector<int>(4));\n\n    while (!pq.empty()) {\n        Company company = pq.top();\n        pq.pop();\n\n        int x = company.x, y = company.y, r = company.r, idx = company.idx;\n\n        int size = sqrt(r);\n        int sx = max(0, x - size / 2), sy = max(0, y - size / 2);\n        int ex = min(10000, x + size / 2), ey = min(10000, y + size / 2);\n\n        // Find a suitable rectangle\n        bool found = false;\n        for (int i = sx; i < ex; ++i) {\n            for (int j = sy; j < ey; ++j) {\n                if (rect[i][j] == -1) {\n                    int a = i, b = j;\n                    int c = min(i + size, 10000), d = min(j + size, 10000);\n\n                    // Check if the rectangle is valid\n                    bool valid = true;\n                    for (int k = a; k < c; ++k) {\n                        for (int l = b; l < d; ++l) {\n                            if (rect[k][l] != -1) {\n                                valid = false;\n                                break;\n                            }\n                        }\n                        if (!valid) break;\n                    }\n\n                    if (valid) {\n                        ans[idx] = {a, b, c, d};\n                        for (int k = a; k < c; ++k) {\n                            for (int l = b; l < d; ++l) {\n                                rect[k][l] = idx;\n                            }\n                        }\n                        found = true;\n                        break;\n                    }\n                }\n            }\n            if (found) break;\n        }\n    }\n\n    for (const auto& a : ans) {\n        cout << a[0] << \" \" << a[1] << \" \" << a[2] << \" \" << a[3] << endl;\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <string>\n#include <random>\n\nusing namespace std;\n\nstruct State {\n    int x, y;\n    int score;\n    string path;\n    unordered_set<int> visited_tiles;\n\n    State(int x, int y, int score, string path, unordered_set<int> visited_tiles)\n        : x(x), y(y), score(score), path(path), visited_tiles(visited_tiles) {}\n};\n\nint main() {\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> tile_ids(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> tile_ids[i][j];\n        }\n    }\n\n    vector<vector<int>> scores(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> scores[i][j];\n        }\n    }\n\n    int initial_tile_id = tile_ids[si][sj];\n    unordered_set<int> initial_visited_tiles = {initial_tile_id};\n    State initial_state(si, sj, scores[si][sj], \"\", initial_visited_tiles);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    priority_queue<pair<int, State>> pq;\n    pq.emplace(initial_state.score, initial_state);\n\n    int max_score = initial_state.score;\n    string max_path = \"\";\n\n    for (int iter = 0; iter < 100000; ++iter) {\n        if (pq.empty()) break;\n        auto [score, state] = pq.top();\n        pq.pop();\n\n        if (score < max_score) continue;\n\n        vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n        vector<char> moves = {'U', 'D', 'L', 'R'};\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = state.x + directions[i].first;\n            int ny = state.y + directions[i].second;\n\n            if (nx < 0 || nx >= 50 || ny < 0 || ny >= 50) continue;\n\n            int next_tile_id = tile_ids[nx][ny];\n            if (state.visited_tiles.count(next_tile_id)) continue;\n\n            unordered_set<int> next_visited_tiles = state.visited_tiles;\n            next_visited_tiles.insert(next_tile_id);\n\n            int next_score = state.score + scores[nx][ny];\n            string next_path = state.path + moves[i];\n\n            State next_state(nx, ny, next_score, next_path, next_visited_tiles);\n\n            if (next_score > max_score) {\n                max_score = next_score;\n                max_path = next_path;\n            }\n\n            pq.emplace(next_score, next_state);\n        }\n    }\n\n    cout << max_path << endl;\n\n    return 0;\n}","ahc003":"#include <iostream>\n#include <queue>\n#include <vector>\n#include <unordered_map>\n#include <limits>\n\nusing namespace std;\n\nstruct Edge {\n    int to;\n    double weight;\n};\n\nusing Graph = vector<vector<Edge>>;\n\nstruct Node {\n    int id;\n    double distance;\n    bool operator>(const Node& other) const {\n        return distance > other.distance;\n    }\n};\n\nGraph buildGraph() {\n    Graph graph(30 * 30);\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            int id = i * 30 + j;\n            if (i > 0) graph[id].push_back({id - 30, 1}); // Up\n            if (i < 29) graph[id].push_back({id + 30, 1}); // Down\n            if (j > 0) graph[id].push_back({id - 1, 1}); // Left\n            if (j < 29) graph[id].push_back({id + 1, 1}); // Right\n        }\n    }\n    return graph;\n}\n\nstring dijkstra(Graph& graph, int source, int target) {\n    vector<double> distances(graph.size(), numeric_limits<double>::max());\n    vector<int> previous(graph.size(), -1);\n    distances[source] = 0;\n\n    priority_queue<Node, vector<Node>, greater<Node>> queue;\n    queue.push({source, 0});\n\n    while (!queue.empty()) {\n        Node node = queue.top();\n        queue.pop();\n        if (node.id == target) break;\n\n        for (const Edge& edge : graph[node.id]) {\n            double newDistance = distances[node.id] + edge.weight;\n            if (newDistance < distances[edge.to]) {\n                distances[edge.to] = newDistance;\n                previous[edge.to] = node.id;\n                queue.push({edge.to, newDistance});\n            }\n        }\n    }\n\n    string path;\n    int current = target;\n    while (current != source) {\n        int prev = previous[current];\n        if (prev == current - 1) path += 'R';\n        else if (prev == current + 1) path += 'L';\n        else if (prev == current - 30) path += 'D';\n        else if (prev == current + 30) path += 'U';\n        current = prev;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nvoid updateGraph(Graph& graph, const string& path, double actualLength) {\n    double totalWeight = 0;\n    for (char c : path) {\n        totalWeight += 1; // Assuming unit weight for simplicity\n    }\n    double scaleFactor = actualLength / totalWeight;\n\n    int currentNode = 0;\n    for (char c : path) {\n        int nextNode;\n        if (c == 'U') nextNode = currentNode - 30;\n        else if (c == 'D') nextNode = currentNode + 30;\n        else if (c == 'L') nextNode = currentNode - 1;\n        else if (c == 'R') nextNode = currentNode + 1;\n\n        for (Edge& edge : graph[currentNode]) {\n            if (edge.to == nextNode) {\n                edge.weight = (edge.weight + scaleFactor) / 2; // Simple moving average\n                break;\n            }\n        }\n        for (Edge& edge : graph[nextNode]) {\n            if (edge.to == currentNode) {\n                edge.weight = (edge.weight + scaleFactor) / 2; // Simple moving average\n                break;\n            }\n        }\n        currentNode = nextNode;\n    }\n}\n\nint main() {\n    Graph graph = buildGraph();\n    int si, sj, ti, tj;\n    double prevResult = 0;\n\n    for (int k = 0; k < 1000; ++k) {\n        cin >> si >> sj >> ti >> tj;\n        int source = si * 30 + sj;\n        int target = ti * 30 + tj;\n\n        string path = dijkstra(graph, source, target);\n        cout << path << endl;\n        cout.flush();\n\n        double actualLength;\n        cin >> actualLength;\n        updateGraph(graph, path, actualLength);\n        prevResult = actualLength;\n    }\n\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_M = 800;\nconst int MAX_LEN = 12;\n\nstruct StringInfo {\n    string s;\n    int len;\n    bool used;\n};\n\nint main() {\n    int M;\n    cin >> N >> M;\n    vector<StringInfo> strings(M);\n\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i].s;\n        strings[i].len = strings[i].s.length();\n        strings[i].used = false;\n    }\n\n    // Sort the strings in descending order of their lengths\n    sort(strings.begin(), strings.end(), [](const StringInfo& a, const StringInfo& b) {\n        return a.len > b.len;\n    });\n\n    vector<vector<char>> matrix(N, vector<char>(N, '.'));\n\n    mt19937 mt(42);\n    uniform_int_distribution<int> dist(0, N - 1);\n\n    for (const auto& s : strings) {\n        if (s.used) continue;\n\n        bool placed = false;\n        for (int trial = 0; trial < 100; ++trial) {\n            int i = dist(mt), j = dist(mt);\n            int dir = dist(mt) % 2; // 0: horizontal, 1: vertical\n\n            if (canPlaceString(matrix, s.s, i, j, dir)) {\n                placeString(matrix, s.s, i, j, dir);\n                placed = true;\n                break;\n            }\n        }\n\n        if (placed) {\n            // Mark the string as used\n            for (auto& str : strings) {\n                if (str.s == s.s) {\n                    str.used = true;\n                    break;\n                }\n            }\n        }\n    }\n\n    // Print the resulting matrix\n    for (const auto& row : matrix) {\n        for (char c : row) {\n            cout << c;\n        }\n        cout << endl;\n    }\n\n    return 0;\n}\n\nbool canPlaceString(vector<vector<char>>& matrix, const string& s, int i, int j, int dir) {\n    int N = matrix.size();\n    int len = s.length();\n\n    if (dir == 0) { // horizontal\n        for (int p = 0; p < len; ++p) {\n            int col = (j + p) % N;\n            if (matrix[i][col] != '.' && matrix[i][col] != s[p]) {\n                return false;\n            }\n        }\n    } else { // vertical\n        for (int p = 0; p < len; ++p) {\n            int row = (i + p) % N;\n            if (matrix[row][j] != '.' && matrix[row][j] != s[p]) {\n                return false;\n            }\n        }\n    }\n\n    return true;\n}\n\nvoid placeString(vector<vector<char>>& matrix, const string& s, int i, int j, int dir) {\n    int N = matrix.size();\n    int len = s.length();\n\n    if (dir == 0) { // horizontal\n        for (int p = 0; p < len; ++p) {\n            int col = (j + p) % N;\n            matrix[i][col] = s[p];\n        }\n    } else { // vertical\n        for (int p = 0; p < len; ++p) {\n            int row = (i + p) % N;\n            matrix[row][j] = s[p];\n        }\n    }\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Pos {\n    int i, j;\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n\n    // Grid preprocessing\n    vector<Pos> roadSquares;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                roadSquares.push_back({i, j});\n            }\n        }\n    }\n\n    // Visibility graph construction\n    unordered_map<Pos, vector<Pos>> visibilityGraph;\n    for (const auto& pos : roadSquares) {\n        vector<Pos> visibleSquares;\n        // Compute visible squares from pos\n        for (const auto& otherPos : roadSquares) {\n            if (isVisible(pos, otherPos, grid)) {\n                visibleSquares.push_back(otherPos);\n            }\n        }\n        visibilityGraph[pos] = visibleSquares;\n    }\n\n    // Route construction\n    vector<Pos> route;\n    unordered_set<Pos> visited;\n    Pos currentPos = {si, sj};\n    route.push_back(currentPos);\n    visited.insert(currentPos);\n\n    while (visited.size() < roadSquares.size()) {\n        Pos nextPos = getNearestUnvisitedSquare(currentPos, visibilityGraph, visited);\n        if (nextPos.i == -1) {\n            // Backtrack\n            currentPos = route.back();\n            route.pop_back();\n        } else {\n            route.push_back(nextPos);\n            visited.insert(nextPos);\n            currentPos = nextPos;\n        }\n    }\n\n    // Route optimization (2-opt)\n    optimizeRoute(route, grid);\n\n    // Output\n    outputRoute(route);\n\n    return 0;\n}\n\n// Helper functions\nbool isVisible(const Pos& pos, const Pos& otherPos, const vector<string>& grid) {\n    // Check if otherPos is visible from pos\n    if (pos.i == otherPos.i) {\n        int minJ = min(pos.j, otherPos.j);\n        int maxJ = max(pos.j, otherPos.j);\n        for (int j = minJ; j <= maxJ; j++) {\n            if (grid[pos.i][j] == '#') {\n                return false;\n            }\n        }\n        return true;\n    } else if (pos.j == otherPos.j) {\n        int minI = min(pos.i, otherPos.i);\n        int maxI = max(pos.i, otherPos.i);\n        for (int i = minI; i <= maxI; i++) {\n            if (grid[i][pos.j] == '#') {\n                return false;\n            }\n        }\n        return true;\n    }\n    return false;\n}\n\nPos getNearestUnvisitedSquare(const Pos& pos, const unordered_map<Pos, vector<Pos>>& visibilityGraph, const unordered_set<Pos>& visited) {\n    // Find nearest unvisited square visible from pos\n    for (const auto& otherPos : visibilityGraph.at(pos)) {\n        if (visited.find(otherPos) == visited.end()) {\n            return otherPos;\n        }\n    }\n    return {-1, -1}; // Not found\n}\n\nvoid optimizeRoute(vector<Pos>& route, const vector<string>& grid) {\n    // 2-opt algorithm to optimize the route\n    int N = route.size();\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 1; i < N - 2; i++) {\n            for (int j = i + 1; j < N - 1; j++) {\n                int oldCost = getTravelTime(route[i - 1], route[i], grid) + getTravelTime(route[j], route[j + 1], grid);\n                int newCost = getTravelTime(route[i - 1], route[j], grid) + getTravelTime(route[i], route[j + 1], grid);\n                if (newCost < oldCost) {\n                    reverse(route.begin() + i, route.begin() + j + 1);\n                    improved = true;\n                }\n            }\n        }\n    }\n}\n\nint getTravelTime(const Pos& pos1, const Pos& pos2, const vector<string>& grid) {\n    // Compute travel time between pos1 and pos2\n    if (abs(pos1.i - pos2.i) + abs(pos1.j - pos2.j) != 1) {\n        return numeric_limits<int>::max(); // Invalid move\n    }\n    int cost = grid[pos2.i][pos2.j] - '0';\n    return cost;\n}\n\nvoid outputRoute(const vector<Pos>& route) {\n    // Output the route as a sequence of moves\n    for (int i = 0; i < route.size() - 1; i++) {\n        Pos pos1 = route[i];\n        Pos pos2 = route[i + 1];\n        if (pos1.i > pos2.i) {\n            cout << 'U';\n        } else if (pos1.i < pos2.i) {\n            cout << 'D';\n        } else if (pos1.j > pos2.j) {\n            cout << 'L';\n        } else if (pos1.j < pos2.j) {\n            cout << 'R';\n        }\n    }\n    cout << endl;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Task {\n    vector<int> d;\n    vector<int> dependencies;\n    int status; // -1: not started, 0: started, 1: completed\n};\n\nstruct TeamMember {\n    vector<int> s; // estimated skill levels\n    int task; // current task being worked on, -1 if available\n    int endDay; // day when the current task will be completed\n};\n\nint main() {\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<Task> tasks(N);\n    for (int i = 0; i < N; i++) {\n        tasks[i].d.resize(K);\n        for (int j = 0; j < K; j++) {\n            cin >> tasks[i].d[j];\n        }\n        tasks[i].status = -1;\n    }\n\n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        tasks[v - 1].dependencies.push_back(u - 1);\n    }\n\n    vector<TeamMember> teamMembers(M);\n    for (int i = 0; i < M; i++) {\n        teamMembers[i].s.resize(K, 0); // initialize estimated skill levels to 0\n        teamMembers[i].task = -1;\n        teamMembers[i].endDay = 0;\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n\n        // receive the list of team members who have completed their tasks\n        int n;\n        cin >> n;\n        if (n == -1) break;\n\n        vector<int> completedTeamMembers(n);\n        for (int i = 0; i < n; i++) {\n            cin >> completedTeamMembers[i];\n            completedTeamMembers[i]--;\n        }\n\n        // update task status and team member status\n        for (int teamMember : completedTeamMembers) {\n            if (teamMembers[teamMember].task != -1) {\n                tasks[teamMembers[teamMember].task].status = 1;\n                teamMembers[teamMember].task = -1;\n            }\n        }\n\n        // estimate skill levels of team members\n        for (int teamMember : completedTeamMembers) {\n            // TO DO: implement skill level estimation\n        }\n\n        // get available tasks\n        vector<int> availableTasks;\n        for (int i = 0; i < N; i++) {\n            if (tasks[i].status == -1) {\n                bool ok = true;\n                for (int dependency : tasks[i].dependencies) {\n                    if (tasks[dependency].status != 1) {\n                        ok = false;\n                        break;\n                    }\n                }\n                if (ok) availableTasks.push_back(i);\n            }\n        }\n\n        // assign tasks to available team members\n        vector<pair<int, int>> assignments;\n        for (int teamMember = 0; teamMember < M; teamMember++) {\n            if (teamMembers[teamMember].task == -1 && !availableTasks.empty()) {\n                // TO DO: implement task assignment heuristic\n                int task = availableTasks.back();\n                availableTasks.pop_back();\n                teamMembers[teamMember].task = task;\n                tasks[task].status = 0;\n                assignments.emplace_back(teamMember + 1, task + 1);\n            }\n        }\n\n        // output assignments\n        cout << assignments.size();\n        for (auto& assignment : assignments) {\n            cout << \" \" << assignment.first << \" \" << assignment.second;\n        }\n        cout << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Order {\n    int id;\n    int a, b, c, d;\n};\n\nint calculateDistance(const pair<int, int>& p1, const pair<int, int>& p2) {\n    return abs(p1.first - p2.first) + abs(p1.second - p2.second);\n}\n\nint main() {\n    vector<Order> orders;\n    for (int i = 0; i < 1000; ++i) {\n        Order order;\n        order.id = i + 1;\n        cin >> order.a >> order.b >> order.c >> order.d;\n        orders.push_back(order);\n    }\n\n    // Greedy algorithm to select 50 orders\n    vector<Order> selectedOrders;\n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(orders.begin(), orders.end(), gen);\n    for (int i = 0; i < 50; ++i) {\n        selectedOrders.push_back(orders[i]);\n    }\n\n    // Local search to improve the solution\n    auto startTime = chrono::high_resolution_clock::now();\n    while (chrono::duration_cast<chrono::seconds>(chrono::high_resolution_clock::now() - startTime).count() < 1.9) {\n        // Perform local search iterations\n        int i = uniform_int_distribution<int>(0, selectedOrders.size() - 1)(gen);\n        int j = uniform_int_distribution<int>(0, orders.size() - 1)(gen);\n        if (find_if(selectedOrders.begin(), selectedOrders.end(), [&](const Order& order) { return order.id == orders[j].id; }) == selectedOrders.end()) {\n            // Replace the i-th order with the j-th order\n            selectedOrders[i] = orders[j];\n        }\n    }\n\n    // Construct the delivery route\n    vector<pair<int, int>> route;\n    route.push_back({400, 400});\n    for (const auto& order : selectedOrders) {\n        route.push_back({order.a, order.b});\n        route.push_back({order.c, order.d});\n    }\n    route.push_back({400, 400});\n\n    // Output the solution\n    cout << selectedOrders.size() << \" \";\n    for (const auto& order : selectedOrders) {\n        cout << order.id << \" \";\n    }\n    cout << endl;\n    cout << route.size() << \" \";\n    for (const auto& point : route) {\n        cout << point.first << \" \" << point.second << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <random>\n#include <cassert>\n\n// Union-Find data structure\nclass UnionFind {\npublic:\n    UnionFind(int n) : parent(n), rank(n, 0) {\n        for (int i = 0; i < n; ++i) {\n            parent[i] = i;\n        }\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\n    void unite(int x, int y) {\n        int root_x = find(x);\n        int root_y = find(y);\n        if (root_x != root_y) {\n            if (rank[root_x] < rank[root_y]) {\n                parent[root_x] = root_y;\n            } else {\n                parent[root_y] = root_x;\n                if (rank[root_x] == rank[root_y]) {\n                    ++rank[root_x];\n                }\n            }\n        }\n    }\n\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n\nprivate:\n    std::vector<int> parent;\n    std::vector<int> rank;\n};\n\nint main() {\n    const int N = 400;\n    const int M = 1995;\n\n    // Read vertex coordinates\n    std::vector<std::pair<int, int>> vertices(N);\n    for (auto& vertex : vertices) {\n        std::cin >> vertex.first >> vertex.second;\n    }\n\n    // Precompute Euclidean distances\n    std::vector<int> distances(M);\n    std::vector<std::pair<int, int>> edges(M);\n    for (int i = 0; i < M; ++i) {\n        std::cin >> edges[i].first >> edges[i].second;\n        int dx = vertices[edges[i].first].first - vertices[edges[i].second].first;\n        int dy = vertices[edges[i].first].second - vertices[edges[i].second].second;\n        distances[i] = std::round(std::sqrt(dx * dx + dy * dy));\n    }\n\n    // Initialize Union-Find data structure\n    UnionFind uf(N);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<double> dis(0.0, 1.0);\n\n    int count = 0;\n    for (int i = 0; i < M; ++i) {\n        int length;\n        std::cin >> length;\n\n        // Check if adopting the edge would form a cycle\n        if (uf.same(edges[i].first, edges[i].second)) {\n            // Edge is not necessary, reject with high probability if it's long\n            double prob = (length > 2 * distances[i]) ? 0.1 : 0.5;\n            bool adopt = dis(gen) < prob;\n            std::cout << (adopt ? \"1\" : \"0\") << std::endl;\n            std::cout.flush();\n            if (adopt) {\n                // Not expected to happen often, but handle it just in case\n                uf.unite(edges[i].first, edges[i].second);\n                count++;\n            }\n        } else {\n            // Edge is necessary, adopt it\n            std::cout << \"1\" << std::endl;\n            std::cout.flush();\n            uf.unite(edges[i].first, edges[i].second);\n            count++;\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 30;\nconst int DIR[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst char DIR_CHAR[4] = {'u', 'd', 'l', 'r'};\nconst char MOVE_CHAR[4] = {'U', 'D', 'L', 'R'};\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nint grid[N][N]; // 0: passable, 1: impassable\nvector<Pet> pets;\nvector<Human> humans;\n\nvoid bfs(int x, int y, vector<vector<bool>>& visited) {\n    queue<pair<int, int>> q;\n    q.emplace(x, y);\n    visited[x][y] = true;\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n        for (int i = 0; i < 4; ++i) {\n            int nx = x + DIR[i][0];\n            int ny = y + DIR[i][1];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0 && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n}\n\nchar getAction(int h) {\n    Human& human = humans[h];\n    int x = human.x;\n    int y = human.y;\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    bfs(x, y, visited);\n    int bestDir = -1;\n    int bestScore = -1;\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + DIR[i][0];\n        int ny = y + DIR[i][1];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0) {\n            // Check if making the square impassable is valid\n            bool valid = true;\n            for (int j = 0; j < 4; ++j) {\n                int nnx = nx + DIR[j][0];\n                int nny = ny + DIR[j][1];\n                if (nnx >= 0 && nnx < N && nny >= 0 && nny < N) {\n                    for (const Pet& pet : pets) {\n                        if (pet.x == nnx && pet.y == nny) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                }\n            }\n            if (!valid) continue;\n            // Simulate making the square impassable\n            grid[nx][ny] = 1;\n            vector<vector<bool>> newVisited(N, vector<bool>(N, false));\n            bfs(x, y, newVisited);\n            int newScore = 0;\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (newVisited[i][j]) ++newScore;\n                }\n            }\n            grid[nx][ny] = 0;\n            if (newScore > bestScore) {\n                bestScore = newScore;\n                bestDir = i;\n            }\n        }\n    }\n    if (bestDir != -1) {\n        return DIR_CHAR[bestDir];\n    } else {\n        // Try to move to an adjacent passable square\n        for (int i = 0; i < 4; ++i) {\n            int nx = x + DIR[i][0];\n            int ny = y + DIR[i][1];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0) {\n                return MOVE_CHAR[i];\n            }\n        }\n    }\n    return '.';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    cin >> N;\n    pets.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n        --pets[i].x;\n        --pets[i].y;\n    }\n    int M;\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].x >> humans[i].y;\n        --humans[i].x;\n        --humans[i].y;\n    }\n    for (int turn = 0; turn < 300; ++turn) {\n        string actions;\n        for (int h = 0; h < M; ++h) {\n            actions += getAction(h);\n        }\n        cout << actions << endl;\n        cout.flush();\n        // Read pet movements\n        for (int i = 0; i < N; ++i) {\n            string movement;\n            cin >> movement;\n            // Update pet positions\n            if (movement != \".\") {\n                for (char c : movement) {\n                    int dx = 0, dy = 0;\n                    if (c == 'U') dx = -1;\n                    if (c == 'D') dx = 1;\n                    if (c == 'L') dy = -1;\n                    if (c == 'R') dy = 1;\n                    pets[i].x += dx;\n                    pets[i].y += dy;\n                }\n            }\n        }\n        // Update human positions\n        for (int h = 0; h < M; ++h) {\n            char action = actions[h];\n            if (action == 'U') --humans[h].x;\n            if (action == 'D') ++humans[h].x;\n            if (action == 'L') --humans[h].y;\n            if (action == 'R') ++humans[h].y;\n        }\n    }\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    int sx, sy, tx, ty;\n    double p;\n    cin >> sx >> sy >> tx >> ty >> p;\n\n    vector<string> h(20), v(20);\n    for (int i = 0; i < 20; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < 19; ++i) {\n        cin >> v[i];\n    }\n\n    // BFS to find a initial path\n    queue<Pos> q;\n    vector<vector<bool>> visited(20, vector<bool>(20, false));\n    q.push({sx, sy});\n    visited[sx][sy] = true;\n    vector<vector<Pos>> parent(20, vector<Pos>(20, {-1, -1}));\n    while (!q.empty()) {\n        Pos curr = q.front(); q.pop();\n        if (curr.x == tx && curr.y == ty) break;\n        // Explore neighbors\n        for (auto dir : {make_pair(0, 1), make_pair(0, -1), make_pair(1, 0), make_pair(-1, 0)}) {\n            int nx = curr.x + dir.first, ny = curr.y + dir.second;\n            if (nx >= 0 && nx < 20 && ny >= 0 && ny < 20 && !visited[nx][ny]) {\n                if (dir.first == 0 && dir.second == 1 && h[curr.x][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == 0 && dir.second == -1 && h[curr.x][ny] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == 1 && dir.second == 0 && v[curr.x][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == -1 && dir.second == 0 && v[nx][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                }\n            }\n        }\n    }\n\n    // Reconstruct path\n    string path;\n    Pos curr = {tx, ty};\n    while (curr.x != sx || curr.y != sy) {\n        Pos prev = parent[curr.x][curr.y];\n        if (prev.x == curr.x - 1) path += 'D';\n        else if (prev.x == curr.x + 1) path += 'U';\n        else if (prev.y == curr.y - 1) path += 'R';\n        else if (prev.y == curr.y + 1) path += 'L';\n        curr = prev;\n    }\n    reverse(path.begin(), path.end());\n\n    // Simple improvement: Repeat the path to make it more robust\n    string robustPath = path;\n    while (robustPath.size() <= 180) {\n        robustPath += path;\n    }\n    robustPath.resize(200);\n\n    cout << robustPath << endl;\n\n    return 0;\n}","ahc010":"","ahc011":"","ahc012":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    long long x, y;\n};\n\nlong long cross(const Point& p1, const Point& p2) {\n    return p1.x * p2.y - p1.y * p2.x;\n}\n\nint main() {\n    int N, K;\n    cin >> N >> K;\n    vector<int> a(10);\n    for (int i = 0; i < 10; ++i) {\n        cin >> a[i];\n    }\n    vector<Point> strawberries(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> strawberries[i].x >> strawberries[i].y;\n    }\n\n    vector<pair<Point, Point>> cuts;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int i = 0; i < K; ++i) {\n        int idx1 = dis(gen);\n        int idx2 = dis(gen);\n        while (idx2 == idx1) {\n            idx2 = dis(gen);\n        }\n        Point p1 = strawberries[idx1];\n        Point p2 = strawberries[idx2];\n        cuts.emplace_back(p1, p2);\n    }\n\n    cout << cuts.size() << endl;\n    for (const auto& cut : cuts) {\n        cout << cut.first.x << \" \" << cut.first.y << \" \" << cut.second.x << \" \" << cut.second.y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <random>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nint N, M;\nvector<Point> dots;\nset<pair<int, int>> dot_set;\nvector<tuple<int, int, int, int, int, int, int, int>> operations;\n\nbool is_valid_rectangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    // Check if the four points form a rectangle\n    if ((x1 == x2 && y1 == y3 && x3 == x4 && y2 == y4) || (x1 == x3 && y1 == y2 && x2 == x4 && y3 == y4)) {\n        // Check if the rectangle is parallel to the axis or inclined at 45 degrees\n        if ((x1 == x2 && x3 == x4) || (y1 == y2 && y3 == y4) || (abs(x1 - x2) == abs(y1 - y2) && abs(x2 - x3) == abs(y2 - y3))) {\n            // Check if there are no dots other than the four points on the perimeter\n            for (int i = min(x1, min(x2, min(x3, x4))); i <= max(x1, max(x2, max(x3, x4))); i++) {\n                for (int j = min(y1, min(y2, min(y3, y4))); j <= max(y1, max(y2, max(y3, y4))); j++) {\n                    if (dot_set.find({i, j}) != dot_set.end() && (i, j) != (x1, y1) && (i, j) != (x2, y2) && (i, j) != (x3, y3) && (i, j) != (x4, y4)) {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    cin >> N >> M;\n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        dots.push_back({x, y});\n        dot_set.insert({x, y});\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int iter = 0; iter < 100000; iter++) {\n        if (iter % 1000 == 0) {\n            cout << \"Iteration \" << iter << endl;\n        }\n        int x1 = dis(gen);\n        int y1 = dis(gen);\n        if (dot_set.find({x1, y1}) != dot_set.end()) {\n            continue;\n        }\n        for (int i = 0; i < dots.size(); i++) {\n            for (int j = i + 1; j < dots.size(); j++) {\n                for (int k = j + 1; k < dots.size(); k++) {\n                    int x2 = dots[i].x;\n                    int y2 = dots[i].y;\n                    int x3 = dots[j].x;\n                    int y3 = dots[j].y;\n                    int x4 = dots[k].x;\n                    int y4 = dots[k].y;\n                    // Check all possible combinations of x1, y1, x2, y2, x3, y3, x4, y4\n                    if (is_valid_rectangle(x1, y1, x2, y2, x3, y3, x4, y4)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x2, y2, x3, y3, x4, y4});\n                        goto next_iter;\n                    }\n                    if (is_valid_rectangle(x1, y1, x2, y2, x4, y4, x3, y3)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x2, y2, x4, y4, x3, y3});\n                        goto next_iter;\n                    }\n                    if (is_valid_rectangle(x1, y1, x3, y3, x2, y2, x4, y4)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x3, y3, x2, y2, x4, y4});\n                        goto next_iter;\n                    }\n                    if (is_valid_rectangle(x1, y1, x3, y3, x4, y4, x2, y2)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x3, y3, x4, y4, x2, y2});\n                        goto next_iter;\n                    }\n                    if (is_valid_rectangle(x1, y1, x4, y4, x2, y2, x3, y3)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x4, y4, x2, y2, x3, y3});\n                        goto next_iter;\n                    }\n                    if (is_valid_rectangle(x1, y1, x4, y4, x3, y3, x2, y2)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x4, y4, x3, y3, x2, y2});\n                        goto next_iter;\n                    }\n                }\n            }\n        }\n        next_iter:;\n    }\n\n    cout << operations.size() << endl;\n    for (auto& op : operations) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << \" \" << get<4>(op) << \" \" << get<5>(op) << \" \" << get<6>(op) << \" \" << get<7>(op) << endl;\n    }\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nconst int N = 10;\nconst int flavors = 3;\n\nstruct CandyBox {\n    int grid[N][N];\n    int count[flavors + 1];\n\n    CandyBox() {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                grid[i][j] = 0;\n            }\n        }\n        for (int i = 1; i <= flavors; i++) {\n            count[i] = 0;\n        }\n    }\n\n    void placeCandy(int flavor, int pos) {\n        int emptyCount = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (grid[i][j] == 0) {\n                    emptyCount++;\n                    if (emptyCount == pos) {\n                        grid[i][j] = flavor;\n                        count[flavor]++;\n                        return;\n                    }\n                }\n            }\n        }\n    }\n\n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; j++) {\n                int writePos = 0;\n                for (int i = 0; i < N; i++) {\n                    if (grid[i][j] != 0) {\n                        grid[writePos++][j] = grid[i][j];\n                    }\n                }\n                for (int i = writePos; i < N; i++) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; j++) {\n                int writePos = N - 1;\n                for (int i = N - 1; i >= 0; i--) {\n                    if (grid[i][j] != 0) {\n                        grid[writePos--][j] = grid[i][j];\n                    }\n                }\n                for (int i = writePos; i >= 0; i--) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; i++) {\n                int writePos = 0;\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] != 0) {\n                        grid[i][writePos++] = grid[i][j];\n                    }\n                }\n                for (int j = writePos; j < N; j++) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'R') {\n            for (int i = 0; i < N; i++) {\n                int writePos = N - 1;\n                for (int j = N - 1; j >= 0; j--) {\n                    if (grid[i][j] != 0) {\n                        grid[i][writePos--] = grid[i][j];\n                    }\n                }\n                for (int j = writePos; j >= 0; j--) {\n                    grid[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    int evaluateScore() {\n        int score = 0;\n        for (int flavor = 1; flavor <= flavors; flavor++) {\n            vector<vector<bool>> visited(N, vector<bool>(N, false));\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] == flavor && !visited[i][j]) {\n                        int componentSize = 0;\n                        vector<pair<int, int>> stack = {{i, j}};\n                        visited[i][j] = true;\n                        while (!stack.empty()) {\n                            auto [x, y] = stack.back();\n                            stack.pop_back();\n                            componentSize++;\n                            for (auto [dx, dy] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                                int nx = x + dx;\n                                int ny = y + dy;\n                                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == flavor && !visited[nx][ny]) {\n                                    stack.emplace_back(nx, ny);\n                                    visited[nx][ny] = true;\n                                }\n                            }\n                        }\n                        score += componentSize * componentSize;\n                    }\n                }\n            }\n        }\n        int denominator = 0;\n        for (int i = 1; i <= flavors; i++) {\n            denominator += count[i] * count[i];\n        }\n        return denominator == 0 ? 0 : score / denominator;\n    }\n};\n\nint main() {\n    vector<int> flavors(100);\n    for (int i = 0; i < 100; i++) {\n        cin >> flavors[i];\n    }\n\n    CandyBox box;\n    for (int t = 0; t < 100; t++) {\n        int pos;\n        cin >> pos;\n        box.placeCandy(flavors[t], pos);\n\n        if (t == 99) break; // no need to output for the last tilt\n\n        char bestDir = 'F';\n        int bestScore = -1;\n        for (char dir : {'F', 'B', 'L', 'R'}) {\n            CandyBox simBox = box;\n            simBox.tilt(dir);\n            int score = simBox.evaluateScore();\n            if (score > bestScore) {\n                bestScore = score;\n                bestDir = dir;\n            }\n        }\n        cout << bestDir << endl;\n        box.tilt(bestDir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint M;\ndouble eps;\nint N = 20; // Example value, might need adjustment\n\n// Function to generate G_k\nstring generateGk(int k) {\n    string gk(N * (N - 1) / 2, '0');\n    // Simple strategy: add edges based on k\n    for (int i = 0; i < N * (N - 1) / 2 && i < k; ++i) {\n        gk[i] = '1';\n    }\n    return gk;\n}\n\n// Function to predict s_k from H_k\nint predictSk(const string& Hk, const vector<string>& G) {\n    int bestMatch = 0;\n    double minDistance = numeric_limits<double>::max();\n    for (int i = 0; i < M; ++i) {\n        double distance = 0;\n        for (int j = 0; j < N * (N - 1) / 2; ++j) {\n            distance += (Hk[j] != G[i][j]);\n        }\n        if (distance < minDistance) {\n            minDistance = distance;\n            bestMatch = i;\n        }\n    }\n    return bestMatch;\n}\n\nint main() {\n    cin >> M >> eps;\n    cout << N << endl;\n    vector<string> G(M);\n    for (int k = 0; k < M; ++k) {\n        G[k] = generateGk(k);\n        cout << G[k] << endl;\n    }\n    cout.flush();\n\n    for (int query = 0; query < 100; ++query) {\n        string Hk;\n        cin >> Hk;\n        int tk = predictSk(Hk, G);\n        cout << tk << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n#include <limits>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v, w, id;\n};\n\nint main() {\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    vector<Edge> edges(M);\n    vector<vector<pair<int, int>>> graph(N);\n\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[i] = {u, v, w, i};\n        graph[u].emplace_back(v, w);\n        graph[v].emplace_back(u, w);\n    }\n\n    // Read and ignore vertex coordinates\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // Initialize repair schedule randomly\n    vector<int> repairDay(M);\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(1, D);\n    for (auto& day : repairDay) {\n        day = dis(gen);\n    }\n\n    // Function to calculate frustration level for a given day\n    auto calculateFrustration = [&](const vector<int>& edgesForDay) {\n        // Create a temporary graph with edges for the day removed\n        vector<vector<pair<int, int>>> tempGraph = graph;\n        for (int edgeId : edgesForDay) {\n            Edge e = edges[edgeId];\n            // Remove edge e from tempGraph\n            tempGraph[e.u].erase(remove_if(tempGraph[e.u].begin(), tempGraph[e.u].end(), [&](const pair<int, int>& p){ return p.first == e.v; }), tempGraph[e.u].end());\n            tempGraph[e.v].erase(remove_if(tempGraph[e.v].begin(), tempGraph[e.v].end(), [&](const pair<int, int>& p){ return p.first == e.u; }), tempGraph[e.v].end());\n        }\n\n        // Calculate shortest paths using Dijkstra's algorithm\n        vector<vector<int>> dist(N, vector<int>(N, numeric_limits<int>::max()));\n        for (int i = 0; i < N; ++i) {\n            dist[i][i] = 0;\n            priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;\n            pq.emplace(0, i);\n            while (!pq.empty()) {\n                int d = pq.top().first, u = pq.top().second;\n                pq.pop();\n                if (d > dist[i][u]) continue;\n                for (const auto& e : tempGraph[u]) {\n                    if (dist[i][e.first] > d + e.second) {\n                        dist[i][e.first] = d + e.second;\n                        pq.emplace(dist[i][e.first], e.first);\n                    }\n                }\n            }\n        }\n\n        // Calculate frustration level\n        int frustration = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (dist[i][j] == numeric_limits<int>::max()) dist[i][j] = 1e9;\n                frustration += dist[i][j] - /* original shortest distance */;\n            }\n        }\n        return frustration;\n    };\n\n    // Main loop to improve the schedule\n    for (int iter = 0; iter < 10000; ++iter) {\n        // Select an edge and a new day for it\n        int edgeId = rand() % M;\n        int newDay = rand() % D + 1;\n        int oldDay = repairDay[edgeId];\n\n        // Check if moving the edge to the new day is valid and improves the schedule\n        vector<int>& oldDayEdges = /* get edges for oldDay */;\n        vector<int>& newDayEdges = /* get edges for newDay */;\n        if (newDayEdges.size() < K) {\n            // Temporarily move the edge\n            oldDayEdges.erase(remove(oldDayEdges.begin(), oldDayEdges.end(), edgeId), oldDayEdges.end());\n            newDayEdges.push_back(edgeId);\n\n            // Calculate new frustration levels\n            int oldFrustration = calculateFrustration(oldDayEdges) + calculateFrustration(newDayEdges);\n            int newFrustration = /* calculate frustration for oldDay without edgeId */ + /* calculate frustration for newDay with edgeId */;\n\n            if (newFrustration < oldFrustration) {\n                // Accept the move\n                repairDay[edgeId] = newDay;\n            } else {\n                // Revert the move\n                newDayEdges.pop_back();\n                oldDayEdges.push_back(edgeId);\n            }\n        }\n    }\n\n    // Output the final repair schedule\n    for (int i = 0; i < M; ++i) {\n        cout << repairDay[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <bitset>\n\nconst int MAX_D = 14;\nint D;\nstd::bitset<MAX_D> f[2][MAX_D][MAX_D];\nstd::bitset<MAX_D> r[2][MAX_D][MAX_D];\nint b[2][MAX_D * MAX_D * MAX_D];\n\nvoid input() {\n    std::cin >> D;\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            std::string s;\n            std::cin >> s;\n            for (int x = 0; x < D; ++x) {\n                f[i][z][x][x] = (s[x] == '1');\n            }\n        }\n        for (int z = 0; z < D; ++z) {\n            std::string s;\n            std::cin >> s;\n            for (int y = 0; y < D; ++y) {\n                r[i][z][y][y] = (s[y] == '1');\n            }\n        }\n    }\n}\n\nvoid solve() {\n    int n = 0;\n    for (int i = 0; i < 2; ++i) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[i][z][x][y] && r[i][z][y][x]) {\n                        b[i][x * D * D + y * D + z] = ++n;\n                    }\n                }\n            }\n        }\n    }\n\n    std::cout << n << std::endl;\n    for (int i = 0; i < D * D * D; ++i) {\n        std::cout << b[0][i] << \" \";\n    }\n    std::cout << std::endl;\n    for (int i = 0; i < D * D * D; ++i) {\n        std::cout << b[1][i] << \" \";\n    }\n    std::cout << std::endl;\n}\n\nint main() {\n    input();\n    solve();\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n    long long w;\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<pair<int, int>> vertices(N);\n    for (auto& [x, y] : vertices) {\n        cin >> x >> y;\n    }\n\n    vector<Edge> edges(M);\n    for (auto& [u, v, w] : edges) {\n        cin >> u >> v >> w;\n        u--; v--;\n    }\n\n    vector<pair<int, int>> residents(K);\n    for (auto& [a, b] : residents) {\n        cin >> a >> b;\n    }\n\n    // Minimum Spanning Tree\n    vector<int> parent(N, -1);\n    vector<bool> in_mst(M, false);\n    {\n        vector<pair<long long, int>> mst_edges;\n        for (int i = 0; i < M; i++) {\n            mst_edges.emplace_back(edges[i].w, i);\n        }\n        sort(mst_edges.begin(), mst_edges.end());\n        vector<int> rank(N, 0);\n        for (auto [w, idx] : mst_edges) {\n            auto& e = edges[idx];\n            int u = e.u, v = e.v;\n            while (u != v) {\n                if (rank[u] > rank[v]) swap(u, v);\n                if (parent[v] == -1) {\n                    parent[v] = u;\n                    break;\n                }\n                int next_v = parent[v];\n                if (rank[v] == rank[next_v]) rank[next_v]++;\n                v = next_v;\n            }\n            if (parent[v] == -1) in_mst[idx] = true;\n        }\n    }\n\n    // Resident Coverage\n    vector<int> output_strength(N, 0);\n    for (auto [a, b] : residents) {\n        int nearest_vertex = 0;\n        long long min_distance = (long long)1e18;\n        for (int i = 0; i < N; i++) {\n            auto [x, y] = vertices[i];\n            long long distance = (x - a) * (x - a) + (y - b) * (y - b);\n            if (distance < min_distance) {\n                min_distance = distance;\n                nearest_vertex = i;\n            }\n        }\n        output_strength[nearest_vertex] = max(output_strength[nearest_vertex], (int)ceil(sqrt(min_distance)) + 1);\n    }\n\n    // Graph Traversal\n    vector<bool> visited(N, false);\n    {\n        queue<int> q;\n        q.push(0);\n        visited[0] = true;\n        while (!q.empty()) {\n            int u = q.front(); q.pop();\n            for (int i = 0; i < M; i++) {\n                if (in_mst[i]) {\n                    auto& e = edges[i];\n                    if (e.u == u && !visited[e.v]) {\n                        visited[e.v] = true;\n                        output_strength[e.v] = max(output_strength[e.v], output_strength[u]);\n                        q.push(e.v);\n                    }\n                    if (e.v == u && !visited[e.u]) {\n                        visited[e.u] = true;\n                        output_strength[e.u] = max(output_strength[e.u], output_strength[u]);\n                        q.push(e.u);\n                    }\n                }\n            }\n        }\n    }\n\n    // Output\n    for (int p : output_strength) {\n        cout << p << \" \";\n    }\n    cout << endl;\n    for (auto& e : edges) {\n        cout << (in_mst[&e - &edges[0]] ? \"1\" : \"0\") << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n\nusing namespace std;\n\nconst int N = 30;\nconst int dx[] = {-1, -1, 0, 0, 1, 1};\nconst int dy[] = {-1, 0, -1, 1, 0, 1};\n\nstruct Ball {\n    int x, y, val;\n};\n\nint main() {\n    vector<vector<int>> pyramid(N);\n    for (int i = 0; i < N; ++i) {\n        pyramid[i].resize(i + 1);\n        for (int j = 0; j <= i; ++j) {\n            cin >> pyramid[i][j];\n        }\n    }\n\n    vector<tuple<int, int, int, int>> operations;\n    for (int i = N - 1; i > 0; --i) {\n        for (int j = 0; j <= i; ++j) {\n            int x = i, y = j;\n            while (x > 0) {\n                int parent_x = x - 1;\n                int parent_y = y;\n                if (y > parent_x) {\n                    parent_y = y - 1;\n                }\n                if (pyramid[x][y] < pyramid[parent_x][parent_y]) {\n                    swap(pyramid[x][y], pyramid[parent_x][parent_y]);\n                    operations.emplace_back(x, y, parent_x, parent_y);\n                }\n                x = parent_x;\n                y = parent_y;\n            }\n        }\n    }\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << endl;\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n\nusing namespace std;\n\nconst int D = 9;\nconst int directions[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nstruct Position {\n    int x, y;\n};\n\nint main() {\n    int N;\n    cin >> D >> N;\n\n    vector<vector<int>> grid(D, vector<int>(D, 0));\n    grid[0][(D - 1) / 2] = -1; // Entrance\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        grid[x][y] = -2; // Obstacle\n    }\n\n    vector<Position> containers;\n    unordered_set<int> containerSet;\n\n    for (int d = 0; d < D * D - 1 - N; ++d) {\n        int t;\n        cin >> t;\n\n        // Find a suitable position for the container using BFS\n        queue<Position> q;\n        vector<vector<bool>> visited(D, vector<bool>(D, false));\n        q.push({0, (D - 1) / 2});\n        visited[0][(D - 1) / 2] = true;\n\n        Position target;\n        bool found = false;\n\n        while (!q.empty()) {\n            Position p = q.front();\n            q.pop();\n\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + directions[i][0];\n                int ny = p.y + directions[i][1];\n\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !visited[nx][ny] && grid[nx][ny] == 0) {\n                    visited[nx][ny] = true;\n                    q.push({nx, ny});\n\n                    // Choose the last visited node as the target position\n                    target = {nx, ny};\n                    found = true;\n                }\n            }\n        }\n\n        if (found) {\n            grid[target.x][target.y] = t;\n            containers.push_back(target);\n            containerSet.insert(target.x * D + target.y);\n            cout << target.x << \" \" << target.y << endl;\n            cout.flush();\n        }\n    }\n\n    // Transport containers out\n    for (int i = 0; i < D * D - 1 - N; ++i) {\n        queue<Position> q;\n        vector<vector<bool>> visited(D, vector<bool>(D, false));\n        q.push({0, (D - 1) / 2});\n        visited[0][(D - 1) / 2] = true;\n\n        Position target;\n        int minNum = D * D;\n\n        while (!q.empty()) {\n            Position p = q.front();\n            q.pop();\n\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + directions[i][0];\n                int ny = p.y + directions[i][1];\n\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !visited[nx][ny]) {\n                    if (grid[nx][ny] >= 0 && grid[nx][ny] < minNum) {\n                        minNum = grid[nx][ny];\n                        target = {nx, ny};\n                    }\n\n                    visited[nx][ny] = true;\n                    q.push({nx, ny});\n                }\n            }\n        }\n\n        if (minNum != D * D) {\n            cout << target.x << \" \" << target.y << endl;\n            grid[target.x][target.y] = 0;\n        }\n    }\n\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n\nusing namespace std;\n\nconst int N = 50;\nconst int M = 100;\n\nint grid[N][N];\nint output[N][N];\nunordered_map<int, pair<int, int>> seeds;\nunordered_set<int> adjacentColors[M + 1];\n\nvoid readInput() {\n    int n, m;\n    cin >> n >> m;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> grid[i][j];\n            if (seeds.find(grid[i][j]) == seeds.end()) {\n                seeds[grid[i][j]] = {i, j};\n            }\n        }\n    }\n}\n\nvoid buildAdjacencyGraph() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int color = grid[i][j];\n            if (i > 0 && grid[i - 1][j] != color) {\n                adjacentColors[color].insert(grid[i - 1][j]);\n            }\n            if (j > 0 && grid[i][j - 1] != color) {\n                adjacentColors[color].insert(grid[i][j - 1]);\n            }\n            if (i < N - 1 && grid[i + 1][j] != color) {\n                adjacentColors[color].insert(grid[i + 1][j]);\n            }\n            if (j < N - 1 && grid[i][j + 1] != color) {\n                adjacentColors[color].insert(grid[i][j + 1]);\n            }\n        }\n    }\n}\n\nvoid processColors() {\n    vector<int> colors;\n    for (int i = 1; i <= M; i++) {\n        colors.push_back(i);\n    }\n    sort(colors.begin(), colors.end(), [](int a, int b) {\n        return adjacentColors[a].size() > adjacentColors[b].size();\n    });\n\n    for (int color : colors) {\n        int x = seeds[color].first;\n        int y = seeds[color].second;\n        output[x][y] = color;\n        queue<pair<int, int>> q;\n        q.push({x, y});\n        while (!q.empty()) {\n            x = q.front().first;\n            y = q.front().second;\n            q.pop();\n            if (x > 0 && grid[x - 1][y] == color && output[x - 1][y] == 0) {\n                output[x - 1][y] = color;\n                q.push({x - 1, y});\n            }\n            if (y > 0 && grid[x][y - 1] == color && output[x][y - 1] == 0) {\n                output[x][y - 1] = color;\n                q.push({x, y - 1});\n            }\n            if (x < N - 1 && grid[x + 1][y] == color && output[x + 1][y] == 0) {\n                output[x + 1][y] = color;\n                q.push({x + 1, y});\n            }\n            if (y < N - 1 && grid[x][y + 1] == color && output[x][y + 1] == 0) {\n                output[x][y + 1] = color;\n                q.push({x, y + 1});\n            }\n        }\n    }\n}\n\nvoid outputResult() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cout << output[i][j] << \" \";\n        }\n        cout << endl;\n    }\n}\n\nint main() {\n    readInput();\n    buildAdjacencyGraph();\n    processColors();\n    outputResult();\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n\nint main() {\n    int N, D, Q;\n    std::cin >> N >> D >> Q;\n\n    // Initialize random number generator\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> dis(0, N - 1);\n\n    // Estimate weights using random comparisons\n    std::vector<double> weights(N, 0.0);\n    for (int q = 0; q < Q; ++q) {\n        // Generate random subsets for comparison\n        std::vector<int> left, right;\n        for (int i = 0; i < N; ++i) {\n            if (dis(gen) % 2 == 0) {\n                left.push_back(i);\n            } else {\n                right.push_back(i);\n            }\n        }\n\n        // Output comparison query\n        std::cout << left.size() << \" \" << right.size() << \" \";\n        for (int i : left) {\n            std::cout << i << \" \";\n        }\n        for (int i : right) {\n            std::cout << i << \" \";\n        }\n        std::cout << std::endl;\n\n        // Read comparison result\n        char result;\n        std::cin >> result;\n\n        // Update weights based on comparison result\n        if (result == '<') {\n            for (int i : left) {\n                weights[i] -= 1.0;\n            }\n            for (int i : right) {\n                weights[i] += 1.0;\n            }\n        } else if (result == '>') {\n            for (int i : left) {\n                weights[i] += 1.0;\n            }\n            for (int i : right) {\n                weights[i] -= 1.0;\n            }\n        }\n    }\n\n    // Cluster or partition items into D subsets\n    std::vector<int> division(N);\n    // ... implement clustering or partitioning algorithm ...\n\n    // Output division\n    for (int i = 0; i < N; ++i) {\n        std::cout << division[i] << \" \";\n    }\n    std::cout << std::endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int n = 200;\nconst int m = 10;\n\nvector<int> stacks[m];\nbool carried_out[n + 1];\nvector<pair<int, int>> operations;\n\nvoid move_box(int v, int dest_stack) {\n    for (int i = 0; i < m; ++i) {\n        auto& stack = stacks[i];\n        if (find(stack.begin(), stack.end(), v) != stack.end()) {\n            int idx = distance(stack.begin(), find(stack.begin(), stack.end(), v));\n            int energy = stack.size() - idx;\n            operations.emplace_back(v, dest_stack + 1);\n            vector<int> temp(stack.begin() + idx, stack.end());\n            stack.erase(stack.begin() + idx, stack.end());\n            stacks[dest_stack].insert(stacks[dest_stack].end(), temp.begin(), temp.end());\n            return;\n        }\n    }\n}\n\nint main() {\n    int b[m][n / m];\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < n / m; ++j) {\n            cin >> b[i][j];\n            stacks[i].push_back(b[i][j]);\n        }\n    }\n\n    for (int v = 1; v <= n; ++v) {\n        int top_stack = -1;\n        for (int i = 0; i < m; ++i) {\n            if (!stacks[i].empty() && stacks[i].back() == v) {\n                top_stack = i;\n                break;\n            }\n        }\n\n        if (top_stack != -1) {\n            operations.emplace_back(v, 0);\n            carried_out[v] = true;\n            stacks[top_stack].pop_back();\n        } else {\n            // Find the stack containing v and move it to an appropriate stack\n            int src_stack = -1;\n            for (int i = 0; i < m; ++i) {\n                auto& stack = stacks[i];\n                auto it = find(stack.begin(), stack.end(), v);\n                if (it != stack.end()) {\n                    src_stack = i;\n                    break;\n                }\n            }\n\n            if (src_stack == -1) {\n                cerr << \"Box \" << v << \" not found.\" << endl;\n                return 1;\n            }\n\n            int dest_stack = -1;\n            int min_top = n + 1;\n            for (int i = 0; i < m; ++i) {\n                if (stacks[i].empty() || (stacks[i].back() > v && stacks[i].back() < min_top)) {\n                    dest_stack = i;\n                    min_top = stacks[i].empty() ? n + 1 : stacks[i].back();\n                }\n            }\n\n            if (dest_stack == -1) {\n                // If no suitable stack is found, just pick any non-empty stack\n                for (int i = 0; i < m; ++i) {\n                    if (!stacks[i].empty()) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n\n            move_box(v, dest_stack);\n            // After moving, check again if v is at the top\n            for (int i = 0; i < m; ++i) {\n                if (!stacks[i].empty() && stacks[i].back() == v) {\n                    operations.emplace_back(v, 0);\n                    carried_out[v] = true;\n                    stacks[i].pop_back();\n                    break;\n                }\n            }\n        }\n    }\n\n    for (const 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>\n#include <stack>\n#include <random>\n\nusing namespace std;\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<bool>> visited;\n\nvoid dfs(int i, int j, vector<char>& route) {\n    visited[i][j] = true;\n    int di[] = {0, 1, 0, -1};\n    int dj[] = {1, 0, -1, 0};\n    char dir[] = {'R', 'D', 'L', 'U'};\n\n    random_device rd;\n    mt19937 g(rd());\n    vector<int> directions = {0, 1, 2, 3};\n    shuffle(directions.begin(), directions.end(), g);\n\n    for (int k : directions) {\n        int i2 = i + di[k];\n        int j2 = j + dj[k];\n        if (0 <= i2 && i2 < N && 0 <= j2 && j2 < N && !visited[i2][j2]) {\n            if (di[k] == 0 && v[i][min(j, j2)] == '0' || dj[k] == 0 && h[min(i, i2)][j] == '0') {\n                route.push_back(dir[k]);\n                dfs(i2, j2, route);\n                route.push_back(dir[(k + 2) % 4]);\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> N;\n    h.resize(N - 1);\n    v.resize(N);\n    d.resize(N, vector<int>(N));\n    visited.resize(N, vector<bool>(N, false));\n\n    for (int i = 0; i < N - 1; i++) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\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<char> route;\n    dfs(0, 0, route);\n\n    // Simple route optimization: remove consecutive duplicates\n    string optimizedRoute;\n    for (char c : route) {\n        if (optimizedRoute.empty() || c != optimizedRoute.back()) {\n            optimizedRoute += c;\n        }\n    }\n\n    cout << optimizedRoute << endl;\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Position {\n    int i, j;\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n\n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> t[i];\n    }\n\n    unordered_map<char, vector<Position>> charPositions;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            charPositions[grid[i][j]].push_back({i, j});\n        }\n    }\n\n    vector<Position> currentPos = {{si, sj}};\n    string S = \"\";\n    vector<pair<int, int>> operations;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int step = 0; step < 5000; ++step) {\n        int bestI = -1, bestJ = -1;\n        int bestCost = 1e9;\n        char bestChar = '\\0';\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                int cost = abs(i - currentPos.back().i) + abs(j - currentPos.back().j) + 1;\n                char c = grid[i][j];\n                string newS = S + c;\n\n                // Simple heuristic: prefer characters that are the next character in some t_k\n                int score = 0;\n                for (const auto& tk : t) {\n                    for (int k = 0; k < tk.size(); ++k) {\n                        if (k < newS.size() && tk.substr(0, k) == newS.substr(newS.size() - k, k) && tk[k] == c) {\n                            score += (k + 1);\n                        }\n                    }\n                }\n\n                if (cost < bestCost || (cost == bestCost && score > 0)) {\n                    bool valid = true;\n                    for (const auto& op : operations) {\n                        if (op.first == i && op.second == j) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                    if (valid) {\n                        bestI = i;\n                        bestJ = j;\n                        bestCost = cost;\n                        bestChar = c;\n                    }\n                }\n            }\n        }\n\n        if (bestI != -1) {\n            currentPos.push_back({bestI, bestJ});\n            S += bestChar;\n            operations.push_back({bestI, bestJ});\n        } else {\n            // If no better move is found, just move to a random position\n            int i = dis(gen);\n            int j = dis(gen);\n            currentPos.push_back({i, j});\n            S += grid[i][j];\n            operations.push_back({i, j});\n        }\n    }\n\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc030":"int main() {\n    read_input();\n    vector<vector<int>> estimated_oil_reserves(N, vector<int>(N, -1));\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dis(0, N - 1);\n\n    for (int i = 0; i < N * N; ++i) {\n        int x = dis(gen);\n        int y = dis(gen);\n        if (estimated_oil_reserves[x][y] == -1) {\n            drill(x, y);\n            // Update estimated_oil_reserves based on the response\n        }\n    }\n\n    // Generate a guess based on estimated_oil_reserves\n    vector<pair<int, int>> guess_squares;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (estimated_oil_reserves[i][j] > 0) {\n                guess_squares.emplace_back(i, j);\n            }\n        }\n    }\n    guess(guess_squares);\n\n    return 0;\n}","ahc031":"```cpp\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int W = 1000;\n\nstruct Rectangle {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    int D, N;\n    cin >> D >> N;\n\n    vector<vector<int>> areas(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> areas[d][k];\n        }\n    }\n\n    vector<vector<Rectangle>> rectangles(D, vector<Rectangle>(N));\n\n    // Initial placement for the first day\n    vector<pair<int, int>> sizes(N);\n    for (int k = 0; k < N; k++) {\n        sizes[k] = {areas[0][k], k};\n    }\n    sort(sizes.begin(), sizes.end());\n\n    int x = 0, y = 0;\n    for (auto [area, k] : sizes) {\n        int w = min(W - x, (int)sqrt(area));\n        int h = (area + w - 1) / w;\n        rectangles[0][k] = {x, y, x + w, y + h};\n        x += w;\n        if (x >= W) {\n            x = 0;\n            y += h;\n        }\n    }\n\n    // Subsequent days\n    for (int d = 1; d < D; d++) {\n        vector<pair<int, int>> sizes(N);\n        for (int k = 0; k < N; k++) {\n            sizes[k] = {areas[d][k], k};\n        }\n        sort(sizes.begin(), sizes.end());\n\n        for (auto [area, k] : sizes) {\n            Rectangle prev_rect = rectangles[d - 1][k];\n            int w = min(W - prev_rect.x1, (int)sqrt(area));\n            int h = (area + w - 1) / w;\n            rectangles[d][k] = {prev_rect.x1, prev_rect.y1, prev_rect.x1 + w, prev_rect.y1 + h};\n        }\n    }\n\n    // Output the rectangle coordinates\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cout << rectangles[d][k].x1 << \" \" << rectangles[d][k].y1 << \" \" << rectangles[d][k].x2 << \" \" << rectangles[d][k].y2 << endl;\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nconst int N = 9;\nconst int MOD = 998244353;\n\nstruct Operation {\n    int stamp_id;\n    int x, y;\n};\n\nint grid[N][N];\nint stamps[20][3][3];\nvector<Operation> operations;\n\nint calculate_remainder_sum() {\n    int sum = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            sum = (sum + grid[i][j] % MOD) % MOD;\n        }\n    }\n    return sum;\n}\n\nbool apply_operation(int stamp_id, int x, int y) {\n    int new_grid[N][N];\n    copy(&grid[0][0], &grid[0][0] + N * N, &new_grid[0][0]);\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            new_grid[x + i][y + j] += stamps[stamp_id][i][j];\n        }\n    }\n    int new_sum = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            new_sum = (new_sum + new_grid[i][j] % MOD) % MOD;\n        }\n    }\n    int current_sum = calculate_remainder_sum();\n    if (new_sum > current_sum) {\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                grid[x + i][y + j] += stamps[stamp_id][i][j];\n            }\n        }\n        operations.push_back({stamp_id, x, y});\n        return true;\n    }\n    return false;\n}\n\nint main() {\n    int M, K;\n    cin >> N >> M >> K;\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 m = 0; m < M; ++m) {\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                cin >> stamps[m][i][j];\n            }\n        }\n    }\n\n    for (int k = 0; k < K; ++k) {\n        int best_stamp_id = -1, best_x = -1, best_y = -1;\n        int max_increase = 0;\n\n        for (int stamp_id = 0; stamp_id < M; ++stamp_id) {\n            for (int x = 0; x <= N - 3; ++x) {\n                for (int y = 0; y <= N - 3; ++y) {\n                    int new_grid[N][N];\n                    copy(&grid[0][0], &grid[0][0] + N * N, &new_grid[0][0]);\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            new_grid[x + i][y + j] += stamps[stamp_id][i][j];\n                        }\n                    }\n                    int new_sum = 0;\n                    for (int i = 0; i < N; ++i) {\n                        for (int j = 0; j < N; ++j) {\n                            new_sum = (new_sum + new_grid[i][j] % MOD) % MOD;\n                        }\n                    }\n                    int current_sum = calculate_remainder_sum();\n                    int increase = new_sum - current_sum;\n                    if (increase > max_increase) {\n                        max_increase = increase;\n                        best_stamp_id = stamp_id;\n                        best_x = x;\n                        best_y = y;\n                    }\n                }\n            }\n        }\n\n        if (max_increase > 0) {\n            apply_operation(best_stamp_id, best_x, best_y);\n        } else {\n            break;\n        }\n    }\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.stamp_id << \" \" << op.x << \" \" << op.y << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURN = 10000;\n\nstruct Crane {\n    int x, y;\n    bool holding;\n    int container;\n};\n\nint grid[N][N];\nCrane cranes[N];\nvector<int> containersToDispatch[N];\nint turn = 0;\n\nvoid simulate() {\n    // Simulate the container dispatch process\n    while (turn < MAX_TURN) {\n        // Bring in new containers\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][0] == -1 && !containersToDispatch[i].empty()) {\n                grid[i][0] = containersToDispatch[i].back();\n                containersToDispatch[i].pop_back();\n            }\n        }\n\n        // Determine the next action for each crane\n        string operations = \"\";\n        for (int i = 0; i < N; ++i) {\n            char operation = '.';\n            // Simple logic to move cranes towards the dispatch gates\n            if (cranes[i].y < N - 1 && !cranes[i].holding) {\n                operation = 'R';\n                cranes[i].y++;\n            } else if (cranes[i].holding && cranes[i].y == N - 1) {\n                operation = 'Q';\n                grid[cranes[i].x][cranes[i].y] = cranes[i].container;\n                cranes[i].holding = false;\n            } else if (!cranes[i].holding && grid[cranes[i].x][cranes[i].y] != -1) {\n                operation = 'P';\n                cranes[i].container = grid[cranes[i].x][cranes[i].y];\n                grid[cranes[i].x][cranes[i].y] = -1;\n                cranes[i].holding = true;\n            }\n            operations += operation;\n        }\n\n        // Dispatch containers\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][N - 1] != -1) {\n                // Dispatch the container\n                grid[i][N - 1] = -1;\n            }\n        }\n\n        // Output the operations for this turn\n        cout << operations << endl;\n\n        turn++;\n    }\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<vector<int>> A(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n            containersToDispatch[i].push_back(A[i][j]);\n        }\n        reverse(containersToDispatch[i].begin(), containersToDispatch[i].end());\n    }\n\n    // Initialize the grid and cranes\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = -1;\n        }\n        cranes[i].x = i;\n        cranes[i].y = 0;\n        cranes[i].holding = false;\n    }\n\n    simulate();\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 20;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nint h[N][N];\nint loaded = 0;\npair<int, int> pos = {0, 0};\n\nvoid load(int d) {\n    cout << \"+\" << d << endl;\n    h[pos.first][pos.second] -= d;\n    loaded += d;\n}\n\nvoid unload(int d) {\n    cout << \"-\" << d << endl;\n    h[pos.first][pos.second] += d;\n    loaded -= d;\n}\n\nvoid move(int d) {\n    cout << dir[d] << endl;\n    pos.first += dx[d];\n    pos.second += dy[d];\n}\n\nint main() {\n    cin >> N;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h[i][j];\n        }\n    }\n\n    // Initial loading/unloading at (0,0)\n    if (h[0][0] > 0) {\n        load(min(h[0][0], 1000000));\n    } else if (h[0][0] < 0) {\n        unload(min(-h[0][0], loaded));\n    }\n\n    // Greedy algorithm\n    priority_queue<pair<int, pair<int, int>>> pq;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (h[i][j] != 0) {\n                pq.push({abs(h[i][j]), {i, j}});\n            }\n        }\n    }\n\n    while (!pq.empty()) {\n        auto [val, pos2] = pq.top();\n        pq.pop();\n        int x = pos2.first, y = pos2.second;\n\n        // Move to (x, y)\n        int min_dist = abs(pos.first - x) + abs(pos.second - y);\n        while (pos.first != x || pos.second != y) {\n            for (int d = 0; d < 4; d++) {\n                int nx = pos.first + dx[d], ny = pos.second + dy[d];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N && abs(nx - x) + abs(ny - y) < min_dist) {\n                    move(d);\n                    min_dist = abs(pos.first - x) + abs(pos.second - y);\n                    break;\n                }\n            }\n        }\n\n        // Load/unload at (x, y)\n        if (h[x][y] > 0) {\n            load(min(h[x][y], 1000000));\n        } else if (h[x][y] < 0) {\n            unload(min(-h[x][y], loaded));\n        }\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Seed {\n    int id;\n    vector<int> eval;\n    int value;\n};\n\nbool compareSeeds(const Seed& a, const Seed& b) {\n    return a.value > b.value;\n}\n\nint main() {\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seedCount = 2 * N * (N - 1);\n    vector<Seed> seeds(seedCount);\n\n    for (int i = 0; i < seedCount; i++) {\n        seeds[i].id = i;\n        seeds[i].eval.resize(M);\n        seeds[i].value = 0;\n\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i].eval[j];\n            seeds[i].value += seeds[i].eval[j];\n        }\n    }\n\n    sort(seeds.begin(), seeds.end(), compareSeeds);\n\n    for (int t = 0; t < T; t++) {\n        vector<vector<int>> grid(N, vector<int>(N));\n\n        // Greedy grid arrangement\n        int idx = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                grid[i][j] = seeds[idx].id;\n                idx++;\n            }\n        }\n\n        // Output grid arrangement\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                else cout << endl;\n            }\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seedCount; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> seeds[i].eval[j];\n                seeds[i].value = 0;\n                for (int k = 0; k < M; k++) {\n                    seeds[i].value += seeds[i].eval[k];\n                }\n            }\n        }\n\n        sort(seeds.begin(), seeds.end(), compareSeeds);\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n\nint main() {\n    int N, M, V;\n    std::cin >> N >> M >> V;\n\n    std::vector<std::vector<int>> s(N, std::vector<int>(N));\n    std::vector<std::vector<int>> t(N, std::vector<int>(N));\n\n    for (int i = 0; i < N; ++i) {\n        std::string str;\n        std::cin >> str;\n        for (int j = 0; j < N; ++j) {\n            s[i][j] = str[j] - '0';\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        std::string str;\n        std::cin >> str;\n        for (int j = 0; j < N; ++j) {\n            t[i][j] = str[j] - '0';\n        }\n    }\n\n    // Design the robotic arm\n    int V_prime = std::min(V, M + 1);\n    std::cout << V_prime << std::endl;\n    for (int i = 1; i < V_prime; ++i) {\n        std::cout << 0 << \" \" << 1 << std::endl;\n    }\n\n    // Initial position of the root\n    int rx = N / 2, ry = N / 2;\n    std::cout << rx << \" \" << ry << std::endl;\n\n    // Sequence of operations\n    for (int turn = 0; turn < 100; ++turn) {\n        std::string op(2 * V_prime, '.');\n        // Simple random movement for demonstration\n        if (rx > 0 && rand() % 2) {\n            rx--;\n            op[0] = 'U';\n        } else if (rx < N - 1 && rand() % 2) {\n            rx++;\n            op[0] = 'D';\n        }\n        if (ry > 0 && rand() % 2) {\n            ry--;\n            op[0] = 'L';\n        } else if (ry < N - 1 && rand() % 2) {\n            ry++;\n            op[0] = 'R';\n        }\n\n        // Random rotation for demonstration\n        if (V_prime > 1 && rand() % 2) {\n            op[1] = 'L';\n        }\n\n        // Grab or release takoyaki for demonstration\n        if (rand() % 2) {\n            op[V_prime] = 'P';\n        }\n\n        std::cout << op << std::endl;\n    }\n\n    return 0;\n}","ahc039":"```cpp\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <queue>\n\nstruct Point {\n    int x, y;\n};\n\nint countMackerels(const std::vector<Point>& points, const std::vector<Point>& polygon) {\n    int count = 0;\n    for (const auto& point : points) {\n        if (point.x >= polygon[0].x && point.x <= polygon[1].x && point.y >= polygon[0].y && point.y <= polygon[2].y) {\n            count++;\n        }\n    }\n    return count;\n}\n\nint countSardines(const std::vector<Point>& points, const std::vector<Point>& polygon) {\n    int count = 0;\n    for (const auto& point : points) {\n        if (point.x >= polygon[0].x && point.x <= polygon[1].x && point.y >= polygon[0].y && point.y <= polygon[2].y) {\n            count++;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int N;\n    std::cin >> N;\n\n    std::vector<Point> mackerels(N);\n    std::vector<Point> sardines(N);\n\n    for (int i = 0; i < N; ++i) {\n        std::cin >> mackerels[i].x >> mackerels[i].y;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        std::cin >> sardines[i].x >> sardines[i].y;\n    }\n\n    int minX = std::min_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.x < b.x; })->x;\n    int maxX = std::max_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.x < b.x; })->x;\n    int minY = std::min_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.y < b.y; })->y;\n    int maxY = std::max_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.y < b.y; })->y;\n\n    std::vector<Point> polygon = {{minX, minY}, {maxX, minY}, {maxX, maxY}, {minX, maxY}};\n\n    std::vector<std::pair<int, int>> events;\n    for (const auto& mackerel : mackerels) {\n        events.push_back({mackerel.x, 1});\n    }\n    for (const auto& sardine : sardines) {\n        events.push_back({sardine.x, -1});\n    }\n    std::sort(events.begin(), events.end());\n\n    std::priority_queue<std::pair<int, int>> queue;\n    for (const auto& event : events) {\n        if (event.second == 1) {\n            queue.push({-event.first, event.first});\n        } else {\n            if (!queue.empty() && -queue.top().first == event.first) {\n                queue.pop();\n            }\n        }\n        if (!queue.empty()) {\n            int x = -queue.top().first;\n            int y = queue.top().second;\n            // Try to update the polygon\n            if (x > minX && x < maxX && y > minY && y < maxY) {\n                // Update the polygon to include the point (x, y)\n                // ...\n            }\n        }\n    }\n\n    std::cout << polygon.size() << std::endl;\n    for (const auto& point : polygon) {\n        std::cout << point.x << \" \" << point.y << std::endl;\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nstruct Rectangle {\n    int index;\n    int w, h;\n};\n\nbool compareRectangles(const Rectangle& a, const Rectangle& b) {\n    return std::max(a.w, a.h) > std::max(b.w, b.h);\n}\n\nint main() {\n    int N, T;\n    double sigma;\n    std::cin >> N >> T >> sigma;\n\n    std::vector<Rectangle> rectangles(N);\n    for (int i = 0; i < N; ++i) {\n        rectangles[i].index = i;\n        std::cin >> rectangles[i].w >> rectangles[i].h;\n    }\n\n    std::sort(rectangles.begin(), rectangles.end(), compareRectangles);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> dis(0, 1);\n\n    for (int t = 0; t < T; ++t) {\n        std::vector<Rectangle> placedRectangles;\n        std::vector<std::pair<int, int>> positions(N, std::make_pair(0, 0));\n\n        int n = N; // Number of rectangles to place\n\n        std::cout << n << std::endl;\n        for (int i = 0; i < n; ++i) {\n            Rectangle rect = rectangles[i];\n            int rotation = dis(gen);\n            char direction = (dis(gen) == 0) ? 'U' : 'L';\n            int reference = (i == 0) ? -1 : (dis(gen) == 0) ? -1 : placedRectangles[dis(gen) % placedRectangles.size()].index;\n\n            if (rotation == 1) {\n                std::swap(rect.w, rect.h);\n            }\n\n            std::cout << rect.index << \" \" << rotation << \" \" << direction << \" \" << reference << std::endl;\n\n            // Update the positions vector\n            if (direction == 'U') {\n                if (reference == -1) {\n                    positions[rect.index].first = 0;\n                    positions[rect.index].second = 0;\n                } else {\n                    // Find the reference rectangle and update the position accordingly\n                    for (const auto& placedRect : placedRectangles) {\n                        if (placedRect.index == reference) {\n                            positions[rect.index].first = positions[placedRect.index].first;\n                            positions[rect.index].second = positions[placedRect.index].second - rect.h;\n                            break;\n                        }\n                    }\n                }\n            } else {\n                if (reference == -1) {\n                    positions[rect.index].first = 0;\n                    positions[rect.index].second = 0;\n                } else {\n                    // Find the reference rectangle and update the position accordingly\n                    for (const auto& placedRect : placedRectangles) {\n                        if (placedRect.index == reference) {\n                            positions[rect.index].first = positions[placedRect.index].first + placedRect.w;\n                            positions[rect.index].second = positions[placedRect.index].second;\n                            break;\n                        }\n                    }\n                }\n            }\n\n            placedRectangles.push_back(rect);\n        }\n\n        std::cout.flush();\n\n        int W, H;\n        std::cin >> W >> H;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n};\n\nint main() {\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<Edge> edges(M);\n    for (int i = 0; i < M; i++) {\n        cin >> edges[i].u >> edges[i].v;\n    }\n\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n\n    // Initialize the parent of each vertex to -1\n    vector<int> parent(N, -1);\n\n    // Construct the rooted trees\n    vector<vector<int>> graph(N);\n    for (const auto& edge : edges) {\n        graph[edge.u].push_back(edge.v);\n        graph[edge.v].push_back(edge.u);\n    }\n\n    // Perform a BFS traversal to construct the rooted trees\n    queue<int> q;\n    q.push(0);\n    vector<bool> visited(N, false);\n    visited[0] = true;\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        for (int v : graph[u]) {\n            if (!visited[v]) {\n                visited[v] = true;\n                parent[v] = u;\n                q.push(v);\n            }\n        }\n    }\n\n    // Optimize the rooted trees using local search\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dis(0, N - 1);\n    for (int iter = 0; iter < 100000; iter++) {\n        int v = dis(gen);\n        if (parent[v] == -1) continue;\n        int p = parent[v];\n        int new_p = -1;\n        for (int u : graph[v]) {\n            if (u != p && (new_p == -1 || A[u] > A[new_p])) {\n                new_p = u;\n            }\n        }\n        if (new_p != -1 && A[new_p] > A[p]) {\n            parent[v] = new_p;\n        }\n    }\n\n    // Output the parent of each vertex\n    for (int i = 0; i < N; i++) {\n        cout << parent[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nconst int N = 20;\n\nint main() {\n    int n;\n    cin >> n;\n    vector<string> grid(n);\n    for (int i = 0; i < n; i++) {\n        cin >> grid[i];\n    }\n\n    vector<pair<char, int>> operations;\n\n    // Iterate through the grid to identify Oni positions\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            if (grid[i][j] == 'x') {\n                // Check if there is no Fukunokami in the upward direction\n                if (true) {\n                    int count = 0;\n                    for (int k = i - 1; k >= 0; k--) {\n                        if (grid[k][j] == 'o') {\n                            count = -1;\n                            break;\n                        }\n                        count++;\n                    }\n                    if (count != -1) {\n                        // Shift column j upward by i+1 times\n                        for (int k = 0; k <= i; k++) {\n                            operations.push_back({'U', j});\n                        }\n                        // Shift column j downward by i+1 times\n                        for (int k = 0; k <= i; k++) {\n                            operations.push_back({'D', j});\n                        }\n                        break;\n                    }\n                }\n\n                // Check if there is no Fukunokami in the downward direction\n                if (true) {\n                    int count = 0;\n                    for (int k = i + 1; k < n; k++) {\n                        if (grid[k][j] == 'o') {\n                            count = -1;\n                            break;\n                        }\n                        count++;\n                    }\n                    if (count != -1) {\n                        // Shift column j downward by n-i times\n                        for (int k = i; k < n - 1; k++) {\n                            operations.push_back({'D', j});\n                        }\n                        // Shift column j upward by n-i times\n                        for (int k = i; k < n - 1; k++) {\n                            operations.push_back({'U', j});\n                        }\n                        break;\n                    }\n                }\n\n                // Check if there is no Fukunokami in the leftward direction\n                if (true) {\n                    int count = 0;\n                    for (int k = j - 1; k >= 0; k--) {\n                        if (grid[i][k] == 'o') {\n                            count = -1;\n                            break;\n                        }\n                        count++;\n                    }\n                    if (count != -1) {\n                        // Shift row i leftward by j+1 times\n                        for (int k = 0; k <= j; k++) {\n                            operations.push_back({'L', i});\n                        }\n                        // Shift row i rightward by j+1 times\n                        for (int k = 0; k <= j; k++) {\n                            operations.push_back({'R', i});\n                        }\n                        break;\n                    }\n                }\n\n                // Check if there is no Fukunokami in the rightward direction\n                if (true) {\n                    int count = 0;\n                    for (int k = j + 1; k < n; k++) {\n                        if (grid[i][k] == 'o') {\n                            count = -1;\n                            break;\n                        }\n                        count++;\n                    }\n                    if (count != -1) {\n                        // Shift row i rightward by n-j times\n                        for (int k = j; k < n - 1; k++) {\n                            operations.push_back({'R', i});\n                        }\n                        // Shift row i leftward by n-j times\n                        for (int k = j; k < n - 1; k++) {\n                            operations.push_back({'L', i});\n                        }\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    // Output the sequence of operations\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nconst int N = 100;\nconst int L = 500000;\n\nvector<int> T(N);\nvector<int> a(N), b(N);\nvector<int> count(N, 0);\nmt19937 mt(42);\n\nvoid simulate(int steps) {\n    uniform_int_distribution<int> dist(0, N-1);\n    for (int step = 0; step < steps; ++step) {\n        int i = dist(mt);\n        int orig_a = a[i], orig_b = b[i];\n        int new_a = dist(mt), new_b = dist(mt);\n        a[i] = new_a;\n        b[i] = new_b;\n        count.assign(N, 0);\n        int last = 0;\n        count[0] = 1;\n        for (int t = 1; t < L; ++t) {\n            int next = (count[last] % 2 == 0) ? b[last] : a[last];\n            count[next]++;\n            last = next;\n        }\n        int new_error = accumulate(count.begin(), count.end(), 0, [&](int sum, int c, int i) { return sum + abs(c - T[i]); });\n        if (new_error > accumulate(count.begin(), count.end(), 0, [&](int sum, int c, int i) { return sum + abs(c - T[i]); })) {\n            a[i] = orig_a;\n            b[i] = orig_b;\n        }\n    }\n}\n\nint main() {\n    cin >> N >> L;\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    // Initialize a and b\n    for (int i = 0; i < N; ++i) {\n        a[i] = (i + 1) % N;\n        b[i] = (i + 2) % N;\n    }\n\n    simulate(100000);\n\n    for (int i = 0; i < N; ++i) {\n        cout << a[i] << \" \" << b[i] << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cassert>\n\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double x, y;\n};\n\nstruct Edge {\n    int u, v;\n};\n\nint N, M, Q, L, W;\nvector<int> G;\nvector<City> cities;\nvector<vector<int>> groups;\nvector<vector<Edge>> edges;\n\nvoid readInput() {\n    cin >> N >> M >> Q >> L >> W;\n    G.resize(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n    cities.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].id = i;\n        cities[i].x = (cities[i].lx + cities[i].rx) / 2.0;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2.0;\n    }\n}\n\nvoid initialGrouping() {\n    sort(cities.begin(), cities.end(), [](const City& a, const City& b) {\n        return make_pair(a.x, a.y) < make_pair(b.x, b.y);\n    });\n    groups.resize(M);\n    int start = 0;\n    for (int i = 0; i < M; ++i) {\n        groups[i].resize(G[i]);\n        for (int j = 0; j < G[i]; ++j) {\n            groups[i][j] = cities[start + j].id;\n        }\n        start += G[i];\n    }\n}\n\nvoid queryFortuneTeller(const vector<int>& group) {\n    if (group.size() <= 1) return;\n    vector<Edge> mstEdges;\n    if (group.size() <= L) {\n        cout << \"? \" << group.size();\n        for (int city : group) cout << \" \" << city;\n        cout << endl;\n        for (int i = 0; i < group.size() - 1; ++i) {\n            int u, v;\n            cin >> u >> v;\n            mstEdges.push_back({u, v});\n        }\n        edges.push_back(mstEdges);\n    } else {\n        // For larger groups, divide them into smaller subsets and query\n        for (size_t i = 0; i < group.size(); i += L - 1) {\n            vector<int> subset;\n            for (size_t j = i; j < min(i + L - 1, group.size()); ++j) {\n                subset.push_back(group[j]);\n            }\n            if (subset.size() > 1) {\n                cout << \"? \" << subset.size();\n                for (int city : subset) cout << \" \" << city;\n                cout << endl;\n                vector<Edge> subsetMstEdges;\n                for (int k = 0; k < subset.size() - 1; ++k) {\n                    int u, v;\n                    cin >> u >> v;\n                    subsetMstEdges.push_back({u, v});\n                }\n                mstEdges.insert(mstEdges.end(), subsetMstEdges.begin(), subsetMstEdges.end());\n            }\n        }\n        edges.push_back(mstEdges);\n    }\n}\n\nvoid buildRoads() {\n    edges.clear();\n    for (const auto& group : groups) {\n        queryFortuneTeller(group);\n    }\n}\n\nvoid outputAnswer() {\n    cout << \"!\" << endl;\n    for (size_t i = 0; i < groups.size(); ++i) {\n        for (int city : groups[i]) cout << city << \" \";\n        cout << endl;\n        for (const auto& edge : edges[i]) cout << edge.u << \" \" << edge.v << endl;\n    }\n}\n\nint main() {\n    readInput();\n    initialGrouping();\n    buildRoads();\n    outputAnswer();\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n\nusing namespace std;\n\nconst int N = 20;\nconst int M = 40;\nint grid[N][N]; // 0: empty, 1: block\n\nstruct Pos {\n    int x, y;\n};\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dirChar[] = {'U', 'D', 'L', 'R'};\n\nint manhattanDistance(Pos a, Pos b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvoid slide(int x, int y, int dir, Pos &end) {\n    int nx = x + dx[dir];\n    int ny = y + dy[dir];\n    while (0 <= nx && nx < N && 0 <= ny && ny < N && grid[nx][ny] == 0) {\n        x = nx;\n        y = ny;\n        nx += dx[dir];\n        ny += dy[dir];\n    }\n    end.x = x;\n    end.y = y;\n}\n\nvoid solve() {\n    int M;\n    cin >> N >> M;\n    Pos pos;\n    cin >> pos.x >> pos.y;\n    vector<Pos> targets(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> targets[i].x >> targets[i].y;\n    }\n\n    for (int targetIndex = 0; targetIndex < M; ++targetIndex) {\n        Pos target = targets[targetIndex];\n        while (pos.x != target.x || pos.y != target.y) {\n            int bestDir = -1;\n            char bestAction = ' ';\n            Pos nextPos = pos;\n            int minDist = manhattanDistance(pos, target);\n\n            for (int dir = 0; dir < 4; ++dir) {\n                int nx = pos.x + dx[dir];\n                int ny = pos.y + dy[dir];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                    // Try Move\n                    if (grid[nx][ny] == 0) {\n                        int dist = manhattanDistance({nx, ny}, target);\n                        if (dist < minDist) {\n                            minDist = dist;\n                            bestDir = dir;\n                            bestAction = 'M';\n                            nextPos = {nx, ny};\n                        }\n                    }\n\n                    // Try Slide\n                    Pos slideEnd = pos;\n                    slide(pos.x, pos.y, dir, slideEnd);\n                    if (slideEnd.x != pos.x || slideEnd.y != pos.y) {\n                        int dist = manhattanDistance(slideEnd, target);\n                        if (dist < minDist && (slideEnd.x != target.x || slideEnd.y != target.y)) {\n                            minDist = dist;\n                            bestDir = dir;\n                            bestAction = 'S';\n                            nextPos = slideEnd;\n                        }\n                    }\n                }\n\n                // Try Alter\n                if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                    int originalBlock = grid[nx][ny];\n                    grid[nx][ny] = 1 - originalBlock;\n                    Pos slideEndAfterAlter = pos;\n                    slide(pos.x, pos.y, dir, slideEndAfterAlter);\n                    int dist = manhattanDistance(slideEndAfterAlter, target);\n                    if (dist < minDist && (slideEndAfterAlter.x != target.x || slideEndAfterAlter.y != target.y)) {\n                        minDist = dist;\n                        bestDir = dir;\n                        bestAction = 'A';\n                        nextPos = pos; // Alter doesn't change pos\n                    }\n                    grid[nx][ny] = originalBlock; // Revert\n                }\n            }\n\n            if (bestAction != ' ') {\n                cout << bestAction << \" \" << dirChar[bestDir] << endl;\n                if (bestAction == 'M') {\n                    pos = nextPos;\n                } else if (bestAction == 'S') {\n                    pos = nextPos;\n                } else if (bestAction == 'A') {\n                    int nx = pos.x + dx[bestDir];\n                    int ny = pos.y + dy[bestDir];\n                    grid[nx][ny] = 1 - grid[nx][ny];\n                }\n            } else {\n                // Fallback, should ideally not reach here\n                cout << \"M U\" << endl;\n            }\n        }\n    }\n}\n\nint main() {\n    solve();\n    return 0;\n}"},"2":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n\nusing namespace std;\n\nstruct Company {\n    int x, y, r, idx;\n    bool operator<(const Company& other) const {\n        return r > other.r;\n    }\n};\n\nint main() {\n    int n;\n    cin >> n;\n\n    vector<Company> companies(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n        companies[i].idx = i;\n    }\n\n    sort(companies.begin(), companies.end());\n\n    vector<vector<int>> grid(10000, vector<int>(10000, 0));\n    vector<vector<int>> rect(10000, vector<int>(10000, -1));\n\n    priority_queue<Company> pq;\n    for (const auto& company : companies) {\n        pq.push(company);\n    }\n\n    vector<vector<int>> ans(n, vector<int>(4));\n\n    while (!pq.empty()) {\n        Company company = pq.top();\n        pq.pop();\n\n        int x = company.x, y = company.y, r = company.r, idx = company.idx;\n\n        int size = sqrt(r);\n        int sx = max(0, x - size / 2), sy = max(0, y - size / 2);\n        int ex = min(10000, x + size / 2), ey = min(10000, y + size / 2);\n\n        // Find a suitable rectangle\n        bool found = false;\n        for (int i = sx; i < ex; ++i) {\n            for (int j = sy; j < ey; ++j) {\n                if (rect[i][j] == -1) {\n                    int a = i, b = j;\n                    int c = min(i + size, 10000), d = min(j + size, 10000);\n\n                    // Check if the rectangle is valid\n                    bool valid = true;\n                    for (int k = a; k < c; ++k) {\n                        for (int l = b; l < d; ++l) {\n                            if (rect[k][l] != -1) {\n                                valid = false;\n                                break;\n                            }\n                        }\n                        if (!valid) break;\n                    }\n\n                    if (valid) {\n                        ans[idx] = {a, b, c, d};\n                        for (int k = a; k < c; ++k) {\n                            for (int l = b; l < d; ++l) {\n                                rect[k][l] = idx;\n                            }\n                        }\n                        found = true;\n                        break;\n                    }\n                }\n            }\n            if (found) break;\n        }\n    }\n\n    for (const auto& a : ans) {\n        cout << a[0] << \" \" << a[1] << \" \" << a[2] << \" \" << a[3] << endl;\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <string>\n\nusing namespace std;\n\nstruct State {\n    int x, y;\n    int score;\n    string path;\n    unordered_set<int> visited_tiles;\n\n    State(int x, int y, int score, string path, unordered_set<int> visited_tiles)\n        : x(x), y(y), score(score), path(path), visited_tiles(visited_tiles) {}\n};\n\nstruct CompareStates {\n    bool operator()(const State& a, const State& b) {\n        return a.score < b.score;\n    }\n};\n\nint main() {\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> tile_ids(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> tile_ids[i][j];\n        }\n    }\n\n    vector<vector<int>> scores(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> scores[i][j];\n        }\n    }\n\n    int initial_tile_id = tile_ids[si][sj];\n    unordered_set<int> initial_visited_tiles = {initial_tile_id};\n    State initial_state(si, sj, scores[si][sj], \"\", initial_visited_tiles);\n\n    priority_queue<State, vector<State>, CompareStates> pq;\n    pq.push(initial_state);\n\n    int max_score = initial_state.score;\n    string max_path = \"\";\n\n    for (int iter = 0; iter < 100000; ++iter) {\n        if (pq.empty()) break;\n        State state = pq.top();\n        pq.pop();\n\n        if (state.score < max_score) continue;\n\n        vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n        vector<char> moves = {'U', 'D', 'L', 'R'};\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = state.x + directions[i].first;\n            int ny = state.y + directions[i].second;\n\n            if (nx < 0 || nx >= 50 || ny < 0 || ny >= 50) continue;\n\n            int next_tile_id = tile_ids[nx][ny];\n            if (state.visited_tiles.count(next_tile_id)) continue;\n\n            unordered_set<int> next_visited_tiles = state.visited_tiles;\n            next_visited_tiles.insert(next_tile_id);\n\n            int next_score = state.score + scores[nx][ny];\n            string next_path = state.path + moves[i];\n\n            State next_state(nx, ny, next_score, next_path, next_visited_tiles);\n\n            if (next_score > max_score) {\n                max_score = next_score;\n                max_path = next_path;\n            }\n\n            pq.push(next_state);\n        }\n    }\n\n    cout << max_path << endl;\n\n    return 0;\n}","ahc003":"#include <iostream>\n#include <queue>\n#include <vector>\n#include <unordered_map>\n#include <limits>\n#include <algorithm> // Include algorithm for reverse\n\nusing namespace std;\n\nstruct Edge {\n    int to;\n    double weight;\n};\n\nusing Graph = vector<vector<Edge>>;\n\nstruct Node {\n    int id;\n    double distance;\n    bool operator>(const Node& other) const {\n        return distance > other.distance;\n    }\n};\n\nGraph buildGraph() {\n    Graph graph(30 * 30);\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            int id = i * 30 + j;\n            if (i > 0) graph[id].push_back({id - 30, 1}); // Up\n            if (i < 29) graph[id].push_back({id + 30, 1}); // Down\n            if (j > 0) graph[id].push_back({id - 1, 1}); // Left\n            if (j < 29) graph[id].push_back({id + 1, 1}); // Right\n        }\n    }\n    return graph;\n}\n\nstring dijkstra(Graph& graph, int source, int target) {\n    vector<double> distances(graph.size(), numeric_limits<double>::max());\n    vector<int> previous(graph.size(), -1);\n    distances[source] = 0;\n\n    priority_queue<Node, vector<Node>, greater<Node>> queue;\n    queue.push({source, 0});\n\n    while (!queue.empty()) {\n        Node node = queue.top();\n        queue.pop();\n        if (node.id == target) break;\n\n        for (const Edge& edge : graph[node.id]) {\n            double newDistance = distances[node.id] + edge.weight;\n            if (newDistance < distances[edge.to]) {\n                distances[edge.to] = newDistance;\n                previous[edge.to] = node.id;\n                queue.push({edge.to, newDistance});\n            }\n        }\n    }\n\n    string path;\n    int current = target;\n    while (current != source) {\n        int prev = previous[current];\n        if (prev == current - 1) path += 'R';\n        else if (prev == current + 1) path += 'L';\n        else if (prev == current - 30) path += 'D';\n        else if (prev == current + 30) path += 'U';\n        current = prev;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nvoid updateGraph(Graph& graph, const string& path, double actualLength) {\n    double scaleFactor = actualLength / path.length(); // Simplified calculation\n\n    int currentNode = 0;\n    for (char direction : path) {\n        int nextNode;\n        if (direction == 'U') nextNode = currentNode - 30;\n        else if (direction == 'D') nextNode = currentNode + 30;\n        else if (direction == 'L') nextNode = currentNode - 1;\n        else if (direction == 'R') nextNode = currentNode + 1;\n\n        for (Edge& edge : graph[currentNode]) {\n            if (edge.to == nextNode) {\n                edge.weight = (edge.weight + scaleFactor) / 2; // Simple moving average\n                break;\n            }\n        }\n        for (Edge& edge : graph[nextNode]) {\n            if (edge.to == currentNode) {\n                edge.weight = (edge.weight + scaleFactor) / 2; // Simple moving average\n                break;\n            }\n        }\n        currentNode = nextNode;\n    }\n}\n\nint main() {\n    Graph graph = buildGraph();\n    int si, sj, ti, tj;\n    double prevResult = 0;\n\n    for (int k = 0; k < 1000; ++k) {\n        cin >> si >> sj >> ti >> tj;\n        int source = si * 30 + sj;\n        int target = ti * 30 + tj;\n\n        string path = dijkstra(graph, source, target);\n        cout << path << endl;\n        cout.flush();\n\n        double actualLength;\n        cin >> actualLength;\n        updateGraph(graph, path, actualLength);\n        prevResult = actualLength;\n    }\n\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_M = 800;\nconst int MAX_LEN = 12;\n\nstruct StringInfo {\n    string s;\n    int len;\n    bool used;\n};\n\nint main() {\n    int M;\n    cin >> N >> M;\n    vector<StringInfo> strings(M);\n\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i].s;\n        strings[i].len = strings[i].s.length();\n        strings[i].used = false;\n    }\n\n    // Sort the strings in descending order of their lengths\n    sort(strings.begin(), strings.end(), [](const StringInfo& a, const StringInfo& b) {\n        return a.len > b.len;\n    });\n\n    vector<vector<char>> matrix(N, vector<char>(N, '.'));\n\n    mt19937 mt(42);\n    uniform_int_distribution<int> dist(0, N - 1);\n\n    for (const auto& s : strings) {\n        if (s.used) continue;\n\n        bool placed = false;\n        for (int trial = 0; trial < 100; ++trial) {\n            int i = dist(mt), j = dist(mt);\n            int dir = dist(mt) % 2; // 0: horizontal, 1: vertical\n\n            if (canPlaceString(matrix, s.s, i, j, dir)) {\n                placeString(matrix, s.s, i, j, dir);\n                placed = true;\n                break;\n            }\n        }\n\n        if (placed) {\n            // Mark the string as used\n            for (auto& str : strings) {\n                if (str.s == s.s) {\n                    str.used = true;\n                    break;\n                }\n            }\n        }\n    }\n\n    // Print the resulting matrix\n    for (const auto& row : matrix) {\n        for (char c : row) {\n            cout << c;\n        }\n        cout << endl;\n    }\n\n    return 0;\n}\n\nbool canPlaceString(vector<vector<char>>& matrix, const string& s, int i, int j, int dir) {\n    int N = matrix.size();\n    int len = s.length();\n\n    if (dir == 0) { // horizontal\n        for (int p = 0; p < len; ++p) {\n            int col = (j + p) % N;\n            if (matrix[i][col] != '.' && matrix[i][col] != s[p]) {\n                return false;\n            }\n        }\n    } else { // vertical\n        for (int p = 0; p < len; ++p) {\n            int row = (i + p) % N;\n            if (matrix[row][j] != '.' && matrix[row][j] != s[p]) {\n                return false;\n            }\n        }\n    }\n\n    return true;\n}\n\nvoid placeString(vector<vector<char>>& matrix, const string& s, int i, int j, int dir) {\n    int N = matrix.size();\n    int len = s.length();\n\n    if (dir == 0) { // horizontal\n        for (int p = 0; p < len; ++p) {\n            int col = (j + p) % N;\n            matrix[i][col] = s[p];\n        }\n    } else { // vertical\n        for (int p = 0; p < len; ++p) {\n            int row = (i + p) % N;\n            matrix[row][j] = s[p];\n        }\n    }\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Pos {\n    int i, j;\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n\n    // Grid preprocessing\n    vector<Pos> roadSquares;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                roadSquares.push_back({i, j});\n            }\n        }\n    }\n\n    // Visibility graph construction\n    unordered_map<Pos, vector<Pos>> visibilityGraph;\n    for (const auto& pos : roadSquares) {\n        vector<Pos> visibleSquares;\n        // Compute visible squares from pos\n        for (const auto& otherPos : roadSquares) {\n            if (isVisible(pos, otherPos, grid)) {\n                visibleSquares.push_back(otherPos);\n            }\n        }\n        visibilityGraph[pos] = visibleSquares;\n    }\n\n    // Route construction\n    vector<Pos> route;\n    unordered_set<Pos> visited;\n    Pos currentPos = {si, sj};\n    route.push_back(currentPos);\n    visited.insert(currentPos);\n\n    while (visited.size() < roadSquares.size()) {\n        Pos nextPos = getNearestUnvisitedSquare(currentPos, visibilityGraph, visited);\n        if (nextPos.i == -1) {\n            // Backtrack\n            currentPos = route.back();\n            route.pop_back();\n        } else {\n            route.push_back(nextPos);\n            visited.insert(nextPos);\n            currentPos = nextPos;\n        }\n    }\n\n    // Route optimization (2-opt)\n    optimizeRoute(route, grid);\n\n    // Output\n    outputRoute(route);\n\n    return 0;\n}\n\n// Helper functions\nbool isVisible(const Pos& pos, const Pos& otherPos, const vector<string>& grid) {\n    // Check if otherPos is visible from pos\n    if (pos.i == otherPos.i) {\n        int minJ = min(pos.j, otherPos.j);\n        int maxJ = max(pos.j, otherPos.j);\n        for (int j = minJ; j <= maxJ; j++) {\n            if (grid[pos.i][j] == '#') {\n                return false;\n            }\n        }\n        return true;\n    } else if (pos.j == otherPos.j) {\n        int minI = min(pos.i, otherPos.i);\n        int maxI = max(pos.i, otherPos.i);\n        for (int i = minI; i <= maxI; i++) {\n            if (grid[i][pos.j] == '#') {\n                return false;\n            }\n        }\n        return true;\n    }\n    return false;\n}\n\nPos getNearestUnvisitedSquare(const Pos& pos, const unordered_map<Pos, vector<Pos>>& visibilityGraph, const unordered_set<Pos>& visited) {\n    // Find nearest unvisited square visible from pos\n    for (const auto& otherPos : visibilityGraph.at(pos)) {\n        if (visited.find(otherPos) == visited.end()) {\n            return otherPos;\n        }\n    }\n    return {-1, -1}; // Not found\n}\n\nvoid optimizeRoute(vector<Pos>& route, const vector<string>& grid) {\n    // 2-opt algorithm to optimize the route\n    int N = route.size();\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 1; i < N - 2; i++) {\n            for (int j = i + 1; j < N - 1; j++) {\n                int oldCost = getTravelTime(route[i - 1], route[i], grid) + getTravelTime(route[j], route[j + 1], grid);\n                int newCost = getTravelTime(route[i - 1], route[j], grid) + getTravelTime(route[i], route[j + 1], grid);\n                if (newCost < oldCost) {\n                    reverse(route.begin() + i, route.begin() + j + 1);\n                    improved = true;\n                }\n            }\n        }\n    }\n}\n\nint getTravelTime(const Pos& pos1, const Pos& pos2, const vector<string>& grid) {\n    // Compute travel time between pos1 and pos2\n    if (abs(pos1.i - pos2.i) + abs(pos1.j - pos2.j) != 1) {\n        return numeric_limits<int>::max(); // Invalid move\n    }\n    int cost = grid[pos2.i][pos2.j] - '0';\n    return cost;\n}\n\nvoid outputRoute(const vector<Pos>& route) {\n    // Output the route as a sequence of moves\n    for (int i = 0; i < route.size() - 1; i++) {\n        Pos pos1 = route[i];\n        Pos pos2 = route[i + 1];\n        if (pos1.i > pos2.i) {\n            cout << 'U';\n        } else if (pos1.i < pos2.i) {\n            cout << 'D';\n        } else if (pos1.j > pos2.j) {\n            cout << 'L';\n        } else if (pos1.j < pos2.j) {\n            cout << 'R';\n        }\n    }\n    cout << endl;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Task {\n    vector<int> d;\n    vector<int> dependencies;\n    int status; // -1: not started, 0: started, 1: completed\n};\n\nstruct TeamMember {\n    vector<int> s; // estimated skill levels\n    int task; // current task being worked on, -1 if available\n    int endDay; // day when the current task will be completed\n};\n\nint main() {\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<Task> tasks(N);\n    for (int i = 0; i < N; i++) {\n        tasks[i].d.resize(K);\n        for (int j = 0; j < K; j++) {\n            cin >> tasks[i].d[j];\n        }\n        tasks[i].status = -1;\n    }\n\n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        tasks[v - 1].dependencies.push_back(u - 1);\n    }\n\n    vector<TeamMember> teamMembers(M);\n    for (int i = 0; i < M; i++) {\n        teamMembers[i].s.resize(K, 0); // initialize estimated skill levels to 0\n        teamMembers[i].task = -1;\n        teamMembers[i].endDay = 0;\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n\n        // receive the list of team members who have completed their tasks\n        int n;\n        cin >> n;\n        if (n == -1) break;\n\n        vector<int> completedTeamMembers(n);\n        for (int i = 0; i < n; i++) {\n            cin >> completedTeamMembers[i];\n            completedTeamMembers[i]--;\n        }\n\n        // update task status and team member status\n        for (int teamMember : completedTeamMembers) {\n            if (teamMembers[teamMember].task != -1) {\n                tasks[teamMembers[teamMember].task].status = 1;\n                teamMembers[teamMember].task = -1;\n            }\n        }\n\n        // estimate skill levels of team members\n        for (int teamMember : completedTeamMembers) {\n            // TO DO: implement skill level estimation\n        }\n\n        // get available tasks\n        vector<int> availableTasks;\n        for (int i = 0; i < N; i++) {\n            if (tasks[i].status == -1) {\n                bool ok = true;\n                for (int dependency : tasks[i].dependencies) {\n                    if (tasks[dependency].status != 1) {\n                        ok = false;\n                        break;\n                    }\n                }\n                if (ok) availableTasks.push_back(i);\n            }\n        }\n\n        // assign tasks to available team members\n        vector<pair<int, int>> assignments;\n        for (int teamMember = 0; teamMember < M; teamMember++) {\n            if (teamMembers[teamMember].task == -1 && !availableTasks.empty()) {\n                // TO DO: implement task assignment heuristic\n                int task = availableTasks.back();\n                availableTasks.pop_back();\n                teamMembers[teamMember].task = task;\n                tasks[task].status = 0;\n                assignments.emplace_back(teamMember + 1, task + 1);\n            }\n        }\n\n        // output assignments\n        cout << assignments.size();\n        for (auto& assignment : assignments) {\n            cout << \" \" << assignment.first << \" \" << assignment.second;\n        }\n        cout << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Order {\n    int id;\n    int a, b, c, d;\n};\n\nint calculateDistance(const pair<int, int>& p1, const pair<int, int>& p2) {\n    return abs(p1.first - p2.first) + abs(p1.second - p2.second);\n}\n\nint main() {\n    vector<Order> orders;\n    for (int i = 0; i < 1000; ++i) {\n        Order order;\n        order.id = i + 1;\n        cin >> order.a >> order.b >> order.c >> order.d;\n        orders.push_back(order);\n    }\n\n    // Greedy algorithm to select 50 orders\n    vector<Order> selectedOrders;\n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(orders.begin(), orders.end(), gen);\n    for (int i = 0; i < 50; ++i) {\n        selectedOrders.push_back(orders[i]);\n    }\n\n    // Local search to improve the solution\n    auto startTime = chrono::high_resolution_clock::now();\n    int iteration = 0;\n    while (chrono::duration_cast<chrono::seconds>(chrono::high_resolution_clock::now() - startTime).count() < 1.9) {\n        iteration++;\n        // Perform local search iterations\n        int i = uniform_int_distribution<int>(0, selectedOrders.size() - 1)(gen);\n        int j = uniform_int_distribution<int>(0, orders.size() - 1)(gen);\n        if (find_if(selectedOrders.begin(), selectedOrders.end(), [&](const Order& order) { return order.id == orders[j].id; }) == selectedOrders.end()) {\n            // Replace the i-th order with the j-th order\n            selectedOrders[i] = orders[j];\n        }\n        if (iteration % 100 == 0) {\n            // Check time limit every 100 iterations\n            if (chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - startTime).count() > 1900) {\n                break;\n            }\n        }\n    }\n\n    // Construct the delivery route\n    vector<pair<int, int>> route;\n    route.push_back({400, 400});\n    for (const auto& order : selectedOrders) {\n        route.push_back({order.a, order.b});\n        route.push_back({order.c, order.d});\n    }\n    route.push_back({400, 400});\n\n    // Output the solution\n    cout << selectedOrders.size() << \" \";\n    for (const auto& order : selectedOrders) {\n        cout << order.id << \" \";\n    }\n    cout << endl;\n    cout << route.size() << \" \";\n    for (const auto& point : route) {\n        cout << point.first << \" \" << point.second << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <random>\n#include <cassert>\n\n// Union-Find data structure\nclass UnionFind {\npublic:\n    UnionFind(int n) : parent(n), rank(n, 0), size(n, 1) {\n        for (int i = 0; i < n; ++i) {\n            parent[i] = i;\n        }\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\n    void unite(int x, int y) {\n        int root_x = find(x);\n        int root_y = find(y);\n        if (root_x != root_y) {\n            if (rank[root_x] < rank[root_y]) {\n                parent[root_x] = root_y;\n                size[root_y] += size[root_x];\n            } else {\n                parent[root_y] = root_x;\n                size[root_x] += size[root_y];\n                if (rank[root_x] == rank[root_y]) {\n                    ++rank[root_x];\n                }\n            }\n        }\n    }\n\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n\n    int getSize(int x) {\n        return size[find(x)];\n    }\n\nprivate:\n    std::vector<int> parent;\n    std::vector<int> rank;\n    std::vector<int> size;\n};\n\nint main() {\n    const int N = 400;\n    const int M = 1995;\n\n    // Read vertex coordinates\n    std::vector<std::pair<int, int>> vertices(N);\n    for (auto& vertex : vertices) {\n        std::cin >> vertex.first >> vertex.second;\n    }\n\n    // Precompute Euclidean distances\n    std::vector<int> distances(M);\n    std::vector<std::pair<int, int>> edges(M);\n    for (int i = 0; i < M; ++i) {\n        std::cin >> edges[i].first >> edges[i].second;\n        int dx = vertices[edges[i].first].first - vertices[edges[i].second].first;\n        int dy = vertices[edges[i].first].second - vertices[edges[i].second].second;\n        distances[i] = std::round(std::sqrt(dx * dx + dy * dy));\n    }\n\n    // Initialize Union-Find data structure\n    UnionFind uf(N);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<double> dis(0.0, 1.0);\n\n    int count = 0;\n    for (int i = 0; i < M; ++i) {\n        int length;\n        std::cin >> length;\n\n        if (uf.same(edges[i].first, edges[i].second)) {\n            double prob = (length > 2 * distances[i]) ? 0.05 : 0.2;\n            bool adopt = dis(gen) < prob;\n            std::cout << (adopt ? \"1\" : \"0\") << std::endl;\n            std::cout.flush();\n            if (adopt) {\n                // Not expected to happen often, but handle it just in case\n                uf.unite(edges[i].first, edges[i].second);\n                count++;\n            }\n        } else {\n            int size1 = uf.getSize(edges[i].first);\n            int size2 = uf.getSize(edges[i].second);\n            double prob = (length <= 1.5 * distances[i]) ? 1.0 : (size1 < N / 2 || size2 < N / 2) ? 0.8 : 0.5;\n            bool adopt = dis(gen) < prob;\n            std::cout << (adopt ? \"1\" : \"0\") << std::endl;\n            std::cout.flush();\n            if (adopt) {\n                uf.unite(edges[i].first, edges[i].second);\n                count++;\n            }\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 30;\nconst int DIR[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst char DIR_CHAR[4] = {'u', 'd', 'l', 'r'};\nconst char MOVE_CHAR[4] = {'U', 'D', 'L', 'R'};\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nint grid[N][N]; // 0: passable, 1: impassable\nvector<Pet> pets;\nvector<Human> humans;\n\nvoid bfs(int x, int y, vector<vector<bool>>& visited) {\n    queue<pair<int, int>> q;\n    q.emplace(x, y);\n    visited[x][y] = true;\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n        for (int i = 0; i < 4; ++i) {\n            int nx = x + DIR[i][0];\n            int ny = y + DIR[i][1];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0 && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n}\n\nchar getAction(int h) {\n    Human& human = humans[h];\n    int x = human.x;\n    int y = human.y;\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    bfs(x, y, visited);\n    int bestDir = -1;\n    int bestScore = -1;\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + DIR[i][0];\n        int ny = y + DIR[i][1];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0) {\n            // Check if making the square impassable is valid\n            bool valid = true;\n            for (int j = 0; j < 4; ++j) {\n                int nnx = nx + DIR[j][0];\n                int nny = ny + DIR[j][1];\n                if (nnx >= 0 && nnx < N && nny >= 0 && nny < N) {\n                    for (const Pet& pet : pets) {\n                        if (pet.x == nnx && pet.y == nny) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                }\n            }\n            if (!valid) continue;\n            // Simulate making the square impassable\n            grid[nx][ny] = 1;\n            vector<vector<bool>> newVisited(N, vector<bool>(N, false));\n            bfs(x, y, newVisited);\n            int newScore = 0;\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (newVisited[i][j]) ++newScore;\n                }\n            }\n            grid[nx][ny] = 0;\n            if (newScore > bestScore) {\n                bestScore = newScore;\n                bestDir = i;\n            }\n        }\n    }\n    if (bestDir != -1) {\n        return DIR_CHAR[bestDir];\n    } else {\n        // Try to move to an adjacent passable square\n        for (int i = 0; i < 4; ++i) {\n            int nx = x + DIR[i][0];\n            int ny = y + DIR[i][1];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0) {\n                return MOVE_CHAR[i];\n            }\n        }\n    }\n    return '.';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    cin >> N;\n    pets.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n        --pets[i].x;\n        --pets[i].y;\n    }\n    int M;\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].x >> humans[i].y;\n        --humans[i].x;\n        --humans[i].y;\n    }\n    for (int turn = 0; turn < 300; ++turn) {\n        string actions;\n        for (int h = 0; h < M; ++h) {\n            actions += getAction(h);\n        }\n        cout << actions << endl;\n        cout.flush();\n        // Read pet movements\n        for (int i = 0; i < N; ++i) {\n            string movement;\n            cin >> movement;\n            // Update pet positions\n            if (movement != \".\") {\n                for (char c : movement) {\n                    int dx = 0, dy = 0;\n                    if (c == 'U') dx = -1;\n                    if (c == 'D') dx = 1;\n                    if (c == 'L') dy = -1;\n                    if (c == 'R') dy = 1;\n                    pets[i].x += dx;\n                    pets[i].y += dy;\n                }\n            }\n        }\n        // Update human positions\n        for (int h = 0; h < M; ++h) {\n            char action = actions[h];\n            if (action == 'U') --humans[h].x;\n            if (action == 'D') ++humans[h].x;\n            if (action == 'L') --humans[h].y;\n            if (action == 'R') ++humans[h].y;\n        }\n    }\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    int sx, sy, tx, ty;\n    double p;\n    cin >> sx >> sy >> tx >> ty >> p;\n\n    vector<string> h(20), v(20);\n    for (int i = 0; i < 20; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < 19; ++i) {\n        cin >> v[i];\n    }\n\n    // BFS to find a initial path\n    queue<Pos> q;\n    vector<vector<bool>> visited(20, vector<bool>(20, false));\n    q.push({sx, sy});\n    visited[sx][sy] = true;\n    vector<vector<Pos>> parent(20, vector<Pos>(20, {-1, -1}));\n    while (!q.empty()) {\n        Pos curr = q.front(); q.pop();\n        if (curr.x == tx && curr.y == ty) break;\n        // Explore neighbors\n        for (auto dir : {make_pair(0, 1), make_pair(0, -1), make_pair(1, 0), make_pair(-1, 0)}) {\n            int nx = curr.x + dir.first, ny = curr.y + dir.second;\n            if (nx >= 0 && nx < 20 && ny >= 0 && ny < 20 && !visited[nx][ny]) {\n                if (dir.first == 0 && dir.second == 1 && ny < 20 && h[curr.x][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == 0 && dir.second == -1 && ny >= 0 && h[curr.x][ny] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == 1 && dir.second == 0 && nx < 20 && v[curr.x][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == -1 && dir.second == 0 && nx >= 0 && v[nx][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                }\n            }\n        }\n    }\n\n    // Reconstruct path\n    string path;\n    Pos curr = {tx, ty};\n    while (curr.x != sx || curr.y != sy) {\n        Pos prev = parent[curr.x][curr.y];\n        if (prev.x == curr.x - 1) path += 'D';\n        else if (prev.x == curr.x + 1) path += 'U';\n        else if (prev.y == curr.y - 1) path += 'R';\n        else if (prev.y == curr.y + 1) path += 'L';\n        curr = prev;\n    }\n    reverse(path.begin(), path.end());\n\n    // Ensure path only contains valid characters and is within length limits\n    string robustPath = path;\n    while (robustPath.size() <= 200) {\n        robustPath += path;\n    }\n    robustPath.resize(200);\n\n    // Validate and output\n    for (char c : robustPath) {\n        if (c != 'U' && c != 'D' && c != 'L' && c != 'R') {\n            cerr << \"Invalid character in path: \" << c << endl;\n            return 1; // Exit with error if invalid character found\n        }\n    }\n\n    cout << robustPath << endl;\n\n    return 0;\n}","ahc010":"","ahc011":"","ahc012":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    long long x, y;\n};\n\nlong long cross(const Point& p1, const Point& p2) {\n    return p1.x * p2.y - p1.y * p2.x;\n}\n\nint main() {\n    int N, K;\n    cin >> N >> K;\n    vector<int> a(10);\n    for (int i = 0; i < 10; ++i) {\n        cin >> a[i];\n    }\n    vector<Point> strawberries(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> strawberries[i].x >> strawberries[i].y;\n    }\n\n    vector<pair<Point, Point>> cuts;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int i = 0; i < K; ++i) {\n        int best_idx1 = -1, best_idx2 = -1;\n        double best_score = -1.0;\n\n        for (int j = 0; j < 100; ++j) {\n            int idx1 = dis(gen);\n            int idx2 = dis(gen);\n            while (idx2 == idx1) {\n                idx2 = dis(gen);\n            }\n\n            // Calculate the score for the current cut\n            double score = 0.0;\n            // TO DO: implement the score calculation\n\n            if (score > best_score) {\n                best_score = score;\n                best_idx1 = idx1;\n                best_idx2 = idx2;\n            }\n        }\n\n        if (best_idx1 != -1 && best_idx2 != -1) {\n            Point p1 = strawberries[best_idx1];\n            Point p2 = strawberries[best_idx2];\n            cuts.emplace_back(p1, p2);\n        }\n    }\n\n    cout << cuts.size() << endl;\n    for (const auto& cut : cuts) {\n        cout << cut.first.x << \" \" << cut.first.y << \" \" << cut.second.x << \" \" << cut.second.y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <random>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nint N, M;\nvector<Point> dots;\nset<pair<int, int>> dot_set;\nvector<tuple<int, int, int, int, int, int, int, int>> operations;\n\nbool is_valid_rectangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    // Check if the four points form a rectangle\n    if ((x1 == x2 && y1 == y3 && x3 == x4 && y2 == y4) || (x1 == x3 && y1 == y2 && x2 == x4 && y3 == y4)) {\n        // Check if the rectangle is parallel to the axis or inclined at 45 degrees\n        if ((x1 == x2 && x3 == x4) || (y1 == y2 && y3 == y4) || (abs(x1 - x2) == abs(y1 - y2) && abs(x2 - x3) == abs(y2 - y3))) {\n            // Check if there are no dots other than the four points on the perimeter\n            for (int i = min(x1, min(x2, min(x3, x4))); i <= max(x1, max(x2, max(x3, x4))); i++) {\n                for (int j = min(y1, min(y2, min(y3, y4))); j <= max(y1, max(y2, max(y3, y4))); j++) {\n                    if (dot_set.find({i, j}) != dot_set.end() && (i, j) != (x1, y1) && (i, j) != (x2, y2) && (i, j) != (x3, y3) && (i, j) != (x4, y4)) {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    cin >> N >> M;\n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        dots.push_back({x, y});\n        dot_set.insert({x, y});\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int iter = 0; iter < 100000; iter++) {\n        if (iter % 1000 == 0) {\n            cout << \"Iteration \" << iter << endl;\n        }\n        int x1 = dis(gen);\n        int y1 = dis(gen);\n        if (dot_set.find({x1, y1}) != dot_set.end()) {\n            continue;\n        }\n        for (int i = 0; i < dots.size(); i++) {\n            for (int j = i + 1; j < dots.size(); j++) {\n                for (int k = j + 1; k < dots.size(); k++) {\n                    int x2 = dots[i].x;\n                    int y2 = dots[i].y;\n                    int x3 = dots[j].x;\n                    int y3 = dots[j].y;\n                    int x4 = dots[k].x;\n                    int y4 = dots[k].y;\n                    // Check all possible combinations of x1, y1, x2, y2, x3, y3, x4, y4\n                    if (is_valid_rectangle(x1, y1, x2, y2, x3, y3, x4, y4)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x2, y2, x3, y3, x4, y4});\n                        goto next_iter;\n                    }\n                    if (is_valid_rectangle(x1, y1, x2, y2, x4, y4, x3, y3)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x2, y2, x4, y4, x3, y3});\n                        goto next_iter;\n                    }\n                    if (is_valid_rectangle(x1, y1, x3, y3, x2, y2, x4, y4)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x3, y3, x2, y2, x4, y4});\n                        goto next_iter;\n                    }\n                    if (is_valid_rectangle(x1, y1, x3, y3, x4, y4, x2, y2)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x3, y3, x4, y4, x2, y2});\n                        goto next_iter;\n                    }\n                    if (is_valid_rectangle(x1, y1, x4, y4, x2, y2, x3, y3)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x4, y4, x2, y2, x3, y3});\n                        goto next_iter;\n                    }\n                    if (is_valid_rectangle(x1, y1, x4, y4, x3, y3, x2, y2)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.push_back({x1, y1, x4, y4, x3, y3, x2, y2});\n                        goto next_iter;\n                    }\n                }\n            }\n        }\n        next_iter:;\n    }\n\n    cout << operations.size() << endl;\n    for (auto& op : operations) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << \" \" << get<4>(op) << \" \" << get<5>(op) << \" \" << get<6>(op) << \" \" << get<7>(op) << endl;\n    }\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nconst int N = 10;\nconst int flavors = 3;\n\nstruct CandyBox {\n    int grid[N][N];\n    int count[flavors + 1];\n\n    CandyBox() {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                grid[i][j] = 0;\n            }\n        }\n        for (int i = 1; i <= flavors; i++) {\n            count[i] = 0;\n        }\n    }\n\n    void placeCandy(int flavor, int pos) {\n        int emptyCount = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (grid[i][j] == 0) {\n                    emptyCount++;\n                    if (emptyCount == pos) {\n                        grid[i][j] = flavor;\n                        count[flavor]++;\n                        return;\n                    }\n                }\n            }\n        }\n    }\n\n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; j++) {\n                int writePos = 0;\n                for (int i = 0; i < N; i++) {\n                    if (grid[i][j] != 0) {\n                        grid[writePos++][j] = grid[i][j];\n                    }\n                }\n                for (int i = writePos; i < N; i++) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; j++) {\n                int writePos = N - 1;\n                for (int i = N - 1; i >= 0; i--) {\n                    if (grid[i][j] != 0) {\n                        grid[writePos--][j] = grid[i][j];\n                    }\n                }\n                for (int i = writePos; i >= 0; i--) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; i++) {\n                int writePos = 0;\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] != 0) {\n                        grid[i][writePos++] = grid[i][j];\n                    }\n                }\n                for (int j = writePos; j < N; j++) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'R') {\n            for (int i = 0; i < N; i++) {\n                int writePos = N - 1;\n                for (int j = N - 1; j >= 0; j--) {\n                    if (grid[i][j] != 0) {\n                        grid[i][writePos--] = grid[i][j];\n                    }\n                }\n                for (int j = writePos; j >= 0; j--) {\n                    grid[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    int evaluateScore() {\n        int score = 0;\n        for (int flavor = 1; flavor <= flavors; flavor++) {\n            vector<vector<bool>> visited(N, vector<bool>(N, false));\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] == flavor && !visited[i][j]) {\n                        int componentSize = 0;\n                        vector<pair<int, int>> stack = {{i, j}};\n                        visited[i][j] = true;\n                        while (!stack.empty()) {\n                            auto [x, y] = stack.back();\n                            stack.pop_back();\n                            componentSize++;\n                            for (auto [dx, dy] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                                int nx = x + dx;\n                                int ny = y + dy;\n                                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == flavor && !visited[nx][ny]) {\n                                    stack.emplace_back(nx, ny);\n                                    visited[nx][ny] = true;\n                                }\n                            }\n                        }\n                        score += componentSize * componentSize;\n                    }\n                }\n            }\n        }\n        int denominator = 0;\n        for (int i = 1; i <= flavors; i++) {\n            denominator += count[i] * count[i];\n        }\n        return denominator == 0 ? 0 : score / denominator;\n    }\n\n    int evaluateScoreWithClustering() {\n        int score = 0;\n        for (int flavor = 1; flavor <= flavors; flavor++) {\n            vector<vector<bool>> visited(N, vector<bool>(N, false));\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] == flavor && !visited[i][j]) {\n                        int componentSize = 0;\n                        vector<pair<int, int>> stack = {{i, j}};\n                        visited[i][j] = true;\n                        while (!stack.empty()) {\n                            auto [x, y] = stack.back();\n                            stack.pop_back();\n                            componentSize++;\n                            for (auto [dx, dy] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                                int nx = x + dx;\n                                int ny = y + dy;\n                                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == flavor && !visited[nx][ny]) {\n                                    stack.emplace_back(nx, ny);\n                                    visited[nx][ny] = true;\n                                }\n                            }\n                        }\n                        score += componentSize * componentSize;\n                        // clustering bonus\n                        if (componentSize > 1) {\n                            score += componentSize;\n                        }\n                    }\n                }\n            }\n        }\n        int denominator = 0;\n        for (int i = 1; i <= flavors; i++) {\n            denominator += count[i] * count[i];\n        }\n        return denominator == 0 ? 0 : score / denominator;\n    }\n};\n\nint main() {\n    vector<int> flavors(100);\n    for (int i = 0; i < 100; i++) {\n        cin >> flavors[i];\n    }\n\n    CandyBox box;\n    for (int t = 0; t < 100; t++) {\n        int pos;\n        cin >> pos;\n        box.placeCandy(flavors[t], pos);\n\n        if (t == 99) break; // no need to output for the last tilt\n\n        char bestDir = 'F';\n        int bestScore = -1;\n        for (char dir : {'F', 'B', 'L', 'R'}) {\n            CandyBox simBox = box;\n            simBox.tilt(dir);\n            int score = simBox.evaluateScoreWithClustering();\n            if (score > bestScore) {\n                bestScore = score;\n                bestDir = dir;\n            }\n        }\n        cout << bestDir << endl;\n        box.tilt(bestDir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint M;\ndouble eps;\nint N = 20; // Example value, might need adjustment\n\n// Function to generate G_k\nstring generateGk(int k) {\n    string gk(N * (N - 1) / 2, '0');\n    // Simple strategy: add edges based on k\n    for (int i = 0; i < N * (N - 1) / 2 && i < k; ++i) {\n        gk[i] = '1';\n    }\n    return gk;\n}\n\n// Function to predict s_k from H_k\nint predictSk(const string& Hk, const vector<string>& G) {\n    int bestMatch = 0;\n    double minDistance = numeric_limits<double>::max();\n    for (int i = 0; i < M; ++i) {\n        double distance = 0;\n        for (int j = 0; j < N * (N - 1) / 2; ++j) {\n            distance += (Hk[j] != G[i][j]);\n        }\n        if (distance < minDistance) {\n            minDistance = distance;\n            bestMatch = i;\n        }\n    }\n    return bestMatch;\n}\n\nint main() {\n    cin >> M >> eps;\n    cout << N << endl;\n    vector<string> G(M);\n    for (int k = 0; k < M; ++k) {\n        G[k] = generateGk(k);\n        cout << G[k] << endl;\n    }\n    cout.flush();\n\n    for (int query = 0; query < 100; ++query) {\n        string Hk;\n        cin >> Hk;\n        int tk = predictSk(Hk, G);\n        cout << tk << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n#include <limits>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v, w, id;\n};\n\nint main() {\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    vector<Edge> edges(M);\n    vector<vector<pair<int, int>>> graph(N);\n\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[i] = {u, v, w, i};\n        graph[u].emplace_back(v, w);\n        graph[v].emplace_back(u, w);\n    }\n\n    // Read and ignore vertex coordinates\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // Initialize repair schedule randomly\n    vector<int> repairDay(M);\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(1, D);\n    for (auto& day : repairDay) {\n        day = dis(gen);\n    }\n\n    // Function to calculate frustration level for a given day\n    auto calculateFrustration = [&](const vector<int>& edgesForDay) {\n        // Create a temporary graph with edges for the day removed\n        vector<vector<pair<int, int>>> tempGraph = graph;\n        for (int edgeId : edgesForDay) {\n            Edge e = edges[edgeId];\n            // Remove edge e from tempGraph\n            tempGraph[e.u].erase(remove_if(tempGraph[e.u].begin(), tempGraph[e.u].end(), [&](const pair<int, int>& p){ return p.first == e.v; }), tempGraph[e.u].end());\n            tempGraph[e.v].erase(remove_if(tempGraph[e.v].begin(), tempGraph[e.v].end(), [&](const pair<int, int>& p){ return p.first == e.u; }), tempGraph[e.v].end());\n        }\n\n        // Calculate shortest paths using Dijkstra's algorithm\n        vector<vector<int>> dist(N, vector<int>(N, numeric_limits<int>::max()));\n        for (int i = 0; i < N; ++i) {\n            dist[i][i] = 0;\n            priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;\n            pq.emplace(0, i);\n            while (!pq.empty()) {\n                int d = pq.top().first, u = pq.top().second;\n                pq.pop();\n                if (d > dist[i][u]) continue;\n                for (const auto& e : tempGraph[u]) {\n                    if (dist[i][e.first] > d + e.second) {\n                        dist[i][e.first] = d + e.second;\n                        pq.emplace(dist[i][e.first], e.first);\n                    }\n                }\n            }\n        }\n\n        // Calculate frustration level\n        int frustration = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (dist[i][j] == numeric_limits<int>::max()) dist[i][j] = 1e9;\n                frustration += dist[i][j] - /* original shortest distance */;\n            }\n        }\n        return frustration;\n    };\n\n    // Main loop to improve the schedule\n    for (int iter = 0; iter < 10000; ++iter) {\n        // Select an edge and a new day for it\n        int edgeId = rand() % M;\n        int newDay = rand() % D + 1;\n        int oldDay = repairDay[edgeId];\n\n        // Check if moving the edge to the new day is valid and improves the schedule\n        vector<int>& oldDayEdges = /* get edges for oldDay */;\n        vector<int>& newDayEdges = /* get edges for newDay */;\n        if (newDayEdges.size() < K) {\n            // Temporarily move the edge\n            oldDayEdges.erase(remove(oldDayEdges.begin(), oldDayEdges.end(), edgeId), oldDayEdges.end());\n            newDayEdges.push_back(edgeId);\n\n            // Calculate new frustration levels\n            int oldFrustration = calculateFrustration(oldDayEdges) + calculateFrustration(newDayEdges);\n            int newFrustration = /* calculate frustration for oldDay without edgeId */ + /* calculate frustration for newDay with edgeId */;\n\n            if (newFrustration < oldFrustration) {\n                // Accept the move\n                repairDay[edgeId] = newDay;\n            } else {\n                // Revert the move\n                newDayEdges.pop_back();\n                oldDayEdges.push_back(edgeId);\n            }\n        }\n    }\n\n    // Output the final repair schedule\n    for (int i = 0; i < M; ++i) {\n        cout << repairDay[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <bitset>\n\nconst int MAX_D = 14;\nint D;\nstd::bitset<MAX_D> f[2][MAX_D][MAX_D];\nstd::bitset<MAX_D> r[2][MAX_D][MAX_D];\nint b[2][MAX_D * MAX_D * MAX_D];\n\nvoid input() {\n    std::cin >> D;\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            std::string s;\n            std::cin >> s;\n            for (int x = 0; x < D; ++x) {\n                f[i][z][x][x] = (s[x] == '1');\n            }\n        }\n        for (int z = 0; z < D; ++z) {\n            std::string s;\n            std::cin >> s;\n            for (int y = 0; y < D; ++y) {\n                r[i][z][y][y] = (s[y] == '1');\n            }\n        }\n    }\n}\n\nvoid solve() {\n    int n = 0;\n    for (int i = 0; i < 2; ++i) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[i][z][x][y] && r[i][z][y][x]) {\n                        b[i][x * D * D + y * D + z] = ++n;\n                    }\n                }\n            }\n        }\n    }\n\n    std::cout << n << std::endl;\n    for (int i = 0; i < D * D * D; ++i) {\n        std::cout << b[0][i] << \" \";\n    }\n    std::cout << std::endl;\n    for (int i = 0; i < D * D * D; ++i) {\n        std::cout << b[1][i] << \" \";\n    }\n    std::cout << std::endl;\n}\n\nint main() {\n    input();\n    solve();\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n    long long w;\n};\n\nstruct UnionFind {\n    vector<int> parent, rank;\n    UnionFind(int n) : parent(n, -1), rank(n, 0) {}\n    int find(int x) {\n        if (parent[x] == -1) return x;\n        return parent[x] = find(parent[x]);\n    }\n    void unionSet(int x, int y) {\n        int rootX = find(x), rootY = find(y);\n        if (rootX != rootY) {\n            if (rank[rootX] > rank[rootY]) {\n                parent[rootY] = rootX;\n            } else {\n                parent[rootX] = rootY;\n                if (rank[rootX] == rank[rootY]) rank[rootY]++;\n            }\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<pair<int, int>> vertices(N);\n    for (auto& [x, y] : vertices) {\n        cin >> x >> y;\n    }\n\n    vector<Edge> edges(M);\n    for (auto& [u, v, w] : edges) {\n        cin >> u >> v >> w;\n        u--; v--;\n    }\n\n    vector<pair<int, int>> residents(K);\n    for (auto& [a, b] : residents) {\n        cin >> a >> b;\n    }\n\n    // Minimum Spanning Tree\n    vector<bool> in_mst(M, false);\n    UnionFind uf(N);\n    {\n        sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        for (auto& e : edges) {\n            if (uf.find(e.u) != uf.find(e.v)) {\n                uf.unionSet(e.u, e.v);\n                in_mst[&e - &edges[0]] = true;\n            }\n        }\n    }\n\n    // Resident Coverage\n    vector<int> output_strength(N, 0);\n    for (auto [a, b] : residents) {\n        int nearest_vertex = 0;\n        long long min_distance = (long long)1e18;\n        for (int i = 0; i < N; i++) {\n            auto [x, y] = vertices[i];\n            long long distance = (long long)(x - a) * (x - a) + (long long)(y - b) * (y - b);\n            if (distance < min_distance) {\n                min_distance = distance;\n                nearest_vertex = i;\n            }\n        }\n        output_strength[nearest_vertex] = max(output_strength[nearest_vertex], (int)ceil(sqrt(min_distance)) + 1);\n    }\n\n    // Graph Traversal\n    vector<bool> visited(N, false);\n    {\n        queue<int> q;\n        q.push(0);\n        visited[0] = true;\n        while (!q.empty()) {\n            int u = q.front(); q.pop();\n            for (int i = 0; i < M; i++) {\n                if (in_mst[i]) {\n                    auto& e = edges[i];\n                    if (e.u == u && !visited[e.v]) {\n                        visited[e.v] = true;\n                        output_strength[e.v] = max(output_strength[e.v], output_strength[u]);\n                        q.push(e.v);\n                    }\n                    if (e.v == u && !visited[e.u]) {\n                        visited[e.u] = true;\n                        output_strength[e.u] = max(output_strength[e.u], output_strength[u]);\n                        q.push(e.u);\n                    }\n                }\n            }\n        }\n    }\n\n    // Output\n    for (int p : output_strength) {\n        cout << p << \" \";\n    }\n    cout << \"\\n\";\n    for (auto& e : edges) {\n        cout << (in_mst[&e - &edges[0]] ? \"1\" : \"0\") << \" \";\n    }\n    cout << \"\\n\";\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n#include <tuple> // Include the necessary header for std::tuple\n\nusing namespace std;\n\nconst int N = 30;\nconst int dx[] = {-1, -1, 0, 0, 1, 1};\nconst int dy[] = {-1, 0, -1, 1, 0, 1};\n\nint main() {\n    vector<vector<int>> pyramid(N);\n    for (int i = 0; i < N; ++i) {\n        pyramid[i].resize(i + 1);\n        for (int j = 0; j <= i; ++j) {\n            cin >> pyramid[i][j];\n        }\n    }\n\n    vector<tuple<int, int, int, int>> operations;\n    for (int i = N - 1; i > 0; --i) {\n        for (int j = 0; j <= i; ++j) {\n            int x = i, y = j;\n            while (x > 0) {\n                int parent_x = x - 1;\n                int parent_y = y;\n                if (y > parent_x) {\n                    parent_y = y - 1;\n                }\n                if (pyramid[x][y] < pyramid[parent_x][parent_y]) {\n                    swap(pyramid[x][y], pyramid[parent_x][parent_y]);\n                    operations.emplace_back(x, y, parent_x, parent_y);\n                }\n                x = parent_x;\n                y = parent_y;\n            }\n        }\n    }\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << endl;\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n\nusing namespace std;\n\nconst int D = 9;\nconst int directions[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nstruct Position {\n    int x, y;\n};\n\nint main() {\n    int N;\n    cin >> D >> N;\n\n    vector<vector<int>> grid(D, vector<int>(D, 0));\n    grid[0][(D - 1) / 2] = -1; // Entrance\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        grid[x][y] = -2; // Obstacle\n    }\n\n    vector<Position> containers;\n    unordered_set<int> containerSet;\n\n    for (int d = 0; d < D * D - 1 - N; ++d) {\n        int t;\n        cin >> t;\n\n        // Find a suitable position for the container using BFS\n        queue<Position> q;\n        vector<vector<bool>> visited(D, vector<bool>(D, false));\n        q.push({0, (D - 1) / 2});\n        visited[0][(D - 1) / 2] = true;\n\n        Position target;\n        bool found = false;\n\n        while (!q.empty()) {\n            Position p = q.front();\n            q.pop();\n\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + directions[i][0];\n                int ny = p.y + directions[i][1];\n\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !visited[nx][ny] && grid[nx][ny] == 0) {\n                    visited[nx][ny] = true;\n                    q.push({nx, ny});\n\n                    // Choose the last visited node as the target position\n                    target = {nx, ny};\n                    found = true;\n                }\n            }\n        }\n\n        if (found) {\n            grid[target.x][target.y] = t;\n            containers.push_back(target);\n            containerSet.insert(target.x * D + target.y);\n            cout << target.x << \" \" << target.y << endl;\n            cout.flush();\n        }\n    }\n\n    // Transport containers out\n    for (int i = 0; i < D * D - 1 - N; ++i) {\n        queue<Position> q;\n        vector<vector<bool>> visited(D, vector<bool>(D, false));\n        q.push({0, (D - 1) / 2});\n        visited[0][(D - 1) / 2] = true;\n\n        Position target;\n        int minNum = D * D;\n\n        while (!q.empty()) {\n            Position p = q.front();\n            q.pop();\n\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + directions[i][0];\n                int ny = p.y + directions[i][1];\n\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !visited[nx][ny]) {\n                    if (grid[nx][ny] >= 0 && grid[nx][ny] < minNum) {\n                        minNum = grid[nx][ny];\n                        target = {nx, ny};\n                    }\n\n                    visited[nx][ny] = true;\n                    q.push({nx, ny});\n                }\n            }\n        }\n\n        if (minNum != D * D) {\n            cout << target.x << \" \" << target.y << endl;\n            grid[target.x][target.y] = 0;\n        }\n    }\n\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm> // Include the algorithm header\n\nusing namespace std;\n\nconst int N = 50;\nconst int M = 100;\n\nint grid[N][N];\nint output[N][N];\nunordered_map<int, pair<int, int>> seeds;\nunordered_set<int> adjacentColors[M + 1];\n\nvoid readInput() {\n    int n, m;\n    cin >> n >> m;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> grid[i][j];\n            if (seeds.find(grid[i][j]) == seeds.end()) {\n                seeds[grid[i][j]] = {i, j};\n            }\n            output[i][j] = 0; // Initialize output grid\n        }\n    }\n}\n\nvoid buildAdjacencyGraph() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int color = grid[i][j];\n            if (i > 0 && grid[i - 1][j] != color) {\n                adjacentColors[color].insert(grid[i - 1][j]);\n            }\n            if (j > 0 && grid[i][j - 1] != color) {\n                adjacentColors[color].insert(grid[i][j - 1]);\n            }\n            if (i < N - 1 && grid[i + 1][j] != color) {\n                adjacentColors[color].insert(grid[i + 1][j]);\n            }\n            if (j < N - 1 && grid[i][j + 1] != color) {\n                adjacentColors[color].insert(grid[i][j + 1]);\n            }\n        }\n    }\n}\n\nvoid processColors() {\n    vector<int> colors;\n    for (int i = 1; i <= M; i++) {\n        colors.push_back(i);\n    }\n    sort(colors.begin(), colors.end(), [&adjColors = adjacentColors](int a, int b) {\n        return adjColors[a].size() > adjColors[b].size();\n    });\n\n    for (int color : colors) {\n        int x = seeds[color].first;\n        int y = seeds[color].second;\n        output[x][y] = color;\n        queue<pair<int, int>> q;\n        q.push({x, y});\n        while (!q.empty()) {\n            x = q.front().first;\n            y = q.front().second;\n            q.pop();\n            if (x > 0 && grid[x - 1][y] == color && output[x - 1][y] == 0) {\n                output[x - 1][y] = color;\n                q.push({x - 1, y});\n            }\n            if (y > 0 && grid[x][y - 1] == color && output[x][y - 1] == 0) {\n                output[x][y - 1] = color;\n                q.push({x, y - 1});\n            }\n            if (x < N - 1 && grid[x + 1][y] == color && output[x + 1][y] == 0) {\n                output[x + 1][y] = color;\n                q.push({x + 1, y});\n            }\n            if (y < N - 1 && grid[x][y + 1] == color && output[x][y + 1] == 0) {\n                output[x][y + 1] = color;\n                q.push({x, y + 1});\n            }\n        }\n    }\n}\n\nvoid outputResult() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cout << output[i][j] << \" \";\n        }\n        cout << endl;\n    }\n}\n\nint main() {\n    readInput();\n    buildAdjacencyGraph();\n    processColors();\n    outputResult();\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n\nint main() {\n    int N, D, Q;\n    std::cin >> N >> D >> Q;\n\n    // Initialize random number generator\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> dis(0, N - 1);\n\n    // Estimate weights using a more sophisticated comparison strategy\n    std::vector<double> weights(N, 0.0);\n    for (int q = 0; q < Q; ++q) {\n        // Generate comparison subsets using a binary search-like approach\n        int i = dis(gen) % N;\n        int j = dis(gen) % N;\n        while (j == i) {\n            j = dis(gen) % N;\n        }\n\n        std::cout << \"1 1 \" << i << \" \" << j << std::endl;\n        char result;\n        std::cin >> result;\n\n        if (result == '<') {\n            weights[i] -= 1.0;\n            weights[j] += 1.0;\n        } else if (result == '>') {\n            weights[i] += 1.0;\n            weights[j] -= 1.0;\n        }\n    }\n\n    // Cluster or partition items into D subsets using a more advanced algorithm\n    std::vector<int> division(N);\n    std::vector<std::pair<double, int>> sorted_weights(N);\n    for (int i = 0; i < N; ++i) {\n        sorted_weights[i] = std::make_pair(weights[i], i);\n    }\n    std::sort(sorted_weights.begin(), sorted_weights.end());\n\n    int subset = 0;\n    for (int i = 0; i < N; ++i) {\n        division[sorted_weights[i].second] = subset;\n        subset = (subset + 1) % D;\n    }\n\n    // Output division\n    for (int i = 0; i < N; ++i) {\n        std::cout << division[i] << \" \";\n    }\n    std::cout << std::endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int n = 200;\nconst int m = 10;\n\nvector<int> stacks[m];\nbool carried_out[n + 1];\nvector<pair<int, int>> operations;\n\nvoid move_box(int v, int dest_stack) {\n    for (int i = 0; i < m; ++i) {\n        auto& stack = stacks[i];\n        if (find(stack.begin(), stack.end(), v) != stack.end()) {\n            int idx = distance(stack.begin(), find(stack.begin(), stack.end(), v));\n            int energy = stack.size() - idx;\n            operations.emplace_back(v, dest_stack + 1);\n            vector<int> temp(stack.begin() + idx, stack.end());\n            stack.erase(stack.begin() + idx, stack.end());\n            stacks[dest_stack].insert(stacks[dest_stack].end(), temp.begin(), temp.end());\n            return;\n        }\n    }\n}\n\nint main() {\n    int b[m][n / m];\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < n / m; ++j) {\n            cin >> b[i][j];\n            stacks[i].push_back(b[i][j]);\n        }\n    }\n\n    for (int v = 1; v <= n; ++v) {\n        int top_stack = -1;\n        for (int i = 0; i < m; ++i) {\n            if (!stacks[i].empty() && stacks[i].back() == v) {\n                top_stack = i;\n                break;\n            }\n        }\n\n        if (top_stack != -1) {\n            operations.emplace_back(v, 0);\n            carried_out[v] = true;\n            stacks[top_stack].pop_back();\n        } else {\n            // Find the stack containing v and move it to an appropriate stack\n            int src_stack = -1;\n            for (int i = 0; i < m; ++i) {\n                auto& stack = stacks[i];\n                auto it = find(stack.begin(), stack.end(), v);\n                if (it != stack.end()) {\n                    src_stack = i;\n                    break;\n                }\n            }\n\n            if (src_stack == -1) {\n                cerr << \"Box \" << v << \" not found.\" << endl;\n                return 1;\n            }\n\n            int dest_stack = -1;\n            int min_top = n + 1;\n            for (int i = 0; i < m; ++i) {\n                if (stacks[i].empty() || (stacks[i].back() > v && stacks[i].back() < min_top)) {\n                    dest_stack = i;\n                    min_top = stacks[i].empty() ? n + 1 : stacks[i].back();\n                }\n            }\n\n            if (dest_stack == -1) {\n                // If no suitable stack is found, just pick any non-empty stack\n                for (int i = 0; i < m; ++i) {\n                    if (!stacks[i].empty()) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n\n            move_box(v, dest_stack);\n            // After moving, check again if v is at the top\n            for (int i = 0; i < m; ++i) {\n                if (!stacks[i].empty() && stacks[i].back() == v) {\n                    operations.emplace_back(v, 0);\n                    carried_out[v] = true;\n                    stacks[i].pop_back();\n                    break;\n                }\n            }\n        }\n    }\n\n    for (const 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>\n#include <stack>\n#include <random>\n\nusing namespace std;\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<bool>> visited;\n\nvoid dfs(int i, int j, vector<char>& route) {\n    visited[i][j] = true;\n    int di[] = {0, 1, 0, -1};\n    int dj[] = {1, 0, -1, 0};\n    char dir[] = {'R', 'D', 'L', 'U'};\n\n    random_device rd;\n    mt19937 g(rd());\n    vector<int> directions = {0, 1, 2, 3};\n    shuffle(directions.begin(), directions.end(), g);\n\n    for (int k : directions) {\n        int i2 = i + di[k];\n        int j2 = j + dj[k];\n        if (0 <= i2 && i2 < N && 0 <= j2 && j2 < N && !visited[i2][j2]) {\n            if (di[k] == 0 && v[i][min(j, j2)] == '0' || dj[k] == 0 && h[min(i, i2)][j] == '0') {\n                route.push_back(dir[k]);\n                dfs(i2, j2, route);\n                route.push_back(dir[(k + 2) % 4]);\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> N;\n    h.resize(N - 1);\n    v.resize(N);\n    d.resize(N, vector<int>(N));\n    visited.resize(N, vector<bool>(N, false));\n\n    for (int i = 0; i < N - 1; i++) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\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<char> route;\n    dfs(0, 0, route);\n\n    // Simple route optimization: remove consecutive duplicates\n    string optimizedRoute;\n    for (char c : route) {\n        if (optimizedRoute.empty() || c != optimizedRoute.back()) {\n            optimizedRoute += c;\n        }\n    }\n\n    cout << optimizedRoute << endl;\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Position {\n    int i, j;\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n\n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> t[i];\n    }\n\n    unordered_map<char, vector<Position>> charPositions;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            charPositions[grid[i][j]].push_back({i, j});\n        }\n    }\n\n    vector<Position> currentPos = {{si, sj}};\n    string S = \"\";\n    vector<pair<int, int>> operations;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int step = 0; step < 5000; ++step) {\n        int bestI = -1, bestJ = -1;\n        int bestCost = 1e9;\n        char bestChar = '\\0';\n\n        // Limit the search to a smaller radius around the current position\n        int radius = min(N, 5);\n        for (int di = -radius; di <= radius; ++di) {\n            for (int dj = -radius; dj <= radius; ++dj) {\n                int i = currentPos.back().i + di;\n                int j = currentPos.back().j + dj;\n                if (i >= 0 && i < N && j >= 0 && j < N) {\n                    int cost = abs(di) + abs(dj) + 1;\n                    char c = grid[i][j];\n                    string newS = S + c;\n\n                    // Simple heuristic: prefer characters that are the next character in some t_k\n                    int score = 0;\n                    for (const auto& tk : t) {\n                        if (newS.size() <= tk.size() && tk.substr(0, newS.size()) == newS) {\n                            score += 1;\n                        }\n                    }\n\n                    if (cost < bestCost || (cost == bestCost && score > 0)) {\n                        bestI = i;\n                        bestJ = j;\n                        bestCost = cost;\n                        bestChar = c;\n                    }\n                }\n            }\n        }\n\n        if (bestI != -1) {\n            currentPos.push_back({bestI, bestJ});\n            S += bestChar;\n            operations.push_back({bestI, bestJ});\n        } else {\n            // If no better move is found, just move to a random position\n            int i = dis(gen) % N;\n            int j = dis(gen) % N;\n            currentPos.push_back({i, j});\n            S += grid[i][j];\n            operations.push_back({i, j});\n        }\n    }\n\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc030":"int main() {\n    read_input();\n    vector<vector<int>> estimated_oil_reserves(N, vector<int>(N, -1));\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dis(0, N - 1);\n\n    for (int i = 0; i < N * N; ++i) {\n        int x = dis(gen);\n        int y = dis(gen);\n        if (estimated_oil_reserves[x][y] == -1) {\n            drill(x, y);\n            // Update estimated_oil_reserves based on the response\n        }\n    }\n\n    // Generate a guess based on estimated_oil_reserves\n    vector<pair<int, int>> guess_squares;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (estimated_oil_reserves[i][j] > 0) {\n                guess_squares.emplace_back(i, j);\n            }\n        }\n    }\n    guess(guess_squares);\n\n    return 0;\n}","ahc031":"```cpp\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int W = 1000;\n\nstruct Rectangle {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    int D, N;\n    cin >> D >> N;\n\n    vector<vector<int>> areas(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> areas[d][k];\n        }\n    }\n\n    vector<vector<Rectangle>> rectangles(D, vector<Rectangle>(N));\n\n    // Initial placement for the first day\n    vector<pair<int, int>> sizes(N);\n    for (int k = 0; k < N; k++) {\n        sizes[k] = {areas[0][k], k};\n    }\n    sort(sizes.begin(), sizes.end());\n\n    int x = 0, y = 0;\n    for (auto [area, k] : sizes) {\n        int w = min(W - x, (int)sqrt(area));\n        int h = (area + w - 1) / w;\n        rectangles[0][k] = {x, y, x + w, y + h};\n        x += w;\n        if (x >= W) {\n            x = 0;\n            y += h;\n        }\n    }\n\n    // Subsequent days\n    for (int d = 1; d < D; d++) {\n        vector<pair<int, int>> sizes(N);\n        for (int k = 0; k < N; k++) {\n            sizes[k] = {areas[d][k], k};\n        }\n        sort(sizes.begin(), sizes.end());\n\n        for (auto [area, k] : sizes) {\n            Rectangle prev_rect = rectangles[d - 1][k];\n            int w = min(W - prev_rect.x1, (int)sqrt(area));\n            int h = (area + w - 1) / w;\n            rectangles[d][k] = {prev_rect.x1, prev_rect.y1, prev_rect.x1 + w, prev_rect.y1 + h};\n        }\n    }\n\n    // Output the rectangle coordinates\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cout << rectangles[d][k].x1 << \" \" << rectangles[d][k].y1 << \" \" << rectangles[d][k].x2 << \" \" << rectangles[d][k].y2 << endl;\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nstruct Operation {\n    int stamp_id;\n    int x, y;\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    int grid[N][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    int stamps[M][3][3];\n    for (int m = 0; m < M; ++m) {\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                cin >> stamps[m][i][j];\n            }\n        }\n    }\n\n    vector<Operation> operations;\n\n    for (int k = 0; k < K; ++k) {\n        int best_stamp_id = -1, best_x = -1, best_y = -1;\n        int max_increase = 0;\n\n        for (int stamp_id = 0; stamp_id < M; ++stamp_id) {\n            for (int x = 0; x <= N - 3; ++x) {\n                for (int y = 0; y <= N - 3; ++y) {\n                    int new_grid[N][N];\n                    copy(&grid[0][0], &grid[0][0] + N * N, &new_grid[0][0]);\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            new_grid[x + i][y + j] += stamps[stamp_id][i][j];\n                        }\n                    }\n                    int new_sum = 0;\n                    for (int i = 0; i < N; ++i) {\n                        for (int j = 0; j < N; ++j) {\n                            new_sum = (new_sum + new_grid[i][j] % MOD) % MOD;\n                        }\n                    }\n                    int current_sum = 0;\n                    for (int i = 0; i < N; ++i) {\n                        for (int j = 0; j < N; ++j) {\n                            current_sum = (current_sum + grid[i][j] % MOD) % MOD;\n                        }\n                    }\n                    int increase = new_sum - current_sum;\n                    if (increase > max_increase) {\n                        max_increase = increase;\n                        best_stamp_id = stamp_id;\n                        best_x = x;\n                        best_y = y;\n                    }\n                }\n            }\n        }\n\n        if (max_increase > 0) {\n            for (int i = 0; i < 3; ++i) {\n                for (int j = 0; j < 3; ++j) {\n                    grid[best_x + i][best_y + j] += stamps[best_stamp_id][i][j];\n                }\n            }\n            operations.push_back({best_stamp_id, best_x, best_y});\n        } else {\n            break;\n        }\n    }\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.stamp_id << \" \" << op.x << \" \" << op.y << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURN = 10000;\n\nstruct Crane {\n    int x, y;\n    bool holding;\n    int container;\n};\n\nint grid[N][N];\nCrane cranes[N];\nvector<int> containersToDispatch[N];\nint turn = 0;\n\nvoid simulate() {\n    vector<string> operations(N, \"\");\n    // Simulate the container dispatch process\n    while (turn < MAX_TURN) {\n        // Bring in new containers\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][0] == -1 && !containersToDispatch[i].empty()) {\n                grid[i][0] = containersToDispatch[i].back();\n                containersToDispatch[i].pop_back();\n            }\n        }\n\n        // Determine the next action for each crane\n        for (int i = 0; i < N; ++i) {\n            char operation = '.';\n            // Simple logic to move cranes towards the dispatch gates\n            if (cranes[i].y < N - 1 && !cranes[i].holding) {\n                operation = 'R';\n                cranes[i].y++;\n            } else if (cranes[i].holding && cranes[i].y == N - 1) {\n                operation = 'Q';\n                grid[cranes[i].x][cranes[i].y] = cranes[i].container;\n                cranes[i].holding = false;\n            } else if (!cranes[i].holding && grid[cranes[i].x][cranes[i].y] != -1) {\n                operation = 'P';\n                cranes[i].container = grid[cranes[i].x][cranes[i].y];\n                grid[cranes[i].x][cranes[i].y] = -1;\n                cranes[i].holding = true;\n            }\n            operations[i] += operation;\n        }\n\n        // Dispatch containers\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][N - 1] != -1) {\n                // Dispatch the container\n                grid[i][N - 1] = -1;\n            }\n        }\n\n        turn++;\n        bool allDone = true;\n        for (int i = 0; i < N; ++i) {\n            if (!containersToDispatch[i].empty()) {\n                allDone = false;\n                break;\n            }\n        }\n        if (allDone) {\n            break;\n        }\n    }\n\n    // Output the operations for each crane\n    for (int i = 0; i < N; ++i) {\n        while (operations[i].length() < turn) {\n            operations[i] += '.';\n        }\n        cout << operations[i] << endl;\n    }\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector<vector<int>> A(n, vector<int>(n));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> A[i][j];\n            containersToDispatch[i].push_back(A[i][j]);\n        }\n        reverse(containersToDispatch[i].begin(), containersToDispatch[i].end());\n    }\n\n    // Initialize the grid and cranes\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            grid[i][j] = -1;\n        }\n        cranes[i].x = i;\n        cranes[i].y = 0;\n        cranes[i].holding = false;\n    }\n\n    simulate();\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 20;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nint h[N][N];\nint loaded = 0;\npair<int, int> pos = {0, 0};\n\nvoid load(int d) {\n    cout << \"+\" << d << endl;\n    h[pos.first][pos.second] -= d;\n    loaded += d;\n}\n\nvoid unload(int d) {\n    cout << \"-\" << d << endl;\n    h[pos.first][pos.second] += d;\n    loaded -= d;\n}\n\nvoid move(int d) {\n    cout << dir[d] << endl;\n    pos.first += dx[d];\n    pos.second += dy[d];\n}\n\nint main() {\n    cin >> N;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h[i][j];\n        }\n    }\n\n    // Initial loading/unloading at (0,0)\n    if (h[0][0] > 0) {\n        load(min(h[0][0], 1000000));\n    } else if (h[0][0] < 0) {\n        unload(min(-h[0][0], loaded));\n    }\n\n    // Greedy algorithm\n    priority_queue<pair<int, pair<int, int>>> pq;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (h[i][j] != 0) {\n                pq.push({abs(h[i][j]), {i, j}});\n            }\n        }\n    }\n\n    while (!pq.empty()) {\n        auto [val, pos2] = pq.top();\n        pq.pop();\n        int x = pos2.first, y = pos2.second;\n\n        // Move to (x, y)\n        int min_dist = abs(pos.first - x) + abs(pos.second - y);\n        while (pos.first != x || pos.second != y) {\n            for (int d = 0; d < 4; d++) {\n                int nx = pos.first + dx[d], ny = pos.second + dy[d];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N && abs(nx - x) + abs(ny - y) < min_dist) {\n                    move(d);\n                    min_dist = abs(pos.first - x) + abs(pos.second - y);\n                    break;\n                }\n            }\n        }\n\n        // Load/unload at (x, y)\n        if (h[x][y] > 0) {\n            load(min(h[x][y], 1000000));\n        } else if (h[x][y] < 0) {\n            unload(min(-h[x][y], loaded));\n        }\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Seed {\n    int id;\n    vector<int> eval;\n    int value;\n};\n\nbool compareSeeds(const Seed& a, const Seed& b) {\n    return a.value > b.value;\n}\n\nint main() {\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seedCount = 2 * N * (N - 1);\n    vector<Seed> seeds(seedCount);\n\n    for (int i = 0; i < seedCount; i++) {\n        seeds[i].id = i;\n        seeds[i].eval.resize(M);\n        seeds[i].value = 0;\n\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i].eval[j];\n            seeds[i].value += seeds[i].eval[j];\n        }\n    }\n\n    sort(seeds.begin(), seeds.end(), compareSeeds);\n\n    for (int t = 0; t < T; t++) {\n        vector<vector<int>> grid(N, vector<int>(N));\n\n        // Greedy grid arrangement\n        int idx = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                grid[i][j] = seeds[idx].id;\n                idx++;\n            }\n        }\n\n        // Output grid arrangement\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                else cout << endl;\n            }\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seedCount; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> seeds[i].eval[j];\n                seeds[i].value = 0;\n                for (int k = 0; k < M; k++) {\n                    seeds[i].value += seeds[i].eval[k];\n                }\n            }\n        }\n\n        sort(seeds.begin(), seeds.end(), compareSeeds);\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n\nint main() {\n    int N, M, V;\n    std::cin >> N >> M >> V;\n\n    std::vector<std::vector<int>> s(N, std::vector<int>(N));\n    std::vector<std::vector<int>> t(N, std::vector<int>(N));\n\n    for (int i = 0; i < N; ++i) {\n        std::string str;\n        std::cin >> str;\n        for (int j = 0; j < N; ++j) {\n            s[i][j] = str[j] - '0';\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        std::string str;\n        std::cin >> str;\n        for (int j = 0; j < N; ++j) {\n            t[i][j] = str[j] - '0';\n        }\n    }\n\n    // Design the robotic arm\n    int V_prime = std::min(V, M + 1);\n    std::cout << V_prime << std::endl;\n    for (int i = 1; i < V_prime; ++i) {\n        std::cout << 0 << \" \" << 1 << std::endl;\n    }\n\n    // Initial position of the root\n    int rx = N / 2, ry = N / 2;\n    std::cout << rx << \" \" << ry << std::endl;\n\n    // Sequence of operations\n    for (int turn = 0; turn < 100; ++turn) {\n        std::string op(2 * V_prime, '.');\n        // Simple random movement for demonstration\n        if (rx > 0 && rand() % 2) {\n            rx--;\n            op[0] = 'U';\n        } else if (rx < N - 1 && rand() % 2) {\n            rx++;\n            op[0] = 'D';\n        }\n        if (ry > 0 && rand() % 2) {\n            ry--;\n            op[0] = 'L';\n        } else if (ry < N - 1 && rand() % 2) {\n            ry++;\n            op[0] = 'R';\n        }\n\n        // Random rotation for demonstration\n        if (V_prime > 1 && rand() % 2) {\n            op[1] = 'L';\n        }\n\n        // Grab or release takoyaki for demonstration\n        if (rand() % 2) {\n            op[V_prime] = 'P';\n        }\n\n        std::cout << op << std::endl;\n    }\n\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cstddef> // Include this for std::size_t and std::ptrdiff_t\n\nstruct Point {\n    int x, y;\n};\n\nint main() {\n    int N;\n    std::cin >> N;\n\n    std::vector<Point> points(2*N);\n    for (int i = 0; i < 2*N; ++i) {\n        std::cin >> points[i].x >> points[i].y;\n    }\n\n    std::vector<Point> mackerels(points.begin(), points.begin() + N);\n    std::vector<Point> sardines(points.begin() + N, points.end());\n\n    int minX = std::min_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.x < b.x; })->x;\n    int maxX = std::max_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.x < b.x; })->x;\n    int minY = std::min_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.y < b.y; })->y;\n    int maxY = std::max_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.y < b.y; })->y;\n\n    std::vector<Point> polygon = {{minX, minY}, {maxX, minY}, {maxX, maxY}, {minX, maxY}};\n\n    std::cout << polygon.size() << std::endl;\n    for (const auto& point : polygon) {\n        std::cout << point.x << \" \" << point.y << std::endl;\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nstruct Rectangle {\n    int index;\n    int w, h;\n};\n\nbool compareRectangles(const Rectangle& a, const Rectangle& b) {\n    return std::max(a.w, a.h) > std::max(b.w, b.h);\n}\n\nint main() {\n    int N, T;\n    double sigma;\n    std::cin >> N >> T >> sigma;\n\n    std::vector<Rectangle> rectangles(N);\n    for (int i = 0; i < N; ++i) {\n        rectangles[i].index = i;\n        std::cin >> rectangles[i].w >> rectangles[i].h;\n    }\n\n    std::sort(rectangles.begin(), rectangles.end(), compareRectangles);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> dis(0, 1);\n\n    for (int t = 0; t < T; ++t) {\n        std::vector<Rectangle> placedRectangles;\n        std::vector<std::pair<int, int>> positions(N, std::make_pair(0, 0));\n\n        int n = N; // Number of rectangles to place\n\n        std::cout << n << std::endl;\n        for (int i = 0; i < n; ++i) {\n            Rectangle rect = rectangles[i];\n            int rotation = dis(gen);\n            char direction = (dis(gen) == 0) ? 'U' : 'L';\n            int reference = (i == 0) ? -1 : (dis(gen) == 0) ? -1 : placedRectangles[dis(gen) % placedRectangles.size()].index;\n\n            if (rotation == 1) {\n                std::swap(rect.w, rect.h);\n            }\n\n            std::cout << rect.index << \" \" << rotation << \" \" << direction << \" \" << reference << std::endl;\n\n            // Update the positions vector\n            if (direction == 'U') {\n                if (reference == -1) {\n                    positions[rect.index].first = 0;\n                    positions[rect.index].second = 0;\n                } else {\n                    // Find the reference rectangle and update the position accordingly\n                    for (const auto& placedRect : placedRectangles) {\n                        if (placedRect.index == reference) {\n                            positions[rect.index].first = positions[placedRect.index].first;\n                            positions[rect.index].second = positions[placedRect.index].second - rect.h;\n                            break;\n                        }\n                    }\n                }\n            } else {\n                if (reference == -1) {\n                    positions[rect.index].first = 0;\n                    positions[rect.index].second = 0;\n                } else {\n                    // Find the reference rectangle and update the position accordingly\n                    for (const auto& placedRect : placedRectangles) {\n                        if (placedRect.index == reference) {\n                            positions[rect.index].first = positions[placedRect.index].first + placedRect.w;\n                            positions[rect.index].second = positions[placedRect.index].second;\n                            break;\n                        }\n                    }\n                }\n            }\n\n            placedRectangles.push_back(rect);\n        }\n\n        std::cout.flush();\n\n        int W, H;\n        std::cin >> W >> H;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n};\n\nint main() {\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<Edge> edges(M);\n    for (int i = 0; i < M; i++) {\n        cin >> edges[i].u >> edges[i].v;\n    }\n\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<int> parent(N, -1);\n    vector<vector<int>> graph(N);\n    for (const auto& edge : edges) {\n        graph[edge.u].push_back(edge.v);\n        graph[edge.v].push_back(edge.u);\n    }\n\n    // Perform a BFS traversal to construct the rooted trees\n    queue<int> q;\n    vector<bool> visited(N, false);\n    vector<int> roots;\n    for (int i = 0; i < N; i++) {\n        if (!visited[i]) {\n            roots.push_back(i);\n            q.push(i);\n            visited[i] = true;\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (int v : graph[u]) {\n                    if (!visited[v]) {\n                        visited[v] = true;\n                        parent[v] = u;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n\n    // Make sure the height constraint is satisfied\n    for (int i = 0; i < N; i++) {\n        if (i != roots[0] && parent[i] != -1) {\n            int height = 0;\n            int v = i;\n            while (v != roots[0]) {\n                height++;\n                v = parent[v];\n                if (height > H) {\n                    parent[i] = -1; // Make i a root if height exceeds H\n                    break;\n                }\n            }\n        }\n    }\n\n    // Output the parent of each vertex\n    for (int i = 0; i < N; i++) {\n        cout << parent[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n\nusing namespace std;\n\nconst int N = 20;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nint main() {\n    int n;\n    cin >> n;\n    vector<string> grid(n);\n    for (int i = 0; i < n; i++) {\n        cin >> grid[i];\n    }\n\n    vector<pair<char, int>> operations;\n    queue<pair<int, int>> oniQueue;\n\n    // Iterate through the grid to identify Oni positions\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            if (grid[i][j] == 'x') {\n                oniQueue.push({i, j});\n            }\n        }\n    }\n\n    while (!oniQueue.empty()) {\n        int x = oniQueue.front().first;\n        int y = oniQueue.front().second;\n        oniQueue.pop();\n\n        if (grid[x][y] != 'x') continue;\n\n        // Check if there is no Fukunokami in any direction\n        for (int k = 0; k < 4; k++) {\n            int count = 0;\n            int nx = x + dx[k];\n            int ny = y + dy[k];\n            while (nx >= 0 && nx < n && ny >= 0 && ny < n) {\n                if (grid[nx][ny] == 'o') break;\n                count++;\n                nx += dx[k];\n                ny += dy[k];\n            }\n\n            if (nx < 0 || nx >= n || ny < 0 || ny >= n) {\n                // Shift in the direction that does not contain a Fukunokami\n                if (k == 0) { // Up\n                    for (int i = 0; i <= x; i++) {\n                        operations.push_back({'U', y});\n                    }\n                    for (int i = 0; i <= x; i++) {\n                        operations.push_back({'D', y});\n                    }\n                } else if (k == 1) { // Down\n                    for (int i = x; i < n - 1; i++) {\n                        operations.push_back({'D', y});\n                    }\n                    for (int i = x; i < n - 1; i++) {\n                        operations.push_back({'U', y});\n                    }\n                } else if (k == 2) { // Left\n                    for (int i = 0; i <= y; i++) {\n                        operations.push_back({'L', x});\n                    }\n                    for (int i = 0; i <= y; i++) {\n                        operations.push_back({'R', x});\n                    }\n                } else if (k == 3) { // Right\n                    for (int i = y; i < n - 1; i++) {\n                        operations.push_back({'R', x});\n                    }\n                    for (int i = y; i < n - 1; i++) {\n                        operations.push_back({'L', x});\n                    }\n                }\n\n                // Update the grid to reflect the removal of the Oni\n                grid[x][y] = '.';\n                break;\n            }\n        }\n    }\n\n    // Output the sequence of operations\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nconst int N = 100;\nconst int L = 500000;\n\nvector<int> T(N);\nvector<int> a(N), b(N);\nvector<int> count(N, 0);\nmt19937 mt(42);\n\nvoid simulate(int steps) {\n    uniform_int_distribution<int> dist(0, N-1);\n    for (int step = 0; step < steps; ++step) {\n        int i = dist(mt);\n        int orig_a = a[i], orig_b = b[i];\n        int new_a = dist(mt), new_b = dist(mt);\n        a[i] = new_a;\n        b[i] = new_b;\n        count.assign(N, 0);\n        int last = 0;\n        count[0] = 1;\n        for (int t = 1; t < L; ++t) {\n            int next = (count[last] % 2 == 0) ? b[last] : a[last];\n            count[next]++;\n            last = next;\n        }\n        int new_error = accumulate(count.begin(), count.end(), 0, [&](int sum, int c, int i) { return sum + abs(c - T[i]); });\n        if (new_error > accumulate(count.begin(), count.end(), 0, [&](int sum, int c, int i) { return sum + abs(c - T[i]); })) {\n            a[i] = orig_a;\n            b[i] = orig_b;\n        }\n    }\n}\n\nint main() {\n    cin >> N >> L;\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    // Initialize a and b\n    for (int i = 0; i < N; ++i) {\n        a[i] = (i + 1) % N;\n        b[i] = (i + 2) % N;\n    }\n\n    simulate(100000);\n\n    for (int i = 0; i < N; ++i) {\n        cout << a[i] << \" \" << b[i] << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cassert>\n\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double x, y;\n};\n\nstruct Edge {\n    int u, v;\n};\n\nint N, M, Q, L, W;\nvector<int> G;\nvector<City> cities;\nvector<vector<int>> groups;\nvector<vector<Edge>> edges;\n\nvoid readInput() {\n    cin >> N >> M >> Q >> L >> W;\n    G.resize(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n    cities.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].id = i;\n        cities[i].x = (cities[i].lx + cities[i].rx) / 2.0;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2.0;\n    }\n}\n\nvoid initialGrouping() {\n    sort(cities.begin(), cities.end(), [](const City& a, const City& b) {\n        return make_pair(a.x, a.y) < make_pair(b.x, b.y);\n    });\n    groups.resize(M);\n    int start = 0;\n    for (int i = 0; i < M; ++i) {\n        groups[i].resize(G[i]);\n        for (int j = 0; j < G[i]; ++j) {\n            groups[i][j] = cities[start + j].id;\n        }\n        start += G[i];\n    }\n}\n\nvoid queryFortuneTeller(const vector<int>& group) {\n    if (group.size() <= 1) return;\n    vector<Edge> mstEdges;\n    if (group.size() <= L) {\n        cout << \"? \" << group.size();\n        for (int city : group) cout << \" \" << city;\n        cout << endl;\n        for (int i = 0; i < group.size() - 1; ++i) {\n            int u, v;\n            cin >> u >> v;\n            mstEdges.push_back({u, v});\n        }\n        edges.push_back(mstEdges);\n    } else {\n        // For larger groups, divide them into smaller subsets and query\n        for (size_t i = 0; i < group.size(); i += L - 1) {\n            vector<int> subset;\n            for (size_t j = i; j < min(i + L - 1, group.size()); ++j) {\n                subset.push_back(group[j]);\n            }\n            if (subset.size() > 1) {\n                cout << \"? \" << subset.size();\n                for (int city : subset) cout << \" \" << city;\n                cout << endl;\n                vector<Edge> subsetMstEdges;\n                for (int k = 0; k < subset.size() - 1; ++k) {\n                    int u, v;\n                    cin >> u >> v;\n                    subsetMstEdges.push_back({u, v});\n                }\n                mstEdges.insert(mstEdges.end(), subsetMstEdges.begin(), subsetMstEdges.end());\n            }\n        }\n        edges.push_back(mstEdges);\n    }\n}\n\nvoid buildRoads() {\n    edges.clear();\n    for (const auto& group : groups) {\n        queryFortuneTeller(group);\n    }\n}\n\nvoid outputAnswer() {\n    cout << \"!\" << endl;\n    for (size_t i = 0; i < groups.size(); ++i) {\n        for (int city : groups[i]) cout << city << \" \";\n        cout << endl;\n        for (const auto& edge : edges[i]) cout << edge.u << \" \" << edge.v << endl;\n    }\n}\n\nint main() {\n    readInput();\n    initialGrouping();\n    buildRoads();\n    outputAnswer();\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n\nusing namespace std;\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n\n    vector<vector<int>> grid(N, vector<int>(N, 0)); // 0: empty, 1: block\n\n    struct Pos {\n        int x, y;\n    };\n\n    Pos pos;\n    cin >> pos.x >> pos.y;\n    vector<Pos> targets(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> targets[i].x >> targets[i].y;\n    }\n\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    char dirChar[] = {'U', 'D', 'L', 'R'};\n\n    auto manhattanDistance = [](Pos a, Pos b) {\n        return abs(a.x - b.x) + abs(a.y - b.y);\n    };\n\n    auto slide = [&](int x, int y, int dir, Pos &end) {\n        int nx = x + dx[dir];\n        int ny = y + dy[dir];\n        while (0 <= nx && nx < N && 0 <= ny && ny < N && grid[nx][ny] == 0) {\n            x = nx;\n            y = ny;\n            nx += dx[dir];\n            ny += dy[dir];\n        }\n        end.x = x;\n        end.y = y;\n    };\n\n    for (int targetIndex = 0; targetIndex < M; ++targetIndex) {\n        Pos target = targets[targetIndex];\n        while (pos.x != target.x || pos.y != target.y) {\n            int bestDir = -1;\n            char bestAction = ' ';\n            Pos nextPos = pos;\n            int minDist = manhattanDistance(pos, target);\n\n            for (int dir = 0; dir < 4; ++dir) {\n                int nx = pos.x + dx[dir];\n                int ny = pos.y + dy[dir];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                    // Try Move\n                    if (grid[nx][ny] == 0) {\n                        int dist = manhattanDistance({nx, ny}, target);\n                        if (dist < minDist) {\n                            minDist = dist;\n                            bestDir = dir;\n                            bestAction = 'M';\n                            nextPos = {nx, ny};\n                        }\n                    }\n\n                    // Try Slide\n                    Pos slideEnd = pos;\n                    slide(pos.x, pos.y, dir, slideEnd);\n                    if (slideEnd.x != pos.x || slideEnd.y != pos.y) {\n                        int dist = manhattanDistance(slideEnd, target);\n                        if (dist < minDist && (slideEnd.x != target.x || slideEnd.y != target.y)) {\n                            minDist = dist;\n                            bestDir = dir;\n                            bestAction = 'S';\n                            nextPos = slideEnd;\n                        }\n                    }\n                }\n\n                // Try Alter\n                if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                    int originalBlock = grid[nx][ny];\n                    grid[nx][ny] = 1 - originalBlock;\n                    Pos slideEndAfterAlter = pos;\n                    slide(pos.x, pos.y, dir, slideEndAfterAlter);\n                    int dist = manhattanDistance(slideEndAfterAlter, target);\n                    if (dist < minDist && (slideEndAfterAlter.x != target.x || slideEndAfterAlter.y != target.y)) {\n                        minDist = dist;\n                        bestDir = dir;\n                        bestAction = 'A';\n                        nextPos = pos; // Alter doesn't change pos\n                    }\n                    grid[nx][ny] = originalBlock; // Revert\n                }\n            }\n\n            if (bestAction != ' ') {\n                cout << bestAction << \" \" << dirChar[bestDir] << endl;\n                if (bestAction == 'M') {\n                    pos = nextPos;\n                } else if (bestAction == 'S') {\n                    pos = nextPos;\n                } else if (bestAction == 'A') {\n                    int nx = pos.x + dx[bestDir];\n                    int ny = pos.y + dy[bestDir];\n                    grid[nx][ny] = 1 - grid[nx][ny];\n                }\n            } else {\n                // Fallback, should ideally not reach here\n                cout << \"M U\" << endl;\n            }\n        }\n    }\n\n    return 0;\n}"},"4":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Company {\n    int x, y, r, idx;\n    bool operator<(const Company& other) const {\n        return r > other.r;\n    }\n};\n\nint main() {\n    int n;\n    cin >> n;\n\n    vector<Company> companies(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n        companies[i].idx = i;\n    }\n\n    sort(companies.begin(), companies.end());\n\n    vector<vector<int>> ans(n, vector<int>(4));\n\n    int gridSize = 10000;\n    vector<bool> used(gridSize * gridSize, false);\n\n    for (const auto& company : companies) {\n        int x = company.x, y = company.y, r = company.r, idx = company.idx;\n\n        int size = min(100, (int)sqrt(r));\n        int sx = max(0, x - size / 2), sy = max(0, y - size / 2);\n\n        bool found = false;\n        for (int i = sx; i <= min(gridSize - size, x + size / 2); ++i) {\n            for (int j = sy; j <= min(gridSize - size, y + size / 2); ++j) {\n                bool valid = true;\n                for (int k = i; k < i + size; ++k) {\n                    for (int l = j; l < j + size; ++l) {\n                        if (used[k * gridSize + l]) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                    if (!valid) break;\n                }\n\n                if (valid) {\n                    ans[idx] = {i, j, i + size, j + size};\n                    for (int k = i; k < i + size; ++k) {\n                        for (int l = j; l < j + size; ++l) {\n                            used[k * gridSize + l] = true;\n                        }\n                    }\n                    found = true;\n                    break;\n                }\n            }\n            if (found) break;\n        }\n\n        if (!found) {\n            // Fallback to a simple assignment if no suitable rectangle is found\n            ans[idx] = {0, 0, 1, 1};\n        }\n    }\n\n    for (const auto& a : ans) {\n        cout << a[0] << \" \" << a[1] << \" \" << a[2] << \" \" << a[3] << endl;\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <string>\n#include <random>\n#include <algorithm> // Include the necessary header for shuffle\n\nusing namespace std;\n\nstruct State {\n    int x, y;\n    int score;\n    string path;\n    unordered_set<int> visited_tiles;\n\n    State(int x, int y, int score, string path, unordered_set<int> visited_tiles)\n        : x(x), y(y), score(score), path(path), visited_tiles(visited_tiles) {}\n};\n\nstruct CompareStates {\n    bool operator()(const State& a, const State& b) {\n        return a.score < b.score;\n    }\n};\n\nint main() {\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> tile_ids(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> tile_ids[i][j];\n        }\n    }\n\n    vector<vector<int>> scores(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> scores[i][j];\n        }\n    }\n\n    int initial_tile_id = tile_ids[si][sj];\n    unordered_set<int> initial_visited_tiles = {initial_tile_id};\n    State initial_state(si, sj, scores[si][sj], \"\", initial_visited_tiles);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    priority_queue<State, vector<State>, CompareStates> pq;\n    pq.push(initial_state);\n\n    int max_score = initial_state.score;\n    string max_path = \"\";\n\n    for (int iter = 0; iter < 200000; ++iter) {\n        if (pq.empty()) break;\n        State state = pq.top();\n        pq.pop();\n\n        if (state.score < max_score) continue;\n\n        vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n        vector<char> moves = {'U', 'D', 'L', 'R'};\n\n        vector<int> indices(4);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), gen);\n\n        for (int i : indices) {\n            int nx = state.x + directions[i].first;\n            int ny = state.y + directions[i].second;\n\n            if (nx < 0 || nx >= 50 || ny < 0 || ny >= 50) continue;\n\n            int next_tile_id = tile_ids[nx][ny];\n            if (state.visited_tiles.count(next_tile_id)) continue;\n\n            unordered_set<int> next_visited_tiles = state.visited_tiles;\n            next_visited_tiles.insert(next_tile_id);\n\n            int next_score = state.score + scores[nx][ny];\n            string next_path = state.path + moves[i];\n\n            State next_state(nx, ny, next_score, next_path, next_visited_tiles);\n\n            if (next_score > max_score) {\n                max_score = next_score;\n                max_path = next_path;\n            }\n\n            pq.push(next_state);\n        }\n    }\n\n    cout << max_path << endl;\n\n    return 0;\n}","ahc003":"#include <iostream>\n#include <queue>\n#include <vector>\n#include <unordered_map>\n#include <limits>\n#include <algorithm> // Include algorithm for reverse\n\nusing namespace std;\n\nstruct Edge {\n    int to;\n    double weight;\n};\n\nusing Graph = vector<vector<Edge>>;\n\nstruct Node {\n    int id;\n    double distance;\n    bool operator>(const Node& other) const {\n        return distance > other.distance;\n    }\n};\n\nGraph buildGraph() {\n    Graph graph(30 * 30);\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            int id = i * 30 + j;\n            if (i > 0) graph[id].push_back({id - 30, 1}); // Up\n            if (i < 29) graph[id].push_back({id + 30, 1}); // Down\n            if (j > 0) graph[id].push_back({id - 1, 1}); // Left\n            if (j < 29) graph[id].push_back({id + 1, 1}); // Right\n        }\n    }\n    return graph;\n}\n\nstring dijkstra(Graph& graph, int source, int target) {\n    vector<double> distances(graph.size(), numeric_limits<double>::max());\n    vector<int> previous(graph.size(), -1);\n    distances[source] = 0;\n\n    priority_queue<Node, vector<Node>, greater<Node>> queue;\n    queue.push({source, 0});\n\n    while (!queue.empty()) {\n        Node node = queue.top();\n        queue.pop();\n        if (node.id == target) break;\n\n        for (const Edge& edge : graph[node.id]) {\n            double newDistance = distances[node.id] + edge.weight;\n            if (newDistance < distances[edge.to]) {\n                distances[edge.to] = newDistance;\n                previous[edge.to] = node.id;\n                queue.push({edge.to, newDistance});\n            }\n        }\n    }\n\n    string path;\n    int current = target;\n    while (current != source) {\n        int prev = previous[current];\n        if (prev == current - 1) path += 'R';\n        else if (prev == current + 1) path += 'L';\n        else if (prev == current - 30) path += 'D';\n        else if (prev == current + 30) path += 'U';\n        current = prev;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nvoid updateGraph(Graph& graph, const string& path, double actualLength) {\n    double scaleFactor = actualLength / path.length(); // Simplified calculation\n\n    int currentNode = 0;\n    for (char direction : path) {\n        int nextNode;\n        if (direction == 'U') nextNode = currentNode - 30;\n        else if (direction == 'D') nextNode = currentNode + 30;\n        else if (direction == 'L') nextNode = currentNode - 1;\n        else if (direction == 'R') nextNode = currentNode + 1;\n\n        for (Edge& edge : graph[currentNode]) {\n            if (edge.to == nextNode) {\n                edge.weight = (edge.weight + scaleFactor) / 2; // Simple moving average\n                break;\n            }\n        }\n        for (Edge& edge : graph[nextNode]) {\n            if (edge.to == currentNode) {\n                edge.weight = (edge.weight + scaleFactor) / 2; // Simple moving average\n                break;\n            }\n        }\n        currentNode = nextNode;\n    }\n}\n\nint main() {\n    Graph graph = buildGraph();\n    int si, sj, ti, tj;\n    double prevResult = 0;\n\n    for (int k = 0; k < 1000; ++k) {\n        cin >> si >> sj >> ti >> tj;\n        int source = si * 30 + sj;\n        int target = ti * 30 + tj;\n\n        string path = dijkstra(graph, source, target);\n        cout << path << endl;\n        cout.flush();\n\n        double actualLength;\n        cin >> actualLength;\n        updateGraph(graph, path, actualLength);\n        prevResult = actualLength;\n    }\n\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct StringInfo {\n    string s;\n    int len;\n    bool used;\n};\n\nbool canPlaceString(vector<vector<char>>& matrix, const string& s, int i, int j, int dir) {\n    int N = matrix.size();\n    int len = s.length();\n\n    if (dir == 0) { // horizontal\n        for (int p = 0; p < len; ++p) {\n            int col = (j + p) % N;\n            if (matrix[i][col] != '.' && matrix[i][col] != s[p]) {\n                return false;\n            }\n        }\n    } else { // vertical\n        for (int p = 0; p < len; ++p) {\n            int row = (i + p) % N;\n            if (matrix[row][j] != '.' && matrix[row][j] != s[p]) {\n                return false;\n            }\n        }\n    }\n\n    return true;\n}\n\nvoid placeString(vector<vector<char>>& matrix, const string& s, int i, int j, int dir) {\n    int N = matrix.size();\n    int len = s.length();\n\n    if (dir == 0) { // horizontal\n        for (int p = 0; p < len; ++p) {\n            int col = (j + p) % N;\n            matrix[i][col] = s[p];\n        }\n    } else { // vertical\n        for (int p = 0; p < len; ++p) {\n            int row = (i + p) % N;\n            matrix[row][j] = s[p];\n        }\n    }\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<StringInfo> strings(M);\n\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i].s;\n        strings[i].len = strings[i].s.length();\n        strings[i].used = false;\n    }\n\n    // Sort the strings in descending order of their lengths\n    sort(strings.begin(), strings.end(), [](const StringInfo& a, const StringInfo& b) {\n        return a.len > b.len;\n    });\n\n    vector<vector<char>> matrix(N, vector<char>(N, '.'));\n\n    mt19937 mt(42);\n    uniform_int_distribution<int> dist(0, N - 1);\n\n    for (const auto& s : strings) {\n        if (s.used) continue;\n\n        bool placed = false;\n        for (int trial = 0; trial < 100; ++trial) {\n            int i = dist(mt), j = dist(mt);\n            int dir = dist(mt) % 2; // 0: horizontal, 1: vertical\n\n            if (canPlaceString(matrix, s.s, i, j, dir)) {\n                placeString(matrix, s.s, i, j, dir);\n                placed = true;\n                break;\n            }\n        }\n\n        if (placed) {\n            // Mark the string as used\n            for (auto& str : strings) {\n                if (str.s == s.s) {\n                    str.used = true;\n                    break;\n                }\n            }\n        }\n    }\n\n    // Print the resulting matrix\n    for (const auto& row : matrix) {\n        for (char c : row) {\n            cout << c;\n        }\n        cout << endl;\n    }\n\n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Pos {\n    int i, j;\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n\n    // Grid preprocessing\n    vector<Pos> roadSquares;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                roadSquares.push_back({i, j});\n            }\n        }\n    }\n\n    // Visibility graph construction\n    unordered_map<Pos, vector<Pos>> visibilityGraph;\n    for (const auto& pos : roadSquares) {\n        vector<Pos> visibleSquares;\n        // Compute visible squares from pos\n        for (const auto& otherPos : roadSquares) {\n            if (isVisible(pos, otherPos, grid)) {\n                visibleSquares.push_back(otherPos);\n            }\n        }\n        visibilityGraph[pos] = visibleSquares;\n    }\n\n    // Route construction\n    vector<Pos> route;\n    unordered_set<Pos> visited;\n    Pos currentPos = {si, sj};\n    route.push_back(currentPos);\n    visited.insert(currentPos);\n\n    while (visited.size() < roadSquares.size()) {\n        Pos nextPos = getNearestUnvisitedSquare(currentPos, visibilityGraph, visited);\n        if (nextPos.i == -1) {\n            // Backtrack\n            currentPos = route.back();\n            route.pop_back();\n        } else {\n            route.push_back(nextPos);\n            visited.insert(nextPos);\n            currentPos = nextPos;\n        }\n    }\n\n    // Route optimization (2-opt)\n    optimizeRoute(route, grid);\n\n    // Output\n    outputRoute(route);\n\n    return 0;\n}\n\n// Helper functions\nbool isVisible(const Pos& pos, const Pos& otherPos, const vector<string>& grid) {\n    // Check if otherPos is visible from pos\n    if (pos.i == otherPos.i) {\n        int minJ = min(pos.j, otherPos.j);\n        int maxJ = max(pos.j, otherPos.j);\n        for (int j = minJ; j <= maxJ; j++) {\n            if (grid[pos.i][j] == '#') {\n                return false;\n            }\n        }\n        return true;\n    } else if (pos.j == otherPos.j) {\n        int minI = min(pos.i, otherPos.i);\n        int maxI = max(pos.i, otherPos.i);\n        for (int i = minI; i <= maxI; i++) {\n            if (grid[i][pos.j] == '#') {\n                return false;\n            }\n        }\n        return true;\n    }\n    return false;\n}\n\nPos getNearestUnvisitedSquare(const Pos& pos, const unordered_map<Pos, vector<Pos>>& visibilityGraph, const unordered_set<Pos>& visited) {\n    // Find nearest unvisited square visible from pos\n    for (const auto& otherPos : visibilityGraph.at(pos)) {\n        if (visited.find(otherPos) == visited.end()) {\n            return otherPos;\n        }\n    }\n    return {-1, -1}; // Not found\n}\n\nvoid optimizeRoute(vector<Pos>& route, const vector<string>& grid) {\n    // 2-opt algorithm to optimize the route\n    int N = route.size();\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 1; i < N - 2; i++) {\n            for (int j = i + 1; j < N - 1; j++) {\n                int oldCost = getTravelTime(route[i - 1], route[i], grid) + getTravelTime(route[j], route[j + 1], grid);\n                int newCost = getTravelTime(route[i - 1], route[j], grid) + getTravelTime(route[i], route[j + 1], grid);\n                if (newCost < oldCost) {\n                    reverse(route.begin() + i, route.begin() + j + 1);\n                    improved = true;\n                }\n            }\n        }\n    }\n}\n\nint getTravelTime(const Pos& pos1, const Pos& pos2, const vector<string>& grid) {\n    // Compute travel time between pos1 and pos2\n    if (abs(pos1.i - pos2.i) + abs(pos1.j - pos2.j) != 1) {\n        return numeric_limits<int>::max(); // Invalid move\n    }\n    int cost = grid[pos2.i][pos2.j] - '0';\n    return cost;\n}\n\nvoid outputRoute(const vector<Pos>& route) {\n    // Output the route as a sequence of moves\n    for (int i = 0; i < route.size() - 1; i++) {\n        Pos pos1 = route[i];\n        Pos pos2 = route[i + 1];\n        if (pos1.i > pos2.i) {\n            cout << 'U';\n        } else if (pos1.i < pos2.i) {\n            cout << 'D';\n        } else if (pos1.j > pos2.j) {\n            cout << 'L';\n        } else if (pos1.j < pos2.j) {\n            cout << 'R';\n        }\n    }\n    cout << endl;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Task {\n    vector<int> d;\n    vector<int> dependencies;\n    int status; // -1: not started, 0: started, 1: completed\n};\n\nstruct TeamMember {\n    vector<int> s; // estimated skill levels\n    int task; // current task being worked on, -1 if available\n    int endDay; // day when the current task will be completed\n};\n\nint main() {\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<Task> tasks(N);\n    for (int i = 0; i < N; i++) {\n        tasks[i].d.resize(K);\n        for (int j = 0; j < K; j++) {\n            cin >> tasks[i].d[j];\n        }\n        tasks[i].status = -1;\n    }\n\n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        tasks[v - 1].dependencies.push_back(u - 1);\n    }\n\n    vector<TeamMember> teamMembers(M);\n    for (int i = 0; i < M; i++) {\n        teamMembers[i].s.resize(K, 0); // initialize estimated skill levels to 0\n        teamMembers[i].task = -1;\n        teamMembers[i].endDay = 0;\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n\n        // receive the list of team members who have completed their tasks\n        int n;\n        cin >> n;\n        if (n == -1) break;\n\n        vector<int> completedTeamMembers(n);\n        for (int i = 0; i < n; i++) {\n            cin >> completedTeamMembers[i];\n            completedTeamMembers[i]--;\n        }\n\n        // update task status and team member status\n        for (int teamMember : completedTeamMembers) {\n            if (teamMembers[teamMember].task != -1) {\n                tasks[teamMembers[teamMember].task].status = 1;\n                teamMembers[teamMember].task = -1;\n            }\n        }\n\n        // estimate skill levels of team members\n        for (int teamMember : completedTeamMembers) {\n            // TO DO: implement skill level estimation\n        }\n\n        // get available tasks\n        vector<int> availableTasks;\n        for (int i = 0; i < N; i++) {\n            if (tasks[i].status == -1) {\n                bool ok = true;\n                for (int dependency : tasks[i].dependencies) {\n                    if (tasks[dependency].status != 1) {\n                        ok = false;\n                        break;\n                    }\n                }\n                if (ok) availableTasks.push_back(i);\n            }\n        }\n\n        // assign tasks to available team members\n        vector<pair<int, int>> assignments;\n        for (int teamMember = 0; teamMember < M; teamMember++) {\n            if (teamMembers[teamMember].task == -1 && !availableTasks.empty()) {\n                // TO DO: implement task assignment heuristic\n                int task = availableTasks.back();\n                availableTasks.pop_back();\n                teamMembers[teamMember].task = task;\n                tasks[task].status = 0;\n                assignments.emplace_back(teamMember + 1, task + 1);\n            }\n        }\n\n        // output assignments\n        cout << assignments.size();\n        for (auto& assignment : assignments) {\n            cout << \" \" << assignment.first << \" \" << assignment.second;\n        }\n        cout << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Order {\n    int id;\n    int a, b, c, d;\n};\n\nint main() {\n    vector<Order> orders;\n    for (int i = 0; i < 1000; ++i) {\n        Order order;\n        order.id = i + 1;\n        cin >> order.a >> order.b >> order.c >> order.d;\n        orders.push_back(order);\n    }\n\n    // Improved initial solution using a greedy algorithm with a better heuristic\n    vector<Order> selectedOrders;\n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(orders.begin(), orders.end(), gen);\n    for (int i = 0; i < 50; ++i) {\n        selectedOrders.push_back(orders[i]);\n    }\n\n    // Simplified simulated annealing to improve the solution\n    auto startTime = chrono::high_resolution_clock::now();\n    int iteration = 0;\n    while (chrono::duration_cast<chrono::seconds>(chrono::high_resolution_clock::now() - startTime).count() < 1.9) {\n        iteration++;\n        int i = uniform_int_distribution<int>(0, selectedOrders.size() - 1)(gen);\n        int j = uniform_int_distribution<int>(0, orders.size() - 1)(gen);\n        if (find_if(selectedOrders.begin(), selectedOrders.end(), [&](const Order& order) { return order.id == orders[j].id; }) == selectedOrders.end()) {\n            // Replace the i-th order with the j-th order\n            selectedOrders[i] = orders[j];\n        }\n        if (iteration % 100 == 0) {\n            // Check time limit every 100 iterations\n            if (chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - startTime).count() > 1900) {\n                break;\n            }\n        }\n    }\n\n    // Construct the delivery route\n    vector<pair<int, int>> route;\n    route.push_back({400, 400});\n    for (const auto& order : selectedOrders) {\n        route.push_back({order.a, order.b});\n        route.push_back({order.c, order.d});\n    }\n    route.push_back({400, 400});\n\n    // Output the solution\n    cout << selectedOrders.size() << \" \";\n    for (const auto& order : selectedOrders) {\n        cout << order.id << \" \";\n    }\n    cout << endl;\n    cout << route.size() << \" \";\n    for (const auto& point : route) {\n        cout << point.first << \" \" << point.second << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <random>\n#include <cassert>\n\n// Union-Find data structure\nclass UnionFind {\npublic:\n    UnionFind(int n) : parent(n), rank(n, 0), size(n, 1) {\n        for (int i = 0; i < n; ++i) {\n            parent[i] = i;\n        }\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\n    void unite(int x, int y) {\n        int root_x = find(x);\n        int root_y = find(y);\n        if (root_x != root_y) {\n            if (rank[root_x] < rank[root_y]) {\n                parent[root_x] = root_y;\n                size[root_y] += size[root_x];\n            } else {\n                parent[root_y] = root_x;\n                size[root_x] += size[root_y];\n                if (rank[root_x] == rank[root_y]) {\n                    ++rank[root_x];\n                }\n            }\n        }\n    }\n\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n\n    int getSize(int x) {\n        return size[find(x)];\n    }\n\nprivate:\n    std::vector<int> parent;\n    std::vector<int> rank;\n    std::vector<int> size;\n};\n\nint main() {\n    const int N = 400;\n    const int M = 1995;\n\n    // Read vertex coordinates\n    std::vector<std::pair<int, int>> vertices(N);\n    for (auto& vertex : vertices) {\n        std::cin >> vertex.first >> vertex.second;\n    }\n\n    // Precompute Euclidean distances\n    std::vector<int> distances(M);\n    std::vector<std::pair<int, int>> edges(M);\n    for (int i = 0; i < M; ++i) {\n        std::cin >> edges[i].first >> edges[i].second;\n        int dx = vertices[edges[i].first].first - vertices[edges[i].second].first;\n        int dy = vertices[edges[i].first].second - vertices[edges[i].second].second;\n        distances[i] = std::round(std::sqrt(dx * dx + dy * dy));\n    }\n\n    // Initialize Union-Find data structure\n    UnionFind uf(N);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<double> dis(0.0, 1.0);\n\n    int count = 0;\n    for (int i = 0; i < M; ++i) {\n        int length;\n        std::cin >> length;\n\n        if (uf.same(edges[i].first, edges[i].second)) {\n            double prob = (length > 2 * distances[i]) ? 0.01 : (length > 1.5 * distances[i]) ? 0.1 : 0.2;\n            bool adopt = dis(gen) < prob;\n            std::cout << (adopt ? \"1\" : \"0\") << std::endl;\n            std::cout.flush();\n            if (adopt) {\n                uf.unite(edges[i].first, edges[i].second);\n                count++;\n            }\n        } else {\n            int size1 = uf.getSize(edges[i].first);\n            int size2 = uf.getSize(edges[i].second);\n            double prob = (length <= 1.2 * distances[i]) ? 1.0 : (size1 < N / 2 || size2 < N / 2) ? 0.9 : (length <= 1.5 * distances[i]) ? 0.8 : 0.5;\n            bool adopt = dis(gen) < prob;\n            std::cout << (adopt ? \"1\" : \"0\") << std::endl;\n            std::cout.flush();\n            if (adopt) {\n                uf.unite(edges[i].first, edges[i].second);\n                count++;\n            }\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 30;\nconst int DIR[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst char DIR_CHAR[4] = {'u', 'd', 'l', 'r'};\nconst char MOVE_CHAR[4] = {'U', 'D', 'L', 'R'};\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nint grid[N][N]; // 0: passable, 1: impassable\nvector<Pet> pets;\nvector<Human> humans;\n\nvoid bfs(int x, int y, vector<vector<bool>>& visited) {\n    queue<pair<int, int>> q;\n    q.emplace(x, y);\n    visited[x][y] = true;\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n        for (int i = 0; i < 4; ++i) {\n            int nx = x + DIR[i][0];\n            int ny = y + DIR[i][1];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0 && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n}\n\nchar getAction(int h) {\n    Human& human = humans[h];\n    int x = human.x;\n    int y = human.y;\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    bfs(x, y, visited);\n    int bestDir = -1;\n    int bestScore = -1;\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + DIR[i][0];\n        int ny = y + DIR[i][1];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0) {\n            // Check if making the square impassable is valid\n            bool valid = true;\n            for (int j = 0; j < 4; ++j) {\n                int nnx = nx + DIR[j][0];\n                int nny = ny + DIR[j][1];\n                if (nnx >= 0 && nnx < N && nny >= 0 && nny < N) {\n                    for (const Pet& pet : pets) {\n                        if (pet.x == nnx && pet.y == nny) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                }\n            }\n            if (!valid) continue;\n            // Simulate making the square impassable\n            grid[nx][ny] = 1;\n            vector<vector<bool>> newVisited(N, vector<bool>(N, false));\n            bfs(x, y, newVisited);\n            int newScore = 0;\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (newVisited[i][j]) ++newScore;\n                }\n            }\n            grid[nx][ny] = 0;\n            if (newScore > bestScore) {\n                bestScore = newScore;\n                bestDir = i;\n            }\n        }\n    }\n    if (bestDir != -1) {\n        return DIR_CHAR[bestDir];\n    } else {\n        // Try to move to an adjacent passable square\n        for (int i = 0; i < 4; ++i) {\n            int nx = x + DIR[i][0];\n            int ny = y + DIR[i][1];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0) {\n                return MOVE_CHAR[i];\n            }\n        }\n    }\n    return '.';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    cin >> N;\n    pets.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n        --pets[i].x;\n        --pets[i].y;\n    }\n    int M;\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].x >> humans[i].y;\n        --humans[i].x;\n        --humans[i].y;\n    }\n    for (int turn = 0; turn < 300; ++turn) {\n        string actions;\n        for (int h = 0; h < M; ++h) {\n            actions += getAction(h);\n        }\n        cout << actions << endl;\n        cout.flush();\n        // Read pet movements\n        for (int i = 0; i < N; ++i) {\n            string movement;\n            cin >> movement;\n            // Update pet positions\n            if (movement != \".\") {\n                for (char c : movement) {\n                    int dx = 0, dy = 0;\n                    if (c == 'U') dx = -1;\n                    if (c == 'D') dx = 1;\n                    if (c == 'L') dy = -1;\n                    if (c == 'R') dy = 1;\n                    pets[i].x += dx;\n                    pets[i].y += dy;\n                }\n            }\n        }\n        // Update human positions\n        for (int h = 0; h < M; ++h) {\n            char action = actions[h];\n            if (action == 'U') --humans[h].x;\n            if (action == 'D') ++humans[h].x;\n            if (action == 'L') --humans[h].y;\n            if (action == 'R') ++humans[h].y;\n        }\n    }\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    int sx, sy, tx, ty;\n    double p;\n    cin >> sx >> sy >> tx >> ty >> p;\n\n    vector<string> h(20), v(20);\n    for (int i = 0; i < 20; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < 19; ++i) {\n        cin >> v[i];\n    }\n\n    // BFS to find a initial path\n    queue<Pos> q;\n    vector<vector<bool>> visited(20, vector<bool>(20, false));\n    q.push({sx, sy});\n    visited[sx][sy] = true;\n    vector<vector<Pos>> parent(20, vector<Pos>(20, {-1, -1}));\n    while (!q.empty()) {\n        Pos curr = q.front(); q.pop();\n        if (curr.x == tx && curr.y == ty) break;\n        // Explore neighbors\n        for (auto dir : {make_pair(0, 1), make_pair(0, -1), make_pair(1, 0), make_pair(-1, 0)}) {\n            int nx = curr.x + dir.first, ny = curr.y + dir.second;\n            if (nx >= 0 && nx < 20 && ny >= 0 && ny < 20 && !visited[nx][ny]) {\n                if (dir.first == 0 && dir.second == 1 && ny < 20 && h[curr.x][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == 0 && dir.second == -1 && ny >= 0 && h[curr.x][ny] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == 1 && dir.second == 0 && nx < 20 && v[curr.x][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == -1 && dir.second == 0 && nx >= 0 && v[nx][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                }\n            }\n        }\n    }\n\n    // Reconstruct path\n    string path;\n    Pos curr = {tx, ty};\n    while (curr.x != sx || curr.y != sy) {\n        Pos prev = parent[curr.x][curr.y];\n        if (prev.x == curr.x - 1) path += 'D';\n        else if (prev.x == curr.x + 1) path += 'U';\n        else if (prev.y == curr.y - 1) path += 'R';\n        else if (prev.y == curr.y + 1) path += 'L';\n        curr = prev;\n    }\n    reverse(path.begin(), path.end());\n\n    // Ensure path only contains valid characters and is within length limits\n    string robustPath = path;\n    while (robustPath.size() <= 200) {\n        robustPath += path;\n    }\n    robustPath.resize(200);\n\n    // Validate and output\n    for (char c : robustPath) {\n        if (c != 'U' && c != 'D' && c != 'L' && c != 'R') {\n            cerr << \"Invalid character in path: \" << c << endl;\n            return 1; // Exit with error if invalid character found\n        }\n    }\n\n    cout << robustPath << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <random>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 30;\nconst int T = 100000;\n\nint tiles[N][N];\nint rotations[N][N];\nint 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};\nint di[4] = {0, -1, 0, 1};\nint dj[4] = {-1, 0, 1, 0};\n\nint traverse_loop(int i, int j, int d) {\n    int length = 0;\n    int si = i, sj = j, sd = d;\n    while (true) {\n        int t = tiles[i][j];\n        for (int k = 0; k < rotations[i][j]; k++) {\n            if (t >= 0 && t <= 3) t = (t + 1) % 4;\n            else if (t == 4 || t == 5) t = 4 + (t - 4 + 1) % 2;\n            else if (t == 6 || t == 7) t = 6 + (t - 6 + 1) % 2;\n        }\n        int d2 = to[t][d];\n        if (d2 == -1) return 0;\n        i += di[d2];\n        j += dj[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (i == si && j == sj && d == sd) return length;\n    }\n}\n\nint calculate_score() {\n    vector<int> loop_lengths;\n    bool visited[N][N] = {};\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (!visited[i][j]) {\n                for (int d = 0; d < 4; d++) {\n                    int length = traverse_loop(i, j, d);\n                    if (length > 0) {\n                        loop_lengths.push_back(length);\n                        // Mark the loop as visited\n                        int ti = i, tj = j, td = d;\n                        while (true) {\n                            visited[ti][tj] = true;\n                            int t = tiles[ti][tj];\n                            for (int k = 0; k < rotations[ti][tj]; k++) {\n                                if (t >= 0 && t <= 3) t = (t + 1) % 4;\n                                else if (t == 4 || t == 5) t = 4 + (t - 4 + 1) % 2;\n                                else if (t == 6 || t == 7) t = 6 + (t - 6 + 1) % 2;\n                            }\n                            int td2 = to[t][td];\n                            ti += di[td2];\n                            tj += dj[td2];\n                            td = (td2 + 2) % 4;\n                            if (ti == i && tj == j && td == d) break;\n                        }\n                        break;\n                    }\n                }\n            }\n        }\n    }\n    sort(loop_lengths.rbegin(), loop_lengths.rend());\n    if (loop_lengths.size() <= 1) return 0;\n    return loop_lengths[0] * loop_lengths[1];\n}\n\nvoid simulated_annealing() {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n    uniform_int_distribution<> rot_dis(0, 3);\n\n    double temperature = 1000;\n    int current_score = calculate_score();\n    while (temperature > 1) {\n        int i = dis(gen);\n        int j = dis(gen);\n        int original_rotation = rotations[i][j];\n        int new_rotation = (original_rotation + 1) % 4;\n        rotations[i][j] = new_rotation;\n        int new_score = calculate_score();\n        if (new_score > current_score) {\n            current_score = new_score;\n        } else {\n            if (exp((double)(new_score - current_score) / temperature) > (double)rand() / RAND_MAX) {\n                current_score = new_score;\n            } else {\n                rotations[i][j] = original_rotation;\n            }\n        }\n        temperature *= 0.99;\n    }\n}\n\nint main() {\n    for (int i = 0; i < N; i++) {\n        string line;\n        cin >> line;\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = line[j] - '0';\n        }\n    }\n\n    simulated_annealing();\n\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cout << rotations[i][j];\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Puzzle {\n    int N;\n    vector<vector<int>> tiles;\n    pair<int, int> empty;\n\n    Puzzle(int N) : N(N), tiles(N, vector<int>(N)) {}\n\n    bool isValidMove(char dir) {\n        int dx = 0, dy = 0;\n        if (dir == 'U') dx = -1;\n        if (dir == 'D') dx = 1;\n        if (dir == 'L') dy = -1;\n        if (dir == 'R') dy = 1;\n\n        int x = empty.first, y = empty.second;\n        int nx = x + dx, ny = y + dy;\n\n        return nx >= 0 && nx < N && ny >= 0 && ny < N;\n    }\n\n    void move(char dir) {\n        int dx = 0, dy = 0;\n        if (dir == 'U') dx = -1;\n        if (dir == 'D') dx = 1;\n        if (dir == 'L') dy = -1;\n        if (dir == 'R') dy = 1;\n\n        int x = empty.first, y = empty.second;\n        int nx = x + dx, ny = y + dy;\n\n        swap(tiles[x][y], tiles[nx][ny]);\n        empty = {nx, ny};\n    }\n\n    int evaluate() {\n        // Implement graph construction and largest tree size calculation here\n        // This is a simplified version\n        int score = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (tiles[i][j] != 0) {\n                    score += 1;\n                }\n            }\n        }\n        return score;\n    }\n};\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n\n    Puzzle puzzle(N);\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            int val = stoi(row.substr(j, 1), 0, 16);\n            puzzle.tiles[i][j] = val;\n            if (val == 0) {\n                puzzle.empty = {i, j};\n            }\n        }\n    }\n\n    string operations;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n    for (int i = 0; i < T; ++i) {\n        char dirs[] = {'U', 'D', 'L', 'R'};\n        char dir;\n        int attempts = 0;\n        do {\n            dir = dirs[dis(gen) % 4];\n            attempts++;\n            if (attempts > 100) break; // Prevent infinite loop\n        } while (!puzzle.isValidMove(dir));\n\n        if (puzzle.isValidMove(dir)) {\n            puzzle.move(dir);\n            operations += dir;\n        } else {\n            break;\n        }\n    }\n\n    cout << operations << endl;\n\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    long long x, y;\n};\n\nlong long cross(const Point& p1, const Point& p2) {\n    return p1.x * p2.y - p1.y * p2.x;\n}\n\nint main() {\n    int N, K;\n    cin >> N >> K;\n    vector<int> a(10);\n    for (int i = 0; i < 10; ++i) {\n        cin >> a[i];\n    }\n    vector<Point> strawberries(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> strawberries[i].x >> strawberries[i].y;\n    }\n\n    vector<pair<Point, Point>> cuts;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int i = 0; i < K; ++i) {\n        int best_idx1 = -1, best_idx2 = -1;\n        double best_score = -1.0;\n\n        for (int j = 0; j < 100; ++j) {\n            int idx1 = dis(gen);\n            int idx2 = dis(gen);\n            while (idx2 == idx1) {\n                idx2 = dis(gen);\n            }\n\n            // Calculate the score for the current cut\n            double score = 0.0;\n            // TO DO: implement the score calculation\n\n            if (score > best_score) {\n                best_score = score;\n                best_idx1 = idx1;\n                best_idx2 = idx2;\n            }\n        }\n\n        if (best_idx1 != -1 && best_idx2 != -1) {\n            Point p1 = strawberries[best_idx1];\n            Point p2 = strawberries[best_idx2];\n            cuts.emplace_back(p1, p2);\n        }\n    }\n\n    cout << cuts.size() << endl;\n    for (const auto& cut : cuts) {\n        cout << cut.first.x << \" \" << cut.first.y << \" \" << cut.second.x << \" \" << cut.second.y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <random>\n#include <tuple>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nint N, M;\nvector<Point> dots;\nset<pair<int, int>> dot_set;\nvector<tuple<int, int, int, int, int, int, int, int>> operations;\n\nbool is_valid_rectangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (x1 == x2 || x1 == x3 || x1 == x4 || y1 == y2 || y1 == y3 || y1 == y4) {\n        return false;\n    }\n    if ((x1 == x3 && y1 == y4 && x2 == x4 && y2 == y3) && (abs(x1 - x2) == abs(y1 - y2))) {\n        if (dot_set.find({x1, y2}) != dot_set.end() && dot_set.find({x2, y1}) != dot_set.end() && dot_set.find({x3, y4}) != dot_set.end() && dot_set.find({x4, y3}) != dot_set.end()) {\n            // Check if there are no dots other than the four points on the perimeter\n            int min_x = min(x1, min(x2, min(x3, x4)));\n            int max_x = max(x1, max(x2, max(x3, x4)));\n            int min_y = min(y1, min(y2, min(y3, y4)));\n            int max_y = max(y1, max(y2, max(y3, y4)));\n            for (int i = min_x; i <= max_x; i++) {\n                for (int j = min_y; j <= max_y; j++) {\n                    if (dot_set.find({i, j}) != dot_set.end() && make_pair(i, j) != make_pair(x1, y1) && make_pair(i, j) != make_pair(x2, y2) && make_pair(i, j) != make_pair(x3, y3) && make_pair(i, j) != make_pair(x4, y4)) {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    cin >> N >> M;\n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        dots.push_back({x, y});\n        dot_set.insert({x, y});\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    int iter_count = 0;\n    while (iter_count < 100000 && (double)clock() / CLOCKS_PER_SEC < 4.5) {\n        int x1 = dis(gen);\n        int y1 = dis(gen);\n        if (dot_set.find({x1, y1}) != dot_set.end()) {\n            iter_count++;\n            continue;\n        }\n        for (int i = 0; i < dots.size(); i++) {\n            for (int j = i + 1; j < dots.size(); j++) {\n                int x2 = dots[i].x;\n                int y2 = dots[i].y;\n                int x3 = dots[j].x;\n                int y3 = dots[j].y;\n                int x4 = x1 + x3 - x2;\n                int y4 = y1 + y3 - y2;\n                if (x4 >= 0 && x4 < N && y4 >= 0 && y4 < N && dot_set.find({x4, y4}) != dot_set.end() && dot_set.find({x2, y3}) == dot_set.end() && dot_set.find({x3, y2}) == dot_set.end()) {\n                    if (is_valid_rectangle(x1, y1, x2, y2, x3, y3, x4, y4)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.emplace_back(x1, y1, x2, y2, x3, y3, x4, y4);\n                        iter_count = 0;\n                        break;\n                    }\n                }\n                x4 = x1 + x2 - x3;\n                y4 = y1 + y2 - y3;\n                if (x4 >= 0 && x4 < N && y4 >= 0 && y4 < N && dot_set.find({x4, y4}) != dot_set.end() && dot_set.find({x2, y3}) == dot_set.end() && dot_set.find({x3, y2}) == dot_set.end()) {\n                    if (is_valid_rectangle(x1, y1, x2, y2, x4, y4, x3, y3)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.emplace_back(x1, y1, x2, y2, x4, y4, x3, y3);\n                        iter_count = 0;\n                        break;\n                    }\n                }\n            }\n            if (iter_count == 0) {\n                break;\n            }\n        }\n        iter_count++;\n    }\n\n    cout << operations.size() << endl;\n    for (auto& op : operations) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << \" \" << get<4>(op) << \" \" << get<5>(op) << \" \" << get<6>(op) << \" \" << get<7>(op) << endl;\n    }\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nconst int N = 10;\nconst int flavors = 3;\n\nstruct CandyBox {\n    int grid[N][N];\n    int count[flavors + 1];\n\n    CandyBox() {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                grid[i][j] = 0;\n            }\n        }\n        for (int i = 1; i <= flavors; i++) {\n            count[i] = 0;\n        }\n    }\n\n    void placeCandy(int flavor, int pos) {\n        int emptyCount = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (grid[i][j] == 0) {\n                    emptyCount++;\n                    if (emptyCount == pos) {\n                        grid[i][j] = flavor;\n                        count[flavor]++;\n                        return;\n                    }\n                }\n            }\n        }\n    }\n\n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; j++) {\n                int writePos = 0;\n                for (int i = 0; i < N; i++) {\n                    if (grid[i][j] != 0) {\n                        grid[writePos++][j] = grid[i][j];\n                    }\n                }\n                for (int i = writePos; i < N; i++) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; j++) {\n                int writePos = N - 1;\n                for (int i = N - 1; i >= 0; i--) {\n                    if (grid[i][j] != 0) {\n                        grid[writePos--][j] = grid[i][j];\n                    }\n                }\n                for (int i = writePos; i >= 0; i--) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; i++) {\n                int writePos = 0;\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] != 0) {\n                        grid[i][writePos++] = grid[i][j];\n                    }\n                }\n                for (int j = writePos; j < N; j++) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'R') {\n            for (int i = 0; i < N; i++) {\n                int writePos = N - 1;\n                for (int j = N - 1; j >= 0; j--) {\n                    if (grid[i][j] != 0) {\n                        grid[i][writePos--] = grid[i][j];\n                    }\n                }\n                for (int j = writePos; j >= 0; j--) {\n                    grid[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    int evaluateScore() {\n        int score = 0;\n        for (int flavor = 1; flavor <= flavors; flavor++) {\n            vector<vector<bool>> visited(N, vector<bool>(N, false));\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] == flavor && !visited[i][j]) {\n                        int componentSize = 0;\n                        vector<pair<int, int>> stack = {{i, j}};\n                        visited[i][j] = true;\n                        while (!stack.empty()) {\n                            auto [x, y] = stack.back();\n                            stack.pop_back();\n                            componentSize++;\n                            for (auto [dx, dy] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                                int nx = x + dx;\n                                int ny = y + dy;\n                                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == flavor && !visited[nx][ny]) {\n                                    stack.emplace_back(nx, ny);\n                                    visited[nx][ny] = true;\n                                }\n                            }\n                        }\n                        score += componentSize * componentSize;\n                    }\n                }\n            }\n        }\n        int denominator = 0;\n        for (int i = 1; i <= flavors; i++) {\n            denominator += count[i] * count[i];\n        }\n        return denominator == 0 ? 0 : score / denominator;\n    }\n\n    int evaluateScoreWithClustering() {\n        int score = 0;\n        for (int flavor = 1; flavor <= flavors; flavor++) {\n            vector<vector<bool>> visited(N, vector<bool>(N, false));\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] == flavor && !visited[i][j]) {\n                        int componentSize = 0;\n                        vector<pair<int, int>> stack = {{i, j}};\n                        visited[i][j] = true;\n                        while (!stack.empty()) {\n                            auto [x, y] = stack.back();\n                            stack.pop_back();\n                            componentSize++;\n                            for (auto [dx, dy] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                                int nx = x + dx;\n                                int ny = y + dy;\n                                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == flavor && !visited[nx][ny]) {\n                                    stack.emplace_back(nx, ny);\n                                    visited[nx][ny] = true;\n                                }\n                            }\n                        }\n                        score += componentSize * componentSize;\n                        // clustering bonus\n                        if (componentSize > 1) {\n                            score += componentSize;\n                        }\n                    }\n                }\n            }\n        }\n        int denominator = 0;\n        for (int i = 1; i <= flavors; i++) {\n            denominator += count[i] * count[i];\n        }\n        return denominator == 0 ? 0 : score / denominator;\n    }\n};\n\nint main() {\n    vector<int> flavors(100);\n    for (int i = 0; i < 100; i++) {\n        cin >> flavors[i];\n    }\n\n    CandyBox box;\n    for (int t = 0; t < 100; t++) {\n        int pos;\n        cin >> pos;\n        box.placeCandy(flavors[t], pos);\n\n        if (t == 99) break; // no need to output for the last tilt\n\n        char bestDir = 'F';\n        int bestScore = -1;\n        for (char dir : {'F', 'B', 'L', 'R'}) {\n            CandyBox simBox = box;\n            simBox.tilt(dir);\n            int score = simBox.evaluateScoreWithClustering();\n            if (score > bestScore) {\n                bestScore = score;\n                bestDir = dir;\n            }\n        }\n        cout << bestDir << endl;\n        box.tilt(bestDir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nint M;\ndouble eps;\nint N = 20;\n\nstring generateGk(int k) {\n    string gk(N * (N - 1) / 2, '0');\n    int count = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            int index = i * (N - 1) - i * (i + 1) / 2 + j - i - 1;\n            if (count < k) {\n                gk[index] = '1';\n                count++;\n            }\n        }\n    }\n    return gk;\n}\n\nint predictSk(const string& Hk, const vector<string>& G) {\n    int bestMatch = 0;\n    int minDistance = numeric_limits<int>::max();\n    for (int i = 0; i < M; ++i) {\n        int distance = 0;\n        for (int j = 0; j < N * (N - 1) / 2; ++j) {\n            distance += (Hk[j] != G[i][j]);\n        }\n        if (distance < minDistance) {\n            minDistance = distance;\n            bestMatch = i;\n        }\n    }\n    return bestMatch;\n}\n\nint main() {\n    cin >> M >> eps;\n    cout << N << endl;\n    vector<string> G(M);\n    for (int k = 0; k < M; ++k) {\n        G[k] = generateGk(k);\n        cout << G[k] << endl;\n    }\n    cout.flush();\n\n    for (int query = 0; query < 100; ++query) {\n        string Hk;\n        cin >> Hk;\n        int tk = predictSk(Hk, G);\n        cout << tk << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n#include <limits>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v, w, id;\n};\n\nint main() {\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    vector<Edge> edges(M);\n    vector<vector<pair<int, int>>> graph(N);\n\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[i] = {u, v, w, i};\n        graph[u].emplace_back(v, w);\n        graph[v].emplace_back(u, w);\n    }\n\n    // Read and ignore vertex coordinates\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // Initialize repair schedule randomly\n    vector<int> repairDay(M);\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(1, D);\n    for (auto& day : repairDay) {\n        day = dis(gen);\n    }\n\n    // Function to calculate frustration level for a given day\n    auto calculateFrustration = [&](const vector<int>& edgesForDay) {\n        // Create a temporary graph with edges for the day removed\n        vector<vector<pair<int, int>>> tempGraph = graph;\n        for (int edgeId : edgesForDay) {\n            Edge e = edges[edgeId];\n            // Remove edge e from tempGraph\n            tempGraph[e.u].erase(remove_if(tempGraph[e.u].begin(), tempGraph[e.u].end(), [&](const pair<int, int>& p){ return p.first == e.v; }), tempGraph[e.u].end());\n            tempGraph[e.v].erase(remove_if(tempGraph[e.v].begin(), tempGraph[e.v].end(), [&](const pair<int, int>& p){ return p.first == e.u; }), tempGraph[e.v].end());\n        }\n\n        // Calculate shortest paths using Dijkstra's algorithm\n        vector<vector<int>> dist(N, vector<int>(N, numeric_limits<int>::max()));\n        for (int i = 0; i < N; ++i) {\n            dist[i][i] = 0;\n            priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;\n            pq.emplace(0, i);\n            while (!pq.empty()) {\n                int d = pq.top().first, u = pq.top().second;\n                pq.pop();\n                if (d > dist[i][u]) continue;\n                for (const auto& e : tempGraph[u]) {\n                    if (dist[i][e.first] > d + e.second) {\n                        dist[i][e.first] = d + e.second;\n                        pq.emplace(dist[i][e.first], e.first);\n                    }\n                }\n            }\n        }\n\n        // Calculate frustration level\n        int frustration = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (dist[i][j] == numeric_limits<int>::max()) dist[i][j] = 1e9;\n                frustration += dist[i][j] - /* original shortest distance */;\n            }\n        }\n        return frustration;\n    };\n\n    // Main loop to improve the schedule\n    for (int iter = 0; iter < 10000; ++iter) {\n        // Select an edge and a new day for it\n        int edgeId = rand() % M;\n        int newDay = rand() % D + 1;\n        int oldDay = repairDay[edgeId];\n\n        // Check if moving the edge to the new day is valid and improves the schedule\n        vector<int>& oldDayEdges = /* get edges for oldDay */;\n        vector<int>& newDayEdges = /* get edges for newDay */;\n        if (newDayEdges.size() < K) {\n            // Temporarily move the edge\n            oldDayEdges.erase(remove(oldDayEdges.begin(), oldDayEdges.end(), edgeId), oldDayEdges.end());\n            newDayEdges.push_back(edgeId);\n\n            // Calculate new frustration levels\n            int oldFrustration = calculateFrustration(oldDayEdges) + calculateFrustration(newDayEdges);\n            int newFrustration = /* calculate frustration for oldDay without edgeId */ + /* calculate frustration for newDay with edgeId */;\n\n            if (newFrustration < oldFrustration) {\n                // Accept the move\n                repairDay[edgeId] = newDay;\n            } else {\n                // Revert the move\n                newDayEdges.pop_back();\n                oldDayEdges.push_back(edgeId);\n            }\n        }\n    }\n\n    // Output the final repair schedule\n    for (int i = 0; i < M; ++i) {\n        cout << repairDay[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <bitset>\n\nconst int MAX_D = 14;\nint D;\nstd::bitset<MAX_D> f[2][MAX_D][MAX_D];\nstd::bitset<MAX_D> r[2][MAX_D][MAX_D];\nint b[2][MAX_D * MAX_D * MAX_D];\n\nvoid input() {\n    std::cin >> D;\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            std::string s;\n            std::cin >> s;\n            for (int x = 0; x < D; ++x) {\n                f[i][z][x][x] = (s[x] == '1');\n            }\n        }\n        for (int z = 0; z < D; ++z) {\n            std::string s;\n            std::cin >> s;\n            for (int y = 0; y < D; ++y) {\n                r[i][z][y][y] = (s[y] == '1');\n            }\n        }\n    }\n}\n\nvoid solve() {\n    int n = 0;\n    for (int i = 0; i < 2; ++i) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[i][z][x][y] && r[i][z][y][x]) {\n                        b[i][x * D * D + y * D + z] = ++n;\n                    }\n                }\n            }\n        }\n    }\n\n    std::cout << n << std::endl;\n    for (int i = 0; i < D * D * D; ++i) {\n        std::cout << b[0][i] << \" \";\n    }\n    std::cout << std::endl;\n    for (int i = 0; i < D * D * D; ++i) {\n        std::cout << b[1][i] << \" \";\n    }\n    std::cout << std::endl;\n}\n\nint main() {\n    input();\n    solve();\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n    long long w;\n};\n\nstruct UnionFind {\n    vector<int> parent, rank;\n    UnionFind(int n) : parent(n, -1), rank(n, 0) {}\n    int find(int x) {\n        if (parent[x] == -1) return x;\n        return parent[x] = find(parent[x]);\n    }\n    void unionSet(int x, int y) {\n        int rootX = find(x), rootY = find(y);\n        if (rootX != rootY) {\n            if (rank[rootX] > rank[rootY]) {\n                parent[rootY] = rootX;\n            } else {\n                parent[rootX] = rootY;\n                if (rank[rootX] == rank[rootY]) rank[rootY]++;\n            }\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<pair<int, int>> vertices(N);\n    for (auto& [x, y] : vertices) {\n        cin >> x >> y;\n    }\n\n    vector<Edge> edges(M);\n    for (auto& [u, v, w] : edges) {\n        cin >> u >> v >> w;\n        u--; v--;\n    }\n\n    vector<pair<int, int>> residents(K);\n    for (auto& [a, b] : residents) {\n        cin >> a >> b;\n    }\n\n    // Minimum Spanning Tree\n    vector<bool> in_mst(M, false);\n    UnionFind uf(N);\n    {\n        sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        for (auto& e : edges) {\n            if (uf.find(e.u) != uf.find(e.v)) {\n                uf.unionSet(e.u, e.v);\n                in_mst[&e - &edges[0]] = true;\n            }\n        }\n    }\n\n    // Resident Coverage\n    vector<int> output_strength(N, 0);\n    for (auto [a, b] : residents) {\n        int nearest_vertex = 0;\n        long long min_distance = (long long)1e18;\n        for (int i = 0; i < N; i++) {\n            auto [x, y] = vertices[i];\n            long long distance = (long long)(x - a) * (x - a) + (long long)(y - b) * (y - b);\n            if (distance < min_distance) {\n                min_distance = distance;\n                nearest_vertex = i;\n            }\n        }\n        output_strength[nearest_vertex] = max(output_strength[nearest_vertex], (int)ceil(sqrt(min_distance)) + 1);\n    }\n\n    // Graph Traversal\n    vector<bool> visited(N, false);\n    {\n        queue<int> q;\n        q.push(0);\n        visited[0] = true;\n        while (!q.empty()) {\n            int u = q.front(); q.pop();\n            for (int i = 0; i < M; i++) {\n                if (in_mst[i]) {\n                    auto& e = edges[i];\n                    if (e.u == u && !visited[e.v]) {\n                        visited[e.v] = true;\n                        output_strength[e.v] = max(output_strength[e.v], output_strength[u]);\n                        q.push(e.v);\n                    }\n                    if (e.v == u && !visited[e.u]) {\n                        visited[e.u] = true;\n                        output_strength[e.u] = max(output_strength[e.u], output_strength[u]);\n                        q.push(e.u);\n                    }\n                }\n            }\n        }\n    }\n\n    // Output\n    for (int p : output_strength) {\n        cout << p << \" \";\n    }\n    cout << \"\\n\";\n    for (auto& e : edges) {\n        cout << (in_mst[&e - &edges[0]] ? \"1\" : \"0\") << \" \";\n    }\n    cout << \"\\n\";\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n#include <tuple> // Include the necessary header for std::tuple\n\nusing namespace std;\n\nconst int N = 30;\nconst int dx[] = {-1, -1, 0, 0, 1, 1};\nconst int dy[] = {-1, 0, -1, 1, 0, 1};\n\nint main() {\n    vector<vector<int>> pyramid(N);\n    for (int i = 0; i < N; ++i) {\n        pyramid[i].resize(i + 1);\n        for (int j = 0; j <= i; ++j) {\n            cin >> pyramid[i][j];\n        }\n    }\n\n    vector<tuple<int, int, int, int>> operations;\n    for (int i = N - 1; i > 0; --i) {\n        for (int j = 0; j <= i; ++j) {\n            int x = i, y = j;\n            while (x > 0) {\n                int parent_x = x - 1;\n                int parent_y = y;\n                if (y > parent_x) {\n                    parent_y = y - 1;\n                }\n                if (pyramid[x][y] < pyramid[parent_x][parent_y]) {\n                    swap(pyramid[x][y], pyramid[parent_x][parent_y]);\n                    operations.emplace_back(x, y, parent_x, parent_y);\n                }\n                x = parent_x;\n                y = parent_y;\n            }\n        }\n    }\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << endl;\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n\nusing namespace std;\n\nconst int D = 9;\nconst int directions[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nstruct Position {\n    int x, y;\n};\n\nint main() {\n    int N;\n    cin >> D >> N;\n\n    vector<vector<int>> grid(D, vector<int>(D, 0));\n    grid[0][(D - 1) / 2] = -1; // Entrance\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        grid[x][y] = -2; // Obstacle\n    }\n\n    vector<Position> containers;\n    unordered_set<int> containerSet;\n\n    for (int d = 0; d < D * D - 1 - N; ++d) {\n        int t;\n        cin >> t;\n\n        // Find a suitable position for the container using BFS\n        queue<Position> q;\n        vector<vector<bool>> visited(D, vector<bool>(D, false));\n        q.push({0, (D - 1) / 2});\n        visited[0][(D - 1) / 2] = true;\n\n        Position target;\n        bool found = false;\n\n        while (!q.empty()) {\n            Position p = q.front();\n            q.pop();\n\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + directions[i][0];\n                int ny = p.y + directions[i][1];\n\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !visited[nx][ny] && grid[nx][ny] == 0) {\n                    visited[nx][ny] = true;\n                    q.push({nx, ny});\n\n                    // Choose the last visited node as the target position\n                    target = {nx, ny};\n                    found = true;\n                }\n            }\n        }\n\n        if (found) {\n            grid[target.x][target.y] = t;\n            containers.push_back(target);\n            containerSet.insert(target.x * D + target.y);\n            cout << target.x << \" \" << target.y << endl;\n            cout.flush();\n        }\n    }\n\n    // Transport containers out\n    for (int i = 0; i < D * D - 1 - N; ++i) {\n        queue<Position> q;\n        vector<vector<bool>> visited(D, vector<bool>(D, false));\n        q.push({0, (D - 1) / 2});\n        visited[0][(D - 1) / 2] = true;\n\n        Position target;\n        int minNum = D * D;\n\n        while (!q.empty()) {\n            Position p = q.front();\n            q.pop();\n\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + directions[i][0];\n                int ny = p.y + directions[i][1];\n\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !visited[nx][ny]) {\n                    if (grid[nx][ny] >= 0 && grid[nx][ny] < minNum) {\n                        minNum = grid[nx][ny];\n                        target = {nx, ny};\n                    }\n\n                    visited[nx][ny] = true;\n                    q.push({nx, ny});\n                }\n            }\n        }\n\n        if (minNum != D * D) {\n            cout << target.x << \" \" << target.y << endl;\n            grid[target.x][target.y] = 0;\n        }\n    }\n\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm> // Include the algorithm header\n\nusing namespace std;\n\nconst int N = 50;\nconst int M = 100;\n\nint grid[N][N];\nint output[N][N];\nunordered_map<int, pair<int, int>> seeds;\nunordered_set<int> adjacentColors[M + 1];\n\nvoid readInput() {\n    int n, m;\n    cin >> n >> m;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> grid[i][j];\n            if (seeds.find(grid[i][j]) == seeds.end()) {\n                seeds[grid[i][j]] = {i, j};\n            }\n            output[i][j] = 0; // Initialize output grid\n        }\n    }\n}\n\nvoid buildAdjacencyGraph() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int color = grid[i][j];\n            if (i > 0 && grid[i - 1][j] != color) {\n                adjacentColors[color].insert(grid[i - 1][j]);\n            }\n            if (j > 0 && grid[i][j - 1] != color) {\n                adjacentColors[color].insert(grid[i][j - 1]);\n            }\n            if (i < N - 1 && grid[i + 1][j] != color) {\n                adjacentColors[color].insert(grid[i + 1][j]);\n            }\n            if (j < N - 1 && grid[i][j + 1] != color) {\n                adjacentColors[color].insert(grid[i][j + 1]);\n            }\n        }\n    }\n}\n\nvoid processColors() {\n    vector<int> colors;\n    for (int i = 1; i <= M; i++) {\n        colors.push_back(i);\n    }\n    sort(colors.begin(), colors.end(), [&adjColors = adjacentColors](int a, int b) {\n        return adjColors[a].size() > adjColors[b].size();\n    });\n\n    for (int color : colors) {\n        int x = seeds[color].first;\n        int y = seeds[color].second;\n        output[x][y] = color;\n        queue<pair<int, int>> q;\n        q.push({x, y});\n        while (!q.empty()) {\n            x = q.front().first;\n            y = q.front().second;\n            q.pop();\n            if (x > 0 && grid[x - 1][y] == color && output[x - 1][y] == 0) {\n                output[x - 1][y] = color;\n                q.push({x - 1, y});\n            }\n            if (y > 0 && grid[x][y - 1] == color && output[x][y - 1] == 0) {\n                output[x][y - 1] = color;\n                q.push({x, y - 1});\n            }\n            if (x < N - 1 && grid[x + 1][y] == color && output[x + 1][y] == 0) {\n                output[x + 1][y] = color;\n                q.push({x + 1, y});\n            }\n            if (y < N - 1 && grid[x][y + 1] == color && output[x][y + 1] == 0) {\n                output[x][y + 1] = color;\n                q.push({x, y + 1});\n            }\n        }\n    }\n}\n\nvoid outputResult() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cout << output[i][j] << \" \";\n        }\n        cout << endl;\n    }\n}\n\nint main() {\n    readInput();\n    buildAdjacencyGraph();\n    processColors();\n    outputResult();\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n\nint main() {\n    int N, D, Q;\n    std::cin >> N >> D >> Q;\n\n    // Initialize random number generator\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> dis(0, N - 1);\n\n    // Estimate weights using a more sophisticated comparison strategy\n    std::vector<double> weights(N, 0.0);\n    for (int q = 0; q < Q; ++q) {\n        // Generate comparison subsets using a binary search-like approach\n        int i = dis(gen) % N;\n        int j = dis(gen) % N;\n        while (j == i) {\n            j = dis(gen) % N;\n        }\n\n        std::cout << \"1 1 \" << i << \" \" << j << std::endl;\n        char result;\n        std::cin >> result;\n\n        if (result == '<') {\n            weights[i] -= 1.0;\n            weights[j] += 1.0;\n        } else if (result == '>') {\n            weights[i] += 1.0;\n            weights[j] -= 1.0;\n        }\n    }\n\n    // Cluster or partition items into D subsets using a more advanced algorithm\n    std::vector<int> division(N);\n    std::vector<std::pair<double, int>> sorted_weights(N);\n    for (int i = 0; i < N; ++i) {\n        sorted_weights[i] = std::make_pair(weights[i], i);\n    }\n    std::sort(sorted_weights.begin(), sorted_weights.end());\n\n    int subset = 0;\n    for (int i = 0; i < N; ++i) {\n        division[sorted_weights[i].second] = subset;\n        subset = (subset + 1) % D;\n    }\n\n    // Output division\n    for (int i = 0; i < N; ++i) {\n        std::cout << division[i] << \" \";\n    }\n    std::cout << std::endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int n = 200;\nconst int m = 10;\n\nvector<int> stacks[m];\nbool carried_out[n + 1];\nvector<pair<int, int>> operations;\n\nvoid move_box(int v, int dest_stack) {\n    for (int i = 0; i < m; ++i) {\n        auto& stack = stacks[i];\n        if (find(stack.begin(), stack.end(), v) != stack.end()) {\n            int idx = distance(stack.begin(), find(stack.begin(), stack.end(), v));\n            int energy = stack.size() - idx;\n            operations.emplace_back(v, dest_stack + 1);\n            vector<int> temp(stack.begin() + idx, stack.end());\n            stack.erase(stack.begin() + idx, stack.end());\n            stacks[dest_stack].insert(stacks[dest_stack].end(), temp.begin(), temp.end());\n            return;\n        }\n    }\n}\n\nint main() {\n    int b[m][n / m];\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < n / m; ++j) {\n            cin >> b[i][j];\n            stacks[i].push_back(b[i][j]);\n        }\n    }\n\n    for (int v = 1; v <= n; ++v) {\n        int top_stack = -1;\n        for (int i = 0; i < m; ++i) {\n            if (!stacks[i].empty() && stacks[i].back() == v) {\n                top_stack = i;\n                break;\n            }\n        }\n\n        if (top_stack != -1) {\n            operations.emplace_back(v, 0);\n            carried_out[v] = true;\n            stacks[top_stack].pop_back();\n        } else {\n            // Find the stack containing v and move it to an appropriate stack\n            int src_stack = -1;\n            for (int i = 0; i < m; ++i) {\n                auto& stack = stacks[i];\n                auto it = find(stack.begin(), stack.end(), v);\n                if (it != stack.end()) {\n                    src_stack = i;\n                    break;\n                }\n            }\n\n            if (src_stack == -1) {\n                cerr << \"Box \" << v << \" not found.\" << endl;\n                return 1;\n            }\n\n            int dest_stack = -1;\n            int min_top = n + 1;\n            for (int i = 0; i < m; ++i) {\n                if (stacks[i].empty() || (stacks[i].back() > v && stacks[i].back() < min_top)) {\n                    dest_stack = i;\n                    min_top = stacks[i].empty() ? n + 1 : stacks[i].back();\n                }\n            }\n\n            if (dest_stack == -1) {\n                // If no suitable stack is found, just pick any non-empty stack\n                for (int i = 0; i < m; ++i) {\n                    if (!stacks[i].empty()) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n\n            move_box(v, dest_stack);\n            // After moving, check again if v is at the top\n            for (int i = 0; i < m; ++i) {\n                if (!stacks[i].empty() && stacks[i].back() == v) {\n                    operations.emplace_back(v, 0);\n                    carried_out[v] = true;\n                    stacks[i].pop_back();\n                    break;\n                }\n            }\n        }\n    }\n\n    for (const 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>\n#include <stack>\n#include <random>\n\nusing namespace std;\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<bool>> visited;\n\nvoid dfs(int i, int j, vector<char>& route) {\n    visited[i][j] = true;\n    int di[] = {0, 1, 0, -1};\n    int dj[] = {1, 0, -1, 0};\n    char dir[] = {'R', 'D', 'L', 'U'};\n\n    random_device rd;\n    mt19937 g(rd());\n    vector<int> directions = {0, 1, 2, 3};\n    shuffle(directions.begin(), directions.end(), g);\n\n    for (int k : directions) {\n        int i2 = i + di[k];\n        int j2 = j + dj[k];\n        if (0 <= i2 && i2 < N && 0 <= j2 && j2 < N && !visited[i2][j2]) {\n            if (di[k] == 0 && v[i][min(j, j2)] == '0' || dj[k] == 0 && h[min(i, i2)][j] == '0') {\n                route.push_back(dir[k]);\n                dfs(i2, j2, route);\n                route.push_back(dir[(k + 2) % 4]);\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> N;\n    h.resize(N - 1);\n    v.resize(N);\n    d.resize(N, vector<int>(N));\n    visited.resize(N, vector<bool>(N, false));\n\n    for (int i = 0; i < N - 1; i++) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\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<char> route;\n    dfs(0, 0, route);\n\n    // Simple route optimization: remove consecutive duplicates\n    string optimizedRoute;\n    for (char c : route) {\n        if (optimizedRoute.empty() || c != optimizedRoute.back()) {\n            optimizedRoute += c;\n        }\n    }\n\n    cout << optimizedRoute << endl;\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n#include <queue>\n\nusing namespace std;\n\nstruct Position {\n    int i, j;\n};\n\nstruct BeamSearchNode {\n    vector<Position> currentPos;\n    string S;\n    vector<pair<int, int>> operations;\n    int score;\n};\n\nstruct CompareNodes {\n    bool operator()(const BeamSearchNode& a, const BeamSearchNode& b) {\n        return a.score < b.score;\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n\n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> t[i];\n    }\n\n    unordered_map<char, vector<Position>> charPositions;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            charPositions[grid[i][j]].push_back({i, j});\n        }\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    priority_queue<BeamSearchNode, vector<BeamSearchNode>, CompareNodes> queue;\n    BeamSearchNode initialNode = {{{si, sj}}, \"\", {}, 0};\n    queue.push(initialNode);\n\n    vector<pair<int, int>> bestOperations;\n    int bestScore = -1e9;\n\n    for (int step = 0; step < 5000; ++step) {\n        if (queue.empty()) break;\n\n        BeamSearchNode node = queue.top();\n        queue.pop();\n\n        if (node.score > bestScore) {\n            bestScore = node.score;\n            bestOperations = node.operations;\n        }\n\n        int radius = min(N, 5);\n        for (int di = -radius; di <= radius; ++di) {\n            for (int dj = -radius; dj <= radius; ++dj) {\n                int i = node.currentPos.back().i + di;\n                int j = node.currentPos.back().j + dj;\n                if (i >= 0 && i < N && j >= 0 && j < N) {\n                    int cost = abs(di) + abs(dj) + 1;\n                    char c = grid[i][j];\n                    string newS = node.S + c;\n\n                    int score = 0;\n                    for (const auto& tk : t) {\n                        if (newS.size() <= tk.size() && tk.substr(0, newS.size()) == newS) {\n                            score += 1;\n                        }\n                    }\n\n                    BeamSearchNode newNode = {node.currentPos, newS, node.operations, node.score + score};\n                    newNode.currentPos.push_back({i, j});\n                    newNode.operations.push_back({i, j});\n\n                    if (newNode.operations.size() <= 5000) {\n                        queue.push(newNode);\n                    }\n                }\n            }\n        }\n    }\n\n    for (const auto& op : bestOperations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc030":"int main() {\n    read_input();\n    vector<vector<int>> estimated_oil_reserves(N, vector<int>(N, -1));\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dis(0, N - 1);\n\n    for (int i = 0; i < N * N; ++i) {\n        int x = dis(gen);\n        int y = dis(gen);\n        if (estimated_oil_reserves[x][y] == -1) {\n            drill(x, y);\n            // Update estimated_oil_reserves based on the response\n        }\n    }\n\n    // Generate a guess based on estimated_oil_reserves\n    vector<pair<int, int>> guess_squares;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (estimated_oil_reserves[i][j] > 0) {\n                guess_squares.emplace_back(i, j);\n            }\n        }\n    }\n    guess(guess_squares);\n\n    return 0;\n}","ahc031":"```cpp\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int W = 1000;\n\nstruct Rectangle {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    int D, N;\n    cin >> D >> N;\n\n    vector<vector<int>> areas(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> areas[d][k];\n        }\n    }\n\n    vector<vector<Rectangle>> rectangles(D, vector<Rectangle>(N));\n\n    // Initial placement for the first day\n    vector<pair<int, int>> sizes(N);\n    for (int k = 0; k < N; k++) {\n        sizes[k] = {areas[0][k], k};\n    }\n    sort(sizes.begin(), sizes.end());\n\n    int x = 0, y = 0;\n    for (auto [area, k] : sizes) {\n        int w = min(W - x, (int)sqrt(area));\n        int h = (area + w - 1) / w;\n        rectangles[0][k] = {x, y, x + w, y + h};\n        x += w;\n        if (x >= W) {\n            x = 0;\n            y += h;\n        }\n    }\n\n    // Subsequent days\n    for (int d = 1; d < D; d++) {\n        vector<pair<int, int>> sizes(N);\n        for (int k = 0; k < N; k++) {\n            sizes[k] = {areas[d][k], k};\n        }\n        sort(sizes.begin(), sizes.end());\n\n        for (auto [area, k] : sizes) {\n            Rectangle prev_rect = rectangles[d - 1][k];\n            int w = min(W - prev_rect.x1, (int)sqrt(area));\n            int h = (area + w - 1) / w;\n            rectangles[d][k] = {prev_rect.x1, prev_rect.y1, prev_rect.x1 + w, prev_rect.y1 + h};\n        }\n    }\n\n    // Output the rectangle coordinates\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cout << rectangles[d][k].x1 << \" \" << rectangles[d][k].y1 << \" \" << rectangles[d][k].x2 << \" \" << rectangles[d][k].y2 << endl;\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nstruct Operation {\n    int stamp_id;\n    int x, y;\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    int grid[N][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    int stamps[M][3][3];\n    for (int m = 0; m < M; ++m) {\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                cin >> stamps[m][i][j];\n            }\n        }\n    }\n\n    vector<Operation> operations;\n\n    for (int k = 0; k < K; ++k) {\n        int best_stamp_id = -1, best_x = -1, best_y = -1;\n        int max_increase = 0;\n\n        for (int stamp_id = 0; stamp_id < M; ++stamp_id) {\n            for (int x = 0; x <= N - 3; ++x) {\n                for (int y = 0; y <= N - 3; ++y) {\n                    int new_grid[N][N];\n                    copy(&grid[0][0], &grid[0][0] + N * N, &new_grid[0][0]);\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            new_grid[x + i][y + j] += stamps[stamp_id][i][j];\n                        }\n                    }\n                    int new_sum = 0;\n                    for (int i = 0; i < N; ++i) {\n                        for (int j = 0; j < N; ++j) {\n                            new_sum = (new_sum + new_grid[i][j] % MOD) % MOD;\n                        }\n                    }\n                    int current_sum = 0;\n                    for (int i = 0; i < N; ++i) {\n                        for (int j = 0; j < N; ++j) {\n                            current_sum = (current_sum + grid[i][j] % MOD) % MOD;\n                        }\n                    }\n                    int increase = new_sum - current_sum;\n                    if (increase > max_increase) {\n                        max_increase = increase;\n                        best_stamp_id = stamp_id;\n                        best_x = x;\n                        best_y = y;\n                    }\n                }\n            }\n        }\n\n        if (max_increase > 0) {\n            for (int i = 0; i < 3; ++i) {\n                for (int j = 0; j < 3; ++j) {\n                    grid[best_x + i][best_y + j] += stamps[best_stamp_id][i][j];\n                }\n            }\n            operations.push_back({best_stamp_id, best_x, best_y});\n        } else {\n            break;\n        }\n    }\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.stamp_id << \" \" << op.x << \" \" << op.y << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURN = 10000;\n\nstruct Crane {\n    int x, y;\n    bool holding;\n    int container;\n};\n\nint grid[N][N];\nCrane cranes[N];\nvector<int> containersToDispatch[N];\nint turn = 0;\n\nvoid simulate() {\n    vector<string> operations(N, \"\");\n    // Simulate the container dispatch process\n    while (turn < MAX_TURN) {\n        // Bring in new containers\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][0] == -1 && !containersToDispatch[i].empty()) {\n                grid[i][0] = containersToDispatch[i].back();\n                containersToDispatch[i].pop_back();\n            }\n        }\n\n        // Determine the next action for each crane\n        for (int i = 0; i < N; ++i) {\n            char operation = '.';\n            // Improved logic to move cranes towards the dispatch gates\n            if (cranes[i].holding && cranes[i].y == N - 1) {\n                operation = 'Q';\n                grid[cranes[i].x][cranes[i].y] = cranes[i].container;\n                cranes[i].holding = false;\n            } else if (!cranes[i].holding && grid[cranes[i].x][cranes[i].y] != -1) {\n                operation = 'P';\n                cranes[i].container = grid[cranes[i].x][cranes[i].y];\n                grid[cranes[i].x][cranes[i].y] = -1;\n                cranes[i].holding = true;\n            } else if (cranes[i].holding && cranes[i].y < N - 1) {\n                operation = 'R';\n                cranes[i].y++;\n            } else if (!cranes[i].holding && cranes[i].y < N - 1 && grid[cranes[i].x][cranes[i].y + 1] == -1) {\n                operation = 'R';\n                cranes[i].y++;\n            }\n            operations[i] += operation;\n        }\n\n        // Dispatch containers\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][N - 1] != -1) {\n                // Dispatch the container\n                grid[i][N - 1] = -1;\n            }\n        }\n\n        turn++;\n        bool allDone = true;\n        for (int i = 0; i < N; ++i) {\n            if (!containersToDispatch[i].empty()) {\n                allDone = false;\n                break;\n            }\n        }\n        if (allDone) {\n            break;\n        }\n    }\n\n    // Output the operations for each crane\n    for (int i = 0; i < N; ++i) {\n        while (operations[i].length() < turn) {\n            operations[i] += '.';\n        }\n        cout << operations[i] << endl;\n    }\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector<vector<int>> A(n, vector<int>(n));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> A[i][j];\n            containersToDispatch[i].push_back(A[i][j]);\n        }\n        reverse(containersToDispatch[i].begin(), containersToDispatch[i].end());\n    }\n\n    // Initialize the grid and cranes\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            grid[i][j] = -1;\n        }\n        cranes[i].x = i;\n        cranes[i].y = 0;\n        cranes[i].holding = false;\n    }\n\n    simulate();\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nint N;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nint h[20][20];\nint loaded = 0;\npair<int, int> pos = {0, 0};\n\nvoid load(int d) {\n    cout << \"+\" << d << endl;\n    h[pos.first][pos.second] -= d;\n    loaded += d;\n}\n\nvoid unload(int d) {\n    cout << \"-\" << d << endl;\n    h[pos.first][pos.second] += d;\n    loaded -= d;\n}\n\nvoid move(int d) {\n    cout << dir[d] << endl;\n    pos.first += dx[d];\n    pos.second += dy[d];\n}\n\nint main() {\n    cin >> N;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h[i][j];\n        }\n    }\n\n    // Greedy algorithm\n    priority_queue<pair<int, pair<int, int>>> pq;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (h[i][j] != 0) {\n                pq.push({abs(h[i][j]), {i, j}});\n            }\n        }\n    }\n\n    while (!pq.empty()) {\n        auto [val, pos2] = pq.top();\n        pq.pop();\n        int x = pos2.first, y = pos2.second;\n\n        // Move to (x, y)\n        int min_dist = abs(pos.first - x) + abs(pos.second - y);\n        while (pos.first != x || pos.second != y) {\n            for (int d = 0; d < 4; d++) {\n                int nx = pos.first + dx[d], ny = pos.second + dy[d];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N && abs(nx - x) + abs(ny - y) < min_dist) {\n                    move(d);\n                    min_dist = abs(pos.first - x) + abs(pos.second - y);\n                    break;\n                }\n            }\n        }\n\n        // Load/unload at (x, y)\n        if (h[x][y] > 0) {\n            load(min(h[x][y], 1000000));\n        } else if (h[x][y] < 0) {\n            if (loaded >= -h[x][y]) { // Check if there's enough soil to unload\n                unload(min(-h[x][y], loaded));\n            } else {\n                // If not enough soil, load the remaining height to make it 0\n                load(min(-h[x][y] - loaded, 1000000));\n                unload(loaded);\n            }\n        }\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nstruct Seed {\n    int id;\n    vector<int> eval;\n    int value;\n};\n\nbool compareSeeds(const Seed& a, const Seed& b) {\n    return a.value > b.value;\n}\n\nint main() {\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seedCount = 2 * N * (N - 1);\n    vector<Seed> seeds(seedCount);\n\n    for (int i = 0; i < seedCount; i++) {\n        seeds[i].id = i;\n        seeds[i].eval.resize(M);\n        seeds[i].value = 0;\n\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i].eval[j];\n            seeds[i].value += seeds[i].eval[j];\n        }\n    }\n\n    sort(seeds.begin(), seeds.end(), compareSeeds);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int t = 0; t < T; t++) {\n        vector<vector<int>> grid(N, vector<int>(N));\n        vector<Seed> selectedSeeds(N * N);\n\n        // Select top N*N seeds\n        for (int i = 0; i < N * N; i++) {\n            selectedSeeds[i] = seeds[i];\n        }\n\n        // Greedy initialization\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                grid[i][j] = i * N + j;\n            }\n        }\n\n        // Simulated annealing\n        double temperature = 1000.0;\n        double coolingRate = 0.99;\n\n        int currentScore = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (i < N - 1) currentScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i + 1][j]].value;\n                if (j < N - 1) currentScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i][j + 1]].value;\n            }\n        }\n\n        for (int iteration = 0; iteration < 10000; iteration++) {\n            int i1 = dis(gen), j1 = dis(gen);\n            int i2 = dis(gen), j2 = dis(gen);\n\n            swap(grid[i1][j1], grid[i2][j2]);\n\n            int newScore = 0;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (i < N - 1) newScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i + 1][j]].value;\n                    if (j < N - 1) newScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i][j + 1]].value;\n                }\n            }\n\n            if (newScore > currentScore || exp((newScore - currentScore) / temperature) > (double)rand() / RAND_MAX) {\n                currentScore = newScore;\n            } else {\n                swap(grid[i1][j1], grid[i2][j2]);\n            }\n\n            temperature *= coolingRate;\n        }\n\n        // Output grid arrangement\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                else cout << endl;\n            }\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seedCount; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> seeds[i].eval[j];\n                seeds[i].value = 0;\n                for (int k = 0; k < M; k++) {\n                    seeds[i].value += seeds[i].eval[k];\n                }\n            }\n        }\n\n        sort(seeds.begin(), seeds.end(), compareSeeds);\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n\nint main() {\n    int N, M, V;\n    std::cin >> N >> M >> V;\n\n    std::vector<std::vector<int>> s(N, std::vector<int>(N));\n    std::vector<std::vector<int>> t(N, std::vector<int>(N));\n\n    for (int i = 0; i < N; ++i) {\n        std::string str;\n        std::cin >> str;\n        for (int j = 0; j < N; ++j) {\n            s[i][j] = str[j] - '0';\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        std::string str;\n        std::cin >> str;\n        for (int j = 0; j < N; ++j) {\n            t[i][j] = str[j] - '0';\n        }\n    }\n\n    // Design the robotic arm\n    int V_prime = std::min(V, M + 1);\n    std::cout << V_prime << std::endl;\n    for (int i = 1; i < V_prime; ++i) {\n        std::cout << 0 << \" \" << 1 << std::endl;\n    }\n\n    // Initial position of the root\n    int rx = N / 2, ry = N / 2;\n    std::cout << rx << \" \" << ry << std::endl;\n\n    // Sequence of operations\n    for (int turn = 0; turn < 100; ++turn) {\n        std::string op(2 * V_prime, '.');\n        // Simple random movement for demonstration\n        if (rx > 0 && rand() % 2) {\n            rx--;\n            op[0] = 'U';\n        } else if (rx < N - 1 && rand() % 2) {\n            rx++;\n            op[0] = 'D';\n        }\n        if (ry > 0 && rand() % 2) {\n            ry--;\n            op[0] = 'L';\n        } else if (ry < N - 1 && rand() % 2) {\n            ry++;\n            op[0] = 'R';\n        }\n\n        // Random rotation for demonstration\n        if (V_prime > 1 && rand() % 2) {\n            op[1] = 'L';\n        }\n\n        // Grab or release takoyaki for demonstration\n        if (rand() % 2) {\n            op[V_prime] = 'P';\n        }\n\n        std::cout << op << std::endl;\n    }\n\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cstddef> // Include this for std::size_t and std::ptrdiff_t\n\nstruct Point {\n    int x, y;\n};\n\nint main() {\n    int N;\n    std::cin >> N;\n\n    std::vector<Point> points(2*N);\n    for (int i = 0; i < 2*N; ++i) {\n        std::cin >> points[i].x >> points[i].y;\n    }\n\n    std::vector<Point> mackerels(points.begin(), points.begin() + N);\n    std::vector<Point> sardines(points.begin() + N, points.end());\n\n    int minX = std::min_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.x < b.x; })->x;\n    int maxX = std::max_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.x < b.x; })->x;\n    int minY = std::min_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.y < b.y; })->y;\n    int maxY = std::max_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.y < b.y; })->y;\n\n    std::vector<Point> polygon = {{minX, minY}, {maxX, minY}, {maxX, maxY}, {minX, maxY}};\n\n    std::cout << polygon.size() << std::endl;\n    for (const auto& point : polygon) {\n        std::cout << point.x << \" \" << point.y << std::endl;\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nstruct Rectangle {\n    int index;\n    int w, h;\n};\n\nbool compareRectangles(const Rectangle& a, const Rectangle& b) {\n    return std::max(a.w, a.h) > std::max(b.w, b.h);\n}\n\nint main() {\n    int N, T;\n    double sigma;\n    std::cin >> N >> T >> sigma;\n\n    std::vector<Rectangle> rectangles(N);\n    for (int i = 0; i < N; ++i) {\n        rectangles[i].index = i;\n        std::cin >> rectangles[i].w >> rectangles[i].h;\n    }\n\n    std::sort(rectangles.begin(), rectangles.end(), compareRectangles);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> dis(0, 1);\n\n    for (int t = 0; t < T; ++t) {\n        std::vector<Rectangle> placedRectangles;\n        std::vector<std::pair<int, int>> positions(N, std::make_pair(0, 0));\n\n        int n = N; // Number of rectangles to place\n\n        std::cout << n << std::endl;\n        for (int i = 0; i < n; ++i) {\n            Rectangle rect = rectangles[i];\n            int rotation = dis(gen);\n            char direction = (dis(gen) == 0) ? 'U' : 'L';\n            int reference = (i == 0) ? -1 : (dis(gen) == 0) ? -1 : placedRectangles[dis(gen) % placedRectangles.size()].index;\n\n            if (rotation == 1) {\n                std::swap(rect.w, rect.h);\n            }\n\n            std::cout << rect.index << \" \" << rotation << \" \" << direction << \" \" << reference << std::endl;\n\n            // Update the positions vector\n            if (direction == 'U') {\n                if (reference == -1) {\n                    positions[rect.index].first = 0;\n                    positions[rect.index].second = 0;\n                } else {\n                    // Find the reference rectangle and update the position accordingly\n                    for (const auto& placedRect : placedRectangles) {\n                        if (placedRect.index == reference) {\n                            positions[rect.index].first = positions[placedRect.index].first;\n                            positions[rect.index].second = positions[placedRect.index].second - rect.h;\n                            break;\n                        }\n                    }\n                }\n            } else {\n                if (reference == -1) {\n                    positions[rect.index].first = 0;\n                    positions[rect.index].second = 0;\n                } else {\n                    // Find the reference rectangle and update the position accordingly\n                    for (const auto& placedRect : placedRectangles) {\n                        if (placedRect.index == reference) {\n                            positions[rect.index].first = positions[placedRect.index].first + placedRect.w;\n                            positions[rect.index].second = positions[placedRect.index].second;\n                            break;\n                        }\n                    }\n                }\n            }\n\n            placedRectangles.push_back(rect);\n        }\n\n        std::cout.flush();\n\n        int W, H;\n        std::cin >> W >> H;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n};\n\nint main() {\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<Edge> edges(M);\n    for (int i = 0; i < M; i++) {\n        cin >> edges[i].u >> edges[i].v;\n    }\n\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<int> parent(N, -1);\n    vector<vector<int>> graph(N);\n    for (const auto& edge : edges) {\n        graph[edge.u].push_back(edge.v);\n        graph[edge.v].push_back(edge.u);\n    }\n\n    // Perform a BFS traversal to construct the rooted trees\n    queue<int> q;\n    vector<bool> visited(N, false);\n    vector<int> roots;\n    for (int i = 0; i < N; i++) {\n        if (!visited[i]) {\n            roots.push_back(i);\n            q.push(i);\n            visited[i] = true;\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (int v : graph[u]) {\n                    if (!visited[v]) {\n                        visited[v] = true;\n                        parent[v] = u;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n\n    // Make sure the height constraint is satisfied\n    for (int i = 0; i < N; i++) {\n        if (i != roots[0] && parent[i] != -1) {\n            int height = 0;\n            int v = i;\n            while (v != roots[0]) {\n                height++;\n                v = parent[v];\n                if (height > H) {\n                    parent[i] = -1; // Make i a root if height exceeds H\n                    break;\n                }\n            }\n        }\n    }\n\n    // Output the parent of each vertex\n    for (int i = 0; i < N; i++) {\n        cout << parent[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n\nusing namespace std;\n\nconst int N = 20;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nint main() {\n    int n;\n    cin >> n;\n    vector<string> grid(n);\n    for (int i = 0; i < n; i++) {\n        cin >> grid[i];\n    }\n\n    vector<pair<char, int>> operations;\n    queue<pair<int, int>> oniQueue;\n\n    // Iterate through the grid to identify Oni positions\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            if (grid[i][j] == 'x') {\n                oniQueue.push({i, j});\n            }\n        }\n    }\n\n    while (!oniQueue.empty()) {\n        int x = oniQueue.front().first;\n        int y = oniQueue.front().second;\n        oniQueue.pop();\n\n        if (grid[x][y] != 'x') continue;\n\n        // Check if there is no Fukunokami in any direction\n        for (int k = 0; k < 4; k++) {\n            int count = 0;\n            int nx = x + dx[k];\n            int ny = y + dy[k];\n            while (nx >= 0 && nx < n && ny >= 0 && ny < n) {\n                if (grid[nx][ny] == 'o') break;\n                count++;\n                nx += dx[k];\n                ny += dy[k];\n            }\n\n            if (nx < 0 || nx >= n || ny < 0 || ny >= n) {\n                // Shift in the direction that does not contain a Fukunokami\n                if (k == 0) { // Up\n                    for (int i = 0; i <= x; i++) {\n                        operations.push_back({'U', y});\n                    }\n                    for (int i = 0; i <= x; i++) {\n                        operations.push_back({'D', y});\n                    }\n                } else if (k == 1) { // Down\n                    for (int i = x; i < n - 1; i++) {\n                        operations.push_back({'D', y});\n                    }\n                    for (int i = x; i < n - 1; i++) {\n                        operations.push_back({'U', y});\n                    }\n                } else if (k == 2) { // Left\n                    for (int i = 0; i <= y; i++) {\n                        operations.push_back({'L', x});\n                    }\n                    for (int i = 0; i <= y; i++) {\n                        operations.push_back({'R', x});\n                    }\n                } else if (k == 3) { // Right\n                    for (int i = y; i < n - 1; i++) {\n                        operations.push_back({'R', x});\n                    }\n                    for (int i = y; i < n - 1; i++) {\n                        operations.push_back({'L', x});\n                    }\n                }\n\n                // Update the grid to reflect the removal of the Oni\n                grid[x][y] = '.';\n                break;\n            }\n        }\n    }\n\n    // Output the sequence of operations\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nconst int N = 100;\nconst int L = 500000;\n\nvector<int> T(N);\nvector<int> a(N), b(N);\nvector<int> count(N, 0);\nmt19937 mt(42);\n\nvoid simulate(int steps) {\n    uniform_int_distribution<int> dist(0, N-1);\n    for (int step = 0; step < steps; ++step) {\n        int i = dist(mt);\n        int orig_a = a[i], orig_b = b[i];\n        int new_a = dist(mt), new_b = dist(mt);\n        a[i] = new_a;\n        b[i] = new_b;\n        count.assign(N, 0);\n        int last = 0;\n        count[0] = 1;\n        for (int t = 1; t < L; ++t) {\n            int next = (count[last] % 2 == 0) ? b[last] : a[last];\n            count[next]++;\n            last = next;\n        }\n        int new_error = accumulate(count.begin(), count.end(), 0, [&](int sum, int c, int i) { return sum + abs(c - T[i]); });\n        if (new_error > accumulate(count.begin(), count.end(), 0, [&](int sum, int c, int i) { return sum + abs(c - T[i]); })) {\n            a[i] = orig_a;\n            b[i] = orig_b;\n        }\n    }\n}\n\nint main() {\n    cin >> N >> L;\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    // Initialize a and b\n    for (int i = 0; i < N; ++i) {\n        a[i] = (i + 1) % N;\n        b[i] = (i + 2) % N;\n    }\n\n    simulate(100000);\n\n    for (int i = 0; i < N; ++i) {\n        cout << a[i] << \" \" << b[i] << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cassert>\n\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double x, y;\n};\n\nstruct Edge {\n    int u, v;\n};\n\nint N, M, Q, L, W;\nvector<int> G;\nvector<City> cities;\nvector<vector<int>> groups;\nvector<vector<Edge>> edges;\n\nvoid readInput() {\n    cin >> N >> M >> Q >> L >> W;\n    G.resize(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n    cities.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].id = i;\n        cities[i].x = (cities[i].lx + cities[i].rx) / 2.0;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2.0;\n    }\n}\n\nvoid initialGrouping() {\n    sort(cities.begin(), cities.end(), [](const City& a, const City& b) {\n        return make_pair(a.x, a.y) < make_pair(b.x, b.y);\n    });\n    groups.resize(M);\n    int start = 0;\n    for (int i = 0; i < M; ++i) {\n        groups[i].resize(G[i]);\n        for (int j = 0; j < G[i]; ++j) {\n            groups[i][j] = cities[start + j].id;\n        }\n        start += G[i];\n    }\n}\n\nvoid queryFortuneTeller(const vector<int>& group) {\n    if (group.size() <= 1) return;\n    vector<Edge> mstEdges;\n    if (group.size() <= L) {\n        cout << \"? \" << group.size();\n        for (int city : group) cout << \" \" << city;\n        cout << endl;\n        for (int i = 0; i < group.size() - 1; ++i) {\n            int u, v;\n            cin >> u >> v;\n            mstEdges.push_back({u, v});\n        }\n        edges.push_back(mstEdges);\n    } else {\n        // For larger groups, divide them into smaller subsets and query\n        for (size_t i = 0; i < group.size(); i += L - 1) {\n            vector<int> subset;\n            for (size_t j = i; j < min(i + L - 1, group.size()); ++j) {\n                subset.push_back(group[j]);\n            }\n            if (subset.size() > 1) {\n                cout << \"? \" << subset.size();\n                for (int city : subset) cout << \" \" << city;\n                cout << endl;\n                vector<Edge> subsetMstEdges;\n                for (int k = 0; k < subset.size() - 1; ++k) {\n                    int u, v;\n                    cin >> u >> v;\n                    subsetMstEdges.push_back({u, v});\n                }\n                mstEdges.insert(mstEdges.end(), subsetMstEdges.begin(), subsetMstEdges.end());\n            }\n        }\n        edges.push_back(mstEdges);\n    }\n}\n\nvoid buildRoads() {\n    edges.clear();\n    for (const auto& group : groups) {\n        queryFortuneTeller(group);\n    }\n}\n\nvoid outputAnswer() {\n    cout << \"!\" << endl;\n    for (size_t i = 0; i < groups.size(); ++i) {\n        for (int city : groups[i]) cout << city << \" \";\n        cout << endl;\n        for (const auto& edge : edges[i]) cout << edge.u << \" \" << edge.v << endl;\n    }\n}\n\nint main() {\n    readInput();\n    initialGrouping();\n    buildRoads();\n    outputAnswer();\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n\nusing namespace std;\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n\n    vector<vector<int>> grid(N, vector<int>(N, 0)); // 0: empty, 1: block\n\n    struct Pos {\n        int x, y;\n    };\n\n    Pos pos;\n    cin >> pos.x >> pos.y;\n    vector<Pos> targets(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> targets[i].x >> targets[i].y;\n    }\n\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    char dirChar[] = {'U', 'D', 'L', 'R'};\n\n    auto manhattanDistance = [](Pos a, Pos b) {\n        return abs(a.x - b.x) + abs(a.y - b.y);\n    };\n\n    auto slide = [&](int x, int y, int dir, Pos &end) {\n        int nx = x + dx[dir];\n        int ny = y + dy[dir];\n        while (0 <= nx && nx < N && 0 <= ny && ny < N && grid[nx][ny] == 0) {\n            x = nx;\n            y = ny;\n            nx += dx[dir];\n            ny += dy[dir];\n        }\n        end.x = x;\n        end.y = y;\n    };\n\n    for (int targetIndex = 0; targetIndex < M; ++targetIndex) {\n        Pos target = targets[targetIndex];\n        while (pos.x != target.x || pos.y != target.y) {\n            int bestDir = -1;\n            char bestAction = ' ';\n            Pos nextPos = pos;\n            int minDist = manhattanDistance(pos, target);\n\n            for (int dir = 0; dir < 4; ++dir) {\n                int nx = pos.x + dx[dir];\n                int ny = pos.y + dy[dir];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                    // Try Move\n                    if (grid[nx][ny] == 0) {\n                        int dist = manhattanDistance({nx, ny}, target);\n                        if (dist < minDist) {\n                            minDist = dist;\n                            bestDir = dir;\n                            bestAction = 'M';\n                            nextPos = {nx, ny};\n                        }\n                    }\n\n                    // Try Slide\n                    Pos slideEnd = pos;\n                    slide(pos.x, pos.y, dir, slideEnd);\n                    if (slideEnd.x != pos.x || slideEnd.y != pos.y) {\n                        int dist = manhattanDistance(slideEnd, target);\n                        if (dist < minDist && (slideEnd.x != target.x || slideEnd.y != target.y)) {\n                            minDist = dist;\n                            bestDir = dir;\n                            bestAction = 'S';\n                            nextPos = slideEnd;\n                        }\n                    }\n                }\n\n                // Try Alter\n                if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                    int originalBlock = grid[nx][ny];\n                    grid[nx][ny] = 1 - originalBlock;\n                    Pos slideEndAfterAlter = pos;\n                    slide(pos.x, pos.y, dir, slideEndAfterAlter);\n                    int dist = manhattanDistance(slideEndAfterAlter, target);\n                    if (dist < minDist && (slideEndAfterAlter.x != target.x || slideEndAfterAlter.y != target.y)) {\n                        minDist = dist;\n                        bestDir = dir;\n                        bestAction = 'A';\n                        nextPos = pos; // Alter doesn't change pos\n                    }\n                    grid[nx][ny] = originalBlock; // Revert\n                }\n            }\n\n            if (bestAction != ' ') {\n                cout << bestAction << \" \" << dirChar[bestDir] << endl;\n                if (bestAction == 'M') {\n                    pos = nextPos;\n                } else if (bestAction == 'S') {\n                    pos = nextPos;\n                } else if (bestAction == 'A') {\n                    int nx = pos.x + dx[bestDir];\n                    int ny = pos.y + dy[bestDir];\n                    grid[nx][ny] = 1 - grid[nx][ny];\n                }\n            } else {\n                // Fallback, should ideally not reach here\n                cout << \"M U\" << endl;\n            }\n        }\n    }\n\n    return 0;\n}"},"8":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Company {\n    int x, y, r, idx;\n    bool operator<(const Company& other) const {\n        return r > other.r;\n    }\n};\n\nint main() {\n    int n;\n    cin >> n;\n\n    vector<Company> companies(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n        companies[i].idx = i;\n    }\n\n    sort(companies.begin(), companies.end());\n\n    vector<vector<int>> ans(n, vector<int>(4));\n\n    int gridSize = 10000;\n    vector<bool> used(gridSize * gridSize, false);\n\n    for (const auto& company : companies) {\n        int x = company.x, y = company.y, r = company.r, idx = company.idx;\n\n        int size = min(100, (int)sqrt(r));\n        int sx = max(0, x - size / 2), sy = max(0, y - size / 2);\n\n        bool found = false;\n        for (int i = sx; i <= min(gridSize - size, x + size / 2); ++i) {\n            for (int j = sy; j <= min(gridSize - size, y + size / 2); ++j) {\n                bool valid = true;\n                for (int k = i; k < i + size; ++k) {\n                    for (int l = j; l < j + size; ++l) {\n                        if (used[k * gridSize + l]) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                    if (!valid) break;\n                }\n\n                if (valid) {\n                    ans[idx] = {i, j, i + size, j + size};\n                    for (int k = i; k < i + size; ++k) {\n                        for (int l = j; l < j + size; ++l) {\n                            used[k * gridSize + l] = true;\n                        }\n                    }\n                    found = true;\n                    break;\n                }\n            }\n            if (found) break;\n        }\n\n        if (!found) {\n            // Fallback to a simple assignment if no suitable rectangle is found\n            ans[idx] = {0, 0, 1, 1};\n        }\n    }\n\n    for (const auto& a : ans) {\n        cout << a[0] << \" \" << a[1] << \" \" << a[2] << \" \" << a[3] << endl;\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct State {\n    int x, y;\n    int score;\n    string path;\n    unordered_set<int> visited_tiles;\n\n    State(int x, int y, int score, string path, unordered_set<int> visited_tiles)\n        : x(x), y(y), score(score), path(path), visited_tiles(visited_tiles) {}\n};\n\nstruct CompareStates {\n    bool operator()(const State& a, const State& b) {\n        return a.score < b.score;\n    }\n};\n\nint main() {\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> tile_ids(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> tile_ids[i][j];\n        }\n    }\n\n    vector<vector<int>> scores(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> scores[i][j];\n        }\n    }\n\n    int initial_tile_id = tile_ids[si][sj];\n    unordered_set<int> initial_visited_tiles = {initial_tile_id};\n    State initial_state(si, sj, scores[si][sj], \"\", initial_visited_tiles);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    priority_queue<State, vector<State>, CompareStates> pq;\n    pq.push(initial_state);\n\n    int max_score = initial_state.score;\n    string max_path = \"\";\n\n    for (int iter = 0; iter < 500000; ++iter) {\n        if (pq.empty()) break;\n        State state = pq.top();\n        pq.pop();\n\n        if (state.score < max_score) continue;\n\n        vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n        vector<char> moves = {'U', 'D', 'L', 'R'};\n\n        vector<int> indices(4);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), gen);\n\n        for (int i : indices) {\n            int nx = state.x + directions[i].first;\n            int ny = state.y + directions[i].second;\n\n            if (nx < 0 || nx >= 50 || ny < 0 || ny >= 50) continue;\n\n            int next_tile_id = tile_ids[nx][ny];\n            if (state.visited_tiles.count(next_tile_id)) continue;\n\n            unordered_set<int> next_visited_tiles = state.visited_tiles;\n            next_visited_tiles.insert(next_tile_id);\n\n            int next_score = state.score + scores[nx][ny];\n            string next_path = state.path + moves[i];\n\n            State next_state(nx, ny, next_score, next_path, next_visited_tiles);\n\n            if (next_score > max_score) {\n                max_score = next_score;\n                max_path = next_path;\n            }\n\n            pq.push(next_state);\n        }\n    }\n\n    cout << max_path << endl;\n\n    return 0;\n}","ahc003":"#include <iostream>\n#include <queue>\n#include <vector>\n#include <unordered_map>\n#include <limits>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Edge {\n    int to;\n    double weight;\n    int count;\n};\n\nusing Graph = vector<vector<Edge>>;\n\nstruct Node {\n    int id;\n    double distance;\n    bool operator>(const Node& other) const {\n        return distance > other.distance;\n    }\n};\n\nGraph buildGraph() {\n    Graph graph(30 * 30);\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            int id = i * 30 + j;\n            if (i > 0) graph[id].push_back({id - 30, 1, 0}); // Up\n            if (i < 29) graph[id].push_back({id + 30, 1, 0}); // Down\n            if (j > 0) graph[id].push_back({id - 1, 1, 0}); // Left\n            if (j < 29) graph[id].push_back({id + 1, 1, 0}); // Right\n        }\n    }\n    return graph;\n}\n\nstring dijkstra(Graph& graph, int source, int target, mt19937& rng) {\n    vector<double> distances(graph.size(), numeric_limits<double>::max());\n    vector<int> previous(graph.size(), -1);\n    distances[source] = 0;\n\n    priority_queue<Node, vector<Node>, greater<Node>> queue;\n    queue.push({source, 0});\n\n    while (!queue.empty()) {\n        Node node = queue.top();\n        queue.pop();\n        if (node.id == target) break;\n\n        vector<Edge>& edges = graph[node.id];\n        shuffle(edges.begin(), edges.end(), rng); // Use shuffle instead of random_shuffle\n\n        for (const Edge& edge : edges) {\n            double newDistance = distances[node.id] + edge.weight;\n            if (newDistance < distances[edge.to]) {\n                distances[edge.to] = newDistance;\n                previous[edge.to] = node.id;\n                queue.push({edge.to, newDistance});\n            }\n        }\n    }\n\n    string path;\n    int current = target;\n    while (current != source) {\n        int prev = previous[current];\n        if (prev == current - 1) path += 'R';\n        else if (prev == current + 1) path += 'L';\n        else if (prev == current - 30) path += 'D';\n        else if (prev == current + 30) path += 'U';\n        current = prev;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nvoid updateGraph(Graph& graph, const string& path, double actualLength) {\n    double scaleFactor = actualLength / path.length();\n\n    int currentNode = 0;\n    for (char direction : path) {\n        int nextNode;\n        if (direction == 'U') nextNode = currentNode - 30;\n        else if (direction == 'D') nextNode = currentNode + 30;\n        else if (direction == 'L') nextNode = currentNode - 1;\n        else if (direction == 'R') nextNode = currentNode + 1;\n\n        for (Edge& edge : graph[currentNode]) {\n            if (edge.to == nextNode) {\n                edge.count++;\n                double alpha = 1.0 / (edge.count + 1);\n                edge.weight = (1 - alpha) * edge.weight + alpha * scaleFactor;\n                break;\n            }\n        }\n        for (Edge& edge : graph[nextNode]) {\n            if (edge.to == currentNode) {\n                edge.count++;\n                double alpha = 1.0 / (edge.count + 1);\n                edge.weight = (1 - alpha) * edge.weight + alpha * scaleFactor;\n                break;\n            }\n        }\n        currentNode = nextNode;\n    }\n}\n\nint main() {\n    Graph graph = buildGraph();\n    random_device rd;\n    mt19937 rng(rd());\n\n    for (int k = 0; k < 1000; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        int source = si * 30 + sj;\n        int target = ti * 30 + tj;\n\n        string path = dijkstra(graph, source, target, rng);\n        cout << path << endl;\n        cout.flush();\n\n        double actualLength;\n        cin >> actualLength;\n        updateGraph(graph, path, actualLength);\n    }\n\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct StringInfo {\n    string s;\n    int len;\n    bool used;\n};\n\nbool canPlaceString(vector<vector<char>>& matrix, const string& s, int i, int j, int dir) {\n    int N = matrix.size();\n    int len = s.length();\n\n    if (dir == 0) { // horizontal\n        for (int p = 0; p < len; ++p) {\n            int col = (j + p) % N;\n            if (matrix[i][col] != '.' && matrix[i][col] != s[p]) {\n                return false;\n            }\n        }\n    } else { // vertical\n        for (int p = 0; p < len; ++p) {\n            int row = (i + p) % N;\n            if (matrix[row][j] != '.' && matrix[row][j] != s[p]) {\n                return false;\n            }\n        }\n    }\n\n    return true;\n}\n\nvoid placeString(vector<vector<char>>& matrix, const string& s, int i, int j, int dir) {\n    int N = matrix.size();\n    int len = s.length();\n\n    if (dir == 0) { // horizontal\n        for (int p = 0; p < len; ++p) {\n            int col = (j + p) % N;\n            matrix[i][col] = s[p];\n        }\n    } else { // vertical\n        for (int p = 0; p < len; ++p) {\n            int row = (i + p) % N;\n            matrix[row][j] = s[p];\n        }\n    }\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<StringInfo> strings(M);\n\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i].s;\n        strings[i].len = strings[i].s.length();\n        strings[i].used = false;\n    }\n\n    // Sort the strings in descending order of their lengths\n    sort(strings.begin(), strings.end(), [](const StringInfo& a, const StringInfo& b) {\n        return a.len > b.len;\n    });\n\n    vector<vector<char>> matrix(N, vector<char>(N, '.'));\n\n    mt19937 mt(42);\n    uniform_int_distribution<int> dist(0, N - 1);\n\n    for (const auto& s : strings) {\n        if (s.used) continue;\n\n        bool placed = false;\n        for (int trial = 0; trial < 100; ++trial) {\n            int i = dist(mt), j = dist(mt);\n            int dir = dist(mt) % 2; // 0: horizontal, 1: vertical\n\n            if (canPlaceString(matrix, s.s, i, j, dir)) {\n                placeString(matrix, s.s, i, j, dir);\n                placed = true;\n                break;\n            }\n        }\n\n        if (placed) {\n            // Mark the string as used\n            for (auto& str : strings) {\n                if (str.s == s.s) {\n                    str.used = true;\n                    break;\n                }\n            }\n        }\n    }\n\n    // Print the resulting matrix\n    for (const auto& row : matrix) {\n        for (char c : row) {\n            cout << c;\n        }\n        cout << endl;\n    }\n\n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Pos {\n    int i, j;\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n\n    // Grid preprocessing\n    vector<Pos> roadSquares;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                roadSquares.push_back({i, j});\n            }\n        }\n    }\n\n    // Visibility graph construction\n    unordered_map<Pos, vector<Pos>> visibilityGraph;\n    for (const auto& pos : roadSquares) {\n        vector<Pos> visibleSquares;\n        // Compute visible squares from pos\n        for (const auto& otherPos : roadSquares) {\n            if (isVisible(pos, otherPos, grid)) {\n                visibleSquares.push_back(otherPos);\n            }\n        }\n        visibilityGraph[pos] = visibleSquares;\n    }\n\n    // Route construction\n    vector<Pos> route;\n    unordered_set<Pos> visited;\n    Pos currentPos = {si, sj};\n    route.push_back(currentPos);\n    visited.insert(currentPos);\n\n    while (visited.size() < roadSquares.size()) {\n        Pos nextPos = getNearestUnvisitedSquare(currentPos, visibilityGraph, visited);\n        if (nextPos.i == -1) {\n            // Backtrack\n            currentPos = route.back();\n            route.pop_back();\n        } else {\n            route.push_back(nextPos);\n            visited.insert(nextPos);\n            currentPos = nextPos;\n        }\n    }\n\n    // Route optimization (2-opt)\n    optimizeRoute(route, grid);\n\n    // Output\n    outputRoute(route);\n\n    return 0;\n}\n\n// Helper functions\nbool isVisible(const Pos& pos, const Pos& otherPos, const vector<string>& grid) {\n    // Check if otherPos is visible from pos\n    if (pos.i == otherPos.i) {\n        int minJ = min(pos.j, otherPos.j);\n        int maxJ = max(pos.j, otherPos.j);\n        for (int j = minJ; j <= maxJ; j++) {\n            if (grid[pos.i][j] == '#') {\n                return false;\n            }\n        }\n        return true;\n    } else if (pos.j == otherPos.j) {\n        int minI = min(pos.i, otherPos.i);\n        int maxI = max(pos.i, otherPos.i);\n        for (int i = minI; i <= maxI; i++) {\n            if (grid[i][pos.j] == '#') {\n                return false;\n            }\n        }\n        return true;\n    }\n    return false;\n}\n\nPos getNearestUnvisitedSquare(const Pos& pos, const unordered_map<Pos, vector<Pos>>& visibilityGraph, const unordered_set<Pos>& visited) {\n    // Find nearest unvisited square visible from pos\n    for (const auto& otherPos : visibilityGraph.at(pos)) {\n        if (visited.find(otherPos) == visited.end()) {\n            return otherPos;\n        }\n    }\n    return {-1, -1}; // Not found\n}\n\nvoid optimizeRoute(vector<Pos>& route, const vector<string>& grid) {\n    // 2-opt algorithm to optimize the route\n    int N = route.size();\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 1; i < N - 2; i++) {\n            for (int j = i + 1; j < N - 1; j++) {\n                int oldCost = getTravelTime(route[i - 1], route[i], grid) + getTravelTime(route[j], route[j + 1], grid);\n                int newCost = getTravelTime(route[i - 1], route[j], grid) + getTravelTime(route[i], route[j + 1], grid);\n                if (newCost < oldCost) {\n                    reverse(route.begin() + i, route.begin() + j + 1);\n                    improved = true;\n                }\n            }\n        }\n    }\n}\n\nint getTravelTime(const Pos& pos1, const Pos& pos2, const vector<string>& grid) {\n    // Compute travel time between pos1 and pos2\n    if (abs(pos1.i - pos2.i) + abs(pos1.j - pos2.j) != 1) {\n        return numeric_limits<int>::max(); // Invalid move\n    }\n    int cost = grid[pos2.i][pos2.j] - '0';\n    return cost;\n}\n\nvoid outputRoute(const vector<Pos>& route) {\n    // Output the route as a sequence of moves\n    for (int i = 0; i < route.size() - 1; i++) {\n        Pos pos1 = route[i];\n        Pos pos2 = route[i + 1];\n        if (pos1.i > pos2.i) {\n            cout << 'U';\n        } else if (pos1.i < pos2.i) {\n            cout << 'D';\n        } else if (pos1.j > pos2.j) {\n            cout << 'L';\n        } else if (pos1.j < pos2.j) {\n            cout << 'R';\n        }\n    }\n    cout << endl;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Task {\n    vector<int> d;\n    vector<int> dependencies;\n    int status; // -1: not started, 0: started, 1: completed\n};\n\nstruct TeamMember {\n    vector<int> s; // estimated skill levels\n    int task; // current task being worked on, -1 if available\n    int endDay; // day when the current task will be completed\n};\n\nint main() {\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<Task> tasks(N);\n    for (int i = 0; i < N; i++) {\n        tasks[i].d.resize(K);\n        for (int j = 0; j < K; j++) {\n            cin >> tasks[i].d[j];\n        }\n        tasks[i].status = -1;\n    }\n\n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        tasks[v - 1].dependencies.push_back(u - 1);\n    }\n\n    vector<TeamMember> teamMembers(M);\n    for (int i = 0; i < M; i++) {\n        teamMembers[i].s.resize(K, 0); // initialize estimated skill levels to 0\n        teamMembers[i].task = -1;\n        teamMembers[i].endDay = 0;\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n\n        // receive the list of team members who have completed their tasks\n        int n;\n        cin >> n;\n        if (n == -1) break;\n\n        vector<int> completedTeamMembers(n);\n        for (int i = 0; i < n; i++) {\n            cin >> completedTeamMembers[i];\n            completedTeamMembers[i]--;\n        }\n\n        // update task status and team member status\n        for (int teamMember : completedTeamMembers) {\n            if (teamMembers[teamMember].task != -1) {\n                tasks[teamMembers[teamMember].task].status = 1;\n                teamMembers[teamMember].task = -1;\n            }\n        }\n\n        // estimate skill levels of team members\n        for (int teamMember : completedTeamMembers) {\n            // TO DO: implement skill level estimation\n        }\n\n        // get available tasks\n        vector<int> availableTasks;\n        for (int i = 0; i < N; i++) {\n            if (tasks[i].status == -1) {\n                bool ok = true;\n                for (int dependency : tasks[i].dependencies) {\n                    if (tasks[dependency].status != 1) {\n                        ok = false;\n                        break;\n                    }\n                }\n                if (ok) availableTasks.push_back(i);\n            }\n        }\n\n        // assign tasks to available team members\n        vector<pair<int, int>> assignments;\n        for (int teamMember = 0; teamMember < M; teamMember++) {\n            if (teamMembers[teamMember].task == -1 && !availableTasks.empty()) {\n                // TO DO: implement task assignment heuristic\n                int task = availableTasks.back();\n                availableTasks.pop_back();\n                teamMembers[teamMember].task = task;\n                tasks[task].status = 0;\n                assignments.emplace_back(teamMember + 1, task + 1);\n            }\n        }\n\n        // output assignments\n        cout << assignments.size();\n        for (auto& assignment : assignments) {\n            cout << \" \" << assignment.first << \" \" << assignment.second;\n        }\n        cout << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Order {\n    int id;\n    int a, b, c, d;\n};\n\nint main() {\n    vector<Order> orders;\n    for (int i = 0; i < 1000; ++i) {\n        Order order;\n        order.id = i + 1;\n        cin >> order.a >> order.b >> order.c >> order.d;\n        orders.push_back(order);\n    }\n\n    // Improved initial solution using a greedy algorithm with a better heuristic\n    vector<Order> selectedOrders;\n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(orders.begin(), orders.end(), gen);\n    for (int i = 0; i < 50; ++i) {\n        selectedOrders.push_back(orders[i]);\n    }\n\n    // Simplified simulated annealing to improve the solution\n    auto startTime = chrono::high_resolution_clock::now();\n    int iteration = 0;\n    while (chrono::duration_cast<chrono::seconds>(chrono::high_resolution_clock::now() - startTime).count() < 1.9) {\n        iteration++;\n        int i = uniform_int_distribution<int>(0, selectedOrders.size() - 1)(gen);\n        int j = uniform_int_distribution<int>(0, orders.size() - 1)(gen);\n        if (find_if(selectedOrders.begin(), selectedOrders.end(), [&](const Order& order) { return order.id == orders[j].id; }) == selectedOrders.end()) {\n            // Replace the i-th order with the j-th order\n            selectedOrders[i] = orders[j];\n        }\n        if (iteration % 100 == 0) {\n            // Check time limit every 100 iterations\n            if (chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - startTime).count() > 1900) {\n                break;\n            }\n        }\n    }\n\n    // Construct the delivery route\n    vector<pair<int, int>> route;\n    route.push_back({400, 400});\n    for (const auto& order : selectedOrders) {\n        route.push_back({order.a, order.b});\n        route.push_back({order.c, order.d});\n    }\n    route.push_back({400, 400});\n\n    // Output the solution\n    cout << selectedOrders.size() << \" \";\n    for (const auto& order : selectedOrders) {\n        cout << order.id << \" \";\n    }\n    cout << endl;\n    cout << route.size() << \" \";\n    for (const auto& point : route) {\n        cout << point.first << \" \" << point.second << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <random>\n#include <cassert>\n\n// Union-Find data structure\nclass UnionFind {\npublic:\n    UnionFind(int n) : parent(n), rank(n, 0), size(n, 1) {\n        for (int i = 0; i < n; ++i) {\n            parent[i] = i;\n        }\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\n    void unite(int x, int y) {\n        int root_x = find(x);\n        int root_y = find(y);\n        if (root_x != root_y) {\n            if (rank[root_x] < rank[root_y]) {\n                parent[root_x] = root_y;\n                size[root_y] += size[root_x];\n            } else {\n                parent[root_y] = root_x;\n                size[root_x] += size[root_y];\n                if (rank[root_x] == rank[root_y]) {\n                    ++rank[root_x];\n                }\n            }\n        }\n    }\n\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n\n    int getSize(int x) {\n        return size[find(x)];\n    }\n\nprivate:\n    std::vector<int> parent;\n    std::vector<int> rank;\n    std::vector<int> size;\n};\n\nint main() {\n    const int N = 400;\n    const int M = 1995;\n\n    // Read vertex coordinates\n    std::vector<std::pair<int, int>> vertices(N);\n    for (auto& vertex : vertices) {\n        std::cin >> vertex.first >> vertex.second;\n    }\n\n    // Precompute Euclidean distances\n    std::vector<int> distances(M);\n    std::vector<std::pair<int, int>> edges(M);\n    for (int i = 0; i < M; ++i) {\n        std::cin >> edges[i].first >> edges[i].second;\n        int dx = vertices[edges[i].first].first - vertices[edges[i].second].first;\n        int dy = vertices[edges[i].first].second - vertices[edges[i].second].second;\n        distances[i] = std::round(std::sqrt(dx * dx + dy * dy));\n    }\n\n    // Initialize Union-Find data structure\n    UnionFind uf(N);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<double> dis(0.0, 1.0);\n\n    int count = 0;\n    for (int i = 0; i < M; ++i) {\n        int length;\n        std::cin >> length;\n\n        if (uf.same(edges[i].first, edges[i].second)) {\n            double prob = (length > 2 * distances[i]) ? 0.001 : (length > 1.5 * distances[i]) ? 0.05 : 0.1;\n            bool adopt = dis(gen) < prob;\n            std::cout << (adopt ? \"1\" : \"0\") << std::endl;\n            std::cout.flush();\n            if (adopt) {\n                uf.unite(edges[i].first, edges[i].second);\n                count++;\n            }\n        } else {\n            int size1 = uf.getSize(edges[i].first);\n            int size2 = uf.getSize(edges[i].second);\n            double prob = (length <= 1.1 * distances[i]) ? 1.0 : (size1 < N / 4 || size2 < N / 4) ? 0.95 : (length <= 1.3 * distances[i]) ? 0.9 : 0.7;\n            bool adopt = dis(gen) < prob;\n            std::cout << (adopt ? \"1\" : \"0\") << std::endl;\n            std::cout.flush();\n            if (adopt) {\n                uf.unite(edges[i].first, edges[i].second);\n                count++;\n            }\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 30;\nconst int DIR[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst char DIR_CHAR[4] = {'u', 'd', 'l', 'r'};\nconst char MOVE_CHAR[4] = {'U', 'D', 'L', 'R'};\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nint grid[N][N]; // 0: passable, 1: impassable\nvector<Pet> pets;\nvector<Human> humans;\nint M;\n\nvoid bfs(int x, int y, vector<vector<bool>>& visited) {\n    queue<pair<int, int>> q;\n    q.emplace(x, y);\n    visited[x][y] = true;\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n        for (int i = 0; i < 4; ++i) {\n            int nx = x + DIR[i][0];\n            int ny = y + DIR[i][1];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0 && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n}\n\nchar getAction(int h) {\n    Human& human = humans[h];\n    int x = human.x;\n    int y = human.y;\n    // Try to move to an adjacent passable square\n    vector<pair<int, int>> validMoves;\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + DIR[i][0];\n        int ny = y + DIR[i][1];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0) {\n            bool petPresent = false;\n            for (const Pet& pet : pets) {\n                if (pet.x == nx && pet.y == ny) {\n                    petPresent = true;\n                    break;\n                }\n            }\n            if (!petPresent) {\n                bool humanPresent = false;\n                for (int j = 0; j < M; ++j) {\n                    if (j != h && humans[j].x == nx && humans[j].y == ny) {\n                        humanPresent = true;\n                        break;\n                    }\n                }\n                if (!humanPresent) {\n                    validMoves.emplace_back(nx, ny);\n                }\n            }\n        }\n    }\n    if (!validMoves.empty()) {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, validMoves.size() - 1);\n        int chosenMove = dis(gen);\n        int dx = validMoves[chosenMove].first - x;\n        int dy = validMoves[chosenMove].second - y;\n        if (dx == -1) return 'U';\n        if (dx == 1) return 'D';\n        if (dy == -1) return 'L';\n        if (dy == 1) return 'R';\n    }\n\n    // Make impassable\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + DIR[i][0];\n        int ny = y + DIR[i][1];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0) {\n            bool valid = true;\n            for (int j = 0; j < 4; ++j) {\n                int nnx = nx + DIR[j][0];\n                int nny = ny + DIR[j][1];\n                if (nnx >= 0 && nnx < N && nny >= 0 && nny < N) {\n                    for (const Pet& pet : pets) {\n                        if (pet.x == nnx && pet.y == nny) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                }\n            }\n            if (valid) {\n                return DIR_CHAR[i];\n            }\n        }\n    }\n\n    return '.';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    cin >> N;\n    pets.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n        --pets[i].x;\n        --pets[i].y;\n    }\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].x >> humans[i].y;\n        --humans[i].x;\n        --humans[i].y;\n    }\n    for (int turn = 0; turn < 300; ++turn) {\n        string actions;\n        for (int h = 0; h < M; ++h) {\n            actions += getAction(h);\n        }\n        cout << actions << endl;\n        cout.flush();\n        // Read pet movements\n        for (int i = 0; i < N; ++i) {\n            string movement;\n            cin >> movement;\n            // Update pet positions\n            if (movement != \".\") {\n                for (char c : movement) {\n                    int dx = 0, dy = 0;\n                    if (c == 'U') dx = -1;\n                    if (c == 'D') dx = 1;\n                    if (c == 'L') dy = -1;\n                    if (c == 'R') dy = 1;\n                    pets[i].x += dx;\n                    pets[i].y += dy;\n                }\n            }\n        }\n        // Update human positions\n        for (int h = 0; h < M; ++h) {\n            char action = actions[h];\n            if (action == 'U') --humans[h].x;\n            if (action == 'D') ++humans[h].x;\n            if (action == 'L') --humans[h].y;\n            if (action == 'R') ++humans[h].y;\n        }\n    }\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    int sx, sy, tx, ty;\n    double p;\n    cin >> sx >> sy >> tx >> ty >> p;\n\n    vector<string> h(20), v(20);\n    for (int i = 0; i < 20; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < 19; ++i) {\n        cin >> v[i];\n    }\n\n    // BFS to find a initial path\n    queue<Pos> q;\n    vector<vector<bool>> visited(20, vector<bool>(20, false));\n    q.push({sx, sy});\n    visited[sx][sy] = true;\n    vector<vector<Pos>> parent(20, vector<Pos>(20, {-1, -1}));\n    while (!q.empty()) {\n        Pos curr = q.front(); q.pop();\n        if (curr.x == tx && curr.y == ty) break;\n        // Explore neighbors\n        for (auto dir : {make_pair(0, 1), make_pair(0, -1), make_pair(1, 0), make_pair(-1, 0)}) {\n            int nx = curr.x + dir.first, ny = curr.y + dir.second;\n            if (nx >= 0 && nx < 20 && ny >= 0 && ny < 20 && !visited[nx][ny]) {\n                if (dir.first == 0 && dir.second == 1 && ny < 20 && h[curr.x][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == 0 && dir.second == -1 && ny >= 0 && h[curr.x][ny] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == 1 && dir.second == 0 && nx < 20 && v[curr.x][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == -1 && dir.second == 0 && nx >= 0 && v[nx][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                }\n            }\n        }\n    }\n\n    // Reconstruct path\n    string path;\n    Pos curr = {tx, ty};\n    while (curr.x != sx || curr.y != sy) {\n        Pos prev = parent[curr.x][curr.y];\n        if (prev.x == curr.x - 1) path += 'D';\n        else if (prev.x == curr.x + 1) path += 'U';\n        else if (prev.y == curr.y - 1) path += 'R';\n        else if (prev.y == curr.y + 1) path += 'L';\n        curr = prev;\n    }\n    reverse(path.begin(), path.end());\n\n    // Ensure path only contains valid characters and is within length limits\n    string robustPath = path;\n    while (robustPath.size() <= 200) {\n        robustPath += path;\n    }\n    robustPath.resize(200);\n\n    // Validate and output\n    for (char c : robustPath) {\n        if (c != 'U' && c != 'D' && c != 'L' && c != 'R') {\n            cerr << \"Invalid character in path: \" << c << endl;\n            return 1; // Exit with error if invalid character found\n        }\n    }\n\n    cout << robustPath << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <random>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 30;\nconst int T = 100000;\n\nint tiles[N][N];\nint rotations[N][N];\nint 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};\nint di[4] = {0, -1, 0, 1};\nint dj[4] = {-1, 0, 1, 0};\n\nint traverse_loop(int i, int j, int d) {\n    int length = 0;\n    int si = i, sj = j, sd = d;\n    while (true) {\n        int t = tiles[i][j];\n        for (int k = 0; k < rotations[i][j]; k++) {\n            if (t >= 0 && t <= 3) t = (t + 1) % 4;\n            else if (t == 4 || t == 5) t = 4 + (t - 4 + 1) % 2;\n            else if (t == 6 || t == 7) t = 6 + (t - 6 + 1) % 2;\n        }\n        int d2 = to[t][d];\n        if (d2 == -1) return 0;\n        i += di[d2];\n        j += dj[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (i == si && j == sj && d == sd) return length;\n    }\n}\n\nint calculate_score() {\n    vector<int> loop_lengths;\n    bool visited[N][N] = {};\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (!visited[i][j]) {\n                for (int d = 0; d < 4; d++) {\n                    int length = traverse_loop(i, j, d);\n                    if (length > 0) {\n                        loop_lengths.push_back(length);\n                        int ti = i, tj = j, td = d;\n                        while (true) {\n                            visited[ti][tj] = true;\n                            int t = tiles[ti][tj];\n                            for (int k = 0; k < rotations[ti][tj]; k++) {\n                                if (t >= 0 && t <= 3) t = (t + 1) % 4;\n                                else if (t == 4 || t == 5) t = 4 + (t - 4 + 1) % 2;\n                                else if (t == 6 || t == 7) t = 6 + (t - 6 + 1) % 2;\n                            }\n                            int td2 = to[t][td];\n                            ti += di[td2];\n                            tj += dj[td2];\n                            td = (td2 + 2) % 4;\n                            if (ti == i && tj == j && td == d) break;\n                        }\n                        break;\n                    }\n                }\n            }\n        }\n    }\n    sort(loop_lengths.rbegin(), loop_lengths.rend());\n    if (loop_lengths.size() <= 1) return 0;\n    return loop_lengths[0] * loop_lengths[1];\n}\n\nvoid simulated_annealing() {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n    uniform_int_distribution<> rot_dis(0, 3);\n\n    double temperature = 1000;\n    int current_score = calculate_score();\n    while (temperature > 1) {\n        int i = dis(gen);\n        int j = dis(gen);\n        int original_rotation = rotations[i][j];\n        int new_rotation = (original_rotation + 1) % 4;\n        rotations[i][j] = new_rotation;\n        int new_score = calculate_score();\n        if (new_score > current_score) {\n            current_score = new_score;\n        } else {\n            if (exp((double)(new_score - current_score) / temperature) > (double)rand() / RAND_MAX) {\n                current_score = new_score;\n            } else {\n                rotations[i][j] = original_rotation;\n            }\n        }\n        temperature *= 0.99;\n    }\n}\n\nint main() {\n    for (int i = 0; i < N; i++) {\n        string line;\n        cin >> line;\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = line[j] - '0';\n        }\n    }\n\n    simulated_annealing();\n\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cout << rotations[i][j];\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Puzzle {\n    int N;\n    vector<vector<int>> tiles;\n    pair<int, int> empty;\n\n    Puzzle(int N) : N(N), tiles(N, vector<int>(N)) {}\n\n    bool isValidMove(char dir) {\n        int dx = 0, dy = 0;\n        if (dir == 'U') dx = -1;\n        if (dir == 'D') dx = 1;\n        if (dir == 'L') dy = -1;\n        if (dir == 'R') dy = 1;\n\n        int x = empty.first, y = empty.second;\n        int nx = x + dx, ny = y + dy;\n\n        return nx >= 0 && nx < N && ny >= 0 && ny < N;\n    }\n\n    void move(char dir) {\n        int dx = 0, dy = 0;\n        if (dir == 'U') dx = -1;\n        if (dir == 'D') dx = 1;\n        if (dir == 'L') dy = -1;\n        if (dir == 'R') dy = 1;\n\n        int x = empty.first, y = empty.second;\n        int nx = x + dx, ny = y + dy;\n\n        swap(tiles[x][y], tiles[nx][ny]);\n        empty = {nx, ny};\n    }\n\n    int evaluate() {\n        int score = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (tiles[i][j] != 0) {\n                    score += 1;\n                }\n            }\n        }\n        return score;\n    }\n};\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n\n    Puzzle puzzle(N);\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            int val = stoi(row.substr(j, 1), 0, 16);\n            puzzle.tiles[i][j] = val;\n            if (val == 0) {\n                puzzle.empty = {i, j};\n            }\n        }\n    }\n\n    string operations;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    double temperature = 1000.0;\n    double coolingRate = 0.99;\n    int maxAttempts = 100;\n\n    for (int i = 0; i < T; ++i) {\n        char dirs[] = {'U', 'D', 'L', 'R'};\n        char dir;\n        int attempts = 0;\n        do {\n            dir = dirs[dis(gen) % 4];\n            attempts++;\n        } while (!puzzle.isValidMove(dir) && attempts < maxAttempts);\n\n        if (puzzle.isValidMove(dir)) {\n            Puzzle newState = puzzle;\n            newState.move(dir);\n            int newScore = newState.evaluate();\n            int currentScore = puzzle.evaluate();\n\n            if (newScore > currentScore || exp((double)(newScore - currentScore) / temperature) > (double)rand() / RAND_MAX) {\n                puzzle = newState;\n                operations += dir;\n            }\n        }\n\n        temperature *= coolingRate;\n    }\n\n    cout << operations << endl;\n\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    long long x, y;\n};\n\nlong long cross(const Point& p1, const Point& p2) {\n    return p1.x * p2.y - p1.y * p2.x;\n}\n\nint main() {\n    int N, K;\n    cin >> N >> K;\n    vector<int> a(10);\n    for (int i = 0; i < 10; ++i) {\n        cin >> a[i];\n    }\n    vector<Point> strawberries(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> strawberries[i].x >> strawberries[i].y;\n    }\n\n    vector<pair<Point, Point>> cuts;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int i = 0; i < K; ++i) {\n        int best_idx1 = -1, best_idx2 = -1;\n        double best_score = -1.0;\n\n        for (int j = 0; j < 100; ++j) {\n            int idx1 = dis(gen);\n            int idx2 = dis(gen);\n            while (idx2 == idx1) {\n                idx2 = dis(gen);\n            }\n\n            // Calculate the score for the current cut\n            double score = 0.0;\n            // TO DO: implement the score calculation\n\n            if (score > best_score) {\n                best_score = score;\n                best_idx1 = idx1;\n                best_idx2 = idx2;\n            }\n        }\n\n        if (best_idx1 != -1 && best_idx2 != -1) {\n            Point p1 = strawberries[best_idx1];\n            Point p2 = strawberries[best_idx2];\n            cuts.emplace_back(p1, p2);\n        }\n    }\n\n    cout << cuts.size() << endl;\n    for (const auto& cut : cuts) {\n        cout << cut.first.x << \" \" << cut.first.y << \" \" << cut.second.x << \" \" << cut.second.y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <random>\n#include <tuple>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nint N, M;\nvector<Point> dots;\nset<pair<int, int>> dot_set;\nvector<tuple<int, int, int, int, int, int, int, int>> operations;\n\nbool is_valid_rectangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (x1 == x2 || x1 == x3 || x1 == x4 || y1 == y2 || y1 == y3 || y1 == y4) {\n        return false;\n    }\n    if ((x1 == x3 && y1 == y4 && x2 == x4 && y2 == y3) && (abs(x1 - x2) == abs(y1 - y2))) {\n        if (dot_set.find({x1, y2}) != dot_set.end() && dot_set.find({x2, y1}) != dot_set.end() && dot_set.find({x3, y4}) != dot_set.end() && dot_set.find({x4, y3}) != dot_set.end()) {\n            // Check if there are no dots other than the four points on the perimeter\n            int min_x = min(x1, min(x2, min(x3, x4)));\n            int max_x = max(x1, max(x2, max(x3, x4)));\n            int min_y = min(y1, min(y2, min(y3, y4)));\n            int max_y = max(y1, max(y2, max(y3, y4)));\n            for (int i = min_x; i <= max_x; i++) {\n                for (int j = min_y; j <= max_y; j++) {\n                    if (dot_set.find({i, j}) != dot_set.end() && make_pair(i, j) != make_pair(x1, y1) && make_pair(i, j) != make_pair(x2, y2) && make_pair(i, j) != make_pair(x3, y3) && make_pair(i, j) != make_pair(x4, y4)) {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    cin >> N >> M;\n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        dots.push_back({x, y});\n        dot_set.insert({x, y});\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    int iter_count = 0;\n    while (iter_count < 100000 && (double)clock() / CLOCKS_PER_SEC < 4.5) {\n        int x1 = dis(gen);\n        int y1 = dis(gen);\n        if (dot_set.find({x1, y1}) != dot_set.end()) {\n            iter_count++;\n            continue;\n        }\n        for (int i = 0; i < dots.size(); i++) {\n            for (int j = i + 1; j < dots.size(); j++) {\n                int x2 = dots[i].x;\n                int y2 = dots[i].y;\n                int x3 = dots[j].x;\n                int y3 = dots[j].y;\n                int x4 = x1 + x3 - x2;\n                int y4 = y1 + y3 - y2;\n                if (x4 >= 0 && x4 < N && y4 >= 0 && y4 < N && dot_set.find({x4, y4}) != dot_set.end() && dot_set.find({x2, y3}) == dot_set.end() && dot_set.find({x3, y2}) == dot_set.end()) {\n                    if (is_valid_rectangle(x1, y1, x2, y2, x3, y3, x4, y4)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.emplace_back(x1, y1, x2, y2, x3, y3, x4, y4);\n                        iter_count = 0;\n                        break;\n                    }\n                }\n                x4 = x1 + x2 - x3;\n                y4 = y1 + y2 - y3;\n                if (x4 >= 0 && x4 < N && y4 >= 0 && y4 < N && dot_set.find({x4, y4}) != dot_set.end() && dot_set.find({x2, y3}) == dot_set.end() && dot_set.find({x3, y2}) == dot_set.end()) {\n                    if (is_valid_rectangle(x1, y1, x2, y2, x4, y4, x3, y3)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.emplace_back(x1, y1, x2, y2, x4, y4, x3, y3);\n                        iter_count = 0;\n                        break;\n                    }\n                }\n            }\n            if (iter_count == 0) {\n                break;\n            }\n        }\n        iter_count++;\n    }\n\n    cout << operations.size() << endl;\n    for (auto& op : operations) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << \" \" << get<4>(op) << \" \" << get<5>(op) << \" \" << get<6>(op) << \" \" << get<7>(op) << endl;\n    }\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nconst int N = 10;\nconst int flavors = 3;\n\nstruct CandyBox {\n    int grid[N][N];\n    int count[flavors + 1];\n\n    CandyBox() {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                grid[i][j] = 0;\n            }\n        }\n        for (int i = 1; i <= flavors; i++) {\n            count[i] = 0;\n        }\n    }\n\n    void placeCandy(int flavor, int pos) {\n        int emptyCount = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (grid[i][j] == 0) {\n                    emptyCount++;\n                    if (emptyCount == pos) {\n                        grid[i][j] = flavor;\n                        count[flavor]++;\n                        return;\n                    }\n                }\n            }\n        }\n    }\n\n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; j++) {\n                int writePos = 0;\n                for (int i = 0; i < N; i++) {\n                    if (grid[i][j] != 0) {\n                        grid[writePos++][j] = grid[i][j];\n                    }\n                }\n                for (int i = writePos; i < N; i++) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; j++) {\n                int writePos = N - 1;\n                for (int i = N - 1; i >= 0; i--) {\n                    if (grid[i][j] != 0) {\n                        grid[writePos--][j] = grid[i][j];\n                    }\n                }\n                for (int i = writePos; i >= 0; i--) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; i++) {\n                int writePos = 0;\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] != 0) {\n                        grid[i][writePos++] = grid[i][j];\n                    }\n                }\n                for (int j = writePos; j < N; j++) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'R') {\n            for (int i = 0; i < N; i++) {\n                int writePos = N - 1;\n                for (int j = N - 1; j >= 0; j--) {\n                    if (grid[i][j] != 0) {\n                        grid[i][writePos--] = grid[i][j];\n                    }\n                }\n                for (int j = writePos; j >= 0; j--) {\n                    grid[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    int evaluateScore() {\n        int score = 0;\n        for (int flavor = 1; flavor <= flavors; flavor++) {\n            vector<vector<bool>> visited(N, vector<bool>(N, false));\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] == flavor && !visited[i][j]) {\n                        int componentSize = 0;\n                        vector<pair<int, int>> stack = {{i, j}};\n                        visited[i][j] = true;\n                        while (!stack.empty()) {\n                            auto [x, y] = stack.back();\n                            stack.pop_back();\n                            componentSize++;\n                            for (auto [dx, dy] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                                int nx = x + dx;\n                                int ny = y + dy;\n                                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == flavor && !visited[nx][ny]) {\n                                    stack.emplace_back(nx, ny);\n                                    visited[nx][ny] = true;\n                                }\n                            }\n                        }\n                        score += componentSize * componentSize;\n                    }\n                }\n            }\n        }\n        int denominator = 0;\n        for (int i = 1; i <= flavors; i++) {\n            denominator += count[i] * count[i];\n        }\n        return denominator == 0 ? 0 : score / denominator;\n    }\n\n    int evaluateScoreWithClustering() {\n        int score = 0;\n        for (int flavor = 1; flavor <= flavors; flavor++) {\n            vector<vector<bool>> visited(N, vector<bool>(N, false));\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] == flavor && !visited[i][j]) {\n                        int componentSize = 0;\n                        vector<pair<int, int>> stack = {{i, j}};\n                        visited[i][j] = true;\n                        while (!stack.empty()) {\n                            auto [x, y] = stack.back();\n                            stack.pop_back();\n                            componentSize++;\n                            for (auto [dx, dy] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                                int nx = x + dx;\n                                int ny = y + dy;\n                                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == flavor && !visited[nx][ny]) {\n                                    stack.emplace_back(nx, ny);\n                                    visited[nx][ny] = true;\n                                }\n                            }\n                        }\n                        score += componentSize * componentSize;\n                        // clustering bonus\n                        if (componentSize > 1) {\n                            score += componentSize;\n                        }\n                    }\n                }\n            }\n        }\n        int denominator = 0;\n        for (int i = 1; i <= flavors; i++) {\n            denominator += count[i] * count[i];\n        }\n        return denominator == 0 ? 0 : score / denominator;\n    }\n};\n\nint main() {\n    vector<int> flavors(100);\n    for (int i = 0; i < 100; i++) {\n        cin >> flavors[i];\n    }\n\n    CandyBox box;\n    for (int t = 0; t < 100; t++) {\n        int pos;\n        cin >> pos;\n        box.placeCandy(flavors[t], pos);\n\n        if (t == 99) break; // no need to output for the last tilt\n\n        char bestDir = 'F';\n        int bestScore = -1;\n        for (char dir : {'F', 'B', 'L', 'R'}) {\n            CandyBox simBox = box;\n            simBox.tilt(dir);\n            int score = simBox.evaluateScoreWithClustering();\n            if (score > bestScore) {\n                bestScore = score;\n                bestDir = dir;\n            }\n        }\n        cout << bestDir << endl;\n        box.tilt(bestDir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nint M;\ndouble eps;\nint N = 20;\n\nstring generateGk(int k) {\n    string gk(N * (N - 1) / 2, '0');\n    int count = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            int index = i * (N - 1) - i * (i + 1) / 2 + j - i - 1;\n            if (count < k) {\n                gk[index] = '1';\n                count++;\n            }\n        }\n    }\n    return gk;\n}\n\nint predictSk(const string& Hk, const vector<string>& G) {\n    int bestMatch = 0;\n    int minDistance = numeric_limits<int>::max();\n    for (int i = 0; i < M; ++i) {\n        int distance = 0;\n        for (int j = 0; j < N * (N - 1) / 2; ++j) {\n            distance += (Hk[j] != G[i][j]);\n        }\n        if (distance < minDistance) {\n            minDistance = distance;\n            bestMatch = i;\n        }\n    }\n    return bestMatch;\n}\n\nint main() {\n    cin >> M >> eps;\n    cout << N << endl;\n    vector<string> G(M);\n    for (int k = 0; k < M; ++k) {\n        G[k] = generateGk(k);\n        cout << G[k] << endl;\n    }\n    cout.flush();\n\n    for (int query = 0; query < 100; ++query) {\n        string Hk;\n        cin >> Hk;\n        int tk = predictSk(Hk, G);\n        cout << tk << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n#include <limits>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v, w, id;\n};\n\nint main() {\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    vector<Edge> edges(M);\n    vector<vector<pair<int, int>>> graph(N);\n\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u; --v;\n        edges[i] = {u, v, w, i};\n        graph[u].emplace_back(v, w);\n        graph[v].emplace_back(u, w);\n    }\n\n    // Read and ignore vertex coordinates\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // Initialize repair schedule randomly\n    vector<int> repairDay(M);\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(1, D);\n    for (auto& day : repairDay) {\n        day = dis(gen);\n    }\n\n    // Function to calculate frustration level for a given day\n    auto calculateFrustration = [&](const vector<int>& edgesForDay) {\n        // Create a temporary graph with edges for the day removed\n        vector<vector<pair<int, int>>> tempGraph = graph;\n        for (int edgeId : edgesForDay) {\n            Edge e = edges[edgeId];\n            // Remove edge e from tempGraph\n            tempGraph[e.u].erase(remove_if(tempGraph[e.u].begin(), tempGraph[e.u].end(), [&](const pair<int, int>& p){ return p.first == e.v; }), tempGraph[e.u].end());\n            tempGraph[e.v].erase(remove_if(tempGraph[e.v].begin(), tempGraph[e.v].end(), [&](const pair<int, int>& p){ return p.first == e.u; }), tempGraph[e.v].end());\n        }\n\n        // Calculate shortest paths using Dijkstra's algorithm\n        vector<vector<int>> dist(N, vector<int>(N, numeric_limits<int>::max()));\n        for (int i = 0; i < N; ++i) {\n            dist[i][i] = 0;\n            priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;\n            pq.emplace(0, i);\n            while (!pq.empty()) {\n                int d = pq.top().first, u = pq.top().second;\n                pq.pop();\n                if (d > dist[i][u]) continue;\n                for (const auto& e : tempGraph[u]) {\n                    if (dist[i][e.first] > d + e.second) {\n                        dist[i][e.first] = d + e.second;\n                        pq.emplace(dist[i][e.first], e.first);\n                    }\n                }\n            }\n        }\n\n        // Calculate frustration level\n        int frustration = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                if (dist[i][j] == numeric_limits<int>::max()) dist[i][j] = 1e9;\n                frustration += dist[i][j] - /* original shortest distance */;\n            }\n        }\n        return frustration;\n    };\n\n    // Main loop to improve the schedule\n    for (int iter = 0; iter < 10000; ++iter) {\n        // Select an edge and a new day for it\n        int edgeId = rand() % M;\n        int newDay = rand() % D + 1;\n        int oldDay = repairDay[edgeId];\n\n        // Check if moving the edge to the new day is valid and improves the schedule\n        vector<int>& oldDayEdges = /* get edges for oldDay */;\n        vector<int>& newDayEdges = /* get edges for newDay */;\n        if (newDayEdges.size() < K) {\n            // Temporarily move the edge\n            oldDayEdges.erase(remove(oldDayEdges.begin(), oldDayEdges.end(), edgeId), oldDayEdges.end());\n            newDayEdges.push_back(edgeId);\n\n            // Calculate new frustration levels\n            int oldFrustration = calculateFrustration(oldDayEdges) + calculateFrustration(newDayEdges);\n            int newFrustration = /* calculate frustration for oldDay without edgeId */ + /* calculate frustration for newDay with edgeId */;\n\n            if (newFrustration < oldFrustration) {\n                // Accept the move\n                repairDay[edgeId] = newDay;\n            } else {\n                // Revert the move\n                newDayEdges.pop_back();\n                oldDayEdges.push_back(edgeId);\n            }\n        }\n    }\n\n    // Output the final repair schedule\n    for (int i = 0; i < M; ++i) {\n        cout << repairDay[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <bitset>\n\nconst int MAX_D = 14;\nint D;\nstd::bitset<MAX_D> f[2][MAX_D][MAX_D];\nstd::bitset<MAX_D> r[2][MAX_D][MAX_D];\nint b[2][MAX_D * MAX_D * MAX_D];\n\nvoid input() {\n    std::cin >> D;\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            std::string s;\n            std::cin >> s;\n            for (int x = 0; x < D; ++x) {\n                f[i][z][x][x] = (s[x] == '1');\n            }\n        }\n        for (int z = 0; z < D; ++z) {\n            std::string s;\n            std::cin >> s;\n            for (int y = 0; y < D; ++y) {\n                r[i][z][y][y] = (s[y] == '1');\n            }\n        }\n    }\n}\n\nvoid solve() {\n    int n = 0;\n    for (int i = 0; i < 2; ++i) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[i][z][x][y] && r[i][z][y][x]) {\n                        b[i][x * D * D + y * D + z] = ++n;\n                    }\n                }\n            }\n        }\n    }\n\n    std::cout << n << std::endl;\n    for (int i = 0; i < D * D * D; ++i) {\n        std::cout << b[0][i] << \" \";\n    }\n    std::cout << std::endl;\n    for (int i = 0; i < D * D * D; ++i) {\n        std::cout << b[1][i] << \" \";\n    }\n    std::cout << std::endl;\n}\n\nint main() {\n    input();\n    solve();\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n    long long w;\n};\n\nstruct UnionFind {\n    vector<int> parent, rank;\n    UnionFind(int n) : parent(n, -1), rank(n, 0) {}\n    int find(int x) {\n        if (parent[x] == -1) return x;\n        return parent[x] = find(parent[x]);\n    }\n    void unionSet(int x, int y) {\n        int rootX = find(x), rootY = find(y);\n        if (rootX != rootY) {\n            if (rank[rootX] > rank[rootY]) {\n                parent[rootY] = rootX;\n            } else {\n                parent[rootX] = rootY;\n                if (rank[rootX] == rank[rootY]) rank[rootY]++;\n            }\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<pair<int, int>> vertices(N);\n    for (auto& [x, y] : vertices) {\n        cin >> x >> y;\n    }\n\n    vector<Edge> edges(M);\n    for (auto& [u, v, w] : edges) {\n        cin >> u >> v >> w;\n        u--; v--;\n    }\n\n    vector<pair<int, int>> residents(K);\n    for (auto& [a, b] : residents) {\n        cin >> a >> b;\n    }\n\n    // Minimum Spanning Tree\n    vector<bool> in_mst(M, false);\n    UnionFind uf(N);\n    {\n        sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        for (auto& e : edges) {\n            if (uf.find(e.u) != uf.find(e.v)) {\n                uf.unionSet(e.u, e.v);\n                in_mst[&e - &edges[0]] = true;\n            }\n        }\n    }\n\n    // Resident Coverage\n    vector<int> output_strength(N, 0);\n    for (auto [a, b] : residents) {\n        int nearest_vertex = 0;\n        long long min_distance = (long long)1e18;\n        for (int i = 0; i < N; i++) {\n            auto [x, y] = vertices[i];\n            long long distance = (long long)(x - a) * (x - a) + (long long)(y - b) * (y - b);\n            if (distance < min_distance) {\n                min_distance = distance;\n                nearest_vertex = i;\n            }\n        }\n        output_strength[nearest_vertex] = max(output_strength[nearest_vertex], (int)ceil(sqrt(min_distance)) + 1);\n    }\n\n    // Graph Traversal\n    vector<bool> visited(N, false);\n    {\n        queue<int> q;\n        q.push(0);\n        visited[0] = true;\n        while (!q.empty()) {\n            int u = q.front(); q.pop();\n            for (int i = 0; i < M; i++) {\n                if (in_mst[i]) {\n                    auto& e = edges[i];\n                    if (e.u == u && !visited[e.v]) {\n                        visited[e.v] = true;\n                        output_strength[e.v] = max(output_strength[e.v], output_strength[u]);\n                        q.push(e.v);\n                    }\n                    if (e.v == u && !visited[e.u]) {\n                        visited[e.u] = true;\n                        output_strength[e.u] = max(output_strength[e.u], output_strength[u]);\n                        q.push(e.u);\n                    }\n                }\n            }\n        }\n    }\n\n    // Output\n    for (int p : output_strength) {\n        cout << p << \" \";\n    }\n    cout << \"\\n\";\n    for (auto& e : edges) {\n        cout << (in_mst[&e - &edges[0]] ? \"1\" : \"0\") << \" \";\n    }\n    cout << \"\\n\";\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n#include <tuple> // Include the necessary header for std::tuple\n\nusing namespace std;\n\nconst int N = 30;\nconst int dx[] = {-1, -1, 0, 0, 1, 1};\nconst int dy[] = {-1, 0, -1, 1, 0, 1};\n\nint main() {\n    vector<vector<int>> pyramid(N);\n    for (int i = 0; i < N; ++i) {\n        pyramid[i].resize(i + 1);\n        for (int j = 0; j <= i; ++j) {\n            cin >> pyramid[i][j];\n        }\n    }\n\n    vector<tuple<int, int, int, int>> operations;\n    for (int i = N - 1; i > 0; --i) {\n        for (int j = 0; j <= i; ++j) {\n            int x = i, y = j;\n            while (x > 0) {\n                int parent_x = x - 1;\n                int parent_y = y;\n                if (y > parent_x) {\n                    parent_y = y - 1;\n                }\n                if (pyramid[x][y] < pyramid[parent_x][parent_y]) {\n                    swap(pyramid[x][y], pyramid[parent_x][parent_y]);\n                    operations.emplace_back(x, y, parent_x, parent_y);\n                }\n                x = parent_x;\n                y = parent_y;\n            }\n        }\n    }\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << endl;\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n\nusing namespace std;\n\nconst int D = 9;\nconst int directions[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nstruct Position {\n    int x, y;\n};\n\nint main() {\n    int N;\n    cin >> D >> N;\n\n    vector<vector<int>> grid(D, vector<int>(D, 0));\n    grid[0][(D - 1) / 2] = -1; // Entrance\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        grid[x][y] = -2; // Obstacle\n    }\n\n    vector<Position> containers;\n    unordered_set<int> containerSet;\n\n    for (int d = 0; d < D * D - 1 - N; ++d) {\n        int t;\n        cin >> t;\n\n        // Find a suitable position for the container using BFS\n        queue<Position> q;\n        vector<vector<bool>> visited(D, vector<bool>(D, false));\n        q.push({0, (D - 1) / 2});\n        visited[0][(D - 1) / 2] = true;\n\n        Position target;\n        bool found = false;\n\n        while (!q.empty()) {\n            Position p = q.front();\n            q.pop();\n\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + directions[i][0];\n                int ny = p.y + directions[i][1];\n\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !visited[nx][ny] && grid[nx][ny] == 0) {\n                    visited[nx][ny] = true;\n                    q.push({nx, ny});\n\n                    // Choose the last visited node as the target position\n                    target = {nx, ny};\n                    found = true;\n                }\n            }\n        }\n\n        if (found) {\n            grid[target.x][target.y] = t;\n            containers.push_back(target);\n            containerSet.insert(target.x * D + target.y);\n            cout << target.x << \" \" << target.y << endl;\n            cout.flush();\n        }\n    }\n\n    // Transport containers out\n    for (int i = 0; i < D * D - 1 - N; ++i) {\n        queue<Position> q;\n        vector<vector<bool>> visited(D, vector<bool>(D, false));\n        q.push({0, (D - 1) / 2});\n        visited[0][(D - 1) / 2] = true;\n\n        Position target;\n        int minNum = D * D;\n\n        while (!q.empty()) {\n            Position p = q.front();\n            q.pop();\n\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + directions[i][0];\n                int ny = p.y + directions[i][1];\n\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !visited[nx][ny]) {\n                    if (grid[nx][ny] >= 0 && grid[nx][ny] < minNum) {\n                        minNum = grid[nx][ny];\n                        target = {nx, ny};\n                    }\n\n                    visited[nx][ny] = true;\n                    q.push({nx, ny});\n                }\n            }\n        }\n\n        if (minNum != D * D) {\n            cout << target.x << \" \" << target.y << endl;\n            grid[target.x][target.y] = 0;\n        }\n    }\n\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm> // Include the algorithm header\n\nusing namespace std;\n\nconst int N = 50;\nconst int M = 100;\n\nint grid[N][N];\nint output[N][N];\nunordered_map<int, pair<int, int>> seeds;\nunordered_set<int> adjacentColors[M + 1];\n\nvoid readInput() {\n    int n, m;\n    cin >> n >> m;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> grid[i][j];\n            if (seeds.find(grid[i][j]) == seeds.end()) {\n                seeds[grid[i][j]] = {i, j};\n            }\n            output[i][j] = 0; // Initialize output grid\n        }\n    }\n}\n\nvoid buildAdjacencyGraph() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int color = grid[i][j];\n            if (i > 0 && grid[i - 1][j] != color) {\n                adjacentColors[color].insert(grid[i - 1][j]);\n            }\n            if (j > 0 && grid[i][j - 1] != color) {\n                adjacentColors[color].insert(grid[i][j - 1]);\n            }\n            if (i < N - 1 && grid[i + 1][j] != color) {\n                adjacentColors[color].insert(grid[i + 1][j]);\n            }\n            if (j < N - 1 && grid[i][j + 1] != color) {\n                adjacentColors[color].insert(grid[i][j + 1]);\n            }\n        }\n    }\n}\n\nvoid processColors() {\n    vector<int> colors;\n    for (int i = 1; i <= M; i++) {\n        colors.push_back(i);\n    }\n    sort(colors.begin(), colors.end(), [&adjColors = adjacentColors](int a, int b) {\n        return adjColors[a].size() > adjColors[b].size();\n    });\n\n    for (int color : colors) {\n        int x = seeds[color].first;\n        int y = seeds[color].second;\n        output[x][y] = color;\n        queue<pair<int, int>> q;\n        q.push({x, y});\n        while (!q.empty()) {\n            x = q.front().first;\n            y = q.front().second;\n            q.pop();\n            if (x > 0 && grid[x - 1][y] == color && output[x - 1][y] == 0) {\n                output[x - 1][y] = color;\n                q.push({x - 1, y});\n            }\n            if (y > 0 && grid[x][y - 1] == color && output[x][y - 1] == 0) {\n                output[x][y - 1] = color;\n                q.push({x, y - 1});\n            }\n            if (x < N - 1 && grid[x + 1][y] == color && output[x + 1][y] == 0) {\n                output[x + 1][y] = color;\n                q.push({x + 1, y});\n            }\n            if (y < N - 1 && grid[x][y + 1] == color && output[x][y + 1] == 0) {\n                output[x][y + 1] = color;\n                q.push({x, y + 1});\n            }\n        }\n    }\n}\n\nvoid outputResult() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cout << output[i][j] << \" \";\n        }\n        cout << endl;\n    }\n}\n\nint main() {\n    readInput();\n    buildAdjacencyGraph();\n    processColors();\n    outputResult();\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n\nint main() {\n    int N, D, Q;\n    std::cin >> N >> D >> Q;\n\n    // Initialize random number generator\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> dis(0, N - 1);\n\n    // Estimate weights using a more sophisticated comparison strategy\n    std::vector<double> weights(N, 0.0);\n    for (int q = 0; q < Q; ++q) {\n        // Generate comparison subsets using a binary search-like approach\n        int i = dis(gen) % N;\n        int j = dis(gen) % N;\n        while (j == i) {\n            j = dis(gen) % N;\n        }\n\n        std::cout << \"1 1 \" << i << \" \" << j << std::endl;\n        char result;\n        std::cin >> result;\n\n        if (result == '<') {\n            weights[i] -= 1.0;\n            weights[j] += 1.0;\n        } else if (result == '>') {\n            weights[i] += 1.0;\n            weights[j] -= 1.0;\n        }\n    }\n\n    // Cluster or partition items into D subsets using a more advanced algorithm\n    std::vector<int> division(N);\n    std::vector<std::pair<double, int>> sorted_weights(N);\n    for (int i = 0; i < N; ++i) {\n        sorted_weights[i] = std::make_pair(weights[i], i);\n    }\n    std::sort(sorted_weights.begin(), sorted_weights.end());\n\n    int subset = 0;\n    for (int i = 0; i < N; ++i) {\n        division[sorted_weights[i].second] = subset;\n        subset = (subset + 1) % D;\n    }\n\n    // Output division\n    for (int i = 0; i < N; ++i) {\n        std::cout << division[i] << \" \";\n    }\n    std::cout << std::endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int n = 200;\nconst int m = 10;\n\nvector<int> stacks[m];\nbool carried_out[n + 1];\nvector<pair<int, int>> operations;\n\nvoid move_box(int v, int dest_stack) {\n    for (int i = 0; i < m; ++i) {\n        auto& stack = stacks[i];\n        if (find(stack.begin(), stack.end(), v) != stack.end()) {\n            int idx = distance(stack.begin(), find(stack.begin(), stack.end(), v));\n            int energy = stack.size() - idx;\n            operations.emplace_back(v, dest_stack + 1);\n            vector<int> temp(stack.begin() + idx, stack.end());\n            stack.erase(stack.begin() + idx, stack.end());\n            stacks[dest_stack].insert(stacks[dest_stack].end(), temp.begin(), temp.end());\n            return;\n        }\n    }\n}\n\nint main() {\n    int b[m][n / m];\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < n / m; ++j) {\n            cin >> b[i][j];\n            stacks[i].push_back(b[i][j]);\n        }\n    }\n\n    for (int v = 1; v <= n; ++v) {\n        int top_stack = -1;\n        for (int i = 0; i < m; ++i) {\n            if (!stacks[i].empty() && stacks[i].back() == v) {\n                top_stack = i;\n                break;\n            }\n        }\n\n        if (top_stack != -1) {\n            operations.emplace_back(v, 0);\n            carried_out[v] = true;\n            stacks[top_stack].pop_back();\n        } else {\n            // Find the stack containing v and move it to an appropriate stack\n            int src_stack = -1;\n            for (int i = 0; i < m; ++i) {\n                auto& stack = stacks[i];\n                auto it = find(stack.begin(), stack.end(), v);\n                if (it != stack.end()) {\n                    src_stack = i;\n                    break;\n                }\n            }\n\n            if (src_stack == -1) {\n                cerr << \"Box \" << v << \" not found.\" << endl;\n                return 1;\n            }\n\n            int dest_stack = -1;\n            int min_top = n + 1;\n            for (int i = 0; i < m; ++i) {\n                if (stacks[i].empty() || (stacks[i].back() > v && stacks[i].back() < min_top)) {\n                    dest_stack = i;\n                    min_top = stacks[i].empty() ? n + 1 : stacks[i].back();\n                }\n            }\n\n            if (dest_stack == -1) {\n                // If no suitable stack is found, just pick any non-empty stack\n                for (int i = 0; i < m; ++i) {\n                    if (!stacks[i].empty()) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n\n            move_box(v, dest_stack);\n            // After moving, check again if v is at the top\n            for (int i = 0; i < m; ++i) {\n                if (!stacks[i].empty() && stacks[i].back() == v) {\n                    operations.emplace_back(v, 0);\n                    carried_out[v] = true;\n                    stacks[i].pop_back();\n                    break;\n                }\n            }\n        }\n    }\n\n    for (const 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>\n#include <stack>\n#include <random>\n\nusing namespace std;\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<bool>> visited;\n\nvoid dfs(int i, int j, vector<char>& route) {\n    visited[i][j] = true;\n    int di[] = {0, 1, 0, -1};\n    int dj[] = {1, 0, -1, 0};\n    char dir[] = {'R', 'D', 'L', 'U'};\n\n    random_device rd;\n    mt19937 g(rd());\n    vector<int> directions = {0, 1, 2, 3};\n    shuffle(directions.begin(), directions.end(), g);\n\n    for (int k : directions) {\n        int i2 = i + di[k];\n        int j2 = j + dj[k];\n        if (0 <= i2 && i2 < N && 0 <= j2 && j2 < N && !visited[i2][j2]) {\n            if (di[k] == 0 && v[i][min(j, j2)] == '0' || dj[k] == 0 && h[min(i, i2)][j] == '0') {\n                route.push_back(dir[k]);\n                dfs(i2, j2, route);\n                route.push_back(dir[(k + 2) % 4]);\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> N;\n    h.resize(N - 1);\n    v.resize(N);\n    d.resize(N, vector<int>(N));\n    visited.resize(N, vector<bool>(N, false));\n\n    for (int i = 0; i < N - 1; i++) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\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<char> route;\n    dfs(0, 0, route);\n\n    // Simple route optimization: remove consecutive duplicates\n    string optimizedRoute;\n    for (char c : route) {\n        if (optimizedRoute.empty() || c != optimizedRoute.back()) {\n            optimizedRoute += c;\n        }\n    }\n\n    cout << optimizedRoute << endl;\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n#include <queue>\n\nusing namespace std;\n\nstruct Position {\n    int i, j;\n};\n\nstruct BeamSearchNode {\n    vector<Position> currentPos;\n    string S;\n    vector<pair<int, int>> operations;\n    int score;\n};\n\nstruct CompareNodes {\n    bool operator()(const BeamSearchNode& a, const BeamSearchNode& b) {\n        return a.score < b.score;\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n\n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> t[i];\n    }\n\n    unordered_map<char, vector<Position>> charPositions;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            charPositions[grid[i][j]].push_back({i, j});\n        }\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    priority_queue<BeamSearchNode, vector<BeamSearchNode>, CompareNodes> queue;\n    BeamSearchNode initialNode = {{{si, sj}}, \"\", {}, 0};\n    queue.push(initialNode);\n\n    vector<pair<int, int>> bestOperations;\n    int bestScore = -1e9;\n\n    for (int step = 0; step < 5000; ++step) {\n        if (queue.empty()) break;\n\n        BeamSearchNode node = queue.top();\n        queue.pop();\n\n        if (node.score > bestScore) {\n            bestScore = node.score;\n            bestOperations = node.operations;\n        }\n\n        int radius = min(N, 5);\n        for (int di = -radius; di <= radius; ++di) {\n            for (int dj = -radius; dj <= radius; ++dj) {\n                int i = node.currentPos.back().i + di;\n                int j = node.currentPos.back().j + dj;\n                if (i >= 0 && i < N && j >= 0 && j < N) {\n                    int cost = abs(di) + abs(dj) + 1;\n                    char c = grid[i][j];\n                    string newS = node.S + c;\n\n                    int score = 0;\n                    for (const auto& tk : t) {\n                        if (newS.size() <= tk.size() && tk.substr(0, newS.size()) == newS) {\n                            score += 1;\n                        }\n                    }\n\n                    BeamSearchNode newNode = {node.currentPos, newS, node.operations, node.score + score};\n                    newNode.currentPos.push_back({i, j});\n                    newNode.operations.push_back({i, j});\n\n                    if (newNode.operations.size() <= 5000) {\n                        queue.push(newNode);\n                    }\n                }\n            }\n        }\n    }\n\n    for (const auto& op : bestOperations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc030":"int main() {\n    read_input();\n    vector<vector<int>> estimated_oil_reserves(N, vector<int>(N, -1));\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dis(0, N - 1);\n\n    for (int i = 0; i < N * N; ++i) {\n        int x = dis(gen);\n        int y = dis(gen);\n        if (estimated_oil_reserves[x][y] == -1) {\n            drill(x, y);\n            // Update estimated_oil_reserves based on the response\n        }\n    }\n\n    // Generate a guess based on estimated_oil_reserves\n    vector<pair<int, int>> guess_squares;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (estimated_oil_reserves[i][j] > 0) {\n                guess_squares.emplace_back(i, j);\n            }\n        }\n    }\n    guess(guess_squares);\n\n    return 0;\n}","ahc031":"```cpp\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int W = 1000;\n\nstruct Rectangle {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    int D, N;\n    cin >> D >> N;\n\n    vector<vector<int>> areas(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> areas[d][k];\n        }\n    }\n\n    vector<vector<Rectangle>> rectangles(D, vector<Rectangle>(N));\n\n    // Initial placement for the first day\n    vector<pair<int, int>> sizes(N);\n    for (int k = 0; k < N; k++) {\n        sizes[k] = {areas[0][k], k};\n    }\n    sort(sizes.begin(), sizes.end());\n\n    int x = 0, y = 0;\n    for (auto [area, k] : sizes) {\n        int w = min(W - x, (int)sqrt(area));\n        int h = (area + w - 1) / w;\n        rectangles[0][k] = {x, y, x + w, y + h};\n        x += w;\n        if (x >= W) {\n            x = 0;\n            y += h;\n        }\n    }\n\n    // Subsequent days\n    for (int d = 1; d < D; d++) {\n        vector<pair<int, int>> sizes(N);\n        for (int k = 0; k < N; k++) {\n            sizes[k] = {areas[d][k], k};\n        }\n        sort(sizes.begin(), sizes.end());\n\n        for (auto [area, k] : sizes) {\n            Rectangle prev_rect = rectangles[d - 1][k];\n            int w = min(W - prev_rect.x1, (int)sqrt(area));\n            int h = (area + w - 1) / w;\n            rectangles[d][k] = {prev_rect.x1, prev_rect.y1, prev_rect.x1 + w, prev_rect.y1 + h};\n        }\n    }\n\n    // Output the rectangle coordinates\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cout << rectangles[d][k].x1 << \" \" << rectangles[d][k].y1 << \" \" << rectangles[d][k].x2 << \" \" << rectangles[d][k].y2 << endl;\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <queue>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int BEAM_WIDTH = 10;\n\nstruct Operation {\n    int stamp_id;\n    int x, y;\n};\n\nstruct BeamState {\n    vector<vector<int>> grid;\n    vector<Operation> operations;\n    int score;\n};\n\nstruct CompareBeamState {\n    bool operator()(const pair<int, BeamState>& a, const pair<int, BeamState>& b) {\n        return a.first < b.first;\n    }\n};\n\nint calculate_score(const vector<vector<int>>& grid) {\n    int score = 0;\n    for (const auto& row : grid) {\n        for (int value : row) {\n            score = (score + value % MOD) % MOD;\n        }\n    }\n    return score;\n}\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n\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    vector<vector<vector<int>>> stamps(M, vector<vector<int>>(3, vector<int>(3)));\n    for (int m = 0; m < M; ++m) {\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                cin >> stamps[m][i][j];\n            }\n        }\n    }\n\n    priority_queue<pair<int, BeamState>, vector<pair<int, BeamState>>, CompareBeamState> beam;\n    beam.push({calculate_score(grid), {grid, {}, calculate_score(grid)}});\n\n    for (int k = 0; k < K; ++k) {\n        priority_queue<pair<int, BeamState>, vector<pair<int, BeamState>>, CompareBeamState> new_beam;\n\n        while (!beam.empty()) {\n            auto state = beam.top().second;\n            beam.pop();\n\n            for (int stamp_id = 0; stamp_id < M; ++stamp_id) {\n                for (int x = 0; x <= N - 3; ++x) {\n                    for (int y = 0; y <= N - 3; ++y) {\n                        vector<vector<int>> new_grid = state.grid;\n                        for (int i = 0; i < 3; ++i) {\n                            for (int j = 0; j < 3; ++j) {\n                                new_grid[x + i][y + j] += stamps[stamp_id][i][j];\n                            }\n                        }\n                        int new_score = calculate_score(new_grid);\n                        vector<Operation> new_operations = state.operations;\n                        new_operations.push_back({stamp_id, x, y});\n\n                        if (new_beam.size() < BEAM_WIDTH) {\n                            new_beam.push({new_score, {new_grid, new_operations, new_score}});\n                        } else if (new_score > new_beam.top().first) {\n                            new_beam.pop();\n                            new_beam.push({new_score, {new_grid, new_operations, new_score}});\n                        }\n                    }\n                }\n            }\n        }\n\n        beam = new_beam;\n    }\n\n    auto best_state = beam.top().second;\n    cout << best_state.operations.size() << endl;\n    for (const auto& op : best_state.operations) {\n        cout << op.stamp_id << \" \" << op.x << \" \" << op.y << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURN = 10000;\n\nstruct Crane {\n    int x, y;\n    bool holding;\n    int container;\n};\n\nint grid[N][N];\nCrane cranes[N];\nvector<int> containersToDispatch[N];\nint turn = 0;\n\nvoid simulate() {\n    vector<string> operations(N, \"\");\n    // Simulate the container dispatch process\n    while (turn < MAX_TURN) {\n        // Bring in new containers\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][0] == -1 && !containersToDispatch[i].empty()) {\n                grid[i][0] = containersToDispatch[i].back();\n                containersToDispatch[i].pop_back();\n            }\n        }\n\n        // Determine the next action for each crane\n        for (int i = 0; i < N; ++i) {\n            char operation = '.';\n            // Improved logic to move cranes towards the dispatch gates\n            if (cranes[i].holding && cranes[i].y == N - 1) {\n                operation = 'Q';\n                grid[cranes[i].x][cranes[i].y] = cranes[i].container;\n                cranes[i].holding = false;\n            } else if (!cranes[i].holding && grid[cranes[i].x][cranes[i].y] != -1) {\n                operation = 'P';\n                cranes[i].container = grid[cranes[i].x][cranes[i].y];\n                grid[cranes[i].x][cranes[i].y] = -1;\n                cranes[i].holding = true;\n            } else if (cranes[i].holding && cranes[i].y < N - 1) {\n                operation = 'R';\n                cranes[i].y++;\n            } else if (!cranes[i].holding && cranes[i].y < N - 1 && grid[cranes[i].x][cranes[i].y + 1] == -1) {\n                operation = 'R';\n                cranes[i].y++;\n            }\n            operations[i] += operation;\n        }\n\n        // Dispatch containers\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][N - 1] != -1) {\n                // Dispatch the container\n                grid[i][N - 1] = -1;\n            }\n        }\n\n        turn++;\n        bool allDone = true;\n        for (int i = 0; i < N; ++i) {\n            if (!containersToDispatch[i].empty()) {\n                allDone = false;\n                break;\n            }\n        }\n        if (allDone) {\n            break;\n        }\n    }\n\n    // Output the operations for each crane\n    for (int i = 0; i < N; ++i) {\n        while (operations[i].length() < turn) {\n            operations[i] += '.';\n        }\n        cout << operations[i] << endl;\n    }\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector<vector<int>> A(n, vector<int>(n));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> A[i][j];\n            containersToDispatch[i].push_back(A[i][j]);\n        }\n        reverse(containersToDispatch[i].begin(), containersToDispatch[i].end());\n    }\n\n    // Initialize the grid and cranes\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            grid[i][j] = -1;\n        }\n        cranes[i].x = i;\n        cranes[i].y = 0;\n        cranes[i].holding = false;\n    }\n\n    simulate();\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nint N;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nint h[20][20];\nint loaded = 0;\npair<int, int> pos = {0, 0};\n\nvoid load(int d) {\n    cout << \"+\" << d << endl;\n    h[pos.first][pos.second] -= d;\n    loaded += d;\n}\n\nvoid unload(int d) {\n    cout << \"-\" << d << endl;\n    h[pos.first][pos.second] += d;\n    loaded -= d;\n}\n\nvoid move(int d) {\n    cout << dir[d] << endl;\n    pos.first += dx[d];\n    pos.second += dy[d];\n}\n\nint main() {\n    cin >> N;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h[i][j];\n        }\n    }\n\n    // Greedy algorithm\n    priority_queue<pair<int, pair<int, int>>> pq;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (h[i][j] != 0) {\n                pq.push({abs(h[i][j]), {i, j}});\n            }\n        }\n    }\n\n    while (!pq.empty()) {\n        auto [val, pos2] = pq.top();\n        pq.pop();\n        int x = pos2.first, y = pos2.second;\n\n        // Move to (x, y)\n        int min_dist = abs(pos.first - x) + abs(pos.second - y);\n        while (pos.first != x || pos.second != y) {\n            for (int d = 0; d < 4; d++) {\n                int nx = pos.first + dx[d], ny = pos.second + dy[d];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N && abs(nx - x) + abs(ny - y) < min_dist) {\n                    move(d);\n                    min_dist = abs(pos.first - x) + abs(pos.second - y);\n                    break;\n                }\n            }\n        }\n\n        // Load/unload at (x, y)\n        if (h[x][y] > 0) {\n            load(min(h[x][y], 1000000));\n        } else if (h[x][y] < 0) {\n            if (loaded >= -h[x][y]) { // Check if there's enough soil to unload\n                unload(min(-h[x][y], loaded));\n            } else {\n                // If not enough soil, load the remaining height to make it 0\n                load(min(-h[x][y] - loaded, 1000000));\n                unload(loaded);\n            }\n        }\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nstruct Seed {\n    int id;\n    vector<int> eval;\n    int value;\n};\n\nbool compareSeeds(const Seed& a, const Seed& b) {\n    return a.value > b.value;\n}\n\nint main() {\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seedCount = 2 * N * (N - 1);\n    vector<Seed> seeds(seedCount);\n\n    for (int i = 0; i < seedCount; i++) {\n        seeds[i].id = i;\n        seeds[i].eval.resize(M);\n        seeds[i].value = 0;\n\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i].eval[j];\n            seeds[i].value += seeds[i].eval[j];\n        }\n    }\n\n    sort(seeds.begin(), seeds.end(), compareSeeds);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int t = 0; t < T; t++) {\n        vector<vector<int>> grid(N, vector<int>(N));\n        vector<Seed> selectedSeeds(N * N);\n\n        // Select top N*N seeds\n        for (int i = 0; i < N * N; i++) {\n            selectedSeeds[i] = seeds[i];\n        }\n\n        // Greedy initialization\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                grid[i][j] = i * N + j;\n            }\n        }\n\n        // Simulated annealing\n        double temperature = 1000.0;\n        double coolingRate = 0.99;\n\n        int currentScore = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (i < N - 1) currentScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i + 1][j]].value;\n                if (j < N - 1) currentScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i][j + 1]].value;\n            }\n        }\n\n        for (int iteration = 0; iteration < 10000; iteration++) {\n            int i1 = dis(gen), j1 = dis(gen);\n            int i2 = dis(gen), j2 = dis(gen);\n\n            swap(grid[i1][j1], grid[i2][j2]);\n\n            int newScore = 0;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (i < N - 1) newScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i + 1][j]].value;\n                    if (j < N - 1) newScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i][j + 1]].value;\n                }\n            }\n\n            if (newScore > currentScore || exp((newScore - currentScore) / temperature) > (double)rand() / RAND_MAX) {\n                currentScore = newScore;\n            } else {\n                swap(grid[i1][j1], grid[i2][j2]);\n            }\n\n            temperature *= coolingRate;\n        }\n\n        // Output grid arrangement\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                else cout << endl;\n            }\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seedCount; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> seeds[i].eval[j];\n                seeds[i].value = 0;\n                for (int k = 0; k < M; k++) {\n                    seeds[i].value += seeds[i].eval[k];\n                }\n            }\n        }\n\n        sort(seeds.begin(), seeds.end(), compareSeeds);\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n\nint main() {\n    int N, M, V;\n    std::cin >> N >> M >> V;\n\n    std::vector<std::vector<int>> s(N, std::vector<int>(N));\n    std::vector<std::vector<int>> t(N, std::vector<int>(N));\n\n    for (int i = 0; i < N; ++i) {\n        std::string str;\n        std::cin >> str;\n        for (int j = 0; j < N; ++j) {\n            s[i][j] = str[j] - '0';\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        std::string str;\n        std::cin >> str;\n        for (int j = 0; j < N; ++j) {\n            t[i][j] = str[j] - '0';\n        }\n    }\n\n    // Design the robotic arm\n    int V_prime = std::min(V, M + 1);\n    std::cout << V_prime << std::endl;\n    for (int i = 1; i < V_prime; ++i) {\n        std::cout << 0 << \" \" << 1 << std::endl;\n    }\n\n    // Initial position of the root\n    int rx = N / 2, ry = N / 2;\n    std::cout << rx << \" \" << ry << std::endl;\n\n    // Sequence of operations\n    for (int turn = 0; turn < 100; ++turn) {\n        std::string op(2 * V_prime, '.');\n        // Simple random movement for demonstration\n        if (rx > 0 && rand() % 2) {\n            rx--;\n            op[0] = 'U';\n        } else if (rx < N - 1 && rand() % 2) {\n            rx++;\n            op[0] = 'D';\n        }\n        if (ry > 0 && rand() % 2) {\n            ry--;\n            op[0] = 'L';\n        } else if (ry < N - 1 && rand() % 2) {\n            ry++;\n            op[0] = 'R';\n        }\n\n        // Random rotation for demonstration\n        if (V_prime > 1 && rand() % 2) {\n            op[1] = 'L';\n        }\n\n        // Grab or release takoyaki for demonstration\n        if (rand() % 2) {\n            op[V_prime] = 'P';\n        }\n\n        std::cout << op << std::endl;\n    }\n\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cstddef>\n#include <random>\n\nstruct Point {\n    int x, y;\n};\n\nint countPoints(const std::vector<Point>& points, int minX, int maxX, int minY, int maxY) {\n    int count = 0;\n    for (const auto& point : points) {\n        if (point.x >= minX && point.x <= maxX && point.y >= minY && point.y <= maxY) {\n            count++;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int N;\n    std::cin >> N;\n\n    std::vector<Point> mackerels(N);\n    std::vector<Point> sardines(N);\n\n    for (int i = 0; i < N; ++i) {\n        std::cin >> mackerels[i].x >> mackerels[i].y;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        std::cin >> sardines[i].x >> sardines[i].y;\n    }\n\n    int minX = std::min_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.x < b.x; })->x;\n    int maxX = std::max_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.x < b.x; })->x;\n    int minY = std::min_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.y < b.y; })->y;\n    int maxY = std::max_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.y < b.y; })->y;\n\n    int bestScore = countPoints(mackerels, minX, maxX, minY, maxY) - countPoints(sardines, minX, maxX, minY, maxY);\n    std::vector<Point> bestPolygon = {{minX, minY}, {maxX, minY}, {maxX, maxY}, {minX, maxY}};\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> disX(minX, maxX);\n    std::uniform_int_distribution<> disY(minY, maxY);\n\n    int iterations = 10000;\n    for (int i = 0; i < iterations; ++i) {\n        int x1 = disX(gen);\n        int x2 = disX(gen);\n        int y1 = disY(gen);\n        int y2 = disY(gen);\n\n        if (x1 > x2) std::swap(x1, x2);\n        if (y1 > y2) std::swap(y1, y2);\n\n        int score = countPoints(mackerels, x1, x2, y1, y2) - countPoints(sardines, x1, x2, y1, y2);\n        if (score > bestScore) {\n            bestScore = score;\n            bestPolygon = {{x1, y1}, {x2, y1}, {x2, y2}, {x1, y2}};\n        }\n    }\n\n    std::cout << bestPolygon.size() << std::endl;\n    for (const auto& point : bestPolygon) {\n        std::cout << point.x << \" \" << point.y << std::endl;\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nstruct Rectangle {\n    int index;\n    int w, h;\n};\n\nstruct Placement {\n    int index;\n    int rotation;\n    char direction;\n    int reference;\n};\n\nbool compareRectangles(const Rectangle& a, const Rectangle& b) {\n    return std::max(a.w, a.h) > std::max(b.w, b.h);\n}\n\nint main() {\n    int N, T;\n    double sigma;\n    std::cin >> N >> T >> sigma;\n\n    std::vector<Rectangle> rectangles(N);\n    for (int i = 0; i < N; ++i) {\n        rectangles[i].index = i;\n        std::cin >> rectangles[i].w >> rectangles[i].h;\n    }\n\n    std::sort(rectangles.begin(), rectangles.end(), compareRectangles);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> dis(0, 1);\n    std::uniform_int_distribution<> disN(N/2, N);\n\n    for (int t = 0; t < T; ++t) {\n        int n = disN(gen);\n        std::vector<Placement> placements;\n        std::vector<Rectangle> placedRectangles;\n\n        std::vector<Rectangle> selectedRectangles(N);\n        for (int i = 0; i < N; ++i) {\n            selectedRectangles[i] = rectangles[i];\n        }\n\n        std::sort(selectedRectangles.begin(), selectedRectangles.end(), [](const Rectangle& a, const Rectangle& b) {\n            return a.index < b.index;\n        });\n\n        for (int i = 0; i < N; ++i) {\n            if (i < n) {\n                Rectangle rect = selectedRectangles[i];\n                int rotation = dis(gen);\n                char direction = (dis(gen) == 0) ? 'U' : 'L';\n                int reference = (placedRectangles.size() == 0) ? -1 : (dis(gen) == 0) ? -1 : placedRectangles[dis(gen) % placedRectangles.size()].index;\n\n                if (rotation == 1) {\n                    std::swap(rect.w, rect.h);\n                }\n\n                placements.push_back({rect.index, rotation, direction, reference});\n\n                placedRectangles.push_back(rect);\n            }\n        }\n\n        std::cout << n << std::endl;\n        for (const auto& placement : placements) {\n            std::cout << placement.index << \" \" << placement.rotation << \" \" << placement.direction << \" \" << placement.reference << std::endl;\n        }\n\n        std::cout.flush();\n\n        int W, H;\n        std::cin >> W >> H;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n};\n\nint main() {\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<Edge> edges(M);\n    for (int i = 0; i < M; i++) {\n        cin >> edges[i].u >> edges[i].v;\n    }\n\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<int> parent(N, -1);\n    vector<vector<int>> graph(N);\n    for (const auto& edge : edges) {\n        graph[edge.u].push_back(edge.v);\n        graph[edge.v].push_back(edge.u);\n    }\n\n    // Perform a BFS traversal to construct the rooted trees\n    queue<int> q;\n    vector<bool> visited(N, false);\n    vector<int> roots;\n    for (int i = 0; i < N; i++) {\n        if (!visited[i]) {\n            roots.push_back(i);\n            q.push(i);\n            visited[i] = true;\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (int v : graph[u]) {\n                    if (!visited[v]) {\n                        visited[v] = true;\n                        parent[v] = u;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n\n    // Make sure the height constraint is satisfied\n    for (int i = 0; i < N; i++) {\n        if (i != roots[0] && parent[i] != -1) {\n            int height = 0;\n            int v = i;\n            while (v != roots[0]) {\n                height++;\n                v = parent[v];\n                if (height > H) {\n                    parent[i] = -1; // Make i a root if height exceeds H\n                    break;\n                }\n            }\n        }\n    }\n\n    // Output the parent of each vertex\n    for (int i = 0; i < N; i++) {\n        cout << parent[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n\nusing namespace std;\n\nconst int N = 20;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nint main() {\n    int n;\n    cin >> n;\n    vector<string> grid(n);\n    for (int i = 0; i < n; i++) {\n        cin >> grid[i];\n    }\n\n    vector<pair<char, int>> operations;\n    queue<pair<int, int>> oniQueue;\n\n    // Iterate through the grid to identify Oni positions\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            if (grid[i][j] == 'x') {\n                oniQueue.push({i, j});\n            }\n        }\n    }\n\n    while (!oniQueue.empty()) {\n        int x = oniQueue.front().first;\n        int y = oniQueue.front().second;\n        oniQueue.pop();\n\n        if (grid[x][y] != 'x') continue;\n\n        // Check if there is no Fukunokami in any direction\n        for (int k = 0; k < 4; k++) {\n            int count = 0;\n            int nx = x + dx[k];\n            int ny = y + dy[k];\n            while (nx >= 0 && nx < n && ny >= 0 && ny < n) {\n                if (grid[nx][ny] == 'o') break;\n                count++;\n                nx += dx[k];\n                ny += dy[k];\n            }\n\n            if (nx < 0 || nx >= n || ny < 0 || ny >= n) {\n                // Shift in the direction that does not contain a Fukunokami\n                if (k == 0) { // Up\n                    for (int i = 0; i <= x; i++) {\n                        operations.push_back({'U', y});\n                    }\n                    for (int i = 0; i <= x; i++) {\n                        operations.push_back({'D', y});\n                    }\n                } else if (k == 1) { // Down\n                    for (int i = x; i < n - 1; i++) {\n                        operations.push_back({'D', y});\n                    }\n                    for (int i = x; i < n - 1; i++) {\n                        operations.push_back({'U', y});\n                    }\n                } else if (k == 2) { // Left\n                    for (int i = 0; i <= y; i++) {\n                        operations.push_back({'L', x});\n                    }\n                    for (int i = 0; i <= y; i++) {\n                        operations.push_back({'R', x});\n                    }\n                } else if (k == 3) { // Right\n                    for (int i = y; i < n - 1; i++) {\n                        operations.push_back({'R', x});\n                    }\n                    for (int i = y; i < n - 1; i++) {\n                        operations.push_back({'L', x});\n                    }\n                }\n\n                // Update the grid to reflect the removal of the Oni\n                grid[x][y] = '.';\n                break;\n            }\n        }\n    }\n\n    // Output the sequence of operations\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nconst int N = 100;\nconst int L = 500000;\n\nvector<int> T(N);\nvector<int> a(N), b(N);\nvector<int> count(N, 0);\nmt19937 mt(42);\n\nvoid simulate(int steps) {\n    uniform_int_distribution<int> dist(0, N-1);\n    for (int step = 0; step < steps; ++step) {\n        int i = dist(mt);\n        int orig_a = a[i], orig_b = b[i];\n        int new_a = dist(mt), new_b = dist(mt);\n        a[i] = new_a;\n        b[i] = new_b;\n        count.assign(N, 0);\n        int last = 0;\n        count[0] = 1;\n        for (int t = 1; t < L; ++t) {\n            int next = (count[last] % 2 == 0) ? b[last] : a[last];\n            count[next]++;\n            last = next;\n        }\n        int new_error = accumulate(count.begin(), count.end(), 0, [&](int sum, int c, int i) { return sum + abs(c - T[i]); });\n        if (new_error > accumulate(count.begin(), count.end(), 0, [&](int sum, int c, int i) { return sum + abs(c - T[i]); })) {\n            a[i] = orig_a;\n            b[i] = orig_b;\n        }\n    }\n}\n\nint main() {\n    cin >> N >> L;\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    // Initialize a and b\n    for (int i = 0; i < N; ++i) {\n        a[i] = (i + 1) % N;\n        b[i] = (i + 2) % N;\n    }\n\n    simulate(100000);\n\n    for (int i = 0; i < N; ++i) {\n        cout << a[i] << \" \" << b[i] << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cassert>\n\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double x, y;\n};\n\nstruct Edge {\n    int u, v;\n};\n\nint N, M, Q, L, W;\nvector<int> G;\nvector<City> cities;\nvector<vector<int>> groups;\nvector<vector<Edge>> edges;\n\nvoid readInput() {\n    cin >> N >> M >> Q >> L >> W;\n    G.resize(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n    cities.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].id = i;\n        cities[i].x = (cities[i].lx + cities[i].rx) / 2.0;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2.0;\n    }\n}\n\nvoid initialGrouping() {\n    sort(cities.begin(), cities.end(), [](const City& a, const City& b) {\n        return make_pair(a.x, a.y) < make_pair(b.x, b.y);\n    });\n    groups.resize(M);\n    int start = 0;\n    for (int i = 0; i < M; ++i) {\n        groups[i].resize(G[i]);\n        for (int j = 0; j < G[i]; ++j) {\n            groups[i][j] = cities[start + j].id;\n        }\n        start += G[i];\n    }\n}\n\nvoid queryFortuneTeller(const vector<int>& group) {\n    if (group.size() <= 1) return;\n    vector<Edge> mstEdges;\n    if (group.size() <= L) {\n        cout << \"? \" << group.size();\n        for (int city : group) cout << \" \" << city;\n        cout << endl;\n        for (int i = 0; i < group.size() - 1; ++i) {\n            int u, v;\n            cin >> u >> v;\n            mstEdges.push_back({u, v});\n        }\n        edges.push_back(mstEdges);\n    } else {\n        // For larger groups, divide them into smaller subsets and query\n        for (size_t i = 0; i < group.size(); i += L - 1) {\n            vector<int> subset;\n            for (size_t j = i; j < min(i + L - 1, group.size()); ++j) {\n                subset.push_back(group[j]);\n            }\n            if (subset.size() > 1) {\n                cout << \"? \" << subset.size();\n                for (int city : subset) cout << \" \" << city;\n                cout << endl;\n                vector<Edge> subsetMstEdges;\n                for (int k = 0; k < subset.size() - 1; ++k) {\n                    int u, v;\n                    cin >> u >> v;\n                    subsetMstEdges.push_back({u, v});\n                }\n                mstEdges.insert(mstEdges.end(), subsetMstEdges.begin(), subsetMstEdges.end());\n            }\n        }\n        edges.push_back(mstEdges);\n    }\n}\n\nvoid buildRoads() {\n    edges.clear();\n    for (const auto& group : groups) {\n        queryFortuneTeller(group);\n    }\n}\n\nvoid outputAnswer() {\n    cout << \"!\" << endl;\n    for (size_t i = 0; i < groups.size(); ++i) {\n        for (int city : groups[i]) cout << city << \" \";\n        cout << endl;\n        for (const auto& edge : edges[i]) cout << edge.u << \" \" << edge.v << endl;\n    }\n}\n\nint main() {\n    readInput();\n    initialGrouping();\n    buildRoads();\n    outputAnswer();\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n\nusing namespace std;\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n\n    vector<vector<int>> grid(N, vector<int>(N, 0)); // 0: empty, 1: block\n\n    struct Pos {\n        int x, y;\n    };\n\n    Pos pos;\n    cin >> pos.x >> pos.y;\n    vector<Pos> targets(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> targets[i].x >> targets[i].y;\n    }\n\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    char dirChar[] = {'U', 'D', 'L', 'R'};\n\n    auto manhattanDistance = [](Pos a, Pos b) {\n        return abs(a.x - b.x) + abs(a.y - b.y);\n    };\n\n    auto slide = [&](int x, int y, int dir, Pos &end) {\n        int nx = x + dx[dir];\n        int ny = y + dy[dir];\n        while (0 <= nx && nx < N && 0 <= ny && ny < N && grid[nx][ny] == 0) {\n            x = nx;\n            y = ny;\n            nx += dx[dir];\n            ny += dy[dir];\n        }\n        end.x = x;\n        end.y = y;\n    };\n\n    for (int targetIndex = 0; targetIndex < M; ++targetIndex) {\n        Pos target = targets[targetIndex];\n        while (pos.x != target.x || pos.y != target.y) {\n            int bestDir = -1;\n            char bestAction = ' ';\n            Pos nextPos = pos;\n            int minDist = manhattanDistance(pos, target);\n\n            for (int dir = 0; dir < 4; ++dir) {\n                int nx = pos.x + dx[dir];\n                int ny = pos.y + dy[dir];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                    // Try Move\n                    if (grid[nx][ny] == 0) {\n                        int dist = manhattanDistance({nx, ny}, target);\n                        if (dist < minDist) {\n                            minDist = dist;\n                            bestDir = dir;\n                            bestAction = 'M';\n                            nextPos = {nx, ny};\n                        }\n                    }\n\n                    // Try Slide\n                    Pos slideEnd = pos;\n                    slide(pos.x, pos.y, dir, slideEnd);\n                    if (slideEnd.x != pos.x || slideEnd.y != pos.y) {\n                        int dist = manhattanDistance(slideEnd, target);\n                        if (dist < minDist && (slideEnd.x != target.x || slideEnd.y != target.y)) {\n                            minDist = dist;\n                            bestDir = dir;\n                            bestAction = 'S';\n                            nextPos = slideEnd;\n                        }\n                    }\n                }\n\n                // Try Alter\n                if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                    int originalBlock = grid[nx][ny];\n                    grid[nx][ny] = 1 - originalBlock;\n                    Pos slideEndAfterAlter = pos;\n                    slide(pos.x, pos.y, dir, slideEndAfterAlter);\n                    int dist = manhattanDistance(slideEndAfterAlter, target);\n                    if (dist < minDist && (slideEndAfterAlter.x != target.x || slideEndAfterAlter.y != target.y)) {\n                        minDist = dist;\n                        bestDir = dir;\n                        bestAction = 'A';\n                        nextPos = pos; // Alter doesn't change pos\n                    }\n                    grid[nx][ny] = originalBlock; // Revert\n                }\n            }\n\n            if (bestAction != ' ') {\n                cout << bestAction << \" \" << dirChar[bestDir] << endl;\n                if (bestAction == 'M') {\n                    pos = nextPos;\n                } else if (bestAction == 'S') {\n                    pos = nextPos;\n                } else if (bestAction == 'A') {\n                    int nx = pos.x + dx[bestDir];\n                    int ny = pos.y + dy[bestDir];\n                    grid[nx][ny] = 1 - grid[nx][ny];\n                }\n            } else {\n                // Fallback, should ideally not reach here\n                cout << \"M U\" << endl;\n            }\n        }\n    }\n\n    return 0;\n}"},"16":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Company {\n    int x, y, r, idx;\n    bool operator<(const Company& other) const {\n        return r > other.r;\n    }\n};\n\nint main() {\n    int n;\n    cin >> n;\n\n    vector<Company> companies(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n        companies[i].idx = i;\n    }\n\n    sort(companies.begin(), companies.end());\n\n    vector<vector<int>> ans(n, vector<int>(4));\n\n    int gridSize = 10000;\n    vector<bool> used(gridSize * gridSize, false);\n\n    for (const auto& company : companies) {\n        int x = company.x, y = company.y, r = company.r, idx = company.idx;\n\n        int size = min(100, (int)sqrt(r));\n        int sx = max(0, x - size / 2), sy = max(0, y - size / 2);\n\n        bool found = false;\n        for (int i = sx; i <= min(gridSize - size, x + size / 2); ++i) {\n            for (int j = sy; j <= min(gridSize - size, y + size / 2); ++j) {\n                bool valid = true;\n                for (int k = i; k < i + size; ++k) {\n                    for (int l = j; l < j + size; ++l) {\n                        if (used[k * gridSize + l]) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                    if (!valid) break;\n                }\n\n                if (valid) {\n                    ans[idx] = {i, j, i + size, j + size};\n                    for (int k = i; k < i + size; ++k) {\n                        for (int l = j; l < j + size; ++l) {\n                            used[k * gridSize + l] = true;\n                        }\n                    }\n                    found = true;\n                    break;\n                }\n            }\n            if (found) break;\n        }\n\n        if (!found) {\n            // Fallback to a simple assignment if no suitable rectangle is found\n            ans[idx] = {0, 0, 1, 1};\n        }\n    }\n\n    for (const auto& a : ans) {\n        cout << a[0] << \" \" << a[1] << \" \" << a[2] << \" \" << a[3] << endl;\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct State {\n    int x, y;\n    int score;\n    string path;\n    unordered_set<int> visited_tiles;\n\n    State(int x, int y, int score, string path, unordered_set<int> visited_tiles)\n        : x(x), y(y), score(score), path(path), visited_tiles(visited_tiles) {}\n};\n\nstruct CompareStates {\n    bool operator()(const State& a, const State& b) {\n        return a.score < b.score;\n    }\n};\n\nint main() {\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> tile_ids(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> tile_ids[i][j];\n        }\n    }\n\n    vector<vector<int>> scores(50, vector<int>(50));\n    for (int i = 0; i < 50; ++i) {\n        for (int j = 0; j < 50; ++j) {\n            cin >> scores[i][j];\n        }\n    }\n\n    int initial_tile_id = tile_ids[si][sj];\n    unordered_set<int> initial_visited_tiles = {initial_tile_id};\n    State initial_state(si, sj, scores[si][sj], \"\", initial_visited_tiles);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    priority_queue<State, vector<State>, CompareStates> pq;\n    pq.push(initial_state);\n\n    int max_score = initial_state.score;\n    string max_path = \"\";\n\n    for (int iter = 0; iter < 500000; ++iter) {\n        if (pq.empty()) break;\n        State state = pq.top();\n        pq.pop();\n\n        if (state.score < max_score) continue;\n\n        vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n        vector<char> moves = {'U', 'D', 'L', 'R'};\n\n        vector<int> indices(4);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), gen);\n\n        for (int i : indices) {\n            int nx = state.x + directions[i].first;\n            int ny = state.y + directions[i].second;\n\n            if (nx < 0 || nx >= 50 || ny < 0 || ny >= 50) continue;\n\n            int next_tile_id = tile_ids[nx][ny];\n            if (state.visited_tiles.count(next_tile_id)) continue;\n\n            unordered_set<int> next_visited_tiles = state.visited_tiles;\n            next_visited_tiles.insert(next_tile_id);\n\n            int next_score = state.score + scores[nx][ny];\n            string next_path = state.path + moves[i];\n\n            State next_state(nx, ny, next_score, next_path, next_visited_tiles);\n\n            if (next_score > max_score) {\n                max_score = next_score;\n                max_path = next_path;\n            }\n\n            pq.push(next_state);\n        }\n    }\n\n    cout << max_path << endl;\n\n    return 0;\n}","ahc003":"#include <iostream>\n#include <queue>\n#include <vector>\n#include <unordered_map>\n#include <limits>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Edge {\n    int to;\n    double weight;\n    int count;\n};\n\nusing Graph = vector<vector<Edge>>;\n\nstruct Node {\n    int id;\n    double distance;\n    bool operator>(const Node& other) const {\n        return distance > other.distance;\n    }\n};\n\nGraph buildGraph() {\n    Graph graph(30 * 30);\n    for (int i = 0; i < 30; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            int id = i * 30 + j;\n            if (i > 0) graph[id].push_back({id - 30, 1, 0}); // Up\n            if (i < 29) graph[id].push_back({id + 30, 1, 0}); // Down\n            if (j > 0) graph[id].push_back({id - 1, 1, 0}); // Left\n            if (j < 29) graph[id].push_back({id + 1, 1, 0}); // Right\n        }\n    }\n    return graph;\n}\n\nstring dijkstra(Graph& graph, int source, int target, mt19937& rng) {\n    vector<double> distances(graph.size(), numeric_limits<double>::max());\n    vector<int> previous(graph.size(), -1);\n    distances[source] = 0;\n\n    priority_queue<Node, vector<Node>, greater<Node>> queue;\n    queue.push({source, 0});\n\n    while (!queue.empty()) {\n        Node node = queue.top();\n        queue.pop();\n        if (node.id == target) break;\n\n        vector<Edge>& edges = graph[node.id];\n        shuffle(edges.begin(), edges.end(), rng); // Use shuffle instead of random_shuffle\n\n        for (const Edge& edge : edges) {\n            double newDistance = distances[node.id] + edge.weight;\n            if (newDistance < distances[edge.to]) {\n                distances[edge.to] = newDistance;\n                previous[edge.to] = node.id;\n                queue.push({edge.to, newDistance});\n            }\n        }\n    }\n\n    string path;\n    int current = target;\n    while (current != source) {\n        int prev = previous[current];\n        if (prev == current - 1) path += 'R';\n        else if (prev == current + 1) path += 'L';\n        else if (prev == current - 30) path += 'D';\n        else if (prev == current + 30) path += 'U';\n        current = prev;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nvoid updateGraph(Graph& graph, const string& path, double actualLength) {\n    double scaleFactor = actualLength / path.length();\n\n    int currentNode = 0;\n    for (char direction : path) {\n        int nextNode;\n        if (direction == 'U') nextNode = currentNode - 30;\n        else if (direction == 'D') nextNode = currentNode + 30;\n        else if (direction == 'L') nextNode = currentNode - 1;\n        else if (direction == 'R') nextNode = currentNode + 1;\n\n        for (Edge& edge : graph[currentNode]) {\n            if (edge.to == nextNode) {\n                edge.count++;\n                double alpha = 1.0 / (edge.count + 1);\n                edge.weight = (1 - alpha) * edge.weight + alpha * scaleFactor;\n                break;\n            }\n        }\n        for (Edge& edge : graph[nextNode]) {\n            if (edge.to == currentNode) {\n                edge.count++;\n                double alpha = 1.0 / (edge.count + 1);\n                edge.weight = (1 - alpha) * edge.weight + alpha * scaleFactor;\n                break;\n            }\n        }\n        currentNode = nextNode;\n    }\n}\n\nint main() {\n    Graph graph = buildGraph();\n    random_device rd;\n    mt19937 rng(rd());\n\n    for (int k = 0; k < 1000; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        int source = si * 30 + sj;\n        int target = ti * 30 + tj;\n\n        string path = dijkstra(graph, source, target, rng);\n        cout << path << endl;\n        cout.flush();\n\n        double actualLength;\n        cin >> actualLength;\n        updateGraph(graph, path, actualLength);\n    }\n\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct StringInfo {\n    string s;\n    int len;\n    bool used;\n};\n\nbool canPlaceString(vector<vector<char>>& matrix, const string& s, int i, int j, int dir) {\n    int N = matrix.size();\n    int len = s.length();\n\n    if (dir == 0) { // horizontal\n        for (int p = 0; p < len; ++p) {\n            int col = (j + p) % N;\n            if (matrix[i][col] != '.' && matrix[i][col] != s[p]) {\n                return false;\n            }\n        }\n    } else { // vertical\n        for (int p = 0; p < len; ++p) {\n            int row = (i + p) % N;\n            if (matrix[row][j] != '.' && matrix[row][j] != s[p]) {\n                return false;\n            }\n        }\n    }\n\n    return true;\n}\n\nvoid placeString(vector<vector<char>>& matrix, const string& s, int i, int j, int dir) {\n    int N = matrix.size();\n    int len = s.length();\n\n    if (dir == 0) { // horizontal\n        for (int p = 0; p < len; ++p) {\n            int col = (j + p) % N;\n            matrix[i][col] = s[p];\n        }\n    } else { // vertical\n        for (int p = 0; p < len; ++p) {\n            int row = (i + p) % N;\n            matrix[row][j] = s[p];\n        }\n    }\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<StringInfo> strings(M);\n\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i].s;\n        strings[i].len = strings[i].s.length();\n        strings[i].used = false;\n    }\n\n    // Sort the strings in descending order of their lengths\n    sort(strings.begin(), strings.end(), [](const StringInfo& a, const StringInfo& b) {\n        return a.len > b.len;\n    });\n\n    vector<vector<char>> matrix(N, vector<char>(N, '.'));\n\n    mt19937 mt(42);\n    uniform_int_distribution<int> dist(0, N - 1);\n\n    for (const auto& s : strings) {\n        if (s.used) continue;\n\n        bool placed = false;\n        for (int trial = 0; trial < 100; ++trial) {\n            int i = dist(mt), j = dist(mt);\n            int dir = dist(mt) % 2; // 0: horizontal, 1: vertical\n\n            if (canPlaceString(matrix, s.s, i, j, dir)) {\n                placeString(matrix, s.s, i, j, dir);\n                placed = true;\n                break;\n            }\n        }\n\n        if (placed) {\n            // Mark the string as used\n            for (auto& str : strings) {\n                if (str.s == s.s) {\n                    str.used = true;\n                    break;\n                }\n            }\n        }\n    }\n\n    // Print the resulting matrix\n    for (const auto& row : matrix) {\n        for (char c : row) {\n            cout << c;\n        }\n        cout << endl;\n    }\n\n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n#include <functional>\n#include <limits>\n\nusing namespace std;\n\nstruct Pos {\n    int i, j;\n    bool operator==(const Pos& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\n// Hash function for Pos struct\nstruct PosHash {\n    size_t operator()(const Pos& pos) const {\n        return hash<int>{}(pos.i) ^ (hash<int>{}(pos.j) << 1);\n    }\n};\n\n// Function declarations\nbool isVisible(const Pos& pos, const Pos& otherPos, const vector<string>& grid);\nbool isValidMove(const Pos& pos1, const Pos& pos2, const vector<string>& grid);\nPos getNearestUnvisitedSquare(const Pos& pos, const unordered_map<Pos, vector<Pos>, PosHash>& visibilityGraph, const unordered_set<Pos, PosHash>& visited);\nvoid optimizeRoute(vector<Pos>& route, const vector<string>& grid);\nint getTravelTime(const Pos& pos1, const Pos& pos2, const vector<string>& grid);\nvoid outputRoute(const vector<Pos>& route);\nvector<Pos> findPath(const Pos& start, const Pos& end, const vector<string>& grid);\nvector<Pos> getNeighbors(const Pos& pos, const vector<string>& grid);\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n\n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n\n    // Grid preprocessing\n    vector<Pos> roadSquares;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                roadSquares.push_back({i, j});\n            }\n        }\n    }\n\n    // Visibility graph construction\n    unordered_map<Pos, vector<Pos>, PosHash> visibilityGraph;\n    for (const auto& pos : roadSquares) {\n        vector<Pos> visibleSquares;\n        for (const auto& otherPos : roadSquares) {\n            if (isVisible(pos, otherPos, grid)) {\n                visibleSquares.push_back(otherPos);\n            }\n        }\n        visibilityGraph[pos] = visibleSquares;\n    }\n\n    // Route construction\n    unordered_set<Pos, PosHash> visited;\n    vector<Pos> route;\n    Pos currentPos = {si, sj};\n    route.push_back(currentPos);\n    visited.insert(currentPos);\n\n    while (visited.size() < roadSquares.size()) {\n        Pos nextPos = getNearestUnvisitedSquare(currentPos, visibilityGraph, visited);\n        if (nextPos.i == -1) {\n            break; // No more unvisited squares\n        }\n        if (isValidMove(currentPos, nextPos, grid)) {\n            route.push_back(nextPos);\n            visited.insert(nextPos);\n            currentPos = nextPos;\n        } else {\n            // Handle invalid move, e.g., by backtracking or skipping\n            break;\n        }\n    }\n\n    // Return to the starting point\n    if (currentPos.i != si || currentPos.j != sj) {\n        vector<Pos> pathBack = findPath(currentPos, {si, sj}, grid);\n        route.insert(route.end(), pathBack.begin() + 1, pathBack.end());\n    }\n\n    // Route optimization (2-opt)\n    optimizeRoute(route, grid);\n\n    // Output\n    outputRoute(route);\n\n    return 0;\n}\n\n// Function definitions\nbool isVisible(const Pos& pos, const Pos& otherPos, const vector<string>& grid) {\n    int N = grid.size();\n    if (pos.i == otherPos.i) {\n        int minJ = min(pos.j, otherPos.j);\n        int maxJ = max(pos.j, otherPos.j);\n        for (int j = minJ; j <= maxJ; j++) {\n            if (j < 0 || j >= N || grid[pos.i][j] == '#') {\n                return false;\n            }\n        }\n        return true;\n    } else if (pos.j == otherPos.j) {\n        int minI = min(pos.i, otherPos.i);\n        int maxI = max(pos.i, otherPos.i);\n        for (int i = minI; i <= maxI; i++) {\n            if (i < 0 || i >= N || grid[i][pos.j] == '#') {\n                return false;\n            }\n        }\n        return true;\n    }\n    return false;\n}\n\nbool isValidMove(const Pos& pos1, const Pos& pos2, const vector<string>& grid) {\n    int di = pos2.i - pos1.i;\n    int dj = pos2.j - pos1.j;\n    if (abs(di) + abs(dj) != 1) {\n        return false; // Invalid move\n    }\n    size_t i = pos2.i;\n    size_t j = pos2.j;\n    if (i >= grid.size() || j >= grid[0].size() || grid[i][j] == '#') {\n        return false; // Obstacle or out of bounds\n    }\n    return true;\n}\n\nPos getNearestUnvisitedSquare(const Pos& pos, const unordered_map<Pos, vector<Pos>, PosHash>& visibilityGraph, const unordered_set<Pos, PosHash>& visited) {\n    for (const auto& otherPos : visibilityGraph.at(pos)) {\n        if (visited.find(otherPos) == visited.end()) {\n            return otherPos;\n        }\n    }\n    return {-1, -1}; // Not found\n}\n\nvoid optimizeRoute(vector<Pos>& route, const vector<string>& grid) {\n    int N = route.size();\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int i = 1; i < N - 2; i++) {\n            for (int j = i + 1; j < N - 1; j++) {\n                Pos pos1 = route[i - 1];\n                Pos pos2 = route[i];\n                Pos pos3 = route[j];\n                Pos pos4 = route[j + 1];\n                if (isValidMove(pos1, pos3, grid) && isValidMove(pos2, pos4, grid)) {\n                    int oldCost = getTravelTime(pos1, pos2, grid) + getTravelTime(pos3, pos4, grid);\n                    int newCost = getTravelTime(pos1, pos3, grid) + getTravelTime(pos2, pos4, grid);\n                    if (newCost < oldCost) {\n                        reverse(route.begin() + i, route.begin() + j + 1);\n                        improved = true;\n                    }\n                }\n            }\n        }\n    }\n}\n\nint getTravelTime(const Pos& pos1, const Pos& pos2, const vector<string>& grid) {\n    if (abs(pos1.i - pos2.i) + abs(pos1.j - pos2.j) != 1) {\n        return numeric_limits<int>::max(); // Invalid move\n    }\n    int cost = grid[pos2.i][pos2.j] - '0';\n    return cost;\n}\n\nvoid outputRoute(const vector<Pos>& route) {\n    size_t N = route.size();\n    for (size_t i = 0; i < N - 1; i++) {\n        Pos pos1 = route[i];\n        Pos pos2 = route[i + 1];\n        if (pos1.i > pos2.i) {\n            cout << 'U';\n        } else if (pos1.i < pos2.i) {\n            cout << 'D';\n        } else if (pos1.j > pos2.j) {\n            cout << 'L';\n        } else if (pos1.j < pos2.j) {\n            cout << 'R';\n        }\n    }\n    cout << endl;\n}\n\nvector<Pos> findPath(const Pos& start, const Pos& end, const vector<string>& grid) {\n    queue<vector<Pos>> q;\n    unordered_set<Pos, PosHash> visited;\n    q.push({start});\n    visited.insert(start);\n\n    while (!q.empty()) {\n        vector<Pos> path = q.front();\n        q.pop();\n        Pos pos = path.back();\n        if (pos.i == end.i && pos.j == end.j) {\n            return path;\n        }\n        vector<Pos> neighbors = getNeighbors(pos, grid);\n        for (const auto& neighbor : neighbors) {\n            if (visited.find(neighbor) == visited.end()) {\n                visited.insert(neighbor);\n                path.push_back(neighbor);\n                q.push(path);\n                path.pop_back();\n            }\n        }\n    }\n    return {}; // No path found\n}\n\nvector<Pos> getNeighbors(const Pos& pos, const vector<string>& grid) {\n    vector<Pos> neighbors;\n    int di[] = {-1, 1, 0, 0};\n    int dj[] = {0, 0, -1, 1};\n    for (int k = 0; k < 4; k++) {\n        int i = pos.i + di[k];\n        int j = pos.j + dj[k];\n        if (i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] != '#') {\n            neighbors.push_back({i, j});\n        }\n    }\n    return neighbors;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Task {\n    vector<int> d;\n    vector<int> dependencies;\n    int status; // -1: not started, 0: started, 1: completed\n};\n\nstruct TeamMember {\n    vector<int> s; // estimated skill levels\n    int task; // current task being worked on, -1 if available\n    int endDay; // day when the current task will be completed\n};\n\nint main() {\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    vector<Task> tasks(N);\n    for (int i = 0; i < N; i++) {\n        tasks[i].d.resize(K);\n        for (int j = 0; j < K; j++) {\n            cin >> tasks[i].d[j];\n        }\n        tasks[i].status = -1;\n    }\n\n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        tasks[v - 1].dependencies.push_back(u - 1);\n    }\n\n    vector<TeamMember> teamMembers(M);\n    for (int i = 0; i < M; i++) {\n        teamMembers[i].s.resize(K, 0); // initialize estimated skill levels to 0\n        teamMembers[i].task = -1;\n        teamMembers[i].endDay = 0;\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n\n        // receive the list of team members who have completed their tasks\n        int n;\n        cin >> n;\n        if (n == -1) break;\n\n        vector<int> completedTeamMembers(n);\n        for (int i = 0; i < n; i++) {\n            cin >> completedTeamMembers[i];\n            completedTeamMembers[i]--;\n        }\n\n        // update task status and team member status\n        for (int teamMember : completedTeamMembers) {\n            if (teamMembers[teamMember].task != -1) {\n                tasks[teamMembers[teamMember].task].status = 1;\n                teamMembers[teamMember].task = -1;\n            }\n        }\n\n        // estimate skill levels of team members\n        for (int teamMember : completedTeamMembers) {\n            // TO DO: implement skill level estimation\n        }\n\n        // get available tasks\n        vector<int> availableTasks;\n        for (int i = 0; i < N; i++) {\n            if (tasks[i].status == -1) {\n                bool ok = true;\n                for (int dependency : tasks[i].dependencies) {\n                    if (tasks[dependency].status != 1) {\n                        ok = false;\n                        break;\n                    }\n                }\n                if (ok) availableTasks.push_back(i);\n            }\n        }\n\n        // assign tasks to available team members\n        vector<pair<int, int>> assignments;\n        for (int teamMember = 0; teamMember < M; teamMember++) {\n            if (teamMembers[teamMember].task == -1 && !availableTasks.empty()) {\n                // TO DO: implement task assignment heuristic\n                int task = availableTasks.back();\n                availableTasks.pop_back();\n                teamMembers[teamMember].task = task;\n                tasks[task].status = 0;\n                assignments.emplace_back(teamMember + 1, task + 1);\n            }\n        }\n\n        // output assignments\n        cout << assignments.size();\n        for (auto& assignment : assignments) {\n            cout << \" \" << assignment.first << \" \" << assignment.second;\n        }\n        cout << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Order {\n    int id;\n    int a, b, c, d;\n};\n\nint main() {\n    vector<Order> orders;\n    for (int i = 0; i < 1000; ++i) {\n        Order order;\n        order.id = i + 1;\n        cin >> order.a >> order.b >> order.c >> order.d;\n        orders.push_back(order);\n    }\n\n    // Improved initial solution using a greedy algorithm with a better heuristic\n    vector<Order> selectedOrders;\n    random_device rd;\n    mt19937 gen(rd());\n    shuffle(orders.begin(), orders.end(), gen);\n    for (int i = 0; i < 50; ++i) {\n        selectedOrders.push_back(orders[i]);\n    }\n\n    // Simplified simulated annealing to improve the solution\n    auto startTime = chrono::high_resolution_clock::now();\n    int iteration = 0;\n    while (chrono::duration_cast<chrono::seconds>(chrono::high_resolution_clock::now() - startTime).count() < 1.9) {\n        iteration++;\n        int i = uniform_int_distribution<int>(0, selectedOrders.size() - 1)(gen);\n        int j = uniform_int_distribution<int>(0, orders.size() - 1)(gen);\n        if (find_if(selectedOrders.begin(), selectedOrders.end(), [&](const Order& order) { return order.id == orders[j].id; }) == selectedOrders.end()) {\n            // Replace the i-th order with the j-th order\n            selectedOrders[i] = orders[j];\n        }\n        if (iteration % 100 == 0) {\n            // Check time limit every 100 iterations\n            if (chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - startTime).count() > 1900) {\n                break;\n            }\n        }\n    }\n\n    // Construct the delivery route\n    vector<pair<int, int>> route;\n    route.push_back({400, 400});\n    for (const auto& order : selectedOrders) {\n        route.push_back({order.a, order.b});\n        route.push_back({order.c, order.d});\n    }\n    route.push_back({400, 400});\n\n    // Output the solution\n    cout << selectedOrders.size() << \" \";\n    for (const auto& order : selectedOrders) {\n        cout << order.id << \" \";\n    }\n    cout << endl;\n    cout << route.size() << \" \";\n    for (const auto& point : route) {\n        cout << point.first << \" \" << point.second << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <cmath>\n#include <random>\n#include <cassert>\n\n// Union-Find data structure\nclass UnionFind {\npublic:\n    UnionFind(int n) : parent(n), rank(n, 0), size(n, 1) {\n        for (int i = 0; i < n; ++i) {\n            parent[i] = i;\n        }\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\n    void unite(int x, int y) {\n        int root_x = find(x);\n        int root_y = find(y);\n        if (root_x != root_y) {\n            if (rank[root_x] < rank[root_y]) {\n                parent[root_x] = root_y;\n                size[root_y] += size[root_x];\n            } else {\n                parent[root_y] = root_x;\n                size[root_x] += size[root_y];\n                if (rank[root_x] == rank[root_y]) {\n                    ++rank[root_x];\n                }\n            }\n        }\n    }\n\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n\n    int getSize(int x) {\n        return size[find(x)];\n    }\n\nprivate:\n    std::vector<int> parent;\n    std::vector<int> rank;\n    std::vector<int> size;\n};\n\nint main() {\n    const int N = 400;\n    const int M = 1995;\n\n    // Read vertex coordinates\n    std::vector<std::pair<int, int>> vertices(N);\n    for (auto& vertex : vertices) {\n        std::cin >> vertex.first >> vertex.second;\n    }\n\n    // Precompute Euclidean distances\n    std::vector<int> distances(M);\n    std::vector<std::pair<int, int>> edges(M);\n    for (int i = 0; i < M; ++i) {\n        std::cin >> edges[i].first >> edges[i].second;\n        int dx = vertices[edges[i].first].first - vertices[edges[i].second].first;\n        int dy = vertices[edges[i].first].second - vertices[edges[i].second].second;\n        distances[i] = std::round(std::sqrt(dx * dx + dy * dy));\n    }\n\n    // Initialize Union-Find data structure\n    UnionFind uf(N);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<double> dis(0.0, 1.0);\n\n    int count = 0;\n    for (int i = 0; i < M; ++i) {\n        int length;\n        std::cin >> length;\n\n        if (uf.same(edges[i].first, edges[i].second)) {\n            double prob = (length > 2 * distances[i]) ? 0.0000001 : (length > 1.5 * distances[i]) ? 0.00001 : 0.0001;\n            bool adopt = dis(gen) < prob;\n            std::cout << (adopt ? \"1\" : \"0\") << std::endl;\n            std::cout.flush();\n            if (adopt) {\n                uf.unite(edges[i].first, edges[i].second);\n                count++;\n            }\n        } else {\n            int size1 = uf.getSize(edges[i].first);\n            int size2 = uf.getSize(edges[i].second);\n            double prob = (length <= 1.001 * distances[i]) ? 1.0 : (size1 < N / 50 || size2 < N / 50) ? 0.999 : (length <= 1.01 * distances[i]) ? 0.995 : 0.95;\n            bool adopt = dis(gen) < prob;\n            std::cout << (adopt ? \"1\" : \"0\") << std::endl;\n            std::cout.flush();\n            if (adopt) {\n                uf.unite(edges[i].first, edges[i].second);\n                count++;\n            }\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 30;\nconst int DIR[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\nconst char DIR_CHAR[4] = {'u', 'd', 'l', 'r'};\nconst char MOVE_CHAR[4] = {'U', 'D', 'L', 'R'};\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nint grid[N][N]; // 0: passable, 1: impassable\nvector<Pet> pets;\nvector<Human> humans;\nint M;\n\nvoid bfs(int x, int y, vector<vector<bool>>& visited) {\n    queue<pair<int, int>> q;\n    q.emplace(x, y);\n    visited[x][y] = true;\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n        for (int i = 0; i < 4; ++i) {\n            int nx = x + DIR[i][0];\n            int ny = y + DIR[i][1];\n            if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0 && !visited[nx][ny]) {\n                visited[nx][ny] = true;\n                q.emplace(nx, ny);\n            }\n        }\n    }\n}\n\nchar getAction(int h) {\n    Human& human = humans[h];\n    int x = human.x;\n    int y = human.y;\n    // Try to move to an adjacent passable square\n    vector<pair<int, int>> validMoves;\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + DIR[i][0];\n        int ny = y + DIR[i][1];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0) {\n            bool petPresent = false;\n            for (const Pet& pet : pets) {\n                if (pet.x == nx && pet.y == ny) {\n                    petPresent = true;\n                    break;\n                }\n            }\n            if (!petPresent) {\n                bool humanPresent = false;\n                for (int j = 0; j < M; ++j) {\n                    if (j != h && humans[j].x == nx && humans[j].y == ny) {\n                        humanPresent = true;\n                        break;\n                    }\n                }\n                if (!humanPresent) {\n                    validMoves.emplace_back(nx, ny);\n                }\n            }\n        }\n    }\n    if (!validMoves.empty()) {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, validMoves.size() - 1);\n        int chosenMove = dis(gen);\n        int dx = validMoves[chosenMove].first - x;\n        int dy = validMoves[chosenMove].second - y;\n        if (dx == -1) return 'U';\n        if (dx == 1) return 'D';\n        if (dy == -1) return 'L';\n        if (dy == 1) return 'R';\n    }\n\n    // Make impassable\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + DIR[i][0];\n        int ny = y + DIR[i][1];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == 0) {\n            bool valid = true;\n            for (int j = 0; j < 4; ++j) {\n                int nnx = nx + DIR[j][0];\n                int nny = ny + DIR[j][1];\n                if (nnx >= 0 && nnx < N && nny >= 0 && nny < N) {\n                    for (const Pet& pet : pets) {\n                        if (pet.x == nnx && pet.y == nny) {\n                            valid = false;\n                            break;\n                        }\n                    }\n                }\n            }\n            if (valid) {\n                return DIR_CHAR[i];\n            }\n        }\n    }\n\n    return '.';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    cin >> N;\n    pets.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].type;\n        --pets[i].x;\n        --pets[i].y;\n    }\n    cin >> M;\n    humans.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].x >> humans[i].y;\n        --humans[i].x;\n        --humans[i].y;\n    }\n    for (int turn = 0; turn < 300; ++turn) {\n        string actions;\n        for (int h = 0; h < M; ++h) {\n            actions += getAction(h);\n        }\n        cout << actions << endl;\n        cout.flush();\n        // Read pet movements\n        for (int i = 0; i < N; ++i) {\n            string movement;\n            cin >> movement;\n            // Update pet positions\n            if (movement != \".\") {\n                for (char c : movement) {\n                    int dx = 0, dy = 0;\n                    if (c == 'U') dx = -1;\n                    if (c == 'D') dx = 1;\n                    if (c == 'L') dy = -1;\n                    if (c == 'R') dy = 1;\n                    pets[i].x += dx;\n                    pets[i].y += dy;\n                }\n            }\n        }\n        // Update human positions\n        for (int h = 0; h < M; ++h) {\n            char action = actions[h];\n            if (action == 'U') --humans[h].x;\n            if (action == 'D') ++humans[h].x;\n            if (action == 'L') --humans[h].y;\n            if (action == 'R') ++humans[h].y;\n        }\n    }\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Pos {\n    int x, y;\n};\n\nint main() {\n    int sx, sy, tx, ty;\n    double p;\n    cin >> sx >> sy >> tx >> ty >> p;\n\n    vector<string> h(20), v(20);\n    for (int i = 0; i < 20; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < 19; ++i) {\n        cin >> v[i];\n    }\n\n    // BFS to find a initial path\n    queue<Pos> q;\n    vector<vector<bool>> visited(20, vector<bool>(20, false));\n    q.push({sx, sy});\n    visited[sx][sy] = true;\n    vector<vector<Pos>> parent(20, vector<Pos>(20, {-1, -1}));\n    while (!q.empty()) {\n        Pos curr = q.front(); q.pop();\n        if (curr.x == tx && curr.y == ty) break;\n        // Explore neighbors\n        for (auto dir : {make_pair(0, 1), make_pair(0, -1), make_pair(1, 0), make_pair(-1, 0)}) {\n            int nx = curr.x + dir.first, ny = curr.y + dir.second;\n            if (nx >= 0 && nx < 20 && ny >= 0 && ny < 20 && !visited[nx][ny]) {\n                if (dir.first == 0 && dir.second == 1 && ny < 20 && h[curr.x][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == 0 && dir.second == -1 && ny >= 0 && h[curr.x][ny] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == 1 && dir.second == 0 && nx < 20 && v[curr.x][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                } else if (dir.first == -1 && dir.second == 0 && nx >= 0 && v[nx][curr.y] == '0') {\n                    q.push({nx, ny});\n                    visited[nx][ny] = true;\n                    parent[nx][ny] = curr;\n                }\n            }\n        }\n    }\n\n    // Reconstruct path\n    string path;\n    Pos curr = {tx, ty};\n    while (curr.x != sx || curr.y != sy) {\n        Pos prev = parent[curr.x][curr.y];\n        if (prev.x == curr.x - 1) path += 'D';\n        else if (prev.x == curr.x + 1) path += 'U';\n        else if (prev.y == curr.y - 1) path += 'R';\n        else if (prev.y == curr.y + 1) path += 'L';\n        curr = prev;\n    }\n    reverse(path.begin(), path.end());\n\n    // Ensure path only contains valid characters and is within length limits\n    string robustPath = path;\n    while (robustPath.size() <= 200) {\n        robustPath += path;\n    }\n    robustPath.resize(200);\n\n    // Validate and output\n    for (char c : robustPath) {\n        if (c != 'U' && c != 'D' && c != 'L' && c != 'R') {\n            cerr << \"Invalid character in path: \" << c << endl;\n            return 1; // Exit with error if invalid character found\n        }\n    }\n\n    cout << robustPath << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <random>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 30;\nconst int T = 100000;\n\nint tiles[N][N];\nint rotations[N][N];\nint 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};\nint di[4] = {0, -1, 0, 1};\nint dj[4] = {-1, 0, 1, 0};\n\nint traverse_loop(int i, int j, int d) {\n    int length = 0;\n    int si = i, sj = j, sd = d;\n    while (true) {\n        int t = tiles[i][j];\n        for (int k = 0; k < rotations[i][j]; k++) {\n            if (t >= 0 && t <= 3) t = (t + 1) % 4;\n            else if (t == 4 || t == 5) t = 4 + (t - 4 + 1) % 2;\n            else if (t == 6 || t == 7) t = 6 + (t - 6 + 1) % 2;\n        }\n        int d2 = to[t][d];\n        if (d2 == -1) return 0;\n        i += di[d2];\n        j += dj[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (i == si && j == sj && d == sd) return length;\n    }\n}\n\nint calculate_score() {\n    vector<int> loop_lengths;\n    bool visited[N][N] = {};\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (!visited[i][j]) {\n                for (int d = 0; d < 4; d++) {\n                    int length = traverse_loop(i, j, d);\n                    if (length > 0) {\n                        loop_lengths.push_back(length);\n                        int ti = i, tj = j, td = d;\n                        while (true) {\n                            visited[ti][tj] = true;\n                            int t = tiles[ti][tj];\n                            for (int k = 0; k < rotations[ti][tj]; k++) {\n                                if (t >= 0 && t <= 3) t = (t + 1) % 4;\n                                else if (t == 4 || t == 5) t = 4 + (t - 4 + 1) % 2;\n                                else if (t == 6 || t == 7) t = 6 + (t - 6 + 1) % 2;\n                            }\n                            int td2 = to[t][td];\n                            ti += di[td2];\n                            tj += dj[td2];\n                            td = (td2 + 2) % 4;\n                            if (ti == i && tj == j && td == d) break;\n                        }\n                        break;\n                    }\n                }\n            }\n        }\n    }\n    sort(loop_lengths.rbegin(), loop_lengths.rend());\n    if (loop_lengths.size() <= 1) return 0;\n    return loop_lengths[0] * loop_lengths[1];\n}\n\nvoid simulated_annealing() {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n    uniform_int_distribution<> rot_dis(0, 3);\n\n    double temperature = 1000;\n    int current_score = calculate_score();\n    while (temperature > 1) {\n        int i = dis(gen);\n        int j = dis(gen);\n        int original_rotation = rotations[i][j];\n        int new_rotation = (original_rotation + 1) % 4;\n        rotations[i][j] = new_rotation;\n        int new_score = calculate_score();\n        if (new_score > current_score) {\n            current_score = new_score;\n        } else {\n            if (exp((double)(new_score - current_score) / temperature) > (double)rand() / RAND_MAX) {\n                current_score = new_score;\n            } else {\n                rotations[i][j] = original_rotation;\n            }\n        }\n        temperature *= 0.99;\n    }\n}\n\nint main() {\n    for (int i = 0; i < N; i++) {\n        string line;\n        cin >> line;\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = line[j] - '0';\n        }\n    }\n\n    simulated_annealing();\n\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cout << rotations[i][j];\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nstruct Puzzle {\n    int N;\n    vector<vector<int>> tiles;\n    pair<int, int> empty;\n\n    Puzzle(int N) : N(N), tiles(N, vector<int>(N)) {}\n\n    bool isValidMove(char dir) {\n        int dx = 0, dy = 0;\n        if (dir == 'U') dx = -1;\n        if (dir == 'D') dx = 1;\n        if (dir == 'L') dy = -1;\n        if (dir == 'R') dy = 1;\n\n        int x = empty.first, y = empty.second;\n        int nx = x + dx, ny = y + dy;\n\n        return nx >= 0 && nx < N && ny >= 0 && ny < N;\n    }\n\n    void move(char dir) {\n        int dx = 0, dy = 0;\n        if (dir == 'U') dx = -1;\n        if (dir == 'D') dx = 1;\n        if (dir == 'L') dy = -1;\n        if (dir == 'R') dy = 1;\n\n        int x = empty.first, y = empty.second;\n        int nx = x + dx, ny = y + dy;\n\n        swap(tiles[x][y], tiles[nx][ny]);\n        empty = {nx, ny};\n    }\n\n    int evaluate() {\n        int score = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (tiles[i][j] != 0) {\n                    score += 1;\n                }\n            }\n        }\n        return score;\n    }\n};\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n\n    Puzzle puzzle(N);\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            int val = stoi(row.substr(j, 1), 0, 16);\n            puzzle.tiles[i][j] = val;\n            if (val == 0) {\n                puzzle.empty = {i, j};\n            }\n        }\n    }\n\n    string operations;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    double temperature = 1000.0;\n    double coolingRate = 0.99;\n    int maxAttempts = 100;\n\n    for (int i = 0; i < T; ++i) {\n        char dirs[] = {'U', 'D', 'L', 'R'};\n        char dir;\n        int attempts = 0;\n        do {\n            dir = dirs[dis(gen) % 4];\n            attempts++;\n        } while (!puzzle.isValidMove(dir) && attempts < maxAttempts);\n\n        if (puzzle.isValidMove(dir)) {\n            Puzzle newState = puzzle;\n            newState.move(dir);\n            int newScore = newState.evaluate();\n            int currentScore = puzzle.evaluate();\n\n            if (newScore > currentScore || exp((double)(newScore - currentScore) / temperature) > (double)rand() / RAND_MAX) {\n                puzzle = newState;\n                operations += dir;\n            }\n        }\n\n        temperature *= coolingRate;\n    }\n\n    cout << operations << endl;\n\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    long long x, y;\n};\n\nlong long cross(const Point& p1, const Point& p2) {\n    return p1.x * p2.y - p1.y * p2.x;\n}\n\nint main() {\n    int N, K;\n    cin >> N >> K;\n    vector<int> a(10);\n    for (int i = 0; i < 10; ++i) {\n        cin >> a[i];\n    }\n    vector<Point> strawberries(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> strawberries[i].x >> strawberries[i].y;\n    }\n\n    vector<pair<Point, Point>> cuts;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int i = 0; i < K; ++i) {\n        int best_idx1 = -1, best_idx2 = -1;\n        double best_score = -1.0;\n\n        for (int j = 0; j < 100; ++j) {\n            int idx1 = dis(gen);\n            int idx2 = dis(gen);\n            while (idx2 == idx1) {\n                idx2 = dis(gen);\n            }\n\n            // Calculate the score for the current cut\n            double score = 0.0;\n            // TO DO: implement the score calculation\n\n            if (score > best_score) {\n                best_score = score;\n                best_idx1 = idx1;\n                best_idx2 = idx2;\n            }\n        }\n\n        if (best_idx1 != -1 && best_idx2 != -1) {\n            Point p1 = strawberries[best_idx1];\n            Point p2 = strawberries[best_idx2];\n            cuts.emplace_back(p1, p2);\n        }\n    }\n\n    cout << cuts.size() << endl;\n    for (const auto& cut : cuts) {\n        cout << cut.first.x << \" \" << cut.first.y << \" \" << cut.second.x << \" \" << cut.second.y << endl;\n    }\n\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <random>\n#include <tuple>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nint N, M;\nvector<Point> dots;\nset<pair<int, int>> dot_set;\nvector<tuple<int, int, int, int, int, int, int, int>> operations;\n\nbool is_valid_rectangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (x1 == x2 || x1 == x3 || x1 == x4 || y1 == y2 || y1 == y3 || y1 == y4) {\n        return false;\n    }\n    if ((x1 == x3 && y1 == y4 && x2 == x4 && y2 == y3) && (abs(x1 - x2) == abs(y1 - y2))) {\n        if (dot_set.find({x1, y2}) != dot_set.end() && dot_set.find({x2, y1}) != dot_set.end() && dot_set.find({x3, y4}) != dot_set.end() && dot_set.find({x4, y3}) != dot_set.end()) {\n            // Check if there are no dots other than the four points on the perimeter\n            int min_x = min(x1, min(x2, min(x3, x4)));\n            int max_x = max(x1, max(x2, max(x3, x4)));\n            int min_y = min(y1, min(y2, min(y3, y4)));\n            int max_y = max(y1, max(y2, max(y3, y4)));\n            for (int i = min_x; i <= max_x; i++) {\n                for (int j = min_y; j <= max_y; j++) {\n                    if (dot_set.find({i, j}) != dot_set.end() && make_pair(i, j) != make_pair(x1, y1) && make_pair(i, j) != make_pair(x2, y2) && make_pair(i, j) != make_pair(x3, y3) && make_pair(i, j) != make_pair(x4, y4)) {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n    }\n    return false;\n}\n\nint main() {\n    cin >> N >> M;\n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        dots.push_back({x, y});\n        dot_set.insert({x, y});\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    int iter_count = 0;\n    while (iter_count < 100000 && (double)clock() / CLOCKS_PER_SEC < 4.5) {\n        int x1 = dis(gen);\n        int y1 = dis(gen);\n        if (dot_set.find({x1, y1}) != dot_set.end()) {\n            iter_count++;\n            continue;\n        }\n        for (int i = 0; i < dots.size(); i++) {\n            for (int j = i + 1; j < dots.size(); j++) {\n                int x2 = dots[i].x;\n                int y2 = dots[i].y;\n                int x3 = dots[j].x;\n                int y3 = dots[j].y;\n                int x4 = x1 + x3 - x2;\n                int y4 = y1 + y3 - y2;\n                if (x4 >= 0 && x4 < N && y4 >= 0 && y4 < N && dot_set.find({x4, y4}) != dot_set.end() && dot_set.find({x2, y3}) == dot_set.end() && dot_set.find({x3, y2}) == dot_set.end()) {\n                    if (is_valid_rectangle(x1, y1, x2, y2, x3, y3, x4, y4)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.emplace_back(x1, y1, x2, y2, x3, y3, x4, y4);\n                        iter_count = 0;\n                        break;\n                    }\n                }\n                x4 = x1 + x2 - x3;\n                y4 = y1 + y2 - y3;\n                if (x4 >= 0 && x4 < N && y4 >= 0 && y4 < N && dot_set.find({x4, y4}) != dot_set.end() && dot_set.find({x2, y3}) == dot_set.end() && dot_set.find({x3, y2}) == dot_set.end()) {\n                    if (is_valid_rectangle(x1, y1, x2, y2, x4, y4, x3, y3)) {\n                        dot_set.insert({x1, y1});\n                        dots.push_back({x1, y1});\n                        operations.emplace_back(x1, y1, x2, y2, x4, y4, x3, y3);\n                        iter_count = 0;\n                        break;\n                    }\n                }\n            }\n            if (iter_count == 0) {\n                break;\n            }\n        }\n        iter_count++;\n    }\n\n    cout << operations.size() << endl;\n    for (auto& op : operations) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << \" \" << get<4>(op) << \" \" << get<5>(op) << \" \" << get<6>(op) << \" \" << get<7>(op) << endl;\n    }\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nconst int N = 10;\nconst int flavors = 3;\n\nstruct CandyBox {\n    int grid[N][N];\n    int count[flavors + 1];\n\n    CandyBox() {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                grid[i][j] = 0;\n            }\n        }\n        for (int i = 1; i <= flavors; i++) {\n            count[i] = 0;\n        }\n    }\n\n    void placeCandy(int flavor, int pos) {\n        int emptyCount = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (grid[i][j] == 0) {\n                    emptyCount++;\n                    if (emptyCount == pos) {\n                        grid[i][j] = flavor;\n                        count[flavor]++;\n                        return;\n                    }\n                }\n            }\n        }\n    }\n\n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; j++) {\n                int writePos = 0;\n                for (int i = 0; i < N; i++) {\n                    if (grid[i][j] != 0) {\n                        grid[writePos++][j] = grid[i][j];\n                    }\n                }\n                for (int i = writePos; i < N; i++) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; j++) {\n                int writePos = N - 1;\n                for (int i = N - 1; i >= 0; i--) {\n                    if (grid[i][j] != 0) {\n                        grid[writePos--][j] = grid[i][j];\n                    }\n                }\n                for (int i = writePos; i >= 0; i--) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; i++) {\n                int writePos = 0;\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] != 0) {\n                        grid[i][writePos++] = grid[i][j];\n                    }\n                }\n                for (int j = writePos; j < N; j++) {\n                    grid[i][j] = 0;\n                }\n            }\n        } else if (dir == 'R') {\n            for (int i = 0; i < N; i++) {\n                int writePos = N - 1;\n                for (int j = N - 1; j >= 0; j--) {\n                    if (grid[i][j] != 0) {\n                        grid[i][writePos--] = grid[i][j];\n                    }\n                }\n                for (int j = writePos; j >= 0; j--) {\n                    grid[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    int evaluateScore() {\n        int score = 0;\n        for (int flavor = 1; flavor <= flavors; flavor++) {\n            vector<vector<bool>> visited(N, vector<bool>(N, false));\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] == flavor && !visited[i][j]) {\n                        int componentSize = 0;\n                        vector<pair<int, int>> stack = {{i, j}};\n                        visited[i][j] = true;\n                        while (!stack.empty()) {\n                            auto [x, y] = stack.back();\n                            stack.pop_back();\n                            componentSize++;\n                            for (auto [dx, dy] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                                int nx = x + dx;\n                                int ny = y + dy;\n                                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == flavor && !visited[nx][ny]) {\n                                    stack.emplace_back(nx, ny);\n                                    visited[nx][ny] = true;\n                                }\n                            }\n                        }\n                        score += componentSize * componentSize;\n                    }\n                }\n            }\n        }\n        int denominator = 0;\n        for (int i = 1; i <= flavors; i++) {\n            denominator += count[i] * count[i];\n        }\n        return denominator == 0 ? 0 : score / denominator;\n    }\n\n    int evaluateScoreWithClustering() {\n        int score = 0;\n        for (int flavor = 1; flavor <= flavors; flavor++) {\n            vector<vector<bool>> visited(N, vector<bool>(N, false));\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] == flavor && !visited[i][j]) {\n                        int componentSize = 0;\n                        vector<pair<int, int>> stack = {{i, j}};\n                        visited[i][j] = true;\n                        while (!stack.empty()) {\n                            auto [x, y] = stack.back();\n                            stack.pop_back();\n                            componentSize++;\n                            for (auto [dx, dy] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                                int nx = x + dx;\n                                int ny = y + dy;\n                                if (nx >= 0 && nx < N && ny >= 0 && ny < N && grid[nx][ny] == flavor && !visited[nx][ny]) {\n                                    stack.emplace_back(nx, ny);\n                                    visited[nx][ny] = true;\n                                }\n                            }\n                        }\n                        score += componentSize * componentSize;\n                        // clustering bonus\n                        if (componentSize > 1) {\n                            score += componentSize;\n                        }\n                    }\n                }\n            }\n        }\n        int denominator = 0;\n        for (int i = 1; i <= flavors; i++) {\n            denominator += count[i] * count[i];\n        }\n        return denominator == 0 ? 0 : score / denominator;\n    }\n};\n\nint main() {\n    vector<int> flavors(100);\n    for (int i = 0; i < 100; i++) {\n        cin >> flavors[i];\n    }\n\n    CandyBox box;\n    for (int t = 0; t < 100; t++) {\n        int pos;\n        cin >> pos;\n        box.placeCandy(flavors[t], pos);\n\n        if (t == 99) break; // no need to output for the last tilt\n\n        char bestDir = 'F';\n        int bestScore = -1;\n        for (char dir : {'F', 'B', 'L', 'R'}) {\n            CandyBox simBox = box;\n            simBox.tilt(dir);\n            int score = simBox.evaluateScoreWithClustering();\n            if (score > bestScore) {\n                bestScore = score;\n                bestDir = dir;\n            }\n        }\n        cout << bestDir << endl;\n        box.tilt(bestDir);\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <random>\n#include <algorithm>\n\nusing namespace std;\n\nint M;\ndouble eps;\nint N = 20;\n\nstring generateGk(int k) {\n    string gk(N * (N - 1) / 2, '0');\n    int count = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            int index = i * (N - 1) - i * (i + 1) / 2 + j - i - 1;\n            if (count < k) {\n                gk[index] = '1';\n                count++;\n            }\n        }\n    }\n    return gk;\n}\n\nint predictSk(const string& Hk, const vector<string>& G) {\n    int bestMatch = 0;\n    int minDistance = numeric_limits<int>::max();\n    for (int i = 0; i < M; ++i) {\n        int distance = 0;\n        for (int j = 0; j < N * (N - 1) / 2; ++j) {\n            distance += (Hk[j] != G[i][j]);\n        }\n        if (distance < minDistance) {\n            minDistance = distance;\n            bestMatch = i;\n        }\n    }\n    return bestMatch;\n}\n\nint main() {\n    cin >> M >> eps;\n    cout << N << endl;\n    vector<string> G(M);\n    for (int k = 0; k < M; ++k) {\n        G[k] = generateGk(k);\n        cout << G[k] << endl;\n    }\n    cout.flush();\n\n    for (int query = 0; query < 100; ++query) {\n        string Hk;\n        cin >> Hk;\n        int tk = predictSk(Hk, G);\n        cout << tk << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n\nint main() {\n    std::ios_base::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n\n    int N, M, D, K;\n    std::cin >> N >> M >> D >> K;\n\n    std::vector<int> edge(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        std::cin >> u >> v >> w;\n        edge[i] = i;\n    }\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        std::cin >> x >> y;\n    }\n\n    // Simple shuffle\n    for (int i = M - 1; i > 0; --i) {\n        int j = rand() % (i + 1);\n        std::swap(edge[i], edge[j]);\n    }\n\n    std::vector<int> repairDay(M);\n    for (int i = 0; i < M; ++i) {\n        repairDay[edge[i]] = i % D + 1;\n    }\n\n    for (int i = 0; i < M; ++i) {\n        std::cout << repairDay[i];\n        if (i < M - 1) std::cout << \" \";\n    }\n    std::cout << std::endl;\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <bitset>\n\nconst int MAX_D = 14;\nint D;\nstd::bitset<MAX_D> f[2][MAX_D][MAX_D];\nstd::bitset<MAX_D> r[2][MAX_D][MAX_D];\nint b[2][MAX_D * MAX_D * MAX_D];\n\nvoid input() {\n    std::cin >> D;\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            std::string s;\n            std::cin >> s;\n            for (int x = 0; x < D; ++x) {\n                f[i][z][x][x] = (s[x] == '1');\n            }\n        }\n        for (int z = 0; z < D; ++z) {\n            std::string s;\n            std::cin >> s;\n            for (int y = 0; y < D; ++y) {\n                r[i][z][y][y] = (s[y] == '1');\n            }\n        }\n    }\n}\n\nvoid solve() {\n    int n = 0;\n    for (int i = 0; i < 2; ++i) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    if (f[i][z][x][y] && r[i][z][y][x]) {\n                        b[i][x * D * D + y * D + z] = ++n;\n                    }\n                }\n            }\n        }\n    }\n\n    std::cout << n << std::endl;\n    for (int i = 0; i < D * D * D; ++i) {\n        std::cout << b[0][i] << \" \";\n    }\n    std::cout << std::endl;\n    for (int i = 0; i < D * D * D; ++i) {\n        std::cout << b[1][i] << \" \";\n    }\n    std::cout << std::endl;\n}\n\nint main() {\n    input();\n    solve();\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n    long long w;\n};\n\nstruct UnionFind {\n    vector<int> parent, rank;\n    UnionFind(int n) : parent(n, -1), rank(n, 0) {}\n    int find(int x) {\n        if (parent[x] == -1) return x;\n        return parent[x] = find(parent[x]);\n    }\n    void unionSet(int x, int y) {\n        int rootX = find(x), rootY = find(y);\n        if (rootX != rootY) {\n            if (rank[rootX] > rank[rootY]) {\n                parent[rootY] = rootX;\n            } else {\n                parent[rootX] = rootY;\n                if (rank[rootX] == rank[rootY]) rank[rootY]++;\n            }\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<pair<int, int>> vertices(N);\n    for (auto& [x, y] : vertices) {\n        cin >> x >> y;\n    }\n\n    vector<Edge> edges(M);\n    for (auto& [u, v, w] : edges) {\n        cin >> u >> v >> w;\n        u--; v--;\n    }\n\n    vector<pair<int, int>> residents(K);\n    for (auto& [a, b] : residents) {\n        cin >> a >> b;\n    }\n\n    // Minimum Spanning Tree\n    vector<bool> in_mst(M, false);\n    UnionFind uf(N);\n    {\n        sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n            return a.w < b.w;\n        });\n        for (auto& e : edges) {\n            if (uf.find(e.u) != uf.find(e.v)) {\n                uf.unionSet(e.u, e.v);\n                in_mst[&e - &edges[0]] = true;\n            }\n        }\n    }\n\n    // Resident Coverage\n    vector<int> output_strength(N, 0);\n    for (auto [a, b] : residents) {\n        int nearest_vertex = 0;\n        long long min_distance = (long long)1e18;\n        for (int i = 0; i < N; i++) {\n            auto [x, y] = vertices[i];\n            long long distance = (long long)(x - a) * (x - a) + (long long)(y - b) * (y - b);\n            if (distance < min_distance) {\n                min_distance = distance;\n                nearest_vertex = i;\n            }\n        }\n        output_strength[nearest_vertex] = max(output_strength[nearest_vertex], (int)ceil(sqrt(min_distance)) + 1);\n    }\n\n    // Graph Traversal\n    vector<bool> visited(N, false);\n    {\n        queue<int> q;\n        q.push(0);\n        visited[0] = true;\n        while (!q.empty()) {\n            int u = q.front(); q.pop();\n            for (int i = 0; i < M; i++) {\n                if (in_mst[i]) {\n                    auto& e = edges[i];\n                    if (e.u == u && !visited[e.v]) {\n                        visited[e.v] = true;\n                        output_strength[e.v] = max(output_strength[e.v], output_strength[u]);\n                        q.push(e.v);\n                    }\n                    if (e.v == u && !visited[e.u]) {\n                        visited[e.u] = true;\n                        output_strength[e.u] = max(output_strength[e.u], output_strength[u]);\n                        q.push(e.u);\n                    }\n                }\n            }\n        }\n    }\n\n    // Output\n    for (int p : output_strength) {\n        cout << p << \" \";\n    }\n    cout << \"\\n\";\n    for (auto& e : edges) {\n        cout << (in_mst[&e - &edges[0]] ? \"1\" : \"0\") << \" \";\n    }\n    cout << \"\\n\";\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n#include <tuple> // Include the necessary header for std::tuple\n\nusing namespace std;\n\nconst int N = 30;\nconst int dx[] = {-1, -1, 0, 0, 1, 1};\nconst int dy[] = {-1, 0, -1, 1, 0, 1};\n\nint main() {\n    vector<vector<int>> pyramid(N);\n    for (int i = 0; i < N; ++i) {\n        pyramid[i].resize(i + 1);\n        for (int j = 0; j <= i; ++j) {\n            cin >> pyramid[i][j];\n        }\n    }\n\n    vector<tuple<int, int, int, int>> operations;\n    for (int i = N - 1; i > 0; --i) {\n        for (int j = 0; j <= i; ++j) {\n            int x = i, y = j;\n            while (x > 0) {\n                int parent_x = x - 1;\n                int parent_y = y;\n                if (y > parent_x) {\n                    parent_y = y - 1;\n                }\n                if (pyramid[x][y] < pyramid[parent_x][parent_y]) {\n                    swap(pyramid[x][y], pyramid[parent_x][parent_y]);\n                    operations.emplace_back(x, y, parent_x, parent_y);\n                }\n                x = parent_x;\n                y = parent_y;\n            }\n        }\n    }\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << get<0>(op) << \" \" << get<1>(op) << \" \" << get<2>(op) << \" \" << get<3>(op) << endl;\n    }\n\n    return 0;\n}","toyota2023summer-final":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n\nusing namespace std;\n\nconst int D = 9;\nconst int directions[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nstruct Position {\n    int x, y;\n};\n\nint main() {\n    int N;\n    cin >> D >> N;\n\n    vector<vector<int>> grid(D, vector<int>(D, 0));\n    grid[0][(D - 1) / 2] = -1; // Entrance\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        grid[x][y] = -2; // Obstacle\n    }\n\n    vector<Position> containers;\n    unordered_set<int> containerSet;\n\n    for (int d = 0; d < D * D - 1 - N; ++d) {\n        int t;\n        cin >> t;\n\n        // Find a suitable position for the container using BFS\n        queue<Position> q;\n        vector<vector<bool>> visited(D, vector<bool>(D, false));\n        q.push({0, (D - 1) / 2});\n        visited[0][(D - 1) / 2] = true;\n\n        Position target;\n        bool found = false;\n\n        while (!q.empty()) {\n            Position p = q.front();\n            q.pop();\n\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + directions[i][0];\n                int ny = p.y + directions[i][1];\n\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !visited[nx][ny] && grid[nx][ny] == 0) {\n                    visited[nx][ny] = true;\n                    q.push({nx, ny});\n\n                    // Choose the last visited node as the target position\n                    target = {nx, ny};\n                    found = true;\n                }\n            }\n        }\n\n        if (found) {\n            grid[target.x][target.y] = t;\n            containers.push_back(target);\n            containerSet.insert(target.x * D + target.y);\n            cout << target.x << \" \" << target.y << endl;\n            cout.flush();\n        }\n    }\n\n    // Transport containers out\n    for (int i = 0; i < D * D - 1 - N; ++i) {\n        queue<Position> q;\n        vector<vector<bool>> visited(D, vector<bool>(D, false));\n        q.push({0, (D - 1) / 2});\n        visited[0][(D - 1) / 2] = true;\n\n        Position target;\n        int minNum = D * D;\n\n        while (!q.empty()) {\n            Position p = q.front();\n            q.pop();\n\n            for (int i = 0; i < 4; ++i) {\n                int nx = p.x + directions[i][0];\n                int ny = p.y + directions[i][1];\n\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !visited[nx][ny]) {\n                    if (grid[nx][ny] >= 0 && grid[nx][ny] < minNum) {\n                        minNum = grid[nx][ny];\n                        target = {nx, ny};\n                    }\n\n                    visited[nx][ny] = true;\n                    q.push({nx, ny});\n                }\n            }\n        }\n\n        if (minNum != D * D) {\n            cout << target.x << \" \" << target.y << endl;\n            grid[target.x][target.y] = 0;\n        }\n    }\n\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm> // Include the algorithm header\n\nusing namespace std;\n\nconst int N = 50;\nconst int M = 100;\n\nint grid[N][N];\nint output[N][N];\nunordered_map<int, pair<int, int>> seeds;\nunordered_set<int> adjacentColors[M + 1];\n\nvoid readInput() {\n    int n, m;\n    cin >> n >> m;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> grid[i][j];\n            if (seeds.find(grid[i][j]) == seeds.end()) {\n                seeds[grid[i][j]] = {i, j};\n            }\n            output[i][j] = 0; // Initialize output grid\n        }\n    }\n}\n\nvoid buildAdjacencyGraph() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int color = grid[i][j];\n            if (i > 0 && grid[i - 1][j] != color) {\n                adjacentColors[color].insert(grid[i - 1][j]);\n            }\n            if (j > 0 && grid[i][j - 1] != color) {\n                adjacentColors[color].insert(grid[i][j - 1]);\n            }\n            if (i < N - 1 && grid[i + 1][j] != color) {\n                adjacentColors[color].insert(grid[i + 1][j]);\n            }\n            if (j < N - 1 && grid[i][j + 1] != color) {\n                adjacentColors[color].insert(grid[i][j + 1]);\n            }\n        }\n    }\n}\n\nvoid processColors() {\n    vector<int> colors;\n    for (int i = 1; i <= M; i++) {\n        colors.push_back(i);\n    }\n    sort(colors.begin(), colors.end(), [&adjColors = adjacentColors](int a, int b) {\n        return adjColors[a].size() > adjColors[b].size();\n    });\n\n    for (int color : colors) {\n        int x = seeds[color].first;\n        int y = seeds[color].second;\n        output[x][y] = color;\n        queue<pair<int, int>> q;\n        q.push({x, y});\n        while (!q.empty()) {\n            x = q.front().first;\n            y = q.front().second;\n            q.pop();\n            if (x > 0 && grid[x - 1][y] == color && output[x - 1][y] == 0) {\n                output[x - 1][y] = color;\n                q.push({x - 1, y});\n            }\n            if (y > 0 && grid[x][y - 1] == color && output[x][y - 1] == 0) {\n                output[x][y - 1] = color;\n                q.push({x, y - 1});\n            }\n            if (x < N - 1 && grid[x + 1][y] == color && output[x + 1][y] == 0) {\n                output[x + 1][y] = color;\n                q.push({x + 1, y});\n            }\n            if (y < N - 1 && grid[x][y + 1] == color && output[x][y + 1] == 0) {\n                output[x][y + 1] = color;\n                q.push({x, y + 1});\n            }\n        }\n    }\n}\n\nvoid outputResult() {\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cout << output[i][j] << \" \";\n        }\n        cout << endl;\n    }\n}\n\nint main() {\n    readInput();\n    buildAdjacencyGraph();\n    processColors();\n    outputResult();\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n\nint main() {\n    int N, D, Q;\n    std::cin >> N >> D >> Q;\n\n    // Initialize random number generator\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> dis(0, N - 1);\n\n    // Estimate weights using a more sophisticated comparison strategy\n    std::vector<double> weights(N, 0.0);\n    for (int q = 0; q < Q; ++q) {\n        // Generate comparison subsets using a binary search-like approach\n        int i = dis(gen) % N;\n        int j = dis(gen) % N;\n        while (j == i) {\n            j = dis(gen) % N;\n        }\n\n        std::cout << \"1 1 \" << i << \" \" << j << std::endl;\n        char result;\n        std::cin >> result;\n\n        if (result == '<') {\n            weights[i] -= 1.0;\n            weights[j] += 1.0;\n        } else if (result == '>') {\n            weights[i] += 1.0;\n            weights[j] -= 1.0;\n        }\n    }\n\n    // Cluster or partition items into D subsets using a more advanced algorithm\n    std::vector<int> division(N);\n    std::vector<std::pair<double, int>> sorted_weights(N);\n    for (int i = 0; i < N; ++i) {\n        sorted_weights[i] = std::make_pair(weights[i], i);\n    }\n    std::sort(sorted_weights.begin(), sorted_weights.end());\n\n    int subset = 0;\n    for (int i = 0; i < N; ++i) {\n        division[sorted_weights[i].second] = subset;\n        subset = (subset + 1) % D;\n    }\n\n    // Output division\n    for (int i = 0; i < N; ++i) {\n        std::cout << division[i] << \" \";\n    }\n    std::cout << std::endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int n = 200;\nconst int m = 10;\n\nvector<int> stacks[m];\nbool carried_out[n + 1];\nvector<pair<int, int>> operations;\n\nvoid move_box(int v, int dest_stack) {\n    for (int i = 0; i < m; ++i) {\n        auto& stack = stacks[i];\n        if (find(stack.begin(), stack.end(), v) != stack.end()) {\n            int idx = distance(stack.begin(), find(stack.begin(), stack.end(), v));\n            int energy = stack.size() - idx;\n            operations.emplace_back(v, dest_stack + 1);\n            vector<int> temp(stack.begin() + idx, stack.end());\n            stack.erase(stack.begin() + idx, stack.end());\n            stacks[dest_stack].insert(stacks[dest_stack].end(), temp.begin(), temp.end());\n            return;\n        }\n    }\n}\n\nint main() {\n    int b[m][n / m];\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < n / m; ++j) {\n            cin >> b[i][j];\n            stacks[i].push_back(b[i][j]);\n        }\n    }\n\n    for (int v = 1; v <= n; ++v) {\n        int top_stack = -1;\n        for (int i = 0; i < m; ++i) {\n            if (!stacks[i].empty() && stacks[i].back() == v) {\n                top_stack = i;\n                break;\n            }\n        }\n\n        if (top_stack != -1) {\n            operations.emplace_back(v, 0);\n            carried_out[v] = true;\n            stacks[top_stack].pop_back();\n        } else {\n            // Find the stack containing v and move it to an appropriate stack\n            int src_stack = -1;\n            for (int i = 0; i < m; ++i) {\n                auto& stack = stacks[i];\n                auto it = find(stack.begin(), stack.end(), v);\n                if (it != stack.end()) {\n                    src_stack = i;\n                    break;\n                }\n            }\n\n            if (src_stack == -1) {\n                cerr << \"Box \" << v << \" not found.\" << endl;\n                return 1;\n            }\n\n            int dest_stack = -1;\n            int min_top = n + 1;\n            for (int i = 0; i < m; ++i) {\n                if (stacks[i].empty() || (stacks[i].back() > v && stacks[i].back() < min_top)) {\n                    dest_stack = i;\n                    min_top = stacks[i].empty() ? n + 1 : stacks[i].back();\n                }\n            }\n\n            if (dest_stack == -1) {\n                // If no suitable stack is found, just pick any non-empty stack\n                for (int i = 0; i < m; ++i) {\n                    if (!stacks[i].empty()) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n\n            move_box(v, dest_stack);\n            // After moving, check again if v is at the top\n            for (int i = 0; i < m; ++i) {\n                if (!stacks[i].empty() && stacks[i].back() == v) {\n                    operations.emplace_back(v, 0);\n                    carried_out[v] = true;\n                    stacks[i].pop_back();\n                    break;\n                }\n            }\n        }\n    }\n\n    for (const 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>\n#include <stack>\n#include <random>\n\nusing namespace std;\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<bool>> visited;\n\nvoid dfs(int i, int j, vector<char>& route) {\n    visited[i][j] = true;\n    int di[] = {0, 1, 0, -1};\n    int dj[] = {1, 0, -1, 0};\n    char dir[] = {'R', 'D', 'L', 'U'};\n\n    random_device rd;\n    mt19937 g(rd());\n    vector<int> directions = {0, 1, 2, 3};\n    shuffle(directions.begin(), directions.end(), g);\n\n    for (int k : directions) {\n        int i2 = i + di[k];\n        int j2 = j + dj[k];\n        if (0 <= i2 && i2 < N && 0 <= j2 && j2 < N && !visited[i2][j2]) {\n            if (di[k] == 0 && v[i][min(j, j2)] == '0' || dj[k] == 0 && h[min(i, i2)][j] == '0') {\n                route.push_back(dir[k]);\n                dfs(i2, j2, route);\n                route.push_back(dir[(k + 2) % 4]);\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> N;\n    h.resize(N - 1);\n    v.resize(N);\n    d.resize(N, vector<int>(N));\n    visited.resize(N, vector<bool>(N, false));\n\n    for (int i = 0; i < N - 1; i++) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\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<char> route;\n    dfs(0, 0, route);\n\n    // Simple route optimization: remove consecutive duplicates\n    string optimizedRoute;\n    for (char c : route) {\n        if (optimizedRoute.empty() || c != optimizedRoute.back()) {\n            optimizedRoute += c;\n        }\n    }\n\n    cout << optimizedRoute << endl;\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n#include <queue>\n\nusing namespace std;\n\nstruct Position {\n    int i, j;\n};\n\nstruct BeamSearchNode {\n    vector<Position> currentPos;\n    string S;\n    vector<pair<int, int>> operations;\n    int score;\n};\n\nstruct CompareNodes {\n    bool operator()(const BeamSearchNode& a, const BeamSearchNode& b) {\n        return a.score < b.score;\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n\n    vector<string> t(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> t[i];\n    }\n\n    unordered_map<char, vector<Position>> charPositions;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            charPositions[grid[i][j]].push_back({i, j});\n        }\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    priority_queue<BeamSearchNode, vector<BeamSearchNode>, CompareNodes> queue;\n    BeamSearchNode initialNode = {{{si, sj}}, \"\", {}, 0};\n    queue.push(initialNode);\n\n    vector<pair<int, int>> bestOperations;\n    int bestScore = -1e9;\n\n    for (int step = 0; step < 5000; ++step) {\n        if (queue.empty()) break;\n\n        BeamSearchNode node = queue.top();\n        queue.pop();\n\n        if (node.score > bestScore) {\n            bestScore = node.score;\n            bestOperations = node.operations;\n        }\n\n        int radius = min(N, 5);\n        for (int di = -radius; di <= radius; ++di) {\n            for (int dj = -radius; dj <= radius; ++dj) {\n                int i = node.currentPos.back().i + di;\n                int j = node.currentPos.back().j + dj;\n                if (i >= 0 && i < N && j >= 0 && j < N) {\n                    int cost = abs(di) + abs(dj) + 1;\n                    char c = grid[i][j];\n                    string newS = node.S + c;\n\n                    int score = 0;\n                    for (const auto& tk : t) {\n                        if (newS.size() <= tk.size() && tk.substr(0, newS.size()) == newS) {\n                            score += 1;\n                        }\n                    }\n\n                    BeamSearchNode newNode = {node.currentPos, newS, node.operations, node.score + score};\n                    newNode.currentPos.push_back({i, j});\n                    newNode.operations.push_back({i, j});\n\n                    if (newNode.operations.size() <= 5000) {\n                        queue.push(newNode);\n                    }\n                }\n            }\n        }\n    }\n\n    for (const auto& op : bestOperations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc030":"int main() {\n    read_input();\n    vector<vector<int>> estimated_oil_reserves(N, vector<int>(N, -1));\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dis(0, N - 1);\n\n    for (int i = 0; i < N * N; ++i) {\n        int x = dis(gen);\n        int y = dis(gen);\n        if (estimated_oil_reserves[x][y] == -1) {\n            drill(x, y);\n            // Update estimated_oil_reserves based on the response\n        }\n    }\n\n    // Generate a guess based on estimated_oil_reserves\n    vector<pair<int, int>> guess_squares;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (estimated_oil_reserves[i][j] > 0) {\n                guess_squares.emplace_back(i, j);\n            }\n        }\n    }\n    guess(guess_squares);\n\n    return 0;\n}","ahc031":"```cpp\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int W = 1000;\n\nstruct Rectangle {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    int D, N;\n    cin >> D >> N;\n\n    vector<vector<int>> areas(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> areas[d][k];\n        }\n    }\n\n    vector<vector<Rectangle>> rectangles(D, vector<Rectangle>(N));\n\n    // Initial placement for the first day\n    vector<pair<int, int>> sizes(N);\n    for (int k = 0; k < N; k++) {\n        sizes[k] = {areas[0][k], k};\n    }\n    sort(sizes.begin(), sizes.end());\n\n    int x = 0, y = 0;\n    for (auto [area, k] : sizes) {\n        int w = min(W - x, (int)sqrt(area));\n        int h = (area + w - 1) / w;\n        rectangles[0][k] = {x, y, x + w, y + h};\n        x += w;\n        if (x >= W) {\n            x = 0;\n            y += h;\n        }\n    }\n\n    // Subsequent days\n    for (int d = 1; d < D; d++) {\n        vector<pair<int, int>> sizes(N);\n        for (int k = 0; k < N; k++) {\n            sizes[k] = {areas[d][k], k};\n        }\n        sort(sizes.begin(), sizes.end());\n\n        for (auto [area, k] : sizes) {\n            Rectangle prev_rect = rectangles[d - 1][k];\n            int w = min(W - prev_rect.x1, (int)sqrt(area));\n            int h = (area + w - 1) / w;\n            rectangles[d][k] = {prev_rect.x1, prev_rect.y1, prev_rect.x1 + w, prev_rect.y1 + h};\n        }\n    }\n\n    // Output the rectangle coordinates\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cout << rectangles[d][k].x1 << \" \" << rectangles[d][k].y1 << \" \" << rectangles[d][k].x2 << \" \" << rectangles[d][k].y2 << endl;\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <queue>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int BEAM_WIDTH = 10;\n\nstruct Operation {\n    int stamp_id;\n    int x, y;\n};\n\nstruct BeamState {\n    vector<vector<int>> grid;\n    vector<Operation> operations;\n    int score;\n};\n\nstruct CompareBeamState {\n    bool operator()(const pair<int, BeamState>& a, const pair<int, BeamState>& b) {\n        return a.first < b.first;\n    }\n};\n\nint calculate_score(const vector<vector<int>>& grid) {\n    int score = 0;\n    for (const auto& row : grid) {\n        for (int value : row) {\n            score = (score + value % MOD) % MOD;\n        }\n    }\n    return score;\n}\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n\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    vector<vector<vector<int>>> stamps(M, vector<vector<int>>(3, vector<int>(3)));\n    for (int m = 0; m < M; ++m) {\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                cin >> stamps[m][i][j];\n            }\n        }\n    }\n\n    priority_queue<pair<int, BeamState>, vector<pair<int, BeamState>>, CompareBeamState> beam;\n    beam.push({calculate_score(grid), {grid, {}, calculate_score(grid)}});\n\n    for (int k = 0; k < K; ++k) {\n        priority_queue<pair<int, BeamState>, vector<pair<int, BeamState>>, CompareBeamState> new_beam;\n\n        while (!beam.empty()) {\n            auto state = beam.top().second;\n            beam.pop();\n\n            for (int stamp_id = 0; stamp_id < M; ++stamp_id) {\n                for (int x = 0; x <= N - 3; ++x) {\n                    for (int y = 0; y <= N - 3; ++y) {\n                        vector<vector<int>> new_grid = state.grid;\n                        for (int i = 0; i < 3; ++i) {\n                            for (int j = 0; j < 3; ++j) {\n                                new_grid[x + i][y + j] += stamps[stamp_id][i][j];\n                            }\n                        }\n                        int new_score = calculate_score(new_grid);\n                        vector<Operation> new_operations = state.operations;\n                        new_operations.push_back({stamp_id, x, y});\n\n                        if (new_beam.size() < BEAM_WIDTH) {\n                            new_beam.push({new_score, {new_grid, new_operations, new_score}});\n                        } else if (new_score > new_beam.top().first) {\n                            new_beam.pop();\n                            new_beam.push({new_score, {new_grid, new_operations, new_score}});\n                        }\n                    }\n                }\n            }\n        }\n\n        beam = new_beam;\n    }\n\n    auto best_state = beam.top().second;\n    cout << best_state.operations.size() << endl;\n    for (const auto& op : best_state.operations) {\n        cout << op.stamp_id << \" \" << op.x << \" \" << op.y << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURN = 10000;\n\nstruct Crane {\n    int x, y;\n    bool holding;\n    int container;\n};\n\nint grid[N][N];\nCrane cranes[N];\nvector<int> containersToDispatch[N];\nint turn = 0;\n\nvoid simulate() {\n    vector<string> operations(N, \"\");\n    // Simulate the container dispatch process\n    while (turn < MAX_TURN) {\n        // Bring in new containers\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][0] == -1 && !containersToDispatch[i].empty()) {\n                grid[i][0] = containersToDispatch[i].back();\n                containersToDispatch[i].pop_back();\n            }\n        }\n\n        // Determine the next action for each crane\n        for (int i = 0; i < N; ++i) {\n            char operation = '.';\n            // Improved logic to move cranes towards the dispatch gates\n            if (cranes[i].holding && cranes[i].y == N - 1) {\n                operation = 'Q';\n                grid[cranes[i].x][cranes[i].y] = cranes[i].container;\n                cranes[i].holding = false;\n            } else if (!cranes[i].holding && grid[cranes[i].x][cranes[i].y] != -1) {\n                operation = 'P';\n                cranes[i].container = grid[cranes[i].x][cranes[i].y];\n                grid[cranes[i].x][cranes[i].y] = -1;\n                cranes[i].holding = true;\n            } else if (cranes[i].holding && cranes[i].y < N - 1) {\n                operation = 'R';\n                cranes[i].y++;\n            } else if (!cranes[i].holding && cranes[i].y < N - 1 && grid[cranes[i].x][cranes[i].y + 1] == -1) {\n                operation = 'R';\n                cranes[i].y++;\n            }\n            operations[i] += operation;\n        }\n\n        // Dispatch containers\n        for (int i = 0; i < N; ++i) {\n            if (grid[i][N - 1] != -1) {\n                // Dispatch the container\n                grid[i][N - 1] = -1;\n            }\n        }\n\n        turn++;\n        bool allDone = true;\n        for (int i = 0; i < N; ++i) {\n            if (!containersToDispatch[i].empty()) {\n                allDone = false;\n                break;\n            }\n        }\n        if (allDone) {\n            break;\n        }\n    }\n\n    // Output the operations for each crane\n    for (int i = 0; i < N; ++i) {\n        while (operations[i].length() < turn) {\n            operations[i] += '.';\n        }\n        cout << operations[i] << endl;\n    }\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector<vector<int>> A(n, vector<int>(n));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> A[i][j];\n            containersToDispatch[i].push_back(A[i][j]);\n        }\n        reverse(containersToDispatch[i].begin(), containersToDispatch[i].end());\n    }\n\n    // Initialize the grid and cranes\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            grid[i][j] = -1;\n        }\n        cranes[i].x = i;\n        cranes[i].y = 0;\n        cranes[i].holding = false;\n    }\n\n    simulate();\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nint N;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nint h[20][20];\nint loaded = 0;\npair<int, int> pos = {0, 0};\n\nvoid load(int d) {\n    cout << \"+\" << d << endl;\n    h[pos.first][pos.second] -= d;\n    loaded += d;\n}\n\nvoid unload(int d) {\n    cout << \"-\" << d << endl;\n    h[pos.first][pos.second] += d;\n    loaded -= d;\n}\n\nvoid move(int d) {\n    cout << dir[d] << endl;\n    pos.first += dx[d];\n    pos.second += dy[d];\n}\n\nint main() {\n    cin >> N;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h[i][j];\n        }\n    }\n\n    // Greedy algorithm\n    priority_queue<pair<int, pair<int, int>>> pq;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (h[i][j] != 0) {\n                pq.push({abs(h[i][j]), {i, j}});\n            }\n        }\n    }\n\n    while (!pq.empty()) {\n        auto [val, pos2] = pq.top();\n        pq.pop();\n        int x = pos2.first, y = pos2.second;\n\n        // Move to (x, y)\n        int min_dist = abs(pos.first - x) + abs(pos.second - y);\n        while (pos.first != x || pos.second != y) {\n            for (int d = 0; d < 4; d++) {\n                int nx = pos.first + dx[d], ny = pos.second + dy[d];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N && abs(nx - x) + abs(ny - y) < min_dist) {\n                    move(d);\n                    min_dist = abs(pos.first - x) + abs(pos.second - y);\n                    break;\n                }\n            }\n        }\n\n        // Load/unload at (x, y)\n        if (h[x][y] > 0) {\n            load(min(h[x][y], 1000000));\n        } else if (h[x][y] < 0) {\n            if (loaded >= -h[x][y]) { // Check if there's enough soil to unload\n                unload(min(-h[x][y], loaded));\n            } else {\n                // If not enough soil, load the remaining height to make it 0\n                load(min(-h[x][y] - loaded, 1000000));\n                unload(loaded);\n            }\n        }\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n\nusing namespace std;\n\nstruct Seed {\n    int id;\n    vector<int> eval;\n    int value;\n};\n\nbool compareSeeds(const Seed& a, const Seed& b) {\n    return a.value > b.value;\n}\n\nint main() {\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seedCount = 2 * N * (N - 1);\n    vector<Seed> seeds(seedCount);\n\n    for (int i = 0; i < seedCount; i++) {\n        seeds[i].id = i;\n        seeds[i].eval.resize(M);\n        seeds[i].value = 0;\n\n        for (int j = 0; j < M; j++) {\n            cin >> seeds[i].eval[j];\n            seeds[i].value += seeds[i].eval[j];\n        }\n    }\n\n    sort(seeds.begin(), seeds.end(), compareSeeds);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    for (int t = 0; t < T; t++) {\n        vector<vector<int>> grid(N, vector<int>(N));\n        vector<Seed> selectedSeeds(N * N);\n\n        // Select top N*N seeds\n        for (int i = 0; i < N * N; i++) {\n            selectedSeeds[i] = seeds[i];\n        }\n\n        // Greedy initialization\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                grid[i][j] = i * N + j;\n            }\n        }\n\n        double temperature = 900.0;\n        double coolingRate = 0.99;\n\n        int currentScore = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (i < N - 1) currentScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i + 1][j]].value;\n                if (j < N - 1) currentScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i][j + 1]].value;\n            }\n        }\n\n        // Simulated annealing with local search\n        for (int iteration = 0; iteration < 20000; iteration++) {\n            int i1 = dis(gen), j1 = dis(gen);\n            int i2 = dis(gen), j2 = dis(gen);\n\n            // Local search with a larger neighborhood\n            int bestI = i1, bestJ = j1;\n            for (int di = -2; di <= 2; di++) {\n                for (int dj = -2; dj <= 2; dj++) {\n                    int ni = i1 + di, nj = j1 + dj;\n                    if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                        if (selectedSeeds[grid[ni][nj]].value > selectedSeeds[grid[bestI][bestJ]].value) {\n                            bestI = ni;\n                            bestJ = nj;\n                        }\n                    }\n                }\n            }\n\n            swap(grid[i1][j1], grid[bestI][bestJ]);\n\n            int newScore = 0;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (i < N - 1) newScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i + 1][j]].value;\n                    if (j < N - 1) newScore += selectedSeeds[grid[i][j]].value + selectedSeeds[grid[i][j + 1]].value;\n                }\n            }\n\n            if (newScore > currentScore || exp((newScore - currentScore) / temperature) > (double)rand() / RAND_MAX) {\n                currentScore = newScore;\n            } else {\n                swap(grid[i1][j1], grid[bestI][bestJ]);\n            }\n\n            temperature *= coolingRate;\n        }\n\n        // Output grid arrangement\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                else cout << endl;\n            }\n        }\n        cout.flush();\n\n        // Read new seeds\n        for (int i = 0; i < seedCount; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> seeds[i].eval[j];\n                seeds[i].value = 0;\n                for (int k = 0; k < M; k++) {\n                    seeds[i].value += seeds[i].eval[k];\n                }\n            }\n        }\n\n        sort(seeds.begin(), seeds.end(), compareSeeds);\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n\nint main() {\n    int N, M, V;\n    std::cin >> N >> M >> V;\n\n    std::vector<std::vector<int>> s(N, std::vector<int>(N));\n    std::vector<std::vector<int>> t(N, std::vector<int>(N));\n\n    for (int i = 0; i < N; ++i) {\n        std::string str;\n        std::cin >> str;\n        for (int j = 0; j < N; ++j) {\n            s[i][j] = str[j] - '0';\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        std::string str;\n        std::cin >> str;\n        for (int j = 0; j < N; ++j) {\n            t[i][j] = str[j] - '0';\n        }\n    }\n\n    // Design the robotic arm\n    int V_prime = std::min(V, M + 1);\n    std::cout << V_prime << std::endl;\n    for (int i = 1; i < V_prime; ++i) {\n        std::cout << 0 << \" \" << 1 << std::endl;\n    }\n\n    // Initial position of the root\n    int rx = N / 2, ry = N / 2;\n    std::cout << rx << \" \" << ry << std::endl;\n\n    // Sequence of operations\n    for (int turn = 0; turn < 100; ++turn) {\n        std::string op(2 * V_prime, '.');\n        // Simple random movement for demonstration\n        if (rx > 0 && rand() % 2) {\n            rx--;\n            op[0] = 'U';\n        } else if (rx < N - 1 && rand() % 2) {\n            rx++;\n            op[0] = 'D';\n        }\n        if (ry > 0 && rand() % 2) {\n            ry--;\n            op[0] = 'L';\n        } else if (ry < N - 1 && rand() % 2) {\n            ry++;\n            op[0] = 'R';\n        }\n\n        // Random rotation for demonstration\n        if (V_prime > 1 && rand() % 2) {\n            op[1] = 'L';\n        }\n\n        // Grab or release takoyaki for demonstration\n        if (rand() % 2) {\n            op[V_prime] = 'P';\n        }\n\n        std::cout << op << std::endl;\n    }\n\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cstddef>\n#include <random>\n\nstruct Point {\n    int x, y;\n};\n\nint countPoints(const std::vector<Point>& points, int minX, int maxX, int minY, int maxY) {\n    int count = 0;\n    for (const auto& point : points) {\n        if (point.x >= minX && point.x <= maxX && point.y >= minY && point.y <= maxY) {\n            count++;\n        }\n    }\n    return count;\n}\n\nint main() {\n    int N;\n    std::cin >> N;\n\n    std::vector<Point> mackerels(N);\n    std::vector<Point> sardines(N);\n\n    for (int i = 0; i < N; ++i) {\n        std::cin >> mackerels[i].x >> mackerels[i].y;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        std::cin >> sardines[i].x >> sardines[i].y;\n    }\n\n    int minX = std::min_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.x < b.x; })->x;\n    int maxX = std::max_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.x < b.x; })->x;\n    int minY = std::min_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.y < b.y; })->y;\n    int maxY = std::max_element(mackerels.begin(), mackerels.end(), [](const Point& a, const Point& b) { return a.y < b.y; })->y;\n\n    int bestScore = countPoints(mackerels, minX, maxX, minY, maxY) - countPoints(sardines, minX, maxX, minY, maxY);\n    std::vector<Point> bestPolygon = {{minX, minY}, {maxX, minY}, {maxX, maxY}, {minX, maxY}};\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> disX(minX, maxX);\n    std::uniform_int_distribution<> disY(minY, maxY);\n\n    int iterations = 20000;\n    for (int i = 0; i < iterations; ++i) {\n        int x1 = disX(gen);\n        int x2 = disX(gen);\n        int y1 = disY(gen);\n        int y2 = disY(gen);\n\n        if (x1 > x2) std::swap(x1, x2);\n        if (y1 > y2) std::swap(y1, y2);\n\n        int score = countPoints(mackerels, x1, x2, y1, y2) - countPoints(sardines, x1, x2, y1, y2);\n        if (score > bestScore) {\n            bestScore = score;\n            bestPolygon = {{x1, y1}, {x2, y1}, {x2, y2}, {x1, y2}};\n        }\n    }\n\n    std::cout << bestPolygon.size() << std::endl;\n    for (const auto& point : bestPolygon) {\n        std::cout << point.x << \" \" << point.y << std::endl;\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n\nstruct Rectangle {\n    int index;\n    int w, h;\n};\n\nstruct Placement {\n    int index;\n    int rotation;\n    char direction;\n    int reference;\n};\n\nbool compareRectangles(const Rectangle& a, const Rectangle& b) {\n    return std::max(a.w, a.h) > std::max(b.w, b.h);\n}\n\nint main() {\n    int N, T;\n    double sigma;\n    std::cin >> N >> T >> sigma;\n\n    std::vector<Rectangle> rectangles(N);\n    for (int i = 0; i < N; ++i) {\n        rectangles[i].index = i;\n        std::cin >> rectangles[i].w >> rectangles[i].h;\n    }\n\n    std::sort(rectangles.begin(), rectangles.end(), compareRectangles);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<> dis(0, 1);\n    std::uniform_int_distribution<> disN(N/2, N);\n\n    for (int t = 0; t < T; ++t) {\n        int n = disN(gen);\n        std::vector<Placement> placements;\n        std::vector<Rectangle> placedRectangles;\n\n        std::vector<Rectangle> selectedRectangles(N);\n        for (int i = 0; i < N; ++i) {\n            selectedRectangles[i] = rectangles[i];\n        }\n\n        std::sort(selectedRectangles.begin(), selectedRectangles.end(), [](const Rectangle& a, const Rectangle& b) {\n            return a.index < b.index;\n        });\n\n        for (int i = 0; i < N; ++i) {\n            if (i < n) {\n                Rectangle rect = selectedRectangles[i];\n                int rotation = dis(gen);\n                char direction = (dis(gen) == 0) ? 'U' : 'L';\n                int reference = (placedRectangles.size() == 0) ? -1 : (dis(gen) == 0) ? -1 : placedRectangles[dis(gen) % placedRectangles.size()].index;\n\n                if (rotation == 1) {\n                    std::swap(rect.w, rect.h);\n                }\n\n                placements.push_back({rect.index, rotation, direction, reference});\n\n                placedRectangles.push_back(rect);\n            }\n        }\n\n        std::cout << n << std::endl;\n        for (const auto& placement : placements) {\n            std::cout << placement.index << \" \" << placement.rotation << \" \" << placement.direction << \" \" << placement.reference << std::endl;\n        }\n\n        std::cout.flush();\n\n        int W, H;\n        std::cin >> W >> H;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n};\n\nint main() {\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<Edge> edges(M);\n    for (int i = 0; i < M; i++) {\n        cin >> edges[i].u >> edges[i].v;\n    }\n\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n\n    vector<int> parent(N, -1);\n    vector<vector<int>> graph(N);\n    for (const auto& edge : edges) {\n        graph[edge.u].push_back(edge.v);\n        graph[edge.v].push_back(edge.u);\n    }\n\n    // Perform a BFS traversal to construct the rooted trees\n    queue<int> q;\n    vector<bool> visited(N, false);\n    vector<int> roots;\n    for (int i = 0; i < N; i++) {\n        if (!visited[i]) {\n            roots.push_back(i);\n            q.push(i);\n            visited[i] = true;\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (int v : graph[u]) {\n                    if (!visited[v]) {\n                        visited[v] = true;\n                        parent[v] = u;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n\n    // Make sure the height constraint is satisfied\n    for (int i = 0; i < N; i++) {\n        if (i != roots[0] && parent[i] != -1) {\n            int height = 0;\n            int v = i;\n            while (v != roots[0]) {\n                height++;\n                v = parent[v];\n                if (height > H) {\n                    parent[i] = -1; // Make i a root if height exceeds H\n                    break;\n                }\n            }\n        }\n    }\n\n    // Output the parent of each vertex\n    for (int i = 0; i < N; i++) {\n        cout << parent[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n\nusing namespace std;\n\nconst int N = 20;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nint main() {\n    int n;\n    cin >> n;\n    vector<string> grid(n);\n    for (int i = 0; i < n; i++) {\n        cin >> grid[i];\n    }\n\n    vector<pair<char, int>> operations;\n    queue<pair<int, int>> oniQueue;\n\n    // Iterate through the grid to identify Oni positions\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            if (grid[i][j] == 'x') {\n                oniQueue.push({i, j});\n            }\n        }\n    }\n\n    while (!oniQueue.empty()) {\n        int x = oniQueue.front().first;\n        int y = oniQueue.front().second;\n        oniQueue.pop();\n\n        if (grid[x][y] != 'x') continue;\n\n        // Check if there is no Fukunokami in any direction\n        for (int k = 0; k < 4; k++) {\n            int count = 0;\n            int nx = x + dx[k];\n            int ny = y + dy[k];\n            while (nx >= 0 && nx < n && ny >= 0 && ny < n) {\n                if (grid[nx][ny] == 'o') break;\n                count++;\n                nx += dx[k];\n                ny += dy[k];\n            }\n\n            if (nx < 0 || nx >= n || ny < 0 || ny >= n) {\n                // Shift in the direction that does not contain a Fukunokami\n                if (k == 0) { // Up\n                    for (int i = 0; i <= x; i++) {\n                        operations.push_back({'U', y});\n                    }\n                    for (int i = 0; i <= x; i++) {\n                        operations.push_back({'D', y});\n                    }\n                } else if (k == 1) { // Down\n                    for (int i = x; i < n - 1; i++) {\n                        operations.push_back({'D', y});\n                    }\n                    for (int i = x; i < n - 1; i++) {\n                        operations.push_back({'U', y});\n                    }\n                } else if (k == 2) { // Left\n                    for (int i = 0; i <= y; i++) {\n                        operations.push_back({'L', x});\n                    }\n                    for (int i = 0; i <= y; i++) {\n                        operations.push_back({'R', x});\n                    }\n                } else if (k == 3) { // Right\n                    for (int i = y; i < n - 1; i++) {\n                        operations.push_back({'R', x});\n                    }\n                    for (int i = y; i < n - 1; i++) {\n                        operations.push_back({'L', x});\n                    }\n                }\n\n                // Update the grid to reflect the removal of the Oni\n                grid[x][y] = '.';\n                break;\n            }\n        }\n    }\n\n    // Output the sequence of operations\n    for (const auto& op : operations) {\n        cout << op.first << \" \" << op.second << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nint N, L;\nvector<int> T, a, b, cleaner_count;\n\nvoid init_simulate() {\n    cleaner_count.assign(N, 0);\n    int last = 0;\n    cleaner_count[0] = 1;\n    for (int t = 1; t < L; ++t) {\n        int next = (cleaner_count[last] % 2 == 0) ? b[last] : a[last];\n        cleaner_count[next]++;\n        last = next;\n    }\n}\n\nint get_error() {\n    int error = 0;\n    for (int i = 0; i < N; ++i) {\n        error += abs(cleaner_count[i] - T[i]);\n    }\n    return error;\n}\n\nint simulate(int i, int new_a, int new_b) {\n    int old_a = a[i], old_b = b[i];\n    a[i] = new_a;\n    b[i] = new_b;\n\n    vector<int> local_count = cleaner_count;\n    int last = i;\n    for (int t = 0; t < L; ++t) {\n        int next = (local_count[last] % 2 == 0) ? b[last] : a[last];\n        local_count[next]++;\n        local_count[last]--;\n        last = next;\n    }\n\n    int new_error = 0;\n    for (int i = 0; i < N; ++i) {\n        new_error += abs(local_count[i] - T[i]);\n    }\n\n    a[i] = old_a;\n    b[i] = old_b;\n\n    return new_error;\n}\n\nvoid optimize() {\n    random_device rd;\n    mt19937 mt(rd());\n    uniform_int_distribution<int> dist(0, N-1);\n    init_simulate();\n    int current_error = get_error();\n    int steps = 1500;\n    for (int step = 0; step < steps; ++step) {\n        int i = dist(mt);\n        int new_a = dist(mt), new_b = dist(mt);\n        int new_error = simulate(i, new_a, new_b);\n        if (new_error < current_error) {\n            a[i] = new_a;\n            b[i] = new_b;\n            current_error = new_error;\n            cleaner_count.assign(N, 0);\n            int last = 0;\n            cleaner_count[0] = 1;\n            for (int t = 1; t < L; ++t) {\n                int next = (cleaner_count[last] % 2 == 0) ? b[last] : a[last];\n                cleaner_count[next]++;\n                last = next;\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> N >> L;\n    T.resize(N);\n    a.resize(N);\n    b.resize(N);\n    cleaner_count.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> T[i];\n    }\n\n    for (int i = 0; i < N; ++i) {\n        a[i] = (i + 1) % N;\n        b[i] = (i + 2) % N;\n    }\n\n    optimize();\n\n    for (int i = 0; i < N; ++i) {\n        cout << a[i] << \" \" << b[i] << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cassert>\n\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double x, y;\n};\n\nstruct Edge {\n    int u, v;\n};\n\nint N, M, Q, L, W;\nvector<int> G;\nvector<City> cities;\nvector<vector<int>> groups;\nvector<vector<Edge>> edges;\n\nvoid readInput() {\n    cin >> N >> M >> Q >> L >> W;\n    G.resize(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n    cities.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> cities[i].lx >> cities[i].rx >> cities[i].ly >> cities[i].ry;\n        cities[i].id = i;\n        cities[i].x = (cities[i].lx + cities[i].rx) / 2.0;\n        cities[i].y = (cities[i].ly + cities[i].ry) / 2.0;\n    }\n}\n\nvoid initialGrouping() {\n    sort(cities.begin(), cities.end(), [](const City& a, const City& b) {\n        return make_pair(a.x, a.y) < make_pair(b.x, b.y);\n    });\n    groups.resize(M);\n    int start = 0;\n    for (int i = 0; i < M; ++i) {\n        groups[i].resize(G[i]);\n        for (int j = 0; j < G[i]; ++j) {\n            groups[i][j] = cities[start + j].id;\n        }\n        start += G[i];\n    }\n}\n\nvoid queryFortuneTeller(const vector<int>& group) {\n    if (group.size() <= 1) return;\n    vector<Edge> mstEdges;\n    if (group.size() <= L) {\n        cout << \"? \" << group.size();\n        for (int city : group) cout << \" \" << city;\n        cout << endl;\n        for (int i = 0; i < group.size() - 1; ++i) {\n            int u, v;\n            cin >> u >> v;\n            mstEdges.push_back({u, v});\n        }\n        edges.push_back(mstEdges);\n    } else {\n        // For larger groups, divide them into smaller subsets and query\n        for (size_t i = 0; i < group.size(); i += L - 1) {\n            vector<int> subset;\n            for (size_t j = i; j < min(i + L - 1, group.size()); ++j) {\n                subset.push_back(group[j]);\n            }\n            if (subset.size() > 1) {\n                cout << \"? \" << subset.size();\n                for (int city : subset) cout << \" \" << city;\n                cout << endl;\n                vector<Edge> subsetMstEdges;\n                for (int k = 0; k < subset.size() - 1; ++k) {\n                    int u, v;\n                    cin >> u >> v;\n                    subsetMstEdges.push_back({u, v});\n                }\n                mstEdges.insert(mstEdges.end(), subsetMstEdges.begin(), subsetMstEdges.end());\n            }\n        }\n        edges.push_back(mstEdges);\n    }\n}\n\nvoid buildRoads() {\n    edges.clear();\n    for (const auto& group : groups) {\n        queryFortuneTeller(group);\n    }\n}\n\nvoid outputAnswer() {\n    cout << \"!\" << endl;\n    for (size_t i = 0; i < groups.size(); ++i) {\n        for (int city : groups[i]) cout << city << \" \";\n        cout << endl;\n        for (const auto& edge : edges[i]) cout << edge.u << \" \" << edge.v << endl;\n    }\n}\n\nint main() {\n    readInput();\n    initialGrouping();\n    buildRoads();\n    outputAnswer();\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <utility>\n\nusing namespace std;\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n\n    vector<vector<int>> grid(N, vector<int>(N, 0)); // 0: empty, 1: block\n\n    struct Pos {\n        int x, y;\n    };\n\n    Pos pos;\n    cin >> pos.x >> pos.y;\n    vector<Pos> targets(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> targets[i].x >> targets[i].y;\n    }\n\n    int dx[] = {-1, 1, 0, 0};\n    int dy[] = {0, 0, -1, 1};\n    char dirChar[] = {'U', 'D', 'L', 'R'};\n\n    auto manhattanDistance = [](Pos a, Pos b) {\n        return abs(a.x - b.x) + abs(a.y - b.y);\n    };\n\n    auto slide = [&](int x, int y, int dir, Pos &end) {\n        int nx = x + dx[dir];\n        int ny = y + dy[dir];\n        while (0 <= nx && nx < N && 0 <= ny && ny < N && grid[nx][ny] == 0) {\n            x = nx;\n            y = ny;\n            nx += dx[dir];\n            ny += dy[dir];\n        }\n        end.x = x;\n        end.y = y;\n    };\n\n    for (int targetIndex = 0; targetIndex < M; ++targetIndex) {\n        Pos target = targets[targetIndex];\n        while (pos.x != target.x || pos.y != target.y) {\n            int bestDir = -1;\n            char bestAction = ' ';\n            Pos nextPos = pos;\n            int minDist = manhattanDistance(pos, target);\n\n            for (int dir = 0; dir < 4; ++dir) {\n                int nx = pos.x + dx[dir];\n                int ny = pos.y + dy[dir];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                    // Try Move\n                    if (grid[nx][ny] == 0) {\n                        int dist = manhattanDistance({nx, ny}, target);\n                        if (dist < minDist) {\n                            minDist = dist;\n                            bestDir = dir;\n                            bestAction = 'M';\n                            nextPos = {nx, ny};\n                        }\n                    }\n\n                    // Try Slide\n                    Pos slideEnd = pos;\n                    slide(pos.x, pos.y, dir, slideEnd);\n                    if (slideEnd.x != pos.x || slideEnd.y != pos.y) {\n                        int dist = manhattanDistance(slideEnd, target);\n                        if (dist < minDist && (slideEnd.x != target.x || slideEnd.y != target.y)) {\n                            minDist = dist;\n                            bestDir = dir;\n                            bestAction = 'S';\n                            nextPos = slideEnd;\n                        }\n                    }\n                }\n\n                // Try Alter\n                if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                    int originalBlock = grid[nx][ny];\n                    grid[nx][ny] = 1 - originalBlock;\n                    Pos slideEndAfterAlter = pos;\n                    slide(pos.x, pos.y, dir, slideEndAfterAlter);\n                    int dist = manhattanDistance(slideEndAfterAlter, target);\n                    if (dist < minDist && (slideEndAfterAlter.x != target.x || slideEndAfterAlter.y != target.y)) {\n                        minDist = dist;\n                        bestDir = dir;\n                        bestAction = 'A';\n                        nextPos = pos; // Alter doesn't change pos\n                    }\n                    grid[nx][ny] = originalBlock; // Revert\n                }\n            }\n\n            if (bestAction != ' ') {\n                cout << bestAction << \" \" << dirChar[bestDir] << endl;\n                if (bestAction == 'M') {\n                    pos = nextPos;\n                } else if (bestAction == 'S') {\n                    pos = nextPos;\n                } else if (bestAction == 'A') {\n                    int nx = pos.x + dx[bestDir];\n                    int ny = pos.y + dy[bestDir];\n                    grid[nx][ny] = 1 - grid[nx][ny];\n                }\n            } else {\n                // Fallback, should ideally not reach here\n                cout << \"M U\" << endl;\n            }\n        }\n    }\n\n    return 0;\n}"}}}