{"model_name":"codestral-2508","codes":{"1":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nstruct Rectangle {\n    int a, b, c, d; // Coordinates of the rectangle\n    int area;       // Area of the rectangle\n};\n\nstruct Company {\n    int x, y;       // Desired location\n    int r;          // Desired area\n};\n\ndouble satisfaction_level(const Rectangle& rect, const Company& company) {\n    if (rect.a > company.x || rect.c <= company.x || rect.b > company.y || rect.d <= company.y) {\n        return 0.0;\n    }\n    double s_i = rect.area;\n    double r_i = company.r;\n    double min_val = min(r_i, s_i);\n    double max_val = max(r_i, s_i);\n    double p_i = 1.0 - pow(1.0 - min_val / max_val, 2.0);\n    return p_i;\n}\n\nbool is_overlapping(const Rectangle& rect1, const Rectangle& rect2) {\n    return !(rect1.c <= rect2.a || rect2.c <= rect1.a || rect1.d <= rect2.b || rect2.d <= rect1.b);\n}\n\nvector<Rectangle> generate_initial_solution(const vector<Company>& companies) {\n    vector<Rectangle> rectangles;\n    for (const auto& company : companies) {\n        int width = static_cast<int>(sqrt(company.r));\n        int height = company.r / width;\n        if (width * height < company.r) {\n            height++;\n        }\n        int a = max(0, company.x - width / 2);\n        int b = max(0, company.y - height / 2);\n        int c = min(10000, a + width);\n        int d = min(10000, b + height);\n        Rectangle rect = {a, b, c, d, (c - a) * (d - b)};\n        rectangles.push_back(rect);\n    }\n    return rectangles;\n}\n\ndouble total_satisfaction(const vector<Rectangle>& rectangles, const vector<Company>& companies) {\n    double total = 0.0;\n    for (size_t i = 0; i < companies.size(); ++i) {\n        total += satisfaction_level(rectangles[i], companies[i]);\n    }\n    return total;\n}\n\nvector<Rectangle> simulated_annealing(const vector<Company>& companies, vector<Rectangle> initial_rectangles, double initial_temp, double cooling_rate, int iterations) {\n    vector<Rectangle> current_rectangles = initial_rectangles;\n    double current_satisfaction = total_satisfaction(current_rectangles, companies);\n    vector<Rectangle> best_rectangles = current_rectangles;\n    double best_satisfaction = current_satisfaction;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    for (double temp = initial_temp; temp > 1e-6; temp *= cooling_rate) {\n        for (int i = 0; i < iterations; ++i) {\n            vector<Rectangle> new_rectangles = current_rectangles;\n            int idx = dis(gen) * companies.size();\n            int delta_x = (dis(gen) * 2 - 1) * 10;\n            int delta_y = (dis(gen) * 2 - 1) * 10;\n            new_rectangles[idx].a = max(0, new_rectangles[idx].a + delta_x);\n            new_rectangles[idx].b = max(0, new_rectangles[idx].b + delta_y);\n            new_rectangles[idx].c = min(10000, new_rectangles[idx].c + delta_x);\n            new_rectangles[idx].d = min(10000, new_rectangles[idx].d + delta_y);\n            new_rectangles[idx].area = (new_rectangles[idx].c - new_rectangles[idx].a) * (new_rectangles[idx].d - new_rectangles[idx].b);\n\n            bool valid = true;\n            for (size_t j = 0; j < new_rectangles.size(); ++j) {\n                if (j != idx && is_overlapping(new_rectangles[idx], new_rectangles[j])) {\n                    valid = false;\n                    break;\n                }\n            }\n\n            if (valid) {\n                double new_satisfaction = total_satisfaction(new_rectangles, companies);\n                double delta = new_satisfaction - current_satisfaction;\n                if (delta > 0 || dis(gen) < exp(delta / temp)) {\n                    current_rectangles = new_rectangles;\n                    current_satisfaction = new_satisfaction;\n                    if (current_satisfaction > best_satisfaction) {\n                        best_rectangles = current_rectangles;\n                        best_satisfaction = current_satisfaction;\n                    }\n                }\n            }\n        }\n    }\n    return best_rectangles;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector<Company> companies(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n\n    vector<Rectangle> initial_rectangles = generate_initial_solution(companies);\n    vector<Rectangle> best_rectangles = simulated_annealing(companies, initial_rectangles, 1000.0, 0.99, 1000);\n\n    for (const auto& rect : best_rectangles) {\n        cout << rect.a << \" \" << rect.b << \" \" << rect.c << \" \" << rect.d << endl;\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <unordered_set>\n#include <queue>\n#include <utility>\n\nusing namespace std;\n\nconst int SIZE = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\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\nbool is_valid(int x, int y) {\n    return x >= 0 && x < SIZE && y >= 0 && y < SIZE;\n}\n\nstring find_max_score_path(int si, int sj, const vector<vector<int>>& tiles, const vector<vector<int>>& points) {\n    unordered_set<int> initial_visited_tiles;\n    initial_visited_tiles.insert(tiles[si][sj]);\n    queue<State> q;\n    q.emplace(si, sj, points[si][sj], \"\", initial_visited_tiles);\n\n    int max_score = points[si][sj];\n    string best_path;\n\n    while (!q.empty()) {\n        State current = q.front();\n        q.pop();\n\n        if (current.score > max_score) {\n            max_score = current.score;\n            best_path = current.path;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = current.x + dx[i];\n            int ny = current.y + dy[i];\n\n            if (is_valid(nx, ny) && current.visited_tiles.find(tiles[nx][ny]) == current.visited_tiles.end()) {\n                unordered_set<int> new_visited_tiles = current.visited_tiles;\n                new_visited_tiles.insert(tiles[nx][ny]);\n                q.emplace(nx, ny, current.score + points[nx][ny], current.path + dir[i], new_visited_tiles);\n            }\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> tiles(SIZE, vector<int>(SIZE));\n    for (int i = 0; i < SIZE; ++i) {\n        for (int j = 0; j < SIZE; ++j) {\n            cin >> tiles[i][j];\n        }\n    }\n\n    vector<vector<int>> points(SIZE, vector<int>(SIZE));\n    for (int i = 0; i < SIZE; ++i) {\n        for (int j = 0; j < SIZE; ++j) {\n            cin >> points[i][j];\n        }\n    }\n\n    string path = find_max_score_path(si, sj, tiles, points);\n    cout << path << endl;\n\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <unordered_map>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int QUERY_COUNT = 1000;\nconst double DECAY_FACTOR = 0.998;\nconst double SCORE_MULTIPLIER = 2312311;\n\nstruct Vertex {\n    int i, j;\n    Vertex(int i, int j) : i(i), j(j) {}\n    bool operator==(const Vertex& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Vertex> {\n        size_t operator()(const Vertex& v) const {\n            return hash<int>()(v.i) ^ hash<int>()(v.j);\n        }\n    };\n}\n\nstruct Edge {\n    Vertex from, to;\n    double estimated_length;\n    Edge(Vertex from, Vertex to, double estimated_length) : from(from), to(to), estimated_length(estimated_length) {}\n};\n\nclass Graph {\nprivate:\n    vector<vector<Vertex>> vertices;\n    unordered_map<Vertex, vector<Edge>> edges;\n    unordered_map<Vertex, unordered_map<Vertex, double>> estimated_lengths;\n\npublic:\n    Graph() {\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            vector<Vertex> row;\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                row.emplace_back(i, j);\n            }\n            vertices.push_back(row);\n        }\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                Vertex from(i, j);\n                if (i > 0) {\n                    Vertex to(i - 1, j);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (i < GRID_SIZE - 1) {\n                    Vertex to(i + 1, j);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (j > 0) {\n                    Vertex to(i, j - 1);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (j < GRID_SIZE - 1) {\n                    Vertex to(i, j + 1);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n            }\n        }\n    }\n\n    void update_estimated_lengths(const vector<Vertex>& path, double actual_length) {\n        double path_length = 0.0;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            path_length += estimated_lengths[path[k]][path[k + 1]];\n        }\n        double factor = actual_length / path_length;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            estimated_lengths[path[k]][path[k + 1]] *= factor;\n            estimated_lengths[path[k + 1]][path[k]] *= factor;\n        }\n    }\n\n    vector<Vertex> a_star_search(const Vertex& start, const Vertex& goal) {\n        auto heuristic = [&](const Vertex& v) {\n            return abs(v.i - goal.i) + abs(v.j - goal.j);\n        };\n\n        priority_queue<pair<double, Vertex>, vector<pair<double, Vertex>>, greater<pair<double, Vertex>>> open_set;\n        unordered_map<Vertex, Vertex> came_from;\n        unordered_map<Vertex, double> g_score;\n        unordered_map<Vertex, double> f_score;\n\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                Vertex v(i, j);\n                g_score[v] = numeric_limits<double>::infinity();\n                f_score[v] = numeric_limits<double>::infinity();\n            }\n        }\n\n        g_score[start] = 0.0;\n        f_score[start] = heuristic(start);\n        open_set.push({f_score[start], start});\n\n        while (!open_set.empty()) {\n            Vertex current = open_set.top().second;\n            open_set.pop();\n\n            if (current == goal) {\n                vector<Vertex> path;\n                while (came_from.find(current) != came_from.end()) {\n                    path.push_back(current);\n                    current = came_from[current];\n                }\n                path.push_back(start);\n                reverse(path.begin(), path.end());\n                return path;\n            }\n\n            for (const Edge& edge : edges[current]) {\n                Vertex neighbor = edge.to;\n                double tentative_g_score = g_score[current] + estimated_lengths[current][neighbor];\n\n                if (tentative_g_score < g_score[neighbor]) {\n                    came_from[neighbor] = current;\n                    g_score[neighbor] = tentative_g_score;\n                    f_score[neighbor] = g_score[neighbor] + heuristic(neighbor);\n                    open_set.push({f_score[neighbor], neighbor});\n                }\n            }\n        }\n\n        return {};\n    }\n\n    string path_to_string(const vector<Vertex>& path) {\n        stringstream ss;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            Vertex from = path[k];\n            Vertex to = path[k + 1];\n            if (to.i == from.i - 1) {\n                ss << \"U\";\n            } else if (to.i == from.i + 1) {\n                ss << \"D\";\n            } else if (to.j == from.j - 1) {\n                ss << \"L\";\n            } else if (to.j == from.j + 1) {\n                ss << \"R\";\n            }\n        }\n        return ss.str();\n    }\n};\n\nint main() {\n    Graph graph;\n    double score = 0.0;\n    int prev_result = 0;\n\n    for (int k = 0; k < QUERY_COUNT; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        Vertex start(si, sj);\n        Vertex goal(ti, tj);\n\n        vector<Vertex> path = graph.a_star_search(start, goal);\n        string path_str = graph.path_to_string(path);\n        cout << path_str << endl;\n        cout.flush();\n\n        int actual_length;\n        cin >> actual_length;\n\n        graph.update_estimated_lengths(path, actual_length);\n\n        double path_length = 0.0;\n        for (size_t i = 0; i < path.size() - 1; ++i) {\n            path_length += graph.estimated_lengths[path[i]][path[i + 1]];\n        }\n\n        double ratio = actual_length / path_length;\n        score = score * DECAY_FACTOR + ratio;\n    }\n\n    cout << round(SCORE_MULTIPLIER * score) << endl;\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <unordered_set>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int ALPHABET_SIZE = 8;\nconst char ALPHABET[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};\nconst char EMPTY = '.';\n\nstruct Matrix {\n    vector<vector<char>> data;\n\n    Matrix() : data(N, vector<char>(N, EMPTY)) {}\n\n    void randomize() {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, ALPHABET_SIZE - 1);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                data[i][j] = ALPHABET[dis(gen)];\n            }\n        }\n    }\n\n    void mutate(double rate) {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_real_distribution<> prob(0.0, 1.0);\n        uniform_int_distribution<> dis(0, ALPHABET_SIZE - 1);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (prob(gen) < rate) {\n                    data[i][j] = ALPHABET[dis(gen)];\n                }\n            }\n        }\n    }\n\n    bool is_subsequence(const string& s) {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                // Check horizontal subsequence\n                bool match = true;\n                for (int k = 0; k < s.size(); ++k) {\n                    if (data[i][(j + k) % N] != s[k]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) return true;\n\n                // Check vertical subsequence\n                match = true;\n                for (int k = 0; k < s.size(); ++k) {\n                    if (data[(i + k) % N][j] != s[k]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) return true;\n            }\n        }\n        return false;\n    }\n\n    int count_subsequences(const vector<string>& strings) {\n        int count = 0;\n        for (const auto& s : strings) {\n            if (is_subsequence(s)) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    int count_empty() {\n        int count = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (data[i][j] == EMPTY) {\n                    count++;\n                }\n            }\n        }\n        return count;\n    }\n\n    void print() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << data[i][j];\n            }\n            cout << endl;\n        }\n    }\n};\n\ndouble evaluate(const Matrix& matrix, const vector<string>& strings) {\n    int c = matrix.count_subsequences(strings);\n    if (c < strings.size()) {\n        return static_cast<double>(c) / strings.size();\n    } else {\n        int d = matrix.count_empty();\n        return static_cast<double>(2 * N * N) / (2 * N * N - d);\n    }\n}\n\nMatrix genetic_algorithm(const vector<string>& strings, int population_size, int generations, double mutation_rate) {\n    random_device rd;\n    mt19937 gen(rd());\n    vector<Matrix> population(population_size);\n\n    for (auto& matrix : population) {\n        matrix.randomize();\n    }\n\n    for (int gen = 0; gen < generations; ++gen) {\n        vector<double> fitness(population_size);\n        for (int i = 0; i < population_size; ++i) {\n            fitness[i] = evaluate(population[i], strings);\n        }\n\n        vector<Matrix> new_population;\n        for (int i = 0; i < population_size; ++i) {\n            uniform_int_distribution<> dis(0, population_size - 1);\n            int parent1 = dis(gen);\n            int parent2 = dis(gen);\n\n            Matrix child;\n            for (int x = 0; x < N; ++x) {\n                for (int y = 0; y < N; ++y) {\n                    if (fitness[parent1] > fitness[parent2]) {\n                        child.data[x][y] = population[parent1].data[x][y];\n                    } else {\n                        child.data[x][y] = population[parent2].data[x][y];\n                    }\n                }\n            }\n\n            child.mutate(mutation_rate);\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n    }\n\n    auto best = max_element(population.begin(), population.end(), [&](const Matrix& a, const Matrix& b) {\n        return evaluate(a, strings) < evaluate(b, strings);\n    });\n\n    return *best;\n}\n\nMatrix simulated_annealing(const vector<string>& strings, double initial_temp, double cooling_rate, int iterations) {\n    Matrix current;\n    current.randomize();\n    double current_score = evaluate(current, strings);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> prob(0.0, 1.0);\n\n    double temp = initial_temp;\n    for (int i = 0; i < iterations; ++i) {\n        Matrix neighbor = current;\n        neighbor.mutate(0.1);\n\n        double neighbor_score = evaluate(neighbor, strings);\n        double delta = neighbor_score - current_score;\n\n        if (delta > 0 || prob(gen) < exp(delta / temp)) {\n            current = neighbor;\n            current_score = neighbor_score;\n        }\n\n        temp *= cooling_rate;\n    }\n\n    return current;\n}\n\nint main() {\n    int M;\n    cin >> M;\n    vector<string> strings(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i];\n    }\n\n    // Run genetic algorithm\n    Matrix best_matrix = genetic_algorithm(strings, 50, 100, 0.01);\n\n    // Run simulated annealing\n    Matrix sa_matrix = simulated_annealing(strings, 1000.0, 0.99, 10000);\n\n    // Choose the best solution\n    if (evaluate(sa_matrix, strings) > evaluate(best_matrix, strings)) {\n        best_matrix = sa_matrix;\n    }\n\n    best_matrix.print();\n\n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int i, j;\n    Point(int i, int j) : i(i), j(j) {}\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.i) ^ hash<int>()(p.j);\n        }\n    };\n}\n\nclass PatrolRoute {\nprivate:\n    int N;\n    Point start;\n    vector<string> grid;\n    vector<vector<unordered_set<Point>>> visibility;\n    vector<Point> roadSquares;\n    vector<vector<int>> moveTime;\n    vector<vector<int>> dist;\n\n    void precomputeVisibility() {\n        visibility.resize(N, vector<unordered_set<Point>>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == '#') continue;\n                // Horizontal visibility\n                for (int k = j - 1; k >= 0; --k) {\n                    if (grid[i][k] == '#') break;\n                    visibility[i][j].insert(Point(i, k));\n                }\n                for (int k = j + 1; k < N; ++k) {\n                    if (grid[i][k] == '#') break;\n                    visibility[i][j].insert(Point(i, k));\n                }\n                // Vertical visibility\n                for (int k = i - 1; k >= 0; --k) {\n                    if (grid[k][j] == '#') break;\n                    visibility[i][j].insert(Point(k, j));\n                }\n                for (int k = i + 1; k < N; ++k) {\n                    if (grid[k][j] == '#') break;\n                    visibility[i][j].insert(Point(k, j));\n                }\n            }\n        }\n    }\n\n    void precomputeRoadSquares() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] != '#') {\n                    roadSquares.emplace_back(i, j);\n                }\n            }\n        }\n    }\n\n    void precomputeMoveTime() {\n        moveTime.resize(N, vector<int>(N, 0));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] != '#') {\n                    moveTime[i][j] = grid[i][j] - '0';\n                }\n            }\n        }\n    }\n\n    void precomputeDistances() {\n        dist.resize(N, vector<int>(N, -1));\n        queue<Point> q;\n        q.push(start);\n        dist[start.i][start.j] = 0;\n        while (!q.empty()) {\n            Point current = q.front();\n            q.pop();\n            for (const auto& neighbor : getNeighbors(current)) {\n                if (dist[neighbor.i][neighbor.j] == -1) {\n                    dist[neighbor.i][neighbor.j] = dist[current.i][current.j] + moveTime[neighbor.i][neighbor.j];\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n\n    vector<Point> getNeighbors(const Point& p) {\n        vector<Point> neighbors;\n        if (p.i > 0 && grid[p.i - 1][p.j] != '#') neighbors.emplace_back(p.i - 1, p.j);\n        if (p.i < N - 1 && grid[p.i + 1][p.j] != '#') neighbors.emplace_back(p.i + 1, p.j);\n        if (p.j > 0 && grid[p.i][p.j - 1] != '#') neighbors.emplace_back(p.i, p.j - 1);\n        if (p.j < N - 1 && grid[p.i][p.j + 1] != '#') neighbors.emplace_back(p.i, p.j + 1);\n        return neighbors;\n    }\n\n    vector<Point> greedyInitialization() {\n        unordered_set<Point> covered;\n        vector<Point> path;\n        Point current = start;\n        path.push_back(current);\n        covered.insert(visibility[current.i][current.j].begin(), visibility[current.i][current.j].end());\n        while (covered.size() < roadSquares.size()) {\n            Point next;\n            int maxNewCovered = -1;\n            for (const auto& neighbor : getNeighbors(current)) {\n                int newCovered = 0;\n                for (const auto& visible : visibility[neighbor.i][neighbor.j]) {\n                    if (covered.find(visible) == covered.end()) {\n                        newCovered++;\n                    }\n                }\n                if (newCovered > maxNewCovered) {\n                    maxNewCovered = newCovered;\n                    next = neighbor;\n                }\n            }\n            if (maxNewCovered == 0) break; // No progress, break to avoid infinite loop\n            current = next;\n            path.push_back(current);\n            covered.insert(visibility[current.i][current.j].begin(), visibility[current.i][current.j].end());\n        }\n        return path;\n    }\n\n    vector<Point> geneticAlgorithm(const vector<Point>& initialPath) {\n        vector<Point> bestPath = initialPath;\n        int bestScore = calculateScore(bestPath);\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, roadSquares.size() - 1);\n        for (int iter = 0; iter < 1000; ++iter) {\n            vector<Point> newPath = bestPath;\n            int a = dis(gen);\n            int b = dis(gen);\n            if (a > b) swap(a, b);\n            reverse(newPath.begin() + a, newPath.begin() + b);\n            int newScore = calculateScore(newPath);\n            if (newScore > bestScore) {\n                bestPath = newPath;\n                bestScore = newScore;\n            }\n        }\n        return bestPath;\n    }\n\n    int calculateScore(const vector<Point>& path) {\n        unordered_set<Point> covered;\n        for (const auto& point : path) {\n            covered.insert(visibility[point.i][point.j].begin(), visibility[point.i][point.j].end());\n        }\n        int v = covered.size();\n        int r = roadSquares.size();\n        if (v < r) {\n            return round(10000 * v / r);\n        } else {\n            int t = 0;\n            for (size_t i = 1; i < path.size(); ++i) {\n                t += moveTime[path[i].i][path[i].j];\n            }\n            return round(10000 + 10000000 * N / t);\n        }\n    }\n\npublic:\n    PatrolRoute(int N, int si, int sj, const vector<string>& grid) : N(N), start(si, sj), grid(grid) {\n        precomputeVisibility();\n        precomputeRoadSquares();\n        precomputeMoveTime();\n        precomputeDistances();\n    }\n\n    string findRoute() {\n        vector<Point> initialPath = greedyInitialization();\n        vector<Point> optimizedPath = geneticAlgorithm(initialPath);\n        string route;\n        for (size_t i = 1; i < optimizedPath.size(); ++i) {\n            Point prev = optimizedPath[i - 1];\n            Point curr = optimizedPath[i];\n            if (curr.i == prev.i - 1) route += 'U';\n            else if (curr.i == prev.i + 1) route += 'D';\n            else if (curr.j == prev.j - 1) route += 'L';\n            else if (curr.j == prev.j + 1) route += 'R';\n        }\n        return route;\n    }\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n    PatrolRoute patrolRoute(N, si, sj, grid);\n    cout << patrolRoute.findRoute() << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <unordered_set>\n#include <queue>\n#include <cmath>\n\nusing namespace std;\n\nstruct Task {\n    vector<int> required_skills;\n    vector<int> dependencies;\n    int duration;\n    bool completed;\n};\n\nstruct TeamMember {\n    vector<int> skills;\n    int current_task;\n    int days_left;\n};\n\nvector<Task> tasks;\nvector<TeamMember> team_members;\nvector<vector<int>> task_dependencies;\nvector<int> in_degree;\nvector<int> completed_tasks;\nvector<int> available_tasks;\n\nvoid initialize(int N, int M, int K, int R) {\n    tasks.resize(N);\n    team_members.resize(M);\n    task_dependencies.resize(N);\n    in_degree.resize(N, 0);\n    completed_tasks.resize(N, 0);\n    available_tasks.resize(N, 0);\n\n    for (int i = 0; i < N; ++i) {\n        tasks[i].required_skills.resize(K);\n        tasks[i].dependencies.clear();\n        tasks[i].duration = 0;\n        tasks[i].completed = false;\n    }\n\n    for (int i = 0; i < M; ++i) {\n        team_members[i].skills.resize(K, 0);\n        team_members[i].current_task = -1;\n        team_members[i].days_left = 0;\n    }\n\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        task_dependencies[u - 1].push_back(v - 1);\n        in_degree[v - 1]++;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        if (in_degree[i] == 0) {\n            available_tasks[i] = 1;\n        }\n    }\n}\n\nvoid update_skills(int member, const vector<int>& completed_tasks) {\n    for (int task : completed_tasks) {\n        for (int k = 0; k < team_members[member].skills.size(); ++k) {\n            team_members[member].skills[k] = max(team_members[member].skills[k], tasks[task].required_skills[k]);\n        }\n    }\n}\n\nint calculate_duration(int task, int member) {\n    int w = 0;\n    for (int k = 0; k < tasks[task].required_skills.size(); ++k) {\n        w += max(0, tasks[task].required_skills[k] - team_members[member].skills[k]);\n    }\n\n    if (w == 0) {\n        return 1;\n    } else {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(-3, 3);\n        int r = dis(gen);\n        return max(1, w + r);\n    }\n}\n\nvoid assign_tasks() {\n    vector<pair<int, int>> assignments;\n\n    for (int i = 0; i < team_members.size(); ++i) {\n        if (team_members[i].current_task == -1) {\n            for (int j = 0; j < tasks.size(); ++j) {\n                if (available_tasks[j] && !tasks[j].completed) {\n                    int duration = calculate_duration(j, i);\n                    if (duration < tasks[j].duration || tasks[j].duration == 0) {\n                        tasks[j].duration = duration;\n                        team_members[i].current_task = j;\n                        team_members[i].days_left = duration;\n                        assignments.emplace_back(i + 1, j + 1);\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    cout << assignments.size();\n    for (const auto& assignment : assignments) {\n        cout << \" \" << assignment.first << \" \" << assignment.second;\n    }\n    cout << endl;\n    cout.flush();\n}\n\nvoid process_completed_tasks(const vector<int>& completed_members) {\n    vector<int> completed_tasks;\n\n    for (int member : completed_members) {\n        int task = team_members[member - 1].current_task;\n        if (task != -1) {\n            tasks[task].completed = true;\n            completed_tasks.push_back(task);\n            team_members[member - 1].current_task = -1;\n            team_members[member - 1].days_left = 0;\n        }\n    }\n\n    for (int task : completed_tasks) {\n        for (int dependent_task : task_dependencies[task]) {\n            in_degree[dependent_task]--;\n            if (in_degree[dependent_task] == 0) {\n                available_tasks[dependent_task] = 1;\n            }\n        }\n    }\n\n    for (int member : completed_members) {\n        update_skills(member - 1, completed_tasks);\n    }\n}\n\nint main() {\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    initialize(N, M, K, R);\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> tasks[i].required_skills[j];\n        }\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n        assign_tasks();\n\n        int n;\n        cin >> n;\n        if (n == -1) {\n            break;\n        }\n\n        vector<int> completed_members(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> completed_members[i];\n        }\n\n        process_completed_tasks(completed_members);\n\n        if (all_of(tasks.begin(), tasks.end(), [](const Task& task) { return task.completed; })) {\n            break;\n        }\n\n        if (day >= 2000) {\n            break;\n        }\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <unordered_set>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nstruct Order {\n    Point restaurant;\n    Point destination;\n    Order(Point restaurant, Point destination) : restaurant(restaurant), destination(destination) {}\n};\n\nstruct Individual {\n    vector<int> orders;\n    vector<Point> route;\n    int fitness;\n};\n\nint manhattanDistance(const Point& a, const Point& b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nint calculateFitness(const Individual& individual, const vector<Order>& allOrders) {\n    int totalDistance = 0;\n    unordered_set<int> selectedOrders(individual.orders.begin(), individual.orders.end());\n\n    // Check if the route starts and ends at the office\n    if (individual.route.front() != Point(400, 400) || individual.route.back() != Point(400, 400)) {\n        return INT_MAX;\n    }\n\n    // Check if all selected orders are visited in the correct order\n    for (int i = 0; i < individual.orders.size(); ++i) {\n        int orderIndex = individual.orders[i];\n        const Order& order = allOrders[orderIndex];\n        bool restaurantVisited = false;\n        bool destinationVisited = false;\n\n        for (int j = 0; j < individual.route.size(); ++j) {\n            if (individual.route[j] == order.restaurant) {\n                restaurantVisited = true;\n            }\n            if (individual.route[j] == order.destination) {\n                if (!restaurantVisited) {\n                    return INT_MAX;\n                }\n                destinationVisited = true;\n            }\n        }\n\n        if (!restaurantVisited || !destinationVisited) {\n            return INT_MAX;\n        }\n    }\n\n    // Calculate total travel time\n    for (int i = 0; i < individual.route.size() - 1; ++i) {\n        totalDistance += manhattanDistance(individual.route[i], individual.route[i + 1]);\n    }\n\n    return totalDistance;\n}\n\nvector<Individual> initializePopulation(int populationSize, const vector<Order>& allOrders) {\n    vector<Individual> population;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n\n    for (int i = 0; i < populationSize; ++i) {\n        Individual individual;\n        unordered_set<int> selectedOrders;\n\n        // Select 50 unique orders\n        while (selectedOrders.size() < 50) {\n            int orderIndex = orderDist(gen);\n            selectedOrders.insert(orderIndex);\n        }\n\n        individual.orders.assign(selectedOrders.begin(), selectedOrders.end());\n\n        // Generate a random route\n        vector<Point> route;\n        route.push_back(Point(400, 400)); // Start at the office\n\n        for (int orderIndex : individual.orders) {\n            const Order& order = allOrders[orderIndex];\n            route.push_back(order.restaurant);\n            route.push_back(order.destination);\n        }\n\n        route.push_back(Point(400, 400)); // End at the office\n\n        individual.route = route;\n        individual.fitness = calculateFitness(individual, allOrders);\n        population.push_back(individual);\n    }\n\n    return population;\n}\n\nIndividual selectParent(const vector<Individual>& population) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dist(0, population.size() - 1);\n\n    int index1 = dist(gen);\n    int index2 = dist(gen);\n\n    return population[index1].fitness < population[index2].fitness ? population[index1] : population[index2];\n}\n\nIndividual crossover(const Individual& parent1, const Individual& parent2, const vector<Order>& allOrders) {\n    Individual child;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dist(0, 49);\n\n    // Select a random subset of orders from parent1\n    unordered_set<int> selectedOrders(parent1.orders.begin(), parent1.orders.begin() + dist(gen));\n\n    // Add the remaining orders from parent2\n    for (int orderIndex : parent2.orders) {\n        if (selectedOrders.size() >= 50) break;\n        if (selectedOrders.find(orderIndex) == selectedOrders.end()) {\n            selectedOrders.insert(orderIndex);\n        }\n    }\n\n    child.orders.assign(selectedOrders.begin(), selectedOrders.end());\n\n    // Generate a random route\n    vector<Point> route;\n    route.push_back(Point(400, 400)); // Start at the office\n\n    for (int orderIndex : child.orders) {\n        const Order& order = allOrders[orderIndex];\n        route.push_back(order.restaurant);\n        route.push_back(order.destination);\n    }\n\n    route.push_back(Point(400, 400)); // End at the office\n\n    child.route = route;\n    child.fitness = calculateFitness(child, allOrders);\n\n    return child;\n}\n\nvoid mutate(Individual& individual, const vector<Order>& allOrders) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n    uniform_int_distribution<> mutationDist(0, 1);\n\n    // Mutate orders\n    for (int& orderIndex : individual.orders) {\n        if (mutationDist(gen) == 0) {\n            orderIndex = orderDist(gen);\n        }\n    }\n\n    // Mutate route\n    for (int i = 1; i < individual.route.size() - 1; ++i) {\n        if (mutationDist(gen) == 0) {\n            int j = uniform_int_distribution<>(1, individual.route.size() - 2)(gen);\n            swap(individual.route[i], individual.route[j]);\n        }\n    }\n\n    individual.fitness = calculateFitness(individual, allOrders);\n}\n\nvector<Individual> evolvePopulation(vector<Individual>& population, const vector<Order>& allOrders) {\n    vector<Individual> newPopulation;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> mutationRate(0.0, 1.0);\n\n    for (int i = 0; i < population.size(); ++i) {\n        Individual parent1 = selectParent(population);\n        Individual parent2 = selectParent(population);\n        Individual child = crossover(parent1, parent2, allOrders);\n\n        if (mutationRate(gen) < 0.1) {\n            mutate(child, allOrders);\n        }\n\n        newPopulation.push_back(child);\n    }\n\n    return newPopulation;\n}\n\nint main() {\n    vector<Order> allOrders;\n    for (int i = 0; i < 1000; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        allOrders.emplace_back(Point(a, b), Point(c, d));\n    }\n\n    const int populationSize = 100;\n    const int generations = 1000;\n\n    vector<Individual> population = initializePopulation(populationSize, allOrders);\n\n    for (int generation = 0; generation < generations; ++generation) {\n        population = evolvePopulation(population, allOrders);\n\n        // Find the best individual in the current population\n        Individual bestIndividual = *min_element(population.begin(), population.end(),\n            [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; });\n\n        cout << \"Generation \" << generation << \": Best Fitness = \" << bestIndividual.fitness << endl;\n    }\n\n    // Find the best individual in the final population\n    Individual bestIndividual = *min_element(population.begin(), population.end(),\n        [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; });\n\n    // Output the best solution\n    cout << bestIndividual.orders.size() << \" \";\n    for (int orderIndex : bestIndividual.orders) {\n        cout << orderIndex + 1 << \" \";\n    }\n    cout << endl;\n\n    cout << bestIndividual.route.size() << \" \";\n    for (const Point& point : bestIndividual.route) {\n        cout << point.x << \" \" << point.y << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <atcoder/dsu>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v;\n    double d; // Euclidean distance rounded to the nearest integer\n    int index; // Original index to keep track of the order\n};\n\nint main() {\n    int N = 400;\n    int M = 1995;\n\n    vector<pair<int, int>> coordinates(N);\n    vector<Edge> edges(M);\n\n    // Read coordinates\n    for (int i = 0; i < N; ++i) {\n        cin >> coordinates[i].first >> coordinates[i].second;\n    }\n\n    // Read edges and compute d_i\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        edges[i].index = i;\n        int dx = coordinates[edges[i].u].first - coordinates[edges[i].v].first;\n        int dy = coordinates[edges[i].u].second - coordinates[edges[i].v].second;\n        edges[i].d = round(sqrt(dx * dx + dy * dy));\n    }\n\n    // Sort edges by d_i in ascending order\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.d < b.d;\n    });\n\n    dsu uf(N);\n    vector<bool> adopted(M, false);\n\n    // Process edges in order of increasing d_i\n    for (const Edge& edge : edges) {\n        int l;\n        cin >> l;\n        if (!uf.same(edge.u, edge.v)) {\n            uf.merge(edge.u, edge.v);\n            adopted[edge.index] = true;\n            cout << \"1\" << endl;\n        } else {\n            cout << \"0\" << endl;\n        }\n        cout.flush();\n    }\n\n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n#include <cmath>\n#include <unordered_set>\n#include <map>\n#include <cassert>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int TURNS = 300;\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nstruct GridState {\n    vector<vector<bool>> passable;\n    vector<Pet> pets;\n    vector<Human> humans;\n};\n\nvector<vector<int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nvector<vector<int>> bfs(const GridState& state, int startX, int startY) {\n    vector<vector<int>> distance(GRID_SIZE, vector<int>(GRID_SIZE, -1));\n    queue<pair<int, int>> q;\n    q.push({startX, startY});\n    distance[startX][startY] = 0;\n\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n\n        for (auto [dx, dy] : directions) {\n            int nx = x + dx;\n            int ny = y + dy;\n            if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny] && distance[nx][ny] == -1) {\n                distance[nx][ny] = distance[x][y] + 1;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return distance;\n}\n\nvector<pair<int, int>> findReachableArea(const GridState& state, int humanIndex) {\n    auto [hx, hy] = state.humans[humanIndex];\n    auto distance = bfs(state, hx, hy);\n    vector<pair<int, int>> reachableArea;\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (distance[i][j] != -1) {\n                reachableArea.emplace_back(i, j);\n            }\n        }\n    }\n    return reachableArea;\n}\n\nint countPetsInArea(const GridState& state, const vector<pair<int, int>>& area) {\n    unordered_set<string> petPositions;\n    for (const auto& pet : state.pets) {\n        petPositions.insert(to_string(pet.x) + \",\" + to_string(pet.y));\n    }\n    int count = 0;\n    for (const auto& [x, y] : area) {\n        if (petPositions.count(to_string(x) + \",\" + to_string(y))) {\n            count++;\n        }\n    }\n    return count;\n}\n\ndouble calculateSatisfaction(const GridState& state, int humanIndex) {\n    auto reachableArea = findReachableArea(state, humanIndex);\n    int areaSize = reachableArea.size();\n    int petCount = countPetsInArea(state, reachableArea);\n    return (areaSize / 900.0) * pow(2, -petCount);\n}\n\nvector<pair<int, int>> findBestSquareToBlock(const GridState& state, int humanIndex) {\n    auto [hx, hy] = state.humans[humanIndex];\n    vector<pair<int, int>> candidates;\n    for (auto [dx, dy] : directions) {\n        int nx = hx + dx;\n        int ny = hy + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n            bool hasPetAdjacent = false;\n            for (auto [adx, ady] : directions) {\n                int anx = nx + adx;\n                int any = ny + ady;\n                if (anx >= 0 && anx < GRID_SIZE && any >= 0 && any < GRID_SIZE) {\n                    for (const auto& pet : state.pets) {\n                        if (pet.x == anx && pet.y == any) {\n                            hasPetAdjacent = true;\n                            break;\n                        }\n                    }\n                }\n                if (hasPetAdjacent) break;\n            }\n            if (!hasPetAdjacent) {\n                candidates.emplace_back(nx, ny);\n            }\n        }\n    }\n    if (candidates.empty()) {\n        return {};\n    }\n    vector<double> scores;\n    for (const auto& [nx, ny] : candidates) {\n        GridState newState = state;\n        newState.passable[nx][ny] = false;\n        auto reachableArea = findReachableArea(newState, humanIndex);\n        int areaSize = reachableArea.size();\n        int petCount = countPetsInArea(newState, reachableArea);\n        scores.push_back((areaSize / 900.0) * pow(2, -petCount));\n    }\n    int bestIndex = max_element(scores.begin(), scores.end()) - scores.begin();\n    return {candidates[bestIndex]};\n}\n\nvector<pair<int, int>> findBestMove(const GridState& state, int humanIndex) {\n    auto [hx, hy] = state.humans[humanIndex];\n    vector<pair<int, int>> candidates;\n    for (auto [dx, dy] : directions) {\n        int nx = hx + dx;\n        int ny = hy + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n            candidates.emplace_back(nx, ny);\n        }\n    }\n    if (candidates.empty()) {\n        return {};\n    }\n    vector<double> scores;\n    for (const auto& [nx, ny] : candidates) {\n        GridState newState = state;\n        newState.humans[humanIndex] = {nx, ny};\n        auto reachableArea = findReachableArea(newState, humanIndex);\n        int areaSize = reachableArea.size();\n        int petCount = countPetsInArea(newState, reachableArea);\n        scores.push_back((areaSize / 900.0) * pow(2, -petCount));\n    }\n    int bestIndex = max_element(scores.begin(), scores.end()) - scores.begin();\n    return {candidates[bestIndex]};\n}\n\nstring decideAction(const GridState& state, int humanIndex) {\n    auto [hx, hy] = state.humans[humanIndex];\n    auto blockSquares = findBestSquareToBlock(state, humanIndex);\n    auto moveSquares = findBestMove(state, humanIndex);\n\n    double currentSatisfaction = calculateSatisfaction(state, humanIndex);\n\n    double blockSatisfaction = -1;\n    if (!blockSquares.empty()) {\n        GridState newState = state;\n        auto [nx, ny] = blockSquares[0];\n        newState.passable[nx][ny] = false;\n        blockSatisfaction = calculateSatisfaction(newState, humanIndex);\n    }\n\n    double moveSatisfaction = -1;\n    if (!moveSquares.empty()) {\n        GridState newState = state;\n        auto [nx, ny] = moveSquares[0];\n        newState.humans[humanIndex] = {nx, ny};\n        moveSatisfaction = calculateSatisfaction(newState, humanIndex);\n    }\n\n    if (blockSatisfaction > currentSatisfaction && blockSatisfaction >= moveSatisfaction) {\n        auto [nx, ny] = blockSquares[0];\n        if (nx == hx - 1 && ny == hy) return \"u\";\n        if (nx == hx + 1 && ny == hy) return \"d\";\n        if (nx == hx && ny == hy - 1) return \"l\";\n        if (nx == hx && ny == hy + 1) return \"r\";\n    } else if (moveSatisfaction > currentSatisfaction && moveSatisfaction >= blockSatisfaction) {\n        auto [nx, ny] = moveSquares[0];\n        if (nx == hx - 1 && ny == hy) return \"U\";\n        if (nx == hx + 1 && ny == hy) return \"D\";\n        if (nx == hx && ny == hy - 1) return \"L\";\n        if (nx == hx && ny == hy + 1) return \"R\";\n    }\n    return \".\";\n}\n\nvoid simulatePetMovement(GridState& state, const vector<string>& petMoves) {\n    for (size_t i = 0; i < state.pets.size(); ++i) {\n        auto& pet = state.pets[i];\n        const string& move = petMoves[i];\n        if (move == \".\") continue;\n\n        for (char c : move) {\n            int dx = 0, dy = 0;\n            if (c == 'U') dx = -1;\n            else if (c == 'D') dx = 1;\n            else if (c == 'L') dy = -1;\n            else if (c == 'R') dy = 1;\n\n            int nx = pet.x + dx;\n            int ny = pet.y + dy;\n            if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n                pet.x = nx;\n                pet.y = ny;\n            }\n        }\n    }\n}\n\nint main() {\n    int N, M;\n    cin >> N;\n    vector<Pet> pets(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    vector<Human> humans(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\n    GridState state;\n    state.passable = vector<vector<bool>>(GRID_SIZE, vector<bool>(GRID_SIZE, true));\n    state.pets = pets;\n    state.humans = humans;\n\n    for (int turn = 0; turn < TURNS; ++turn) {\n        string actions;\n        for (int i = 0; i < M; ++i) {\n            actions += decideAction(state, i);\n        }\n        cout << actions << endl;\n        cout.flush();\n\n        vector<string> petMoves(N);\n        for (int i = 0; i < N; ++i) {\n            cin >> petMoves[i];\n        }\n        simulatePetMovement(state, petMoves);\n    }\n\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <tuple>\n#include <algorithm>\n#include <cmath>\n#include <unordered_map>\n#include <map>\n#include <set>\n#include <string>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MAX_N = 20;\nconst int MAX_M = 20;\nconst int MAX_T = 200;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct State {\n    int x, y, t;\n    double prob;\n    string path;\n\n    bool operator<(const State& other) const {\n        return prob < other.prob;\n    }\n};\n\ndouble solve(int si, int sj, int ti, int tj, double p, const vector<string>& h, const vector<string>& v) {\n    priority_queue<State> pq;\n    map<tuple<int, int, int>, double> best_prob;\n    map<tuple<int, int, int>, string> best_path;\n\n    pq.push({si, sj, 0, 1.0, \"\"});\n    best_prob[{si, sj, 0}] = 1.0;\n    best_path[{si, sj, 0}] = \"\";\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.x == ti && current.y == tj) {\n            return current.prob * (401 - current.t);\n        }\n\n        if (current.t >= MAX_T) {\n            continue;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = current.x + dx[i];\n            int ny = current.y + dy[i];\n\n            if (nx < 0 || nx >= MAX_N || ny < 0 || ny >= MAX_M) {\n                continue;\n            }\n\n            if (i == 0 && v[current.x - 1][current.y] == '1') {\n                continue;\n            }\n            if (i == 1 && v[current.x][current.y] == '1') {\n                continue;\n            }\n            if (i == 2 && h[current.x][current.y - 1] == '1') {\n                continue;\n            }\n            if (i == 3 && h[current.x][current.y] == '1') {\n                continue;\n            }\n\n            double new_prob = current.prob * (1 - p);\n            int new_t = current.t + 1;\n            string new_path = current.path + dir[i];\n\n            if (best_prob.find({nx, ny, new_t}) == best_prob.end() || new_prob > best_prob[{nx, ny, new_t}]) {\n                best_prob[{nx, ny, new_t}] = new_prob;\n                best_path[{nx, ny, new_t}] = new_path;\n                pq.push({nx, ny, new_t, new_prob, new_path});\n            }\n        }\n\n        // Stay in the current square\n        double new_prob = current.prob * p;\n        int new_t = current.t + 1;\n        string new_path = current.path + \"S\"; // 'S' represents staying\n\n        if (best_prob.find({current.x, current.y, new_t}) == best_prob.end() || new_prob > best_prob[{current.x, current.y, new_t}]) {\n            best_prob[{current.x, current.y, new_t}] = new_prob;\n            best_path[{current.x, current.y, new_t}] = new_path;\n            pq.push({current.x, current.y, new_t, new_prob, new_path});\n        }\n    }\n\n    return 0.0;\n}\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    vector<string> h(MAX_N), v(MAX_N);\n\n    cin >> si >> sj >> ti >> tj >> p;\n    for (int i = 0; i < MAX_N; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < MAX_N; ++i) {\n        cin >> v[i];\n    }\n\n    double max_score = 0.0;\n    string best_path;\n\n    // Use a heuristic to find a good path\n    // For simplicity, we use a combination of BFS and DP\n    // In a real contest, you might want to use a more sophisticated approach\n    double score = solve(si, sj, ti, tj, p, h, v);\n\n    cout << best_path << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <unordered_set>\n#include <queue>\n#include <tuple>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int POPULATION_SIZE = 100;\nconst int MAX_GENERATIONS = 100;\nconst double MUTATION_RATE = 0.1;\nconst double CROSSOVER_RATE = 0.7;\n\nvector<vector<int>> tiles(GRID_SIZE, vector<int>(GRID_SIZE));\nvector<vector<int>> rotations(GRID_SIZE, vector<int>(GRID_SIZE));\n\n// Directions: left, up, right, down\nconst int di[] = {0, -1, 0, 1};\nconst int dj[] = {-1, 0, 1, 0};\n\n// Transition table for tile types and directions\nconst vector<vector<int>> to = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\n\nint calculate_loop_length(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    unordered_set<string> visited;\n\n    while (true) {\n        int d2 = to[tiles[i][j]][d];\n        if (d2 == -1) return 0;\n        i += di[d2];\n        j += dj[d2];\n        if (i < 0 || i >= GRID_SIZE || j < 0 || j >= GRID_SIZE) return 0;\n        d = (d2 + 2) % 4;\n        length += 1;\n\n        string key = to_string(i) + \",\" + to_string(j) + \",\" + to_string(d);\n        if (visited.count(key)) break;\n        visited.insert(key);\n    }\n\n    return length;\n}\n\nvector<int> find_loop_lines() {\n    vector<int> loop_lengths;\n    vector<vector<vector<bool>>> visited(GRID_SIZE, vector<vector<bool>>(GRID_SIZE, vector<bool>(4, false)));\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            for (int d = 0; d < 4; ++d) {\n                if (!visited[i][j][d]) {\n                    int length = calculate_loop_length(i, j, d);\n                    if (length > 0) {\n                        loop_lengths.push_back(length);\n                        // Mark all tiles in the loop as visited\n                        int ci = i, cj = j, cd = d;\n                        for (int k = 0; k < length; ++k) {\n                            int cd2 = to[tiles[ci][cj]][cd];\n                            ci += di[cd2];\n                            cj += dj[cd2];\n                            cd = (cd2 + 2) % 4;\n                            visited[ci][cj][cd] = true;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    sort(loop_lengths.rbegin(), loop_lengths.rend());\n    return loop_lengths;\n}\n\nint fitness_function() {\n    vector<int> loop_lengths = find_loop_lines();\n    if (loop_lengths.size() < 2) return 0;\n    return loop_lengths[0] * loop_lengths[1];\n}\n\nvoid initialize_population(vector<vector<vector<int>>>& population) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                population[p][i][j] = dis(gen);\n            }\n        }\n    }\n}\n\nvoid mutate(vector<vector<int>>& individual) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> rot_dis(0, 3);\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (dis(gen) < MUTATION_RATE) {\n                individual[i][j] = rot_dis(gen);\n            }\n        }\n    }\n}\n\nvector<vector<int>> crossover(const vector<vector<int>>& parent1, const vector<vector<int>>& parent2) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> row_dis(0, GRID_SIZE - 1);\n    uniform_int_distribution<> col_dis(0, GRID_SIZE - 1);\n\n    vector<vector<int>> child(GRID_SIZE, vector<int>(GRID_SIZE));\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (dis(gen) < CROSSOVER_RATE) {\n                child[i][j] = parent1[i][j];\n            } else {\n                child[i][j] = parent2[i][j];\n            }\n        }\n    }\n\n    return child;\n}\n\nvoid genetic_algorithm() {\n    vector<vector<vector<int>>> population(POPULATION_SIZE, vector<vector<int>>(GRID_SIZE, vector<int>(GRID_SIZE)));\n    initialize_population(population);\n\n    for (int gen = 0; gen < MAX_GENERATIONS; ++gen) {\n        vector<int> fitness_scores(POPULATION_SIZE);\n        for (int p = 0; p < POPULATION_SIZE; ++p) {\n            rotations = population[p];\n            fitness_scores[p] = fitness_function();\n        }\n\n        vector<vector<vector<int>>> new_population;\n        for (int p = 0; p < POPULATION_SIZE; ++p) {\n            int parent1_idx = distance(fitness_scores.begin(), max_element(fitness_scores.begin(), fitness_scores.end()));\n            fitness_scores[parent1_idx] = -1;\n            int parent2_idx = distance(fitness_scores.begin(), max_element(fitness_scores.begin(), fitness_scores.end()));\n            fitness_scores[parent2_idx] = -1;\n\n            vector<vector<int>> child = crossover(population[parent1_idx], population[parent2_idx]);\n            mutate(child);\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n    }\n\n    // Find the best solution\n    int best_fitness = -1;\n    vector<vector<int>> best_rotations;\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        rotations = population[p];\n        int current_fitness = fitness_function();\n        if (current_fitness > best_fitness) {\n            best_fitness = current_fitness;\n            best_rotations = population[p];\n        }\n    }\n\n    rotations = best_rotations;\n}\n\nint main() {\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            tiles[i][j] = row[j] - '0';\n        }\n    }\n\n    genetic_algorithm();\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            cout << rotations[i][j];\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\n\nstruct State {\n    vector<vector<int>> board;\n    pair<int, int> empty;\n    int cost;\n    int heuristic;\n\n    bool operator==(const State& other) const {\n        return board == other.board && empty == other.empty;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<State> {\n        size_t operator()(const State& state) const {\n            size_t seed = 0;\n            for (const auto& row : state.board) {\n                for (int tile : row) {\n                    seed ^= hash<int>{}(tile) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n                }\n            }\n            seed ^= hash<int>{}(state.empty.first) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            seed ^= hash<int>{}(state.empty.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            return seed;\n        }\n    };\n}\n\nint calculate_heuristic(const vector<vector<int>>& board, int N) {\n    dsu_union_find uf(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0) continue;\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N || board[ni][nj] == 0) continue;\n                if ((board[i][j] & (1 << k)) && (board[ni][nj] & (1 << ((k + 2) % 4)))) {\n                    uf.merge(i * N + j, ni * N + nj);\n                }\n            }\n        }\n    }\n    unordered_set<int> roots;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] != 0) {\n                roots.insert(uf.leader(i * N + j));\n            }\n        }\n    }\n    return roots.size();\n}\n\nvector<State> get_neighbors(const State& state, int N) {\n    vector<State> neighbors;\n    int x = state.empty.first;\n    int y = state.empty.second;\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + dx[i];\n        int ny = y + dy[i];\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n        State neighbor = state;\n        neighbor.board[x][y] = neighbor.board[nx][ny];\n        neighbor.board[nx][ny] = 0;\n        neighbor.empty = {nx, ny};\n        neighbor.cost = state.cost + 1;\n        neighbor.heuristic = calculate_heuristic(neighbor.board, N);\n        neighbors.push_back(neighbor);\n    }\n    return neighbors;\n}\n\nstring a_star_search(State initial, int N, int T) {\n    auto cmp = [](const State& a, const State& b) {\n        return a.cost + a.heuristic > b.cost + b.heuristic;\n    };\n    priority_queue<State, vector<State>, decltype(cmp)> open(cmp);\n    unordered_set<State> closed;\n    open.push(initial);\n    while (!open.empty()) {\n        State current = open.top();\n        open.pop();\n        if (current.heuristic == 1) {\n            return \"\"; // Reached the goal\n        }\n        if (closed.count(current)) continue;\n        closed.insert(current);\n        for (const State& neighbor : get_neighbors(current, N)) {\n            if (!closed.count(neighbor)) {\n                open.push(neighbor);\n            }\n        }\n    }\n    return \"\"; // No solution found\n}\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    pair<int, int> empty;\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            char c = row[j];\n            if (c >= '0' && c <= '9') {\n                board[i][j] = c - '0';\n            } else {\n                board[i][j] = 10 + (c - 'a');\n            }\n            if (board[i][j] == 0) {\n                empty = {i, j};\n            }\n        }\n    }\n    State initial = {board, empty, 0, calculate_heuristic(board, N)};\n    string solution = a_star_search(initial, N, T);\n    cout << solution << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <limits>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Line {\n    Point p, q;\n    Line(Point p, Point q) : p(p), q(q) {}\n};\n\nstruct Strawberry {\n    int x, y;\n    Strawberry(int x, int y) : x(x), y(y) {}\n};\n\nvector<Strawberry> strawberries;\nvector<int> a_d(10);\nint K;\n\ndouble distance(const Point& p1, const Point& p2) {\n    return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));\n}\n\nbool isInside(const Point& p, const Line& line) {\n    // Check if point p is inside the cake and not cut by the line\n    if (distance(p, Point(0, 0)) >= 10000) {\n        return false;\n    }\n    // Check if the point is on the line\n    int x1 = line.p.x, y1 = line.p.y;\n    int x2 = line.q.x, y2 = line.q.y;\n    int x = p.x, y = p.y;\n    if ((y2 - y1) * (x - x1) == (y - y1) * (x2 - x1)) {\n        return false;\n    }\n    return true;\n}\n\nint countPieces(const vector<Line>& lines, int d) {\n    vector<vector<bool>> inside(strawberries.size(), vector<bool>(lines.size() + 1, true));\n    for (int i = 0; i < lines.size(); ++i) {\n        for (int j = 0; j < strawberries.size(); ++j) {\n            if (!isInside(Point(strawberries[j].x, strawberries[j].y), lines[i])) {\n                inside[j][i + 1] = false;\n            }\n        }\n    }\n    int count = 0;\n    for (int i = 0; i < strawberries.size(); ++i) {\n        int c = 0;\n        for (int j = 0; j <= lines.size(); ++j) {\n            if (inside[i][j]) {\n                c++;\n            }\n        }\n        if (c == d) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvector<Line> greedyAlgorithm() {\n    vector<Line> lines;\n    for (int d = 1; d <= 10; ++d) {\n        if (a_d[d - 1] == 0) continue;\n        int maxPieces = 0;\n        Line bestLine(Point(0, 0), Point(0, 0));\n        for (int i = 0; i < 100; ++i) {\n            // Generate random line\n            random_device rd;\n            mt19937 gen(rd());\n            uniform_int_distribution<> dis(-1e9, 1e9);\n            Point p(dis(gen), dis(gen));\n            Point q(dis(gen), dis(gen));\n            Line line(p, q);\n            vector<Line> tempLines = lines;\n            tempLines.push_back(line);\n            int pieces = countPieces(tempLines, d);\n            if (pieces > maxPieces) {\n                maxPieces = pieces;\n                bestLine = line;\n            }\n        }\n        if (maxPieces > 0) {\n            lines.push_back(bestLine);\n            if (lines.size() >= K) break;\n        }\n    }\n    return lines;\n}\n\nint main() {\n    int N;\n    cin >> N >> K;\n    for (int i = 0; i < 10; ++i) {\n        cin >> a_d[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        strawberries.emplace_back(x, y);\n    }\n    vector<Line> lines = greedyAlgorithm();\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line.p.x << \" \" << line.p.y << \" \" << line.q.x << \" \" << line.q.y << endl;\n    }\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n#include <unordered_set>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nclass RectJoinGame {\nprivate:\n    int N, M;\n    unordered_set<Point> dots;\n    vector<Rectangle> rectangles;\n    int c;\n    double S;\n    mt19937 rng;\n\n    double weight(int x, int y) {\n        return (x - c) * (x - c) + (y - c) * (y - c) + 1;\n    }\n\n    bool isValidRectangle(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        // Check if the points form a valid rectangle (axis-aligned or 45-degree)\n        int dx1 = p2.x - p1.x;\n        int dy1 = p2.y - p1.y;\n        int dx2 = p3.x - p2.x;\n        int dy2 = p3.y - p2.y;\n        int dx3 = p4.x - p3.x;\n        int dy3 = p4.y - p3.y;\n        int dx4 = p1.x - p4.x;\n        int dy4 = p1.y - p4.y;\n\n        // Check if the sides are equal and perpendicular\n        if ((dx1 == dx3 && dy1 == dy3) && (dx2 == dx4 && dy2 == dy4) &&\n            (dx1 * dx2 + dy1 * dy2 == 0)) {\n            // Check if the rectangle is axis-aligned or 45-degree\n            if ((dx1 == 0 || dy1 == 0 || abs(dx1) == abs(dy1)) &&\n                (dx2 == 0 || dy2 == 0 || abs(dx2) == abs(dy2))) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    bool isValidOperation(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        if (dots.count(p1)) return false;\n        if (!dots.count(p2) || !dots.count(p3) || !dots.count(p4)) return false;\n        if (!isValidRectangle(p1, p2, p3, p4)) return false;\n\n        // Check if the perimeter of the rectangle contains any other dots\n        set<Point> perimeter;\n        int dx = p2.x - p1.x;\n        int dy = p2.y - p1.y;\n        for (int i = 0; i <= 1; ++i) {\n            for (int j = 0; j <= 1; ++j) {\n                int x = p1.x + i * dx;\n                int y = p1.y + i * dy;\n                for (int k = 0; k <= 1; ++k) {\n                    int nx = x + k * dy;\n                    int ny = y - k * dx;\n                    perimeter.insert(Point(nx, ny));\n                }\n            }\n        }\n        for (const auto& p : perimeter) {\n            if (dots.count(p) && !(p == p1 || p == p2 || p == p3 || p == p4)) {\n                return false;\n            }\n        }\n\n        // Check if the perimeter of the rectangle shares a common segment with any previously drawn rectangle\n        for (const auto& rect : rectangles) {\n            set<Point> rectPerimeter;\n            int rdx = rect.p2.x - rect.p1.x;\n            int rdy = rect.p2.y - rect.p1.y;\n            for (int i = 0; i <= 1; ++i) {\n                for (int j = 0; j <= 1; ++j) {\n                    int x = rect.p1.x + i * rdx;\n                    int y = rect.p1.y + i * rdy;\n                    for (int k = 0; k <= 1; ++k) {\n                        int nx = x + k * rdy;\n                        int ny = y - k * rdx;\n                        rectPerimeter.insert(Point(nx, ny));\n                    }\n                }\n            }\n            set<Point> intersection;\n            set_intersection(perimeter.begin(), perimeter.end(), rectPerimeter.begin(), rectPerimeter.end(), inserter(intersection, intersection.begin()));\n            if (intersection.size() > 2) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    double calculateScore() {\n        double sum = 0;\n        for (const auto& p : dots) {\n            sum += weight(p.x, p.y);\n        }\n        return round(1e6 * N * N / M * sum / S);\n    }\n\n    vector<Point> getNeighbors(const Point& p) {\n        vector<Point> neighbors;\n        for (int dx = -1; dx <= 1; ++dx) {\n            for (int dy = -1; dy <= 1; ++dy) {\n                if (dx == 0 && dy == 0) continue;\n                int nx = p.x + dx;\n                int ny = p.y + dy;\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N) {\n                    neighbors.emplace_back(nx, ny);\n                }\n            }\n        }\n        return neighbors;\n    }\n\n    pair<Point, vector<Point>> findBestOperation() {\n        double bestScore = -1;\n        Point bestP1;\n        vector<Point> bestP234;\n\n        for (const auto& p1 : dots) {\n            auto neighbors = getNeighbors(p1);\n            for (const auto& p2 : neighbors) {\n                if (!dots.count(p2)) continue;\n                for (const auto& p3 : neighbors) {\n                    if (!dots.count(p3) || p3 == p2) continue;\n                    for (const auto& p4 : neighbors) {\n                        if (!dots.count(p4) || p4 == p2 || p4 == p3) continue;\n                        if (isValidOperation(p1, p2, p3, p4)) {\n                            dots.insert(p1);\n                            rectangles.emplace_back(p1, p2, p3, p4);\n                            double score = calculateScore();\n                            dots.erase(p1);\n                            rectangles.pop_back();\n                            if (score > bestScore) {\n                                bestScore = score;\n                                bestP1 = p1;\n                                bestP234 = {p2, p3, p4};\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        return {bestP1, bestP234};\n    }\n\n    void simulatedAnnealing(double initialTemp, double finalTemp, double alpha) {\n        double temp = initialTemp;\n        auto currentScore = calculateScore();\n        auto bestScore = currentScore;\n        vector<Rectangle> bestRectangles = rectangles;\n\n        while (temp > finalTemp) {\n            auto [p1, p234] = findBestOperation();\n            if (p234.empty()) break;\n\n            dots.insert(p1);\n            rectangles.emplace_back(p1, p234[0], p234[1], p234[2]);\n            auto newScore = calculateScore();\n\n            if (newScore > currentScore || exp((newScore - currentScore) / temp) > uniform_real_distribution<double>(0, 1)(rng)) {\n                currentScore = newScore;\n                if (newScore > bestScore) {\n                    bestScore = newScore;\n                    bestRectangles = rectangles;\n                }\n            } else {\n                dots.erase(p1);\n                rectangles.pop_back();\n            }\n\n            temp *= alpha;\n        }\n\n        rectangles = bestRectangles;\n    }\n\npublic:\n    RectJoinGame(int N, int M, const vector<Point>& initialDots) : N(N), M(M), dots(initialDots.begin(), initialDots.end()), c((N - 1) / 2), rng(chrono::steady_clock::now().time_since_epoch().count()) {\n        S = 0;\n        for (int x = 0; x < N; ++x) {\n            for (int y = 0; y < N; ++y) {\n                S += weight(x, y);\n            }\n        }\n    }\n\n    void play() {\n        simulatedAnnealing(1000, 0.1, 0.99);\n    }\n\n    void output() const {\n        cout << rectangles.size() << endl;\n        for (const auto& rect : rectangles) {\n            cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n                 << rect.p2.x << \" \" << rect.p2.y << \" \"\n                 << rect.p3.x << \" \" << rect.p3.y << \" \"\n                 << rect.p4.x << \" \" << rect.p4.y << endl;\n        }\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<Point> initialDots;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        initialDots.emplace_back(x, y);\n    }\n\n    RectJoinGame game(N, M, initialDots);\n    game.play();\n    game.output();\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <array>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n\nusing namespace std;\n\nconst int GRID_SIZE = 10;\nconst int NUM_FLAVORS = 3;\nconst int NUM_CANDIES = 100;\n\nenum Direction { FORWARD, BACKWARD, LEFT, RIGHT };\n\nstruct Candy {\n    int flavor;\n    int row;\n    int col;\n};\n\nstruct Grid {\n    array<array<int, GRID_SIZE>, GRID_SIZE> cells;\n    vector<Candy> candies;\n\n    Grid() {\n        for (auto& row : cells) {\n            fill(row.begin(), row.end(), 0);\n        }\n    }\n\n    void place_candy(int flavor, int row, int col) {\n        cells[row][col] = flavor;\n        candies.push_back({flavor, row, col});\n    }\n\n    void tilt(Direction dir) {\n        switch (dir) {\n            case FORWARD:\n                tilt_forward();\n                break;\n            case BACKWARD:\n                tilt_backward();\n                break;\n            case LEFT:\n                tilt_left();\n                break;\n            case RIGHT:\n                tilt_right();\n                break;\n        }\n    }\n\n    void tilt_forward() {\n        for (int col = 0; col < GRID_SIZE; ++col) {\n            int empty_row = GRID_SIZE - 1;\n            for (int row = GRID_SIZE - 1; row >= 0; --row) {\n                if (cells[row][col] != 0) {\n                    cells[empty_row][col] = cells[row][col];\n                    if (empty_row != row) {\n                        cells[row][col] = 0;\n                    }\n                    --empty_row;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_backward() {\n        for (int col = 0; col < GRID_SIZE; ++col) {\n            int empty_row = 0;\n            for (int row = 0; row < GRID_SIZE; ++row) {\n                if (cells[row][col] != 0) {\n                    cells[empty_row][col] = cells[row][col];\n                    if (empty_row != row) {\n                        cells[row][col] = 0;\n                    }\n                    ++empty_row;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_left() {\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            int empty_col = 0;\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0) {\n                    cells[row][empty_col] = cells[row][col];\n                    if (empty_col != col) {\n                        cells[row][col] = 0;\n                    }\n                    ++empty_col;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_right() {\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            int empty_col = GRID_SIZE - 1;\n            for (int col = GRID_SIZE - 1; col >= 0; --col) {\n                if (cells[row][col] != 0) {\n                    cells[row][empty_col] = cells[row][col];\n                    if (empty_col != col) {\n                        cells[row][col] = 0;\n                    }\n                    --empty_col;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void update_candies() {\n        candies.clear();\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0) {\n                    candies.push_back({cells[row][col], row, col});\n                }\n            }\n        }\n    }\n\n    int calculate_score() {\n        array<int, NUM_FLAVORS + 1> flavor_counts = {0};\n        for (const auto& candy : candies) {\n            flavor_counts[candy.flavor]++;\n        }\n\n        int sum_squares = 0;\n        for (int i = 1; i <= NUM_FLAVORS; ++i) {\n            sum_squares += flavor_counts[i] * flavor_counts[i];\n        }\n\n        array<array<bool, GRID_SIZE>, GRID_SIZE> visited = {false};\n        int connectivity = 0;\n\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0 && !visited[row][col]) {\n                    int flavor = cells[row][col];\n                    int component_size = 0;\n                    vector<pair<int, int>> stack = {{row, col}};\n                    visited[row][col] = true;\n\n                    while (!stack.empty()) {\n                        auto [r, c] = stack.back();\n                        stack.pop_back();\n                        component_size++;\n\n                        for (const auto& [dr, dc] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                            int nr = r + dr;\n                            int nc = c + dc;\n                            if (nr >= 0 && nr < GRID_SIZE && nc >= 0 && nc < GRID_SIZE && cells[nr][nc] == flavor && !visited[nr][nc]) {\n                                visited[nr][nc] = true;\n                                stack.emplace_back(nr, nc);\n                            }\n                        }\n                    }\n\n                    connectivity += component_size * component_size;\n                }\n            }\n        }\n\n        return round(1e6 * static_cast<double>(connectivity) / sum_squares);\n    }\n};\n\nDirection choose_direction(const Grid& grid, int flavor) {\n    array<int, 4> scores = {0};\n    array<Grid, 4> grids;\n\n    for (int i = 0; i < 4; ++i) {\n        grids[i] = grid;\n        grids[i].tilt(static_cast<Direction>(i));\n        scores[i] = grids[i].calculate_score();\n    }\n\n    int max_score = *max_element(scores.begin(), scores.end());\n    vector<Direction> best_directions;\n\n    for (int i = 0; i < 4; ++i) {\n        if (scores[i] == max_score) {\n            best_directions.push_back(static_cast<Direction>(i));\n        }\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, best_directions.size() - 1);\n\n    return best_directions[dis(gen)];\n}\n\nint main() {\n    vector<int> flavors(NUM_CANDIES);\n    for (int& flavor : flavors) {\n        cin >> flavor;\n    }\n\n    Grid grid;\n    for (int t = 0; t < NUM_CANDIES; ++t) {\n        int p;\n        cin >> p;\n\n        int empty_cell = 0;\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (grid.cells[row][col] == 0) {\n                    empty_cell++;\n                    if (empty_cell == p) {\n                        grid.place_candy(flavors[t], row, col);\n                        break;\n                    }\n                }\n            }\n            if (empty_cell == p) {\n                break;\n            }\n        }\n\n        if (t < NUM_CANDIES - 1) {\n            Direction dir = choose_direction(grid, flavors[t]);\n            grid.tilt(dir);\n\n            switch (dir) {\n                case FORWARD:\n                    cout << \"F\" << endl;\n                    break;\n                case BACKWARD:\n                    cout << \"B\" << endl;\n                    break;\n                case LEFT:\n                    cout << \"L\" << endl;\n                    break;\n                case RIGHT:\n                    cout << \"R\" << endl;\n                    break;\n            }\n            cout.flush();\n        }\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int MAX_N = 100;\nconst int MAX_M = 100;\nconst int MAX_QUERIES = 100;\n\nmt19937 rng(random_device{}());\n\nint M;\ndouble epsilon;\nint N;\nvector<vector<vector<bool>>> G;\nvector<vector<bool>> H;\n\nvoid generate_graphs() {\n    // Use a combination of edge patterns and vertex orderings to encode numbers\n    for (int k = 0; k < M; ++k) {\n        vector<vector<bool>> graph(N, vector<bool>(N, false));\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                // Use a combination of edge patterns to encode the number k\n                if ((k & (1 << (i + j))) != 0) {\n                    graph[i][j] = true;\n                    graph[j][i] = true;\n                }\n            }\n        }\n        G.push_back(graph);\n    }\n}\n\nvoid output_graphs() {\n    cout << N << endl;\n    for (const auto& graph : G) {\n        string s;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                s += graph[i][j] ? '1' : '0';\n            }\n        }\n        cout << s << endl;\n    }\n    cout.flush();\n}\n\nvoid read_graph() {\n    string s;\n    cin >> s;\n    H.assign(N, vector<bool>(N, false));\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            H[i][j] = (s[idx++] == '1');\n            H[j][i] = H[i][j];\n        }\n    }\n}\n\nint calculate_similarity(const vector<vector<bool>>& a, const vector<vector<bool>>& b) {\n    int similarity = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (a[i][j] == b[i][j]) {\n                similarity++;\n            }\n        }\n    }\n    return similarity;\n}\n\nint predict_graph() {\n    int best_match = -1;\n    int max_similarity = -1;\n    for (int k = 0; k < M; ++k) {\n        int similarity = calculate_similarity(H, G[k]);\n        if (similarity > max_similarity) {\n            max_similarity = similarity;\n            best_match = k;\n        }\n    }\n    return best_match;\n}\n\nint main() {\n    cin >> M >> epsilon;\n    N = 20; // Choose a reasonable N within the constraints\n\n    generate_graphs();\n    output_graphs();\n\n    for (int q = 0; q < MAX_QUERIES; ++q) {\n        read_graph();\n        int t = predict_graph();\n        cout << t << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <limits>\n#include <unordered_map>\n#include <unordered_set>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v, w;\n    int day;\n    bool operator<(const Edge& other) const {\n        return w > other.w;\n    }\n};\n\nstruct Vertex {\n    int id;\n    double betweenness;\n    Vertex(int id) : id(id), betweenness(0.0) {}\n};\n\nclass Graph {\nprivate:\n    int N, M, D, K;\n    vector<vector<pair<int, int>>> adj;\n    vector<Edge> edges;\n    vector<Vertex> vertices;\n\n    void computeBetweennessCentrality() {\n        for (int s = 0; s < N; ++s) {\n            vector<int> numSP(N, 0);\n            vector<double> bc(N, 0.0);\n            vector<vector<int>> predecessors(N);\n            vector<int> stack;\n            vector<int> sigma(N, 0);\n            vector<int> distance(N, -1);\n\n            queue<int> q;\n            q.push(s);\n            sigma[s] = 1;\n            distance[s] = 0;\n\n            while (!q.empty()) {\n                int v = q.front();\n                q.pop();\n                stack.push_back(v);\n                for (const auto& neighbor : adj[v]) {\n                    int w = neighbor.first;\n                    if (distance[w] < 0) {\n                        q.push(w);\n                        distance[w] = distance[v] + 1;\n                    }\n                    if (distance[w] == distance[v] + 1) {\n                        sigma[w] += sigma[v];\n                        predecessors[w].push_back(v);\n                    }\n                }\n            }\n\n            while (!stack.empty()) {\n                int w = stack.back();\n                stack.pop_back();\n                for (int v : predecessors[w]) {\n                    bc[v] += (sigma[v] / static_cast<double>(sigma[w])) * (1.0 + bc[w]);\n                }\n                if (w != s) {\n                    vertices[w].betweenness += bc[w];\n                }\n            }\n        }\n    }\n\n    void prioritizeEdges() {\n        computeBetweennessCentrality();\n        sort(edges.begin(), edges.end(), [this](const Edge& a, const Edge& b) {\n            double a_betweenness = vertices[a.u].betweenness + vertices[a.v].betweenness;\n            double b_betweenness = vertices[b.u].betweenness + vertices[b.v].betweenness;\n            return a_betweenness > b_betweenness;\n        });\n    }\n\n    void assignDays() {\n        vector<int> dayCounts(D, 0);\n        for (auto& edge : edges) {\n            int bestDay = -1;\n            double minIncrease = numeric_limits<double>::max();\n            for (int day = 0; day < D; ++day) {\n                if (dayCounts[day] >= K) continue;\n                double increase = calculateFrustrationIncrease(edge, day);\n                if (increase < minIncrease) {\n                    minIncrease = increase;\n                    bestDay = day;\n                }\n            }\n            edge.day = bestDay;\n            dayCounts[bestDay]++;\n        }\n    }\n\n    double calculateFrustrationIncrease(const Edge& edge, int day) {\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            for (const auto& neighbor : adj[i]) {\n                int v = neighbor.first;\n                int w = neighbor.second;\n                dist[i][v] = min(dist[i][v], w);\n            }\n        }\n\n        for (int k = 0; k < N; ++k) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (dist[i][k] != numeric_limits<int>::max() && dist[k][j] != numeric_limits<int>::max()) {\n                        dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n                    }\n                }\n            }\n        }\n\n        vector<vector<int>> newDist = dist;\n        newDist[edge.u][edge.v] = numeric_limits<int>::max();\n        newDist[edge.v][edge.u] = numeric_limits<int>::max();\n\n        for (int k = 0; k < N; ++k) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (newDist[i][k] != numeric_limits<int>::max() && newDist[k][j] != numeric_limits<int>::max()) {\n                        newDist[i][j] = min(newDist[i][j], newDist[i][k] + newDist[k][j]);\n                    }\n                }\n            }\n        }\n\n        double totalIncrease = 0.0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (i != j) {\n                    int originalDist = dist[i][j];\n                    int newDistVal = newDist[i][j];\n                    if (newDistVal == numeric_limits<int>::max()) {\n                        newDistVal = 1e9;\n                    }\n                    totalIncrease += (newDistVal - originalDist);\n                }\n            }\n        }\n\n        return totalIncrease / (N * (N - 1));\n    }\n\npublic:\n    Graph(int N, int M, int D, int K) : N(N), M(M), D(D), K(K), adj(N), vertices(N) {\n        for (int i = 0; i < N; ++i) {\n            vertices[i].id = i;\n        }\n    }\n\n    void addEdge(int u, int v, int w) {\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n        edges.push_back({u, v, w, -1});\n    }\n\n    void solve() {\n        prioritizeEdges();\n        assignDays();\n    }\n\n    void printSolution() {\n        for (const auto& edge : edges) {\n            cout << edge.day + 1 << \" \";\n        }\n        cout << endl;\n    }\n};\n\nint main() {\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    Graph graph(N, M, D, K);\n\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        graph.addEdge(u - 1, v - 1, w);\n    }\n\n    // Skip reading the coordinates if not needed\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    graph.solve();\n    graph.printSolution();\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Block {\n    vector<vector<vector<bool>>> shape;\n    int volume;\n\n    Block(const vector<vector<vector<bool>>>& s) : shape(s) {\n        volume = 0;\n        for (const auto& layer : shape) {\n            for (const auto& row : layer) {\n                for (bool cell : row) {\n                    if (cell) volume++;\n                }\n            }\n        }\n    }\n\n    void rotateX() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[x][D - 1 - z][y] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n\n    void rotateY() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[z][y][D - 1 - x] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n\n    void rotateZ() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[D - 1 - y][x][z] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n};\n\nstruct Individual {\n    vector<Block> blocks;\n    vector<vector<vector<int>>> arrangement1;\n    vector<vector<vector<int>>> arrangement2;\n    double fitness;\n\n    Individual(const vector<Block>& b, int D) : blocks(b) {\n        arrangement1 = vector<vector<vector<int>>>(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        arrangement2 = vector<vector<vector<int>>>(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        fitness = 0.0;\n    }\n};\n\nvector<Block> generateInitialBlocks(int D) {\n    vector<Block> blocks;\n    // Generate some initial blocks, e.g., single cubes, 2x2x2 cubes, etc.\n    // This is a placeholder; actual block generation should be more sophisticated.\n    vector<vector<vector<bool>>> singleCube(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    singleCube[0][0][0] = true;\n    blocks.emplace_back(singleCube);\n\n    vector<vector<vector<bool>>> twoCube(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    twoCube[0][0][0] = true;\n    twoCube[0][0][1] = true;\n    blocks.emplace_back(twoCube);\n\n    return blocks;\n}\n\nvector<vector<vector<bool>>> createSilhouette(int D, const vector<string>& f, const vector<string>& r) {\n    vector<vector<vector<bool>>> silhouette(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    for (int z = 0; z < D; ++z) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                if (f[z][x] == '1' && r[z][y] == '1') {\n                    silhouette[x][y][z] = true;\n                }\n            }\n        }\n    }\n    return silhouette;\n}\n\ndouble evaluateFitness(const Individual& ind, const vector<vector<vector<bool>>>& silhouette1, const vector<vector<vector<bool>>>& silhouette2) {\n    int D = silhouette1.size();\n    double fitness = 0.0;\n\n    // Check silhouette1\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 (silhouette1[x][y][z]) {\n                    bool covered = false;\n                    for (const auto& block : ind.blocks) {\n                        if (ind.arrangement1[x][y][z] != 0) {\n                            covered = true;\n                            break;\n                        }\n                    }\n                    if (!covered) fitness += 1.0;\n                }\n            }\n        }\n    }\n\n    // Check silhouette2\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 (silhouette2[x][y][z]) {\n                    bool covered = false;\n                    for (const auto& block : ind.blocks) {\n                        if (ind.arrangement2[x][y][z] != 0) {\n                            covered = true;\n                            break;\n                        }\n                    }\n                    if (!covered) fitness += 1.0;\n                }\n            }\n        }\n    }\n\n    // Penalize unused blocks\n    unordered_set<int> usedBlocks1, usedBlocks2;\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 (ind.arrangement1[x][y][z] != 0) usedBlocks1.insert(ind.arrangement1[x][y][z]);\n                if (ind.arrangement2[x][y][z] != 0) usedBlocks2.insert(ind.arrangement2[x][y][z]);\n            }\n        }\n    }\n    for (int i = 1; i <= ind.blocks.size(); ++i) {\n        if (usedBlocks1.find(i) == usedBlocks1.end() && usedBlocks2.find(i) == usedBlocks2.end()) {\n            fitness += ind.blocks[i - 1].volume;\n        }\n    }\n\n    // Penalize blocks used in both arrangements\n    unordered_set<int> commonBlocks;\n    for (int block : usedBlocks1) {\n        if (usedBlocks2.find(block) != usedBlocks2.end()) {\n            commonBlocks.insert(block);\n        }\n    }\n    for (int block : commonBlocks) {\n        fitness += 1.0 / ind.blocks[block - 1].volume;\n    }\n\n    return fitness;\n}\n\nIndividual geneticAlgorithm(int D, const vector<vector<vector<bool>>>& silhouette1, const vector<vector<vector<bool>>>& silhouette2, int populationSize, int generations) {\n    vector<Block> initialBlocks = generateInitialBlocks(D);\n    vector<Individual> population;\n    for (int i = 0; i < populationSize; ++i) {\n        population.emplace_back(initialBlocks, D);\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> blockDist(0, initialBlocks.size() - 1);\n    uniform_int_distribution<> posDist(0, D - 1);\n\n    for (int gen = 0; gen < generations; ++gen) {\n        // Evaluate fitness\n        for (auto& ind : population) {\n            ind.fitness = evaluateFitness(ind, silhouette1, silhouette2);\n        }\n\n        // Sort by fitness\n        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n            return a.fitness < b.fitness;\n        });\n\n        // Select top individuals\n        vector<Individual> newPopulation;\n        for (int i = 0; i < populationSize / 2; ++i) {\n            newPopulation.push_back(population[i]);\n        }\n\n        // Crossover and mutation\n        while (newPopulation.size() < populationSize) {\n            Individual parent1 = population[rand() % (populationSize / 2)];\n            Individual parent2 = population[rand() % (populationSize / 2)];\n            Individual child(parent1.blocks, D);\n\n            // Crossover: randomly select arrangements from parents\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 (rand() % 2) {\n                            child.arrangement1[x][y][z] = parent1.arrangement1[x][y][z];\n                            child.arrangement2[x][y][z] = parent1.arrangement2[x][y][z];\n                        } else {\n                            child.arrangement1[x][y][z] = parent2.arrangement1[x][y][z];\n                            child.arrangement2[x][y][z] = parent2.arrangement2[x][y][z];\n                        }\n                    }\n                }\n            }\n\n            // Mutation: randomly change some blocks\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 (rand() % 100 < 5) { // 5% mutation rate\n                            child.arrangement1[x][y][z] = blockDist(gen) + 1;\n                            child.arrangement2[x][y][z] = blockDist(gen) + 1;\n                        }\n                    }\n                }\n            }\n\n            newPopulation.push_back(child);\n        }\n\n        population = newPopulation;\n    }\n\n    // Return the best individual\n    sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n        return a.fitness < b.fitness;\n    });\n\n    return population[0];\n}\n\nint main() {\n    int D;\n    cin >> D;\n\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for (int i = 0; i < D; ++i) cin >> f1[i];\n    for (int i = 0; i < D; ++i) cin >> r1[i];\n    for (int i = 0; i < D; ++i) cin >> f2[i];\n    for (int i = 0; i < D; ++i) cin >> r2[i];\n\n    vector<vector<vector<bool>>> silhouette1 = createSilhouette(D, f1, r1);\n    vector<vector<vector<bool>>> silhouette2 = createSilhouette(D, f2, r2);\n\n    Individual bestIndividual = geneticAlgorithm(D, silhouette1, silhouette2, 50, 100);\n\n    // Output the best individual\n    int n = bestIndividual.blocks.size();\n    cout << n << endl;\n\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                cout << bestIndividual.arrangement1[x][y][z] << \" \";\n            }\n        }\n    }\n    cout << endl;\n\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                cout << bestIndividual.arrangement2[x][y][z] << \" \";\n            }\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <limits>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\nusing namespace std;\nusing namespace boost;\n\ntypedef adjacency_list<vecS, vecS, undirectedS,\n                       no_property,\n                       property<edge_weight_t, int> > Graph;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef graph_traits<Graph>::edge_descriptor Edge;\ntypedef graph_traits<Graph>::edge_iterator EdgeIterator;\ntypedef graph_traits<Graph>::vertex_iterator VertexIterator;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Resident {\n    int a, b;\n    Resident(int a, int b) : a(a), b(b) {}\n};\n\nstruct EdgeInfo {\n    int u, v, w;\n    EdgeInfo(int u, int v, int w) : u(u), v(v), w(w) {}\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<Point> stations(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> stations[i].x >> stations[i].y;\n    }\n\n    vector<EdgeInfo> edges(M);\n    for (int j = 0; j < M; ++j) {\n        cin >> edges[j].u >> edges[j].v >> edges[j].w;\n        edges[j].u--; // Convert to 0-based index\n        edges[j].v--;\n    }\n\n    vector<Resident> residents(K);\n    for (int k = 0; k < K; ++k) {\n        cin >> residents[k].a >> residents[k].b;\n    }\n\n    // Build the graph\n    Graph g(N);\n    vector<Edge> edge_map(M);\n    for (int j = 0; j < M; ++j) {\n        edge_map[j] = add_edge(edges[j].u, edges[j].v, edges[j].w, g).first;\n    }\n\n    // Find the Minimum Spanning Tree (MST)\n    vector<Edge> mst_edges;\n    kruskal_minimum_spanning_tree(g, back_inserter(mst_edges));\n\n    // Create a subgraph with MST edges\n    Graph mst(N);\n    for (const auto& e : mst_edges) {\n        add_edge(source(e, g), target(e, g), get(edge_weight, g, e), mst);\n    }\n\n    // Calculate the minimum output strength for each station\n    vector<int> P(N, 0);\n    for (int i = 0; i < N; ++i) {\n        double max_dist = 0.0;\n        for (const auto& resident : residents) {\n            double dist = sqrt(pow(stations[i].x - resident.a, 2) + pow(stations[i].y - resident.b, 2));\n            if (dist > max_dist) {\n                max_dist = dist;\n            }\n        }\n        P[i] = static_cast<int>(ceil(max_dist));\n    }\n\n    // Ensure all residents are covered\n    unordered_set<int> covered_residents;\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            double dist = sqrt(pow(stations[i].x - residents[k].a, 2) + pow(stations[i].y - residents[k].b, 2));\n            if (dist <= P[i]) {\n                covered_residents.insert(k);\n            }\n        }\n    }\n\n    // If not all residents are covered, increase the output strength of the nearest station\n    while (covered_residents.size() < K) {\n        for (int k = 0; k < K; ++k) {\n            if (covered_residents.find(k) == covered_residents.end()) {\n                double min_dist = numeric_limits<double>::max();\n                int nearest_station = -1;\n                for (int i = 0; i < N; ++i) {\n                    double dist = sqrt(pow(stations[i].x - residents[k].a, 2) + pow(stations[i].y - residents[k].b, 2));\n                    if (dist < min_dist) {\n                        min_dist = dist;\n                        nearest_station = i;\n                    }\n                }\n                P[nearest_station] = static_cast<int>(ceil(min_dist));\n                for (int kk = 0; kk < K; ++kk) {\n                    double dist = sqrt(pow(stations[nearest_station].x - residents[kk].a, 2) + pow(stations[nearest_station].y - residents[kk].b, 2));\n                    if (dist <= P[nearest_station]) {\n                        covered_residents.insert(kk);\n                    }\n                }\n            }\n        }\n    }\n\n    // Output the results\n    for (int i = 0; i < N; ++i) {\n        cout << P[i] << \" \";\n    }\n    cout << endl;\n\n    // Create a set of edges in the MST for quick lookup\n    unordered_set<Edge> mst_edge_set;\n    for (const auto& e : mst_edges) {\n        mst_edge_set.insert(e);\n    }\n\n    // Output the power status of each edge\n    for (int j = 0; j < M; ++j) {\n        Edge e = edge(edges[j].u, edges[j].v, g).first;\n        if (mst_edge_set.find(e) != mst_edge_set.end()) {\n            cout << \"1 \";\n        } else {\n            cout << \"0 \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 30;\nconst int MAX_OPERATIONS = 10000;\n\nvector<vector<int>> pyramid;\n\nstruct Operation {\n    int x1, y1, x2, y2;\n};\n\nvector<Operation> operations;\n\nbool is_adjacent(int x1, int y1, int x2, int y2) {\n    if (x1 == x2 - 1 && y1 == y2 - 1) return true;\n    if (x1 == x2 - 1 && y1 == y2) return true;\n    if (x1 == x2 && y1 == y2 - 1) return true;\n    if (x1 == x2 && y1 == y2 + 1) return true;\n    if (x1 == x2 + 1 && y1 == y2) return true;\n    if (x1 == x2 + 1 && y1 == y2 + 1) return true;\n    return false;\n}\n\nvoid swap_balls(int x1, int y1, int x2, int y2) {\n    swap(pyramid[x1][y1], pyramid[x2][y2]);\n    operations.push_back({x1, y1, x2, y2});\n}\n\nint count_violations() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] > pyramid[x + 1][y]) violations++;\n            if (pyramid[x][y] > pyramid[x + 1][y + 1]) violations++;\n        }\n    }\n    return violations;\n}\n\nvoid greedy_algorithm() {\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] > pyramid[x + 1][y]) {\n                if (is_adjacent(x, y, x + 1, y)) {\n                    swap_balls(x, y, x + 1, y);\n                } else {\n                    // Find a path to swap\n                    // This is a simplified approach; a more sophisticated pathfinding algorithm can be used here\n                    for (int i = x + 1; i < N; ++i) {\n                        if (is_adjacent(i, y, i + 1, y)) {\n                            swap_balls(i, y, i + 1, y);\n                        }\n                    }\n                }\n            }\n            if (pyramid[x][y] > pyramid[x + 1][y + 1]) {\n                if (is_adjacent(x, y, x + 1, y + 1)) {\n                    swap_balls(x, y, x + 1, y + 1);\n                } else {\n                    // Find a path to swap\n                    // This is a simplified approach; a more sophisticated pathfinding algorithm can be used here\n                    for (int i = x + 1; i < N; ++i) {\n                        if (is_adjacent(i, y + 1, i + 1, y + 1)) {\n                            swap_balls(i, y + 1, i + 1, y + 1);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid simulated_annealing() {\n    int current_violations = count_violations();\n    if (current_violations == 0) return;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    double temperature = 1.0;\n    double cooling_rate = 0.999;\n    int max_iterations = 10000;\n\n    for (int iter = 0; iter < max_iterations && current_violations > 0; ++iter) {\n        // Randomly select two adjacent balls to swap\n        int x1 = dis(gen) * N;\n        int y1 = dis(gen) * (x1 + 1);\n        int direction = dis(gen) * 6;\n\n        int x2, y2;\n        switch (direction) {\n            case 0: x2 = x1 - 1; y2 = y1 - 1; break;\n            case 1: x2 = x1 - 1; y2 = y1; break;\n            case 2: x2 = x1; y2 = y1 - 1; break;\n            case 3: x2 = x1; y2 = y1 + 1; break;\n            case 4: x2 = x1 + 1; y2 = y1; break;\n            case 5: x2 = x1 + 1; y2 = y1 + 1; break;\n        }\n\n        if (x2 < 0 || x2 >= N || y2 < 0 || y2 > x2) continue;\n\n        swap_balls(x1, y1, x2, y2);\n        int new_violations = count_violations();\n\n        if (new_violations < current_violations) {\n            current_violations = new_violations;\n        } else {\n            double probability = exp((current_violations - new_violations) / temperature);\n            if (dis(gen) > probability) {\n                swap_balls(x1, y1, x2, y2); // Revert the swap\n            } else {\n                current_violations = new_violations;\n            }\n        }\n\n        temperature *= cooling_rate;\n    }\n}\n\nint main() {\n    pyramid.resize(N);\n    for (int x = 0; x < N; ++x) {\n        pyramid[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> pyramid[x][y];\n        }\n    }\n\n    greedy_algorithm();\n    simulated_annealing();\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.x1 << \" \" << op.y1 << \" \" << op.x2 << \" \" << op.y2 << 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#include <utility>\n#include <cmath>\n\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = (D - 1) / 2;\n\nstruct Point {\n    int i, j;\n    Point(int i, int j) : i(i), j(j) {}\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.i) ^ hash<int>()(p.j);\n        }\n    };\n}\n\nvector<Point> get_neighbors(const Point& p, const unordered_set<Point>& obstacles) {\n    vector<Point> neighbors;\n    int di[] = {-1, 1, 0, 0};\n    int dj[] = {0, 0, -1, 1};\n    for (int k = 0; k < 4; ++k) {\n        Point neighbor(p.i + di[k], p.j + dj[k]);\n        if (neighbor.i >= 0 && neighbor.i < D && neighbor.j >= 0 && neighbor.j < D &&\n            obstacles.find(neighbor) == obstacles.end()) {\n            neighbors.push_back(neighbor);\n        }\n    }\n    return neighbors;\n}\n\nvector<vector<int>> bfs(const unordered_set<Point>& obstacles) {\n    vector<vector<int>> distance(D, vector<int>(D, -1));\n    queue<Point> q;\n    Point entrance(ENTRANCE_I, ENTRANCE_J);\n    distance[entrance.i][entrance.j] = 0;\n    q.push(entrance);\n\n    while (!q.empty()) {\n        Point current = q.front();\n        q.pop();\n        for (const Point& neighbor : get_neighbors(current, obstacles)) {\n            if (distance[neighbor.i][neighbor.j] == -1) {\n                distance[neighbor.i][neighbor.j] = distance[current.i][current.j] + 1;\n                q.push(neighbor);\n            }\n        }\n    }\n    return distance;\n}\n\nPoint find_storage_location(const unordered_set<Point>& obstacles, const vector<vector<int>>& distance, const unordered_set<Point>& occupied) {\n    vector<Point> candidates;\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            Point p(i, j);\n            if (distance[i][j] != -1 && obstacles.find(p) == obstacles.end() && occupied.find(p) == occupied.end()) {\n                candidates.push_back(p);\n            }\n        }\n    }\n    if (candidates.empty()) {\n        return Point(-1, -1); // No valid storage location\n    }\n    // Sort candidates by distance from entrance and then by some heuristic\n    sort(candidates.begin(), candidates.end(), [&distance](const Point& a, const Point& b) {\n        return distance[a.i][a.j] < distance[b.i][b.j];\n    });\n    return candidates[0];\n}\n\nvector<Point> find_retrieval_order(const unordered_set<Point>& obstacles, const vector<vector<Point>>& storage_order) {\n    vector<vector<int>> distance = bfs(obstacles);\n    unordered_set<Point> occupied;\n    for (const auto& row : storage_order) {\n        for (const Point& p : row) {\n            if (p.i != -1 && p.j != -1) {\n                occupied.insert(p);\n            }\n        }\n    }\n    vector<Point> retrieval_order;\n    while (!occupied.empty()) {\n        vector<Point> candidates;\n        for (const Point& p : occupied) {\n            if (distance[p.i][p.j] != -1) {\n                candidates.push_back(p);\n            }\n        }\n        if (candidates.empty()) {\n            break; // No more reachable containers\n        }\n        // Sort candidates by distance from entrance and then by some heuristic\n        sort(candidates.begin(), candidates.end(), [&distance](const Point& a, const Point& b) {\n            return distance[a.i][a.j] < distance[b.i][b.j];\n        });\n        Point next = candidates[0];\n        retrieval_order.push_back(next);\n        occupied.erase(next);\n        // Update distance for adjacent squares\n        for (const Point& neighbor : get_neighbors(next, obstacles)) {\n            if (occupied.find(neighbor) == occupied.end()) {\n                distance[neighbor.i][neighbor.j] = -1;\n            }\n        }\n    }\n    return retrieval_order;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    unordered_set<Point> obstacles;\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        obstacles.insert(Point(ri, rj));\n    }\n    vector<vector<int>> distance = bfs(obstacles);\n    unordered_set<Point> occupied;\n    vector<vector<Point>> storage_order(D, vector<Point>(D, Point(-1, -1)));\n    for (int d = 0; d < D * D - 1 - N; ++d) {\n        int t_d;\n        cin >> t_d;\n        Point storage_location = find_storage_location(obstacles, distance, occupied);\n        if (storage_location.i == -1 && storage_location.j == -1) {\n            cerr << \"No valid storage location found for container \" << t_d << endl;\n            return 1;\n        }\n        storage_order[storage_location.i][storage_location.j] = Point(t_d, d);\n        occupied.insert(storage_location);\n        cout << storage_location.i << \" \" << storage_location.j << endl;\n        cout.flush();\n    }\n    vector<Point> retrieval_order = find_retrieval_order(obstacles, storage_order);\n    for (const Point& p : retrieval_order) {\n        cout << p.i << \" \" << p.j << endl;\n    }\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <unordered_set>\n#include <algorithm>\n#include <atcoder/dsu>\n#include <atcoder/maxflow>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nvector<vector<int>> grid;\nvector<vector<int>> simplified_grid;\nint n, m;\n\nvoid bfs(int x, int y, int color, vector<vector<bool>>& visited) {\n    queue<Point> q;\n    q.push(Point(x, y));\n    visited[x][y] = true;\n    simplified_grid[x][y] = color;\n\n    while (!q.empty()) {\n        Point p = q.front();\n        q.pop();\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = p.x + dx[i];\n            int ny = p.y + dy[i];\n\n            if (nx >= 0 && nx < n && ny >= 0 && ny < n && !visited[nx][ny] && grid[nx][ny] == color) {\n                visited[nx][ny] = true;\n                simplified_grid[nx][ny] = color;\n                q.push(Point(nx, ny));\n            }\n        }\n    }\n}\n\nvoid simplify_map() {\n    simplified_grid = vector<vector<int>>(n, vector<int>(n, 0));\n    vector<vector<bool>> visited(n, vector<bool>(n, false));\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (!visited[i][j] && grid[i][j] != 0) {\n                bfs(i, j, grid[i][j], visited);\n            }\n        }\n    }\n}\n\nvoid connect_components() {\n    dsu d(n * n);\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] != 0) {\n                for (int k = 0; k < 4; ++k) {\n                    int ni = i + dx[k];\n                    int nj = j + dy[k];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && simplified_grid[ni][nj] != 0) {\n                        d.merge(i * n + j, ni * n + nj);\n                    }\n                }\n            }\n        }\n    }\n\n    unordered_map<int, vector<Point>> components;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] != 0) {\n                components[d.leader(i * n + j)].push_back(Point(i, j));\n            }\n        }\n    }\n\n    for (auto& [leader, points] : components) {\n        for (auto& p : points) {\n            simplified_grid[p.x][p.y] = simplified_grid[points[0].x][points[0].y];\n        }\n    }\n}\n\nvoid minimize_connectors() {\n    // This is a placeholder for a more sophisticated heuristic\n    // For simplicity, we'll just ensure that the connectors are minimal\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] == 0) {\n                bool is_connector = false;\n                for (int k = 0; k < 4; ++k) {\n                    int ni = i + dx[k];\n                    int nj = j + dy[k];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && simplified_grid[ni][nj] != 0) {\n                        is_connector = true;\n                        break;\n                    }\n                }\n                if (!is_connector) {\n                    simplified_grid[i][j] = 0;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> n >> m;\n    grid.resize(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    simplify_map();\n    connect_components();\n    minimize_connectors();\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cout << simplified_grid[i][j] << (j == n - 1 ? \"\\n\" : \" \");\n        }\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <iomanip>\n#include <climits>\n#include <cfloat>\n#include <cstring>\n#include <cassert>\n#include <chrono>\n#include <fstream>\n#include <sstream>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<pii> vpii;\ntypedef vector<pll> vpll;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef vector<vpii> vvpii;\ntypedef vector<vpll> vvpll;\ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\ntypedef tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;\n\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define lb lower_bound\n#define ub upper_bound\n\nconst int INF = 1e9;\nconst ll LINF = 1e18;\nconst ld EPS = 1e-9;\nconst int MOD = 1e9 + 7;\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint n, d, q;\nvector<double> weights;\nvector<int> groups;\n\nchar compare(const vector<int>& l, const vector<int>& r) {\n    cout << l.size() << \" \" << r.size();\n    for (int i : l) cout << \" \" << i;\n    for (int i : r) cout << \" \" << i;\n    cout << endl;\n    char res;\n    cin >> res;\n    return res;\n}\n\nvoid estimate_weights() {\n    weights.resize(n, 0.0);\n    for (int i = 0; i < n; ++i) {\n        for (int j = i + 1; j < n; ++j) {\n            char res = compare({i}, {j});\n            if (res == '<') {\n                weights[j] += 1.0;\n            } else if (res == '>') {\n                weights[i] += 1.0;\n            } else {\n                weights[i] += 0.5;\n                weights[j] += 0.5;\n            }\n        }\n    }\n}\n\nvoid assign_groups() {\n    groups.resize(n, 0);\n    vector<double> group_weights(d, 0.0);\n    for (int i = 0; i < n; ++i) {\n        int best_group = 0;\n        double min_diff = fabs(group_weights[0] - weights[i]);\n        for (int j = 1; j < d; ++j) {\n            double diff = fabs(group_weights[j] - weights[i]);\n            if (diff < min_diff) {\n                min_diff = diff;\n                best_group = j;\n            }\n        }\n        groups[i] = best_group;\n        group_weights[best_group] += weights[i];\n    }\n}\n\nvoid refine_weights() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = i + 1; j < n; ++j) {\n            if (groups[i] != groups[j]) {\n                char res = compare({i}, {j});\n                if (res == '<') {\n                    weights[j] += 1.0;\n                } else if (res == '>') {\n                    weights[i] += 1.0;\n                } else {\n                    weights[i] += 0.5;\n                    weights[j] += 0.5;\n                }\n            }\n        }\n    }\n}\n\nvoid solve() {\n    estimate_weights();\n    assign_groups();\n    refine_weights();\n    assign_groups();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> n >> d >> q;\n    solve();\n\n    for (int i = 0; i < n; ++i) {\n        cout << groups[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cassert>\n\nusing namespace std;\n\nconst int n = 200;\nconst int m = 10;\nconst int max_operations = 5000;\n\nvector<vector<int>> stacks(m, vector<int>(n / m));\n\nvoid read_input() {\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < n / m; ++j) {\n            cin >> stacks[i][j];\n        }\n    }\n}\n\nint find_stack(int v) {\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < stacks[i].size(); ++j) {\n            if (stacks[i][j] == v) {\n                return i;\n            }\n        }\n    }\n    return -1;\n}\n\nint find_position(int i, int v) {\n    for (int j = 0; j < stacks[i].size(); ++j) {\n        if (stacks[i][j] == v) {\n            return j;\n        }\n    }\n    return -1;\n}\n\nvoid move_box(int v, int dest_stack) {\n    int src_stack = find_stack(v);\n    int pos = find_position(src_stack, v);\n\n    vector<int> moved_boxes(stacks[src_stack].begin() + pos, stacks[src_stack].end());\n    stacks[src_stack].erase(stacks[src_stack].begin() + pos, stacks[src_stack].end());\n\n    stacks[dest_stack].insert(stacks[dest_stack].end(), moved_boxes.begin(), moved_boxes.end());\n}\n\nint find_smallest_remaining() {\n    int smallest = n + 1;\n    for (int i = 0; i < m; ++i) {\n        if (!stacks[i].empty()) {\n            smallest = min(smallest, stacks[i][0]);\n        }\n    }\n    return smallest;\n}\n\nbool is_smallest_at_top(int v) {\n    for (int i = 0; i < m; ++i) {\n        if (!stacks[i].empty() && stacks[i][0] == v) {\n            return true;\n        }\n    }\n    return false;\n}\n\nvector<pair<int, int>> solve() {\n    vector<pair<int, int>> operations;\n    int current_smallest = 1;\n\n    while (current_smallest <= n) {\n        if (is_smallest_at_top(current_smallest)) {\n            operations.emplace_back(current_smallest, 0);\n            current_smallest++;\n        } else {\n            int src_stack = find_stack(current_smallest);\n            int dest_stack = -1;\n            int min_size = n + 1;\n\n            for (int i = 0; i < m; ++i) {\n                if (i != src_stack && stacks[i].size() < min_size) {\n                    min_size = stacks[i].size();\n                    dest_stack = i;\n                }\n            }\n\n            if (dest_stack == -1) {\n                // No other stack available, move to any other stack\n                for (int i = 0; i < m; ++i) {\n                    if (i != src_stack) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n\n            operations.emplace_back(current_smallest, dest_stack + 1);\n            move_box(current_smallest, dest_stack);\n        }\n    }\n\n    return operations;\n}\n\nint main() {\n    read_input();\n    auto operations = solve();\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 <queue>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Square {\n    int i, j;\n    int dirtiness;\n    bool operator<(const Square& other) const {\n        return dirtiness < other.dirtiness;\n    }\n};\n\nvector<vector<int>> generateRoute(int N, const vector<vector<int>>& h, const vector<vector<int>>& v, const vector<vector<int>>& d) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    vector<vector<int>> route;\n    priority_queue<Square> pq;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            pq.push({i, j, d[i][j]});\n        }\n    }\n\n    auto isValidMove = [&](int i, int j, int di, int dj) {\n        if (di == 0) {\n            if (dj == 1) return j < N - 1 && v[i][j] == 0;\n            else return j > 0 && v[i][j - 1] == 0;\n        } else {\n            if (di == 1) return i < N - 1 && h[i][j] == 0;\n            else return i > 0 && h[i - 1][j] == 0;\n        }\n    };\n\n    auto dfs = [&](auto&& self, int i, int j) -> void {\n        visited[i][j] = true;\n        vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        vector<char> dirChars = {'R', 'D', 'L', 'U'};\n\n        // Prioritize high-dirtiness squares\n        vector<pair<int, int>> highDirtinessSquares;\n        for (const auto& dir : directions) {\n            int ni = i + dir.first;\n            int nj = j + dir.second;\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj] && isValidMove(i, j, dir.first, dir.second)) {\n                highDirtinessSquares.emplace_back(ni, nj);\n            }\n        }\n        sort(highDirtinessSquares.begin(), highDirtinessSquares.end(), [&](const auto& a, const auto& b) {\n            return d[a.first][a.second] > d[b.first][b.second];\n        });\n\n        for (const auto& sq : highDirtinessSquares) {\n            int ni = sq.first;\n            int nj = sq.second;\n            if (!visited[ni][nj]) {\n                for (size_t k = 0; k < directions.size(); ++k) {\n                    if (ni == i + directions[k].first && nj == j + directions[k].second) {\n                        route.push_back({i, j, ni, nj, dirChars[k]});\n                        break;\n                    }\n                }\n                self(self, ni, nj);\n            }\n        }\n    };\n\n    dfs(dfs, 0, 0);\n\n    // Ensure all squares are visited\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!visited[i][j]) {\n                // Find a path to the unvisited square\n                vector<vector<int>> dist(N, vector<int>(N, -1));\n                queue<pair<int, int>> q;\n                q.push({i, j});\n                dist[i][j] = 0;\n                vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n\n                while (!q.empty()) {\n                    auto [ci, cj] = q.front();\n                    q.pop();\n                    for (const auto& dir : directions) {\n                        int ni = ci + dir.first;\n                        int nj = cj + dir.second;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist[ni][nj] == -1 && isValidMove(ci, cj, dir.first, dir.second)) {\n                            dist[ni][nj] = dist[ci][cj] + 1;\n                            parent[ni][nj] = {ci, cj};\n                            q.push({ni, nj});\n                        }\n                    }\n                }\n\n                // Reconstruct path\n                vector<pair<int, int>> path;\n                for (int x = 0; x < N; ++x) {\n                    for (int y = 0; y < N; ++y) {\n                        if (visited[x][y]) {\n                            int current_i = x, current_j = y;\n                            while (current_i != -1 && current_j != -1) {\n                                path.emplace_back(current_i, current_j);\n                                auto [pi, pj] = parent[current_i][current_j];\n                                current_i = pi;\n                                current_j = pj;\n                            }\n                            reverse(path.begin(), path.end());\n                            break;\n                        }\n                    }\n                    if (!path.empty()) break;\n                }\n\n                for (size_t k = 1; k < path.size(); ++k) {\n                    auto [pi, pj] = path[k - 1];\n                    auto [ci, cj] = path[k];\n                    for (size_t l = 0; l < directions.size(); ++l) {\n                        if (ci == pi + directions[l].first && cj == pj + directions[l].second) {\n                            route.push_back({pi, pj, ci, cj, dirChars[l]});\n                            break;\n                        }\n                    }\n                }\n                dfs(dfs, i, j);\n            }\n        }\n    }\n\n    // Convert route to string\n    vector<char> result;\n    for (const auto& move : route) {\n        result.push_back(move[4]);\n    }\n\n    // Ensure the route returns to (0, 0)\n    if (route.back()[2] != 0 || route.back()[3] != 0) {\n        // Find a path back to (0, 0)\n        vector<vector<int>> dist(N, vector<int>(N, -1));\n        queue<pair<int, int>> q;\n        q.push({route.back()[2], route.back()[3]});\n        dist[route.back()[2]][route.back()[3]] = 0;\n        vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n\n        while (!q.empty()) {\n            auto [ci, cj] = q.front();\n            q.pop();\n            for (const auto& dir : directions) {\n                int ni = ci + dir.first;\n                int nj = cj + dir.second;\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist[ni][nj] == -1 && isValidMove(ci, cj, dir.first, dir.second)) {\n                    dist[ni][nj] = dist[ci][cj] + 1;\n                    parent[ni][nj] = {ci, cj};\n                    q.push({ni, nj});\n                }\n            }\n        }\n\n        // Reconstruct path\n        vector<pair<int, int>> path;\n        int current_i = 0, current_j = 0;\n        while (current_i != -1 && current_j != -1) {\n            path.emplace_back(current_i, current_j);\n            auto [pi, pj] = parent[current_i][current_j];\n            current_i = pi;\n            current_j = pj;\n        }\n        reverse(path.begin(), path.end());\n\n        for (size_t k = 1; k < path.size(); ++k) {\n            auto [pi, pj] = path[k - 1];\n            auto [ci, cj] = path[k];\n            for (size_t l = 0; l < directions.size(); ++l) {\n                if (ci == pi + directions[l].first && cj == pj + directions[l].second) {\n                    result.push_back(dirChars[l]);\n                    break;\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int N;\n    cin >> N;\n\n    vector<vector<int>> h(N - 1, vector<int>(N));\n    for (int i = 0; i < N - 1; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            h[i][j] = row[j] - '0';\n        }\n    }\n\n    vector<vector<int>> v(N, vector<int>(N - 1));\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N - 1; ++j) {\n            v[i][j] = row[j] - '0';\n        }\n    }\n\n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    vector<char> route = generateRoute(N, h, v, d);\n\n    for (char move : route) {\n        cout << move;\n    }\n    cout << endl;\n\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nstruct State {\n    int i, j;\n    unordered_set<int> included;\n    int cost;\n\n    bool operator>(const State& other) const {\n        return cost > other.cost;\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int s_i, s_j;\n    cin >> s_i >> s_j;\n\n    vector<vector<char>> keyboard(N, vector<char>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> keyboard[i][j];\n        }\n    }\n\n    vector<string> t(M);\n    for (int k = 0; k < M; ++k) {\n        cin >> t[k];\n    }\n\n    // Preprocess the positions of each character\n    unordered_map<char, vector<pair<int, int>>> char_positions;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char_positions[keyboard[i][j]].emplace_back(i, j);\n        }\n    }\n\n    // Priority queue for Dijkstra's algorithm\n    priority_queue<State, vector<State>, greater<State>> pq;\n    pq.push({s_i, s_j, {}, 0});\n\n    // Visited set to avoid revisiting the same state\n    unordered_map<int, unordered_map<int, unordered_set<int>>> visited;\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.included.size() == M) {\n            // Found a solution, output the path\n            // (In a real implementation, you would need to reconstruct the path)\n            // For simplicity, we assume the path is stored and output here\n            cout << \"Solution found with cost \" << current.cost << endl;\n            return 0;\n        }\n\n        if (visited[current.i][current.j].count(current.included.size())) {\n            continue;\n        }\n        visited[current.i][current.j].insert(current.included.size());\n\n        // Explore all possible next characters\n        for (const auto& entry : char_positions) {\n            char c = entry.first;\n            for (const auto& pos : entry.second) {\n                int next_i = pos.first;\n                int next_j = pos.second;\n\n                // Calculate the cost to move to this character\n                int move_cost = abs(next_i - current.i) + abs(next_j - current.j) + 1;\n\n                // Check if adding this character includes any new lucky words\n                unordered_set<int> new_included = current.included;\n                for (int k = 0; k < M; ++k) {\n                    if (new_included.count(k)) continue;\n                    // Check if the new character includes the k-th lucky word\n                    // This is a simplified check; in practice, you would need a more efficient way\n                    // For example, using a suffix automaton or a rolling hash\n                    string s;\n                    // Reconstruct the string from the current state (simplified)\n                    // In a real implementation, you would need to keep track of the string\n                    if (s.find(t[k]) != string::npos) {\n                        new_included.insert(k);\n                    }\n                }\n\n                if (new_included.size() > current.included.size()) {\n                    pq.push({next_i, next_j, new_included, current.cost + move_cost});\n                }\n            }\n        }\n    }\n\n    cout << \"No solution found within the operation limit.\" << endl;\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <set>\n#include <random>\n#include <cmath>\n#include <algorithm>\n#include <atcoder/random>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Square {\n    int i, j;\n    Square(int i, int j) : i(i), j(j) {}\n    bool operator<(const Square& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nstruct OilField {\n    vector<Square> squares;\n    int di, dj;\n};\n\nvector<OilField> fields;\nint N, M;\ndouble epsilon;\n\nvoid read_input() {\n    cin >> N >> M >> epsilon;\n    fields.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        fields[k].squares.resize(d);\n        for (int l = 0; l < d; ++l) {\n            cin >> fields[k].squares[l].i >> fields[k].squares[l].j;\n        }\n    }\n}\n\nvoid drill(int i, int j) {\n    cout << \"q 1 \" << i << \" \" << j << endl;\n    cout.flush();\n    int v;\n    cin >> v;\n    // Update the oil reserves for the square (i, j)\n}\n\nint divinate(const vector<Square>& squares) {\n    cout << \"q \" << squares.size();\n    for (const auto& sq : squares) {\n        cout << \" \" << sq.i << \" \" << sq.j;\n    }\n    cout << endl;\n    cout.flush();\n    int v;\n    cin >> v;\n    return v;\n}\n\nvoid guess(const set<Square>& squares) {\n    cout << \"a \" << squares.size();\n    for (const auto& sq : squares) {\n        cout << \" \" << sq.i << \" \" << sq.j;\n    }\n    cout << endl;\n    cout.flush();\n    int correct;\n    cin >> correct;\n    if (correct) {\n        exit(0);\n    }\n}\n\nint main() {\n    read_input();\n\n    // Initial random drilling\n    set<Square> drilled;\n    mt19937 rng(random_device{}());\n    uniform_int_distribution<int> dist(0, N - 1);\n    for (int k = 0; k < 10; ++k) {\n        int i = dist(rng);\n        int j = dist(rng);\n        drill(i, j);\n        drilled.insert(Square(i, j));\n    }\n\n    // Divination to estimate total oil reserves\n    vector<Square> all_squares;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            all_squares.emplace_back(i, j);\n        }\n    }\n    int total_estimate = divinate(all_squares);\n\n    // Heuristic guided drilling\n    set<Square> candidates;\n    for (const auto& field : fields) {\n        for (const auto& sq : field.squares) {\n            candidates.insert(sq);\n        }\n    }\n\n    while (true) {\n        // Prioritize squares that are part of the polyominoes with the highest estimated oil reserves\n        vector<Square> to_divinate;\n        for (const auto& sq : candidates) {\n            if (drilled.find(sq) == drilled.end()) {\n                to_divinate.push_back(sq);\n            }\n        }\n\n        if (to_divinate.empty()) break;\n\n        // Divinate a subset of candidates\n        int k = min(10, (int)to_divinate.size());\n        vector<Square> subset(to_divinate.begin(), to_divinate.begin() + k);\n        int estimate = divinate(subset);\n\n        // Update the set of candidates based on the estimate\n        for (const auto& sq : subset) {\n            if (estimate > 0) {\n                candidates.insert(sq);\n            } else {\n                candidates.erase(sq);\n            }\n        }\n\n        // Drill a square from the candidates\n        if (!candidates.empty()) {\n            auto it = candidates.begin();\n            advance(it, dist(rng) % candidates.size());\n            Square sq = *it;\n            drill(sq.i, sq.j);\n            drilled.insert(sq);\n        }\n\n        // Guess the set of squares with oil reserves\n        if (drilled.size() >= 10) {\n            guess(drilled);\n        }\n    }\n\n    return 0;\n}","ahc031":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <climits>\n\nusing namespace std;\n\nstruct Rectangle {\n    int i0, j0, i1, j1;\n    Rectangle(int i0, int j0, int i1, int j1) : i0(i0), j0(j0), i1(i1), j1(j1) {}\n    int area() const { return (i1 - i0) * (j1 - j0); }\n};\n\nstruct Solution {\n    vector<vector<Rectangle>> rectangles;\n    int total_cost;\n};\n\nint calculate_area_cost(const vector<vector<int>>& a, const Solution& sol) {\n    int cost = 0;\n    for (int d = 0; d < sol.rectangles.size(); ++d) {\n        for (int k = 0; k < sol.rectangles[d].size(); ++k) {\n            int b = sol.rectangles[d][k].area();\n            if (a[d][k] > b) {\n                cost += 100 * (a[d][k] - b);\n            }\n        }\n    }\n    return cost;\n}\n\nint calculate_partition_cost(const Solution& prev_sol, const Solution& curr_sol) {\n    int cost = 0;\n    for (int d = 0; d < curr_sol.rectangles.size(); ++d) {\n        if (d == 0) continue; // No partition cost on the first day\n        for (int i = 1; i < 1000; ++i) {\n            for (int j = 0; j < 999; ++j) {\n                bool prev_has_horizontal = false;\n                bool curr_has_horizontal = false;\n                for (const auto& rect : prev_sol.rectangles[d-1]) {\n                    if ((rect.i0 == i && rect.j0 <= j && rect.j1 > j) ||\n                        (rect.i1 == i && rect.j0 <= j && rect.j1 > j)) {\n                        prev_has_horizontal = true;\n                        break;\n                    }\n                }\n                for (const auto& rect : curr_sol.rectangles[d]) {\n                    if ((rect.i0 == i && rect.j0 <= j && rect.j1 > j) ||\n                        (rect.i1 == i && rect.j0 <= j && rect.j1 > j)) {\n                        curr_has_horizontal = true;\n                        break;\n                    }\n                }\n                if (prev_has_horizontal != curr_has_horizontal) {\n                    cost++;\n                }\n            }\n        }\n        for (int i = 0; i < 999; ++i) {\n            for (int j = 1; j < 1000; ++j) {\n                bool prev_has_vertical = false;\n                bool curr_has_vertical = false;\n                for (const auto& rect : prev_sol.rectangles[d-1]) {\n                    if ((rect.j0 == j && rect.i0 <= i && rect.i1 > i) ||\n                        (rect.j1 == j && rect.i0 <= i && rect.i1 > i)) {\n                        prev_has_vertical = true;\n                        break;\n                    }\n                }\n                for (const auto& rect : curr_sol.rectangles[d]) {\n                    if ((rect.j0 == j && rect.i0 <= i && rect.i1 > i) ||\n                        (rect.j1 == j && rect.i0 <= i && rect.i1 > i)) {\n                        curr_has_vertical = true;\n                        break;\n                    }\n                }\n                if (prev_has_vertical != curr_has_vertical) {\n                    cost++;\n                }\n            }\n        }\n    }\n    return cost;\n}\n\nSolution greedy_solution(const vector<vector<int>>& a) {\n    Solution sol;\n    sol.rectangles.resize(a.size());\n    for (int d = 0; d < a.size(); ++d) {\n        vector<int> remaining_area = a[d];\n        sort(remaining_area.rbegin(), remaining_area.rend());\n        vector<pair<int, int>> positions;\n        for (int i = 0; i < 1000; ++i) {\n            for (int j = 0; j < 1000; ++j) {\n                positions.emplace_back(i, j);\n            }\n        }\n        random_device rd;\n        mt19937 g(rd());\n        shuffle(positions.begin(), positions.end(), g);\n        for (int k = 0; k < a[d].size(); ++k) {\n            int best_area = 0;\n            Rectangle best_rect(0, 0, 0, 0);\n            for (const auto& pos : positions) {\n                int i0 = pos.first;\n                int j0 = pos.second;\n                for (int i1 = i0 + 1; i1 <= 1000; ++i1) {\n                    for (int j1 = j0 + 1; j1 <= 1000; ++j1) {\n                        int area = (i1 - i0) * (j1 - j0);\n                        if (area > remaining_area[k]) continue;\n                        if (area > best_area) {\n                            best_area = area;\n                            best_rect = Rectangle(i0, j0, i1, j1);\n                        }\n                    }\n                }\n            }\n            sol.rectangles[d].push_back(best_rect);\n            remaining_area[k] -= best_area;\n        }\n    }\n    sol.total_cost = calculate_area_cost(a, sol) + calculate_partition_cost(sol, sol);\n    return sol;\n}\n\nSolution simulated_annealing(const vector<vector<int>>& a, const Solution& initial_sol, double initial_temp, double cooling_rate, int iterations) {\n    Solution current_sol = initial_sol;\n    Solution best_sol = initial_sol;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    double temp = initial_temp;\n    for (int iter = 0; iter < iterations; ++iter) {\n        Solution new_sol = current_sol;\n        int d = rand() % a.size();\n        int k = rand() % a[d].size();\n        int i0 = rand() % 1000;\n        int j0 = rand() % 1000;\n        int i1 = i0 + 1 + rand() % (1000 - i0);\n        int j1 = j0 + 1 + rand() % (1000 - j0);\n        new_sol.rectangles[d][k] = Rectangle(i0, j0, i1, j1);\n        int new_area_cost = calculate_area_cost(a, new_sol);\n        int new_partition_cost = calculate_partition_cost(current_sol, new_sol);\n        int new_total_cost = new_area_cost + new_partition_cost;\n        if (new_total_cost < current_sol.total_cost || dis(gen) < exp((current_sol.total_cost - new_total_cost) / temp)) {\n            current_sol = new_sol;\n            current_sol.total_cost = new_total_cost;\n            if (new_total_cost < best_sol.total_cost) {\n                best_sol = new_sol;\n                best_sol.total_cost = new_total_cost;\n            }\n        }\n        temp *= cooling_rate;\n    }\n    return best_sol;\n}\n\nint main() {\n    int W, D, N;\n    cin >> W >> D >> N;\n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cin >> a[d][k];\n        }\n    }\n    Solution initial_sol = greedy_solution(a);\n    Solution best_sol = simulated_annealing(a, initial_sol, 1000.0, 0.999, 10000);\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << best_sol.rectangles[d][k].i0 << \" \" << best_sol.rectangles[d][k].j0 << \" \"\n                 << best_sol.rectangles[d][k].i1 << \" \" << best_sol.rectangles[d][k].j1 << endl;\n        }\n    }\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\n\nstruct Stamp {\n    int s[3][3];\n};\n\nstruct Operation {\n    int m, p, q;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int a[N][N];\n    Stamp stamps[M];\n\n    // Read initial grid\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> a[i][j];\n        }\n    }\n\n    // Read stamps\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].s[i][j];\n            }\n        }\n    }\n\n    vector<Operation> operations;\n    int current_sum = 0;\n\n    // Calculate initial sum\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            current_sum = (current_sum + a[i][j] % MOD) % MOD;\n        }\n    }\n\n    // Greedy approach\n    for (int op = 0; op < K; ++op) {\n        int best_m = -1, best_p = -1, best_q = -1;\n        int max_increase = 0;\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    int increase = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            int new_val = (a[p + i][q + j] + stamps[m].s[i][j]) % MOD;\n                            increase += (new_val - (a[p + i][q + j] % MOD)) % MOD;\n                        }\n                    }\n                    if (increase > max_increase) {\n                        max_increase = increase;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_m == -1) break; // No more beneficial operations\n\n        operations.push_back({best_m, best_p, best_q});\n\n        // Apply the best operation\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                a[best_p + i][best_q + j] = (a[best_p + i][best_q + j] + stamps[best_m].s[i][j]) % MOD;\n            }\n        }\n\n        current_sum = (current_sum + max_increase) % MOD;\n    }\n\n    // Output the operations\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.m << \" \" << op.p << \" \" << op.q << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_map>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURNS = 10000;\n\nstruct Crane {\n    int x, y;\n    bool is_large;\n    bool holding;\n    int container;\n};\n\nstruct Container {\n    int x, y;\n    int number;\n};\n\nvector<vector<int>> A(N, vector<int>(N));\nvector<Crane> cranes;\nvector<vector<int>> grid(N, vector<int>(N, -1));\nvector<vector<int>> next_container(N, vector<int>(N, 0));\nvector<string> actions(N, string(MAX_TURNS, '.'));\n\nint calculate_score() {\n    // Implement scoring logic here\n    return 0;\n}\n\nvoid simulate_turn() {\n    // Step 1: Bring in new containers\n    for (int i = 0; i < N; ++i) {\n        if (next_container[i][0] < N && grid[i][0] == -1) {\n            grid[i][0] = A[i][next_container[i][0]];\n            next_container[i][0]++;\n        }\n    }\n\n    // Step 2: Perform crane actions\n    vector<vector<int>> new_grid(N, vector<int>(N, -1));\n    vector<Crane> new_cranes;\n    for (int i = 0; i < N; ++i) {\n        Crane c = cranes[i];\n        char action = actions[i][0];\n        actions[i].erase(0, 1);\n\n        if (action == 'B' && !c.holding) {\n            continue; // Crane is bombed\n        }\n\n        switch (action) {\n            case 'P':\n                if (!c.holding && grid[c.x][c.y] != -1) {\n                    c.holding = true;\n                    c.container = grid[c.x][c.y];\n                    grid[c.x][c.y] = -1;\n                }\n                break;\n            case 'Q':\n                if (c.holding && grid[c.x][c.y] == -1) {\n                    grid[c.x][c.y] = c.container;\n                    c.holding = false;\n                }\n                break;\n            case 'U':\n                if (c.x > 0 && (grid[c.x - 1][c.y] == -1 || c.is_large)) {\n                    c.x--;\n                }\n                break;\n            case 'D':\n                if (c.x < N - 1 && (grid[c.x + 1][c.y] == -1 || c.is_large)) {\n                    c.x++;\n                }\n                break;\n            case 'L':\n                if (c.y > 0 && (grid[c.x][c.y - 1] == -1 || c.is_large)) {\n                    c.y--;\n                }\n                break;\n            case 'R':\n                if (c.y < N - 1 && (grid[c.x][c.y + 1] == -1 || c.is_large)) {\n                    c.y++;\n                }\n                break;\n            case '.':\n                break;\n        }\n\n        if (action != 'B') {\n            new_cranes.push_back(c);\n        }\n    }\n    cranes = new_cranes;\n\n    // Step 3: Dispatch containers\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][N - 1] != -1) {\n            grid[i][N - 1] = -1;\n        }\n    }\n}\n\nvoid heuristic_solution() {\n    // Initialize cranes\n    for (int i = 0; i < N; ++i) {\n        cranes.push_back({i, 0, i == 0, false, -1});\n    }\n\n    // Simulate turns\n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        simulate_turn();\n\n        // Simple heuristic: Move cranes towards the right edge\n        for (int i = 0; i < N; ++i) {\n            Crane &c = cranes[i];\n            if (c.y < N - 1) {\n                actions[i][turn] = 'R';\n            } else if (c.y == N - 1 && c.holding) {\n                actions[i][turn] = 'Q';\n            } else if (c.y == N - 1 && !c.holding && grid[c.x][c.y] != -1) {\n                actions[i][turn] = 'P';\n            } else if (c.y == N - 1 && !c.holding && grid[c.x][c.y] == -1) {\n                actions[i][turn] = '.';\n            }\n        }\n    }\n}\n\nint main() {\n    // Read input\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n        }\n    }\n\n    // Run heuristic solution\n    heuristic_solution();\n\n    // Output actions\n    for (int i = 0; i < N; ++i) {\n        cout << actions[i] << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <climits>\n#include <unordered_map>\n#include <tuple>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_OPERATIONS = 100000;\nconst int MAX_SOIL = 1000000;\n\nstruct State {\n    int x, y;\n    int soil;\n    int cost;\n    vector<string> operations;\n\n    bool operator>(const State& other) const {\n        return cost > other.cost;\n    }\n};\n\nint heuristic(int x1, int y1, int x2, int y2, int soil) {\n    return abs(x1 - x2) + abs(y1 - y2) + soil;\n}\n\nvector<string> findPath(int startX, int startY, int endX, int endY, int soil) {\n    priority_queue<State, vector<State>, greater<State>> pq;\n    unordered_map<int, unordered_map<int, int>> visited;\n\n    pq.push({startX, startY, soil, 0, {}});\n    visited[startX][startY] = 0;\n\n    vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n    vector<string> dirChars = {\"U\", \"D\", \"L\", \"R\"};\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.x == endX && current.y == endY) {\n            return current.operations;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int newX = current.x + directions[i].first;\n            int newY = current.y + directions[i].second;\n\n            if (newX >= 0 && newX < N && newY >= 0 && newY < N) {\n                int newCost = current.cost + 100 + current.soil;\n                if (visited[newX][newY] == 0 || newCost < visited[newX][newY]) {\n                    visited[newX][newY] = newCost;\n                    vector<string> newOperations = current.operations;\n                    newOperations.push_back(dirChars[i]);\n                    pq.push({newX, newY, current.soil, newCost, newOperations});\n                }\n            }\n        }\n    }\n\n    return {};\n}\n\nvector<string> solve(vector<vector<int>>& grid) {\n    vector<string> operations;\n    int totalOperations = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == 0) continue;\n\n            int currentX = 0, currentY = 0;\n            int soil = 0;\n\n            // Move to the target square\n            vector<string> path = findPath(currentX, currentY, i, j, soil);\n            operations.insert(operations.end(), path.begin(), path.end());\n            currentX = i;\n            currentY = j;\n\n            // Load or unload soil\n            if (grid[i][j] > 0) {\n                int d = min(grid[i][j], MAX_SOIL);\n                operations.push_back(\"+\" + to_string(d));\n                soil += d;\n                grid[i][j] -= d;\n            } else {\n                int d = min(-grid[i][j], soil);\n                operations.push_back(\"-\" + to_string(d));\n                soil -= d;\n                grid[i][j] += d;\n            }\n\n            // Move back to the origin if there's soil to carry\n            if (soil > 0) {\n                path = findPath(currentX, currentY, 0, 0, soil);\n                operations.insert(operations.end(), path.begin(), path.end());\n                currentX = 0;\n                currentY = 0;\n            }\n\n            if (operations.size() >= MAX_OPERATIONS) break;\n        }\n        if (operations.size() >= MAX_OPERATIONS) break;\n    }\n\n    return operations;\n}\n\nint main() {\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<string> operations = solve(grid);\n    for (const string& op : operations) {\n        cout << op << endl;\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 6;\nconst int M = 15;\nconst int T = 10;\nconst int SEED_COUNT = 2 * N * (N - 1);\nconst int POPULATION_SIZE = 50;\nconst int GENERATIONS = 10;\nconst double MUTATION_RATE = 0.1;\n\nvector<vector<int>> X(SEED_COUNT, vector<int>(M, 0));\nvector<int> X_max(M, 0);\n\nstruct Individual {\n    vector<vector<int>> grid;\n    int fitness;\n\n    Individual() : grid(N, vector<int>(N, 0)), fitness(0) {}\n};\n\nvector<Individual> population(POPULATION_SIZE);\n\nvoid initializePopulation() {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, SEED_COUNT - 1);\n\n    for (auto& individual : population) {\n        vector<int> seeds(SEED_COUNT);\n        iota(seeds.begin(), seeds.end(), 0);\n        shuffle(seeds.begin(), seeds.end(), gen);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                individual.grid[i][j] = seeds[i * N + j];\n            }\n        }\n    }\n}\n\nvector<vector<int>> generateNewSeeds(const vector<vector<int>>& grid) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, 1);\n\n    vector<vector<int>> newSeeds(SEED_COUNT, vector<int>(M, 0));\n\n    int index = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N - 1; ++j) {\n            int seed1 = grid[i][j];\n            int seed2 = grid[i][j + 1];\n            for (int l = 0; l < M; ++l) {\n                newSeeds[index][l] = dist(gen) ? X[seed1][l] : X[seed2][l];\n            }\n            ++index;\n        }\n    }\n\n    for (int i = 0; i < N - 1; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int seed1 = grid[i][j];\n            int seed2 = grid[i + 1][j];\n            for (int l = 0; l < M; ++l) {\n                newSeeds[index][l] = dist(gen) ? X[seed1][l] : X[seed2][l];\n            }\n            ++index;\n        }\n    }\n\n    return newSeeds;\n}\n\nint calculateFitness(const vector<vector<int>>& grid) {\n    vector<vector<int>> currentSeeds = X;\n    for (int t = 0; t < T; ++t) {\n        currentSeeds = generateNewSeeds(grid);\n    }\n\n    int maxValue = 0;\n    for (const auto& seed : currentSeeds) {\n        int value = accumulate(seed.begin(), seed.end(), 0);\n        if (value > maxValue) {\n            maxValue = value;\n        }\n    }\n\n    int sumXMax = accumulate(X_max.begin(), X_max.end(), 0);\n    return round(1e6 * maxValue / sumXMax);\n}\n\nvoid evaluatePopulation() {\n    for (auto& individual : population) {\n        individual.fitness = calculateFitness(individual.grid);\n    }\n}\n\nvector<Individual> selectParents() {\n    vector<Individual> parents;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, POPULATION_SIZE - 1);\n\n    for (int i = 0; i < POPULATION_SIZE; ++i) {\n        int idx1 = dist(gen);\n        int idx2 = dist(gen);\n        parents.push_back(population[idx1].fitness > population[idx2].fitness ? population[idx1] : population[idx2]);\n    }\n\n    return parents;\n}\n\nvector<Individual> crossover(const vector<Individual>& parents) {\n    vector<Individual> offspring;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, N * N - 1);\n\n    for (int i = 0; i < POPULATION_SIZE; i += 2) {\n        Individual child1, child2;\n        int crossoverPoint = dist(gen);\n\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < N; ++k) {\n                if (j * N + k < crossoverPoint) {\n                    child1.grid[j][k] = parents[i].grid[j][k];\n                    child2.grid[j][k] = parents[i + 1].grid[j][k];\n                } else {\n                    child1.grid[j][k] = parents[i + 1].grid[j][k];\n                    child2.grid[j][k] = parents[i].grid[j][k];\n                }\n            }\n        }\n\n        offspring.push_back(child1);\n        offspring.push_back(child2);\n    }\n\n    return offspring;\n}\n\nvoid mutate(vector<Individual>& offspring) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<double> dist(0.0, 1.0);\n    uniform_int_distribution<int> seedDist(0, SEED_COUNT - 1);\n\n    for (auto& individual : offspring) {\n        if (dist(gen) < MUTATION_RATE) {\n            int i1 = seedDist(gen) / N;\n            int j1 = seedDist(gen) % N;\n            int i2 = seedDist(gen) / N;\n            int j2 = seedDist(gen) % N;\n            swap(individual.grid[i1][j1], individual.grid[i2][j2]);\n        }\n    }\n}\n\nvoid geneticAlgorithm() {\n    initializePopulation();\n    evaluatePopulation();\n\n    for (int gen = 0; gen < GENERATIONS; ++gen) {\n        vector<Individual> parents = selectParents();\n        vector<Individual> offspring = crossover(parents);\n        mutate(offspring);\n\n        for (auto& individual : offspring) {\n            individual.fitness = calculateFitness(individual.grid);\n        }\n\n        population.insert(population.end(), offspring.begin(), offspring.end());\n        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n            return a.fitness > b.fitness;\n        });\n        population.resize(POPULATION_SIZE);\n    }\n}\n\nint main() {\n    // Read input\n    for (int i = 0; i < SEED_COUNT; ++i) {\n        for (int j = 0; j < M; ++j) {\n            cin >> X[i][j];\n            if (X[i][j] > X_max[j]) {\n                X_max[j] = X[i][j];\n            }\n        }\n    }\n\n    // Run genetic algorithm\n    geneticAlgorithm();\n\n    // Output the best solution\n    Individual best = *max_element(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n        return a.fitness < b.fitness;\n    });\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << best.grid[i][j];\n            if (j < N - 1) {\n                cout << \" \";\n            } else {\n                cout << endl;\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct TreeNode {\n    int id;\n    int parent;\n    int length;\n    vector<int> children;\n    Point position;\n    Point direction;\n    bool isFingertip;\n    bool holding;\n\n    TreeNode(int id, int parent, int length, const Point& position, const Point& direction, bool isFingertip)\n        : id(id), parent(parent), length(length), position(position), direction(direction), isFingertip(isFingertip), holding(false) {}\n};\n\nclass RoboticArm {\nprivate:\n    int N, M, V;\n    vector<vector<int>> grid;\n    vector<vector<int>> target;\n    vector<TreeNode> tree;\n    Point rootPosition;\n    vector<string> operations;\n    unordered_map<Point, bool> occupied;\n\n    void designTree() {\n        // Design a star-shaped tree\n        tree.emplace_back(0, -1, 0, rootPosition, Point(1, 0), false);\n        for (int i = 1; i < V; ++i) {\n            int parent = 0;\n            int length = 1;\n            Point direction = Point(1, 0);\n            tree.emplace_back(i, parent, length, rootPosition, direction, true);\n            tree[parent].children.push_back(i);\n        }\n    }\n\n    void moveRoot(int dx, int dy) {\n        rootPosition.x += dx;\n        rootPosition.y += dy;\n        for (auto& node : tree) {\n            node.position.x += dx;\n            node.position.y += dy;\n        }\n    }\n\n    void rotateSubtree(int nodeId, int rotation) {\n        if (rotation == 0) return;\n        TreeNode& node = tree[nodeId];\n        int newDirX = node.direction.x;\n        int newDirY = node.direction.y;\n        if (rotation == 1) { // Counterclockwise\n            newDirX = -node.direction.y;\n            newDirY = node.direction.x;\n        } else if (rotation == 2) { // Clockwise\n            newDirX = node.direction.y;\n            newDirY = -node.direction.x;\n        }\n        node.direction.x = newDirX;\n        node.direction.y = newDirY;\n        for (int childId : node.children) {\n            rotateSubtree(childId, rotation);\n        }\n    }\n\n    void grabOrRelease(int nodeId) {\n        TreeNode& node = tree[nodeId];\n        if (!node.isFingertip) return;\n        Point fingertipPos = node.position;\n        fingertipPos.x += node.direction.x * node.length;\n        fingertipPos.y += node.direction.y * node.length;\n        if (fingertipPos.x < 0 || fingertipPos.x >= N || fingertipPos.y < 0 || fingertipPos.y >= N) return;\n        if (grid[fingertipPos.x][fingertipPos.y] == 1 && target[fingertipPos.x][fingertipPos.y] == 0 && !node.holding) {\n            grid[fingertipPos.x][fingertipPos.y] = 0;\n            node.holding = true;\n        } else if (grid[fingertipPos.x][fingertipPos.y] == 0 && target[fingertipPos.x][fingertipPos.y] == 1 && node.holding) {\n            grid[fingertipPos.x][fingertipPos.y] = 1;\n            node.holding = false;\n        }\n    }\n\n    void performOperation(const string& op) {\n        operations.push_back(op);\n        char move = op[0];\n        if (move == 'U') moveRoot(-1, 0);\n        else if (move == 'D') moveRoot(1, 0);\n        else if (move == 'L') moveRoot(0, -1);\n        else if (move == 'R') moveRoot(0, 1);\n        for (int i = 1; i < V; ++i) {\n            char rot = op[i];\n            if (rot == 'L') rotateSubtree(i, 1);\n            else if (rot == 'R') rotateSubtree(i, 2);\n        }\n        for (int i = 0; i < V; ++i) {\n            char action = op[V + i];\n            if (action == 'P') grabOrRelease(i);\n        }\n    }\n\n    void moveTakoyaki(const Point& start, const Point& end) {\n        // Simplified path planning: move directly to the target\n        int dx = end.x - start.x;\n        int dy = end.y - start.y;\n        string op(V * 2, '.');\n        if (dx > 0) op[0] = 'D';\n        else if (dx < 0) op[0] = 'U';\n        else if (dy > 0) op[0] = 'R';\n        else if (dy < 0) op[0] = 'L';\n        performOperation(op);\n        op = string(V * 2, '.');\n        op[V + 1] = 'P'; // Grab or release\n        performOperation(op);\n        if (dx > 0) op[0] = 'U';\n        else if (dx < 0) op[0] = 'D';\n        else if (dy > 0) op[0] = 'L';\n        else if (dy < 0) op[0] = 'R';\n        performOperation(op);\n        op[V + 1] = 'P'; // Grab or release\n        performOperation(op);\n    }\n\npublic:\n    RoboticArm(int N, int M, int V, const vector<vector<int>>& grid, const vector<vector<int>>& target)\n        : N(N), M(M), V(V), grid(grid), target(target), rootPosition(0, 0) {\n        designTree();\n    }\n\n    void solve() {\n        vector<Point> takoyakiPositions;\n        vector<Point> targetPositions;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == 1) {\n                    takoyakiPositions.emplace_back(i, j);\n                }\n                if (target[i][j] == 1) {\n                    targetPositions.emplace_back(i, j);\n                }\n            }\n        }\n        for (size_t i = 0; i < takoyakiPositions.size(); ++i) {\n            moveTakoyaki(takoyakiPositions[i], targetPositions[i]);\n        }\n    }\n\n    void printSolution() {\n        cout << tree.size() << endl;\n        for (size_t i = 1; i < tree.size(); ++i) {\n            cout << tree[i].parent << \" \" << tree[i].length << endl;\n        }\n        cout << rootPosition.x << \" \" << rootPosition.y << endl;\n        for (const string& op : operations) {\n            cout << op << endl;\n        }\n    }\n};\n\nint main() {\n    int N, M, V;\n    cin >> N >> M >> V;\n    vector<vector<int>> grid(N, vector<int>(N));\n    vector<vector<int>> target(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = row[j] - '0';\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            target[i][j] = row[j] - '0';\n        }\n    }\n    RoboticArm arm(N, M, V, grid, target);\n    arm.solve();\n    arm.printSolution();\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Polygon {\n    vector<Point> vertices;\n    int mackerels, sardines;\n    Polygon() : mackerels(0), sardines(0) {}\n};\n\nint cross(const Point &O, const Point &A, const Point &B) {\n    return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);\n}\n\nvector<Point> convex_hull(vector<Point> points) {\n    int n = points.size(), k = 0;\n    vector<Point> hull(2 * n);\n    sort(points.begin(), points.end(), [](const Point &a, const Point &b) {\n        return a.x < b.x || (a.x == b.x && a.y < b.y);\n    });\n    for (int i = 0; i < n; ++i) {\n        while (k >= 2 && cross(hull[k-2], hull[k-1], points[i]) <= 0) k--;\n        hull[k++] = points[i];\n    }\n    for (int i = n-2, t = k+1; i >= 0; --i) {\n        while (k >= t && cross(hull[k-2], hull[k-1], points[i]) <= 0) k--;\n        hull[k++] = points[i];\n    }\n    hull.resize(k-1);\n    return hull;\n}\n\nbool is_point_in_polygon(const Point &p, const Polygon &poly) {\n    int n = poly.vertices.size();\n    if (n < 3) return false;\n    bool inside = false;\n    for (int i = 0, j = n - 1; i < n; j = i++) {\n        if (((poly.vertices[i].y > p.y) != (poly.vertices[j].y > p.y)) &&\n            (p.x < (poly.vertices[j].x - poly.vertices[i].x) * (p.y - poly.vertices[i].y) / (poly.vertices[j].y - poly.vertices[i].y) + poly.vertices[i].x))\n            inside = !inside;\n    }\n    return inside;\n}\n\nint count_points_in_polygon(const vector<Point> &points, const Polygon &poly) {\n    int count = 0;\n    for (const auto &p : points) {\n        if (is_point_in_polygon(p, poly)) {\n            count++;\n        }\n    }\n    return count;\n}\n\nPolygon generate_random_polygon(const vector<Point> &hull, int max_vertices, int max_edge_length) {\n    Polygon poly;\n    int n = hull.size();\n    if (n < 4) return poly;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, n - 1);\n\n    int start = dis(gen);\n    poly.vertices.push_back(hull[start]);\n\n    int current = start;\n    int total_length = 0;\n    while (poly.vertices.size() < max_vertices) {\n        int next = (current + 1) % n;\n        int dx = hull[next].x - hull[current].x;\n        int dy = hull[next].y - hull[current].y;\n        int edge_length = abs(dx) + abs(dy);\n\n        if (total_length + edge_length > max_edge_length) {\n            break;\n        }\n\n        if (dx != 0 && dy != 0) {\n            // Ensure edges are parallel to x-axis or y-axis\n            if (abs(dx) > abs(dy)) {\n                poly.vertices.emplace_back(hull[current].x + dx, hull[current].y);\n            } else {\n                poly.vertices.emplace_back(hull[current].x, hull[current].y + dy);\n            }\n        } else {\n            poly.vertices.push_back(hull[next]);\n        }\n\n        total_length += edge_length;\n        current = next;\n    }\n\n    // Close the polygon\n    if (poly.vertices.size() >= 3) {\n        int dx = poly.vertices.back().x - poly.vertices[0].x;\n        int dy = poly.vertices.back().y - poly.vertices[0].y;\n        if (dx != 0 && dy != 0) {\n            if (abs(dx) > abs(dy)) {\n                poly.vertices.emplace_back(poly.vertices.back().x, poly.vertices[0].y);\n            } else {\n                poly.vertices.emplace_back(poly.vertices[0].x, poly.vertices.back().y);\n            }\n        }\n    }\n\n    return poly;\n}\n\nint evaluate_polygon(const Polygon &poly, const vector<Point> &mackerels, const vector<Point> &sardines) {\n    int m = count_points_in_polygon(mackerels, poly);\n    int s = count_points_in_polygon(sardines, poly);\n    return max(0, m - s + 1);\n}\n\nPolygon simulated_annealing(const vector<Point> &hull, const vector<Point> &mackerels, const vector<Point> &sardines, int max_vertices, int max_edge_length, int iterations) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    Polygon current = generate_random_polygon(hull, max_vertices, max_edge_length);\n    current.mackerels = count_points_in_polygon(mackerels, current);\n    current.sardines = count_points_in_polygon(sardines, current);\n    int current_score = evaluate_polygon(current, mackerels, sardines);\n\n    Polygon best = current;\n    int best_score = current_score;\n\n    double temperature = 1.0;\n    double cooling_rate = 0.999;\n\n    for (int i = 0; i < iterations; ++i) {\n        Polygon neighbor = generate_random_polygon(hull, max_vertices, max_edge_length);\n        neighbor.mackerels = count_points_in_polygon(mackerels, neighbor);\n        neighbor.sardines = count_points_in_polygon(sardines, neighbor);\n        int neighbor_score = evaluate_polygon(neighbor, mackerels, sardines);\n\n        if (neighbor_score > current_score || dis(gen) < exp((neighbor_score - current_score) / temperature)) {\n            current = neighbor;\n            current_score = neighbor_score;\n        }\n\n        if (current_score > best_score) {\n            best = current;\n            best_score = current_score;\n        }\n\n        temperature *= cooling_rate;\n    }\n\n    return best;\n}\n\nint main() {\n    int N;\n    cin >> N;\n\n    vector<Point> mackerels;\n    vector<Point> sardines;\n    vector<Point> all_points;\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        mackerels.emplace_back(x, y);\n        all_points.emplace_back(x, y);\n    }\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        sardines.emplace_back(x, y);\n        all_points.emplace_back(x, y);\n    }\n\n    vector<Point> hull = convex_hull(all_points);\n    int max_vertices = 1000;\n    int max_edge_length = 400000;\n    int iterations = 10000;\n\n    Polygon best_polygon = simulated_annealing(hull, mackerels, sardines, max_vertices, max_edge_length, iterations);\n\n    cout << best_polygon.vertices.size() << endl;\n    for (const auto &p : best_polygon.vertices) {\n        cout << p.x << \" \" << p.y << endl;\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <limits>\n#include <chrono>\n\nusing namespace std;\n\nstruct Rectangle {\n    int w, h;\n    int w_prime, h_prime;\n};\n\nstruct Placement {\n    int p; // index of the rectangle\n    int r; // rotation (0 or 1)\n    char d; // direction ('U' or 'L')\n    int b; // reference rectangle index or -1\n};\n\nstruct Solution {\n    vector<Placement> placements;\n    int width, height;\n    int score;\n};\n\nclass RectanglePacker {\nprivate:\n    int N, T, sigma;\n    vector<Rectangle> rectangles;\n    mt19937 rng;\n    uniform_real_distribution<double> dist;\n\n    Solution generateInitialSolution() {\n        Solution solution;\n        vector<int> indices(N);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), rng);\n\n        for (int i = 0; i < N; ++i) {\n            int p = indices[i];\n            int r = uniform_int_distribution<int>(0, 1)(rng);\n            char d = uniform_int_distribution<int>(0, 1)(rng) ? 'U' : 'L';\n            int b = i == 0 ? -1 : uniform_int_distribution<int>(-1, i - 1)(rng);\n            solution.placements.push_back({p, r, d, b});\n        }\n\n        return solution;\n    }\n\n    Solution placeRectangles(const Solution& solution) {\n        Solution result = solution;\n        vector<pair<int, int>> positions(N, {-1, -1});\n        int max_x = 0, max_y = 0;\n\n        for (const auto& placement : solution.placements) {\n            int p = placement.p;\n            int r = placement.r;\n            char d = placement.d;\n            int b = placement.b;\n\n            int w = r == 0 ? rectangles[p].w_prime : rectangles[p].h_prime;\n            int h = r == 0 ? rectangles[p].h_prime : rectangles[p].w_prime;\n\n            int x, y;\n            if (d == 'U') {\n                if (b == -1) {\n                    x = 0;\n                } else {\n                    x = positions[b].first + (r == 0 ? rectangles[b].w_prime : rectangles[b].h_prime);\n                }\n                y = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (positions[i].first != -1 && positions[i].first < x + w && positions[i].first + (r == 0 ? rectangles[i].w_prime : rectangles[i].h_prime) > x) {\n                        y = max(y, positions[i].second + (r == 0 ? rectangles[i].h_prime : rectangles[i].w_prime));\n                    }\n                }\n            } else { // d == 'L'\n                if (b == -1) {\n                    y = 0;\n                } else {\n                    y = positions[b].second + (r == 0 ? rectangles[b].h_prime : rectangles[b].w_prime);\n                }\n                x = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (positions[i].second != -1 && positions[i].second < y + h && positions[i].second + (r == 0 ? rectangles[i].h_prime : rectangles[i].w_prime) > y) {\n                        x = max(x, positions[i].first + (r == 0 ? rectangles[i].w_prime : rectangles[i].h_prime));\n                    }\n                }\n            }\n\n            positions[p] = {x, y};\n            max_x = max(max_x, x + w);\n            max_y = max(max_y, y + h);\n        }\n\n        result.width = max_x;\n        result.height = max_y;\n        result.score = max_x + max_y;\n\n        return result;\n    }\n\n    Solution mutateSolution(const Solution& solution) {\n        Solution new_solution = solution;\n        int mutation_type = uniform_int_distribution<int>(0, 2)(rng);\n\n        if (mutation_type == 0) { // Change rotation\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            new_solution.placements[idx].r = 1 - new_solution.placements[idx].r;\n        } else if (mutation_type == 1) { // Change direction\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            new_solution.placements[idx].d = new_solution.placements[idx].d == 'U' ? 'L' : 'U';\n        } else { // Change reference\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            int b = idx == 0 ? -1 : uniform_int_distribution<int>(-1, idx - 1)(rng);\n            new_solution.placements[idx].b = b;\n        }\n\n        return new_solution;\n    }\n\n    Solution simulatedAnnealing() {\n        Solution current_solution = generateInitialSolution();\n        current_solution = placeRectangles(current_solution);\n        Solution best_solution = current_solution;\n\n        double temperature = 1000.0;\n        double cooling_rate = 0.99;\n        int iterations = 1000;\n\n        for (int i = 0; i < iterations; ++i) {\n            Solution new_solution = mutateSolution(current_solution);\n            new_solution = placeRectangles(new_solution);\n\n            double delta = new_solution.score - current_solution.score;\n            if (delta < 0 || exp(-delta / temperature) > dist(rng)) {\n                current_solution = new_solution;\n                if (new_solution.score < best_solution.score) {\n                    best_solution = new_solution;\n                }\n            }\n\n            temperature *= cooling_rate;\n        }\n\n        return best_solution;\n    }\n\npublic:\n    RectanglePacker(int N, int T, int sigma, const vector<Rectangle>& rectangles)\n        : N(N), T(T), sigma(sigma), rectangles(rectangles), rng(chrono::steady_clock::now().time_since_epoch().count()), dist(0.0, 1.0) {}\n\n    Solution findBestSolution() {\n        Solution best_solution;\n        best_solution.score = numeric_limits<int>::max();\n\n        for (int t = 0; t < T; ++t) {\n            Solution solution = simulatedAnnealing();\n            if (solution.score < best_solution.score) {\n                best_solution = solution;\n            }\n        }\n\n        return best_solution;\n    }\n};\n\nint main() {\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n\n    vector<Rectangle> rectangles(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> rectangles[i].w_prime >> rectangles[i].h_prime;\n    }\n\n    RectanglePacker packer(N, T, sigma, rectangles);\n    Solution best_solution = packer.findBestSolution();\n\n    cout << best_solution.placements.size() << endl;\n    for (const auto& placement : best_solution.placements) {\n        cout << placement.p << \" \" << placement.r << \" \" << placement.d << \" \" << placement.b << endl;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_set>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n};\n\nstruct Vertex {\n    int id;\n    int beauty;\n    vector<int> neighbors;\n};\n\nstruct Tree {\n    int root;\n    vector<int> parent;\n    vector<int> height;\n};\n\nint N, M, H;\nvector<Vertex> vertices;\nvector<Edge> edges;\nvector<int> x, y;\n\nvoid input() {\n    cin >> N >> M >> H;\n    vertices.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> vertices[i].beauty;\n        vertices[i].id = i;\n    }\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        vertices[edges[i].u].neighbors.push_back(edges[i].v);\n        vertices[edges[i].v].neighbors.push_back(edges[i].u);\n    }\n    x.resize(N);\n    y.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> x[i] >> y[i];\n    }\n}\n\nvector<int> solve() {\n    vector<int> parent(N, -1);\n    vector<bool> visited(N, false);\n    priority_queue<pair<int, int>> pq; // (beauty, id)\n\n    for (int i = 0; i < N; ++i) {\n        pq.push({vertices[i].beauty, i});\n    }\n\n    while (!pq.empty()) {\n        auto current = pq.top();\n        pq.pop();\n        int u = current.second;\n\n        if (visited[u]) continue;\n        visited[u] = true;\n\n        queue<pair<int, int>> q; // (vertex, parent)\n        q.push({u, -1});\n        int current_height = 0;\n\n        while (!q.empty() && current_height <= H) {\n            int size = q.size();\n            for (int i = 0; i < size; ++i) {\n                auto front = q.front();\n                q.pop();\n                int v = front.first;\n                int p = front.second;\n\n                if (visited[v]) continue;\n                visited[v] = true;\n                parent[v] = p;\n\n                for (int neighbor : vertices[v].neighbors) {\n                    if (!visited[neighbor]) {\n                        q.push({neighbor, v});\n                    }\n                }\n            }\n            current_height++;\n        }\n    }\n\n    return parent;\n}\n\nint main() {\n    input();\n    auto parent = solve();\n    for (int p : parent) {\n        cout << p << \" \";\n    }\n    cout << endl;\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cassert>\n\nusing namespace std;\n\nstruct Move {\n    char direction;\n    int index;\n};\n\nvector<Move> solve(const vector<string>& board) {\n    int N = board.size();\n    vector<Move> moves;\n    vector<vector<char>> current_board = board;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (current_board[i][j] == 'x') {\n                // Check if we can remove the Oni by shifting the row left\n                bool can_remove_left = true;\n                for (int k = 0; k < i; ++k) {\n                    if (current_board[k][j] == 'o') {\n                        can_remove_left = false;\n                        break;\n                    }\n                }\n                if (can_remove_left) {\n                    // Shift the row left to remove the Oni\n                    for (int k = 0; k <= i; ++k) {\n                        moves.push_back({'L', i});\n                    }\n                    for (int k = 0; k <= i; ++k) {\n                        moves.push_back({'R', i});\n                    }\n                    // Update the board state\n                    for (int k = 0; k < N - 1; ++k) {\n                        current_board[i][k] = current_board[i][k + 1];\n                    }\n                    current_board[i][N - 1] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the row right\n                bool can_remove_right = true;\n                for (int k = i + 1; k < N; ++k) {\n                    if (current_board[k][j] == 'o') {\n                        can_remove_right = false;\n                        break;\n                    }\n                }\n                if (can_remove_right) {\n                    // Shift the row right to remove the Oni\n                    for (int k = 0; k <= N - 1 - i; ++k) {\n                        moves.push_back({'R', i});\n                    }\n                    for (int k = 0; k <= N - 1 - i; ++k) {\n                        moves.push_back({'L', i});\n                    }\n                    // Update the board state\n                    for (int k = N - 1; k > 0; --k) {\n                        current_board[i][k] = current_board[i][k - 1];\n                    }\n                    current_board[i][0] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the column up\n                bool can_remove_up = true;\n                for (int k = 0; k < j; ++k) {\n                    if (current_board[i][k] == 'o') {\n                        can_remove_up = false;\n                        break;\n                    }\n                }\n                if (can_remove_up) {\n                    // Shift the column up to remove the Oni\n                    for (int k = 0; k <= j; ++k) {\n                        moves.push_back({'U', j});\n                    }\n                    for (int k = 0; k <= j; ++k) {\n                        moves.push_back({'D', j});\n                    }\n                    // Update the board state\n                    for (int k = 0; k < N - 1; ++k) {\n                        current_board[k][j] = current_board[k + 1][j];\n                    }\n                    current_board[N - 1][j] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the column down\n                bool can_remove_down = true;\n                for (int k = j + 1; k < N; ++k) {\n                    if (current_board[i][k] == 'o') {\n                        can_remove_down = false;\n                        break;\n                    }\n                }\n                if (can_remove_down) {\n                    // Shift the column down to remove the Oni\n                    for (int k = 0; k <= N - 1 - j; ++k) {\n                        moves.push_back({'D', j});\n                    }\n                    for (int k = 0; k <= N - 1 - j; ++k) {\n                        moves.push_back({'U', j});\n                    }\n                    // Update the board state\n                    for (int k = N - 1; k > 0; --k) {\n                        current_board[k][j] = current_board[k - 1][j];\n                    }\n                    current_board[0][j] = '.';\n                }\n            }\n        }\n    }\n\n    return moves;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n    }\n\n    vector<Move> moves = solve(board);\n\n    for (const auto& move : moves) {\n        cout << move.direction << \" \" << move.index << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <random>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nstruct Employee {\n    int a;\n    int b;\n};\n\nstruct State {\n    vector<Employee> employees;\n    int error;\n};\n\nint calculate_error(const vector<int>& actual, const vector<int>& target) {\n    int error = 0;\n    for (size_t i = 0; i < actual.size(); ++i) {\n        error += abs(actual[i] - target[i]);\n    }\n    return error;\n}\n\nvector<int> simulate_cleaning_plan(const vector<Employee>& employees, int L) {\n    vector<int> actual(employees.size(), 0);\n    int current = 0;\n    vector<int> counts(employees.size(), 0);\n\n    for (int week = 0; week < L; ++week) {\n        actual[current]++;\n        counts[current]++;\n        int t = counts[current];\n        if (t % 2 == 1) {\n            current = employees[current].a;\n        } else {\n            current = employees[current].b;\n        }\n    }\n\n    return actual;\n}\n\nState generate_initial_state(int N) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n\n    vector<Employee> employees(N);\n    for (int i = 0; i < N; ++i) {\n        employees[i].a = dis(gen);\n        employees[i].b = dis(gen);\n    }\n\n    State state;\n    state.employees = employees;\n    state.error = 0; // Will be calculated later\n    return state;\n}\n\nState simulated_annealing(const vector<int>& target, int N, int L, double initial_temp, double cooling_rate, int iterations) {\n    State current_state = generate_initial_state(N);\n    current_state.error = calculate_error(simulate_cleaning_plan(current_state.employees, L), target);\n\n    State best_state = current_state;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, N - 1);\n    uniform_real_distribution<> prob_dis(0.0, 1.0);\n\n    double temp = initial_temp;\n\n    for (int i = 0; i < iterations; ++i) {\n        State new_state = current_state;\n        int employee = dis(gen);\n        int choice = dis(gen) % 2;\n\n        if (choice == 0) {\n            new_state.employees[employee].a = dis(gen);\n        } else {\n            new_state.employees[employee].b = dis(gen);\n        }\n\n        vector<int> actual = simulate_cleaning_plan(new_state.employees, L);\n        new_state.error = calculate_error(actual, target);\n\n        double delta = new_state.error - current_state.error;\n        if (delta < 0 || prob_dis(gen) < exp(-delta / temp)) {\n            current_state = new_state;\n            if (current_state.error < best_state.error) {\n                best_state = current_state;\n            }\n        }\n\n        temp *= cooling_rate;\n    }\n\n    return best_state;\n}\n\nint main() {\n    int N, L;\n    cin >> N >> L;\n\n    vector<int> target(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> target[i];\n    }\n\n    double initial_temp = 1000.0;\n    double cooling_rate = 0.999;\n    int iterations = 100000;\n\n    State best_state = simulated_annealing(target, N, L, initial_temp, cooling_rate, iterations);\n\n    for (const auto& employee : best_state.employees) {\n        cout << employee.a << \" \" << employee.b << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <limits>\n\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double cx, cy; // Center coordinates\n};\n\nstruct Edge {\n    int u, v;\n    double distance;\n};\n\nstruct CompareEdge {\n    bool operator()(const Edge& a, const Edge& b) {\n        return a.distance > b.distance;\n    }\n};\n\nvector<Edge> query(const vector<int>& cities) {\n    cout << \"? \" << cities.size();\n    for (int city : cities) {\n        cout << \" \" << city;\n    }\n    cout << endl;\n    cout.flush();\n\n    vector<Edge> edges;\n    for (size_t i = 0; i < cities.size() - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        edges.push_back({u, v, 0.0}); // Distance will be calculated later\n    }\n    return edges;\n}\n\nvoid answer(const vector<vector<int>>& groups, const vector<vector<Edge>>& edges) {\n    cout << \"!\" << endl;\n    for (size_t i = 0; i < groups.size(); ++i) {\n        for (int city : groups[i]) {\n            cout << city << \" \";\n        }\n        cout << endl;\n        for (const Edge& edge : edges[i]) {\n            cout << edge.u << \" \" << edge.v << endl;\n        }\n    }\n}\n\nvector<vector<int>> greedyGrouping(const vector<City>& cities, const vector<int>& G) {\n    vector<City> sortedCities = cities;\n    sort(sortedCities.begin(), sortedCities.end(), [](const City& a, const City& b) {\n        return a.cx < b.cx || (a.cx == b.cx && a.cy < b.cy);\n    });\n\n    vector<vector<int>> groups;\n    size_t startIdx = 0;\n    for (int g : G) {\n        vector<int> group;\n        for (size_t i = startIdx; i < startIdx + g; ++i) {\n            group.push_back(sortedCities[i].id);\n        }\n        groups.push_back(group);\n        startIdx += g;\n    }\n    return groups;\n}\n\nvector<Edge> calculateMST(const vector<int>& group, const vector<City>& cities) {\n    unordered_map<int, int> cityToIndex;\n    for (size_t i = 0; i < cities.size(); ++i) {\n        cityToIndex[cities[i].id] = i;\n    }\n\n    vector<vector<double>> dist(group.size(), vector<double>(group.size(), 0.0));\n    for (size_t i = 0; i < group.size(); ++i) {\n        for (size_t j = i + 1; j < group.size(); ++j) {\n            const City& a = cities[cityToIndex[group[i]]];\n            const City& b = cities[cityToIndex[group[j]]];\n            double dx = a.cx - b.cx;\n            double dy = a.cy - b.cy;\n            dist[i][j] = dist[j][i] = sqrt(dx * dx + dy * dy);\n        }\n    }\n\n    priority_queue<Edge, vector<Edge>, CompareEdge> pq;\n    for (size_t i = 0; i < group.size(); ++i) {\n        for (size_t j = i + 1; j < group.size(); ++j) {\n            pq.push({group[i], group[j], dist[i][j]});\n        }\n    }\n\n    vector<Edge> mstEdges;\n    vector<int> parent(group.size(), -1);\n    vector<int> rank(group.size(), 0);\n\n    function<int(int)> find = [&](int u) {\n        if (parent[u] == -1) return u;\n        return parent[u] = find(parent[u]);\n    };\n\n    while (!pq.empty() && mstEdges.size() < group.size() - 1) {\n        Edge edge = pq.top();\n        pq.pop();\n        int u = find(edge.u);\n        int v = find(edge.v);\n        if (u != v) {\n            mstEdges.push_back(edge);\n            if (rank[u] > rank[v]) {\n                parent[v] = u;\n            } else {\n                parent[u] = v;\n                if (rank[u] == rank[v]) {\n                    rank[v]++;\n                }\n            }\n        }\n    }\n    return mstEdges;\n}\n\nint main() {\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> G[i];\n    }\n\n    vector<City> cities(N);\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cities[i] = {i, lx, rx, ly, ry, (lx + rx) / 2.0, (ly + ry) / 2.0};\n    }\n\n    vector<vector<int>> groups = greedyGrouping(cities, G);\n    vector<vector<Edge>> edges(M);\n\n    for (int k = 0; k < M; ++k) {\n        for (size_t i = 0; i < groups[k].size() - 1; i += 2) {\n            if (i < groups[k].size() - 2) {\n                vector<int> queryCities = {groups[k][i], groups[k][i + 1], groups[k][i + 2]};\n                vector<Edge> queryEdges = query(queryCities);\n                edges[k].insert(edges[k].end(), queryEdges.begin(), queryEdges.end());\n            } else {\n                edges[k].push_back({groups[k][i], groups[k][i + 1], 0.0});\n            }\n        }\n    }\n\n    answer(groups, edges);\n\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 20;\nconst int M = 40;\nconst int MAX_ACTIONS = 2 * N * M;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct State {\n    Point pos;\n    unordered_set<Point> blocks;\n    int visited;\n    int actions;\n    State(Point pos, unordered_set<Point> blocks, int visited, int actions)\n        : pos(pos), blocks(blocks), visited(visited), actions(actions) {}\n};\n\nstruct Action {\n    char type;\n    char direction;\n    Action(char type, char direction) : type(type), direction(direction) {}\n};\n\nvector<Action> directions = {\n    {'U', 'U'}, {'D', 'D'}, {'L', 'L'}, {'R', 'R'}\n};\n\nvector<Action> actions = {\n    {'M', 'U'}, {'M', 'D'}, {'M', 'L'}, {'M', 'R'},\n    {'S', 'U'}, {'S', 'D'}, {'S', 'L'}, {'S', 'R'},\n    {'A', 'U'}, {'A', 'D'}, {'A', 'L'}, {'A', 'R'}\n};\n\nbool isValid(Point p) {\n    return p.x >= 0 && p.x < N && p.y >= 0 && p.y < N;\n}\n\nPoint move(Point p, char direction) {\n    switch (direction) {\n        case 'U': return Point(p.x - 1, p.y);\n        case 'D': return Point(p.x + 1, p.y);\n        case 'L': return Point(p.x, p.y - 1);\n        case 'R': return Point(p.x, p.y + 1);\n    }\n    return p;\n}\n\nPoint slide(Point p, char direction, const unordered_set<Point>& blocks) {\n    Point next = p;\n    while (true) {\n        Point newPos = move(next, direction);\n        if (!isValid(newPos) || blocks.count(newPos)) break;\n        next = newPos;\n    }\n    return next;\n}\n\nunordered_set<Point> alter(Point p, char direction, unordered_set<Point> blocks) {\n    Point target = move(p, direction);\n    if (isValid(target)) {\n        if (blocks.count(target)) {\n            blocks.erase(target);\n        } else {\n            blocks.insert(target);\n        }\n    }\n    return blocks;\n}\n\nint heuristic(Point a, Point b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvector<Action> solve(vector<Point> targets) {\n    vector<Action> result;\n    unordered_set<Point> blocks;\n    Point current = targets[0];\n    int visited = 0;\n\n    for (int i = 1; i < targets.size(); ++i) {\n        Point target = targets[i];\n        priority_queue<pair<int, State>, vector<pair<int, State>>, greater<pair<int, State>>> pq;\n        unordered_set<Point> initialBlocks = blocks;\n        pq.push({heuristic(current, target), State(current, initialBlocks, visited, 0)});\n\n        while (!pq.empty()) {\n            auto [cost, state] = pq.top();\n            pq.pop();\n\n            if (state.pos == target) {\n                current = target;\n                visited = i;\n                blocks = state.blocks;\n                break;\n            }\n\n            if (state.actions >= MAX_ACTIONS) continue;\n\n            for (auto& action : actions) {\n                Point newPos = state.pos;\n                unordered_set<Point> newBlocks = state.blocks;\n                int newVisited = state.visited;\n                int newActions = state.actions + 1;\n\n                if (action.type == 'M') {\n                    newPos = move(state.pos, action.direction);\n                    if (!isValid(newPos) || newBlocks.count(newPos)) continue;\n                } else if (action.type == 'S') {\n                    newPos = slide(state.pos, action.direction, newBlocks);\n                } else if (action.type == 'A') {\n                    newBlocks = alter(state.pos, action.direction, newBlocks);\n                }\n\n                if (newPos == target) newVisited = i;\n\n                int newCost = newActions + heuristic(newPos, target);\n                pq.push({newCost, State(newPos, newBlocks, newVisited, newActions)});\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<Point> targets;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        targets.emplace_back(x, y);\n    }\n\n    vector<Action> result = solve(targets);\n    for (auto& action : result) {\n        cout << action.type << \" \" << action.direction << endl;\n    }\n\n    return 0;\n}"},"2":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nstruct Rectangle {\n    int a, b, c, d; // Coordinates of the rectangle\n    int area;       // Area of the rectangle\n};\n\nstruct Company {\n    int x, y;       // Desired location\n    int r;          // Desired area\n};\n\ndouble satisfaction_level(const Rectangle& rect, const Company& company) {\n    if (rect.a > company.x || rect.c <= company.x || rect.b > company.y || rect.d <= company.y) {\n        return 0.0;\n    }\n    double s_i = rect.area;\n    double r_i = company.r;\n    double min_val = min(r_i, s_i);\n    double max_val = max(r_i, s_i);\n    double p_i = 1.0 - pow(1.0 - min_val / max_val, 2.0);\n    return p_i;\n}\n\nbool is_overlapping(const Rectangle& rect1, const Rectangle& rect2) {\n    return !(rect1.c <= rect2.a || rect2.c <= rect1.a || rect1.d <= rect2.b || rect2.d <= rect1.b);\n}\n\nvector<Rectangle> generate_initial_solution(const vector<Company>& companies) {\n    vector<Rectangle> rectangles;\n    for (const auto& company : companies) {\n        int width = static_cast<int>(sqrt(company.r));\n        int height = company.r / width;\n        if (width * height < company.r) {\n            height++;\n        }\n        int a = max(0, company.x - width / 2);\n        int b = max(0, company.y - height / 2);\n        int c = min(10000, a + width);\n        int d = min(10000, b + height);\n        Rectangle rect = {a, b, c, d, (c - a) * (d - b)};\n        rectangles.push_back(rect);\n    }\n    return rectangles;\n}\n\ndouble total_satisfaction(const vector<Rectangle>& rectangles, const vector<Company>& companies) {\n    double total = 0.0;\n    for (size_t i = 0; i < companies.size(); ++i) {\n        total += satisfaction_level(rectangles[i], companies[i]);\n    }\n    return total;\n}\n\nvector<Rectangle> simulated_annealing(const vector<Company>& companies, vector<Rectangle> initial_rectangles, double initial_temp, double cooling_rate, int iterations) {\n    vector<Rectangle> current_rectangles = initial_rectangles;\n    double current_satisfaction = total_satisfaction(current_rectangles, companies);\n    vector<Rectangle> best_rectangles = current_rectangles;\n    double best_satisfaction = current_satisfaction;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    for (double temp = initial_temp; temp > 1e-6; temp *= cooling_rate) {\n        for (int i = 0; i < iterations; ++i) {\n            vector<Rectangle> new_rectangles = current_rectangles;\n            int idx = dis(gen) * companies.size();\n            int delta_x = (dis(gen) * 2 - 1) * 10;\n            int delta_y = (dis(gen) * 2 - 1) * 10;\n            new_rectangles[idx].a = max(0, new_rectangles[idx].a + delta_x);\n            new_rectangles[idx].b = max(0, new_rectangles[idx].b + delta_y);\n            new_rectangles[idx].c = min(10000, new_rectangles[idx].c + delta_x);\n            new_rectangles[idx].d = min(10000, new_rectangles[idx].d + delta_y);\n            new_rectangles[idx].area = (new_rectangles[idx].c - new_rectangles[idx].a) * (new_rectangles[idx].d - new_rectangles[idx].b);\n\n            bool valid = true;\n            for (size_t j = 0; j < new_rectangles.size(); ++j) {\n                if (j != idx && is_overlapping(new_rectangles[idx], new_rectangles[j])) {\n                    valid = false;\n                    break;\n                }\n            }\n\n            if (valid) {\n                double new_satisfaction = total_satisfaction(new_rectangles, companies);\n                double delta = new_satisfaction - current_satisfaction;\n                if (delta > 0 || dis(gen) < exp(delta / temp)) {\n                    current_rectangles = new_rectangles;\n                    current_satisfaction = new_satisfaction;\n                    if (current_satisfaction > best_satisfaction) {\n                        best_rectangles = current_rectangles;\n                        best_satisfaction = current_satisfaction;\n                    }\n                }\n            }\n        }\n    }\n    return best_rectangles;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector<Company> companies(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n\n    vector<Rectangle> initial_rectangles = generate_initial_solution(companies);\n    vector<Rectangle> best_rectangles = simulated_annealing(companies, initial_rectangles, 1000.0, 0.99, 1000);\n\n    for (const auto& rect : best_rectangles) {\n        cout << rect.a << \" \" << rect.b << \" \" << rect.c << \" \" << rect.d << endl;\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <unordered_set>\n#include <stack>\n#include <utility>\n\nusing namespace std;\n\nconst int SIZE = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\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\nbool is_valid(int x, int y) {\n    return x >= 0 && x < SIZE && y >= 0 && y < SIZE;\n}\n\nbool iddfs(int si, int sj, const vector<vector<int>>& tiles, const vector<vector<int>>& points, int max_depth, int& max_score, string& best_path) {\n    stack<pair<State, int>> s;\n    unordered_set<int> initial_visited_tiles;\n    initial_visited_tiles.insert(tiles[si][sj]);\n    s.emplace(State(si, sj, points[si][sj], \"\", initial_visited_tiles), 0);\n\n    while (!s.empty()) {\n        auto [current, depth] = s.top();\n        s.pop();\n\n        if (current.score > max_score) {\n            max_score = current.score;\n            best_path = current.path;\n        }\n\n        if (depth < max_depth) {\n            for (int i = 0; i < 4; ++i) {\n                int nx = current.x + dx[i];\n                int ny = current.y + dy[i];\n\n                if (is_valid(nx, ny) && current.visited_tiles.find(tiles[nx][ny]) == current.visited_tiles.end()) {\n                    unordered_set<int> new_visited_tiles = current.visited_tiles;\n                    new_visited_tiles.insert(tiles[nx][ny]);\n                    s.emplace(State(nx, ny, current.score + points[nx][ny], current.path + dir[i], new_visited_tiles), depth + 1);\n                }\n            }\n        }\n    }\n\n    return max_score != points[si][sj];\n}\n\nstring find_max_score_path(int si, int sj, const vector<vector<int>>& tiles, const vector<vector<int>>& points) {\n    int max_score = points[si][sj];\n    string best_path;\n\n    for (int max_depth = 1; max_depth <= SIZE * SIZE; ++max_depth) {\n        if (iddfs(si, sj, tiles, points, max_depth, max_score, best_path)) {\n            break;\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> tiles(SIZE, vector<int>(SIZE));\n    for (int i = 0; i < SIZE; ++i) {\n        for (int j = 0; j < SIZE; ++j) {\n            cin >> tiles[i][j];\n        }\n    }\n\n    vector<vector<int>> points(SIZE, vector<int>(SIZE));\n    for (int i = 0; i < SIZE; ++i) {\n        for (int j = 0; j < SIZE; ++j) {\n            cin >> points[i][j];\n        }\n    }\n\n    string path = find_max_score_path(si, sj, tiles, points);\n    cout << path << endl;\n\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <unordered_map>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int QUERY_COUNT = 1000;\nconst double DECAY_FACTOR = 0.998;\nconst double SCORE_MULTIPLIER = 2312311;\n\nstruct Vertex {\n    int i, j;\n    Vertex(int i, int j) : i(i), j(j) {}\n    bool operator==(const Vertex& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Vertex> {\n        size_t operator()(const Vertex& v) const {\n            return hash<int>()(v.i) ^ hash<int>()(v.j);\n        }\n    };\n}\n\nstruct Edge {\n    Vertex from, to;\n    double estimated_length;\n    Edge(Vertex from, Vertex to, double estimated_length) : from(from), to(to), estimated_length(estimated_length) {}\n};\n\nclass Graph {\nprivate:\n    vector<vector<Vertex>> vertices;\n    unordered_map<Vertex, vector<Edge>> edges;\n    unordered_map<Vertex, unordered_map<Vertex, double>> estimated_lengths;\n\npublic:\n    Graph() {\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            vector<Vertex> row;\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                row.emplace_back(i, j);\n            }\n            vertices.push_back(row);\n        }\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                Vertex from(i, j);\n                if (i > 0) {\n                    Vertex to(i - 1, j);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (i < GRID_SIZE - 1) {\n                    Vertex to(i + 1, j);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (j > 0) {\n                    Vertex to(i, j - 1);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (j < GRID_SIZE - 1) {\n                    Vertex to(i, j + 1);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n            }\n        }\n    }\n\n    void update_estimated_lengths(const vector<Vertex>& path, double actual_length) {\n        double path_length = 0.0;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            path_length += estimated_lengths[path[k]][path[k + 1]];\n        }\n        double factor = actual_length / path_length;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            estimated_lengths[path[k]][path[k + 1]] *= factor;\n            estimated_lengths[path[k + 1]][path[k]] *= factor;\n        }\n    }\n\n    vector<Vertex> a_star_search(const Vertex& start, const Vertex& goal) {\n        auto heuristic = [&](const Vertex& v) {\n            return abs(v.i - goal.i) + abs(v.j - goal.j);\n        };\n\n        priority_queue<pair<double, Vertex>, vector<pair<double, Vertex>>, greater<pair<double, Vertex>>> open_set;\n        unordered_map<Vertex, Vertex> came_from;\n        unordered_map<Vertex, double> g_score;\n        unordered_map<Vertex, double> f_score;\n\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                Vertex v(i, j);\n                g_score[v] = numeric_limits<double>::infinity();\n                f_score[v] = numeric_limits<double>::infinity();\n            }\n        }\n\n        g_score[start] = 0.0;\n        f_score[start] = heuristic(start);\n        open_set.push({f_score[start], start});\n\n        while (!open_set.empty()) {\n            Vertex current = open_set.top().second;\n            open_set.pop();\n\n            if (current == goal) {\n                vector<Vertex> path;\n                while (came_from.find(current) != came_from.end()) {\n                    path.push_back(current);\n                    current = came_from[current];\n                }\n                path.push_back(start);\n                reverse(path.begin(), path.end());\n                return path;\n            }\n\n            for (const Edge& edge : edges[current]) {\n                Vertex neighbor = edge.to;\n                double tentative_g_score = g_score[current] + estimated_lengths[current][neighbor];\n\n                if (tentative_g_score < g_score[neighbor]) {\n                    came_from[neighbor] = current;\n                    g_score[neighbor] = tentative_g_score;\n                    f_score[neighbor] = g_score[neighbor] + heuristic(neighbor);\n                    open_set.push({f_score[neighbor], neighbor});\n                }\n            }\n        }\n\n        return {};\n    }\n\n    string path_to_string(const vector<Vertex>& path) {\n        stringstream ss;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            Vertex from = path[k];\n            Vertex to = path[k + 1];\n            if (to.i == from.i - 1) {\n                ss << \"U\";\n            } else if (to.i == from.i + 1) {\n                ss << \"D\";\n            } else if (to.j == from.j - 1) {\n                ss << \"L\";\n            } else if (to.j == from.j + 1) {\n                ss << \"R\";\n            }\n        }\n        return ss.str();\n    }\n};\n\nint main() {\n    Graph graph;\n    double score = 0.0;\n    int prev_result = 0;\n\n    for (int k = 0; k < QUERY_COUNT; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        Vertex start(si, sj);\n        Vertex goal(ti, tj);\n\n        vector<Vertex> path = graph.a_star_search(start, goal);\n        string path_str = graph.path_to_string(path);\n        cout << path_str << endl;\n        cout.flush();\n\n        int actual_length;\n        cin >> actual_length;\n\n        graph.update_estimated_lengths(path, actual_length);\n\n        double path_length = 0.0;\n        for (size_t i = 0; i < path.size() - 1; ++i) {\n            path_length += graph.estimated_lengths[path[i]][path[i + 1]];\n        }\n\n        double ratio = actual_length / path_length;\n        score = score * DECAY_FACTOR + ratio;\n    }\n\n    cout << round(SCORE_MULTIPLIER * score) << endl;\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <unordered_set>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int ALPHABET_SIZE = 8;\nconst char ALPHABET[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};\nconst char EMPTY = '.';\n\nstruct Matrix {\n    vector<vector<char>> data;\n\n    Matrix() : data(N, vector<char>(N, EMPTY)) {}\n\n    void randomize() {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, ALPHABET_SIZE - 1);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                data[i][j] = ALPHABET[dis(gen)];\n            }\n        }\n    }\n\n    void mutate(double rate) {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_real_distribution<> prob(0.0, 1.0);\n        uniform_int_distribution<> dis(0, ALPHABET_SIZE - 1);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (prob(gen) < rate) {\n                    data[i][j] = ALPHABET[dis(gen)];\n                }\n            }\n        }\n    }\n\n    bool is_subsequence(const string& s) {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                // Check horizontal subsequence\n                bool match = true;\n                for (int k = 0; k < s.size(); ++k) {\n                    if (data[i][(j + k) % N] != s[k]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) return true;\n\n                // Check vertical subsequence\n                match = true;\n                for (int k = 0; k < s.size(); ++k) {\n                    if (data[(i + k) % N][j] != s[k]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) return true;\n            }\n        }\n        return false;\n    }\n\n    int count_subsequences(const vector<string>& strings) {\n        int count = 0;\n        for (const auto& s : strings) {\n            if (is_subsequence(s)) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    int count_empty() {\n        int count = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (data[i][j] == EMPTY) {\n                    count++;\n                }\n            }\n        }\n        return count;\n    }\n\n    void print() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << data[i][j];\n            }\n            cout << endl;\n        }\n    }\n};\n\ndouble evaluate(const Matrix& matrix, const vector<string>& strings) {\n    int c = matrix.count_subsequences(strings);\n    if (c < strings.size()) {\n        return static_cast<double>(c) / strings.size();\n    } else {\n        int d = matrix.count_empty();\n        return static_cast<double>(2 * N * N) / (2 * N * N - d);\n    }\n}\n\nMatrix genetic_algorithm(const vector<string>& strings, int population_size, int generations, double mutation_rate) {\n    random_device rd;\n    mt19937 gen(rd());\n    vector<Matrix> population(population_size);\n\n    for (auto& matrix : population) {\n        matrix.randomize();\n    }\n\n    for (int gen = 0; gen < generations; ++gen) {\n        vector<double> fitness(population_size);\n        for (int i = 0; i < population_size; ++i) {\n            fitness[i] = evaluate(population[i], strings);\n        }\n\n        vector<Matrix> new_population;\n        for (int i = 0; i < population_size; ++i) {\n            uniform_int_distribution<> dis(0, population_size - 1);\n            int parent1 = dis(gen);\n            int parent2 = dis(gen);\n\n            Matrix child;\n            for (int x = 0; x < N; ++x) {\n                for (int y = 0; y < N; ++y) {\n                    if (fitness[parent1] > fitness[parent2]) {\n                        child.data[x][y] = population[parent1].data[x][y];\n                    } else {\n                        child.data[x][y] = population[parent2].data[x][y];\n                    }\n                }\n            }\n\n            child.mutate(mutation_rate);\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n    }\n\n    auto best = max_element(population.begin(), population.end(), [&](const Matrix& a, const Matrix& b) {\n        return evaluate(a, strings) < evaluate(b, strings);\n    });\n\n    return *best;\n}\n\nMatrix simulated_annealing(const vector<string>& strings, double initial_temp, double cooling_rate, int iterations) {\n    Matrix current;\n    current.randomize();\n    double current_score = evaluate(current, strings);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> prob(0.0, 1.0);\n\n    double temp = initial_temp;\n    for (int i = 0; i < iterations; ++i) {\n        Matrix neighbor = current;\n        neighbor.mutate(0.1);\n\n        double neighbor_score = evaluate(neighbor, strings);\n        double delta = neighbor_score - current_score;\n\n        if (delta > 0 || prob(gen) < exp(delta / temp)) {\n            current = neighbor;\n            current_score = neighbor_score;\n        }\n\n        temp *= cooling_rate;\n    }\n\n    return current;\n}\n\nint main() {\n    int M;\n    cin >> M;\n    vector<string> strings(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i];\n    }\n\n    // Run genetic algorithm\n    Matrix best_matrix = genetic_algorithm(strings, 50, 100, 0.01);\n\n    // Run simulated annealing\n    Matrix sa_matrix = simulated_annealing(strings, 1000.0, 0.99, 10000);\n\n    // Choose the best solution\n    if (evaluate(sa_matrix, strings) > evaluate(best_matrix, strings)) {\n        best_matrix = sa_matrix;\n    }\n\n    best_matrix.print();\n\n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int i, j;\n    Point(int i, int j) : i(i), j(j) {}\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.i) ^ hash<int>()(p.j);\n        }\n    };\n}\n\nclass PatrolRoute {\nprivate:\n    int N;\n    Point start;\n    vector<string> grid;\n    vector<vector<unordered_set<Point>>> visibility;\n    vector<Point> roadSquares;\n    vector<vector<int>> moveTime;\n    vector<vector<int>> dist;\n\n    void precomputeVisibility() {\n        visibility.resize(N, vector<unordered_set<Point>>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == '#') continue;\n                // Horizontal visibility\n                for (int k = j - 1; k >= 0; --k) {\n                    if (grid[i][k] == '#') break;\n                    visibility[i][j].insert(Point(i, k));\n                }\n                for (int k = j + 1; k < N; ++k) {\n                    if (grid[i][k] == '#') break;\n                    visibility[i][j].insert(Point(i, k));\n                }\n                // Vertical visibility\n                for (int k = i - 1; k >= 0; --k) {\n                    if (grid[k][j] == '#') break;\n                    visibility[i][j].insert(Point(k, j));\n                }\n                for (int k = i + 1; k < N; ++k) {\n                    if (grid[k][j] == '#') break;\n                    visibility[i][j].insert(Point(k, j));\n                }\n            }\n        }\n    }\n\n    void precomputeRoadSquares() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] != '#') {\n                    roadSquares.emplace_back(i, j);\n                }\n            }\n        }\n    }\n\n    void precomputeMoveTime() {\n        moveTime.resize(N, vector<int>(N, 0));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] != '#') {\n                    moveTime[i][j] = grid[i][j] - '0';\n                }\n            }\n        }\n    }\n\n    void precomputeDistances() {\n        dist.resize(N, vector<int>(N, -1));\n        queue<Point> q;\n        q.push(start);\n        dist[start.i][start.j] = 0;\n        while (!q.empty()) {\n            Point current = q.front();\n            q.pop();\n            for (const auto& neighbor : getNeighbors(current)) {\n                if (dist[neighbor.i][neighbor.j] == -1) {\n                    dist[neighbor.i][neighbor.j] = dist[current.i][current.j] + moveTime[neighbor.i][neighbor.j];\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n\n    vector<Point> getNeighbors(const Point& p) {\n        vector<Point> neighbors;\n        if (p.i > 0 && grid[p.i - 1][p.j] != '#') neighbors.emplace_back(p.i - 1, p.j);\n        if (p.i < N - 1 && grid[p.i + 1][p.j] != '#') neighbors.emplace_back(p.i + 1, p.j);\n        if (p.j > 0 && grid[p.i][p.j - 1] != '#') neighbors.emplace_back(p.i, p.j - 1);\n        if (p.j < N - 1 && grid[p.i][p.j + 1] != '#') neighbors.emplace_back(p.i, p.j + 1);\n        return neighbors;\n    }\n\n    vector<Point> greedyInitialization() {\n        unordered_set<Point> covered;\n        vector<Point> path;\n        Point current = start;\n        path.push_back(current);\n        covered.insert(visibility[current.i][current.j].begin(), visibility[current.i][current.j].end());\n        while (covered.size() < roadSquares.size()) {\n            Point next;\n            int maxNewCovered = -1;\n            for (const auto& neighbor : getNeighbors(current)) {\n                int newCovered = 0;\n                for (const auto& visible : visibility[neighbor.i][neighbor.j]) {\n                    if (covered.find(visible) == covered.end()) {\n                        newCovered++;\n                    }\n                }\n                if (newCovered > maxNewCovered) {\n                    maxNewCovered = newCovered;\n                    next = neighbor;\n                }\n            }\n            if (maxNewCovered == 0) break; // No progress, break to avoid infinite loop\n            current = next;\n            path.push_back(current);\n            covered.insert(visibility[current.i][current.j].begin(), visibility[current.i][current.j].end());\n        }\n        return path;\n    }\n\n    vector<Point> geneticAlgorithm(const vector<Point>& initialPath) {\n        vector<Point> bestPath = initialPath;\n        int bestScore = calculateScore(bestPath);\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, roadSquares.size() - 1);\n        for (int iter = 0; iter < 1000; ++iter) {\n            vector<Point> newPath = bestPath;\n            int a = dis(gen);\n            int b = dis(gen);\n            if (a > b) swap(a, b);\n            reverse(newPath.begin() + a, newPath.begin() + b);\n            int newScore = calculateScore(newPath);\n            if (newScore > bestScore) {\n                bestPath = newPath;\n                bestScore = newScore;\n            }\n        }\n        return bestPath;\n    }\n\n    int calculateScore(const vector<Point>& path) {\n        unordered_set<Point> covered;\n        for (const auto& point : path) {\n            covered.insert(visibility[point.i][point.j].begin(), visibility[point.i][point.j].end());\n        }\n        int v = covered.size();\n        int r = roadSquares.size();\n        if (v < r) {\n            return round(10000 * v / r);\n        } else {\n            int t = 0;\n            for (size_t i = 1; i < path.size(); ++i) {\n                t += moveTime[path[i].i][path[i].j];\n            }\n            return round(10000 + 10000000 * N / t);\n        }\n    }\n\npublic:\n    PatrolRoute(int N, int si, int sj, const vector<string>& grid) : N(N), start(si, sj), grid(grid) {\n        precomputeVisibility();\n        precomputeRoadSquares();\n        precomputeMoveTime();\n        precomputeDistances();\n    }\n\n    string findRoute() {\n        vector<Point> initialPath = greedyInitialization();\n        vector<Point> optimizedPath = geneticAlgorithm(initialPath);\n        string route;\n        for (size_t i = 1; i < optimizedPath.size(); ++i) {\n            Point prev = optimizedPath[i - 1];\n            Point curr = optimizedPath[i];\n            if (curr.i == prev.i - 1) route += 'U';\n            else if (curr.i == prev.i + 1) route += 'D';\n            else if (curr.j == prev.j - 1) route += 'L';\n            else if (curr.j == prev.j + 1) route += 'R';\n        }\n        return route;\n    }\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n    PatrolRoute patrolRoute(N, si, sj, grid);\n    cout << patrolRoute.findRoute() << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <unordered_set>\n#include <queue>\n#include <cmath>\n\nusing namespace std;\n\nstruct Task {\n    vector<int> required_skills;\n    vector<int> dependencies;\n    int duration;\n    bool completed;\n};\n\nstruct TeamMember {\n    vector<int> skills;\n    int current_task;\n    int days_left;\n};\n\nvector<Task> tasks;\nvector<TeamMember> team_members;\nvector<vector<int>> task_dependencies;\nvector<int> in_degree;\nvector<int> completed_tasks;\nvector<int> available_tasks;\n\nvoid initialize(int N, int M, int K, int R) {\n    tasks.resize(N);\n    team_members.resize(M);\n    task_dependencies.resize(N);\n    in_degree.resize(N, 0);\n    completed_tasks.resize(N, 0);\n    available_tasks.resize(N, 0);\n\n    for (int i = 0; i < N; ++i) {\n        tasks[i].required_skills.resize(K);\n        tasks[i].dependencies.clear();\n        tasks[i].duration = 0;\n        tasks[i].completed = false;\n    }\n\n    for (int i = 0; i < M; ++i) {\n        team_members[i].skills.resize(K, 0);\n        team_members[i].current_task = -1;\n        team_members[i].days_left = 0;\n    }\n\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        task_dependencies[u - 1].push_back(v - 1);\n        in_degree[v - 1]++;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        if (in_degree[i] == 0) {\n            available_tasks[i] = 1;\n        }\n    }\n}\n\nvoid update_skills(int member, const vector<int>& completed_tasks) {\n    for (int task : completed_tasks) {\n        for (int k = 0; k < team_members[member].skills.size(); ++k) {\n            team_members[member].skills[k] = max(team_members[member].skills[k], tasks[task].required_skills[k]);\n        }\n    }\n}\n\nint calculate_duration(int task, int member) {\n    int w = 0;\n    for (int k = 0; k < tasks[task].required_skills.size(); ++k) {\n        w += max(0, tasks[task].required_skills[k] - team_members[member].skills[k]);\n    }\n\n    if (w == 0) {\n        return 1;\n    } else {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(-3, 3);\n        int r = dis(gen);\n        return max(1, w + r);\n    }\n}\n\nvoid assign_tasks() {\n    vector<pair<int, int>> assignments;\n\n    for (int i = 0; i < team_members.size(); ++i) {\n        if (team_members[i].current_task == -1) {\n            for (int j = 0; j < tasks.size(); ++j) {\n                if (available_tasks[j] && !tasks[j].completed) {\n                    int duration = calculate_duration(j, i);\n                    if (duration < tasks[j].duration || tasks[j].duration == 0) {\n                        tasks[j].duration = duration;\n                        team_members[i].current_task = j;\n                        team_members[i].days_left = duration;\n                        assignments.emplace_back(i + 1, j + 1);\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    cout << assignments.size();\n    for (const auto& assignment : assignments) {\n        cout << \" \" << assignment.first << \" \" << assignment.second;\n    }\n    cout << endl;\n    cout.flush();\n}\n\nvoid process_completed_tasks(const vector<int>& completed_members) {\n    vector<int> completed_tasks;\n\n    for (int member : completed_members) {\n        int task = team_members[member - 1].current_task;\n        if (task != -1) {\n            tasks[task].completed = true;\n            completed_tasks.push_back(task);\n            team_members[member - 1].current_task = -1;\n            team_members[member - 1].days_left = 0;\n        }\n    }\n\n    for (int task : completed_tasks) {\n        for (int dependent_task : task_dependencies[task]) {\n            in_degree[dependent_task]--;\n            if (in_degree[dependent_task] == 0) {\n                available_tasks[dependent_task] = 1;\n            }\n        }\n    }\n\n    for (int member : completed_members) {\n        update_skills(member - 1, completed_tasks);\n    }\n}\n\nint main() {\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    initialize(N, M, K, R);\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> tasks[i].required_skills[j];\n        }\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n        assign_tasks();\n\n        int n;\n        cin >> n;\n        if (n == -1) {\n            break;\n        }\n\n        vector<int> completed_members(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> completed_members[i];\n        }\n\n        process_completed_tasks(completed_members);\n\n        if (all_of(tasks.begin(), tasks.end(), [](const Task& task) { return task.completed; })) {\n            break;\n        }\n\n        if (day >= 2000) {\n            break;\n        }\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <unordered_set>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nstruct Order {\n    Point restaurant;\n    Point destination;\n    Order(Point restaurant, Point destination) : restaurant(restaurant), destination(destination) {}\n};\n\nstruct Individual {\n    vector<int> orders;\n    vector<Point> route;\n    int fitness;\n};\n\nint manhattanDistance(const Point& a, const Point& b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nint calculateFitness(const Individual& individual, const vector<Order>& allOrders) {\n    int totalDistance = 0;\n    unordered_set<int> selectedOrders(individual.orders.begin(), individual.orders.end());\n\n    // Check if the route starts and ends at the office\n    if (individual.route.front() != Point(400, 400) || individual.route.back() != Point(400, 400)) {\n        return INT_MAX;\n    }\n\n    // Check if all selected orders are visited in the correct order\n    for (int i = 0; i < individual.orders.size(); ++i) {\n        int orderIndex = individual.orders[i];\n        const Order& order = allOrders[orderIndex];\n        bool restaurantVisited = false;\n        bool destinationVisited = false;\n\n        for (int j = 0; j < individual.route.size(); ++j) {\n            if (individual.route[j] == order.restaurant) {\n                restaurantVisited = true;\n            }\n            if (individual.route[j] == order.destination) {\n                if (!restaurantVisited) {\n                    return INT_MAX;\n                }\n                destinationVisited = true;\n            }\n        }\n\n        if (!restaurantVisited || !destinationVisited) {\n            return INT_MAX;\n        }\n    }\n\n    // Calculate total travel time\n    for (int i = 0; i < individual.route.size() - 1; ++i) {\n        totalDistance += manhattanDistance(individual.route[i], individual.route[i + 1]);\n    }\n\n    return totalDistance;\n}\n\nvector<Individual> initializePopulation(int populationSize, const vector<Order>& allOrders) {\n    vector<Individual> population;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n\n    for (int i = 0; i < populationSize; ++i) {\n        Individual individual;\n        unordered_set<int> selectedOrders;\n\n        // Select 50 unique orders\n        while (selectedOrders.size() < 50) {\n            int orderIndex = orderDist(gen);\n            selectedOrders.insert(orderIndex);\n        }\n\n        individual.orders.assign(selectedOrders.begin(), selectedOrders.end());\n\n        // Generate a random route\n        vector<Point> route;\n        route.push_back(Point(400, 400)); // Start at the office\n\n        for (int orderIndex : individual.orders) {\n            const Order& order = allOrders[orderIndex];\n            route.push_back(order.restaurant);\n            route.push_back(order.destination);\n        }\n\n        route.push_back(Point(400, 400)); // End at the office\n\n        individual.route = route;\n        individual.fitness = calculateFitness(individual, allOrders);\n        population.push_back(individual);\n    }\n\n    return population;\n}\n\nIndividual selectParent(const vector<Individual>& population) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dist(0, population.size() - 1);\n\n    int index1 = dist(gen);\n    int index2 = dist(gen);\n\n    return population[index1].fitness < population[index2].fitness ? population[index1] : population[index2];\n}\n\nIndividual crossover(const Individual& parent1, const Individual& parent2, const vector<Order>& allOrders) {\n    Individual child;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dist(0, 49);\n\n    // Select a random subset of orders from parent1\n    unordered_set<int> selectedOrders(parent1.orders.begin(), parent1.orders.begin() + dist(gen));\n\n    // Add the remaining orders from parent2\n    for (int orderIndex : parent2.orders) {\n        if (selectedOrders.size() >= 50) break;\n        if (selectedOrders.find(orderIndex) == selectedOrders.end()) {\n            selectedOrders.insert(orderIndex);\n        }\n    }\n\n    child.orders.assign(selectedOrders.begin(), selectedOrders.end());\n\n    // Generate a random route\n    vector<Point> route;\n    route.push_back(Point(400, 400)); // Start at the office\n\n    for (int orderIndex : child.orders) {\n        const Order& order = allOrders[orderIndex];\n        route.push_back(order.restaurant);\n        route.push_back(order.destination);\n    }\n\n    route.push_back(Point(400, 400)); // End at the office\n\n    child.route = route;\n    child.fitness = calculateFitness(child, allOrders);\n\n    return child;\n}\n\nvoid mutate(Individual& individual, const vector<Order>& allOrders) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n    uniform_int_distribution<> mutationDist(0, 1);\n\n    // Mutate orders\n    for (int& orderIndex : individual.orders) {\n        if (mutationDist(gen) == 0) {\n            orderIndex = orderDist(gen);\n        }\n    }\n\n    // Mutate route\n    for (int i = 1; i < individual.route.size() - 1; ++i) {\n        if (mutationDist(gen) == 0) {\n            int j = uniform_int_distribution<>(1, individual.route.size() - 2)(gen);\n            swap(individual.route[i], individual.route[j]);\n        }\n    }\n\n    individual.fitness = calculateFitness(individual, allOrders);\n}\n\nvector<Individual> evolvePopulation(vector<Individual>& population, const vector<Order>& allOrders) {\n    vector<Individual> newPopulation;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> mutationRate(0.0, 1.0);\n\n    for (int i = 0; i < population.size(); ++i) {\n        Individual parent1 = selectParent(population);\n        Individual parent2 = selectParent(population);\n        Individual child = crossover(parent1, parent2, allOrders);\n\n        if (mutationRate(gen) < 0.1) {\n            mutate(child, allOrders);\n        }\n\n        newPopulation.push_back(child);\n    }\n\n    return newPopulation;\n}\n\nint main() {\n    vector<Order> allOrders;\n    for (int i = 0; i < 1000; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        allOrders.emplace_back(Point(a, b), Point(c, d));\n    }\n\n    const int populationSize = 100;\n    const int generations = 1000;\n\n    vector<Individual> population = initializePopulation(populationSize, allOrders);\n\n    for (int generation = 0; generation < generations; ++generation) {\n        population = evolvePopulation(population, allOrders);\n\n        // Find the best individual in the current population\n        Individual bestIndividual = *min_element(population.begin(), population.end(),\n            [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; });\n\n        cout << \"Generation \" << generation << \": Best Fitness = \" << bestIndividual.fitness << endl;\n    }\n\n    // Find the best individual in the final population\n    Individual bestIndividual = *min_element(population.begin(), population.end(),\n        [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; });\n\n    // Output the best solution\n    cout << bestIndividual.orders.size() << \" \";\n    for (int orderIndex : bestIndividual.orders) {\n        cout << orderIndex + 1 << \" \";\n    }\n    cout << endl;\n\n    cout << bestIndividual.route.size() << \" \";\n    for (const Point& point : bestIndividual.route) {\n        cout << point.x << \" \" << point.y << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <atcoder/dsu>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v;\n    double d; // Euclidean distance rounded to the nearest integer\n    int index; // Original index to keep track of the order\n};\n\nint main() {\n    int N = 400;\n    int M = 1995;\n\n    vector<pair<int, int>> coordinates(N);\n    vector<Edge> edges(M);\n\n    // Read coordinates\n    for (int i = 0; i < N; ++i) {\n        cin >> coordinates[i].first >> coordinates[i].second;\n    }\n\n    // Read edges and compute d_i\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        edges[i].index = i;\n        int dx = coordinates[edges[i].u].first - coordinates[edges[i].v].first;\n        int dy = coordinates[edges[i].u].second - coordinates[edges[i].v].second;\n        edges[i].d = round(sqrt(dx * dx + dy * dy));\n    }\n\n    // Sort edges by d_i in ascending order\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.d < b.d;\n    });\n\n    dsu uf(N);\n    vector<bool> adopted(M, false);\n\n    // Process edges in order of increasing d_i\n    for (const Edge& edge : edges) {\n        int l;\n        cin >> l;\n        if (!uf.same(edge.u, edge.v)) {\n            uf.merge(edge.u, edge.v);\n            adopted[edge.index] = true;\n            cout << \"1\" << endl;\n        } else {\n            cout << \"0\" << endl;\n        }\n        cout.flush();\n    }\n\n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n#include <cmath>\n#include <unordered_set>\n#include <map>\n#include <cassert>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int TURNS = 300;\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nstruct GridState {\n    vector<vector<bool>> passable;\n    vector<Pet> pets;\n    vector<Human> humans;\n};\n\nvector<vector<int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nvector<vector<int>> bfs(const GridState& state, int startX, int startY) {\n    vector<vector<int>> distance(GRID_SIZE, vector<int>(GRID_SIZE, -1));\n    queue<pair<int, int>> q;\n    q.push({startX, startY});\n    distance[startX][startY] = 0;\n\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n\n        for (auto [dx, dy] : directions) {\n            int nx = x + dx;\n            int ny = y + dy;\n            if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny] && distance[nx][ny] == -1) {\n                distance[nx][ny] = distance[x][y] + 1;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return distance;\n}\n\nvector<pair<int, int>> findReachableArea(const GridState& state, int humanIndex) {\n    auto [hx, hy] = state.humans[humanIndex];\n    auto distance = bfs(state, hx, hy);\n    vector<pair<int, int>> reachableArea;\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (distance[i][j] != -1) {\n                reachableArea.emplace_back(i, j);\n            }\n        }\n    }\n    return reachableArea;\n}\n\nint countPetsInArea(const GridState& state, const vector<pair<int, int>>& area) {\n    unordered_set<string> petPositions;\n    for (const auto& pet : state.pets) {\n        petPositions.insert(to_string(pet.x) + \",\" + to_string(pet.y));\n    }\n    int count = 0;\n    for (const auto& [x, y] : area) {\n        if (petPositions.count(to_string(x) + \",\" + to_string(y))) {\n            count++;\n        }\n    }\n    return count;\n}\n\ndouble calculateSatisfaction(const GridState& state, int humanIndex) {\n    auto reachableArea = findReachableArea(state, humanIndex);\n    int areaSize = reachableArea.size();\n    int petCount = countPetsInArea(state, reachableArea);\n    return (areaSize / 900.0) * pow(2, -petCount);\n}\n\nvector<pair<int, int>> findBestSquareToBlock(const GridState& state, int humanIndex) {\n    auto [hx, hy] = state.humans[humanIndex];\n    vector<pair<int, int>> candidates;\n    for (auto [dx, dy] : directions) {\n        int nx = hx + dx;\n        int ny = hy + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n            bool hasPetAdjacent = false;\n            for (auto [adx, ady] : directions) {\n                int anx = nx + adx;\n                int any = ny + ady;\n                if (anx >= 0 && anx < GRID_SIZE && any >= 0 && any < GRID_SIZE) {\n                    for (const auto& pet : state.pets) {\n                        if (pet.x == anx && pet.y == any) {\n                            hasPetAdjacent = true;\n                            break;\n                        }\n                    }\n                }\n                if (hasPetAdjacent) break;\n            }\n            if (!hasPetAdjacent) {\n                candidates.emplace_back(nx, ny);\n            }\n        }\n    }\n    if (candidates.empty()) {\n        return {};\n    }\n    vector<double> scores;\n    for (const auto& [nx, ny] : candidates) {\n        GridState newState = state;\n        newState.passable[nx][ny] = false;\n        auto reachableArea = findReachableArea(newState, humanIndex);\n        int areaSize = reachableArea.size();\n        int petCount = countPetsInArea(newState, reachableArea);\n        scores.push_back((areaSize / 900.0) * pow(2, -petCount));\n    }\n    int bestIndex = max_element(scores.begin(), scores.end()) - scores.begin();\n    return {candidates[bestIndex]};\n}\n\nvector<pair<int, int>> findBestMove(const GridState& state, int humanIndex) {\n    auto [hx, hy] = state.humans[humanIndex];\n    vector<pair<int, int>> candidates;\n    for (auto [dx, dy] : directions) {\n        int nx = hx + dx;\n        int ny = hy + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n            candidates.emplace_back(nx, ny);\n        }\n    }\n    if (candidates.empty()) {\n        return {};\n    }\n    vector<double> scores;\n    for (const auto& [nx, ny] : candidates) {\n        GridState newState = state;\n        newState.humans[humanIndex] = {nx, ny};\n        auto reachableArea = findReachableArea(newState, humanIndex);\n        int areaSize = reachableArea.size();\n        int petCount = countPetsInArea(newState, reachableArea);\n        scores.push_back((areaSize / 900.0) * pow(2, -petCount));\n    }\n    int bestIndex = max_element(scores.begin(), scores.end()) - scores.begin();\n    return {candidates[bestIndex]};\n}\n\nstring decideAction(const GridState& state, int humanIndex) {\n    auto [hx, hy] = state.humans[humanIndex];\n    auto blockSquares = findBestSquareToBlock(state, humanIndex);\n    auto moveSquares = findBestMove(state, humanIndex);\n\n    double currentSatisfaction = calculateSatisfaction(state, humanIndex);\n\n    double blockSatisfaction = -1;\n    if (!blockSquares.empty()) {\n        GridState newState = state;\n        auto [nx, ny] = blockSquares[0];\n        newState.passable[nx][ny] = false;\n        blockSatisfaction = calculateSatisfaction(newState, humanIndex);\n    }\n\n    double moveSatisfaction = -1;\n    if (!moveSquares.empty()) {\n        GridState newState = state;\n        auto [nx, ny] = moveSquares[0];\n        newState.humans[humanIndex] = {nx, ny};\n        moveSatisfaction = calculateSatisfaction(newState, humanIndex);\n    }\n\n    if (blockSatisfaction > currentSatisfaction && blockSatisfaction >= moveSatisfaction) {\n        auto [nx, ny] = blockSquares[0];\n        if (nx == hx - 1 && ny == hy) return \"u\";\n        if (nx == hx + 1 && ny == hy) return \"d\";\n        if (nx == hx && ny == hy - 1) return \"l\";\n        if (nx == hx && ny == hy + 1) return \"r\";\n    } else if (moveSatisfaction > currentSatisfaction && moveSatisfaction >= blockSatisfaction) {\n        auto [nx, ny] = moveSquares[0];\n        if (nx == hx - 1 && ny == hy) return \"U\";\n        if (nx == hx + 1 && ny == hy) return \"D\";\n        if (nx == hx && ny == hy - 1) return \"L\";\n        if (nx == hx && ny == hy + 1) return \"R\";\n    }\n    return \".\";\n}\n\nvoid simulatePetMovement(GridState& state, const vector<string>& petMoves) {\n    for (size_t i = 0; i < state.pets.size(); ++i) {\n        auto& pet = state.pets[i];\n        const string& move = petMoves[i];\n        if (move == \".\") continue;\n\n        for (char c : move) {\n            int dx = 0, dy = 0;\n            if (c == 'U') dx = -1;\n            else if (c == 'D') dx = 1;\n            else if (c == 'L') dy = -1;\n            else if (c == 'R') dy = 1;\n\n            int nx = pet.x + dx;\n            int ny = pet.y + dy;\n            if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n                pet.x = nx;\n                pet.y = ny;\n            }\n        }\n    }\n}\n\nint main() {\n    int N, M;\n    cin >> N;\n    vector<Pet> pets(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    vector<Human> humans(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\n    GridState state;\n    state.passable = vector<vector<bool>>(GRID_SIZE, vector<bool>(GRID_SIZE, true));\n    state.pets = pets;\n    state.humans = humans;\n\n    for (int turn = 0; turn < TURNS; ++turn) {\n        string actions;\n        for (int i = 0; i < M; ++i) {\n            actions += decideAction(state, i);\n        }\n        cout << actions << endl;\n        cout.flush();\n\n        vector<string> petMoves(N);\n        for (int i = 0; i < N; ++i) {\n            cin >> petMoves[i];\n        }\n        simulatePetMovement(state, petMoves);\n    }\n\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <tuple>\n#include <algorithm>\n#include <cmath>\n#include <unordered_map>\n#include <map>\n#include <set>\n#include <string>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MAX_N = 20;\nconst int MAX_M = 20;\nconst int MAX_T = 200;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct State {\n    int x, y, t;\n    double prob;\n    string path;\n\n    bool operator<(const State& other) const {\n        return prob < other.prob;\n    }\n};\n\ndouble solve(int si, int sj, int ti, int tj, double p, const vector<string>& h, const vector<string>& v) {\n    priority_queue<State> pq;\n    map<tuple<int, int, int>, double> best_prob;\n    map<tuple<int, int, int>, string> best_path;\n\n    pq.push({si, sj, 0, 1.0, \"\"});\n    best_prob[{si, sj, 0}] = 1.0;\n    best_path[{si, sj, 0}] = \"\";\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.x == ti && current.y == tj) {\n            return current.prob * (401 - current.t);\n        }\n\n        if (current.t >= MAX_T) {\n            continue;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = current.x + dx[i];\n            int ny = current.y + dy[i];\n\n            if (nx < 0 || nx >= MAX_N || ny < 0 || ny >= MAX_M) {\n                continue;\n            }\n\n            if (i == 0 && v[current.x - 1][current.y] == '1') {\n                continue;\n            }\n            if (i == 1 && v[current.x][current.y] == '1') {\n                continue;\n            }\n            if (i == 2 && h[current.x][current.y - 1] == '1') {\n                continue;\n            }\n            if (i == 3 && h[current.x][current.y] == '1') {\n                continue;\n            }\n\n            double new_prob = current.prob * (1 - p);\n            int new_t = current.t + 1;\n            string new_path = current.path + dir[i];\n\n            if (best_prob.find({nx, ny, new_t}) == best_prob.end() || new_prob > best_prob[{nx, ny, new_t}]) {\n                best_prob[{nx, ny, new_t}] = new_prob;\n                best_path[{nx, ny, new_t}] = new_path;\n                pq.push({nx, ny, new_t, new_prob, new_path});\n            }\n        }\n\n        // Stay in the current square\n        double new_prob = current.prob * p;\n        int new_t = current.t + 1;\n        string new_path = current.path + \"S\"; // 'S' represents staying\n\n        if (best_prob.find({current.x, current.y, new_t}) == best_prob.end() || new_prob > best_prob[{current.x, current.y, new_t}]) {\n            best_prob[{current.x, current.y, new_t}] = new_prob;\n            best_path[{current.x, current.y, new_t}] = new_path;\n            pq.push({current.x, current.y, new_t, new_prob, new_path});\n        }\n    }\n\n    return 0.0;\n}\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    vector<string> h(MAX_N), v(MAX_N);\n\n    cin >> si >> sj >> ti >> tj >> p;\n    for (int i = 0; i < MAX_N; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < MAX_N; ++i) {\n        cin >> v[i];\n    }\n\n    double max_score = 0.0;\n    string best_path;\n\n    // Use a heuristic to find a good path\n    // For simplicity, we use a combination of BFS and DP\n    // In a real contest, you might want to use a more sophisticated approach\n    double score = solve(si, sj, ti, tj, p, h, v);\n\n    cout << best_path << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <unordered_set>\n#include <queue>\n#include <tuple>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int POPULATION_SIZE = 100;\nconst int MAX_GENERATIONS = 100;\nconst double MUTATION_RATE = 0.1;\nconst double CROSSOVER_RATE = 0.7;\n\nvector<vector<int>> tiles(GRID_SIZE, vector<int>(GRID_SIZE));\nvector<vector<int>> rotations(GRID_SIZE, vector<int>(GRID_SIZE));\n\n// Directions: left, up, right, down\nconst int di[] = {0, -1, 0, 1};\nconst int dj[] = {-1, 0, 1, 0};\n\n// Transition table for tile types and directions\nconst vector<vector<int>> to = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\n\nint calculate_loop_length(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    unordered_set<string> visited;\n\n    while (true) {\n        int d2 = to[tiles[i][j]][d];\n        if (d2 == -1) return 0;\n        i += di[d2];\n        j += dj[d2];\n        if (i < 0 || i >= GRID_SIZE || j < 0 || j >= GRID_SIZE) return 0;\n        d = (d2 + 2) % 4;\n        length += 1;\n\n        string key = to_string(i) + \",\" + to_string(j) + \",\" + to_string(d);\n        if (visited.count(key)) break;\n        visited.insert(key);\n    }\n\n    return length;\n}\n\nvector<int> find_loop_lines() {\n    vector<int> loop_lengths;\n    vector<vector<vector<bool>>> visited(GRID_SIZE, vector<vector<bool>>(GRID_SIZE, vector<bool>(4, false)));\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            for (int d = 0; d < 4; ++d) {\n                if (!visited[i][j][d]) {\n                    int length = calculate_loop_length(i, j, d);\n                    if (length > 0) {\n                        loop_lengths.push_back(length);\n                        // Mark all tiles in the loop as visited\n                        int ci = i, cj = j, cd = d;\n                        for (int k = 0; k < length; ++k) {\n                            int cd2 = to[tiles[ci][cj]][cd];\n                            ci += di[cd2];\n                            cj += dj[cd2];\n                            cd = (cd2 + 2) % 4;\n                            visited[ci][cj][cd] = true;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    sort(loop_lengths.rbegin(), loop_lengths.rend());\n    return loop_lengths;\n}\n\nint fitness_function() {\n    vector<int> loop_lengths = find_loop_lines();\n    if (loop_lengths.size() < 2) return 0;\n    return loop_lengths[0] * loop_lengths[1];\n}\n\nvoid initialize_population(vector<vector<vector<int>>>& population) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                population[p][i][j] = dis(gen);\n            }\n        }\n    }\n}\n\nvoid mutate(vector<vector<int>>& individual) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> rot_dis(0, 3);\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (dis(gen) < MUTATION_RATE) {\n                individual[i][j] = rot_dis(gen);\n            }\n        }\n    }\n}\n\nvector<vector<int>> crossover(const vector<vector<int>>& parent1, const vector<vector<int>>& parent2) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> row_dis(0, GRID_SIZE - 1);\n    uniform_int_distribution<> col_dis(0, GRID_SIZE - 1);\n\n    vector<vector<int>> child(GRID_SIZE, vector<int>(GRID_SIZE));\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (dis(gen) < CROSSOVER_RATE) {\n                child[i][j] = parent1[i][j];\n            } else {\n                child[i][j] = parent2[i][j];\n            }\n        }\n    }\n\n    return child;\n}\n\nvoid genetic_algorithm() {\n    vector<vector<vector<int>>> population(POPULATION_SIZE, vector<vector<int>>(GRID_SIZE, vector<int>(GRID_SIZE)));\n    initialize_population(population);\n\n    for (int gen = 0; gen < MAX_GENERATIONS; ++gen) {\n        vector<int> fitness_scores(POPULATION_SIZE);\n        for (int p = 0; p < POPULATION_SIZE; ++p) {\n            rotations = population[p];\n            fitness_scores[p] = fitness_function();\n        }\n\n        vector<vector<vector<int>>> new_population;\n        for (int p = 0; p < POPULATION_SIZE; ++p) {\n            int parent1_idx = distance(fitness_scores.begin(), max_element(fitness_scores.begin(), fitness_scores.end()));\n            fitness_scores[parent1_idx] = -1;\n            int parent2_idx = distance(fitness_scores.begin(), max_element(fitness_scores.begin(), fitness_scores.end()));\n            fitness_scores[parent2_idx] = -1;\n\n            vector<vector<int>> child = crossover(population[parent1_idx], population[parent2_idx]);\n            mutate(child);\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n    }\n\n    // Find the best solution\n    int best_fitness = -1;\n    vector<vector<int>> best_rotations;\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        rotations = population[p];\n        int current_fitness = fitness_function();\n        if (current_fitness > best_fitness) {\n            best_fitness = current_fitness;\n            best_rotations = population[p];\n        }\n    }\n\n    rotations = best_rotations;\n}\n\nint main() {\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            tiles[i][j] = row[j] - '0';\n        }\n    }\n\n    genetic_algorithm();\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            cout << rotations[i][j];\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\n\nstruct State {\n    vector<vector<int>> board;\n    pair<int, int> empty;\n    int cost;\n    int heuristic;\n\n    bool operator==(const State& other) const {\n        return board == other.board && empty == other.empty;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<State> {\n        size_t operator()(const State& state) const {\n            size_t seed = 0;\n            for (const auto& row : state.board) {\n                for (int tile : row) {\n                    seed ^= hash<int>{}(tile) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n                }\n            }\n            seed ^= hash<int>{}(state.empty.first) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            seed ^= hash<int>{}(state.empty.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            return seed;\n        }\n    };\n}\n\nint calculate_heuristic(const vector<vector<int>>& board, int N) {\n    dsu_union_find uf(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0) continue;\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N || board[ni][nj] == 0) continue;\n                if ((board[i][j] & (1 << k)) && (board[ni][nj] & (1 << ((k + 2) % 4)))) {\n                    uf.merge(i * N + j, ni * N + nj);\n                }\n            }\n        }\n    }\n    unordered_set<int> roots;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] != 0) {\n                roots.insert(uf.leader(i * N + j));\n            }\n        }\n    }\n    return roots.size();\n}\n\nvector<State> get_neighbors(const State& state, int N) {\n    vector<State> neighbors;\n    int x = state.empty.first;\n    int y = state.empty.second;\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + dx[i];\n        int ny = y + dy[i];\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n        State neighbor = state;\n        neighbor.board[x][y] = neighbor.board[nx][ny];\n        neighbor.board[nx][ny] = 0;\n        neighbor.empty = {nx, ny};\n        neighbor.cost = state.cost + 1;\n        neighbor.heuristic = calculate_heuristic(neighbor.board, N);\n        neighbors.push_back(neighbor);\n    }\n    return neighbors;\n}\n\nstring a_star_search(State initial, int N, int T) {\n    auto cmp = [](const State& a, const State& b) {\n        return a.cost + a.heuristic > b.cost + b.heuristic;\n    };\n    priority_queue<State, vector<State>, decltype(cmp)> open(cmp);\n    unordered_set<State> closed;\n    open.push(initial);\n    while (!open.empty()) {\n        State current = open.top();\n        open.pop();\n        if (current.heuristic == 1) {\n            return \"\"; // Reached the goal\n        }\n        if (closed.count(current)) continue;\n        closed.insert(current);\n        for (const State& neighbor : get_neighbors(current, N)) {\n            if (!closed.count(neighbor)) {\n                open.push(neighbor);\n            }\n        }\n    }\n    return \"\"; // No solution found\n}\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    pair<int, int> empty;\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            char c = row[j];\n            if (c >= '0' && c <= '9') {\n                board[i][j] = c - '0';\n            } else {\n                board[i][j] = 10 + (c - 'a');\n            }\n            if (board[i][j] == 0) {\n                empty = {i, j};\n            }\n        }\n    }\n    State initial = {board, empty, 0, calculate_heuristic(board, N)};\n    string solution = a_star_search(initial, N, T);\n    cout << solution << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <limits>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Line {\n    Point p, q;\n    Line(Point p, Point q) : p(p), q(q) {}\n};\n\nstruct Strawberry {\n    int x, y;\n    Strawberry(int x, int y) : x(x), y(y) {}\n};\n\nvector<Strawberry> strawberries;\nvector<int> a_d(10);\nint K;\n\ndouble distance(const Point& p1, const Point& p2) {\n    return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));\n}\n\nbool isInside(const Point& p, const Line& line) {\n    // Check if point p is inside the cake and not cut by the line\n    if (distance(p, Point(0, 0)) >= 10000) {\n        return false;\n    }\n    // Check if the point is on the line\n    int x1 = line.p.x, y1 = line.p.y;\n    int x2 = line.q.x, y2 = line.q.y;\n    int x = p.x, y = p.y;\n    if ((y2 - y1) * (x - x1) == (y - y1) * (x2 - x1)) {\n        return false;\n    }\n    return true;\n}\n\nint countPieces(const vector<Line>& lines, int d) {\n    vector<vector<bool>> inside(strawberries.size(), vector<bool>(lines.size() + 1, true));\n    for (int i = 0; i < lines.size(); ++i) {\n        for (int j = 0; j < strawberries.size(); ++j) {\n            if (!isInside(Point(strawberries[j].x, strawberries[j].y), lines[i])) {\n                inside[j][i + 1] = false;\n            }\n        }\n    }\n    int count = 0;\n    for (int i = 0; i < strawberries.size(); ++i) {\n        int c = 0;\n        for (int j = 0; j <= lines.size(); ++j) {\n            if (inside[i][j]) {\n                c++;\n            }\n        }\n        if (c == d) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvector<Line> greedyAlgorithm() {\n    vector<Line> lines;\n    for (int d = 1; d <= 10; ++d) {\n        if (a_d[d - 1] == 0) continue;\n        int maxPieces = 0;\n        Line bestLine(Point(0, 0), Point(0, 0));\n        for (int i = 0; i < 100; ++i) {\n            // Generate random line\n            random_device rd;\n            mt19937 gen(rd());\n            uniform_int_distribution<> dis(-1e9, 1e9);\n            Point p(dis(gen), dis(gen));\n            Point q(dis(gen), dis(gen));\n            Line line(p, q);\n            vector<Line> tempLines = lines;\n            tempLines.push_back(line);\n            int pieces = countPieces(tempLines, d);\n            if (pieces > maxPieces) {\n                maxPieces = pieces;\n                bestLine = line;\n            }\n        }\n        if (maxPieces > 0) {\n            lines.push_back(bestLine);\n            if (lines.size() >= K) break;\n        }\n    }\n    return lines;\n}\n\nint main() {\n    int N;\n    cin >> N >> K;\n    for (int i = 0; i < 10; ++i) {\n        cin >> a_d[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        strawberries.emplace_back(x, y);\n    }\n    vector<Line> lines = greedyAlgorithm();\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line.p.x << \" \" << line.p.y << \" \" << line.q.x << \" \" << line.q.y << endl;\n    }\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n#include <unordered_set>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nclass RectJoinGame {\nprivate:\n    int N, M;\n    unordered_set<Point> dots;\n    vector<Rectangle> rectangles;\n    int c;\n    double S;\n    mt19937 rng;\n\n    double weight(int x, int y) {\n        return (x - c) * (x - c) + (y - c) * (y - c) + 1;\n    }\n\n    bool isValidRectangle(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        // Check if the points form a valid rectangle (axis-aligned or 45-degree)\n        int dx1 = p2.x - p1.x;\n        int dy1 = p2.y - p1.y;\n        int dx2 = p3.x - p2.x;\n        int dy2 = p3.y - p2.y;\n        int dx3 = p4.x - p3.x;\n        int dy3 = p4.y - p3.y;\n        int dx4 = p1.x - p4.x;\n        int dy4 = p1.y - p4.y;\n\n        // Check if the sides are equal and perpendicular\n        if ((dx1 == dx3 && dy1 == dy3) && (dx2 == dx4 && dy2 == dy4) &&\n            (dx1 * dx2 + dy1 * dy2 == 0)) {\n            // Check if the rectangle is axis-aligned or 45-degree\n            if ((dx1 == 0 || dy1 == 0 || abs(dx1) == abs(dy1)) &&\n                (dx2 == 0 || dy2 == 0 || abs(dx2) == abs(dy2))) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    bool isValidOperation(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        if (dots.count(p1)) return false;\n        if (!dots.count(p2) || !dots.count(p3) || !dots.count(p4)) return false;\n        if (!isValidRectangle(p1, p2, p3, p4)) return false;\n\n        // Check if the perimeter of the rectangle contains any other dots\n        set<Point> perimeter;\n        int dx = p2.x - p1.x;\n        int dy = p2.y - p1.y;\n        for (int i = 0; i <= 1; ++i) {\n            for (int j = 0; j <= 1; ++j) {\n                int x = p1.x + i * dx;\n                int y = p1.y + i * dy;\n                for (int k = 0; k <= 1; ++k) {\n                    int nx = x + k * dy;\n                    int ny = y - k * dx;\n                    perimeter.insert(Point(nx, ny));\n                }\n            }\n        }\n        for (const auto& p : perimeter) {\n            if (dots.count(p) && !(p == p1 || p == p2 || p == p3 || p == p4)) {\n                return false;\n            }\n        }\n\n        // Check if the perimeter of the rectangle shares a common segment with any previously drawn rectangle\n        for (const auto& rect : rectangles) {\n            set<Point> rectPerimeter;\n            int rdx = rect.p2.x - rect.p1.x;\n            int rdy = rect.p2.y - rect.p1.y;\n            for (int i = 0; i <= 1; ++i) {\n                for (int j = 0; j <= 1; ++j) {\n                    int x = rect.p1.x + i * rdx;\n                    int y = rect.p1.y + i * rdy;\n                    for (int k = 0; k <= 1; ++k) {\n                        int nx = x + k * rdy;\n                        int ny = y - k * rdx;\n                        rectPerimeter.insert(Point(nx, ny));\n                    }\n                }\n            }\n            set<Point> intersection;\n            set_intersection(perimeter.begin(), perimeter.end(), rectPerimeter.begin(), rectPerimeter.end(), inserter(intersection, intersection.begin()));\n            if (intersection.size() > 2) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    double calculateScore() {\n        double sum = 0;\n        for (const auto& p : dots) {\n            sum += weight(p.x, p.y);\n        }\n        return round(1e6 * N * N / M * sum / S);\n    }\n\n    vector<Point> getNeighbors(const Point& p) {\n        vector<Point> neighbors;\n        for (int dx = -1; dx <= 1; ++dx) {\n            for (int dy = -1; dy <= 1; ++dy) {\n                if (dx == 0 && dy == 0) continue;\n                int nx = p.x + dx;\n                int ny = p.y + dy;\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N) {\n                    neighbors.emplace_back(nx, ny);\n                }\n            }\n        }\n        return neighbors;\n    }\n\n    pair<Point, vector<Point>> findBestOperation() {\n        double bestScore = -1;\n        Point bestP1(-1, -1); // Initialize with default values\n        vector<Point> bestP234;\n\n        for (const auto& p1 : dots) {\n            auto neighbors = getNeighbors(p1);\n            for (const auto& p2 : neighbors) {\n                if (!dots.count(p2)) continue;\n                for (const auto& p3 : neighbors) {\n                    if (!dots.count(p3) || p3 == p2) continue;\n                    for (const auto& p4 : neighbors) {\n                        if (!dots.count(p4) || p4 == p2 || p4 == p3) continue;\n                        if (isValidOperation(p1, p2, p3, p4)) {\n                            dots.insert(p1);\n                            rectangles.emplace_back(p1, p2, p3, p4);\n                            double score = calculateScore();\n                            dots.erase(p1);\n                            rectangles.pop_back();\n                            if (score > bestScore) {\n                                bestScore = score;\n                                bestP1 = p1;\n                                bestP234 = {p2, p3, p4};\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        return {bestP1, bestP234};\n    }\n\n    void simulatedAnnealing(double initialTemp, double finalTemp, double alpha) {\n        double temp = initialTemp;\n        auto currentScore = calculateScore();\n        auto bestScore = currentScore;\n        vector<Rectangle> bestRectangles = rectangles;\n\n        while (temp > finalTemp) {\n            auto [p1, p234] = findBestOperation();\n            if (p234.empty()) break;\n\n            dots.insert(p1);\n            rectangles.emplace_back(p1, p234[0], p234[1], p234[2]);\n            auto newScore = calculateScore();\n\n            if (newScore > currentScore || exp((newScore - currentScore) / temp) > uniform_real_distribution<double>(0, 1)(rng)) {\n                currentScore = newScore;\n                if (newScore > bestScore) {\n                    bestScore = newScore;\n                    bestRectangles = rectangles;\n                }\n            } else {\n                dots.erase(p1);\n                rectangles.pop_back();\n            }\n\n            temp *= alpha;\n        }\n\n        rectangles = bestRectangles;\n    }\n\npublic:\n    RectJoinGame(int N, int M, const vector<Point>& initialDots) : N(N), M(M), dots(initialDots.begin(), initialDots.end()), c((N - 1) / 2), rng(chrono::steady_clock::now().time_since_epoch().count()) {\n        S = 0;\n        for (int x = 0; x < N; ++x) {\n            for (int y = 0; y < N; ++y) {\n                S += weight(x, y);\n            }\n        }\n    }\n\n    void play() {\n        simulatedAnnealing(1000, 0.1, 0.99);\n    }\n\n    void output() const {\n        cout << rectangles.size() << endl;\n        for (const auto& rect : rectangles) {\n            cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n                 << rect.p2.x << \" \" << rect.p2.y << \" \"\n                 << rect.p3.x << \" \" << rect.p3.y << \" \"\n                 << rect.p4.x << \" \" << rect.p4.y << endl;\n        }\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<Point> initialDots;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        initialDots.emplace_back(x, y);\n    }\n\n    RectJoinGame game(N, M, initialDots);\n    game.play();\n    game.output();\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <array>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <queue>\n\nusing namespace std;\n\nconst int GRID_SIZE = 10;\nconst int NUM_FLAVORS = 3;\nconst int NUM_CANDIES = 100;\nconst int LOOKAHEAD_STEPS = 3;\n\nenum Direction { FORWARD, BACKWARD, LEFT, RIGHT };\n\nstruct Candy {\n    int flavor;\n    int row;\n    int col;\n};\n\nstruct Grid {\n    array<array<int, GRID_SIZE>, GRID_SIZE> cells;\n    vector<Candy> candies;\n\n    Grid() {\n        for (auto& row : cells) {\n            fill(row.begin(), row.end(), 0);\n        }\n    }\n\n    void place_candy(int flavor, int row, int col) {\n        cells[row][col] = flavor;\n        candies.push_back({flavor, row, col});\n    }\n\n    void tilt(Direction dir) {\n        switch (dir) {\n            case FORWARD:\n                tilt_forward();\n                break;\n            case BACKWARD:\n                tilt_backward();\n                break;\n            case LEFT:\n                tilt_left();\n                break;\n            case RIGHT:\n                tilt_right();\n                break;\n        }\n    }\n\n    void tilt_forward() {\n        for (int col = 0; col < GRID_SIZE; ++col) {\n            int empty_row = GRID_SIZE - 1;\n            for (int row = GRID_SIZE - 1; row >= 0; --row) {\n                if (cells[row][col] != 0) {\n                    cells[empty_row][col] = cells[row][col];\n                    if (empty_row != row) {\n                        cells[row][col] = 0;\n                    }\n                    --empty_row;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_backward() {\n        for (int col = 0; col < GRID_SIZE; ++col) {\n            int empty_row = 0;\n            for (int row = 0; row < GRID_SIZE; ++row) {\n                if (cells[row][col] != 0) {\n                    cells[empty_row][col] = cells[row][col];\n                    if (empty_row != row) {\n                        cells[row][col] = 0;\n                    }\n                    ++empty_row;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_left() {\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            int empty_col = 0;\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0) {\n                    cells[row][empty_col] = cells[row][col];\n                    if (empty_col != col) {\n                        cells[row][col] = 0;\n                    }\n                    ++empty_col;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_right() {\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            int empty_col = GRID_SIZE - 1;\n            for (int col = GRID_SIZE - 1; col >= 0; --col) {\n                if (cells[row][col] != 0) {\n                    cells[row][empty_col] = cells[row][col];\n                    if (empty_col != col) {\n                        cells[row][col] = 0;\n                    }\n                    --empty_col;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void update_candies() {\n        candies.clear();\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0) {\n                    candies.push_back({cells[row][col], row, col});\n                }\n            }\n        }\n    }\n\n    int calculate_score() {\n        array<int, NUM_FLAVORS + 1> flavor_counts = {0};\n        for (const auto& candy : candies) {\n            flavor_counts[candy.flavor]++;\n        }\n\n        int sum_squares = 0;\n        for (int i = 1; i <= NUM_FLAVORS; ++i) {\n            sum_squares += flavor_counts[i] * flavor_counts[i];\n        }\n\n        array<array<bool, GRID_SIZE>, GRID_SIZE> visited = {false};\n        int connectivity = 0;\n\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0 && !visited[row][col]) {\n                    int flavor = cells[row][col];\n                    int component_size = 0;\n                    vector<pair<int, int>> stack = {{row, col}};\n                    visited[row][col] = true;\n\n                    while (!stack.empty()) {\n                        auto [r, c] = stack.back();\n                        stack.pop_back();\n                        component_size++;\n\n                        for (const auto& [dr, dc] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                            int nr = r + dr;\n                            int nc = c + dc;\n                            if (nr >= 0 && nr < GRID_SIZE && nc >= 0 && nc < GRID_SIZE && cells[nr][nc] == flavor && !visited[nr][nc]) {\n                                visited[nr][nc] = true;\n                                stack.emplace_back(nr, nc);\n                            }\n                        }\n                    }\n\n                    connectivity += component_size * component_size;\n                }\n            }\n        }\n\n        return round(1e6 * static_cast<double>(connectivity) / sum_squares);\n    }\n};\n\nDirection choose_direction(const Grid& grid, int flavor, const vector<int>& remaining_flavors) {\n    array<int, 4> scores = {0};\n    array<Grid, 4> grids;\n\n    for (int i = 0; i < 4; ++i) {\n        grids[i] = grid;\n        grids[i].tilt(static_cast<Direction>(i));\n\n        // Simulate lookahead steps\n        Grid lookahead_grid = grids[i];\n        for (int step = 0; step < LOOKAHEAD_STEPS && step < remaining_flavors.size(); ++step) {\n            // Place the next candy in a random empty cell\n            vector<pair<int, int>> empty_cells;\n            for (int row = 0; row < GRID_SIZE; ++row) {\n                for (int col = 0; col < GRID_SIZE; ++col) {\n                    if (lookahead_grid.cells[row][col] == 0) {\n                        empty_cells.emplace_back(row, col);\n                    }\n                }\n            }\n\n            if (!empty_cells.empty()) {\n                random_device rd;\n                mt19937 gen(rd());\n                uniform_int_distribution<> dis(0, empty_cells.size() - 1);\n                auto [row, col] = empty_cells[dis(gen)];\n                lookahead_grid.place_candy(remaining_flavors[step], row, col);\n\n                // Choose a random tilt direction for the next step\n                uniform_int_distribution<> tilt_dis(0, 3);\n                lookahead_grid.tilt(static_cast<Direction>(tilt_dis(gen)));\n            }\n        }\n\n        scores[i] = lookahead_grid.calculate_score();\n    }\n\n    int max_score = *max_element(scores.begin(), scores.end());\n    vector<Direction> best_directions;\n\n    for (int i = 0; i < 4; ++i) {\n        if (scores[i] == max_score) {\n            best_directions.push_back(static_cast<Direction>(i));\n        }\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, best_directions.size() - 1);\n\n    return best_directions[dis(gen)];\n}\n\nint main() {\n    vector<int> flavors(NUM_CANDIES);\n    for (int& flavor : flavors) {\n        cin >> flavor;\n    }\n\n    Grid grid;\n    for (int t = 0; t < NUM_CANDIES; ++t) {\n        int p;\n        cin >> p;\n\n        int empty_cell = 0;\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (grid.cells[row][col] == 0) {\n                    empty_cell++;\n                    if (empty_cell == p) {\n                        grid.place_candy(flavors[t], row, col);\n                        break;\n                    }\n                }\n            }\n            if (empty_cell == p) {\n                break;\n            }\n        }\n\n        if (t < NUM_CANDIES - 1) {\n            vector<int> remaining_flavors(flavors.begin() + t + 1, flavors.end());\n            Direction dir = choose_direction(grid, flavors[t], remaining_flavors);\n            grid.tilt(dir);\n\n            switch (dir) {\n                case FORWARD:\n                    cout << \"F\" << endl;\n                    break;\n                case BACKWARD:\n                    cout << \"B\" << endl;\n                    break;\n                case LEFT:\n                    cout << \"L\" << endl;\n                    break;\n                case RIGHT:\n                    cout << \"R\" << endl;\n                    break;\n            }\n            cout.flush();\n        }\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int MAX_N = 100;\nconst int MAX_M = 100;\nconst int MAX_QUERIES = 100;\n\nmt19937 rng(random_device{}());\n\nint M;\ndouble epsilon;\nint N;\nvector<vector<vector<bool>>> G;\nvector<vector<bool>> H;\n\nvoid generate_graphs() {\n    // Use a combination of edge patterns and vertex orderings to encode numbers\n    for (int k = 0; k < M; ++k) {\n        vector<vector<bool>> graph(N, vector<bool>(N, false));\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                // Use a combination of edge patterns to encode the number k\n                if ((k & (1 << (i + j))) != 0) {\n                    graph[i][j] = true;\n                    graph[j][i] = true;\n                }\n            }\n        }\n        G.push_back(graph);\n    }\n}\n\nvoid output_graphs() {\n    cout << N << endl;\n    for (const auto& graph : G) {\n        string s;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                s += graph[i][j] ? '1' : '0';\n            }\n        }\n        cout << s << endl;\n    }\n    cout.flush();\n}\n\nvoid read_graph() {\n    string s;\n    cin >> s;\n    H.assign(N, vector<bool>(N, false));\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            H[i][j] = (s[idx++] == '1');\n            H[j][i] = H[i][j];\n        }\n    }\n}\n\nint calculate_similarity(const vector<vector<bool>>& a, const vector<vector<bool>>& b) {\n    int similarity = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (a[i][j] == b[i][j]) {\n                similarity++;\n            }\n        }\n    }\n    return similarity;\n}\n\nint predict_graph() {\n    int best_match = -1;\n    int max_similarity = -1;\n    for (int k = 0; k < M; ++k) {\n        int similarity = calculate_similarity(H, G[k]);\n        if (similarity > max_similarity) {\n            max_similarity = similarity;\n            best_match = k;\n        }\n    }\n    return best_match;\n}\n\nint main() {\n    cin >> M >> epsilon;\n    N = 20; // Choose a reasonable N within the constraints\n\n    generate_graphs();\n    output_graphs();\n\n    for (int q = 0; q < MAX_QUERIES; ++q) {\n        read_graph();\n        int t = predict_graph();\n        cout << t << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <limits>\n#include <unordered_map>\n#include <unordered_set>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v, w;\n    int day;\n    bool operator<(const Edge& other) const {\n        return w > other.w;\n    }\n};\n\nstruct Vertex {\n    int id;\n    double betweenness;\n    Vertex(int id) : id(id), betweenness(0.0) {}\n};\n\nclass Graph {\nprivate:\n    int N, M, D, K;\n    vector<vector<pair<int, int>>> adj;\n    vector<Edge> edges;\n    vector<Vertex> vertices;\n\n    void computeBetweennessCentrality() {\n        for (int s = 0; s < N; ++s) {\n            vector<int> numSP(N, 0);\n            vector<double> bc(N, 0.0);\n            vector<vector<int>> predecessors(N);\n            vector<int> stack;\n            vector<int> sigma(N, 0);\n            vector<int> distance(N, -1);\n\n            queue<int> q;\n            q.push(s);\n            sigma[s] = 1;\n            distance[s] = 0;\n\n            while (!q.empty()) {\n                int v = q.front();\n                q.pop();\n                stack.push_back(v);\n                for (const auto& neighbor : adj[v]) {\n                    int w = neighbor.first;\n                    if (distance[w] < 0) {\n                        q.push(w);\n                        distance[w] = distance[v] + 1;\n                    }\n                    if (distance[w] == distance[v] + 1) {\n                        sigma[w] += sigma[v];\n                        predecessors[w].push_back(v);\n                    }\n                }\n            }\n\n            while (!stack.empty()) {\n                int w = stack.back();\n                stack.pop_back();\n                for (int v : predecessors[w]) {\n                    bc[v] += (sigma[v] / static_cast<double>(sigma[w])) * (1.0 + bc[w]);\n                }\n                if (w != s) {\n                    vertices[w].betweenness += bc[w];\n                }\n            }\n        }\n    }\n\n    void prioritizeEdges() {\n        computeBetweennessCentrality();\n        sort(edges.begin(), edges.end(), [this](const Edge& a, const Edge& b) {\n            double a_betweenness = vertices[a.u].betweenness + vertices[a.v].betweenness;\n            double b_betweenness = vertices[b.u].betweenness + vertices[b.v].betweenness;\n            return a_betweenness > b_betweenness;\n        });\n    }\n\n    void assignDays() {\n        vector<int> dayCounts(D, 0);\n        for (auto& edge : edges) {\n            int bestDay = -1;\n            double minIncrease = numeric_limits<double>::max();\n            for (int day = 0; day < D; ++day) {\n                if (dayCounts[day] >= K) continue;\n                double increase = calculateFrustrationIncrease(edge, day);\n                if (increase < minIncrease) {\n                    minIncrease = increase;\n                    bestDay = day;\n                }\n            }\n            edge.day = bestDay;\n            dayCounts[bestDay]++;\n        }\n    }\n\n    double calculateFrustrationIncrease(const Edge& edge, int day) {\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            for (const auto& neighbor : adj[i]) {\n                int v = neighbor.first;\n                int w = neighbor.second;\n                dist[i][v] = min(dist[i][v], w);\n            }\n        }\n\n        for (int k = 0; k < N; ++k) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (dist[i][k] != numeric_limits<int>::max() && dist[k][j] != numeric_limits<int>::max()) {\n                        dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n                    }\n                }\n            }\n        }\n\n        vector<vector<int>> newDist = dist;\n        newDist[edge.u][edge.v] = numeric_limits<int>::max();\n        newDist[edge.v][edge.u] = numeric_limits<int>::max();\n\n        for (int k = 0; k < N; ++k) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (newDist[i][k] != numeric_limits<int>::max() && newDist[k][j] != numeric_limits<int>::max()) {\n                        newDist[i][j] = min(newDist[i][j], newDist[i][k] + newDist[k][j]);\n                    }\n                }\n            }\n        }\n\n        double totalIncrease = 0.0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (i != j) {\n                    int originalDist = dist[i][j];\n                    int newDistVal = newDist[i][j];\n                    if (newDistVal == numeric_limits<int>::max()) {\n                        newDistVal = 1e9;\n                    }\n                    totalIncrease += (newDistVal - originalDist);\n                }\n            }\n        }\n\n        return totalIncrease / (N * (N - 1));\n    }\n\npublic:\n    Graph(int N, int M, int D, int K) : N(N), M(M), D(D), K(K), adj(N), vertices(N) {\n        for (int i = 0; i < N; ++i) {\n            vertices[i].id = i;\n        }\n    }\n\n    void addEdge(int u, int v, int w) {\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n        edges.push_back({u, v, w, -1});\n    }\n\n    void solve() {\n        prioritizeEdges();\n        assignDays();\n    }\n\n    void printSolution() {\n        for (const auto& edge : edges) {\n            cout << edge.day + 1 << \" \";\n        }\n        cout << endl;\n    }\n};\n\nint main() {\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    Graph graph(N, M, D, K);\n\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        graph.addEdge(u - 1, v - 1, w);\n    }\n\n    // Skip reading the coordinates if not needed\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    graph.solve();\n    graph.printSolution();\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Block {\n    vector<vector<vector<bool>>> shape;\n    int volume;\n\n    Block(const vector<vector<vector<bool>>>& s) : shape(s) {\n        volume = 0;\n        for (const auto& layer : shape) {\n            for (const auto& row : layer) {\n                for (bool cell : row) {\n                    if (cell) volume++;\n                }\n            }\n        }\n    }\n\n    void rotateX() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[x][D - 1 - z][y] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n\n    void rotateY() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[z][y][D - 1 - x] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n\n    void rotateZ() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[D - 1 - y][x][z] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n};\n\nstruct Individual {\n    vector<Block> blocks;\n    vector<vector<vector<int>>> arrangement1;\n    vector<vector<vector<int>>> arrangement2;\n    double fitness;\n\n    Individual(const vector<Block>& b, int D) : blocks(b) {\n        arrangement1 = vector<vector<vector<int>>>(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        arrangement2 = vector<vector<vector<int>>>(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        fitness = 0.0;\n    }\n};\n\nvector<Block> generateInitialBlocks(int D) {\n    vector<Block> blocks;\n    // Generate some initial blocks, e.g., single cubes, 2x2x2 cubes, etc.\n    // This is a placeholder; actual block generation should be more sophisticated.\n    vector<vector<vector<bool>>> singleCube(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    singleCube[0][0][0] = true;\n    blocks.emplace_back(singleCube);\n\n    vector<vector<vector<bool>>> twoCube(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    twoCube[0][0][0] = true;\n    twoCube[0][0][1] = true;\n    blocks.emplace_back(twoCube);\n\n    return blocks;\n}\n\nvector<vector<vector<bool>>> createSilhouette(int D, const vector<string>& f, const vector<string>& r) {\n    vector<vector<vector<bool>>> silhouette(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    for (int z = 0; z < D; ++z) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                if (f[z][x] == '1' && r[z][y] == '1') {\n                    silhouette[x][y][z] = true;\n                }\n            }\n        }\n    }\n    return silhouette;\n}\n\ndouble evaluateFitness(const Individual& ind, const vector<vector<vector<bool>>>& silhouette1, const vector<vector<vector<bool>>>& silhouette2) {\n    int D = silhouette1.size();\n    double fitness = 0.0;\n\n    // Check silhouette1\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 (silhouette1[x][y][z]) {\n                    bool covered = false;\n                    for (const auto& block : ind.blocks) {\n                        if (ind.arrangement1[x][y][z] != 0) {\n                            covered = true;\n                            break;\n                        }\n                    }\n                    if (!covered) fitness += 1.0;\n                }\n            }\n        }\n    }\n\n    // Check silhouette2\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 (silhouette2[x][y][z]) {\n                    bool covered = false;\n                    for (const auto& block : ind.blocks) {\n                        if (ind.arrangement2[x][y][z] != 0) {\n                            covered = true;\n                            break;\n                        }\n                    }\n                    if (!covered) fitness += 1.0;\n                }\n            }\n        }\n    }\n\n    // Penalize unused blocks\n    unordered_set<int> usedBlocks1, usedBlocks2;\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 (ind.arrangement1[x][y][z] != 0) usedBlocks1.insert(ind.arrangement1[x][y][z]);\n                if (ind.arrangement2[x][y][z] != 0) usedBlocks2.insert(ind.arrangement2[x][y][z]);\n            }\n        }\n    }\n    for (int i = 1; i <= ind.blocks.size(); ++i) {\n        if (usedBlocks1.find(i) == usedBlocks1.end() && usedBlocks2.find(i) == usedBlocks2.end()) {\n            fitness += ind.blocks[i - 1].volume;\n        }\n    }\n\n    // Penalize blocks used in both arrangements\n    unordered_set<int> commonBlocks;\n    for (int block : usedBlocks1) {\n        if (usedBlocks2.find(block) != usedBlocks2.end()) {\n            commonBlocks.insert(block);\n        }\n    }\n    for (int block : commonBlocks) {\n        fitness += 1.0 / ind.blocks[block - 1].volume;\n    }\n\n    return fitness;\n}\n\nIndividual geneticAlgorithm(int D, const vector<vector<vector<bool>>>& silhouette1, const vector<vector<vector<bool>>>& silhouette2, int populationSize, int generations) {\n    vector<Block> initialBlocks = generateInitialBlocks(D);\n    vector<Individual> population;\n    for (int i = 0; i < populationSize; ++i) {\n        population.emplace_back(initialBlocks, D);\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> blockDist(0, initialBlocks.size() - 1);\n    uniform_int_distribution<> posDist(0, D - 1);\n\n    for (int gen = 0; gen < generations; ++gen) {\n        // Evaluate fitness\n        for (auto& ind : population) {\n            ind.fitness = evaluateFitness(ind, silhouette1, silhouette2);\n        }\n\n        // Sort by fitness\n        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n            return a.fitness < b.fitness;\n        });\n\n        // Select top individuals\n        vector<Individual> newPopulation;\n        for (int i = 0; i < populationSize / 2; ++i) {\n            newPopulation.push_back(population[i]);\n        }\n\n        // Crossover and mutation\n        while (newPopulation.size() < populationSize) {\n            Individual parent1 = population[rand() % (populationSize / 2)];\n            Individual parent2 = population[rand() % (populationSize / 2)];\n            Individual child(parent1.blocks, D);\n\n            // Crossover: randomly select arrangements from parents\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 (rand() % 2) {\n                            child.arrangement1[x][y][z] = parent1.arrangement1[x][y][z];\n                            child.arrangement2[x][y][z] = parent1.arrangement2[x][y][z];\n                        } else {\n                            child.arrangement1[x][y][z] = parent2.arrangement1[x][y][z];\n                            child.arrangement2[x][y][z] = parent2.arrangement2[x][y][z];\n                        }\n                    }\n                }\n            }\n\n            // Mutation: randomly change some blocks\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 (rand() % 100 < 5) { // 5% mutation rate\n                            child.arrangement1[x][y][z] = blockDist(gen) + 1;\n                            child.arrangement2[x][y][z] = blockDist(gen) + 1;\n                        }\n                    }\n                }\n            }\n\n            newPopulation.push_back(child);\n        }\n\n        population = newPopulation;\n    }\n\n    // Return the best individual\n    sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n        return a.fitness < b.fitness;\n    });\n\n    return population[0];\n}\n\nint main() {\n    int D;\n    cin >> D;\n\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for (int i = 0; i < D; ++i) cin >> f1[i];\n    for (int i = 0; i < D; ++i) cin >> r1[i];\n    for (int i = 0; i < D; ++i) cin >> f2[i];\n    for (int i = 0; i < D; ++i) cin >> r2[i];\n\n    vector<vector<vector<bool>>> silhouette1 = createSilhouette(D, f1, r1);\n    vector<vector<vector<bool>>> silhouette2 = createSilhouette(D, f2, r2);\n\n    Individual bestIndividual = geneticAlgorithm(D, silhouette1, silhouette2, 50, 100);\n\n    // Output the best individual\n    int n = bestIndividual.blocks.size();\n    cout << n << endl;\n\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                cout << bestIndividual.arrangement1[x][y][z] << \" \";\n            }\n        }\n    }\n    cout << endl;\n\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                cout << bestIndividual.arrangement2[x][y][z] << \" \";\n            }\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <limits>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\nusing namespace std;\nusing namespace boost;\n\ntypedef adjacency_list<vecS, vecS, undirectedS,\n                       no_property,\n                       property<edge_weight_t, int> > Graph;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef graph_traits<Graph>::edge_descriptor Edge;\ntypedef graph_traits<Graph>::edge_iterator EdgeIterator;\ntypedef graph_traits<Graph>::vertex_iterator VertexIterator;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Resident {\n    int a, b;\n    Resident(int a, int b) : a(a), b(b) {}\n};\n\nstruct EdgeInfo {\n    int u, v, w;\n    EdgeInfo(int u, int v, int w) : u(u), v(v), w(w) {}\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<Point> stations(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> stations[i].x >> stations[i].y;\n    }\n\n    vector<EdgeInfo> edges(M);\n    for (int j = 0; j < M; ++j) {\n        cin >> edges[j].u >> edges[j].v >> edges[j].w;\n        edges[j].u--; // Convert to 0-based index\n        edges[j].v--;\n    }\n\n    vector<Resident> residents(K);\n    for (int k = 0; k < K; ++k) {\n        cin >> residents[k].a >> residents[k].b;\n    }\n\n    // Build the graph\n    Graph g(N);\n    vector<Edge> edge_map(M);\n    for (int j = 0; j < M; ++j) {\n        edge_map[j] = add_edge(edges[j].u, edges[j].v, edges[j].w, g).first;\n    }\n\n    // Find the Minimum Spanning Tree (MST)\n    vector<Edge> mst_edges;\n    kruskal_minimum_spanning_tree(g, back_inserter(mst_edges));\n\n    // Create a subgraph with MST edges\n    Graph mst(N);\n    for (const auto& e : mst_edges) {\n        add_edge(source(e, g), target(e, g), get(edge_weight, g, e), mst);\n    }\n\n    // Calculate the minimum output strength for each station\n    vector<int> P(N, 0);\n    for (int i = 0; i < N; ++i) {\n        double max_dist = 0.0;\n        for (const auto& resident : residents) {\n            double dist = sqrt(pow(stations[i].x - resident.a, 2) + pow(stations[i].y - resident.b, 2));\n            if (dist > max_dist) {\n                max_dist = dist;\n            }\n        }\n        P[i] = static_cast<int>(ceil(max_dist));\n    }\n\n    // Ensure all residents are covered\n    unordered_set<int> covered_residents;\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            double dist = sqrt(pow(stations[i].x - residents[k].a, 2) + pow(stations[i].y - residents[k].b, 2));\n            if (dist <= P[i]) {\n                covered_residents.insert(k);\n            }\n        }\n    }\n\n    // If not all residents are covered, increase the output strength of the nearest station\n    while (covered_residents.size() < K) {\n        for (int k = 0; k < K; ++k) {\n            if (covered_residents.find(k) == covered_residents.end()) {\n                double min_dist = numeric_limits<double>::max();\n                int nearest_station = -1;\n                for (int i = 0; i < N; ++i) {\n                    double dist = sqrt(pow(stations[i].x - residents[k].a, 2) + pow(stations[i].y - residents[k].b, 2));\n                    if (dist < min_dist) {\n                        min_dist = dist;\n                        nearest_station = i;\n                    }\n                }\n                P[nearest_station] = static_cast<int>(ceil(min_dist));\n                for (int kk = 0; kk < K; ++kk) {\n                    double dist = sqrt(pow(stations[nearest_station].x - residents[kk].a, 2) + pow(stations[nearest_station].y - residents[kk].b, 2));\n                    if (dist <= P[nearest_station]) {\n                        covered_residents.insert(kk);\n                    }\n                }\n            }\n        }\n    }\n\n    // Output the results\n    for (int i = 0; i < N; ++i) {\n        cout << P[i] << \" \";\n    }\n    cout << endl;\n\n    // Create a set of edges in the MST for quick lookup\n    unordered_set<Edge> mst_edge_set;\n    for (const auto& e : mst_edges) {\n        mst_edge_set.insert(e);\n    }\n\n    // Output the power status of each edge\n    for (int j = 0; j < M; ++j) {\n        Edge e = edge(edges[j].u, edges[j].v, g).first;\n        if (mst_edge_set.find(e) != mst_edge_set.end()) {\n            cout << \"1 \";\n        } else {\n            cout << \"0 \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 30;\nconst int MAX_OPERATIONS = 10000;\n\nvector<vector<int>> pyramid;\n\nstruct Operation {\n    int x1, y1, x2, y2;\n};\n\nvector<Operation> operations;\n\nbool is_adjacent(int x1, int y1, int x2, int y2) {\n    if (x1 == x2 - 1 && y1 == y2 - 1) return true;\n    if (x1 == x2 - 1 && y1 == y2) return true;\n    if (x1 == x2 && y1 == y2 - 1) return true;\n    if (x1 == x2 && y1 == y2 + 1) return true;\n    if (x1 == x2 + 1 && y1 == y2) return true;\n    if (x1 == x2 + 1 && y1 == y2 + 1) return true;\n    return false;\n}\n\nvoid swap_balls(int x1, int y1, int x2, int y2) {\n    swap(pyramid[x1][y1], pyramid[x2][y2]);\n    operations.push_back({x1, y1, x2, y2});\n}\n\nint count_violations() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] > pyramid[x + 1][y]) violations++;\n            if (pyramid[x][y] > pyramid[x + 1][y + 1]) violations++;\n        }\n    }\n    return violations;\n}\n\nvoid greedy_algorithm() {\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] > pyramid[x + 1][y]) {\n                if (is_adjacent(x, y, x + 1, y)) {\n                    swap_balls(x, y, x + 1, y);\n                } else {\n                    // Find a path to swap\n                    // This is a simplified approach; a more sophisticated pathfinding algorithm can be used here\n                    for (int i = x + 1; i < N; ++i) {\n                        if (is_adjacent(i, y, i + 1, y)) {\n                            swap_balls(i, y, i + 1, y);\n                        }\n                    }\n                }\n            }\n            if (pyramid[x][y] > pyramid[x + 1][y + 1]) {\n                if (is_adjacent(x, y, x + 1, y + 1)) {\n                    swap_balls(x, y, x + 1, y + 1);\n                } else {\n                    // Find a path to swap\n                    // This is a simplified approach; a more sophisticated pathfinding algorithm can be used here\n                    for (int i = x + 1; i < N; ++i) {\n                        if (is_adjacent(i, y + 1, i + 1, y + 1)) {\n                            swap_balls(i, y + 1, i + 1, y + 1);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid simulated_annealing() {\n    int current_violations = count_violations();\n    if (current_violations == 0) return;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    double temperature = 1.0;\n    double cooling_rate = 0.999;\n    int max_iterations = 10000;\n\n    for (int iter = 0; iter < max_iterations && current_violations > 0; ++iter) {\n        // Randomly select two adjacent balls to swap\n        int x1 = dis(gen) * N;\n        int y1 = dis(gen) * (x1 + 1);\n        int direction = dis(gen) * 6;\n\n        int x2, y2;\n        switch (direction) {\n            case 0: x2 = x1 - 1; y2 = y1 - 1; break;\n            case 1: x2 = x1 - 1; y2 = y1; break;\n            case 2: x2 = x1; y2 = y1 - 1; break;\n            case 3: x2 = x1; y2 = y1 + 1; break;\n            case 4: x2 = x1 + 1; y2 = y1; break;\n            case 5: x2 = x1 + 1; y2 = y1 + 1; break;\n        }\n\n        if (x2 < 0 || x2 >= N || y2 < 0 || y2 > x2) continue;\n\n        swap_balls(x1, y1, x2, y2);\n        int new_violations = count_violations();\n\n        if (new_violations < current_violations) {\n            current_violations = new_violations;\n        } else {\n            double probability = exp((current_violations - new_violations) / temperature);\n            if (dis(gen) > probability) {\n                swap_balls(x1, y1, x2, y2); // Revert the swap\n            } else {\n                current_violations = new_violations;\n            }\n        }\n\n        temperature *= cooling_rate;\n    }\n}\n\nint main() {\n    pyramid.resize(N);\n    for (int x = 0; x < N; ++x) {\n        pyramid[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> pyramid[x][y];\n        }\n    }\n\n    greedy_algorithm();\n    simulated_annealing();\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.x1 << \" \" << op.y1 << \" \" << op.x2 << \" \" << op.y2 << 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#include <utility>\n#include <cmath>\n\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = (D - 1) / 2;\n\nstruct Point {\n    int i, j;\n    Point(int i, int j) : i(i), j(j) {}\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.i) ^ hash<int>()(p.j);\n        }\n    };\n}\n\nvector<Point> get_neighbors(const Point& p, const unordered_set<Point>& obstacles) {\n    vector<Point> neighbors;\n    int di[] = {-1, 1, 0, 0};\n    int dj[] = {0, 0, -1, 1};\n    for (int k = 0; k < 4; ++k) {\n        Point neighbor(p.i + di[k], p.j + dj[k]);\n        if (neighbor.i >= 0 && neighbor.i < D && neighbor.j >= 0 && neighbor.j < D &&\n            obstacles.find(neighbor) == obstacles.end()) {\n            neighbors.push_back(neighbor);\n        }\n    }\n    return neighbors;\n}\n\nvector<vector<int>> bfs(const unordered_set<Point>& obstacles) {\n    vector<vector<int>> distance(D, vector<int>(D, -1));\n    queue<Point> q;\n    Point entrance(ENTRANCE_I, ENTRANCE_J);\n    distance[entrance.i][entrance.j] = 0;\n    q.push(entrance);\n\n    while (!q.empty()) {\n        Point current = q.front();\n        q.pop();\n        for (const Point& neighbor : get_neighbors(current, obstacles)) {\n            if (distance[neighbor.i][neighbor.j] == -1) {\n                distance[neighbor.i][neighbor.j] = distance[current.i][current.j] + 1;\n                q.push(neighbor);\n            }\n        }\n    }\n    return distance;\n}\n\nPoint find_storage_location(const unordered_set<Point>& obstacles, const vector<vector<int>>& distance, const unordered_set<Point>& occupied) {\n    vector<Point> candidates;\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            Point p(i, j);\n            if (distance[i][j] != -1 && obstacles.find(p) == obstacles.end() && occupied.find(p) == occupied.end()) {\n                candidates.push_back(p);\n            }\n        }\n    }\n    if (candidates.empty()) {\n        return Point(-1, -1); // No valid storage location\n    }\n    // Sort candidates by distance from entrance and then by some heuristic\n    sort(candidates.begin(), candidates.end(), [&distance](const Point& a, const Point& b) {\n        return distance[a.i][a.j] < distance[b.i][b.j];\n    });\n    return candidates[0];\n}\n\nvector<Point> find_retrieval_order(const unordered_set<Point>& obstacles, const vector<vector<Point>>& storage_order) {\n    vector<vector<int>> distance = bfs(obstacles);\n    unordered_set<Point> occupied;\n    for (const auto& row : storage_order) {\n        for (const Point& p : row) {\n            if (p.i != -1 && p.j != -1) {\n                occupied.insert(p);\n            }\n        }\n    }\n    vector<Point> retrieval_order;\n    while (!occupied.empty()) {\n        vector<Point> candidates;\n        for (const Point& p : occupied) {\n            if (distance[p.i][p.j] != -1) {\n                candidates.push_back(p);\n            }\n        }\n        if (candidates.empty()) {\n            break; // No more reachable containers\n        }\n        // Sort candidates by distance from entrance and then by some heuristic\n        sort(candidates.begin(), candidates.end(), [&distance](const Point& a, const Point& b) {\n            return distance[a.i][a.j] < distance[b.i][b.j];\n        });\n        Point next = candidates[0];\n        retrieval_order.push_back(next);\n        occupied.erase(next);\n        // Update distance for adjacent squares\n        for (const Point& neighbor : get_neighbors(next, obstacles)) {\n            if (occupied.find(neighbor) == occupied.end()) {\n                distance[neighbor.i][neighbor.j] = -1;\n            }\n        }\n    }\n    return retrieval_order;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    unordered_set<Point> obstacles;\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        obstacles.insert(Point(ri, rj));\n    }\n    vector<vector<int>> distance = bfs(obstacles);\n    unordered_set<Point> occupied;\n    vector<vector<Point>> storage_order(D, vector<Point>(D, Point(-1, -1)));\n    for (int d = 0; d < D * D - 1 - N; ++d) {\n        int t_d;\n        cin >> t_d;\n        Point storage_location = find_storage_location(obstacles, distance, occupied);\n        if (storage_location.i == -1 && storage_location.j == -1) {\n            cerr << \"No valid storage location found for container \" << t_d << endl;\n            return 1;\n        }\n        storage_order[storage_location.i][storage_location.j] = Point(t_d, d);\n        occupied.insert(storage_location);\n        cout << storage_location.i << \" \" << storage_location.j << endl;\n        cout.flush();\n    }\n    vector<Point> retrieval_order = find_retrieval_order(obstacles, storage_order);\n    for (const Point& p : retrieval_order) {\n        cout << p.i << \" \" << p.j << endl;\n    }\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <unordered_set>\n#include <algorithm>\n#include <atcoder/dsu>\n#include <atcoder/maxflow>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nvector<vector<int>> grid;\nvector<vector<int>> simplified_grid;\nint n, m;\n\nvoid bfs(int x, int y, int color, vector<vector<bool>>& visited) {\n    queue<Point> q;\n    q.push(Point(x, y));\n    visited[x][y] = true;\n    simplified_grid[x][y] = color;\n\n    while (!q.empty()) {\n        Point p = q.front();\n        q.pop();\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = p.x + dx[i];\n            int ny = p.y + dy[i];\n\n            if (nx >= 0 && nx < n && ny >= 0 && ny < n && !visited[nx][ny] && grid[nx][ny] == color) {\n                visited[nx][ny] = true;\n                simplified_grid[nx][ny] = color;\n                q.push(Point(nx, ny));\n            }\n        }\n    }\n}\n\nvoid simplify_map() {\n    simplified_grid = vector<vector<int>>(n, vector<int>(n, 0));\n    vector<vector<bool>> visited(n, vector<bool>(n, false));\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (!visited[i][j] && grid[i][j] != 0) {\n                bfs(i, j, grid[i][j], visited);\n            }\n        }\n    }\n}\n\nvoid connect_components() {\n    dsu d(n * n);\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] != 0) {\n                for (int k = 0; k < 4; ++k) {\n                    int ni = i + dx[k];\n                    int nj = j + dy[k];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && simplified_grid[ni][nj] != 0) {\n                        d.merge(i * n + j, ni * n + nj);\n                    }\n                }\n            }\n        }\n    }\n\n    unordered_map<int, vector<Point>> components;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] != 0) {\n                components[d.leader(i * n + j)].push_back(Point(i, j));\n            }\n        }\n    }\n\n    for (auto& [leader, points] : components) {\n        for (auto& p : points) {\n            simplified_grid[p.x][p.y] = simplified_grid[points[0].x][points[0].y];\n        }\n    }\n}\n\nvoid minimize_connectors() {\n    // This is a placeholder for a more sophisticated heuristic\n    // For simplicity, we'll just ensure that the connectors are minimal\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] == 0) {\n                bool is_connector = false;\n                for (int k = 0; k < 4; ++k) {\n                    int ni = i + dx[k];\n                    int nj = j + dy[k];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && simplified_grid[ni][nj] != 0) {\n                        is_connector = true;\n                        break;\n                    }\n                }\n                if (!is_connector) {\n                    simplified_grid[i][j] = 0;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> n >> m;\n    grid.resize(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    simplify_map();\n    connect_components();\n    minimize_connectors();\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cout << simplified_grid[i][j] << (j == n - 1 ? \"\\n\" : \" \");\n        }\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <iomanip>\n#include <climits>\n#include <cfloat>\n#include <cstring>\n#include <cassert>\n#include <chrono>\n#include <fstream>\n#include <sstream>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<pii> vpii;\ntypedef vector<pll> vpll;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef vector<vpii> vvpii;\ntypedef vector<vpll> vvpll;\ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\ntypedef tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;\n\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define lb lower_bound\n#define ub upper_bound\n\nconst int INF = 1e9;\nconst ll LINF = 1e18;\nconst ld EPS = 1e-9;\nconst int MOD = 1e9 + 7;\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint n, d, q;\nvector<double> weights;\nvector<int> groups;\n\nchar compare(const vector<int>& l, const vector<int>& r) {\n    cout << l.size() << \" \" << r.size();\n    for (int i : l) cout << \" \" << i;\n    for (int i : r) cout << \" \" << i;\n    cout << endl;\n    char res;\n    cin >> res;\n    return res;\n}\n\nvoid estimate_weights() {\n    weights.resize(n, 0.0);\n    for (int i = 0; i < n; ++i) {\n        for (int j = i + 1; j < n; ++j) {\n            char res = compare({i}, {j});\n            if (res == '<') {\n                weights[j] += 1.0;\n            } else if (res == '>') {\n                weights[i] += 1.0;\n            } else {\n                weights[i] += 0.5;\n                weights[j] += 0.5;\n            }\n        }\n    }\n}\n\nvoid assign_groups() {\n    groups.resize(n, 0);\n    vector<double> group_weights(d, 0.0);\n    for (int i = 0; i < n; ++i) {\n        int best_group = 0;\n        double min_diff = fabs(group_weights[0] - weights[i]);\n        for (int j = 1; j < d; ++j) {\n            double diff = fabs(group_weights[j] - weights[i]);\n            if (diff < min_diff) {\n                min_diff = diff;\n                best_group = j;\n            }\n        }\n        groups[i] = best_group;\n        group_weights[best_group] += weights[i];\n    }\n}\n\nvoid refine_weights() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = i + 1; j < n; ++j) {\n            if (groups[i] != groups[j]) {\n                char res = compare({i}, {j});\n                if (res == '<') {\n                    weights[j] += 1.0;\n                } else if (res == '>') {\n                    weights[i] += 1.0;\n                } else {\n                    weights[i] += 0.5;\n                    weights[j] += 0.5;\n                }\n            }\n        }\n    }\n}\n\nvoid solve() {\n    estimate_weights();\n    assign_groups();\n    refine_weights();\n    assign_groups();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> n >> d >> q;\n    solve();\n\n    for (int i = 0; i < n; ++i) {\n        cout << groups[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cassert>\n\nusing namespace std;\n\nconst int n = 200;\nconst int m = 10;\nconst int max_operations = 5000;\n\nvector<vector<int>> stacks(m, vector<int>(n / m));\n\nvoid read_input() {\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < n / m; ++j) {\n            cin >> stacks[i][j];\n        }\n    }\n}\n\nint find_stack(int v) {\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < stacks[i].size(); ++j) {\n            if (stacks[i][j] == v) {\n                return i;\n            }\n        }\n    }\n    return -1;\n}\n\nint find_position(int i, int v) {\n    for (int j = 0; j < stacks[i].size(); ++j) {\n        if (stacks[i][j] == v) {\n            return j;\n        }\n    }\n    return -1;\n}\n\nvoid move_box(int v, int dest_stack) {\n    int src_stack = find_stack(v);\n    int pos = find_position(src_stack, v);\n\n    vector<int> moved_boxes(stacks[src_stack].begin() + pos, stacks[src_stack].end());\n    stacks[src_stack].erase(stacks[src_stack].begin() + pos, stacks[src_stack].end());\n\n    stacks[dest_stack].insert(stacks[dest_stack].end(), moved_boxes.begin(), moved_boxes.end());\n}\n\nint find_smallest_remaining() {\n    int smallest = n + 1;\n    for (int i = 0; i < m; ++i) {\n        if (!stacks[i].empty()) {\n            smallest = min(smallest, stacks[i][0]);\n        }\n    }\n    return smallest;\n}\n\nbool is_smallest_at_top(int v) {\n    for (int i = 0; i < m; ++i) {\n        if (!stacks[i].empty() && stacks[i][0] == v) {\n            return true;\n        }\n    }\n    return false;\n}\n\nvector<pair<int, int>> solve() {\n    vector<pair<int, int>> operations;\n    int current_smallest = 1;\n\n    while (current_smallest <= n) {\n        if (is_smallest_at_top(current_smallest)) {\n            operations.emplace_back(current_smallest, 0);\n            current_smallest++;\n        } else {\n            int src_stack = find_stack(current_smallest);\n            int dest_stack = -1;\n            int min_size = n + 1;\n\n            for (int i = 0; i < m; ++i) {\n                if (i != src_stack && stacks[i].size() < min_size) {\n                    min_size = stacks[i].size();\n                    dest_stack = i;\n                }\n            }\n\n            if (dest_stack == -1) {\n                // No other stack available, move to any other stack\n                for (int i = 0; i < m; ++i) {\n                    if (i != src_stack) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n\n            operations.emplace_back(current_smallest, dest_stack + 1);\n            move_box(current_smallest, dest_stack);\n        }\n    }\n\n    return operations;\n}\n\nint main() {\n    read_input();\n    auto operations = solve();\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 <queue>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Square {\n    int i, j;\n    int dirtiness;\n    bool operator<(const Square& other) const {\n        return dirtiness < other.dirtiness;\n    }\n};\n\nvector<vector<int>> generateRoute(int N, const vector<vector<int>>& h, const vector<vector<int>>& v, const vector<vector<int>>& d) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    vector<vector<int>> route;\n    priority_queue<Square> pq;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            pq.push({i, j, d[i][j]});\n        }\n    }\n\n    auto isValidMove = [&](int i, int j, int di, int dj) {\n        if (di == 0) {\n            if (dj == 1) return j < N - 1 && v[i][j] == 0;\n            else return j > 0 && v[i][j - 1] == 0;\n        } else {\n            if (di == 1) return i < N - 1 && h[i][j] == 0;\n            else return i > 0 && h[i - 1][j] == 0;\n        }\n    };\n\n    auto dfs = [&](auto&& self, int i, int j) -> void {\n        visited[i][j] = true;\n        vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        vector<char> dirChars = {'R', 'D', 'L', 'U'};\n\n        // Prioritize high-dirtiness squares\n        vector<pair<int, int>> highDirtinessSquares;\n        for (const auto& dir : directions) {\n            int ni = i + dir.first;\n            int nj = j + dir.second;\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj] && isValidMove(i, j, dir.first, dir.second)) {\n                highDirtinessSquares.emplace_back(ni, nj);\n            }\n        }\n        sort(highDirtinessSquares.begin(), highDirtinessSquares.end(), [&](const auto& a, const auto& b) {\n            return d[a.first][a.second] > d[b.first][b.second];\n        });\n\n        for (const auto& sq : highDirtinessSquares) {\n            int ni = sq.first;\n            int nj = sq.second;\n            if (!visited[ni][nj]) {\n                for (size_t k = 0; k < directions.size(); ++k) {\n                    if (ni == i + directions[k].first && nj == j + directions[k].second) {\n                        route.push_back({i, j, ni, nj, dirChars[k]});\n                        break;\n                    }\n                }\n                self(self, ni, nj);\n            }\n        }\n    };\n\n    dfs(dfs, 0, 0);\n\n    // Ensure all squares are visited\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!visited[i][j]) {\n                // Find a path to the unvisited square\n                vector<vector<int>> dist(N, vector<int>(N, -1));\n                queue<pair<int, int>> q;\n                q.push({i, j});\n                dist[i][j] = 0;\n                vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n\n                while (!q.empty()) {\n                    auto [ci, cj] = q.front();\n                    q.pop();\n                    for (const auto& dir : directions) {\n                        int ni = ci + dir.first;\n                        int nj = cj + dir.second;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist[ni][nj] == -1 && isValidMove(ci, cj, dir.first, dir.second)) {\n                            dist[ni][nj] = dist[ci][cj] + 1;\n                            parent[ni][nj] = {ci, cj};\n                            q.push({ni, nj});\n                        }\n                    }\n                }\n\n                // Reconstruct path\n                vector<pair<int, int>> path;\n                for (int x = 0; x < N; ++x) {\n                    for (int y = 0; y < N; ++y) {\n                        if (visited[x][y]) {\n                            int current_i = x, current_j = y;\n                            while (current_i != -1 && current_j != -1) {\n                                path.emplace_back(current_i, current_j);\n                                auto [pi, pj] = parent[current_i][current_j];\n                                current_i = pi;\n                                current_j = pj;\n                            }\n                            reverse(path.begin(), path.end());\n                            break;\n                        }\n                    }\n                    if (!path.empty()) break;\n                }\n\n                for (size_t k = 1; k < path.size(); ++k) {\n                    auto [pi, pj] = path[k - 1];\n                    auto [ci, cj] = path[k];\n                    for (size_t l = 0; l < directions.size(); ++l) {\n                        if (ci == pi + directions[l].first && cj == pj + directions[l].second) {\n                            route.push_back({pi, pj, ci, cj, dirChars[l]});\n                            break;\n                        }\n                    }\n                }\n                dfs(dfs, i, j);\n            }\n        }\n    }\n\n    // Convert route to string\n    vector<char> result;\n    for (const auto& move : route) {\n        result.push_back(move[4]);\n    }\n\n    // Ensure the route returns to (0, 0)\n    if (route.back()[2] != 0 || route.back()[3] != 0) {\n        // Find a path back to (0, 0)\n        vector<vector<int>> dist(N, vector<int>(N, -1));\n        queue<pair<int, int>> q;\n        q.push({route.back()[2], route.back()[3]});\n        dist[route.back()[2]][route.back()[3]] = 0;\n        vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n\n        while (!q.empty()) {\n            auto [ci, cj] = q.front();\n            q.pop();\n            for (const auto& dir : directions) {\n                int ni = ci + dir.first;\n                int nj = cj + dir.second;\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist[ni][nj] == -1 && isValidMove(ci, cj, dir.first, dir.second)) {\n                    dist[ni][nj] = dist[ci][cj] + 1;\n                    parent[ni][nj] = {ci, cj};\n                    q.push({ni, nj});\n                }\n            }\n        }\n\n        // Reconstruct path\n        vector<pair<int, int>> path;\n        int current_i = 0, current_j = 0;\n        while (current_i != -1 && current_j != -1) {\n            path.emplace_back(current_i, current_j);\n            auto [pi, pj] = parent[current_i][current_j];\n            current_i = pi;\n            current_j = pj;\n        }\n        reverse(path.begin(), path.end());\n\n        for (size_t k = 1; k < path.size(); ++k) {\n            auto [pi, pj] = path[k - 1];\n            auto [ci, cj] = path[k];\n            for (size_t l = 0; l < directions.size(); ++l) {\n                if (ci == pi + directions[l].first && cj == pj + directions[l].second) {\n                    result.push_back(dirChars[l]);\n                    break;\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int N;\n    cin >> N;\n\n    vector<vector<int>> h(N - 1, vector<int>(N));\n    for (int i = 0; i < N - 1; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            h[i][j] = row[j] - '0';\n        }\n    }\n\n    vector<vector<int>> v(N, vector<int>(N - 1));\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N - 1; ++j) {\n            v[i][j] = row[j] - '0';\n        }\n    }\n\n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    vector<char> route = generateRoute(N, h, v, d);\n\n    for (char move : route) {\n        cout << move;\n    }\n    cout << endl;\n\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nstruct State {\n    int i, j;\n    unordered_set<int> included;\n    int cost;\n\n    bool operator>(const State& other) const {\n        return cost > other.cost;\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int s_i, s_j;\n    cin >> s_i >> s_j;\n\n    vector<vector<char>> keyboard(N, vector<char>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> keyboard[i][j];\n        }\n    }\n\n    vector<string> t(M);\n    for (int k = 0; k < M; ++k) {\n        cin >> t[k];\n    }\n\n    // Preprocess the positions of each character\n    unordered_map<char, vector<pair<int, int>>> char_positions;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char_positions[keyboard[i][j]].emplace_back(i, j);\n        }\n    }\n\n    // Priority queue for Dijkstra's algorithm\n    priority_queue<State, vector<State>, greater<State>> pq;\n    pq.push({s_i, s_j, {}, 0});\n\n    // Visited set to avoid revisiting the same state\n    unordered_map<int, unordered_map<int, unordered_set<int>>> visited;\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.included.size() == M) {\n            // Found a solution, output the path\n            // (In a real implementation, you would need to reconstruct the path)\n            // For simplicity, we assume the path is stored and output here\n            cout << \"Solution found with cost \" << current.cost << endl;\n            return 0;\n        }\n\n        if (visited[current.i][current.j].count(current.included.size())) {\n            continue;\n        }\n        visited[current.i][current.j].insert(current.included.size());\n\n        // Explore all possible next characters\n        for (const auto& entry : char_positions) {\n            char c = entry.first;\n            for (const auto& pos : entry.second) {\n                int next_i = pos.first;\n                int next_j = pos.second;\n\n                // Calculate the cost to move to this character\n                int move_cost = abs(next_i - current.i) + abs(next_j - current.j) + 1;\n\n                // Check if adding this character includes any new lucky words\n                unordered_set<int> new_included = current.included;\n                for (int k = 0; k < M; ++k) {\n                    if (new_included.count(k)) continue;\n                    // Check if the new character includes the k-th lucky word\n                    // This is a simplified check; in practice, you would need a more efficient way\n                    // For example, using a suffix automaton or a rolling hash\n                    string s;\n                    // Reconstruct the string from the current state (simplified)\n                    // In a real implementation, you would need to keep track of the string\n                    if (s.find(t[k]) != string::npos) {\n                        new_included.insert(k);\n                    }\n                }\n\n                if (new_included.size() > current.included.size()) {\n                    pq.push({next_i, next_j, new_included, current.cost + move_cost});\n                }\n            }\n        }\n    }\n\n    cout << \"No solution found within the operation limit.\" << endl;\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <set>\n#include <random>\n#include <cmath>\n#include <algorithm>\n#include <atcoder/random>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Square {\n    int i, j;\n    Square(int i, int j) : i(i), j(j) {}\n    bool operator<(const Square& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nstruct OilField {\n    vector<Square> squares;\n    int di, dj;\n};\n\nvector<OilField> fields;\nint N, M;\ndouble epsilon;\n\nvoid read_input() {\n    cin >> N >> M >> epsilon;\n    fields.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        fields[k].squares.resize(d);\n        for (int l = 0; l < d; ++l) {\n            cin >> fields[k].squares[l].i >> fields[k].squares[l].j;\n        }\n    }\n}\n\nvoid drill(int i, int j) {\n    cout << \"q 1 \" << i << \" \" << j << endl;\n    cout.flush();\n    int v;\n    cin >> v;\n    // Update the oil reserves for the square (i, j)\n}\n\nint divinate(const vector<Square>& squares) {\n    cout << \"q \" << squares.size();\n    for (const auto& sq : squares) {\n        cout << \" \" << sq.i << \" \" << sq.j;\n    }\n    cout << endl;\n    cout.flush();\n    int v;\n    cin >> v;\n    return v;\n}\n\nvoid guess(const set<Square>& squares) {\n    cout << \"a \" << squares.size();\n    for (const auto& sq : squares) {\n        cout << \" \" << sq.i << \" \" << sq.j;\n    }\n    cout << endl;\n    cout.flush();\n    int correct;\n    cin >> correct;\n    if (correct) {\n        exit(0);\n    }\n}\n\nint main() {\n    read_input();\n\n    // Initial random drilling\n    set<Square> drilled;\n    mt19937 rng(random_device{}());\n    uniform_int_distribution<int> dist(0, N - 1);\n    for (int k = 0; k < 10; ++k) {\n        int i = dist(rng);\n        int j = dist(rng);\n        drill(i, j);\n        drilled.insert(Square(i, j));\n    }\n\n    // Divination to estimate total oil reserves\n    vector<Square> all_squares;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            all_squares.emplace_back(i, j);\n        }\n    }\n    int total_estimate = divinate(all_squares);\n\n    // Heuristic guided drilling\n    set<Square> candidates;\n    for (const auto& field : fields) {\n        for (const auto& sq : field.squares) {\n            candidates.insert(sq);\n        }\n    }\n\n    while (true) {\n        // Prioritize squares that are part of the polyominoes with the highest estimated oil reserves\n        vector<Square> to_divinate;\n        for (const auto& sq : candidates) {\n            if (drilled.find(sq) == drilled.end()) {\n                to_divinate.push_back(sq);\n            }\n        }\n\n        if (to_divinate.empty()) break;\n\n        // Divinate a subset of candidates\n        int k = min(10, (int)to_divinate.size());\n        vector<Square> subset(to_divinate.begin(), to_divinate.begin() + k);\n        int estimate = divinate(subset);\n\n        // Update the set of candidates based on the estimate\n        for (const auto& sq : subset) {\n            if (estimate > 0) {\n                candidates.insert(sq);\n            } else {\n                candidates.erase(sq);\n            }\n        }\n\n        // Drill a square from the candidates\n        if (!candidates.empty()) {\n            auto it = candidates.begin();\n            advance(it, dist(rng) % candidates.size());\n            Square sq = *it;\n            drill(sq.i, sq.j);\n            drilled.insert(sq);\n        }\n\n        // Guess the set of squares with oil reserves\n        if (drilled.size() >= 10) {\n            guess(drilled);\n        }\n    }\n\n    return 0;\n}","ahc031":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <climits>\n\nusing namespace std;\n\nstruct Rectangle {\n    int i0, j0, i1, j1;\n    Rectangle(int i0, int j0, int i1, int j1) : i0(i0), j0(j0), i1(i1), j1(j1) {}\n    int area() const { return (i1 - i0) * (j1 - j0); }\n};\n\nstruct Solution {\n    vector<vector<Rectangle>> rectangles;\n    int total_cost;\n};\n\nint calculate_area_cost(const vector<vector<int>>& a, const Solution& sol) {\n    int cost = 0;\n    for (int d = 0; d < sol.rectangles.size(); ++d) {\n        for (int k = 0; k < sol.rectangles[d].size(); ++k) {\n            int b = sol.rectangles[d][k].area();\n            if (a[d][k] > b) {\n                cost += 100 * (a[d][k] - b);\n            }\n        }\n    }\n    return cost;\n}\n\nint calculate_partition_cost(const Solution& prev_sol, const Solution& curr_sol) {\n    int cost = 0;\n    for (int d = 0; d < curr_sol.rectangles.size(); ++d) {\n        if (d == 0) continue; // No partition cost on the first day\n        for (int i = 1; i < 1000; ++i) {\n            for (int j = 0; j < 999; ++j) {\n                bool prev_has_horizontal = false;\n                bool curr_has_horizontal = false;\n                for (const auto& rect : prev_sol.rectangles[d-1]) {\n                    if ((rect.i0 == i && rect.j0 <= j && rect.j1 > j) ||\n                        (rect.i1 == i && rect.j0 <= j && rect.j1 > j)) {\n                        prev_has_horizontal = true;\n                        break;\n                    }\n                }\n                for (const auto& rect : curr_sol.rectangles[d]) {\n                    if ((rect.i0 == i && rect.j0 <= j && rect.j1 > j) ||\n                        (rect.i1 == i && rect.j0 <= j && rect.j1 > j)) {\n                        curr_has_horizontal = true;\n                        break;\n                    }\n                }\n                if (prev_has_horizontal != curr_has_horizontal) {\n                    cost++;\n                }\n            }\n        }\n        for (int i = 0; i < 999; ++i) {\n            for (int j = 1; j < 1000; ++j) {\n                bool prev_has_vertical = false;\n                bool curr_has_vertical = false;\n                for (const auto& rect : prev_sol.rectangles[d-1]) {\n                    if ((rect.j0 == j && rect.i0 <= i && rect.i1 > i) ||\n                        (rect.j1 == j && rect.i0 <= i && rect.i1 > i)) {\n                        prev_has_vertical = true;\n                        break;\n                    }\n                }\n                for (const auto& rect : curr_sol.rectangles[d]) {\n                    if ((rect.j0 == j && rect.i0 <= i && rect.i1 > i) ||\n                        (rect.j1 == j && rect.i0 <= i && rect.i1 > i)) {\n                        curr_has_vertical = true;\n                        break;\n                    }\n                }\n                if (prev_has_vertical != curr_has_vertical) {\n                    cost++;\n                }\n            }\n        }\n    }\n    return cost;\n}\n\nSolution greedy_solution(const vector<vector<int>>& a) {\n    Solution sol;\n    sol.rectangles.resize(a.size());\n    for (int d = 0; d < a.size(); ++d) {\n        vector<int> remaining_area = a[d];\n        sort(remaining_area.rbegin(), remaining_area.rend());\n        vector<pair<int, int>> positions;\n        for (int i = 0; i < 1000; ++i) {\n            for (int j = 0; j < 1000; ++j) {\n                positions.emplace_back(i, j);\n            }\n        }\n        random_device rd;\n        mt19937 g(rd());\n        shuffle(positions.begin(), positions.end(), g);\n        for (int k = 0; k < a[d].size(); ++k) {\n            int best_area = 0;\n            Rectangle best_rect(0, 0, 0, 0);\n            for (const auto& pos : positions) {\n                int i0 = pos.first;\n                int j0 = pos.second;\n                for (int i1 = i0 + 1; i1 <= 1000; ++i1) {\n                    for (int j1 = j0 + 1; j1 <= 1000; ++j1) {\n                        int area = (i1 - i0) * (j1 - j0);\n                        if (area > remaining_area[k]) continue;\n                        if (area > best_area) {\n                            best_area = area;\n                            best_rect = Rectangle(i0, j0, i1, j1);\n                        }\n                    }\n                }\n            }\n            sol.rectangles[d].push_back(best_rect);\n            remaining_area[k] -= best_area;\n        }\n    }\n    sol.total_cost = calculate_area_cost(a, sol) + calculate_partition_cost(sol, sol);\n    return sol;\n}\n\nSolution simulated_annealing(const vector<vector<int>>& a, const Solution& initial_sol, double initial_temp, double cooling_rate, int iterations) {\n    Solution current_sol = initial_sol;\n    Solution best_sol = initial_sol;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    double temp = initial_temp;\n    for (int iter = 0; iter < iterations; ++iter) {\n        Solution new_sol = current_sol;\n        int d = rand() % a.size();\n        int k = rand() % a[d].size();\n        int i0 = rand() % 1000;\n        int j0 = rand() % 1000;\n        int i1 = i0 + 1 + rand() % (1000 - i0);\n        int j1 = j0 + 1 + rand() % (1000 - j0);\n        new_sol.rectangles[d][k] = Rectangle(i0, j0, i1, j1);\n        int new_area_cost = calculate_area_cost(a, new_sol);\n        int new_partition_cost = calculate_partition_cost(current_sol, new_sol);\n        int new_total_cost = new_area_cost + new_partition_cost;\n        if (new_total_cost < current_sol.total_cost || dis(gen) < exp((current_sol.total_cost - new_total_cost) / temp)) {\n            current_sol = new_sol;\n            current_sol.total_cost = new_total_cost;\n            if (new_total_cost < best_sol.total_cost) {\n                best_sol = new_sol;\n                best_sol.total_cost = new_total_cost;\n            }\n        }\n        temp *= cooling_rate;\n    }\n    return best_sol;\n}\n\nint main() {\n    int W, D, N;\n    cin >> W >> D >> N;\n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cin >> a[d][k];\n        }\n    }\n    Solution initial_sol = greedy_solution(a);\n    Solution best_sol = simulated_annealing(a, initial_sol, 1000.0, 0.999, 10000);\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << best_sol.rectangles[d][k].i0 << \" \" << best_sol.rectangles[d][k].j0 << \" \"\n                 << best_sol.rectangles[d][k].i1 << \" \" << best_sol.rectangles[d][k].j1 << endl;\n        }\n    }\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\n\nstruct Stamp {\n    int s[3][3];\n};\n\nstruct Operation {\n    int m, p, q;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int a[N][N];\n    Stamp stamps[M];\n\n    // Read initial grid\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> a[i][j];\n        }\n    }\n\n    // Read stamps\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].s[i][j];\n            }\n        }\n    }\n\n    vector<Operation> operations;\n    int current_sum = 0;\n\n    // Calculate initial sum\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            current_sum = (current_sum + a[i][j] % MOD) % MOD;\n        }\n    }\n\n    // Greedy approach\n    for (int op = 0; op < K; ++op) {\n        int best_m = -1, best_p = -1, best_q = -1;\n        int max_increase = 0;\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    int increase = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            int new_val = (a[p + i][q + j] + stamps[m].s[i][j]) % MOD;\n                            increase += (new_val - (a[p + i][q + j] % MOD)) % MOD;\n                        }\n                    }\n                    if (increase > max_increase) {\n                        max_increase = increase;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_m == -1) break; // No more beneficial operations\n\n        operations.push_back({best_m, best_p, best_q});\n\n        // Apply the best operation\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                a[best_p + i][best_q + j] = (a[best_p + i][best_q + j] + stamps[best_m].s[i][j]) % MOD;\n            }\n        }\n\n        current_sum = (current_sum + max_increase) % MOD;\n    }\n\n    // Output the operations\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.m << \" \" << op.p << \" \" << op.q << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_map>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURNS = 10000;\n\nstruct Crane {\n    int x, y;\n    bool is_large;\n    bool holding;\n    int container;\n};\n\nstruct Container {\n    int x, y;\n    int number;\n};\n\nvector<vector<int>> A(N, vector<int>(N));\nvector<Crane> cranes;\nvector<vector<int>> grid(N, vector<int>(N, -1));\nvector<vector<int>> next_container(N, vector<int>(N, 0));\nvector<string> actions(N, string(MAX_TURNS, '.'));\n\nint calculate_score() {\n    // Implement scoring logic here\n    return 0;\n}\n\nvoid simulate_turn() {\n    // Step 1: Bring in new containers\n    for (int i = 0; i < N; ++i) {\n        if (next_container[i][0] < N && grid[i][0] == -1) {\n            grid[i][0] = A[i][next_container[i][0]];\n            next_container[i][0]++;\n        }\n    }\n\n    // Step 2: Perform crane actions\n    vector<vector<int>> new_grid(N, vector<int>(N, -1));\n    vector<Crane> new_cranes;\n    for (int i = 0; i < N; ++i) {\n        Crane c = cranes[i];\n        char action = actions[i][0];\n        actions[i].erase(0, 1);\n\n        if (action == 'B' && !c.holding) {\n            continue; // Crane is bombed\n        }\n\n        switch (action) {\n            case 'P':\n                if (!c.holding && grid[c.x][c.y] != -1) {\n                    c.holding = true;\n                    c.container = grid[c.x][c.y];\n                    grid[c.x][c.y] = -1;\n                }\n                break;\n            case 'Q':\n                if (c.holding && grid[c.x][c.y] == -1) {\n                    grid[c.x][c.y] = c.container;\n                    c.holding = false;\n                }\n                break;\n            case 'U':\n                if (c.x > 0 && (grid[c.x - 1][c.y] == -1 || c.is_large)) {\n                    c.x--;\n                }\n                break;\n            case 'D':\n                if (c.x < N - 1 && (grid[c.x + 1][c.y] == -1 || c.is_large)) {\n                    c.x++;\n                }\n                break;\n            case 'L':\n                if (c.y > 0 && (grid[c.x][c.y - 1] == -1 || c.is_large)) {\n                    c.y--;\n                }\n                break;\n            case 'R':\n                if (c.y < N - 1 && (grid[c.x][c.y + 1] == -1 || c.is_large)) {\n                    c.y++;\n                }\n                break;\n            case '.':\n                break;\n        }\n\n        if (action != 'B') {\n            new_cranes.push_back(c);\n        }\n    }\n    cranes = new_cranes;\n\n    // Step 3: Dispatch containers\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][N - 1] != -1) {\n            grid[i][N - 1] = -1;\n        }\n    }\n}\n\nvoid heuristic_solution() {\n    // Initialize cranes\n    for (int i = 0; i < N; ++i) {\n        cranes.push_back({i, 0, i == 0, false, -1});\n    }\n\n    // Simulate turns\n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        simulate_turn();\n\n        // Simple heuristic: Move cranes towards the right edge\n        for (int i = 0; i < N; ++i) {\n            Crane &c = cranes[i];\n            if (c.y < N - 1) {\n                actions[i][turn] = 'R';\n            } else if (c.y == N - 1 && c.holding) {\n                actions[i][turn] = 'Q';\n            } else if (c.y == N - 1 && !c.holding && grid[c.x][c.y] != -1) {\n                actions[i][turn] = 'P';\n            } else if (c.y == N - 1 && !c.holding && grid[c.x][c.y] == -1) {\n                actions[i][turn] = '.';\n            }\n        }\n    }\n}\n\nint main() {\n    // Read input\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n        }\n    }\n\n    // Run heuristic solution\n    heuristic_solution();\n\n    // Output actions\n    for (int i = 0; i < N; ++i) {\n        cout << actions[i] << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <climits>\n#include <unordered_map>\n#include <tuple>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_OPERATIONS = 100000;\nconst int MAX_SOIL = 1000000;\n\nstruct State {\n    int x, y;\n    int soil;\n    int cost;\n    vector<string> operations;\n\n    bool operator>(const State& other) const {\n        return cost > other.cost;\n    }\n};\n\nint heuristic(int x1, int y1, int x2, int y2, int soil) {\n    return abs(x1 - x2) + abs(y1 - y2) + soil;\n}\n\nvector<string> findPath(int startX, int startY, int endX, int endY, int soil) {\n    priority_queue<State, vector<State>, greater<State>> pq;\n    unordered_map<int, unordered_map<int, int>> visited;\n\n    pq.push({startX, startY, soil, 0, {}});\n    visited[startX][startY] = 0;\n\n    vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n    vector<string> dirChars = {\"U\", \"D\", \"L\", \"R\"};\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.x == endX && current.y == endY) {\n            return current.operations;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int newX = current.x + directions[i].first;\n            int newY = current.y + directions[i].second;\n\n            if (newX >= 0 && newX < N && newY >= 0 && newY < N) {\n                int newCost = current.cost + 100 + current.soil;\n                if (visited[newX][newY] == 0 || newCost < visited[newX][newY]) {\n                    visited[newX][newY] = newCost;\n                    vector<string> newOperations = current.operations;\n                    newOperations.push_back(dirChars[i]);\n                    pq.push({newX, newY, current.soil, newCost, newOperations});\n                }\n            }\n        }\n    }\n\n    return {};\n}\n\nvector<string> solve(vector<vector<int>>& grid) {\n    vector<string> operations;\n    int totalOperations = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == 0) continue;\n\n            int currentX = 0, currentY = 0;\n            int soil = 0;\n\n            // Move to the target square\n            vector<string> path = findPath(currentX, currentY, i, j, soil);\n            operations.insert(operations.end(), path.begin(), path.end());\n            currentX = i;\n            currentY = j;\n\n            // Load or unload soil\n            if (grid[i][j] > 0) {\n                int d = min(grid[i][j], MAX_SOIL);\n                operations.push_back(\"+\" + to_string(d));\n                soil += d;\n                grid[i][j] -= d;\n            } else {\n                int d = min(-grid[i][j], soil);\n                operations.push_back(\"-\" + to_string(d));\n                soil -= d;\n                grid[i][j] += d;\n            }\n\n            // Move back to the origin if there's soil to carry\n            if (soil > 0) {\n                path = findPath(currentX, currentY, 0, 0, soil);\n                operations.insert(operations.end(), path.begin(), path.end());\n                currentX = 0;\n                currentY = 0;\n            }\n\n            if (operations.size() >= MAX_OPERATIONS) break;\n        }\n        if (operations.size() >= MAX_OPERATIONS) break;\n    }\n\n    return operations;\n}\n\nint main() {\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<string> operations = solve(grid);\n    for (const string& op : operations) {\n        cout << op << endl;\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 6;\nconst int M = 15;\nconst int T = 10;\nconst int SEED_COUNT = 2 * N * (N - 1);\nconst int POPULATION_SIZE = 50;\nconst int GENERATIONS = 10;\nconst double MUTATION_RATE = 0.1;\n\nvector<vector<int>> X(SEED_COUNT, vector<int>(M, 0));\nvector<int> X_max(M, 0);\n\nstruct Individual {\n    vector<vector<int>> grid;\n    int fitness;\n\n    Individual() : grid(N, vector<int>(N, 0)), fitness(0) {}\n};\n\nvector<Individual> population(POPULATION_SIZE);\n\nvoid initializePopulation() {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, SEED_COUNT - 1);\n\n    for (auto& individual : population) {\n        vector<int> seeds(SEED_COUNT);\n        iota(seeds.begin(), seeds.end(), 0);\n        shuffle(seeds.begin(), seeds.end(), gen);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                individual.grid[i][j] = seeds[i * N + j];\n            }\n        }\n    }\n}\n\nvector<vector<int>> generateNewSeeds(const vector<vector<int>>& grid) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, 1);\n\n    vector<vector<int>> newSeeds(SEED_COUNT, vector<int>(M, 0));\n\n    int index = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N - 1; ++j) {\n            int seed1 = grid[i][j];\n            int seed2 = grid[i][j + 1];\n            for (int l = 0; l < M; ++l) {\n                newSeeds[index][l] = dist(gen) ? X[seed1][l] : X[seed2][l];\n            }\n            ++index;\n        }\n    }\n\n    for (int i = 0; i < N - 1; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int seed1 = grid[i][j];\n            int seed2 = grid[i + 1][j];\n            for (int l = 0; l < M; ++l) {\n                newSeeds[index][l] = dist(gen) ? X[seed1][l] : X[seed2][l];\n            }\n            ++index;\n        }\n    }\n\n    return newSeeds;\n}\n\nint calculateFitness(const vector<vector<int>>& grid) {\n    vector<vector<int>> currentSeeds = X;\n    for (int t = 0; t < T; ++t) {\n        currentSeeds = generateNewSeeds(grid);\n    }\n\n    int maxValue = 0;\n    for (const auto& seed : currentSeeds) {\n        int value = accumulate(seed.begin(), seed.end(), 0);\n        if (value > maxValue) {\n            maxValue = value;\n        }\n    }\n\n    int sumXMax = accumulate(X_max.begin(), X_max.end(), 0);\n    return round(1e6 * maxValue / sumXMax);\n}\n\nvoid evaluatePopulation() {\n    for (auto& individual : population) {\n        individual.fitness = calculateFitness(individual.grid);\n    }\n}\n\nvector<Individual> selectParents() {\n    vector<Individual> parents;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, POPULATION_SIZE - 1);\n\n    for (int i = 0; i < POPULATION_SIZE; ++i) {\n        int idx1 = dist(gen);\n        int idx2 = dist(gen);\n        parents.push_back(population[idx1].fitness > population[idx2].fitness ? population[idx1] : population[idx2]);\n    }\n\n    return parents;\n}\n\nvector<Individual> crossover(const vector<Individual>& parents) {\n    vector<Individual> offspring;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, N * N - 1);\n\n    for (int i = 0; i < POPULATION_SIZE; i += 2) {\n        Individual child1, child2;\n        int crossoverPoint = dist(gen);\n\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < N; ++k) {\n                if (j * N + k < crossoverPoint) {\n                    child1.grid[j][k] = parents[i].grid[j][k];\n                    child2.grid[j][k] = parents[i + 1].grid[j][k];\n                } else {\n                    child1.grid[j][k] = parents[i + 1].grid[j][k];\n                    child2.grid[j][k] = parents[i].grid[j][k];\n                }\n            }\n        }\n\n        offspring.push_back(child1);\n        offspring.push_back(child2);\n    }\n\n    return offspring;\n}\n\nvoid mutate(vector<Individual>& offspring) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<double> dist(0.0, 1.0);\n    uniform_int_distribution<int> seedDist(0, SEED_COUNT - 1);\n\n    for (auto& individual : offspring) {\n        if (dist(gen) < MUTATION_RATE) {\n            int i1 = seedDist(gen) / N;\n            int j1 = seedDist(gen) % N;\n            int i2 = seedDist(gen) / N;\n            int j2 = seedDist(gen) % N;\n            swap(individual.grid[i1][j1], individual.grid[i2][j2]);\n        }\n    }\n}\n\nvoid geneticAlgorithm() {\n    initializePopulation();\n    evaluatePopulation();\n\n    for (int gen = 0; gen < GENERATIONS; ++gen) {\n        vector<Individual> parents = selectParents();\n        vector<Individual> offspring = crossover(parents);\n        mutate(offspring);\n\n        for (auto& individual : offspring) {\n            individual.fitness = calculateFitness(individual.grid);\n        }\n\n        population.insert(population.end(), offspring.begin(), offspring.end());\n        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n            return a.fitness > b.fitness;\n        });\n        population.resize(POPULATION_SIZE);\n    }\n}\n\nint main() {\n    // Read input\n    for (int i = 0; i < SEED_COUNT; ++i) {\n        for (int j = 0; j < M; ++j) {\n            cin >> X[i][j];\n            if (X[i][j] > X_max[j]) {\n                X_max[j] = X[i][j];\n            }\n        }\n    }\n\n    // Run genetic algorithm\n    geneticAlgorithm();\n\n    // Output the best solution\n    Individual best = *max_element(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n        return a.fitness < b.fitness;\n    });\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << best.grid[i][j];\n            if (j < N - 1) {\n                cout << \" \";\n            } else {\n                cout << endl;\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct TreeNode {\n    int id;\n    int parent;\n    int length;\n    vector<int> children;\n    Point position;\n    Point direction;\n    bool isFingertip;\n    bool holding;\n\n    TreeNode(int id, int parent, int length, const Point& position, const Point& direction, bool isFingertip)\n        : id(id), parent(parent), length(length), position(position), direction(direction), isFingertip(isFingertip), holding(false) {}\n};\n\nclass RoboticArm {\nprivate:\n    int N, M, V;\n    vector<vector<int>> grid;\n    vector<vector<int>> target;\n    vector<TreeNode> tree;\n    Point rootPosition;\n    vector<string> operations;\n    unordered_map<Point, bool> occupied;\n\n    void designTree() {\n        // Design a star-shaped tree\n        tree.emplace_back(0, -1, 0, rootPosition, Point(1, 0), false);\n        for (int i = 1; i < V; ++i) {\n            int parent = 0;\n            int length = 1;\n            Point direction = Point(1, 0);\n            tree.emplace_back(i, parent, length, rootPosition, direction, true);\n            tree[parent].children.push_back(i);\n        }\n    }\n\n    void moveRoot(int dx, int dy) {\n        rootPosition.x += dx;\n        rootPosition.y += dy;\n        for (auto& node : tree) {\n            node.position.x += dx;\n            node.position.y += dy;\n        }\n    }\n\n    void rotateSubtree(int nodeId, int rotation) {\n        if (rotation == 0) return;\n        TreeNode& node = tree[nodeId];\n        int newDirX = node.direction.x;\n        int newDirY = node.direction.y;\n        if (rotation == 1) { // Counterclockwise\n            newDirX = -node.direction.y;\n            newDirY = node.direction.x;\n        } else if (rotation == 2) { // Clockwise\n            newDirX = node.direction.y;\n            newDirY = -node.direction.x;\n        }\n        node.direction.x = newDirX;\n        node.direction.y = newDirY;\n        for (int childId : node.children) {\n            rotateSubtree(childId, rotation);\n        }\n    }\n\n    void grabOrRelease(int nodeId) {\n        TreeNode& node = tree[nodeId];\n        if (!node.isFingertip) return;\n        Point fingertipPos = node.position;\n        fingertipPos.x += node.direction.x * node.length;\n        fingertipPos.y += node.direction.y * node.length;\n        if (fingertipPos.x < 0 || fingertipPos.x >= N || fingertipPos.y < 0 || fingertipPos.y >= N) return;\n        if (grid[fingertipPos.x][fingertipPos.y] == 1 && target[fingertipPos.x][fingertipPos.y] == 0 && !node.holding) {\n            grid[fingertipPos.x][fingertipPos.y] = 0;\n            node.holding = true;\n        } else if (grid[fingertipPos.x][fingertipPos.y] == 0 && target[fingertipPos.x][fingertipPos.y] == 1 && node.holding) {\n            grid[fingertipPos.x][fingertipPos.y] = 1;\n            node.holding = false;\n        }\n    }\n\n    void performOperation(const string& op) {\n        operations.push_back(op);\n        char move = op[0];\n        if (move == 'U') moveRoot(-1, 0);\n        else if (move == 'D') moveRoot(1, 0);\n        else if (move == 'L') moveRoot(0, -1);\n        else if (move == 'R') moveRoot(0, 1);\n        for (int i = 1; i < V; ++i) {\n            char rot = op[i];\n            if (rot == 'L') rotateSubtree(i, 1);\n            else if (rot == 'R') rotateSubtree(i, 2);\n        }\n        for (int i = 0; i < V; ++i) {\n            char action = op[V + i];\n            if (action == 'P') grabOrRelease(i);\n        }\n    }\n\n    void moveTakoyaki(const Point& start, const Point& end) {\n        // Simplified path planning: move directly to the target\n        int dx = end.x - start.x;\n        int dy = end.y - start.y;\n        string op(V * 2, '.');\n        if (dx > 0) op[0] = 'D';\n        else if (dx < 0) op[0] = 'U';\n        else if (dy > 0) op[0] = 'R';\n        else if (dy < 0) op[0] = 'L';\n        performOperation(op);\n        op = string(V * 2, '.');\n        op[V + 1] = 'P'; // Grab or release\n        performOperation(op);\n        if (dx > 0) op[0] = 'U';\n        else if (dx < 0) op[0] = 'D';\n        else if (dy > 0) op[0] = 'L';\n        else if (dy < 0) op[0] = 'R';\n        performOperation(op);\n        op[V + 1] = 'P'; // Grab or release\n        performOperation(op);\n    }\n\npublic:\n    RoboticArm(int N, int M, int V, const vector<vector<int>>& grid, const vector<vector<int>>& target)\n        : N(N), M(M), V(V), grid(grid), target(target), rootPosition(0, 0) {\n        designTree();\n    }\n\n    void solve() {\n        vector<Point> takoyakiPositions;\n        vector<Point> targetPositions;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == 1) {\n                    takoyakiPositions.emplace_back(i, j);\n                }\n                if (target[i][j] == 1) {\n                    targetPositions.emplace_back(i, j);\n                }\n            }\n        }\n        for (size_t i = 0; i < takoyakiPositions.size(); ++i) {\n            moveTakoyaki(takoyakiPositions[i], targetPositions[i]);\n        }\n    }\n\n    void printSolution() {\n        cout << tree.size() << endl;\n        for (size_t i = 1; i < tree.size(); ++i) {\n            cout << tree[i].parent << \" \" << tree[i].length << endl;\n        }\n        cout << rootPosition.x << \" \" << rootPosition.y << endl;\n        for (const string& op : operations) {\n            cout << op << endl;\n        }\n    }\n};\n\nint main() {\n    int N, M, V;\n    cin >> N >> M >> V;\n    vector<vector<int>> grid(N, vector<int>(N));\n    vector<vector<int>> target(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = row[j] - '0';\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            target[i][j] = row[j] - '0';\n        }\n    }\n    RoboticArm arm(N, M, V, grid, target);\n    arm.solve();\n    arm.printSolution();\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Polygon {\n    vector<Point> vertices;\n    int mackerels, sardines;\n    Polygon() : mackerels(0), sardines(0) {}\n};\n\nint cross(const Point &O, const Point &A, const Point &B) {\n    return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);\n}\n\nvector<Point> convex_hull(vector<Point> points) {\n    int n = points.size(), k = 0;\n    vector<Point> hull(2 * n);\n    sort(points.begin(), points.end(), [](const Point &a, const Point &b) {\n        return a.x < b.x || (a.x == b.x && a.y < b.y);\n    });\n    for (int i = 0; i < n; ++i) {\n        while (k >= 2 && cross(hull[k-2], hull[k-1], points[i]) <= 0) k--;\n        hull[k++] = points[i];\n    }\n    for (int i = n-2, t = k+1; i >= 0; --i) {\n        while (k >= t && cross(hull[k-2], hull[k-1], points[i]) <= 0) k--;\n        hull[k++] = points[i];\n    }\n    hull.resize(k-1);\n    return hull;\n}\n\nbool is_point_in_polygon(const Point &p, const Polygon &poly) {\n    int n = poly.vertices.size();\n    if (n < 3) return false;\n    bool inside = false;\n    for (int i = 0, j = n - 1; i < n; j = i++) {\n        if (((poly.vertices[i].y > p.y) != (poly.vertices[j].y > p.y)) &&\n            (p.x < (poly.vertices[j].x - poly.vertices[i].x) * (p.y - poly.vertices[i].y) / (poly.vertices[j].y - poly.vertices[i].y) + poly.vertices[i].x))\n            inside = !inside;\n    }\n    return inside;\n}\n\nint count_points_in_polygon(const vector<Point> &points, const Polygon &poly) {\n    int count = 0;\n    for (const auto &p : points) {\n        if (is_point_in_polygon(p, poly)) {\n            count++;\n        }\n    }\n    return count;\n}\n\nPolygon generate_random_polygon(const vector<Point> &hull, int max_vertices, int max_edge_length) {\n    Polygon poly;\n    int n = hull.size();\n    if (n < 4) return poly;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, n - 1);\n\n    int start = dis(gen);\n    poly.vertices.push_back(hull[start]);\n\n    int current = start;\n    int total_length = 0;\n    while (poly.vertices.size() < max_vertices) {\n        int next = (current + 1) % n;\n        int dx = hull[next].x - hull[current].x;\n        int dy = hull[next].y - hull[current].y;\n        int edge_length = abs(dx) + abs(dy);\n\n        if (total_length + edge_length > max_edge_length) {\n            break;\n        }\n\n        if (dx != 0 && dy != 0) {\n            // Ensure edges are parallel to x-axis or y-axis\n            if (abs(dx) > abs(dy)) {\n                poly.vertices.emplace_back(hull[current].x + dx, hull[current].y);\n            } else {\n                poly.vertices.emplace_back(hull[current].x, hull[current].y + dy);\n            }\n        } else {\n            poly.vertices.push_back(hull[next]);\n        }\n\n        total_length += edge_length;\n        current = next;\n    }\n\n    // Close the polygon\n    if (poly.vertices.size() >= 3) {\n        int dx = poly.vertices.back().x - poly.vertices[0].x;\n        int dy = poly.vertices.back().y - poly.vertices[0].y;\n        if (dx != 0 && dy != 0) {\n            if (abs(dx) > abs(dy)) {\n                poly.vertices.emplace_back(poly.vertices.back().x, poly.vertices[0].y);\n            } else {\n                poly.vertices.emplace_back(poly.vertices[0].x, poly.vertices.back().y);\n            }\n        }\n    }\n\n    return poly;\n}\n\nint evaluate_polygon(const Polygon &poly, const vector<Point> &mackerels, const vector<Point> &sardines) {\n    int m = count_points_in_polygon(mackerels, poly);\n    int s = count_points_in_polygon(sardines, poly);\n    return max(0, m - s + 1);\n}\n\nPolygon simulated_annealing(const vector<Point> &hull, const vector<Point> &mackerels, const vector<Point> &sardines, int max_vertices, int max_edge_length, int iterations) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    Polygon current = generate_random_polygon(hull, max_vertices, max_edge_length);\n    current.mackerels = count_points_in_polygon(mackerels, current);\n    current.sardines = count_points_in_polygon(sardines, current);\n    int current_score = evaluate_polygon(current, mackerels, sardines);\n\n    Polygon best = current;\n    int best_score = current_score;\n\n    double temperature = 1.0;\n    double cooling_rate = 0.999;\n\n    for (int i = 0; i < iterations; ++i) {\n        Polygon neighbor = generate_random_polygon(hull, max_vertices, max_edge_length);\n        neighbor.mackerels = count_points_in_polygon(mackerels, neighbor);\n        neighbor.sardines = count_points_in_polygon(sardines, neighbor);\n        int neighbor_score = evaluate_polygon(neighbor, mackerels, sardines);\n\n        if (neighbor_score > current_score || dis(gen) < exp((neighbor_score - current_score) / temperature)) {\n            current = neighbor;\n            current_score = neighbor_score;\n        }\n\n        if (current_score > best_score) {\n            best = current;\n            best_score = current_score;\n        }\n\n        temperature *= cooling_rate;\n    }\n\n    return best;\n}\n\nint main() {\n    int N;\n    cin >> N;\n\n    vector<Point> mackerels;\n    vector<Point> sardines;\n    vector<Point> all_points;\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        mackerels.emplace_back(x, y);\n        all_points.emplace_back(x, y);\n    }\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        sardines.emplace_back(x, y);\n        all_points.emplace_back(x, y);\n    }\n\n    vector<Point> hull = convex_hull(all_points);\n    int max_vertices = 1000;\n    int max_edge_length = 400000;\n    int iterations = 10000;\n\n    Polygon best_polygon = simulated_annealing(hull, mackerels, sardines, max_vertices, max_edge_length, iterations);\n\n    cout << best_polygon.vertices.size() << endl;\n    for (const auto &p : best_polygon.vertices) {\n        cout << p.x << \" \" << p.y << endl;\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <limits>\n#include <chrono>\n\nusing namespace std;\n\nstruct Rectangle {\n    int w, h;\n    int w_prime, h_prime;\n};\n\nstruct Placement {\n    int p; // index of the rectangle\n    int r; // rotation (0 or 1)\n    char d; // direction ('U' or 'L')\n    int b; // reference rectangle index or -1\n};\n\nstruct Solution {\n    vector<Placement> placements;\n    int width, height;\n    int score;\n};\n\nclass RectanglePacker {\nprivate:\n    int N, T, sigma;\n    vector<Rectangle> rectangles;\n    mt19937 rng;\n    uniform_real_distribution<double> dist;\n\n    Solution generateInitialSolution() {\n        Solution solution;\n        vector<int> indices(N);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), rng);\n\n        for (int i = 0; i < N; ++i) {\n            int p = indices[i];\n            int r = uniform_int_distribution<int>(0, 1)(rng);\n            char d = uniform_int_distribution<int>(0, 1)(rng) ? 'U' : 'L';\n            int b = i == 0 ? -1 : uniform_int_distribution<int>(-1, i - 1)(rng);\n            solution.placements.push_back({p, r, d, b});\n        }\n\n        return solution;\n    }\n\n    Solution placeRectangles(const Solution& solution) {\n        Solution result = solution;\n        vector<pair<int, int>> positions(N, {-1, -1});\n        int max_x = 0, max_y = 0;\n\n        for (const auto& placement : solution.placements) {\n            int p = placement.p;\n            int r = placement.r;\n            char d = placement.d;\n            int b = placement.b;\n\n            int w = r == 0 ? rectangles[p].w_prime : rectangles[p].h_prime;\n            int h = r == 0 ? rectangles[p].h_prime : rectangles[p].w_prime;\n\n            int x, y;\n            if (d == 'U') {\n                if (b == -1) {\n                    x = 0;\n                } else {\n                    x = positions[b].first + (r == 0 ? rectangles[b].w_prime : rectangles[b].h_prime);\n                }\n                y = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (positions[i].first != -1 && positions[i].first < x + w && positions[i].first + (r == 0 ? rectangles[i].w_prime : rectangles[i].h_prime) > x) {\n                        y = max(y, positions[i].second + (r == 0 ? rectangles[i].h_prime : rectangles[i].w_prime));\n                    }\n                }\n            } else { // d == 'L'\n                if (b == -1) {\n                    y = 0;\n                } else {\n                    y = positions[b].second + (r == 0 ? rectangles[b].h_prime : rectangles[b].w_prime);\n                }\n                x = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (positions[i].second != -1 && positions[i].second < y + h && positions[i].second + (r == 0 ? rectangles[i].h_prime : rectangles[i].w_prime) > y) {\n                        x = max(x, positions[i].first + (r == 0 ? rectangles[i].w_prime : rectangles[i].h_prime));\n                    }\n                }\n            }\n\n            positions[p] = {x, y};\n            max_x = max(max_x, x + w);\n            max_y = max(max_y, y + h);\n        }\n\n        result.width = max_x;\n        result.height = max_y;\n        result.score = max_x + max_y;\n\n        return result;\n    }\n\n    Solution mutateSolution(const Solution& solution) {\n        Solution new_solution = solution;\n        int mutation_type = uniform_int_distribution<int>(0, 2)(rng);\n\n        if (mutation_type == 0) { // Change rotation\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            new_solution.placements[idx].r = 1 - new_solution.placements[idx].r;\n        } else if (mutation_type == 1) { // Change direction\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            new_solution.placements[idx].d = new_solution.placements[idx].d == 'U' ? 'L' : 'U';\n        } else { // Change reference\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            int b = idx == 0 ? -1 : uniform_int_distribution<int>(-1, idx - 1)(rng);\n            new_solution.placements[idx].b = b;\n        }\n\n        return new_solution;\n    }\n\n    Solution simulatedAnnealing() {\n        Solution current_solution = generateInitialSolution();\n        current_solution = placeRectangles(current_solution);\n        Solution best_solution = current_solution;\n\n        double temperature = 1000.0;\n        double cooling_rate = 0.99;\n        int iterations = 1000;\n\n        for (int i = 0; i < iterations; ++i) {\n            Solution new_solution = mutateSolution(current_solution);\n            new_solution = placeRectangles(new_solution);\n\n            double delta = new_solution.score - current_solution.score;\n            if (delta < 0 || exp(-delta / temperature) > dist(rng)) {\n                current_solution = new_solution;\n                if (new_solution.score < best_solution.score) {\n                    best_solution = new_solution;\n                }\n            }\n\n            temperature *= cooling_rate;\n        }\n\n        return best_solution;\n    }\n\npublic:\n    RectanglePacker(int N, int T, int sigma, const vector<Rectangle>& rectangles)\n        : N(N), T(T), sigma(sigma), rectangles(rectangles), rng(chrono::steady_clock::now().time_since_epoch().count()), dist(0.0, 1.0) {}\n\n    Solution findBestSolution() {\n        Solution best_solution;\n        best_solution.score = numeric_limits<int>::max();\n\n        for (int t = 0; t < T; ++t) {\n            Solution solution = simulatedAnnealing();\n            if (solution.score < best_solution.score) {\n                best_solution = solution;\n            }\n        }\n\n        return best_solution;\n    }\n};\n\nint main() {\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n\n    vector<Rectangle> rectangles(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> rectangles[i].w_prime >> rectangles[i].h_prime;\n    }\n\n    RectanglePacker packer(N, T, sigma, rectangles);\n    Solution best_solution = packer.findBestSolution();\n\n    cout << best_solution.placements.size() << endl;\n    for (const auto& placement : best_solution.placements) {\n        cout << placement.p << \" \" << placement.r << \" \" << placement.d << \" \" << placement.b << endl;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_set>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n};\n\nstruct Vertex {\n    int id;\n    int beauty;\n    vector<int> neighbors;\n};\n\nstruct Tree {\n    int root;\n    vector<int> parent;\n    vector<int> height;\n};\n\nint N, M, H;\nvector<Vertex> vertices;\nvector<Edge> edges;\nvector<int> x, y;\n\nvoid input() {\n    cin >> N >> M >> H;\n    vertices.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> vertices[i].beauty;\n        vertices[i].id = i;\n    }\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        vertices[edges[i].u].neighbors.push_back(edges[i].v);\n        vertices[edges[i].v].neighbors.push_back(edges[i].u);\n    }\n    x.resize(N);\n    y.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> x[i] >> y[i];\n    }\n}\n\nvector<int> solve() {\n    vector<int> parent(N, -1);\n    vector<bool> visited(N, false);\n    priority_queue<pair<int, int>> pq; // (beauty, id)\n\n    for (int i = 0; i < N; ++i) {\n        pq.push({vertices[i].beauty, i});\n    }\n\n    while (!pq.empty()) {\n        auto current = pq.top();\n        pq.pop();\n        int u = current.second;\n\n        if (visited[u]) continue;\n        visited[u] = true;\n\n        queue<pair<int, int>> q; // (vertex, parent)\n        q.push({u, -1});\n        int current_height = 0;\n\n        while (!q.empty() && current_height <= H) {\n            int size = q.size();\n            for (int i = 0; i < size; ++i) {\n                auto front = q.front();\n                q.pop();\n                int v = front.first;\n                int p = front.second;\n\n                if (visited[v]) continue;\n                visited[v] = true;\n                parent[v] = p;\n\n                for (int neighbor : vertices[v].neighbors) {\n                    if (!visited[neighbor]) {\n                        q.push({neighbor, v});\n                    }\n                }\n            }\n            current_height++;\n        }\n    }\n\n    return parent;\n}\n\nint main() {\n    input();\n    auto parent = solve();\n    for (int p : parent) {\n        cout << p << \" \";\n    }\n    cout << endl;\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cassert>\n\nusing namespace std;\n\nstruct Move {\n    char direction;\n    int index;\n};\n\nvector<Move> solve(const vector<string>& board) {\n    int N = board.size();\n    vector<Move> moves;\n    vector<vector<char>> current_board(N, vector<char>(N));\n\n    // Convert the input board to a 2D vector of characters\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            current_board[i][j] = board[i][j];\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (current_board[i][j] == 'x') {\n                // Check if we can remove the Oni by shifting the row left\n                bool can_remove_left = true;\n                for (int k = 0; k < i; ++k) {\n                    if (current_board[k][j] == 'o') {\n                        can_remove_left = false;\n                        break;\n                    }\n                }\n                if (can_remove_left) {\n                    // Shift the row left to remove the Oni\n                    for (int k = 0; k <= i; ++k) {\n                        moves.push_back({'L', i});\n                    }\n                    for (int k = 0; k <= i; ++k) {\n                        moves.push_back({'R', i});\n                    }\n                    // Update the board state\n                    for (int k = 0; k < N - 1; ++k) {\n                        current_board[i][k] = current_board[i][k + 1];\n                    }\n                    current_board[i][N - 1] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the row right\n                bool can_remove_right = true;\n                for (int k = i + 1; k < N; ++k) {\n                    if (current_board[k][j] == 'o') {\n                        can_remove_right = false;\n                        break;\n                    }\n                }\n                if (can_remove_right) {\n                    // Shift the row right to remove the Oni\n                    for (int k = 0; k <= N - 1 - i; ++k) {\n                        moves.push_back({'R', i});\n                    }\n                    for (int k = 0; k <= N - 1 - i; ++k) {\n                        moves.push_back({'L', i});\n                    }\n                    // Update the board state\n                    for (int k = N - 1; k > 0; --k) {\n                        current_board[i][k] = current_board[i][k - 1];\n                    }\n                    current_board[i][0] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the column up\n                bool can_remove_up = true;\n                for (int k = 0; k < j; ++k) {\n                    if (current_board[i][k] == 'o') {\n                        can_remove_up = false;\n                        break;\n                    }\n                }\n                if (can_remove_up) {\n                    // Shift the column up to remove the Oni\n                    for (int k = 0; k <= j; ++k) {\n                        moves.push_back({'U', j});\n                    }\n                    for (int k = 0; k <= j; ++k) {\n                        moves.push_back({'D', j});\n                    }\n                    // Update the board state\n                    for (int k = 0; k < N - 1; ++k) {\n                        current_board[k][j] = current_board[k + 1][j];\n                    }\n                    current_board[N - 1][j] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the column down\n                bool can_remove_down = true;\n                for (int k = j + 1; k < N; ++k) {\n                    if (current_board[i][k] == 'o') {\n                        can_remove_down = false;\n                        break;\n                    }\n                }\n                if (can_remove_down) {\n                    // Shift the column down to remove the Oni\n                    for (int k = 0; k <= N - 1 - j; ++k) {\n                        moves.push_back({'D', j});\n                    }\n                    for (int k = 0; k <= N - 1 - j; ++k) {\n                        moves.push_back({'U', j});\n                    }\n                    // Update the board state\n                    for (int k = N - 1; k > 0; --k) {\n                        current_board[k][j] = current_board[k - 1][j];\n                    }\n                    current_board[0][j] = '.';\n                }\n            }\n        }\n    }\n\n    return moves;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n    }\n\n    vector<Move> moves = solve(board);\n\n    for (const auto& move : moves) {\n        cout << move.direction << \" \" << move.index << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nstruct Employee {\n    int a;\n    int b;\n};\n\nvector<int> simulate_cleaning_plan(const vector<Employee>& employees, int L) {\n    vector<int> actual(employees.size(), 0);\n    unordered_map<int, int> cycle_counts;\n    vector<bool> visited(employees.size(), false);\n    vector<int> path;\n\n    for (int i = 0; i < employees.size(); ++i) {\n        if (!visited[i]) {\n            int current = i;\n            path.clear();\n            while (!visited[current]) {\n                visited[current] = true;\n                path.push_back(current);\n                int t = count(actual.begin(), actual.end(), current);\n                if (t % 2 == 1) {\n                    current = employees[current].a;\n                } else {\n                    current = employees[current].b;\n                }\n            }\n\n            // Check if the current path is a cycle\n            auto it = find(path.begin(), path.end(), current);\n            if (it != path.end()) {\n                int cycle_length = distance(it, path.end());\n                int cycle_start = distance(path.begin(), it);\n                int cycle_repeats = (L - cycle_start) / cycle_length;\n                int remaining = (L - cycle_start) % cycle_length;\n\n                for (int j = cycle_start; j < path.size(); ++j) {\n                    actual[path[j]] += cycle_repeats;\n                }\n                for (int j = 0; j < remaining; ++j) {\n                    actual[path[cycle_start + j]]++;\n                }\n            } else {\n                for (int j = 0; j < path.size(); ++j) {\n                    actual[path[j]]++;\n                }\n            }\n        }\n    }\n\n    return actual;\n}\n\nint calculate_error(const vector<int>& actual, const vector<int>& target) {\n    int error = 0;\n    for (size_t i = 0; i < actual.size(); ++i) {\n        error += abs(actual[i] - target[i]);\n    }\n    return error;\n}\n\nvector<Employee> generate_initial_state(int N) {\n    vector<Employee> employees(N);\n    for (int i = 0; i < N; ++i) {\n        employees[i].a = i;\n        employees[i].b = i;\n    }\n    return employees;\n}\n\nvector<Employee> hill_climbing(const vector<int>& target, int N, int L, int iterations) {\n    vector<Employee> current_employees = generate_initial_state(N);\n    vector<int> current_actual = simulate_cleaning_plan(current_employees, L);\n    int current_error = calculate_error(current_actual, target);\n\n    for (int i = 0; i < iterations; ++i) {\n        vector<Employee> new_employees = current_employees;\n        int employee = rand() % N;\n        int choice = rand() % 2;\n\n        if (choice == 0) {\n            new_employees[employee].a = rand() % N;\n        } else {\n            new_employees[employee].b = rand() % N;\n        }\n\n        vector<int> new_actual = simulate_cleaning_plan(new_employees, L);\n        int new_error = calculate_error(new_actual, target);\n\n        if (new_error < current_error) {\n            current_employees = new_employees;\n            current_error = new_error;\n        }\n    }\n\n    return current_employees;\n}\n\nint main() {\n    int N, L;\n    cin >> N >> L;\n\n    vector<int> target(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> target[i];\n    }\n\n    int iterations = 10000;\n    vector<Employee> best_employees = hill_climbing(target, N, L, iterations);\n\n    for (const auto& employee : best_employees) {\n        cout << employee.a << \" \" << employee.b << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <limits>\n\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double cx, cy; // Center coordinates\n};\n\nstruct Edge {\n    int u, v;\n    double distance;\n};\n\nstruct CompareEdge {\n    bool operator()(const Edge& a, const Edge& b) {\n        return a.distance > b.distance;\n    }\n};\n\nvector<Edge> query(const vector<int>& cities) {\n    cout << \"? \" << cities.size();\n    for (int city : cities) {\n        cout << \" \" << city;\n    }\n    cout << endl;\n    cout.flush();\n\n    vector<Edge> edges;\n    for (size_t i = 0; i < cities.size() - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        edges.push_back({u, v, 0.0}); // Distance will be calculated later\n    }\n    return edges;\n}\n\nvoid answer(const vector<vector<int>>& groups, const vector<vector<Edge>>& edges) {\n    cout << \"!\" << endl;\n    for (size_t i = 0; i < groups.size(); ++i) {\n        for (int city : groups[i]) {\n            cout << city << \" \";\n        }\n        cout << endl;\n        for (const Edge& edge : edges[i]) {\n            cout << edge.u << \" \" << edge.v << endl;\n        }\n    }\n}\n\nvector<vector<int>> greedyGrouping(const vector<City>& cities, const vector<int>& G) {\n    vector<City> sortedCities = cities;\n    sort(sortedCities.begin(), sortedCities.end(), [](const City& a, const City& b) {\n        return a.cx < b.cx || (a.cx == b.cx && a.cy < b.cy);\n    });\n\n    vector<vector<int>> groups;\n    size_t startIdx = 0;\n    for (int g : G) {\n        vector<int> group;\n        for (size_t i = startIdx; i < startIdx + g; ++i) {\n            group.push_back(sortedCities[i].id);\n        }\n        groups.push_back(group);\n        startIdx += g;\n    }\n    return groups;\n}\n\nvector<Edge> calculateMST(const vector<int>& group, const vector<City>& cities) {\n    unordered_map<int, int> cityToIndex;\n    for (size_t i = 0; i < cities.size(); ++i) {\n        cityToIndex[cities[i].id] = i;\n    }\n\n    vector<vector<double>> dist(group.size(), vector<double>(group.size(), 0.0));\n    for (size_t i = 0; i < group.size(); ++i) {\n        for (size_t j = i + 1; j < group.size(); ++j) {\n            const City& a = cities[cityToIndex[group[i]]];\n            const City& b = cities[cityToIndex[group[j]]];\n            double dx = a.cx - b.cx;\n            double dy = a.cy - b.cy;\n            dist[i][j] = dist[j][i] = sqrt(dx * dx + dy * dy);\n        }\n    }\n\n    priority_queue<Edge, vector<Edge>, CompareEdge> pq;\n    for (size_t i = 0; i < group.size(); ++i) {\n        for (size_t j = i + 1; j < group.size(); ++j) {\n            pq.push({group[i], group[j], dist[i][j]});\n        }\n    }\n\n    vector<Edge> mstEdges;\n    vector<int> parent(group.size(), -1);\n    vector<int> rank(group.size(), 0);\n\n    function<int(int)> find = [&](int u) {\n        if (parent[u] == -1) return u;\n        return parent[u] = find(parent[u]);\n    };\n\n    while (!pq.empty() && mstEdges.size() < group.size() - 1) {\n        Edge edge = pq.top();\n        pq.pop();\n        int u = find(edge.u);\n        int v = find(edge.v);\n        if (u != v) {\n            mstEdges.push_back(edge);\n            if (rank[u] > rank[v]) {\n                parent[v] = u;\n            } else {\n                parent[u] = v;\n                if (rank[u] == rank[v]) {\n                    rank[v]++;\n                }\n            }\n        }\n    }\n    return mstEdges;\n}\n\nint main() {\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> G[i];\n    }\n\n    vector<City> cities(N);\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cities[i] = {i, lx, rx, ly, ry, (lx + rx) / 2.0, (ly + ry) / 2.0};\n    }\n\n    vector<vector<int>> groups = greedyGrouping(cities, G);\n    vector<vector<Edge>> edges(M);\n\n    for (int k = 0; k < M; ++k) {\n        for (size_t i = 0; i < groups[k].size() - 1; i += 2) {\n            if (i < groups[k].size() - 2) {\n                vector<int> queryCities = {groups[k][i], groups[k][i + 1], groups[k][i + 2]};\n                vector<Edge> queryEdges = query(queryCities);\n                edges[k].insert(edges[k].end(), queryEdges.begin(), queryEdges.end());\n            } else {\n                edges[k].push_back({groups[k][i], groups[k][i + 1], 0.0});\n            }\n        }\n    }\n\n    answer(groups, edges);\n\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 20;\nconst int M = 40;\nconst int MAX_ACTIONS = 2 * N * M;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct State {\n    Point pos;\n    unordered_set<Point> blocks;\n    int visited;\n    int actions;\n    State(Point pos, unordered_set<Point> blocks, int visited, int actions)\n        : pos(pos), blocks(blocks), visited(visited), actions(actions) {}\n};\n\nstruct Action {\n    char type;\n    char direction;\n    Action(char type, char direction) : type(type), direction(direction) {}\n};\n\nvector<Action> directions = {\n    {'U', 'U'}, {'D', 'D'}, {'L', 'L'}, {'R', 'R'}\n};\n\nvector<Action> actions = {\n    {'M', 'U'}, {'M', 'D'}, {'M', 'L'}, {'M', 'R'},\n    {'S', 'U'}, {'S', 'D'}, {'S', 'L'}, {'S', 'R'},\n    {'A', 'U'}, {'A', 'D'}, {'A', 'L'}, {'A', 'R'}\n};\n\nbool isValid(Point p) {\n    return p.x >= 0 && p.x < N && p.y >= 0 && p.y < N;\n}\n\nPoint move(Point p, char direction) {\n    switch (direction) {\n        case 'U': return Point(p.x - 1, p.y);\n        case 'D': return Point(p.x + 1, p.y);\n        case 'L': return Point(p.x, p.y - 1);\n        case 'R': return Point(p.x, p.y + 1);\n    }\n    return p;\n}\n\nPoint slide(Point p, char direction, const unordered_set<Point>& blocks) {\n    Point next = p;\n    while (true) {\n        Point newPos = move(next, direction);\n        if (!isValid(newPos) || blocks.count(newPos)) break;\n        next = newPos;\n    }\n    return next;\n}\n\nunordered_set<Point> alter(Point p, char direction, unordered_set<Point> blocks) {\n    Point target = move(p, direction);\n    if (isValid(target)) {\n        if (blocks.count(target)) {\n            blocks.erase(target);\n        } else {\n            blocks.insert(target);\n        }\n    }\n    return blocks;\n}\n\nint heuristic(Point a, Point b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvector<Action> solve(vector<Point> targets) {\n    vector<Action> result;\n    unordered_set<Point> blocks;\n    Point current = targets[0];\n    int visited = 0;\n\n    for (int i = 1; i < targets.size(); ++i) {\n        Point target = targets[i];\n        priority_queue<pair<int, State>, vector<pair<int, State>>, greater<pair<int, State>>> pq;\n        unordered_set<Point> initialBlocks = blocks;\n        pq.push({heuristic(current, target), State(current, initialBlocks, visited, 0)});\n\n        while (!pq.empty()) {\n            auto [cost, state] = pq.top();\n            pq.pop();\n\n            if (state.pos == target) {\n                current = target;\n                visited = i;\n                blocks = state.blocks;\n                break;\n            }\n\n            if (state.actions >= MAX_ACTIONS) continue;\n\n            for (auto& action : actions) {\n                Point newPos = state.pos;\n                unordered_set<Point> newBlocks = state.blocks;\n                int newVisited = state.visited;\n                int newActions = state.actions + 1;\n\n                if (action.type == 'M') {\n                    newPos = move(state.pos, action.direction);\n                    if (!isValid(newPos) || newBlocks.count(newPos)) continue;\n                } else if (action.type == 'S') {\n                    newPos = slide(state.pos, action.direction, newBlocks);\n                } else if (action.type == 'A') {\n                    newBlocks = alter(state.pos, action.direction, newBlocks);\n                }\n\n                if (newPos == target) newVisited = i;\n\n                int newCost = newActions + heuristic(newPos, target);\n                pq.push({newCost, State(newPos, newBlocks, newVisited, newActions)});\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<Point> targets;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        targets.emplace_back(x, y);\n    }\n\n    vector<Action> result = solve(targets);\n    for (auto& action : result) {\n        cout << action.type << \" \" << action.direction << endl;\n    }\n\n    return 0;\n}"},"4":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nstruct Rectangle {\n    int a, b, c, d; // Coordinates of the rectangle\n    int area;       // Area of the rectangle\n};\n\nstruct Company {\n    int x, y;       // Desired location\n    int r;          // Desired area\n};\n\ndouble satisfaction_level(const Rectangle& rect, const Company& company) {\n    if (rect.a > company.x || rect.c <= company.x || rect.b > company.y || rect.d <= company.y) {\n        return 0.0;\n    }\n    double s_i = rect.area;\n    double r_i = company.r;\n    double min_val = min(r_i, s_i);\n    double max_val = max(r_i, s_i);\n    double p_i = 1.0 - pow(1.0 - min_val / max_val, 2.0);\n    return p_i;\n}\n\nbool is_overlapping(const Rectangle& rect1, const Rectangle& rect2) {\n    return !(rect1.c <= rect2.a || rect2.c <= rect1.a || rect1.d <= rect2.b || rect2.d <= rect1.b);\n}\n\nvector<Rectangle> generate_initial_solution(const vector<Company>& companies) {\n    vector<Rectangle> rectangles;\n    for (const auto& company : companies) {\n        int width = static_cast<int>(sqrt(company.r));\n        int height = company.r / width;\n        if (width * height < company.r) {\n            height++;\n        }\n        int a = max(0, company.x - width / 2);\n        int b = max(0, company.y - height / 2);\n        int c = min(10000, a + width);\n        int d = min(10000, b + height);\n        Rectangle rect = {a, b, c, d, (c - a) * (d - b)};\n        rectangles.push_back(rect);\n    }\n    return rectangles;\n}\n\ndouble total_satisfaction(const vector<Rectangle>& rectangles, const vector<Company>& companies) {\n    double total = 0.0;\n    for (size_t i = 0; i < companies.size(); ++i) {\n        total += satisfaction_level(rectangles[i], companies[i]);\n    }\n    return total;\n}\n\nvector<Rectangle> simulated_annealing(const vector<Company>& companies, vector<Rectangle> initial_rectangles, double initial_temp, double cooling_rate, int iterations) {\n    vector<Rectangle> current_rectangles = initial_rectangles;\n    double current_satisfaction = total_satisfaction(current_rectangles, companies);\n    vector<Rectangle> best_rectangles = current_rectangles;\n    double best_satisfaction = current_satisfaction;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    for (double temp = initial_temp; temp > 1e-6; temp *= cooling_rate) {\n        for (int i = 0; i < iterations; ++i) {\n            vector<Rectangle> new_rectangles = current_rectangles;\n            int idx = dis(gen) * companies.size();\n            int delta_x = (dis(gen) * 2 - 1) * 10;\n            int delta_y = (dis(gen) * 2 - 1) * 10;\n            new_rectangles[idx].a = max(0, new_rectangles[idx].a + delta_x);\n            new_rectangles[idx].b = max(0, new_rectangles[idx].b + delta_y);\n            new_rectangles[idx].c = min(10000, new_rectangles[idx].c + delta_x);\n            new_rectangles[idx].d = min(10000, new_rectangles[idx].d + delta_y);\n            new_rectangles[idx].area = (new_rectangles[idx].c - new_rectangles[idx].a) * (new_rectangles[idx].d - new_rectangles[idx].b);\n\n            bool valid = true;\n            for (size_t j = 0; j < new_rectangles.size(); ++j) {\n                if (j != idx && is_overlapping(new_rectangles[idx], new_rectangles[j])) {\n                    valid = false;\n                    break;\n                }\n            }\n\n            if (valid) {\n                double new_satisfaction = total_satisfaction(new_rectangles, companies);\n                double delta = new_satisfaction - current_satisfaction;\n                if (delta > 0 || dis(gen) < exp(delta / temp)) {\n                    current_rectangles = new_rectangles;\n                    current_satisfaction = new_satisfaction;\n                    if (current_satisfaction > best_satisfaction) {\n                        best_rectangles = current_rectangles;\n                        best_satisfaction = current_satisfaction;\n                    }\n                }\n            }\n        }\n    }\n    return best_rectangles;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector<Company> companies(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n\n    vector<Rectangle> initial_rectangles = generate_initial_solution(companies);\n    vector<Rectangle> best_rectangles = simulated_annealing(companies, initial_rectangles, 1000.0, 0.99, 1000);\n\n    for (const auto& rect : best_rectangles) {\n        cout << rect.a << \" \" << rect.b << \" \" << rect.c << \" \" << rect.d << endl;\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <unordered_set>\n#include <queue>\n#include <utility>\n#include <unordered_map>\n\nusing namespace std;\n\nconst int SIZE = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\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\nbool is_valid(int x, int y) {\n    return x >= 0 && x < SIZE && y >= 0 && y < SIZE;\n}\n\nint heuristic(int x, int y, const vector<vector<int>>& points) {\n    int max_score = 0;\n    for (int i = max(0, x - 2); i < min(SIZE, x + 3); ++i) {\n        for (int j = max(0, y - 2); j < min(SIZE, y + 3); ++j) {\n            max_score = max(max_score, points[i][j]);\n        }\n    }\n    return max_score;\n}\n\nstruct CompareState {\n    bool operator()(const pair<int, State>& a, const pair<int, State>& b) {\n        return a.first < b.first;\n    }\n};\n\nstring find_max_score_path(int si, int sj, const vector<vector<int>>& tiles, const vector<vector<int>>& points) {\n    unordered_set<int> initial_visited_tiles;\n    initial_visited_tiles.insert(tiles[si][sj]);\n    priority_queue<pair<int, State>, vector<pair<int, State>>, CompareState> pq;\n    pq.emplace(points[si][sj] + heuristic(si, sj, points), State(si, sj, points[si][sj], \"\", initial_visited_tiles));\n\n    unordered_map<int, unordered_map<int, int>> best_scores;\n    best_scores[si][sj] = points[si][sj];\n\n    int max_score = points[si][sj];\n    string best_path;\n\n    while (!pq.empty()) {\n        auto [current_priority, current] = pq.top();\n        pq.pop();\n\n        if (current.score > max_score) {\n            max_score = current.score;\n            best_path = current.path;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = current.x + dx[i];\n            int ny = current.y + dy[i];\n\n            if (is_valid(nx, ny) && current.visited_tiles.find(tiles[nx][ny]) == current.visited_tiles.end()) {\n                int new_score = current.score + points[nx][ny];\n                if (best_scores[nx][ny] < new_score) {\n                    best_scores[nx][ny] = new_score;\n                    unordered_set<int> new_visited_tiles = current.visited_tiles;\n                    new_visited_tiles.insert(tiles[nx][ny]);\n                    pq.emplace(new_score + heuristic(nx, ny, points), State(nx, ny, new_score, current.path + dir[i], new_visited_tiles));\n                }\n            }\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> tiles(SIZE, vector<int>(SIZE));\n    for (int i = 0; i < SIZE; ++i) {\n        for (int j = 0; j < SIZE; ++j) {\n            cin >> tiles[i][j];\n        }\n    }\n\n    vector<vector<int>> points(SIZE, vector<int>(SIZE));\n    for (int i = 0; i < SIZE; ++i) {\n        for (int j = 0; j < SIZE; ++j) {\n            cin >> points[i][j];\n        }\n    }\n\n    string path = find_max_score_path(si, sj, tiles, points);\n    cout << path << endl;\n\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <unordered_map>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int QUERY_COUNT = 1000;\nconst double DECAY_FACTOR = 0.998;\nconst double SCORE_MULTIPLIER = 2312311;\n\nstruct Vertex {\n    int i, j;\n    Vertex(int i, int j) : i(i), j(j) {}\n    bool operator==(const Vertex& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Vertex> {\n        size_t operator()(const Vertex& v) const {\n            return hash<int>()(v.i) ^ hash<int>()(v.j);\n        }\n    };\n}\n\nstruct Edge {\n    Vertex from, to;\n    double estimated_length;\n    Edge(Vertex from, Vertex to, double estimated_length) : from(from), to(to), estimated_length(estimated_length) {}\n};\n\nclass Graph {\nprivate:\n    vector<vector<Vertex>> vertices;\n    unordered_map<Vertex, vector<Edge>> edges;\n    unordered_map<Vertex, unordered_map<Vertex, double>> estimated_lengths;\n\npublic:\n    Graph() {\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            vector<Vertex> row;\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                row.emplace_back(i, j);\n            }\n            vertices.push_back(row);\n        }\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                Vertex from(i, j);\n                if (i > 0) {\n                    Vertex to(i - 1, j);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (i < GRID_SIZE - 1) {\n                    Vertex to(i + 1, j);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (j > 0) {\n                    Vertex to(i, j - 1);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (j < GRID_SIZE - 1) {\n                    Vertex to(i, j + 1);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n            }\n        }\n    }\n\n    void update_estimated_lengths(const vector<Vertex>& path, double actual_length) {\n        double path_length = 0.0;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            path_length += estimated_lengths[path[k]][path[k + 1]];\n        }\n        double factor = actual_length / path_length;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            estimated_lengths[path[k]][path[k + 1]] *= factor;\n            estimated_lengths[path[k + 1]][path[k]] *= factor;\n        }\n    }\n\n    vector<Vertex> a_star_search(const Vertex& start, const Vertex& goal) {\n        auto heuristic = [&](const Vertex& v) {\n            return abs(v.i - goal.i) + abs(v.j - goal.j);\n        };\n\n        priority_queue<pair<double, Vertex>, vector<pair<double, Vertex>>, greater<pair<double, Vertex>>> open_set;\n        unordered_map<Vertex, Vertex> came_from;\n        unordered_map<Vertex, double> g_score;\n        unordered_map<Vertex, double> f_score;\n\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                Vertex v(i, j);\n                g_score[v] = numeric_limits<double>::infinity();\n                f_score[v] = numeric_limits<double>::infinity();\n            }\n        }\n\n        g_score[start] = 0.0;\n        f_score[start] = heuristic(start);\n        open_set.push({f_score[start], start});\n\n        while (!open_set.empty()) {\n            Vertex current = open_set.top().second;\n            open_set.pop();\n\n            if (current == goal) {\n                vector<Vertex> path;\n                while (came_from.find(current) != came_from.end()) {\n                    path.push_back(current);\n                    current = came_from[current];\n                }\n                path.push_back(start);\n                reverse(path.begin(), path.end());\n                return path;\n            }\n\n            for (const Edge& edge : edges[current]) {\n                Vertex neighbor = edge.to;\n                double tentative_g_score = g_score[current] + estimated_lengths[current][neighbor];\n\n                if (tentative_g_score < g_score[neighbor]) {\n                    came_from[neighbor] = current;\n                    g_score[neighbor] = tentative_g_score;\n                    f_score[neighbor] = g_score[neighbor] + heuristic(neighbor);\n                    open_set.push({f_score[neighbor], neighbor});\n                }\n            }\n        }\n\n        return {};\n    }\n\n    string path_to_string(const vector<Vertex>& path) {\n        stringstream ss;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            Vertex from = path[k];\n            Vertex to = path[k + 1];\n            if (to.i == from.i - 1) {\n                ss << \"U\";\n            } else if (to.i == from.i + 1) {\n                ss << \"D\";\n            } else if (to.j == from.j - 1) {\n                ss << \"L\";\n            } else if (to.j == from.j + 1) {\n                ss << \"R\";\n            }\n        }\n        return ss.str();\n    }\n};\n\nint main() {\n    Graph graph;\n    double score = 0.0;\n    int prev_result = 0;\n\n    for (int k = 0; k < QUERY_COUNT; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        Vertex start(si, sj);\n        Vertex goal(ti, tj);\n\n        vector<Vertex> path = graph.a_star_search(start, goal);\n        string path_str = graph.path_to_string(path);\n        cout << path_str << endl;\n        cout.flush();\n\n        int actual_length;\n        cin >> actual_length;\n\n        graph.update_estimated_lengths(path, actual_length);\n\n        double path_length = 0.0;\n        for (size_t i = 0; i < path.size() - 1; ++i) {\n            path_length += graph.estimated_lengths[path[i]][path[i + 1]];\n        }\n\n        double ratio = actual_length / path_length;\n        score = score * DECAY_FACTOR + ratio;\n    }\n\n    cout << round(SCORE_MULTIPLIER * score) << endl;\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <unordered_set>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int ALPHABET_SIZE = 8;\nconst char ALPHABET[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};\nconst char EMPTY = '.';\n\nstruct Matrix {\n    vector<vector<char>> data;\n\n    Matrix() : data(N, vector<char>(N, EMPTY)) {}\n\n    void randomize() {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, ALPHABET_SIZE - 1);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                data[i][j] = ALPHABET[dis(gen)];\n            }\n        }\n    }\n\n    void mutate(double rate) {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_real_distribution<> prob(0.0, 1.0);\n        uniform_int_distribution<> dis(0, ALPHABET_SIZE - 1);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (prob(gen) < rate) {\n                    data[i][j] = ALPHABET[dis(gen)];\n                }\n            }\n        }\n    }\n\n    bool is_subsequence(const string& s) {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                // Check horizontal subsequence\n                bool match = true;\n                for (int k = 0; k < s.size(); ++k) {\n                    if (data[i][(j + k) % N] != s[k]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) return true;\n\n                // Check vertical subsequence\n                match = true;\n                for (int k = 0; k < s.size(); ++k) {\n                    if (data[(i + k) % N][j] != s[k]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) return true;\n            }\n        }\n        return false;\n    }\n\n    int count_subsequences(const vector<string>& strings) {\n        int count = 0;\n        for (const auto& s : strings) {\n            if (is_subsequence(s)) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    int count_empty() {\n        int count = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (data[i][j] == EMPTY) {\n                    count++;\n                }\n            }\n        }\n        return count;\n    }\n\n    void print() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << data[i][j];\n            }\n            cout << endl;\n        }\n    }\n};\n\ndouble evaluate(const Matrix& matrix, const vector<string>& strings) {\n    int c = matrix.count_subsequences(strings);\n    if (c < strings.size()) {\n        return static_cast<double>(c) / strings.size();\n    } else {\n        int d = matrix.count_empty();\n        return static_cast<double>(2 * N * N) / (2 * N * N - d);\n    }\n}\n\nMatrix genetic_algorithm(const vector<string>& strings, int population_size, int generations, double mutation_rate) {\n    random_device rd;\n    mt19937 gen(rd());\n    vector<Matrix> population(population_size);\n\n    for (auto& matrix : population) {\n        matrix.randomize();\n    }\n\n    for (int gen = 0; gen < generations; ++gen) {\n        vector<double> fitness(population_size);\n        for (int i = 0; i < population_size; ++i) {\n            fitness[i] = evaluate(population[i], strings);\n        }\n\n        vector<Matrix> new_population;\n        for (int i = 0; i < population_size; ++i) {\n            uniform_int_distribution<> dis(0, population_size - 1);\n            int parent1 = dis(gen);\n            int parent2 = dis(gen);\n\n            Matrix child;\n            for (int x = 0; x < N; ++x) {\n                for (int y = 0; y < N; ++y) {\n                    if (fitness[parent1] > fitness[parent2]) {\n                        child.data[x][y] = population[parent1].data[x][y];\n                    } else {\n                        child.data[x][y] = population[parent2].data[x][y];\n                    }\n                }\n            }\n\n            child.mutate(mutation_rate);\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n    }\n\n    auto best = max_element(population.begin(), population.end(), [&](const Matrix& a, const Matrix& b) {\n        return evaluate(a, strings) < evaluate(b, strings);\n    });\n\n    return *best;\n}\n\nMatrix simulated_annealing(const vector<string>& strings, double initial_temp, double cooling_rate, int iterations) {\n    Matrix current;\n    current.randomize();\n    double current_score = evaluate(current, strings);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> prob(0.0, 1.0);\n\n    double temp = initial_temp;\n    for (int i = 0; i < iterations; ++i) {\n        Matrix neighbor = current;\n        neighbor.mutate(0.1);\n\n        double neighbor_score = evaluate(neighbor, strings);\n        double delta = neighbor_score - current_score;\n\n        if (delta > 0 || prob(gen) < exp(delta / temp)) {\n            current = neighbor;\n            current_score = neighbor_score;\n        }\n\n        temp *= cooling_rate;\n    }\n\n    return current;\n}\n\nint main() {\n    int M;\n    cin >> M;\n    vector<string> strings(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i];\n    }\n\n    // Run genetic algorithm\n    Matrix best_matrix = genetic_algorithm(strings, 50, 100, 0.01);\n\n    // Run simulated annealing\n    Matrix sa_matrix = simulated_annealing(strings, 1000.0, 0.99, 10000);\n\n    // Choose the best solution\n    if (evaluate(sa_matrix, strings) > evaluate(best_matrix, strings)) {\n        best_matrix = sa_matrix;\n    }\n\n    best_matrix.print();\n\n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int i, j;\n    Point(int i, int j) : i(i), j(j) {}\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.i) ^ hash<int>()(p.j);\n        }\n    };\n}\n\nclass PatrolRoute {\nprivate:\n    int N;\n    Point start;\n    vector<string> grid;\n    vector<vector<unordered_set<Point>>> visibility;\n    vector<Point> roadSquares;\n    vector<vector<int>> moveTime;\n    vector<vector<int>> dist;\n\n    void precomputeVisibility() {\n        visibility.resize(N, vector<unordered_set<Point>>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == '#') continue;\n                // Horizontal visibility\n                for (int k = j - 1; k >= 0; --k) {\n                    if (grid[i][k] == '#') break;\n                    visibility[i][j].insert(Point(i, k));\n                }\n                for (int k = j + 1; k < N; ++k) {\n                    if (grid[i][k] == '#') break;\n                    visibility[i][j].insert(Point(i, k));\n                }\n                // Vertical visibility\n                for (int k = i - 1; k >= 0; --k) {\n                    if (grid[k][j] == '#') break;\n                    visibility[i][j].insert(Point(k, j));\n                }\n                for (int k = i + 1; k < N; ++k) {\n                    if (grid[k][j] == '#') break;\n                    visibility[i][j].insert(Point(k, j));\n                }\n            }\n        }\n    }\n\n    void precomputeRoadSquares() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] != '#') {\n                    roadSquares.emplace_back(i, j);\n                }\n            }\n        }\n    }\n\n    void precomputeMoveTime() {\n        moveTime.resize(N, vector<int>(N, 0));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] != '#') {\n                    moveTime[i][j] = grid[i][j] - '0';\n                }\n            }\n        }\n    }\n\n    void precomputeDistances() {\n        dist.resize(N, vector<int>(N, -1));\n        queue<Point> q;\n        q.push(start);\n        dist[start.i][start.j] = 0;\n        while (!q.empty()) {\n            Point current = q.front();\n            q.pop();\n            for (const auto& neighbor : getNeighbors(current)) {\n                if (dist[neighbor.i][neighbor.j] == -1) {\n                    dist[neighbor.i][neighbor.j] = dist[current.i][current.j] + moveTime[neighbor.i][neighbor.j];\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n\n    vector<Point> getNeighbors(const Point& p) {\n        vector<Point> neighbors;\n        if (p.i > 0 && grid[p.i - 1][p.j] != '#') neighbors.emplace_back(p.i - 1, p.j);\n        if (p.i < N - 1 && grid[p.i + 1][p.j] != '#') neighbors.emplace_back(p.i + 1, p.j);\n        if (p.j > 0 && grid[p.i][p.j - 1] != '#') neighbors.emplace_back(p.i, p.j - 1);\n        if (p.j < N - 1 && grid[p.i][p.j + 1] != '#') neighbors.emplace_back(p.i, p.j + 1);\n        return neighbors;\n    }\n\n    vector<Point> greedyInitialization() {\n        unordered_set<Point> covered;\n        vector<Point> path;\n        Point current = start;\n        path.push_back(current);\n        covered.insert(visibility[current.i][current.j].begin(), visibility[current.i][current.j].end());\n        while (covered.size() < roadSquares.size()) {\n            Point next;\n            int maxNewCovered = -1;\n            for (const auto& neighbor : getNeighbors(current)) {\n                int newCovered = 0;\n                for (const auto& visible : visibility[neighbor.i][neighbor.j]) {\n                    if (covered.find(visible) == covered.end()) {\n                        newCovered++;\n                    }\n                }\n                if (newCovered > maxNewCovered) {\n                    maxNewCovered = newCovered;\n                    next = neighbor;\n                }\n            }\n            if (maxNewCovered == 0) break; // No progress, break to avoid infinite loop\n            current = next;\n            path.push_back(current);\n            covered.insert(visibility[current.i][current.j].begin(), visibility[current.i][current.j].end());\n        }\n        return path;\n    }\n\n    vector<Point> geneticAlgorithm(const vector<Point>& initialPath) {\n        vector<Point> bestPath = initialPath;\n        int bestScore = calculateScore(bestPath);\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, roadSquares.size() - 1);\n        for (int iter = 0; iter < 1000; ++iter) {\n            vector<Point> newPath = bestPath;\n            int a = dis(gen);\n            int b = dis(gen);\n            if (a > b) swap(a, b);\n            reverse(newPath.begin() + a, newPath.begin() + b);\n            int newScore = calculateScore(newPath);\n            if (newScore > bestScore) {\n                bestPath = newPath;\n                bestScore = newScore;\n            }\n        }\n        return bestPath;\n    }\n\n    int calculateScore(const vector<Point>& path) {\n        unordered_set<Point> covered;\n        for (const auto& point : path) {\n            covered.insert(visibility[point.i][point.j].begin(), visibility[point.i][point.j].end());\n        }\n        int v = covered.size();\n        int r = roadSquares.size();\n        if (v < r) {\n            return round(10000 * v / r);\n        } else {\n            int t = 0;\n            for (size_t i = 1; i < path.size(); ++i) {\n                t += moveTime[path[i].i][path[i].j];\n            }\n            return round(10000 + 10000000 * N / t);\n        }\n    }\n\npublic:\n    PatrolRoute(int N, int si, int sj, const vector<string>& grid) : N(N), start(si, sj), grid(grid) {\n        precomputeVisibility();\n        precomputeRoadSquares();\n        precomputeMoveTime();\n        precomputeDistances();\n    }\n\n    string findRoute() {\n        vector<Point> initialPath = greedyInitialization();\n        vector<Point> optimizedPath = geneticAlgorithm(initialPath);\n        string route;\n        for (size_t i = 1; i < optimizedPath.size(); ++i) {\n            Point prev = optimizedPath[i - 1];\n            Point curr = optimizedPath[i];\n            if (curr.i == prev.i - 1) route += 'U';\n            else if (curr.i == prev.i + 1) route += 'D';\n            else if (curr.j == prev.j - 1) route += 'L';\n            else if (curr.j == prev.j + 1) route += 'R';\n        }\n        return route;\n    }\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n    PatrolRoute patrolRoute(N, si, sj, grid);\n    cout << patrolRoute.findRoute() << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <unordered_set>\n#include <queue>\n#include <cmath>\n\nusing namespace std;\n\nstruct Task {\n    vector<int> required_skills;\n    vector<int> dependencies;\n    int duration;\n    bool completed;\n};\n\nstruct TeamMember {\n    vector<int> skills;\n    int current_task;\n    int days_left;\n};\n\nvector<Task> tasks;\nvector<TeamMember> team_members;\nvector<vector<int>> task_dependencies;\nvector<int> in_degree;\nvector<int> completed_tasks;\nvector<int> available_tasks;\n\nvoid initialize(int N, int M, int K, int R) {\n    tasks.resize(N);\n    team_members.resize(M);\n    task_dependencies.resize(N);\n    in_degree.resize(N, 0);\n    completed_tasks.resize(N, 0);\n    available_tasks.resize(N, 0);\n\n    for (int i = 0; i < N; ++i) {\n        tasks[i].required_skills.resize(K);\n        tasks[i].dependencies.clear();\n        tasks[i].duration = 0;\n        tasks[i].completed = false;\n    }\n\n    for (int i = 0; i < M; ++i) {\n        team_members[i].skills.resize(K, 0);\n        team_members[i].current_task = -1;\n        team_members[i].days_left = 0;\n    }\n\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        task_dependencies[u - 1].push_back(v - 1);\n        in_degree[v - 1]++;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        if (in_degree[i] == 0) {\n            available_tasks[i] = 1;\n        }\n    }\n}\n\nvoid update_skills(int member, const vector<int>& completed_tasks) {\n    for (int task : completed_tasks) {\n        for (int k = 0; k < team_members[member].skills.size(); ++k) {\n            team_members[member].skills[k] = max(team_members[member].skills[k], tasks[task].required_skills[k]);\n        }\n    }\n}\n\nint calculate_duration(int task, int member) {\n    int w = 0;\n    for (int k = 0; k < tasks[task].required_skills.size(); ++k) {\n        w += max(0, tasks[task].required_skills[k] - team_members[member].skills[k]);\n    }\n\n    if (w == 0) {\n        return 1;\n    } else {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(-3, 3);\n        int r = dis(gen);\n        return max(1, w + r);\n    }\n}\n\nvoid assign_tasks() {\n    vector<pair<int, int>> assignments;\n\n    for (int i = 0; i < team_members.size(); ++i) {\n        if (team_members[i].current_task == -1) {\n            for (int j = 0; j < tasks.size(); ++j) {\n                if (available_tasks[j] && !tasks[j].completed) {\n                    int duration = calculate_duration(j, i);\n                    if (duration < tasks[j].duration || tasks[j].duration == 0) {\n                        tasks[j].duration = duration;\n                        team_members[i].current_task = j;\n                        team_members[i].days_left = duration;\n                        assignments.emplace_back(i + 1, j + 1);\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    cout << assignments.size();\n    for (const auto& assignment : assignments) {\n        cout << \" \" << assignment.first << \" \" << assignment.second;\n    }\n    cout << endl;\n    cout.flush();\n}\n\nvoid process_completed_tasks(const vector<int>& completed_members) {\n    vector<int> completed_tasks;\n\n    for (int member : completed_members) {\n        int task = team_members[member - 1].current_task;\n        if (task != -1) {\n            tasks[task].completed = true;\n            completed_tasks.push_back(task);\n            team_members[member - 1].current_task = -1;\n            team_members[member - 1].days_left = 0;\n        }\n    }\n\n    for (int task : completed_tasks) {\n        for (int dependent_task : task_dependencies[task]) {\n            in_degree[dependent_task]--;\n            if (in_degree[dependent_task] == 0) {\n                available_tasks[dependent_task] = 1;\n            }\n        }\n    }\n\n    for (int member : completed_members) {\n        update_skills(member - 1, completed_tasks);\n    }\n}\n\nint main() {\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    initialize(N, M, K, R);\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> tasks[i].required_skills[j];\n        }\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n        assign_tasks();\n\n        int n;\n        cin >> n;\n        if (n == -1) {\n            break;\n        }\n\n        vector<int> completed_members(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> completed_members[i];\n        }\n\n        process_completed_tasks(completed_members);\n\n        if (all_of(tasks.begin(), tasks.end(), [](const Task& task) { return task.completed; })) {\n            break;\n        }\n\n        if (day >= 2000) {\n            break;\n        }\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <unordered_set>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nstruct Order {\n    Point restaurant;\n    Point destination;\n    Order(Point restaurant, Point destination) : restaurant(restaurant), destination(destination) {}\n};\n\nstruct Individual {\n    vector<int> orders;\n    vector<Point> route;\n    int fitness;\n};\n\nint manhattanDistance(const Point& a, const Point& b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nint calculateFitness(const Individual& individual, const vector<Order>& allOrders) {\n    int totalDistance = 0;\n    unordered_set<int> selectedOrders(individual.orders.begin(), individual.orders.end());\n\n    // Check if the route starts and ends at the office\n    if (individual.route.front() != Point(400, 400) || individual.route.back() != Point(400, 400)) {\n        return INT_MAX;\n    }\n\n    // Check if all selected orders are visited in the correct order\n    for (int i = 0; i < individual.orders.size(); ++i) {\n        int orderIndex = individual.orders[i];\n        const Order& order = allOrders[orderIndex];\n        bool restaurantVisited = false;\n        bool destinationVisited = false;\n\n        for (int j = 0; j < individual.route.size(); ++j) {\n            if (individual.route[j] == order.restaurant) {\n                restaurantVisited = true;\n            }\n            if (individual.route[j] == order.destination) {\n                if (!restaurantVisited) {\n                    return INT_MAX;\n                }\n                destinationVisited = true;\n            }\n        }\n\n        if (!restaurantVisited || !destinationVisited) {\n            return INT_MAX;\n        }\n    }\n\n    // Calculate total travel time\n    for (int i = 0; i < individual.route.size() - 1; ++i) {\n        totalDistance += manhattanDistance(individual.route[i], individual.route[i + 1]);\n    }\n\n    return totalDistance;\n}\n\nvector<Individual> initializePopulation(int populationSize, const vector<Order>& allOrders) {\n    vector<Individual> population;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n\n    for (int i = 0; i < populationSize; ++i) {\n        Individual individual;\n        unordered_set<int> selectedOrders;\n\n        // Select 50 unique orders\n        while (selectedOrders.size() < 50) {\n            int orderIndex = orderDist(gen);\n            selectedOrders.insert(orderIndex);\n        }\n\n        individual.orders.assign(selectedOrders.begin(), selectedOrders.end());\n\n        // Generate a random route\n        vector<Point> route;\n        route.push_back(Point(400, 400)); // Start at the office\n\n        for (int orderIndex : individual.orders) {\n            const Order& order = allOrders[orderIndex];\n            route.push_back(order.restaurant);\n            route.push_back(order.destination);\n        }\n\n        route.push_back(Point(400, 400)); // End at the office\n\n        individual.route = route;\n        individual.fitness = calculateFitness(individual, allOrders);\n        population.push_back(individual);\n    }\n\n    return population;\n}\n\nIndividual selectParent(const vector<Individual>& population) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dist(0, population.size() - 1);\n\n    int index1 = dist(gen);\n    int index2 = dist(gen);\n\n    return population[index1].fitness < population[index2].fitness ? population[index1] : population[index2];\n}\n\nIndividual crossover(const Individual& parent1, const Individual& parent2, const vector<Order>& allOrders) {\n    Individual child;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dist(0, 49);\n\n    // Select a random subset of orders from parent1\n    unordered_set<int> selectedOrders(parent1.orders.begin(), parent1.orders.begin() + dist(gen));\n\n    // Add the remaining orders from parent2\n    for (int orderIndex : parent2.orders) {\n        if (selectedOrders.size() >= 50) break;\n        if (selectedOrders.find(orderIndex) == selectedOrders.end()) {\n            selectedOrders.insert(orderIndex);\n        }\n    }\n\n    child.orders.assign(selectedOrders.begin(), selectedOrders.end());\n\n    // Generate a random route\n    vector<Point> route;\n    route.push_back(Point(400, 400)); // Start at the office\n\n    for (int orderIndex : child.orders) {\n        const Order& order = allOrders[orderIndex];\n        route.push_back(order.restaurant);\n        route.push_back(order.destination);\n    }\n\n    route.push_back(Point(400, 400)); // End at the office\n\n    child.route = route;\n    child.fitness = calculateFitness(child, allOrders);\n\n    return child;\n}\n\nvoid mutate(Individual& individual, const vector<Order>& allOrders) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n    uniform_int_distribution<> mutationDist(0, 1);\n\n    // Mutate orders\n    for (int& orderIndex : individual.orders) {\n        if (mutationDist(gen) == 0) {\n            orderIndex = orderDist(gen);\n        }\n    }\n\n    // Mutate route\n    for (int i = 1; i < individual.route.size() - 1; ++i) {\n        if (mutationDist(gen) == 0) {\n            int j = uniform_int_distribution<>(1, individual.route.size() - 2)(gen);\n            swap(individual.route[i], individual.route[j]);\n        }\n    }\n\n    individual.fitness = calculateFitness(individual, allOrders);\n}\n\nvector<Individual> evolvePopulation(vector<Individual>& population, const vector<Order>& allOrders) {\n    vector<Individual> newPopulation;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> mutationRate(0.0, 1.0);\n\n    for (int i = 0; i < population.size(); ++i) {\n        Individual parent1 = selectParent(population);\n        Individual parent2 = selectParent(population);\n        Individual child = crossover(parent1, parent2, allOrders);\n\n        if (mutationRate(gen) < 0.1) {\n            mutate(child, allOrders);\n        }\n\n        newPopulation.push_back(child);\n    }\n\n    return newPopulation;\n}\n\nint main() {\n    vector<Order> allOrders;\n    for (int i = 0; i < 1000; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        allOrders.emplace_back(Point(a, b), Point(c, d));\n    }\n\n    const int populationSize = 100;\n    const int generations = 1000;\n\n    vector<Individual> population = initializePopulation(populationSize, allOrders);\n\n    for (int generation = 0; generation < generations; ++generation) {\n        population = evolvePopulation(population, allOrders);\n\n        // Find the best individual in the current population\n        Individual bestIndividual = *min_element(population.begin(), population.end(),\n            [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; });\n\n        cout << \"Generation \" << generation << \": Best Fitness = \" << bestIndividual.fitness << endl;\n    }\n\n    // Find the best individual in the final population\n    Individual bestIndividual = *min_element(population.begin(), population.end(),\n        [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; });\n\n    // Output the best solution\n    cout << bestIndividual.orders.size() << \" \";\n    for (int orderIndex : bestIndividual.orders) {\n        cout << orderIndex + 1 << \" \";\n    }\n    cout << endl;\n\n    cout << bestIndividual.route.size() << \" \";\n    for (const Point& point : bestIndividual.route) {\n        cout << point.x << \" \" << point.y << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <atcoder/dsu>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v;\n    double d; // Euclidean distance rounded to the nearest integer\n    int index; // Original index to keep track of the order\n};\n\nint main() {\n    int N = 400;\n    int M = 1995;\n\n    vector<pair<int, int>> coordinates(N);\n    vector<Edge> edges(M);\n\n    // Read coordinates\n    for (int i = 0; i < N; ++i) {\n        cin >> coordinates[i].first >> coordinates[i].second;\n    }\n\n    // Read edges and compute d_i\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        edges[i].index = i;\n        int dx = coordinates[edges[i].u].first - coordinates[edges[i].v].first;\n        int dy = coordinates[edges[i].u].second - coordinates[edges[i].v].second;\n        edges[i].d = round(sqrt(dx * dx + dy * dy));\n    }\n\n    // Sort edges by d_i in ascending order\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.d < b.d;\n    });\n\n    dsu uf(N);\n    vector<bool> adopted(M, false);\n\n    // Process edges in order of increasing d_i\n    for (const Edge& edge : edges) {\n        int l;\n        cin >> l;\n        if (!uf.same(edge.u, edge.v)) {\n            uf.merge(edge.u, edge.v);\n            adopted[edge.index] = true;\n            cout << \"1\" << endl;\n        } else {\n            cout << \"0\" << endl;\n        }\n        cout.flush();\n    }\n\n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n#include <cmath>\n#include <unordered_set>\n#include <map>\n#include <cassert>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int TURNS = 300;\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nstruct GridState {\n    vector<vector<bool>> passable;\n    vector<Pet> pets;\n    vector<Human> humans;\n};\n\nvector<vector<int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nvector<vector<int>> bfs(const GridState& state, int startX, int startY) {\n    vector<vector<int>> distance(GRID_SIZE, vector<int>(GRID_SIZE, -1));\n    queue<pair<int, int>> q;\n    q.push({startX, startY});\n    distance[startX][startY] = 0;\n\n    while (!q.empty()) {\n        auto current = q.front();\n        int x = current.first;\n        int y = current.second;\n        q.pop();\n\n        for (size_t i = 0; i < directions.size(); ++i) {\n            int dx = directions[i][0];\n            int dy = directions[i][1];\n            int nx = x + dx;\n            int ny = y + dy;\n            if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny] && distance[nx][ny] == -1) {\n                distance[nx][ny] = distance[x][y] + 1;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return distance;\n}\n\nvector<pair<int, int>> findReachableArea(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    auto distance = bfs(state, hx, hy);\n    vector<pair<int, int>> reachableArea;\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (distance[i][j] != -1) {\n                reachableArea.emplace_back(i, j);\n            }\n        }\n    }\n    return reachableArea;\n}\n\nint countPetsInArea(const GridState& state, const vector<pair<int, int>>& area) {\n    unordered_set<string> petPositions;\n    for (const auto& pet : state.pets) {\n        petPositions.insert(to_string(pet.x) + \",\" + to_string(pet.y));\n    }\n    int count = 0;\n    for (const auto& pos : area) {\n        int x = pos.first;\n        int y = pos.second;\n        if (petPositions.count(to_string(x) + \",\" + to_string(y))) {\n            count++;\n        }\n    }\n    return count;\n}\n\ndouble calculateSatisfaction(const GridState& state, int humanIndex) {\n    auto reachableArea = findReachableArea(state, humanIndex);\n    int areaSize = reachableArea.size();\n    int petCount = countPetsInArea(state, reachableArea);\n    return (areaSize / 900.0) * pow(2, -petCount);\n}\n\nbool isSquareSafeToBlock(const GridState& state, int x, int y) {\n    for (const auto& pet : state.pets) {\n        if (pet.x == x && pet.y == y) {\n            return false;\n        }\n    }\n    for (size_t i = 0; i < directions.size(); ++i) {\n        int dx = directions[i][0];\n        int dy = directions[i][1];\n        int nx = x + dx;\n        int ny = y + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE) {\n            for (const auto& pet : state.pets) {\n                if (pet.x == nx && pet.y == ny) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nvector<pair<int, int>> findBestSquareToBlock(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    vector<pair<int, int>> candidates;\n    for (size_t i = 0; i < directions.size(); ++i) {\n        int dx = directions[i][0];\n        int dy = directions[i][1];\n        int nx = hx + dx;\n        int ny = hy + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny] && isSquareSafeToBlock(state, nx, ny)) {\n            candidates.emplace_back(nx, ny);\n        }\n    }\n    if (candidates.empty()) {\n        return {};\n    }\n    vector<double> scores;\n    for (const auto& candidate : candidates) {\n        int nx = candidate.first;\n        int ny = candidate.second;\n        GridState newState = state;\n        newState.passable[nx][ny] = false;\n        auto reachableArea = findReachableArea(newState, humanIndex);\n        int areaSize = reachableArea.size();\n        int petCount = countPetsInArea(newState, reachableArea);\n        scores.push_back((areaSize / 900.0) * pow(2, -petCount));\n    }\n    int bestIndex = max_element(scores.begin(), scores.end()) - scores.begin();\n    return {candidates[bestIndex]};\n}\n\nvector<pair<int, int>> findBestMove(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    vector<pair<int, int>> candidates;\n    for (size_t i = 0; i < directions.size(); ++i) {\n        int dx = directions[i][0];\n        int dy = directions[i][1];\n        int nx = hx + dx;\n        int ny = hy + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n            candidates.emplace_back(nx, ny);\n        }\n    }\n    if (candidates.empty()) {\n        return {};\n    }\n    vector<double> scores;\n    for (const auto& candidate : candidates) {\n        int nx = candidate.first;\n        int ny = candidate.second;\n        GridState newState = state;\n        newState.humans[humanIndex] = {nx, ny};\n        auto reachableArea = findReachableArea(newState, humanIndex);\n        int areaSize = reachableArea.size();\n        int petCount = countPetsInArea(newState, reachableArea);\n        scores.push_back((areaSize / 900.0) * pow(2, -petCount));\n    }\n    int bestIndex = max_element(scores.begin(), scores.end()) - scores.begin();\n    return {candidates[bestIndex]};\n}\n\nstring decideAction(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    auto blockSquares = findBestSquareToBlock(state, humanIndex);\n    auto moveSquares = findBestMove(state, humanIndex);\n\n    double currentSatisfaction = calculateSatisfaction(state, humanIndex);\n\n    double blockSatisfaction = -1;\n    if (!blockSquares.empty()) {\n        auto blockSquare = blockSquares[0];\n        int nx = blockSquare.first;\n        int ny = blockSquare.second;\n        GridState newState = state;\n        newState.passable[nx][ny] = false;\n        blockSatisfaction = calculateSatisfaction(newState, humanIndex);\n    }\n\n    double moveSatisfaction = -1;\n    if (!moveSquares.empty()) {\n        auto moveSquare = moveSquares[0];\n        int nx = moveSquare.first;\n        int ny = moveSquare.second;\n        GridState newState = state;\n        newState.humans[humanIndex] = {nx, ny};\n        moveSatisfaction = calculateSatisfaction(newState, humanIndex);\n    }\n\n    if (blockSatisfaction > currentSatisfaction && blockSatisfaction >= moveSatisfaction) {\n        auto blockSquare = blockSquares[0];\n        int nx = blockSquare.first;\n        int ny = blockSquare.second;\n        if (nx == hx - 1 && ny == hy) return \"u\";\n        if (nx == hx + 1 && ny == hy) return \"d\";\n        if (nx == hx && ny == hy - 1) return \"l\";\n        if (nx == hx && ny == hy + 1) return \"r\";\n    } else if (moveSatisfaction > currentSatisfaction && moveSatisfaction >= blockSatisfaction) {\n        auto moveSquare = moveSquares[0];\n        int nx = moveSquare.first;\n        int ny = moveSquare.second;\n        if (nx == hx - 1 && ny == hy) return \"U\";\n        if (nx == hx + 1 && ny == hy) return \"D\";\n        if (nx == hx && ny == hy - 1) return \"L\";\n        if (nx == hx && ny == hy + 1) return \"R\";\n    }\n    return \".\";\n}\n\nvoid simulatePetMovement(GridState& state, const vector<string>& petMoves) {\n    for (size_t i = 0; i < state.pets.size(); ++i) {\n        auto& pet = state.pets[i];\n        const string& move = petMoves[i];\n        if (move == \".\") continue;\n\n        for (char c : move) {\n            int dx = 0, dy = 0;\n            if (c == 'U') dx = -1;\n            else if (c == 'D') dx = 1;\n            else if (c == 'L') dy = -1;\n            else if (c == 'R') dy = 1;\n\n            int nx = pet.x + dx;\n            int ny = pet.y + dy;\n            if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n                pet.x = nx;\n                pet.y = ny;\n            }\n        }\n    }\n}\n\nint main() {\n    int N, M;\n    cin >> N;\n    vector<Pet> pets(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    vector<Human> humans(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\n    GridState state;\n    state.passable = vector<vector<bool>>(GRID_SIZE, vector<bool>(GRID_SIZE, true));\n    state.pets = pets;\n    state.humans = humans;\n\n    for (int turn = 0; turn < TURNS; ++turn) {\n        string actions;\n        for (int i = 0; i < M; ++i) {\n            actions += decideAction(state, i);\n        }\n        cout << actions << endl;\n        cout.flush();\n\n        vector<string> petMoves(N);\n        for (int i = 0; i < N; ++i) {\n            cin >> petMoves[i];\n        }\n        simulatePetMovement(state, petMoves);\n    }\n\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <tuple>\n#include <algorithm>\n#include <cmath>\n#include <unordered_map>\n#include <map>\n#include <set>\n#include <string>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MAX_N = 20;\nconst int MAX_M = 20;\nconst int MAX_T = 200;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct State {\n    int x, y, t;\n    double prob;\n    string path;\n\n    bool operator<(const State& other) const {\n        return prob < other.prob;\n    }\n};\n\ndouble simulate(int si, int sj, int ti, int tj, double p, const string& path, const vector<string>& h, const vector<string>& v) {\n    int x = si, y = sj;\n    double prob = 1.0;\n\n    for (char c : path) {\n        if (c == 'S') {\n            prob *= p;\n            continue;\n        }\n\n        int i;\n        for (i = 0; i < 4; ++i) {\n            if (dir[i] == c) break;\n        }\n\n        int nx = x + dx[i];\n        int ny = y + dy[i];\n\n        if (nx < 0 || nx >= MAX_N || ny < 0 || ny >= MAX_M) {\n            prob *= p;\n            continue;\n        }\n\n        if (i == 0 && v[x - 1][y] == '1') {\n            prob *= p;\n            continue;\n        }\n        if (i == 1 && v[x][y] == '1') {\n            prob *= p;\n            continue;\n        }\n        if (i == 2 && h[x][y - 1] == '1') {\n            prob *= p;\n            continue;\n        }\n        if (i == 3 && h[x][y] == '1') {\n            prob *= p;\n            continue;\n        }\n\n        x = nx;\n        y = ny;\n        prob *= (1 - p);\n\n        if (x == ti && y == tj) {\n            return prob * (401 - path.size());\n        }\n    }\n\n    return 0.0;\n}\n\nstring generate_random_path(int length) {\n    static random_device rd;\n    static mt19937 gen(rd());\n    static uniform_int_distribution<> dis(0, 3);\n\n    string path;\n    for (int i = 0; i < length; ++i) {\n        path += dir[dis(gen)];\n    }\n    return path;\n}\n\nstring monte_carlo_simulation(int si, int sj, int ti, int tj, double p, const vector<string>& h, const vector<string>& v, int iterations = 1000) {\n    string best_path;\n    double max_score = 0.0;\n\n    for (int i = 0; i < iterations; ++i) {\n        string path = generate_random_path(200);\n        double score = simulate(si, sj, ti, tj, p, path, h, v);\n\n        if (score > max_score) {\n            max_score = score;\n            best_path = path;\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    vector<string> h(MAX_N), v(MAX_N);\n\n    cin >> si >> sj >> ti >> tj >> p;\n    for (int i = 0; i < MAX_N; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < MAX_N; ++i) {\n        cin >> v[i];\n    }\n\n    string best_path = monte_carlo_simulation(si, sj, ti, tj, p, h, v);\n\n    cout << best_path << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <unordered_set>\n#include <queue>\n#include <tuple>\n#include <thread>\n#include <mutex>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int POPULATION_SIZE = 50;\nconst int MAX_GENERATIONS = 50;\nconst double MUTATION_RATE = 0.1;\nconst double CROSSOVER_RATE = 0.7;\n\nvector<vector<int>> tiles(GRID_SIZE, vector<int>(GRID_SIZE));\nvector<vector<int>> rotations(GRID_SIZE, vector<int>(GRID_SIZE));\n\n// Directions: left, up, right, down\nconst int di[] = {0, -1, 0, 1};\nconst int dj[] = {-1, 0, 1, 0};\n\n// Transition table for tile types and directions\nconst vector<vector<int>> to = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\n\nmutex mtx;\n\nint simple_fitness_function() {\n    int connected_tiles = 0;\n    vector<vector<vector<bool>>> visited(GRID_SIZE, vector<vector<bool>>(GRID_SIZE, vector<bool>(4, false)));\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            for (int d = 0; d < 4; ++d) {\n                if (!visited[i][j][d]) {\n                    int d2 = to[tiles[i][j]][d];\n                    if (d2 != -1) {\n                        int ni = i + di[d2];\n                        int nj = j + dj[d2];\n                        if (ni >= 0 && ni < GRID_SIZE && nj >= 0 && nj < GRID_SIZE) {\n                            connected_tiles++;\n                            visited[i][j][d] = true;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    return connected_tiles;\n}\n\nvoid initialize_population(vector<vector<vector<int>>>& population) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                population[p][i][j] = dis(gen);\n            }\n        }\n    }\n}\n\nvoid mutate(vector<vector<int>>& individual) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> rot_dis(0, 3);\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (dis(gen) < MUTATION_RATE) {\n                individual[i][j] = rot_dis(gen);\n            }\n        }\n    }\n}\n\nvector<vector<int>> crossover(const vector<vector<int>>& parent1, const vector<vector<int>>& parent2) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> row_dis(0, GRID_SIZE - 1);\n    uniform_int_distribution<> col_dis(0, GRID_SIZE - 1);\n\n    vector<vector<int>> child(GRID_SIZE, vector<int>(GRID_SIZE));\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (dis(gen) < CROSSOVER_RATE) {\n                child[i][j] = parent1[i][j];\n            } else {\n                child[i][j] = parent2[i][j];\n            }\n        }\n    }\n\n    return child;\n}\n\nvoid evaluate_fitness(vector<vector<vector<int>>>& population, vector<int>& fitness_scores) {\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        rotations = population[p];\n        fitness_scores[p] = simple_fitness_function();\n    }\n}\n\nvoid genetic_algorithm() {\n    vector<vector<vector<int>>> population(POPULATION_SIZE, vector<vector<int>>(GRID_SIZE, vector<int>(GRID_SIZE)));\n    initialize_population(population);\n\n    vector<int> fitness_scores(POPULATION_SIZE);\n    evaluate_fitness(population, fitness_scores);\n\n    for (int gen = 0; gen < MAX_GENERATIONS; ++gen) {\n        vector<vector<vector<int>>> new_population;\n        for (int p = 0; p < POPULATION_SIZE; ++p) {\n            int parent1_idx = distance(fitness_scores.begin(), max_element(fitness_scores.begin(), fitness_scores.end()));\n            fitness_scores[parent1_idx] = -1;\n            int parent2_idx = distance(fitness_scores.begin(), max_element(fitness_scores.begin(), fitness_scores.end()));\n            fitness_scores[parent2_idx] = -1;\n\n            vector<vector<int>> child = crossover(population[parent1_idx], population[parent2_idx]);\n            mutate(child);\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n        evaluate_fitness(population, fitness_scores);\n    }\n\n    // Find the best solution\n    int best_fitness = -1;\n    vector<vector<int>> best_rotations;\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        rotations = population[p];\n        int current_fitness = simple_fitness_function();\n        if (current_fitness > best_fitness) {\n            best_fitness = current_fitness;\n            best_rotations = population[p];\n        }\n    }\n\n    rotations = best_rotations;\n}\n\nint main() {\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            tiles[i][j] = row[j] - '0';\n        }\n    }\n\n    genetic_algorithm();\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            cout << rotations[i][j];\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\n\nstruct State {\n    vector<vector<int>> board;\n    pair<int, int> empty;\n    int cost;\n    int heuristic;\n\n    bool operator==(const State& other) const {\n        return board == other.board && empty == other.empty;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<State> {\n        size_t operator()(const State& state) const {\n            size_t seed = 0;\n            for (const auto& row : state.board) {\n                for (int tile : row) {\n                    seed ^= hash<int>{}(tile) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n                }\n            }\n            seed ^= hash<int>{}(state.empty.first) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            seed ^= hash<int>{}(state.empty.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            return seed;\n        }\n    };\n}\n\nint calculate_heuristic(const vector<vector<int>>& board, int N) {\n    dsu_union_find uf(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0) continue;\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N || board[ni][nj] == 0) continue;\n                if ((board[i][j] & (1 << k)) && (board[ni][nj] & (1 << ((k + 2) % 4)))) {\n                    uf.merge(i * N + j, ni * N + nj);\n                }\n            }\n        }\n    }\n    unordered_set<int> roots;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] != 0) {\n                roots.insert(uf.leader(i * N + j));\n            }\n        }\n    }\n    return roots.size();\n}\n\nvector<State> get_neighbors(const State& state, int N) {\n    vector<State> neighbors;\n    int x = state.empty.first;\n    int y = state.empty.second;\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + dx[i];\n        int ny = y + dy[i];\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n        State neighbor = state;\n        neighbor.board[x][y] = neighbor.board[nx][ny];\n        neighbor.board[nx][ny] = 0;\n        neighbor.empty = {nx, ny};\n        neighbor.cost = state.cost + 1;\n        neighbor.heuristic = calculate_heuristic(neighbor.board, N);\n        neighbors.push_back(neighbor);\n    }\n    return neighbors;\n}\n\nstring a_star_search(State initial, int N, int T) {\n    auto cmp = [](const State& a, const State& b) {\n        return a.cost + a.heuristic > b.cost + b.heuristic;\n    };\n    priority_queue<State, vector<State>, decltype(cmp)> open(cmp);\n    unordered_set<State> closed;\n    open.push(initial);\n    while (!open.empty()) {\n        State current = open.top();\n        open.pop();\n        if (current.heuristic == 1) {\n            return \"\"; // Reached the goal\n        }\n        if (closed.count(current)) continue;\n        closed.insert(current);\n        for (const State& neighbor : get_neighbors(current, N)) {\n            if (!closed.count(neighbor)) {\n                open.push(neighbor);\n            }\n        }\n    }\n    return \"\"; // No solution found\n}\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    pair<int, int> empty;\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            char c = row[j];\n            if (c >= '0' && c <= '9') {\n                board[i][j] = c - '0';\n            } else {\n                board[i][j] = 10 + (c - 'a');\n            }\n            if (board[i][j] == 0) {\n                empty = {i, j};\n            }\n        }\n    }\n    State initial = {board, empty, 0, calculate_heuristic(board, N)};\n    string solution = a_star_search(initial, N, T);\n    cout << solution << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <limits>\n#include <unordered_set>\n#include <utility>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct Line {\n    Point p, q;\n    Line(Point p, Point q) : p(p), q(q) {}\n    bool operator==(const Line& other) const {\n        return (p == other.p && q == other.q) || (p == other.q && q == other.p);\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Line> {\n        size_t operator()(const Line& l) const {\n            return hash<Point>()(l.p) ^ hash<Point>()(l.q);\n        }\n    };\n}\n\nstruct Strawberry {\n    int x, y;\n    Strawberry(int x, int y) : x(x), y(y) {}\n};\n\nvector<Strawberry> strawberries;\nvector<int> a_d(10);\nint K;\n\ndouble distance(const Point& p1, const Point& p2) {\n    return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));\n}\n\nbool isInside(const Point& p, const Line& line) {\n    // Check if point p is inside the cake and not cut by the line\n    if (distance(p, Point(0, 0)) >= 10000) {\n        return false;\n    }\n    // Check if the point is on the line\n    int x1 = line.p.x, y1 = line.p.y;\n    int x2 = line.q.x, y2 = line.q.y;\n    int x = p.x, y = p.y;\n    if ((y2 - y1) * (x - x1) == (y - y1) * (x2 - x1)) {\n        return false;\n    }\n    return true;\n}\n\nint countPieces(const vector<Line>& lines, int d) {\n    vector<vector<bool>> inside(strawberries.size(), vector<bool>(lines.size() + 1, true));\n    for (int i = 0; i < lines.size(); ++i) {\n        for (int j = 0; j < strawberries.size(); ++j) {\n            if (!isInside(Point(strawberries[j].x, strawberries[j].y), lines[i])) {\n                inside[j][i + 1] = false;\n            }\n        }\n    }\n    int count = 0;\n    for (int i = 0; i < strawberries.size(); ++i) {\n        int c = 0;\n        for (int j = 0; j <= lines.size(); ++j) {\n            if (inside[i][j]) {\n                c++;\n            }\n        }\n        if (c == d) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvector<Line> minimalLineGeneration() {\n    vector<Line> lines;\n    unordered_set<Line> uniqueLines;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(-1e9, 1e9);\n\n    // Generate lines through pairs of strawberries\n    for (int i = 0; i < min(10, (int)strawberries.size()); ++i) {\n        for (int j = i + 1; j < min(10, (int)strawberries.size()); ++j) {\n            Point p(strawberries[i].x, strawberries[i].y);\n            Point q(strawberries[j].x, strawberries[j].y);\n            Line line(p, q);\n            if (uniqueLines.find(line) == uniqueLines.end()) {\n                uniqueLines.insert(line);\n                lines.push_back(line);\n            }\n        }\n    }\n\n    // Generate random lines\n    for (int i = 0; i < 10; ++i) {\n        Point p(dis(gen), dis(gen));\n        Point q(dis(gen), dis(gen));\n        Line line(p, q);\n        if (uniqueLines.find(line) == uniqueLines.end()) {\n            uniqueLines.insert(line);\n            lines.push_back(line);\n        }\n    }\n\n    return lines;\n}\n\nvector<Line> minimalGreedyAlgorithm() {\n    vector<Line> lines;\n    vector<Line> candidateLines = minimalLineGeneration();\n\n    for (int d = 1; d <= 10; ++d) {\n        if (a_d[d - 1] == 0) continue;\n        int maxPieces = 0;\n        Line bestLine(Point(0, 0), Point(0, 0));\n        for (const auto& line : candidateLines) {\n            vector<Line> tempLines = lines;\n            tempLines.push_back(line);\n            int pieces = countPieces(tempLines, d);\n            if (pieces > maxPieces) {\n                maxPieces = pieces;\n                bestLine = line;\n            }\n        }\n        if (maxPieces > 0) {\n            lines.push_back(bestLine);\n            if (lines.size() >= K) break;\n        }\n    }\n    return lines;\n}\n\nint main() {\n    int N;\n    cin >> N >> K;\n    for (int i = 0; i < 10; ++i) {\n        cin >> a_d[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        strawberries.emplace_back(x, y);\n    }\n    vector<Line> lines = minimalGreedyAlgorithm();\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line.p.x << \" \" << line.p.y << \" \" << line.q.x << \" \" << line.q.y << endl;\n    }\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n#include <unordered_set>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nclass RectJoinGame {\nprivate:\n    int N, M;\n    unordered_set<Point> dots;\n    vector<Rectangle> rectangles;\n    int c;\n    double S;\n    mt19937 rng;\n\n    double weight(int x, int y) {\n        return (x - c) * (x - c) + (y - c) * (y - c) + 1;\n    }\n\n    bool isValidRectangle(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        // Check if the points form a valid rectangle (axis-aligned or 45-degree)\n        int dx1 = p2.x - p1.x;\n        int dy1 = p2.y - p1.y;\n        int dx2 = p3.x - p2.x;\n        int dy2 = p3.y - p2.y;\n        int dx3 = p4.x - p3.x;\n        int dy3 = p4.y - p3.y;\n        int dx4 = p1.x - p4.x;\n        int dy4 = p1.y - p4.y;\n\n        // Check if the sides are equal and perpendicular\n        if ((dx1 == dx3 && dy1 == dy3) && (dx2 == dx4 && dy2 == dy4) &&\n            (dx1 * dx2 + dy1 * dy2 == 0)) {\n            // Check if the rectangle is axis-aligned or 45-degree\n            if ((dx1 == 0 || dy1 == 0 || abs(dx1) == abs(dy1)) &&\n                (dx2 == 0 || dy2 == 0 || abs(dx2) == abs(dy2))) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    bool isValidOperation(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        if (dots.count(p1)) return false;\n        if (!dots.count(p2) || !dots.count(p3) || !dots.count(p4)) return false;\n        if (!isValidRectangle(p1, p2, p3, p4)) return false;\n\n        // Check if the perimeter of the rectangle contains any other dots\n        set<Point> perimeter;\n        int dx = p2.x - p1.x;\n        int dy = p2.y - p1.y;\n        for (int i = 0; i <= 1; ++i) {\n            for (int j = 0; j <= 1; ++j) {\n                int x = p1.x + i * dx;\n                int y = p1.y + i * dy;\n                for (int k = 0; k <= 1; ++k) {\n                    int nx = x + k * dy;\n                    int ny = y - k * dx;\n                    perimeter.insert(Point(nx, ny));\n                }\n            }\n        }\n        for (const auto& p : perimeter) {\n            if (dots.count(p) && !(p == p1 || p == p2 || p == p3 || p == p4)) {\n                return false;\n            }\n        }\n\n        // Check if the perimeter of the rectangle shares a common segment with any previously drawn rectangle\n        for (const auto& rect : rectangles) {\n            set<Point> rectPerimeter;\n            int rdx = rect.p2.x - rect.p1.x;\n            int rdy = rect.p2.y - rect.p1.y;\n            for (int i = 0; i <= 1; ++i) {\n                for (int j = 0; j <= 1; ++j) {\n                    int x = rect.p1.x + i * rdx;\n                    int y = rect.p1.y + i * rdy;\n                    for (int k = 0; k <= 1; ++k) {\n                        int nx = x + k * rdy;\n                        int ny = y - k * rdx;\n                        rectPerimeter.insert(Point(nx, ny));\n                    }\n                }\n            }\n            set<Point> intersection;\n            set_intersection(perimeter.begin(), perimeter.end(), rectPerimeter.begin(), rectPerimeter.end(), inserter(intersection, intersection.begin()));\n            if (intersection.size() > 2) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    double calculateScore() {\n        double sum = 0;\n        for (const auto& p : dots) {\n            sum += weight(p.x, p.y);\n        }\n        return round(1e6 * N * N / M * sum / S);\n    }\n\n    vector<Point> getNeighbors(const Point& p) {\n        vector<Point> neighbors;\n        for (int dx = -1; dx <= 1; ++dx) {\n            for (int dy = -1; dy <= 1; ++dy) {\n                if (dx == 0 && dy == 0) continue;\n                int nx = p.x + dx;\n                int ny = p.y + dy;\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N) {\n                    neighbors.emplace_back(nx, ny);\n                }\n            }\n        }\n        return neighbors;\n    }\n\n    pair<Point, vector<Point>> findBestOperation() {\n        double bestScore = -1;\n        Point bestP1(-1, -1); // Initialize with default values\n        vector<Point> bestP234;\n\n        for (const auto& p1 : dots) {\n            auto neighbors = getNeighbors(p1);\n            for (const auto& p2 : neighbors) {\n                if (!dots.count(p2)) continue;\n                for (const auto& p3 : neighbors) {\n                    if (!dots.count(p3) || p3 == p2) continue;\n                    for (const auto& p4 : neighbors) {\n                        if (!dots.count(p4) || p4 == p2 || p4 == p3) continue;\n                        if (isValidOperation(p1, p2, p3, p4)) {\n                            dots.insert(p1);\n                            rectangles.emplace_back(p1, p2, p3, p4);\n                            double score = calculateScore();\n                            dots.erase(p1);\n                            rectangles.pop_back();\n                            if (score > bestScore) {\n                                bestScore = score;\n                                bestP1 = p1;\n                                bestP234 = {p2, p3, p4};\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        return {bestP1, bestP234};\n    }\n\n    void simulatedAnnealing(double initialTemp, double finalTemp, double alpha) {\n        double temp = initialTemp;\n        auto currentScore = calculateScore();\n        auto bestScore = currentScore;\n        vector<Rectangle> bestRectangles = rectangles;\n\n        while (temp > finalTemp) {\n            auto [p1, p234] = findBestOperation();\n            if (p234.empty()) break;\n\n            dots.insert(p1);\n            rectangles.emplace_back(p1, p234[0], p234[1], p234[2]);\n            auto newScore = calculateScore();\n\n            if (newScore > currentScore || exp((newScore - currentScore) / temp) > uniform_real_distribution<double>(0, 1)(rng)) {\n                currentScore = newScore;\n                if (newScore > bestScore) {\n                    bestScore = newScore;\n                    bestRectangles = rectangles;\n                }\n            } else {\n                dots.erase(p1);\n                rectangles.pop_back();\n            }\n\n            temp *= alpha;\n        }\n\n        rectangles = bestRectangles;\n    }\n\npublic:\n    RectJoinGame(int N, int M, const vector<Point>& initialDots) : N(N), M(M), dots(initialDots.begin(), initialDots.end()), c((N - 1) / 2), rng(chrono::steady_clock::now().time_since_epoch().count()) {\n        S = 0;\n        for (int x = 0; x < N; ++x) {\n            for (int y = 0; y < N; ++y) {\n                S += weight(x, y);\n            }\n        }\n    }\n\n    void play() {\n        simulatedAnnealing(1000, 0.1, 0.99);\n    }\n\n    void output() const {\n        cout << rectangles.size() << endl;\n        for (const auto& rect : rectangles) {\n            cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n                 << rect.p2.x << \" \" << rect.p2.y << \" \"\n                 << rect.p3.x << \" \" << rect.p3.y << \" \"\n                 << rect.p4.x << \" \" << rect.p4.y << endl;\n        }\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<Point> initialDots;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        initialDots.emplace_back(x, y);\n    }\n\n    RectJoinGame game(N, M, initialDots);\n    game.play();\n    game.output();\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <array>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <queue>\n#include <unordered_map>\n\nusing namespace std;\n\nconst int GRID_SIZE = 10;\nconst int NUM_FLAVORS = 3;\nconst int NUM_CANDIES = 100;\nconst int LOOKAHEAD_STEPS = 3;\nconst int NUM_SIMULATIONS = 5;\n\nenum Direction { FORWARD, BACKWARD, LEFT, RIGHT };\n\nstruct Candy {\n    int flavor;\n    int row;\n    int col;\n};\n\nstruct Grid {\n    array<array<int, GRID_SIZE>, GRID_SIZE> cells;\n    vector<Candy> candies;\n\n    Grid() {\n        for (auto& row : cells) {\n            fill(row.begin(), row.end(), 0);\n        }\n    }\n\n    void place_candy(int flavor, int row, int col) {\n        cells[row][col] = flavor;\n        candies.push_back({flavor, row, col});\n    }\n\n    void tilt(Direction dir) {\n        switch (dir) {\n            case FORWARD:\n                tilt_forward();\n                break;\n            case BACKWARD:\n                tilt_backward();\n                break;\n            case LEFT:\n                tilt_left();\n                break;\n            case RIGHT:\n                tilt_right();\n                break;\n        }\n    }\n\n    void tilt_forward() {\n        for (int col = 0; col < GRID_SIZE; ++col) {\n            int empty_row = GRID_SIZE - 1;\n            for (int row = GRID_SIZE - 1; row >= 0; --row) {\n                if (cells[row][col] != 0) {\n                    cells[empty_row][col] = cells[row][col];\n                    if (empty_row != row) {\n                        cells[row][col] = 0;\n                    }\n                    --empty_row;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_backward() {\n        for (int col = 0; col < GRID_SIZE; ++col) {\n            int empty_row = 0;\n            for (int row = 0; row < GRID_SIZE; ++row) {\n                if (cells[row][col] != 0) {\n                    cells[empty_row][col] = cells[row][col];\n                    if (empty_row != row) {\n                        cells[row][col] = 0;\n                    }\n                    ++empty_row;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_left() {\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            int empty_col = 0;\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0) {\n                    cells[row][empty_col] = cells[row][col];\n                    if (empty_col != col) {\n                        cells[row][col] = 0;\n                    }\n                    ++empty_col;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_right() {\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            int empty_col = GRID_SIZE - 1;\n            for (int col = GRID_SIZE - 1; col >= 0; --col) {\n                if (cells[row][col] != 0) {\n                    cells[row][empty_col] = cells[row][col];\n                    if (empty_col != col) {\n                        cells[row][col] = 0;\n                    }\n                    --empty_col;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void update_candies() {\n        candies.clear();\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0) {\n                    candies.push_back({cells[row][col], row, col});\n                }\n            }\n        }\n    }\n\n    int calculate_score() {\n        array<int, NUM_FLAVORS + 1> flavor_counts = {0};\n        for (const auto& candy : candies) {\n            flavor_counts[candy.flavor]++;\n        }\n\n        int sum_squares = 0;\n        for (int i = 1; i <= NUM_FLAVORS; ++i) {\n            sum_squares += flavor_counts[i] * flavor_counts[i];\n        }\n\n        array<array<bool, GRID_SIZE>, GRID_SIZE> visited = {false};\n        int connectivity = 0;\n\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0 && !visited[row][col]) {\n                    int flavor = cells[row][col];\n                    int component_size = 0;\n                    vector<pair<int, int>> stack = {{row, col}};\n                    visited[row][col] = true;\n\n                    while (!stack.empty()) {\n                        auto [r, c] = stack.back();\n                        stack.pop_back();\n                        component_size++;\n\n                        for (const auto& [dr, dc] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                            int nr = r + dr;\n                            int nc = c + dc;\n                            if (nr >= 0 && nr < GRID_SIZE && nc >= 0 && nc < GRID_SIZE && cells[nr][nc] == flavor && !visited[nr][nc]) {\n                                visited[nr][nc] = true;\n                                stack.emplace_back(nr, nc);\n                            }\n                        }\n                    }\n\n                    connectivity += component_size * component_size;\n                }\n            }\n        }\n\n        return round(1e6 * static_cast<double>(connectivity) / sum_squares);\n    }\n};\n\nDirection choose_direction(const Grid& grid, int flavor, const vector<int>& remaining_flavors) {\n    array<int, 4> scores = {0};\n    array<Grid, 4> grids;\n\n    for (int i = 0; i < 4; ++i) {\n        grids[i] = grid;\n        grids[i].tilt(static_cast<Direction>(i));\n\n        // Simulate lookahead steps with multiple simulations\n        for (int sim = 0; sim < NUM_SIMULATIONS; ++sim) {\n            Grid lookahead_grid = grids[i];\n            for (int step = 0; step < LOOKAHEAD_STEPS && step < remaining_flavors.size(); ++step) {\n                // Place the next candy in a random empty cell\n                vector<pair<int, int>> empty_cells;\n                for (int row = 0; row < GRID_SIZE; ++row) {\n                    for (int col = 0; col < GRID_SIZE; ++col) {\n                        if (lookahead_grid.cells[row][col] == 0) {\n                            empty_cells.emplace_back(row, col);\n                        }\n                    }\n                }\n\n                if (!empty_cells.empty()) {\n                    random_device rd;\n                    mt19937 gen(rd());\n                    uniform_int_distribution<> dis(0, empty_cells.size() - 1);\n                    auto [row, col] = empty_cells[dis(gen)];\n                    lookahead_grid.place_candy(remaining_flavors[step], row, col);\n\n                    // Choose a random tilt direction for the next step\n                    uniform_int_distribution<> tilt_dis(0, 3);\n                    lookahead_grid.tilt(static_cast<Direction>(tilt_dis(gen)));\n                }\n            }\n            scores[i] += lookahead_grid.calculate_score();\n        }\n    }\n\n    int max_score = *max_element(scores.begin(), scores.end());\n    vector<Direction> best_directions;\n\n    for (int i = 0; i < 4; ++i) {\n        if (scores[i] == max_score) {\n            best_directions.push_back(static_cast<Direction>(i));\n        }\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, best_directions.size() - 1);\n\n    return best_directions[dis(gen)];\n}\n\nint main() {\n    vector<int> flavors(NUM_CANDIES);\n    for (int& flavor : flavors) {\n        cin >> flavor;\n    }\n\n    Grid grid;\n    for (int t = 0; t < NUM_CANDIES; ++t) {\n        int p;\n        cin >> p;\n\n        int empty_cell = 0;\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (grid.cells[row][col] == 0) {\n                    empty_cell++;\n                    if (empty_cell == p) {\n                        grid.place_candy(flavors[t], row, col);\n                        break;\n                    }\n                }\n            }\n            if (empty_cell == p) {\n                break;\n            }\n        }\n\n        if (t < NUM_CANDIES - 1) {\n            vector<int> remaining_flavors(flavors.begin() + t + 1, flavors.end());\n            Direction dir = choose_direction(grid, flavors[t], remaining_flavors);\n            grid.tilt(dir);\n\n            switch (dir) {\n                case FORWARD:\n                    cout << \"F\" << endl;\n                    break;\n                case BACKWARD:\n                    cout << \"B\" << endl;\n                    break;\n                case LEFT:\n                    cout << \"L\" << endl;\n                    break;\n                case RIGHT:\n                    cout << \"R\" << endl;\n                    break;\n            }\n            cout.flush();\n        }\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int MAX_N = 100;\nconst int MAX_M = 100;\nconst int MAX_QUERIES = 100;\n\nmt19937 rng(random_device{}());\n\nint M;\ndouble epsilon;\nint N;\nvector<vector<vector<bool>>> G;\nvector<vector<bool>> H;\n\nvoid generate_graphs() {\n    // Use a combination of edge patterns and vertex orderings to encode numbers\n    for (int k = 0; k < M; ++k) {\n        vector<vector<bool>> graph(N, vector<bool>(N, false));\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                // Use a combination of edge patterns to encode the number k\n                if ((k & (1 << (i + j))) != 0) {\n                    graph[i][j] = true;\n                    graph[j][i] = true;\n                }\n            }\n        }\n        G.push_back(graph);\n    }\n}\n\nvoid output_graphs() {\n    cout << N << endl;\n    for (const auto& graph : G) {\n        string s;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                s += graph[i][j] ? '1' : '0';\n            }\n        }\n        cout << s << endl;\n    }\n    cout.flush();\n}\n\nvoid read_graph() {\n    string s;\n    cin >> s;\n    H.assign(N, vector<bool>(N, false));\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            H[i][j] = (s[idx++] == '1');\n            H[j][i] = H[i][j];\n        }\n    }\n}\n\nint calculate_similarity(const vector<vector<bool>>& a, const vector<vector<bool>>& b) {\n    int similarity = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (a[i][j] == b[i][j]) {\n                similarity++;\n            }\n        }\n    }\n    return similarity;\n}\n\nint predict_graph() {\n    int best_match = -1;\n    int max_similarity = -1;\n    for (int k = 0; k < M; ++k) {\n        int similarity = calculate_similarity(H, G[k]);\n        if (similarity > max_similarity) {\n            max_similarity = similarity;\n            best_match = k;\n        }\n    }\n    return best_match;\n}\n\nint main() {\n    cin >> M >> epsilon;\n    N = 20; // Choose a reasonable N within the constraints\n\n    generate_graphs();\n    output_graphs();\n\n    for (int q = 0; q < MAX_QUERIES; ++q) {\n        read_graph();\n        int t = predict_graph();\n        cout << t << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <limits>\n#include <unordered_map>\n#include <unordered_set>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v, w;\n    int day;\n    bool operator<(const Edge& other) const {\n        return w > other.w;\n    }\n};\n\nstruct Vertex {\n    int id;\n    double betweenness;\n    Vertex(int id) : id(id), betweenness(0.0) {}\n};\n\nclass Graph {\nprivate:\n    int N, M, D, K;\n    vector<vector<pair<int, int>>> adj;\n    vector<Edge> edges;\n    vector<Vertex> vertices;\n\n    void computeBetweennessCentrality() {\n        for (int s = 0; s < N; ++s) {\n            vector<int> numSP(N, 0);\n            vector<double> bc(N, 0.0);\n            vector<vector<int>> predecessors(N);\n            vector<int> stack;\n            vector<int> sigma(N, 0);\n            vector<int> distance(N, -1);\n\n            queue<int> q;\n            q.push(s);\n            sigma[s] = 1;\n            distance[s] = 0;\n\n            while (!q.empty()) {\n                int v = q.front();\n                q.pop();\n                stack.push_back(v);\n                for (const auto& neighbor : adj[v]) {\n                    int w = neighbor.first;\n                    if (distance[w] < 0) {\n                        q.push(w);\n                        distance[w] = distance[v] + 1;\n                    }\n                    if (distance[w] == distance[v] + 1) {\n                        sigma[w] += sigma[v];\n                        predecessors[w].push_back(v);\n                    }\n                }\n            }\n\n            while (!stack.empty()) {\n                int w = stack.back();\n                stack.pop_back();\n                for (int v : predecessors[w]) {\n                    bc[v] += (sigma[v] / static_cast<double>(sigma[w])) * (1.0 + bc[w]);\n                }\n                if (w != s) {\n                    vertices[w].betweenness += bc[w];\n                }\n            }\n        }\n    }\n\n    void prioritizeEdges() {\n        computeBetweennessCentrality();\n        sort(edges.begin(), edges.end(), [this](const Edge& a, const Edge& b) {\n            double a_betweenness = vertices[a.u].betweenness + vertices[a.v].betweenness;\n            double b_betweenness = vertices[b.u].betweenness + vertices[b.v].betweenness;\n            return a_betweenness > b_betweenness;\n        });\n    }\n\n    void assignDays() {\n        vector<int> dayCounts(D, 0);\n        for (auto& edge : edges) {\n            int bestDay = -1;\n            double minIncrease = numeric_limits<double>::max();\n            for (int day = 0; day < D; ++day) {\n                if (dayCounts[day] >= K) continue;\n                double increase = calculateFrustrationIncrease(edge, day);\n                if (increase < minIncrease) {\n                    minIncrease = increase;\n                    bestDay = day;\n                }\n            }\n            edge.day = bestDay;\n            dayCounts[bestDay]++;\n        }\n    }\n\n    double calculateFrustrationIncrease(const Edge& edge, int day) {\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            for (const auto& neighbor : adj[i]) {\n                int v = neighbor.first;\n                int w = neighbor.second;\n                dist[i][v] = min(dist[i][v], w);\n            }\n        }\n\n        for (int k = 0; k < N; ++k) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (dist[i][k] != numeric_limits<int>::max() && dist[k][j] != numeric_limits<int>::max()) {\n                        dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n                    }\n                }\n            }\n        }\n\n        vector<vector<int>> newDist = dist;\n        newDist[edge.u][edge.v] = numeric_limits<int>::max();\n        newDist[edge.v][edge.u] = numeric_limits<int>::max();\n\n        for (int k = 0; k < N; ++k) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (newDist[i][k] != numeric_limits<int>::max() && newDist[k][j] != numeric_limits<int>::max()) {\n                        newDist[i][j] = min(newDist[i][j], newDist[i][k] + newDist[k][j]);\n                    }\n                }\n            }\n        }\n\n        double totalIncrease = 0.0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (i != j) {\n                    int originalDist = dist[i][j];\n                    int newDistVal = newDist[i][j];\n                    if (newDistVal == numeric_limits<int>::max()) {\n                        newDistVal = 1e9;\n                    }\n                    totalIncrease += (newDistVal - originalDist);\n                }\n            }\n        }\n\n        return totalIncrease / (N * (N - 1));\n    }\n\npublic:\n    Graph(int N, int M, int D, int K) : N(N), M(M), D(D), K(K), adj(N), vertices(N) {\n        for (int i = 0; i < N; ++i) {\n            vertices[i].id = i;\n        }\n    }\n\n    void addEdge(int u, int v, int w) {\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n        edges.push_back({u, v, w, -1});\n    }\n\n    void solve() {\n        prioritizeEdges();\n        assignDays();\n    }\n\n    void printSolution() {\n        for (const auto& edge : edges) {\n            cout << edge.day + 1 << \" \";\n        }\n        cout << endl;\n    }\n};\n\nint main() {\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    Graph graph(N, M, D, K);\n\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        graph.addEdge(u - 1, v - 1, w);\n    }\n\n    // Skip reading the coordinates if not needed\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    graph.solve();\n    graph.printSolution();\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Block {\n    vector<vector<vector<bool>>> shape;\n    int volume;\n\n    Block(const vector<vector<vector<bool>>>& s) : shape(s) {\n        volume = 0;\n        for (const auto& layer : shape) {\n            for (const auto& row : layer) {\n                for (bool cell : row) {\n                    if (cell) volume++;\n                }\n            }\n        }\n    }\n\n    void rotateX() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[x][D - 1 - z][y] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n\n    void rotateY() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[z][y][D - 1 - x] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n\n    void rotateZ() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[D - 1 - y][x][z] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n};\n\nstruct Individual {\n    vector<Block> blocks;\n    vector<vector<vector<int>>> arrangement1;\n    vector<vector<vector<int>>> arrangement2;\n    double fitness;\n\n    Individual(const vector<Block>& b, int D) : blocks(b) {\n        arrangement1 = vector<vector<vector<int>>>(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        arrangement2 = vector<vector<vector<int>>>(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        fitness = 0.0;\n    }\n};\n\nvector<Block> generateInitialBlocks(int D) {\n    vector<Block> blocks;\n    // Generate some initial blocks, e.g., single cubes, 2x2x2 cubes, etc.\n    // This is a placeholder; actual block generation should be more sophisticated.\n    vector<vector<vector<bool>>> singleCube(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    singleCube[0][0][0] = true;\n    blocks.emplace_back(singleCube);\n\n    vector<vector<vector<bool>>> twoCube(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    twoCube[0][0][0] = true;\n    twoCube[0][0][1] = true;\n    blocks.emplace_back(twoCube);\n\n    return blocks;\n}\n\nvector<vector<vector<bool>>> createSilhouette(int D, const vector<string>& f, const vector<string>& r) {\n    vector<vector<vector<bool>>> silhouette(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    for (int z = 0; z < D; ++z) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                if (f[z][x] == '1' && r[z][y] == '1') {\n                    silhouette[x][y][z] = true;\n                }\n            }\n        }\n    }\n    return silhouette;\n}\n\ndouble evaluateFitness(const Individual& ind, const vector<vector<vector<bool>>>& silhouette1, const vector<vector<vector<bool>>>& silhouette2) {\n    int D = silhouette1.size();\n    double fitness = 0.0;\n\n    // Check silhouette1\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 (silhouette1[x][y][z]) {\n                    bool covered = false;\n                    for (const auto& block : ind.blocks) {\n                        if (ind.arrangement1[x][y][z] != 0) {\n                            covered = true;\n                            break;\n                        }\n                    }\n                    if (!covered) fitness += 1.0;\n                }\n            }\n        }\n    }\n\n    // Check silhouette2\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 (silhouette2[x][y][z]) {\n                    bool covered = false;\n                    for (const auto& block : ind.blocks) {\n                        if (ind.arrangement2[x][y][z] != 0) {\n                            covered = true;\n                            break;\n                        }\n                    }\n                    if (!covered) fitness += 1.0;\n                }\n            }\n        }\n    }\n\n    // Penalize unused blocks\n    unordered_set<int> usedBlocks1, usedBlocks2;\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 (ind.arrangement1[x][y][z] != 0) usedBlocks1.insert(ind.arrangement1[x][y][z]);\n                if (ind.arrangement2[x][y][z] != 0) usedBlocks2.insert(ind.arrangement2[x][y][z]);\n            }\n        }\n    }\n    for (int i = 1; i <= ind.blocks.size(); ++i) {\n        if (usedBlocks1.find(i) == usedBlocks1.end() && usedBlocks2.find(i) == usedBlocks2.end()) {\n            fitness += ind.blocks[i - 1].volume;\n        }\n    }\n\n    // Penalize blocks used in both arrangements\n    unordered_set<int> commonBlocks;\n    for (int block : usedBlocks1) {\n        if (usedBlocks2.find(block) != usedBlocks2.end()) {\n            commonBlocks.insert(block);\n        }\n    }\n    for (int block : commonBlocks) {\n        fitness += 1.0 / ind.blocks[block - 1].volume;\n    }\n\n    return fitness;\n}\n\nIndividual geneticAlgorithm(int D, const vector<vector<vector<bool>>>& silhouette1, const vector<vector<vector<bool>>>& silhouette2, int populationSize, int generations) {\n    vector<Block> initialBlocks = generateInitialBlocks(D);\n    vector<Individual> population;\n    for (int i = 0; i < populationSize; ++i) {\n        population.emplace_back(initialBlocks, D);\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> blockDist(0, initialBlocks.size() - 1);\n    uniform_int_distribution<> posDist(0, D - 1);\n\n    for (int gen = 0; gen < generations; ++gen) {\n        // Evaluate fitness\n        for (auto& ind : population) {\n            ind.fitness = evaluateFitness(ind, silhouette1, silhouette2);\n        }\n\n        // Sort by fitness\n        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n            return a.fitness < b.fitness;\n        });\n\n        // Select top individuals\n        vector<Individual> newPopulation;\n        for (int i = 0; i < populationSize / 2; ++i) {\n            newPopulation.push_back(population[i]);\n        }\n\n        // Crossover and mutation\n        while (newPopulation.size() < populationSize) {\n            Individual parent1 = population[rand() % (populationSize / 2)];\n            Individual parent2 = population[rand() % (populationSize / 2)];\n            Individual child(parent1.blocks, D);\n\n            // Crossover: randomly select arrangements from parents\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 (rand() % 2) {\n                            child.arrangement1[x][y][z] = parent1.arrangement1[x][y][z];\n                            child.arrangement2[x][y][z] = parent1.arrangement2[x][y][z];\n                        } else {\n                            child.arrangement1[x][y][z] = parent2.arrangement1[x][y][z];\n                            child.arrangement2[x][y][z] = parent2.arrangement2[x][y][z];\n                        }\n                    }\n                }\n            }\n\n            // Mutation: randomly change some blocks\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 (rand() % 100 < 5) { // 5% mutation rate\n                            child.arrangement1[x][y][z] = blockDist(gen) + 1;\n                            child.arrangement2[x][y][z] = blockDist(gen) + 1;\n                        }\n                    }\n                }\n            }\n\n            newPopulation.push_back(child);\n        }\n\n        population = newPopulation;\n    }\n\n    // Return the best individual\n    sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n        return a.fitness < b.fitness;\n    });\n\n    return population[0];\n}\n\nint main() {\n    int D;\n    cin >> D;\n\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for (int i = 0; i < D; ++i) cin >> f1[i];\n    for (int i = 0; i < D; ++i) cin >> r1[i];\n    for (int i = 0; i < D; ++i) cin >> f2[i];\n    for (int i = 0; i < D; ++i) cin >> r2[i];\n\n    vector<vector<vector<bool>>> silhouette1 = createSilhouette(D, f1, r1);\n    vector<vector<vector<bool>>> silhouette2 = createSilhouette(D, f2, r2);\n\n    Individual bestIndividual = geneticAlgorithm(D, silhouette1, silhouette2, 50, 100);\n\n    // Output the best individual\n    int n = bestIndividual.blocks.size();\n    cout << n << endl;\n\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                cout << bestIndividual.arrangement1[x][y][z] << \" \";\n            }\n        }\n    }\n    cout << endl;\n\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                cout << bestIndividual.arrangement2[x][y][z] << \" \";\n            }\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <limits>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\nusing namespace std;\nusing namespace boost;\n\ntypedef adjacency_list<vecS, vecS, undirectedS,\n                       no_property,\n                       property<edge_weight_t, int> > Graph;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef graph_traits<Graph>::edge_descriptor Edge;\ntypedef graph_traits<Graph>::edge_iterator EdgeIterator;\ntypedef graph_traits<Graph>::vertex_iterator VertexIterator;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Resident {\n    int a, b;\n    Resident(int a, int b) : a(a), b(b) {}\n};\n\nstruct EdgeInfo {\n    int u, v, w;\n    EdgeInfo(int u, int v, int w) : u(u), v(v), w(w) {}\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<Point> stations(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> stations[i].x >> stations[i].y;\n    }\n\n    vector<EdgeInfo> edges(M);\n    for (int j = 0; j < M; ++j) {\n        cin >> edges[j].u >> edges[j].v >> edges[j].w;\n        edges[j].u--; // Convert to 0-based index\n        edges[j].v--;\n    }\n\n    vector<Resident> residents(K);\n    for (int k = 0; k < K; ++k) {\n        cin >> residents[k].a >> residents[k].b;\n    }\n\n    // Build the graph\n    Graph g(N);\n    vector<Edge> edge_map(M);\n    for (int j = 0; j < M; ++j) {\n        edge_map[j] = add_edge(edges[j].u, edges[j].v, edges[j].w, g).first;\n    }\n\n    // Find the Minimum Spanning Tree (MST)\n    vector<Edge> mst_edges;\n    kruskal_minimum_spanning_tree(g, back_inserter(mst_edges));\n\n    // Create a subgraph with MST edges\n    Graph mst(N);\n    for (const auto& e : mst_edges) {\n        add_edge(source(e, g), target(e, g), get(edge_weight, g, e), mst);\n    }\n\n    // Calculate the minimum output strength for each station\n    vector<int> P(N, 0);\n    for (int i = 0; i < N; ++i) {\n        double max_dist = 0.0;\n        for (const auto& resident : residents) {\n            double dist = sqrt(pow(stations[i].x - resident.a, 2) + pow(stations[i].y - resident.b, 2));\n            if (dist > max_dist) {\n                max_dist = dist;\n            }\n        }\n        P[i] = static_cast<int>(ceil(max_dist));\n    }\n\n    // Ensure all residents are covered\n    unordered_set<int> covered_residents;\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            double dist = sqrt(pow(stations[i].x - residents[k].a, 2) + pow(stations[i].y - residents[k].b, 2));\n            if (dist <= P[i]) {\n                covered_residents.insert(k);\n            }\n        }\n    }\n\n    // If not all residents are covered, increase the output strength of the nearest station\n    while (covered_residents.size() < K) {\n        for (int k = 0; k < K; ++k) {\n            if (covered_residents.find(k) == covered_residents.end()) {\n                double min_dist = numeric_limits<double>::max();\n                int nearest_station = -1;\n                for (int i = 0; i < N; ++i) {\n                    double dist = sqrt(pow(stations[i].x - residents[k].a, 2) + pow(stations[i].y - residents[k].b, 2));\n                    if (dist < min_dist) {\n                        min_dist = dist;\n                        nearest_station = i;\n                    }\n                }\n                P[nearest_station] = static_cast<int>(ceil(min_dist));\n                for (int kk = 0; kk < K; ++kk) {\n                    double dist = sqrt(pow(stations[nearest_station].x - residents[kk].a, 2) + pow(stations[nearest_station].y - residents[kk].b, 2));\n                    if (dist <= P[nearest_station]) {\n                        covered_residents.insert(kk);\n                    }\n                }\n            }\n        }\n    }\n\n    // Output the results\n    for (int i = 0; i < N; ++i) {\n        cout << P[i] << \" \";\n    }\n    cout << endl;\n\n    // Create a set of edges in the MST for quick lookup\n    unordered_set<Edge> mst_edge_set;\n    for (const auto& e : mst_edges) {\n        mst_edge_set.insert(e);\n    }\n\n    // Output the power status of each edge\n    for (int j = 0; j < M; ++j) {\n        Edge e = edge(edges[j].u, edges[j].v, g).first;\n        if (mst_edge_set.find(e) != mst_edge_set.end()) {\n            cout << \"1 \";\n        } else {\n            cout << \"0 \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 30;\nconst int MAX_OPERATIONS = 10000;\n\nvector<vector<int>> pyramid;\n\nstruct Operation {\n    int x1, y1, x2, y2;\n};\n\nvector<Operation> operations;\n\nbool is_adjacent(int x1, int y1, int x2, int y2) {\n    if (x1 == x2 - 1 && y1 == y2 - 1) return true;\n    if (x1 == x2 - 1 && y1 == y2) return true;\n    if (x1 == x2 && y1 == y2 - 1) return true;\n    if (x1 == x2 && y1 == y2 + 1) return true;\n    if (x1 == x2 + 1 && y1 == y2) return true;\n    if (x1 == x2 + 1 && y1 == y2 + 1) return true;\n    return false;\n}\n\nvoid swap_balls(int x1, int y1, int x2, int y2) {\n    swap(pyramid[x1][y1], pyramid[x2][y2]);\n    operations.push_back({x1, y1, x2, y2});\n}\n\nint count_violations() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] > pyramid[x + 1][y]) violations++;\n            if (pyramid[x][y] > pyramid[x + 1][y + 1]) violations++;\n        }\n    }\n    return violations;\n}\n\nvoid greedy_algorithm() {\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] > pyramid[x + 1][y]) {\n                if (is_adjacent(x, y, x + 1, y)) {\n                    swap_balls(x, y, x + 1, y);\n                } else {\n                    // Find a path to swap\n                    // This is a simplified approach; a more sophisticated pathfinding algorithm can be used here\n                    for (int i = x + 1; i < N; ++i) {\n                        if (is_adjacent(i, y, i + 1, y)) {\n                            swap_balls(i, y, i + 1, y);\n                        }\n                    }\n                }\n            }\n            if (pyramid[x][y] > pyramid[x + 1][y + 1]) {\n                if (is_adjacent(x, y, x + 1, y + 1)) {\n                    swap_balls(x, y, x + 1, y + 1);\n                } else {\n                    // Find a path to swap\n                    // This is a simplified approach; a more sophisticated pathfinding algorithm can be used here\n                    for (int i = x + 1; i < N; ++i) {\n                        if (is_adjacent(i, y + 1, i + 1, y + 1)) {\n                            swap_balls(i, y + 1, i + 1, y + 1);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid simulated_annealing() {\n    int current_violations = count_violations();\n    if (current_violations == 0) return;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    double temperature = 1.0;\n    double cooling_rate = 0.999;\n    int max_iterations = 10000;\n\n    for (int iter = 0; iter < max_iterations && current_violations > 0; ++iter) {\n        // Randomly select two adjacent balls to swap\n        int x1 = dis(gen) * N;\n        int y1 = dis(gen) * (x1 + 1);\n        int direction = dis(gen) * 6;\n\n        int x2, y2;\n        switch (direction) {\n            case 0: x2 = x1 - 1; y2 = y1 - 1; break;\n            case 1: x2 = x1 - 1; y2 = y1; break;\n            case 2: x2 = x1; y2 = y1 - 1; break;\n            case 3: x2 = x1; y2 = y1 + 1; break;\n            case 4: x2 = x1 + 1; y2 = y1; break;\n            case 5: x2 = x1 + 1; y2 = y1 + 1; break;\n        }\n\n        if (x2 < 0 || x2 >= N || y2 < 0 || y2 > x2) continue;\n\n        swap_balls(x1, y1, x2, y2);\n        int new_violations = count_violations();\n\n        if (new_violations < current_violations) {\n            current_violations = new_violations;\n        } else {\n            double probability = exp((current_violations - new_violations) / temperature);\n            if (dis(gen) > probability) {\n                swap_balls(x1, y1, x2, y2); // Revert the swap\n            } else {\n                current_violations = new_violations;\n            }\n        }\n\n        temperature *= cooling_rate;\n    }\n}\n\nint main() {\n    pyramid.resize(N);\n    for (int x = 0; x < N; ++x) {\n        pyramid[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> pyramid[x][y];\n        }\n    }\n\n    greedy_algorithm();\n    simulated_annealing();\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.x1 << \" \" << op.y1 << \" \" << op.x2 << \" \" << op.y2 << 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#include <utility>\n#include <cmath>\n\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = (D - 1) / 2;\n\nstruct Point {\n    int i, j;\n    Point(int i, int j) : i(i), j(j) {}\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.i) ^ hash<int>()(p.j);\n        }\n    };\n}\n\nvector<Point> get_neighbors(const Point& p, const unordered_set<Point>& obstacles) {\n    vector<Point> neighbors;\n    int di[] = {-1, 1, 0, 0};\n    int dj[] = {0, 0, -1, 1};\n    for (int k = 0; k < 4; ++k) {\n        Point neighbor(p.i + di[k], p.j + dj[k]);\n        if (neighbor.i >= 0 && neighbor.i < D && neighbor.j >= 0 && neighbor.j < D &&\n            obstacles.find(neighbor) == obstacles.end()) {\n            neighbors.push_back(neighbor);\n        }\n    }\n    return neighbors;\n}\n\nvector<vector<int>> bfs(const unordered_set<Point>& obstacles) {\n    vector<vector<int>> distance(D, vector<int>(D, -1));\n    queue<Point> q;\n    Point entrance(ENTRANCE_I, ENTRANCE_J);\n    distance[entrance.i][entrance.j] = 0;\n    q.push(entrance);\n\n    while (!q.empty()) {\n        Point current = q.front();\n        q.pop();\n        for (const Point& neighbor : get_neighbors(current, obstacles)) {\n            if (distance[neighbor.i][neighbor.j] == -1) {\n                distance[neighbor.i][neighbor.j] = distance[current.i][current.j] + 1;\n                q.push(neighbor);\n            }\n        }\n    }\n    return distance;\n}\n\nPoint find_storage_location(const unordered_set<Point>& obstacles, const vector<vector<int>>& distance, const unordered_set<Point>& occupied) {\n    vector<Point> candidates;\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            Point p(i, j);\n            if (distance[i][j] != -1 && obstacles.find(p) == obstacles.end() && occupied.find(p) == occupied.end()) {\n                candidates.push_back(p);\n            }\n        }\n    }\n    if (candidates.empty()) {\n        return Point(-1, -1); // No valid storage location\n    }\n    // Sort candidates by distance from entrance and then by some heuristic\n    sort(candidates.begin(), candidates.end(), [&distance](const Point& a, const Point& b) {\n        return distance[a.i][a.j] < distance[b.i][b.j];\n    });\n    return candidates[0];\n}\n\nvector<Point> find_retrieval_order(const unordered_set<Point>& obstacles, const vector<vector<Point>>& storage_order) {\n    vector<vector<int>> distance = bfs(obstacles);\n    unordered_set<Point> occupied;\n    for (const auto& row : storage_order) {\n        for (const Point& p : row) {\n            if (p.i != -1 && p.j != -1) {\n                occupied.insert(p);\n            }\n        }\n    }\n    vector<Point> retrieval_order;\n    while (!occupied.empty()) {\n        vector<Point> candidates;\n        for (const Point& p : occupied) {\n            if (distance[p.i][p.j] != -1) {\n                candidates.push_back(p);\n            }\n        }\n        if (candidates.empty()) {\n            break; // No more reachable containers\n        }\n        // Sort candidates by distance from entrance and then by some heuristic\n        sort(candidates.begin(), candidates.end(), [&distance](const Point& a, const Point& b) {\n            return distance[a.i][a.j] < distance[b.i][b.j];\n        });\n        Point next = candidates[0];\n        retrieval_order.push_back(next);\n        occupied.erase(next);\n        // Update distance for adjacent squares\n        for (const Point& neighbor : get_neighbors(next, obstacles)) {\n            if (occupied.find(neighbor) == occupied.end()) {\n                distance[neighbor.i][neighbor.j] = -1;\n            }\n        }\n    }\n    return retrieval_order;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    unordered_set<Point> obstacles;\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        obstacles.insert(Point(ri, rj));\n    }\n    vector<vector<int>> distance = bfs(obstacles);\n    unordered_set<Point> occupied;\n    vector<vector<Point>> storage_order(D, vector<Point>(D, Point(-1, -1)));\n    for (int d = 0; d < D * D - 1 - N; ++d) {\n        int t_d;\n        cin >> t_d;\n        Point storage_location = find_storage_location(obstacles, distance, occupied);\n        if (storage_location.i == -1 && storage_location.j == -1) {\n            cerr << \"No valid storage location found for container \" << t_d << endl;\n            return 1;\n        }\n        storage_order[storage_location.i][storage_location.j] = Point(t_d, d);\n        occupied.insert(storage_location);\n        cout << storage_location.i << \" \" << storage_location.j << endl;\n        cout.flush();\n    }\n    vector<Point> retrieval_order = find_retrieval_order(obstacles, storage_order);\n    for (const Point& p : retrieval_order) {\n        cout << p.i << \" \" << p.j << endl;\n    }\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <unordered_set>\n#include <algorithm>\n#include <atcoder/dsu>\n#include <atcoder/maxflow>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nvector<vector<int>> grid;\nvector<vector<int>> simplified_grid;\nint n, m;\n\nvoid bfs(int x, int y, int color, vector<vector<bool>>& visited) {\n    queue<Point> q;\n    q.push(Point(x, y));\n    visited[x][y] = true;\n    simplified_grid[x][y] = color;\n\n    while (!q.empty()) {\n        Point p = q.front();\n        q.pop();\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = p.x + dx[i];\n            int ny = p.y + dy[i];\n\n            if (nx >= 0 && nx < n && ny >= 0 && ny < n && !visited[nx][ny] && grid[nx][ny] == color) {\n                visited[nx][ny] = true;\n                simplified_grid[nx][ny] = color;\n                q.push(Point(nx, ny));\n            }\n        }\n    }\n}\n\nvoid simplify_map() {\n    simplified_grid = vector<vector<int>>(n, vector<int>(n, 0));\n    vector<vector<bool>> visited(n, vector<bool>(n, false));\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (!visited[i][j] && grid[i][j] != 0) {\n                bfs(i, j, grid[i][j], visited);\n            }\n        }\n    }\n}\n\nvoid connect_components() {\n    dsu d(n * n);\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] != 0) {\n                for (int k = 0; k < 4; ++k) {\n                    int ni = i + dx[k];\n                    int nj = j + dy[k];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && simplified_grid[ni][nj] != 0) {\n                        d.merge(i * n + j, ni * n + nj);\n                    }\n                }\n            }\n        }\n    }\n\n    unordered_map<int, vector<Point>> components;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] != 0) {\n                components[d.leader(i * n + j)].push_back(Point(i, j));\n            }\n        }\n    }\n\n    for (auto& [leader, points] : components) {\n        for (auto& p : points) {\n            simplified_grid[p.x][p.y] = simplified_grid[points[0].x][points[0].y];\n        }\n    }\n}\n\nvoid minimize_connectors() {\n    // This is a placeholder for a more sophisticated heuristic\n    // For simplicity, we'll just ensure that the connectors are minimal\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] == 0) {\n                bool is_connector = false;\n                for (int k = 0; k < 4; ++k) {\n                    int ni = i + dx[k];\n                    int nj = j + dy[k];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && simplified_grid[ni][nj] != 0) {\n                        is_connector = true;\n                        break;\n                    }\n                }\n                if (!is_connector) {\n                    simplified_grid[i][j] = 0;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> n >> m;\n    grid.resize(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    simplify_map();\n    connect_components();\n    minimize_connectors();\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cout << simplified_grid[i][j] << (j == n - 1 ? \"\\n\" : \" \");\n        }\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <iomanip>\n#include <climits>\n#include <cfloat>\n#include <cstring>\n#include <cassert>\n#include <chrono>\n#include <fstream>\n#include <sstream>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<pii> vpii;\ntypedef vector<pll> vpll;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef vector<vpii> vvpii;\ntypedef vector<vpll> vvpll;\ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\ntypedef tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;\n\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define lb lower_bound\n#define ub upper_bound\n\nconst int INF = 1e9;\nconst ll LINF = 1e18;\nconst ld EPS = 1e-9;\nconst int MOD = 1e9 + 7;\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint n, d, q;\nvector<double> weights;\nvector<int> groups;\n\nchar compare(const vector<int>& l, const vector<int>& r) {\n    cout << l.size() << \" \" << r.size();\n    for (int i : l) cout << \" \" << i;\n    for (int i : r) cout << \" \" << i;\n    cout << endl;\n    char res;\n    cin >> res;\n    return res;\n}\n\nvoid estimate_weights() {\n    weights.resize(n, 0.0);\n    for (int i = 0; i < n; ++i) {\n        for (int j = i + 1; j < n; ++j) {\n            char res = compare({i}, {j});\n            if (res == '<') {\n                weights[j] += 1.0;\n            } else if (res == '>') {\n                weights[i] += 1.0;\n            } else {\n                weights[i] += 0.5;\n                weights[j] += 0.5;\n            }\n        }\n    }\n}\n\nvoid assign_groups() {\n    groups.resize(n, 0);\n    vector<double> group_weights(d, 0.0);\n    for (int i = 0; i < n; ++i) {\n        int best_group = 0;\n        double min_diff = fabs(group_weights[0] - weights[i]);\n        for (int j = 1; j < d; ++j) {\n            double diff = fabs(group_weights[j] - weights[i]);\n            if (diff < min_diff) {\n                min_diff = diff;\n                best_group = j;\n            }\n        }\n        groups[i] = best_group;\n        group_weights[best_group] += weights[i];\n    }\n}\n\nvoid refine_weights() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = i + 1; j < n; ++j) {\n            if (groups[i] != groups[j]) {\n                char res = compare({i}, {j});\n                if (res == '<') {\n                    weights[j] += 1.0;\n                } else if (res == '>') {\n                    weights[i] += 1.0;\n                } else {\n                    weights[i] += 0.5;\n                    weights[j] += 0.5;\n                }\n            }\n        }\n    }\n}\n\nvoid solve() {\n    estimate_weights();\n    assign_groups();\n    refine_weights();\n    assign_groups();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> n >> d >> q;\n    solve();\n\n    for (int i = 0; i < n; ++i) {\n        cout << groups[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cassert>\n\nusing namespace std;\n\nconst int n = 200;\nconst int m = 10;\nconst int max_operations = 5000;\n\nvector<vector<int>> stacks(m, vector<int>(n / m));\n\nvoid read_input() {\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < n / m; ++j) {\n            cin >> stacks[i][j];\n        }\n    }\n}\n\nint find_stack(int v) {\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < stacks[i].size(); ++j) {\n            if (stacks[i][j] == v) {\n                return i;\n            }\n        }\n    }\n    return -1;\n}\n\nint find_position(int i, int v) {\n    for (int j = 0; j < stacks[i].size(); ++j) {\n        if (stacks[i][j] == v) {\n            return j;\n        }\n    }\n    return -1;\n}\n\nvoid move_box(int v, int dest_stack) {\n    int src_stack = find_stack(v);\n    int pos = find_position(src_stack, v);\n\n    vector<int> moved_boxes(stacks[src_stack].begin() + pos, stacks[src_stack].end());\n    stacks[src_stack].erase(stacks[src_stack].begin() + pos, stacks[src_stack].end());\n\n    stacks[dest_stack].insert(stacks[dest_stack].end(), moved_boxes.begin(), moved_boxes.end());\n}\n\nint find_smallest_remaining() {\n    int smallest = n + 1;\n    for (int i = 0; i < m; ++i) {\n        if (!stacks[i].empty()) {\n            smallest = min(smallest, stacks[i][0]);\n        }\n    }\n    return smallest;\n}\n\nbool is_smallest_at_top(int v) {\n    for (int i = 0; i < m; ++i) {\n        if (!stacks[i].empty() && stacks[i][0] == v) {\n            return true;\n        }\n    }\n    return false;\n}\n\nvector<pair<int, int>> solve() {\n    vector<pair<int, int>> operations;\n    int current_smallest = 1;\n\n    while (current_smallest <= n) {\n        if (is_smallest_at_top(current_smallest)) {\n            operations.emplace_back(current_smallest, 0);\n            current_smallest++;\n        } else {\n            int src_stack = find_stack(current_smallest);\n            int dest_stack = -1;\n            int min_size = n + 1;\n\n            for (int i = 0; i < m; ++i) {\n                if (i != src_stack && stacks[i].size() < min_size) {\n                    min_size = stacks[i].size();\n                    dest_stack = i;\n                }\n            }\n\n            if (dest_stack == -1) {\n                // No other stack available, move to any other stack\n                for (int i = 0; i < m; ++i) {\n                    if (i != src_stack) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n\n            operations.emplace_back(current_smallest, dest_stack + 1);\n            move_box(current_smallest, dest_stack);\n        }\n    }\n\n    return operations;\n}\n\nint main() {\n    read_input();\n    auto operations = solve();\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 <queue>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Square {\n    int i, j;\n    int dirtiness;\n    bool operator<(const Square& other) const {\n        return dirtiness < other.dirtiness;\n    }\n};\n\nvector<vector<int>> generateRoute(int N, const vector<vector<int>>& h, const vector<vector<int>>& v, const vector<vector<int>>& d) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    vector<vector<int>> route;\n    priority_queue<Square> pq;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            pq.push({i, j, d[i][j]});\n        }\n    }\n\n    auto isValidMove = [&](int i, int j, int di, int dj) {\n        if (di == 0) {\n            if (dj == 1) return j < N - 1 && v[i][j] == 0;\n            else return j > 0 && v[i][j - 1] == 0;\n        } else {\n            if (di == 1) return i < N - 1 && h[i][j] == 0;\n            else return i > 0 && h[i - 1][j] == 0;\n        }\n    };\n\n    auto dfs = [&](auto&& self, int i, int j) -> void {\n        visited[i][j] = true;\n        vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        vector<char> dirChars = {'R', 'D', 'L', 'U'};\n\n        // Prioritize high-dirtiness squares\n        vector<pair<int, int>> highDirtinessSquares;\n        for (const auto& dir : directions) {\n            int ni = i + dir.first;\n            int nj = j + dir.second;\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj] && isValidMove(i, j, dir.first, dir.second)) {\n                highDirtinessSquares.emplace_back(ni, nj);\n            }\n        }\n        sort(highDirtinessSquares.begin(), highDirtinessSquares.end(), [&](const auto& a, const auto& b) {\n            return d[a.first][a.second] > d[b.first][b.second];\n        });\n\n        for (const auto& sq : highDirtinessSquares) {\n            int ni = sq.first;\n            int nj = sq.second;\n            if (!visited[ni][nj]) {\n                for (size_t k = 0; k < directions.size(); ++k) {\n                    if (ni == i + directions[k].first && nj == j + directions[k].second) {\n                        route.push_back({i, j, ni, nj, dirChars[k]});\n                        break;\n                    }\n                }\n                self(self, ni, nj);\n            }\n        }\n    };\n\n    dfs(dfs, 0, 0);\n\n    // Ensure all squares are visited\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!visited[i][j]) {\n                // Find a path to the unvisited square\n                vector<vector<int>> dist(N, vector<int>(N, -1));\n                queue<pair<int, int>> q;\n                q.push({i, j});\n                dist[i][j] = 0;\n                vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n\n                while (!q.empty()) {\n                    auto [ci, cj] = q.front();\n                    q.pop();\n                    for (const auto& dir : directions) {\n                        int ni = ci + dir.first;\n                        int nj = cj + dir.second;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist[ni][nj] == -1 && isValidMove(ci, cj, dir.first, dir.second)) {\n                            dist[ni][nj] = dist[ci][cj] + 1;\n                            parent[ni][nj] = {ci, cj};\n                            q.push({ni, nj});\n                        }\n                    }\n                }\n\n                // Reconstruct path\n                vector<pair<int, int>> path;\n                for (int x = 0; x < N; ++x) {\n                    for (int y = 0; y < N; ++y) {\n                        if (visited[x][y]) {\n                            int current_i = x, current_j = y;\n                            while (current_i != -1 && current_j != -1) {\n                                path.emplace_back(current_i, current_j);\n                                auto [pi, pj] = parent[current_i][current_j];\n                                current_i = pi;\n                                current_j = pj;\n                            }\n                            reverse(path.begin(), path.end());\n                            break;\n                        }\n                    }\n                    if (!path.empty()) break;\n                }\n\n                for (size_t k = 1; k < path.size(); ++k) {\n                    auto [pi, pj] = path[k - 1];\n                    auto [ci, cj] = path[k];\n                    for (size_t l = 0; l < directions.size(); ++l) {\n                        if (ci == pi + directions[l].first && cj == pj + directions[l].second) {\n                            route.push_back({pi, pj, ci, cj, dirChars[l]});\n                            break;\n                        }\n                    }\n                }\n                dfs(dfs, i, j);\n            }\n        }\n    }\n\n    // Convert route to string\n    vector<char> result;\n    for (const auto& move : route) {\n        result.push_back(move[4]);\n    }\n\n    // Ensure the route returns to (0, 0)\n    if (route.back()[2] != 0 || route.back()[3] != 0) {\n        // Find a path back to (0, 0)\n        vector<vector<int>> dist(N, vector<int>(N, -1));\n        queue<pair<int, int>> q;\n        q.push({route.back()[2], route.back()[3]});\n        dist[route.back()[2]][route.back()[3]] = 0;\n        vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n\n        while (!q.empty()) {\n            auto [ci, cj] = q.front();\n            q.pop();\n            for (const auto& dir : directions) {\n                int ni = ci + dir.first;\n                int nj = cj + dir.second;\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist[ni][nj] == -1 && isValidMove(ci, cj, dir.first, dir.second)) {\n                    dist[ni][nj] = dist[ci][cj] + 1;\n                    parent[ni][nj] = {ci, cj};\n                    q.push({ni, nj});\n                }\n            }\n        }\n\n        // Reconstruct path\n        vector<pair<int, int>> path;\n        int current_i = 0, current_j = 0;\n        while (current_i != -1 && current_j != -1) {\n            path.emplace_back(current_i, current_j);\n            auto [pi, pj] = parent[current_i][current_j];\n            current_i = pi;\n            current_j = pj;\n        }\n        reverse(path.begin(), path.end());\n\n        for (size_t k = 1; k < path.size(); ++k) {\n            auto [pi, pj] = path[k - 1];\n            auto [ci, cj] = path[k];\n            for (size_t l = 0; l < directions.size(); ++l) {\n                if (ci == pi + directions[l].first && cj == pj + directions[l].second) {\n                    result.push_back(dirChars[l]);\n                    break;\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int N;\n    cin >> N;\n\n    vector<vector<int>> h(N - 1, vector<int>(N));\n    for (int i = 0; i < N - 1; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            h[i][j] = row[j] - '0';\n        }\n    }\n\n    vector<vector<int>> v(N, vector<int>(N - 1));\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N - 1; ++j) {\n            v[i][j] = row[j] - '0';\n        }\n    }\n\n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    vector<char> route = generateRoute(N, h, v, d);\n\n    for (char move : route) {\n        cout << move;\n    }\n    cout << endl;\n\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nstruct State {\n    int i, j;\n    unordered_set<int> included;\n    int cost;\n\n    bool operator>(const State& other) const {\n        return cost > other.cost;\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int s_i, s_j;\n    cin >> s_i >> s_j;\n\n    vector<vector<char>> keyboard(N, vector<char>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> keyboard[i][j];\n        }\n    }\n\n    vector<string> t(M);\n    for (int k = 0; k < M; ++k) {\n        cin >> t[k];\n    }\n\n    // Preprocess the positions of each character\n    unordered_map<char, vector<pair<int, int>>> char_positions;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char_positions[keyboard[i][j]].emplace_back(i, j);\n        }\n    }\n\n    // Priority queue for Dijkstra's algorithm\n    priority_queue<State, vector<State>, greater<State>> pq;\n    pq.push({s_i, s_j, {}, 0});\n\n    // Visited set to avoid revisiting the same state\n    unordered_map<int, unordered_map<int, unordered_set<int>>> visited;\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.included.size() == M) {\n            // Found a solution, output the path\n            // (In a real implementation, you would need to reconstruct the path)\n            // For simplicity, we assume the path is stored and output here\n            cout << \"Solution found with cost \" << current.cost << endl;\n            return 0;\n        }\n\n        if (visited[current.i][current.j].count(current.included.size())) {\n            continue;\n        }\n        visited[current.i][current.j].insert(current.included.size());\n\n        // Explore all possible next characters\n        for (const auto& entry : char_positions) {\n            char c = entry.first;\n            for (const auto& pos : entry.second) {\n                int next_i = pos.first;\n                int next_j = pos.second;\n\n                // Calculate the cost to move to this character\n                int move_cost = abs(next_i - current.i) + abs(next_j - current.j) + 1;\n\n                // Check if adding this character includes any new lucky words\n                unordered_set<int> new_included = current.included;\n                for (int k = 0; k < M; ++k) {\n                    if (new_included.count(k)) continue;\n                    // Check if the new character includes the k-th lucky word\n                    // This is a simplified check; in practice, you would need a more efficient way\n                    // For example, using a suffix automaton or a rolling hash\n                    string s;\n                    // Reconstruct the string from the current state (simplified)\n                    // In a real implementation, you would need to keep track of the string\n                    if (s.find(t[k]) != string::npos) {\n                        new_included.insert(k);\n                    }\n                }\n\n                if (new_included.size() > current.included.size()) {\n                    pq.push({next_i, next_j, new_included, current.cost + move_cost});\n                }\n            }\n        }\n    }\n\n    cout << \"No solution found within the operation limit.\" << endl;\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <set>\n#include <random>\n#include <cmath>\n#include <algorithm>\n#include <atcoder/random>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Square {\n    int i, j;\n    Square(int i, int j) : i(i), j(j) {}\n    bool operator<(const Square& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nstruct OilField {\n    vector<Square> squares;\n    int di, dj;\n};\n\nvector<OilField> fields;\nint N, M;\ndouble epsilon;\n\nvoid read_input() {\n    cin >> N >> M >> epsilon;\n    fields.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        fields[k].squares.resize(d);\n        for (int l = 0; l < d; ++l) {\n            cin >> fields[k].squares[l].i >> fields[k].squares[l].j;\n        }\n    }\n}\n\nvoid drill(int i, int j) {\n    cout << \"q 1 \" << i << \" \" << j << endl;\n    cout.flush();\n    int v;\n    cin >> v;\n    // Update the oil reserves for the square (i, j)\n}\n\nint divinate(const vector<Square>& squares) {\n    cout << \"q \" << squares.size();\n    for (const auto& sq : squares) {\n        cout << \" \" << sq.i << \" \" << sq.j;\n    }\n    cout << endl;\n    cout.flush();\n    int v;\n    cin >> v;\n    return v;\n}\n\nvoid guess(const set<Square>& squares) {\n    cout << \"a \" << squares.size();\n    for (const auto& sq : squares) {\n        cout << \" \" << sq.i << \" \" << sq.j;\n    }\n    cout << endl;\n    cout.flush();\n    int correct;\n    cin >> correct;\n    if (correct) {\n        exit(0);\n    }\n}\n\nint main() {\n    read_input();\n\n    // Initial random drilling\n    set<Square> drilled;\n    mt19937 rng(random_device{}());\n    uniform_int_distribution<int> dist(0, N - 1);\n    for (int k = 0; k < 10; ++k) {\n        int i = dist(rng);\n        int j = dist(rng);\n        drill(i, j);\n        drilled.insert(Square(i, j));\n    }\n\n    // Divination to estimate total oil reserves\n    vector<Square> all_squares;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            all_squares.emplace_back(i, j);\n        }\n    }\n    int total_estimate = divinate(all_squares);\n\n    // Heuristic guided drilling\n    set<Square> candidates;\n    for (const auto& field : fields) {\n        for (const auto& sq : field.squares) {\n            candidates.insert(sq);\n        }\n    }\n\n    while (true) {\n        // Prioritize squares that are part of the polyominoes with the highest estimated oil reserves\n        vector<Square> to_divinate;\n        for (const auto& sq : candidates) {\n            if (drilled.find(sq) == drilled.end()) {\n                to_divinate.push_back(sq);\n            }\n        }\n\n        if (to_divinate.empty()) break;\n\n        // Divinate a subset of candidates\n        int k = min(10, (int)to_divinate.size());\n        vector<Square> subset(to_divinate.begin(), to_divinate.begin() + k);\n        int estimate = divinate(subset);\n\n        // Update the set of candidates based on the estimate\n        for (const auto& sq : subset) {\n            if (estimate > 0) {\n                candidates.insert(sq);\n            } else {\n                candidates.erase(sq);\n            }\n        }\n\n        // Drill a square from the candidates\n        if (!candidates.empty()) {\n            auto it = candidates.begin();\n            advance(it, dist(rng) % candidates.size());\n            Square sq = *it;\n            drill(sq.i, sq.j);\n            drilled.insert(sq);\n        }\n\n        // Guess the set of squares with oil reserves\n        if (drilled.size() >= 10) {\n            guess(drilled);\n        }\n    }\n\n    return 0;\n}","ahc031":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <climits>\n\nusing namespace std;\n\nstruct Rectangle {\n    int i0, j0, i1, j1;\n    Rectangle(int i0, int j0, int i1, int j1) : i0(i0), j0(j0), i1(i1), j1(j1) {}\n    int area() const { return (i1 - i0) * (j1 - j0); }\n};\n\nstruct Solution {\n    vector<vector<Rectangle>> rectangles;\n    int total_cost;\n};\n\nint calculate_area_cost(const vector<vector<int>>& a, const Solution& sol) {\n    int cost = 0;\n    for (int d = 0; d < sol.rectangles.size(); ++d) {\n        for (int k = 0; k < sol.rectangles[d].size(); ++k) {\n            int b = sol.rectangles[d][k].area();\n            if (a[d][k] > b) {\n                cost += 100 * (a[d][k] - b);\n            }\n        }\n    }\n    return cost;\n}\n\nint calculate_partition_cost(const Solution& prev_sol, const Solution& curr_sol) {\n    int cost = 0;\n    for (int d = 0; d < curr_sol.rectangles.size(); ++d) {\n        if (d == 0) continue; // No partition cost on the first day\n        for (int i = 1; i < 1000; ++i) {\n            for (int j = 0; j < 999; ++j) {\n                bool prev_has_horizontal = false;\n                bool curr_has_horizontal = false;\n                for (const auto& rect : prev_sol.rectangles[d-1]) {\n                    if ((rect.i0 == i && rect.j0 <= j && rect.j1 > j) ||\n                        (rect.i1 == i && rect.j0 <= j && rect.j1 > j)) {\n                        prev_has_horizontal = true;\n                        break;\n                    }\n                }\n                for (const auto& rect : curr_sol.rectangles[d]) {\n                    if ((rect.i0 == i && rect.j0 <= j && rect.j1 > j) ||\n                        (rect.i1 == i && rect.j0 <= j && rect.j1 > j)) {\n                        curr_has_horizontal = true;\n                        break;\n                    }\n                }\n                if (prev_has_horizontal != curr_has_horizontal) {\n                    cost++;\n                }\n            }\n        }\n        for (int i = 0; i < 999; ++i) {\n            for (int j = 1; j < 1000; ++j) {\n                bool prev_has_vertical = false;\n                bool curr_has_vertical = false;\n                for (const auto& rect : prev_sol.rectangles[d-1]) {\n                    if ((rect.j0 == j && rect.i0 <= i && rect.i1 > i) ||\n                        (rect.j1 == j && rect.i0 <= i && rect.i1 > i)) {\n                        prev_has_vertical = true;\n                        break;\n                    }\n                }\n                for (const auto& rect : curr_sol.rectangles[d]) {\n                    if ((rect.j0 == j && rect.i0 <= i && rect.i1 > i) ||\n                        (rect.j1 == j && rect.i0 <= i && rect.i1 > i)) {\n                        curr_has_vertical = true;\n                        break;\n                    }\n                }\n                if (prev_has_vertical != curr_has_vertical) {\n                    cost++;\n                }\n            }\n        }\n    }\n    return cost;\n}\n\nSolution greedy_solution(const vector<vector<int>>& a) {\n    Solution sol;\n    sol.rectangles.resize(a.size());\n    for (int d = 0; d < a.size(); ++d) {\n        vector<int> remaining_area = a[d];\n        sort(remaining_area.rbegin(), remaining_area.rend());\n        vector<pair<int, int>> positions;\n        for (int i = 0; i < 1000; ++i) {\n            for (int j = 0; j < 1000; ++j) {\n                positions.emplace_back(i, j);\n            }\n        }\n        random_device rd;\n        mt19937 g(rd());\n        shuffle(positions.begin(), positions.end(), g);\n        for (int k = 0; k < a[d].size(); ++k) {\n            int best_area = 0;\n            Rectangle best_rect(0, 0, 0, 0);\n            for (const auto& pos : positions) {\n                int i0 = pos.first;\n                int j0 = pos.second;\n                for (int i1 = i0 + 1; i1 <= 1000; ++i1) {\n                    for (int j1 = j0 + 1; j1 <= 1000; ++j1) {\n                        int area = (i1 - i0) * (j1 - j0);\n                        if (area > remaining_area[k]) continue;\n                        if (area > best_area) {\n                            best_area = area;\n                            best_rect = Rectangle(i0, j0, i1, j1);\n                        }\n                    }\n                }\n            }\n            sol.rectangles[d].push_back(best_rect);\n            remaining_area[k] -= best_area;\n        }\n    }\n    sol.total_cost = calculate_area_cost(a, sol) + calculate_partition_cost(sol, sol);\n    return sol;\n}\n\nSolution simulated_annealing(const vector<vector<int>>& a, const Solution& initial_sol, double initial_temp, double cooling_rate, int iterations) {\n    Solution current_sol = initial_sol;\n    Solution best_sol = initial_sol;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    double temp = initial_temp;\n    for (int iter = 0; iter < iterations; ++iter) {\n        Solution new_sol = current_sol;\n        int d = rand() % a.size();\n        int k = rand() % a[d].size();\n        int i0 = rand() % 1000;\n        int j0 = rand() % 1000;\n        int i1 = i0 + 1 + rand() % (1000 - i0);\n        int j1 = j0 + 1 + rand() % (1000 - j0);\n        new_sol.rectangles[d][k] = Rectangle(i0, j0, i1, j1);\n        int new_area_cost = calculate_area_cost(a, new_sol);\n        int new_partition_cost = calculate_partition_cost(current_sol, new_sol);\n        int new_total_cost = new_area_cost + new_partition_cost;\n        if (new_total_cost < current_sol.total_cost || dis(gen) < exp((current_sol.total_cost - new_total_cost) / temp)) {\n            current_sol = new_sol;\n            current_sol.total_cost = new_total_cost;\n            if (new_total_cost < best_sol.total_cost) {\n                best_sol = new_sol;\n                best_sol.total_cost = new_total_cost;\n            }\n        }\n        temp *= cooling_rate;\n    }\n    return best_sol;\n}\n\nint main() {\n    int W, D, N;\n    cin >> W >> D >> N;\n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cin >> a[d][k];\n        }\n    }\n    Solution initial_sol = greedy_solution(a);\n    Solution best_sol = simulated_annealing(a, initial_sol, 1000.0, 0.999, 10000);\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << best_sol.rectangles[d][k].i0 << \" \" << best_sol.rectangles[d][k].j0 << \" \"\n                 << best_sol.rectangles[d][k].i1 << \" \" << best_sol.rectangles[d][k].j1 << endl;\n        }\n    }\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\n\nstruct Stamp {\n    int s[3][3];\n};\n\nstruct Operation {\n    int m, p, q;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int a[N][N];\n    Stamp stamps[M];\n\n    // Read initial grid\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> a[i][j];\n        }\n    }\n\n    // Read stamps\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].s[i][j];\n            }\n        }\n    }\n\n    vector<Operation> operations;\n    int current_sum = 0;\n\n    // Calculate initial sum\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            current_sum = (current_sum + a[i][j] % MOD) % MOD;\n        }\n    }\n\n    // Greedy approach\n    for (int op = 0; op < K; ++op) {\n        int best_m = -1, best_p = -1, best_q = -1;\n        int max_increase = 0;\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    int increase = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            int new_val = (a[p + i][q + j] + stamps[m].s[i][j]) % MOD;\n                            increase += (new_val - (a[p + i][q + j] % MOD)) % MOD;\n                        }\n                    }\n                    if (increase > max_increase) {\n                        max_increase = increase;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_m == -1) break; // No more beneficial operations\n\n        operations.push_back({best_m, best_p, best_q});\n\n        // Apply the best operation\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                a[best_p + i][best_q + j] = (a[best_p + i][best_q + j] + stamps[best_m].s[i][j]) % MOD;\n            }\n        }\n\n        current_sum = (current_sum + max_increase) % MOD;\n    }\n\n    // Output the operations\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.m << \" \" << op.p << \" \" << op.q << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_map>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURNS = 10000;\n\nstruct Crane {\n    int x, y;\n    bool is_large;\n    bool holding;\n    int container;\n};\n\nstruct Container {\n    int x, y;\n    int number;\n};\n\nvector<vector<int>> A(N, vector<int>(N));\nvector<Crane> cranes;\nvector<vector<int>> grid(N, vector<int>(N, -1));\nvector<vector<int>> next_container(N, vector<int>(N, 0));\nvector<string> actions(N, string(MAX_TURNS, '.'));\n\nint calculate_score() {\n    // Implement scoring logic here\n    return 0;\n}\n\nvoid simulate_turn() {\n    // Step 1: Bring in new containers\n    for (int i = 0; i < N; ++i) {\n        if (next_container[i][0] < N && grid[i][0] == -1) {\n            grid[i][0] = A[i][next_container[i][0]];\n            next_container[i][0]++;\n        }\n    }\n\n    // Step 2: Perform crane actions\n    vector<vector<int>> new_grid(N, vector<int>(N, -1));\n    vector<Crane> new_cranes;\n    for (int i = 0; i < N; ++i) {\n        Crane c = cranes[i];\n        char action = actions[i][0];\n        actions[i].erase(0, 1);\n\n        if (action == 'B' && !c.holding) {\n            continue; // Crane is bombed\n        }\n\n        switch (action) {\n            case 'P':\n                if (!c.holding && grid[c.x][c.y] != -1) {\n                    c.holding = true;\n                    c.container = grid[c.x][c.y];\n                    grid[c.x][c.y] = -1;\n                }\n                break;\n            case 'Q':\n                if (c.holding && grid[c.x][c.y] == -1) {\n                    grid[c.x][c.y] = c.container;\n                    c.holding = false;\n                }\n                break;\n            case 'U':\n                if (c.x > 0 && (grid[c.x - 1][c.y] == -1 || c.is_large)) {\n                    c.x--;\n                }\n                break;\n            case 'D':\n                if (c.x < N - 1 && (grid[c.x + 1][c.y] == -1 || c.is_large)) {\n                    c.x++;\n                }\n                break;\n            case 'L':\n                if (c.y > 0 && (grid[c.x][c.y - 1] == -1 || c.is_large)) {\n                    c.y--;\n                }\n                break;\n            case 'R':\n                if (c.y < N - 1 && (grid[c.x][c.y + 1] == -1 || c.is_large)) {\n                    c.y++;\n                }\n                break;\n            case '.':\n                break;\n        }\n\n        if (action != 'B') {\n            new_cranes.push_back(c);\n        }\n    }\n    cranes = new_cranes;\n\n    // Step 3: Dispatch containers\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][N - 1] != -1) {\n            grid[i][N - 1] = -1;\n        }\n    }\n}\n\nvoid heuristic_solution() {\n    // Initialize cranes\n    for (int i = 0; i < N; ++i) {\n        cranes.push_back({i, 0, i == 0, false, -1});\n    }\n\n    // Simulate turns\n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        simulate_turn();\n\n        // Simple heuristic: Move cranes towards the right edge\n        for (int i = 0; i < N; ++i) {\n            Crane &c = cranes[i];\n            if (c.y < N - 1) {\n                actions[i][turn] = 'R';\n            } else if (c.y == N - 1 && c.holding) {\n                actions[i][turn] = 'Q';\n            } else if (c.y == N - 1 && !c.holding && grid[c.x][c.y] != -1) {\n                actions[i][turn] = 'P';\n            } else if (c.y == N - 1 && !c.holding && grid[c.x][c.y] == -1) {\n                actions[i][turn] = '.';\n            }\n        }\n    }\n}\n\nint main() {\n    // Read input\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n        }\n    }\n\n    // Run heuristic solution\n    heuristic_solution();\n\n    // Output actions\n    for (int i = 0; i < N; ++i) {\n        cout << actions[i] << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <climits>\n#include <unordered_map>\n#include <tuple>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_OPERATIONS = 100000;\nconst int MAX_SOIL = 1000000;\n\nstruct State {\n    int x, y;\n    int soil;\n    int cost;\n    vector<string> operations;\n\n    bool operator>(const State& other) const {\n        return cost > other.cost;\n    }\n};\n\nint heuristic(int x1, int y1, int x2, int y2, int soil) {\n    return abs(x1 - x2) + abs(y1 - y2) + soil;\n}\n\nvector<string> findPath(int startX, int startY, int endX, int endY, int soil) {\n    priority_queue<State, vector<State>, greater<State>> pq;\n    unordered_map<int, unordered_map<int, int>> visited;\n\n    pq.push({startX, startY, soil, 0, {}});\n    visited[startX][startY] = 0;\n\n    vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n    vector<string> dirChars = {\"U\", \"D\", \"L\", \"R\"};\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.x == endX && current.y == endY) {\n            return current.operations;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int newX = current.x + directions[i].first;\n            int newY = current.y + directions[i].second;\n\n            if (newX >= 0 && newX < N && newY >= 0 && newY < N) {\n                int newCost = current.cost + 100 + current.soil;\n                if (visited[newX][newY] == 0 || newCost < visited[newX][newY]) {\n                    visited[newX][newY] = newCost;\n                    vector<string> newOperations = current.operations;\n                    newOperations.push_back(dirChars[i]);\n                    pq.push({newX, newY, current.soil, newCost, newOperations});\n                }\n            }\n        }\n    }\n\n    return {};\n}\n\nvector<string> solve(vector<vector<int>>& grid) {\n    vector<string> operations;\n    int totalOperations = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == 0) continue;\n\n            int currentX = 0, currentY = 0;\n            int soil = 0;\n\n            // Move to the target square\n            vector<string> path = findPath(currentX, currentY, i, j, soil);\n            operations.insert(operations.end(), path.begin(), path.end());\n            currentX = i;\n            currentY = j;\n\n            // Load or unload soil\n            if (grid[i][j] > 0) {\n                int d = min(grid[i][j], MAX_SOIL);\n                operations.push_back(\"+\" + to_string(d));\n                soil += d;\n                grid[i][j] -= d;\n            } else {\n                int d = min(-grid[i][j], soil);\n                operations.push_back(\"-\" + to_string(d));\n                soil -= d;\n                grid[i][j] += d;\n            }\n\n            // Move back to the origin if there's soil to carry\n            if (soil > 0) {\n                path = findPath(currentX, currentY, 0, 0, soil);\n                operations.insert(operations.end(), path.begin(), path.end());\n                currentX = 0;\n                currentY = 0;\n            }\n\n            if (operations.size() >= MAX_OPERATIONS) break;\n        }\n        if (operations.size() >= MAX_OPERATIONS) break;\n    }\n\n    return operations;\n}\n\nint main() {\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<string> operations = solve(grid);\n    for (const string& op : operations) {\n        cout << op << endl;\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 6;\nconst int M = 15;\nconst int T = 10;\nconst int SEED_COUNT = 2 * N * (N - 1);\nconst int POPULATION_SIZE = 50;\nconst int GENERATIONS = 10;\nconst double MUTATION_RATE = 0.1;\n\nvector<vector<int>> X(SEED_COUNT, vector<int>(M, 0));\nvector<int> X_max(M, 0);\n\nstruct Individual {\n    vector<vector<int>> grid;\n    int fitness;\n\n    Individual() : grid(N, vector<int>(N, 0)), fitness(0) {}\n};\n\nvector<Individual> population(POPULATION_SIZE);\n\nvoid initializePopulation() {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, SEED_COUNT - 1);\n\n    for (auto& individual : population) {\n        vector<int> seeds(SEED_COUNT);\n        iota(seeds.begin(), seeds.end(), 0);\n        shuffle(seeds.begin(), seeds.end(), gen);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                individual.grid[i][j] = seeds[i * N + j];\n            }\n        }\n    }\n}\n\nvector<vector<int>> generateNewSeeds(const vector<vector<int>>& grid) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, 1);\n\n    vector<vector<int>> newSeeds(SEED_COUNT, vector<int>(M, 0));\n\n    int index = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N - 1; ++j) {\n            int seed1 = grid[i][j];\n            int seed2 = grid[i][j + 1];\n            for (int l = 0; l < M; ++l) {\n                newSeeds[index][l] = dist(gen) ? X[seed1][l] : X[seed2][l];\n            }\n            ++index;\n        }\n    }\n\n    for (int i = 0; i < N - 1; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int seed1 = grid[i][j];\n            int seed2 = grid[i + 1][j];\n            for (int l = 0; l < M; ++l) {\n                newSeeds[index][l] = dist(gen) ? X[seed1][l] : X[seed2][l];\n            }\n            ++index;\n        }\n    }\n\n    return newSeeds;\n}\n\nint calculateFitness(const vector<vector<int>>& grid) {\n    vector<vector<int>> currentSeeds = X;\n    for (int t = 0; t < T; ++t) {\n        currentSeeds = generateNewSeeds(grid);\n    }\n\n    int maxValue = 0;\n    for (const auto& seed : currentSeeds) {\n        int value = accumulate(seed.begin(), seed.end(), 0);\n        if (value > maxValue) {\n            maxValue = value;\n        }\n    }\n\n    int sumXMax = accumulate(X_max.begin(), X_max.end(), 0);\n    return round(1e6 * maxValue / sumXMax);\n}\n\nvoid evaluatePopulation() {\n    for (auto& individual : population) {\n        individual.fitness = calculateFitness(individual.grid);\n    }\n}\n\nvector<Individual> selectParents() {\n    vector<Individual> parents;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, POPULATION_SIZE - 1);\n\n    for (int i = 0; i < POPULATION_SIZE; ++i) {\n        int idx1 = dist(gen);\n        int idx2 = dist(gen);\n        parents.push_back(population[idx1].fitness > population[idx2].fitness ? population[idx1] : population[idx2]);\n    }\n\n    return parents;\n}\n\nvector<Individual> crossover(const vector<Individual>& parents) {\n    vector<Individual> offspring;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, N * N - 1);\n\n    for (int i = 0; i < POPULATION_SIZE; i += 2) {\n        Individual child1, child2;\n        int crossoverPoint = dist(gen);\n\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < N; ++k) {\n                if (j * N + k < crossoverPoint) {\n                    child1.grid[j][k] = parents[i].grid[j][k];\n                    child2.grid[j][k] = parents[i + 1].grid[j][k];\n                } else {\n                    child1.grid[j][k] = parents[i + 1].grid[j][k];\n                    child2.grid[j][k] = parents[i].grid[j][k];\n                }\n            }\n        }\n\n        offspring.push_back(child1);\n        offspring.push_back(child2);\n    }\n\n    return offspring;\n}\n\nvoid mutate(vector<Individual>& offspring) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<double> dist(0.0, 1.0);\n    uniform_int_distribution<int> seedDist(0, SEED_COUNT - 1);\n\n    for (auto& individual : offspring) {\n        if (dist(gen) < MUTATION_RATE) {\n            int i1 = seedDist(gen) / N;\n            int j1 = seedDist(gen) % N;\n            int i2 = seedDist(gen) / N;\n            int j2 = seedDist(gen) % N;\n            swap(individual.grid[i1][j1], individual.grid[i2][j2]);\n        }\n    }\n}\n\nvoid geneticAlgorithm() {\n    initializePopulation();\n    evaluatePopulation();\n\n    for (int gen = 0; gen < GENERATIONS; ++gen) {\n        vector<Individual> parents = selectParents();\n        vector<Individual> offspring = crossover(parents);\n        mutate(offspring);\n\n        for (auto& individual : offspring) {\n            individual.fitness = calculateFitness(individual.grid);\n        }\n\n        population.insert(population.end(), offspring.begin(), offspring.end());\n        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n            return a.fitness > b.fitness;\n        });\n        population.resize(POPULATION_SIZE);\n    }\n}\n\nint main() {\n    // Read input\n    for (int i = 0; i < SEED_COUNT; ++i) {\n        for (int j = 0; j < M; ++j) {\n            cin >> X[i][j];\n            if (X[i][j] > X_max[j]) {\n                X_max[j] = X[i][j];\n            }\n        }\n    }\n\n    // Run genetic algorithm\n    geneticAlgorithm();\n\n    // Output the best solution\n    Individual best = *max_element(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n        return a.fitness < b.fitness;\n    });\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << best.grid[i][j];\n            if (j < N - 1) {\n                cout << \" \";\n            } else {\n                cout << endl;\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct TreeNode {\n    int id;\n    int parent;\n    int length;\n    vector<int> children;\n    Point position;\n    Point direction;\n    bool isFingertip;\n    bool holding;\n\n    TreeNode(int id, int parent, int length, const Point& position, const Point& direction, bool isFingertip)\n        : id(id), parent(parent), length(length), position(position), direction(direction), isFingertip(isFingertip), holding(false) {}\n};\n\nclass RoboticArm {\nprivate:\n    int N, M, V;\n    vector<vector<int>> grid;\n    vector<vector<int>> target;\n    vector<TreeNode> tree;\n    Point rootPosition;\n    vector<string> operations;\n    unordered_map<Point, bool> occupied;\n\n    void designTree() {\n        // Design a star-shaped tree\n        tree.emplace_back(0, -1, 0, rootPosition, Point(1, 0), false);\n        for (int i = 1; i < V; ++i) {\n            int parent = 0;\n            int length = 1;\n            Point direction = Point(1, 0);\n            tree.emplace_back(i, parent, length, rootPosition, direction, true);\n            tree[parent].children.push_back(i);\n        }\n    }\n\n    void moveRoot(int dx, int dy) {\n        rootPosition.x += dx;\n        rootPosition.y += dy;\n        for (auto& node : tree) {\n            node.position.x += dx;\n            node.position.y += dy;\n        }\n    }\n\n    void rotateSubtree(int nodeId, int rotation) {\n        if (rotation == 0) return;\n        TreeNode& node = tree[nodeId];\n        int newDirX = node.direction.x;\n        int newDirY = node.direction.y;\n        if (rotation == 1) { // Counterclockwise\n            newDirX = -node.direction.y;\n            newDirY = node.direction.x;\n        } else if (rotation == 2) { // Clockwise\n            newDirX = node.direction.y;\n            newDirY = -node.direction.x;\n        }\n        node.direction.x = newDirX;\n        node.direction.y = newDirY;\n        for (int childId : node.children) {\n            rotateSubtree(childId, rotation);\n        }\n    }\n\n    void grabOrRelease(int nodeId) {\n        TreeNode& node = tree[nodeId];\n        if (!node.isFingertip) return;\n        Point fingertipPos = node.position;\n        fingertipPos.x += node.direction.x * node.length;\n        fingertipPos.y += node.direction.y * node.length;\n        if (fingertipPos.x < 0 || fingertipPos.x >= N || fingertipPos.y < 0 || fingertipPos.y >= N) return;\n        if (grid[fingertipPos.x][fingertipPos.y] == 1 && target[fingertipPos.x][fingertipPos.y] == 0 && !node.holding) {\n            grid[fingertipPos.x][fingertipPos.y] = 0;\n            node.holding = true;\n        } else if (grid[fingertipPos.x][fingertipPos.y] == 0 && target[fingertipPos.x][fingertipPos.y] == 1 && node.holding) {\n            grid[fingertipPos.x][fingertipPos.y] = 1;\n            node.holding = false;\n        }\n    }\n\n    void performOperation(const string& op) {\n        operations.push_back(op);\n        char move = op[0];\n        if (move == 'U') moveRoot(-1, 0);\n        else if (move == 'D') moveRoot(1, 0);\n        else if (move == 'L') moveRoot(0, -1);\n        else if (move == 'R') moveRoot(0, 1);\n        for (int i = 1; i < V; ++i) {\n            char rot = op[i];\n            if (rot == 'L') rotateSubtree(i, 1);\n            else if (rot == 'R') rotateSubtree(i, 2);\n        }\n        for (int i = 0; i < V; ++i) {\n            char action = op[V + i];\n            if (action == 'P') grabOrRelease(i);\n        }\n    }\n\n    void moveTakoyaki(const Point& start, const Point& end) {\n        // Simplified path planning: move directly to the target\n        int dx = end.x - start.x;\n        int dy = end.y - start.y;\n        string op(V * 2, '.');\n        if (dx > 0) op[0] = 'D';\n        else if (dx < 0) op[0] = 'U';\n        else if (dy > 0) op[0] = 'R';\n        else if (dy < 0) op[0] = 'L';\n        performOperation(op);\n        op = string(V * 2, '.');\n        op[V + 1] = 'P'; // Grab or release\n        performOperation(op);\n        if (dx > 0) op[0] = 'U';\n        else if (dx < 0) op[0] = 'D';\n        else if (dy > 0) op[0] = 'L';\n        else if (dy < 0) op[0] = 'R';\n        performOperation(op);\n        op[V + 1] = 'P'; // Grab or release\n        performOperation(op);\n    }\n\npublic:\n    RoboticArm(int N, int M, int V, const vector<vector<int>>& grid, const vector<vector<int>>& target)\n        : N(N), M(M), V(V), grid(grid), target(target), rootPosition(0, 0) {\n        designTree();\n    }\n\n    void solve() {\n        vector<Point> takoyakiPositions;\n        vector<Point> targetPositions;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == 1) {\n                    takoyakiPositions.emplace_back(i, j);\n                }\n                if (target[i][j] == 1) {\n                    targetPositions.emplace_back(i, j);\n                }\n            }\n        }\n        for (size_t i = 0; i < takoyakiPositions.size(); ++i) {\n            moveTakoyaki(takoyakiPositions[i], targetPositions[i]);\n        }\n    }\n\n    void printSolution() {\n        cout << tree.size() << endl;\n        for (size_t i = 1; i < tree.size(); ++i) {\n            cout << tree[i].parent << \" \" << tree[i].length << endl;\n        }\n        cout << rootPosition.x << \" \" << rootPosition.y << endl;\n        for (const string& op : operations) {\n            cout << op << endl;\n        }\n    }\n};\n\nint main() {\n    int N, M, V;\n    cin >> N >> M >> V;\n    vector<vector<int>> grid(N, vector<int>(N));\n    vector<vector<int>> target(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = row[j] - '0';\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            target[i][j] = row[j] - '0';\n        }\n    }\n    RoboticArm arm(N, M, V, grid, target);\n    arm.solve();\n    arm.printSolution();\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Polygon {\n    vector<Point> vertices;\n    int mackerels, sardines;\n    Polygon() : mackerels(0), sardines(0) {}\n};\n\nint cross(const Point &O, const Point &A, const Point &B) {\n    return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);\n}\n\nvector<Point> convex_hull(vector<Point> points) {\n    int n = points.size(), k = 0;\n    vector<Point> hull(2 * n);\n    sort(points.begin(), points.end(), [](const Point &a, const Point &b) {\n        return a.x < b.x || (a.x == b.x && a.y < b.y);\n    });\n    for (int i = 0; i < n; ++i) {\n        while (k >= 2 && cross(hull[k-2], hull[k-1], points[i]) <= 0) k--;\n        hull[k++] = points[i];\n    }\n    for (int i = n-2, t = k+1; i >= 0; --i) {\n        while (k >= t && cross(hull[k-2], hull[k-1], points[i]) <= 0) k--;\n        hull[k++] = points[i];\n    }\n    hull.resize(k-1);\n    return hull;\n}\n\nbool is_point_in_polygon(const Point &p, const Polygon &poly) {\n    int n = poly.vertices.size();\n    if (n < 3) return false;\n    bool inside = false;\n    for (int i = 0, j = n - 1; i < n; j = i++) {\n        if (((poly.vertices[i].y > p.y) != (poly.vertices[j].y > p.y)) &&\n            (p.x < (poly.vertices[j].x - poly.vertices[i].x) * (p.y - poly.vertices[i].y) / (poly.vertices[j].y - poly.vertices[i].y) + poly.vertices[i].x))\n            inside = !inside;\n    }\n    return inside;\n}\n\nint count_points_in_polygon(const vector<Point> &points, const Polygon &poly) {\n    int count = 0;\n    for (const auto &p : points) {\n        if (is_point_in_polygon(p, poly)) {\n            count++;\n        }\n    }\n    return count;\n}\n\nPolygon generate_random_polygon(const vector<Point> &hull, int max_vertices, int max_edge_length) {\n    Polygon poly;\n    int n = hull.size();\n    if (n < 4) return poly;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, n - 1);\n\n    int start = dis(gen);\n    poly.vertices.push_back(hull[start]);\n\n    int current = start;\n    int total_length = 0;\n    while (poly.vertices.size() < max_vertices) {\n        int next = (current + 1) % n;\n        int dx = hull[next].x - hull[current].x;\n        int dy = hull[next].y - hull[current].y;\n        int edge_length = abs(dx) + abs(dy);\n\n        if (total_length + edge_length > max_edge_length) {\n            break;\n        }\n\n        if (dx != 0 && dy != 0) {\n            // Ensure edges are parallel to x-axis or y-axis\n            if (abs(dx) > abs(dy)) {\n                poly.vertices.emplace_back(hull[current].x + dx, hull[current].y);\n            } else {\n                poly.vertices.emplace_back(hull[current].x, hull[current].y + dy);\n            }\n        } else {\n            poly.vertices.push_back(hull[next]);\n        }\n\n        total_length += edge_length;\n        current = next;\n    }\n\n    // Close the polygon\n    if (poly.vertices.size() >= 3) {\n        int dx = poly.vertices.back().x - poly.vertices[0].x;\n        int dy = poly.vertices.back().y - poly.vertices[0].y;\n        if (dx != 0 && dy != 0) {\n            if (abs(dx) > abs(dy)) {\n                poly.vertices.emplace_back(poly.vertices.back().x, poly.vertices[0].y);\n            } else {\n                poly.vertices.emplace_back(poly.vertices[0].x, poly.vertices.back().y);\n            }\n        }\n    }\n\n    return poly;\n}\n\nint evaluate_polygon(const Polygon &poly, const vector<Point> &mackerels, const vector<Point> &sardines) {\n    int m = count_points_in_polygon(mackerels, poly);\n    int s = count_points_in_polygon(sardines, poly);\n    return max(0, m - s + 1);\n}\n\nPolygon simulated_annealing(const vector<Point> &hull, const vector<Point> &mackerels, const vector<Point> &sardines, int max_vertices, int max_edge_length, int iterations) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    Polygon current = generate_random_polygon(hull, max_vertices, max_edge_length);\n    current.mackerels = count_points_in_polygon(mackerels, current);\n    current.sardines = count_points_in_polygon(sardines, current);\n    int current_score = evaluate_polygon(current, mackerels, sardines);\n\n    Polygon best = current;\n    int best_score = current_score;\n\n    double temperature = 1.0;\n    double cooling_rate = 0.999;\n\n    for (int i = 0; i < iterations; ++i) {\n        Polygon neighbor = generate_random_polygon(hull, max_vertices, max_edge_length);\n        neighbor.mackerels = count_points_in_polygon(mackerels, neighbor);\n        neighbor.sardines = count_points_in_polygon(sardines, neighbor);\n        int neighbor_score = evaluate_polygon(neighbor, mackerels, sardines);\n\n        if (neighbor_score > current_score || dis(gen) < exp((neighbor_score - current_score) / temperature)) {\n            current = neighbor;\n            current_score = neighbor_score;\n        }\n\n        if (current_score > best_score) {\n            best = current;\n            best_score = current_score;\n        }\n\n        temperature *= cooling_rate;\n    }\n\n    return best;\n}\n\nint main() {\n    int N;\n    cin >> N;\n\n    vector<Point> mackerels;\n    vector<Point> sardines;\n    vector<Point> all_points;\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        mackerels.emplace_back(x, y);\n        all_points.emplace_back(x, y);\n    }\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        sardines.emplace_back(x, y);\n        all_points.emplace_back(x, y);\n    }\n\n    vector<Point> hull = convex_hull(all_points);\n    int max_vertices = 1000;\n    int max_edge_length = 400000;\n    int iterations = 10000;\n\n    Polygon best_polygon = simulated_annealing(hull, mackerels, sardines, max_vertices, max_edge_length, iterations);\n\n    cout << best_polygon.vertices.size() << endl;\n    for (const auto &p : best_polygon.vertices) {\n        cout << p.x << \" \" << p.y << endl;\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <limits>\n#include <chrono>\n\nusing namespace std;\n\nstruct Rectangle {\n    int w, h;\n    int w_prime, h_prime;\n};\n\nstruct Placement {\n    int p; // index of the rectangle\n    int r; // rotation (0 or 1)\n    char d; // direction ('U' or 'L')\n    int b; // reference rectangle index or -1\n};\n\nstruct Solution {\n    vector<Placement> placements;\n    int width, height;\n    int score;\n};\n\nclass RectanglePacker {\nprivate:\n    int N, T, sigma;\n    vector<Rectangle> rectangles;\n    mt19937 rng;\n    uniform_real_distribution<double> dist;\n\n    Solution generateInitialSolution() {\n        Solution solution;\n        vector<int> indices(N);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), rng);\n\n        for (int i = 0; i < N; ++i) {\n            int p = indices[i];\n            int r = uniform_int_distribution<int>(0, 1)(rng);\n            char d = uniform_int_distribution<int>(0, 1)(rng) ? 'U' : 'L';\n            int b = i == 0 ? -1 : uniform_int_distribution<int>(-1, i - 1)(rng);\n            solution.placements.push_back({p, r, d, b});\n        }\n\n        return solution;\n    }\n\n    Solution placeRectangles(const Solution& solution) {\n        Solution result = solution;\n        vector<pair<int, int>> positions(N, {-1, -1});\n        int max_x = 0, max_y = 0;\n\n        for (const auto& placement : solution.placements) {\n            int p = placement.p;\n            int r = placement.r;\n            char d = placement.d;\n            int b = placement.b;\n\n            int w = r == 0 ? rectangles[p].w_prime : rectangles[p].h_prime;\n            int h = r == 0 ? rectangles[p].h_prime : rectangles[p].w_prime;\n\n            int x, y;\n            if (d == 'U') {\n                if (b == -1) {\n                    x = 0;\n                } else {\n                    x = positions[b].first + (r == 0 ? rectangles[b].w_prime : rectangles[b].h_prime);\n                }\n                y = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (positions[i].first != -1 && positions[i].first < x + w && positions[i].first + (r == 0 ? rectangles[i].w_prime : rectangles[i].h_prime) > x) {\n                        y = max(y, positions[i].second + (r == 0 ? rectangles[i].h_prime : rectangles[i].w_prime));\n                    }\n                }\n            } else { // d == 'L'\n                if (b == -1) {\n                    y = 0;\n                } else {\n                    y = positions[b].second + (r == 0 ? rectangles[b].h_prime : rectangles[b].w_prime);\n                }\n                x = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (positions[i].second != -1 && positions[i].second < y + h && positions[i].second + (r == 0 ? rectangles[i].h_prime : rectangles[i].w_prime) > y) {\n                        x = max(x, positions[i].first + (r == 0 ? rectangles[i].w_prime : rectangles[i].h_prime));\n                    }\n                }\n            }\n\n            positions[p] = {x, y};\n            max_x = max(max_x, x + w);\n            max_y = max(max_y, y + h);\n        }\n\n        result.width = max_x;\n        result.height = max_y;\n        result.score = max_x + max_y;\n\n        return result;\n    }\n\n    Solution mutateSolution(const Solution& solution) {\n        Solution new_solution = solution;\n        int mutation_type = uniform_int_distribution<int>(0, 2)(rng);\n\n        if (mutation_type == 0) { // Change rotation\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            new_solution.placements[idx].r = 1 - new_solution.placements[idx].r;\n        } else if (mutation_type == 1) { // Change direction\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            new_solution.placements[idx].d = new_solution.placements[idx].d == 'U' ? 'L' : 'U';\n        } else { // Change reference\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            int b = idx == 0 ? -1 : uniform_int_distribution<int>(-1, idx - 1)(rng);\n            new_solution.placements[idx].b = b;\n        }\n\n        return new_solution;\n    }\n\n    Solution simulatedAnnealing() {\n        Solution current_solution = generateInitialSolution();\n        current_solution = placeRectangles(current_solution);\n        Solution best_solution = current_solution;\n\n        double temperature = 1000.0;\n        double cooling_rate = 0.99;\n        int iterations = 1000;\n\n        for (int i = 0; i < iterations; ++i) {\n            Solution new_solution = mutateSolution(current_solution);\n            new_solution = placeRectangles(new_solution);\n\n            double delta = new_solution.score - current_solution.score;\n            if (delta < 0 || exp(-delta / temperature) > dist(rng)) {\n                current_solution = new_solution;\n                if (new_solution.score < best_solution.score) {\n                    best_solution = new_solution;\n                }\n            }\n\n            temperature *= cooling_rate;\n        }\n\n        return best_solution;\n    }\n\npublic:\n    RectanglePacker(int N, int T, int sigma, const vector<Rectangle>& rectangles)\n        : N(N), T(T), sigma(sigma), rectangles(rectangles), rng(chrono::steady_clock::now().time_since_epoch().count()), dist(0.0, 1.0) {}\n\n    Solution findBestSolution() {\n        Solution best_solution;\n        best_solution.score = numeric_limits<int>::max();\n\n        for (int t = 0; t < T; ++t) {\n            Solution solution = simulatedAnnealing();\n            if (solution.score < best_solution.score) {\n                best_solution = solution;\n            }\n        }\n\n        return best_solution;\n    }\n};\n\nint main() {\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n\n    vector<Rectangle> rectangles(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> rectangles[i].w_prime >> rectangles[i].h_prime;\n    }\n\n    RectanglePacker packer(N, T, sigma, rectangles);\n    Solution best_solution = packer.findBestSolution();\n\n    cout << best_solution.placements.size() << endl;\n    for (const auto& placement : best_solution.placements) {\n        cout << placement.p << \" \" << placement.r << \" \" << placement.d << \" \" << placement.b << endl;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_set>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n};\n\nstruct Vertex {\n    int id;\n    int beauty;\n    vector<int> neighbors;\n};\n\nstruct Tree {\n    int root;\n    vector<int> parent;\n    vector<int> height;\n};\n\nint N, M, H;\nvector<Vertex> vertices;\nvector<Edge> edges;\nvector<int> x, y;\n\nvoid input() {\n    cin >> N >> M >> H;\n    vertices.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> vertices[i].beauty;\n        vertices[i].id = i;\n    }\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        vertices[edges[i].u].neighbors.push_back(edges[i].v);\n        vertices[edges[i].v].neighbors.push_back(edges[i].u);\n    }\n    x.resize(N);\n    y.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> x[i] >> y[i];\n    }\n}\n\nvector<int> solve() {\n    vector<int> parent(N, -1);\n    vector<bool> visited(N, false);\n    priority_queue<pair<int, int>> pq; // (beauty, id)\n\n    for (int i = 0; i < N; ++i) {\n        pq.push({vertices[i].beauty, i});\n    }\n\n    while (!pq.empty()) {\n        auto current = pq.top();\n        pq.pop();\n        int u = current.second;\n\n        if (visited[u]) continue;\n        visited[u] = true;\n\n        queue<pair<int, int>> q; // (vertex, parent)\n        q.push({u, -1});\n        int current_height = 0;\n\n        while (!q.empty() && current_height <= H) {\n            int size = q.size();\n            for (int i = 0; i < size; ++i) {\n                auto front = q.front();\n                q.pop();\n                int v = front.first;\n                int p = front.second;\n\n                if (visited[v]) continue;\n                visited[v] = true;\n                parent[v] = p;\n\n                for (int neighbor : vertices[v].neighbors) {\n                    if (!visited[neighbor]) {\n                        q.push({neighbor, v});\n                    }\n                }\n            }\n            current_height++;\n        }\n    }\n\n    return parent;\n}\n\nint main() {\n    input();\n    auto parent = solve();\n    for (int p : parent) {\n        cout << p << \" \";\n    }\n    cout << endl;\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cassert>\n\nusing namespace std;\n\nstruct Move {\n    char direction;\n    int index;\n};\n\nvector<Move> solve(const vector<string>& board) {\n    int N = board.size();\n    vector<Move> moves;\n    vector<vector<char>> current_board(N, vector<char>(N));\n\n    // Convert the input board to a 2D vector of characters\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            current_board[i][j] = board[i][j];\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (current_board[i][j] == 'x') {\n                // Check if we can remove the Oni by shifting the row left\n                bool can_remove_left = true;\n                for (int k = 0; k < i; ++k) {\n                    if (current_board[k][j] == 'o') {\n                        can_remove_left = false;\n                        break;\n                    }\n                }\n                if (can_remove_left) {\n                    // Shift the row left to remove the Oni\n                    for (int k = 0; k <= i; ++k) {\n                        moves.push_back({'L', i});\n                    }\n                    for (int k = 0; k <= i; ++k) {\n                        moves.push_back({'R', i});\n                    }\n                    // Update the board state\n                    for (int k = 0; k < N - 1; ++k) {\n                        current_board[i][k] = current_board[i][k + 1];\n                    }\n                    current_board[i][N - 1] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the row right\n                bool can_remove_right = true;\n                for (int k = i + 1; k < N; ++k) {\n                    if (current_board[k][j] == 'o') {\n                        can_remove_right = false;\n                        break;\n                    }\n                }\n                if (can_remove_right) {\n                    // Shift the row right to remove the Oni\n                    for (int k = 0; k <= N - 1 - i; ++k) {\n                        moves.push_back({'R', i});\n                    }\n                    for (int k = 0; k <= N - 1 - i; ++k) {\n                        moves.push_back({'L', i});\n                    }\n                    // Update the board state\n                    for (int k = N - 1; k > 0; --k) {\n                        current_board[i][k] = current_board[i][k - 1];\n                    }\n                    current_board[i][0] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the column up\n                bool can_remove_up = true;\n                for (int k = 0; k < j; ++k) {\n                    if (current_board[i][k] == 'o') {\n                        can_remove_up = false;\n                        break;\n                    }\n                }\n                if (can_remove_up) {\n                    // Shift the column up to remove the Oni\n                    for (int k = 0; k <= j; ++k) {\n                        moves.push_back({'U', j});\n                    }\n                    for (int k = 0; k <= j; ++k) {\n                        moves.push_back({'D', j});\n                    }\n                    // Update the board state\n                    for (int k = 0; k < N - 1; ++k) {\n                        current_board[k][j] = current_board[k + 1][j];\n                    }\n                    current_board[N - 1][j] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the column down\n                bool can_remove_down = true;\n                for (int k = j + 1; k < N; ++k) {\n                    if (current_board[i][k] == 'o') {\n                        can_remove_down = false;\n                        break;\n                    }\n                }\n                if (can_remove_down) {\n                    // Shift the column down to remove the Oni\n                    for (int k = 0; k <= N - 1 - j; ++k) {\n                        moves.push_back({'D', j});\n                    }\n                    for (int k = 0; k <= N - 1 - j; ++k) {\n                        moves.push_back({'U', j});\n                    }\n                    // Update the board state\n                    for (int k = N - 1; k > 0; --k) {\n                        current_board[k][j] = current_board[k - 1][j];\n                    }\n                    current_board[0][j] = '.';\n                }\n            }\n        }\n    }\n\n    return moves;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n    }\n\n    vector<Move> moves = solve(board);\n\n    for (const auto& move : moves) {\n        cout << move.direction << \" \" << move.index << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nstruct Employee {\n    int a;\n    int b;\n};\n\nvector<int> simulate_cleaning_plan(const vector<Employee>& employees, int L) {\n    vector<int> actual(employees.size(), 0);\n    unordered_map<int, int> cycle_counts;\n    vector<bool> visited(employees.size(), false);\n    vector<int> path;\n\n    for (int i = 0; i < employees.size(); ++i) {\n        if (!visited[i]) {\n            int current = i;\n            path.clear();\n            while (!visited[current]) {\n                visited[current] = true;\n                path.push_back(current);\n                int t = count(actual.begin(), actual.end(), current);\n                if (t % 2 == 1) {\n                    current = employees[current].a;\n                } else {\n                    current = employees[current].b;\n                }\n            }\n\n            // Check if the current path is a cycle\n            auto it = find(path.begin(), path.end(), current);\n            if (it != path.end()) {\n                int cycle_length = distance(it, path.end());\n                int cycle_start = distance(path.begin(), it);\n                int cycle_repeats = (L - cycle_start) / cycle_length;\n                int remaining = (L - cycle_start) % cycle_length;\n\n                for (int j = cycle_start; j < path.size(); ++j) {\n                    actual[path[j]] += cycle_repeats;\n                }\n                for (int j = 0; j < remaining; ++j) {\n                    actual[path[cycle_start + j]]++;\n                }\n            } else {\n                for (int j = 0; j < path.size(); ++j) {\n                    actual[path[j]]++;\n                }\n            }\n        }\n    }\n\n    return actual;\n}\n\nint calculate_error(const vector<int>& actual, const vector<int>& target) {\n    int error = 0;\n    for (size_t i = 0; i < actual.size(); ++i) {\n        error += abs(actual[i] - target[i]);\n    }\n    return error;\n}\n\nvector<Employee> generate_initial_state(int N) {\n    vector<Employee> employees(N);\n    for (int i = 0; i < N; ++i) {\n        employees[i].a = i;\n        employees[i].b = i;\n    }\n    return employees;\n}\n\nvector<Employee> hill_climbing(const vector<int>& target, int N, int L, int iterations) {\n    vector<Employee> current_employees = generate_initial_state(N);\n    vector<int> current_actual = simulate_cleaning_plan(current_employees, L);\n    int current_error = calculate_error(current_actual, target);\n\n    for (int i = 0; i < iterations; ++i) {\n        vector<Employee> new_employees = current_employees;\n        int employee = rand() % N;\n        int choice = rand() % 2;\n\n        if (choice == 0) {\n            new_employees[employee].a = rand() % N;\n        } else {\n            new_employees[employee].b = rand() % N;\n        }\n\n        vector<int> new_actual = simulate_cleaning_plan(new_employees, L);\n        int new_error = calculate_error(new_actual, target);\n\n        if (new_error < current_error) {\n            current_employees = new_employees;\n            current_error = new_error;\n        }\n    }\n\n    return current_employees;\n}\n\nint main() {\n    int N, L;\n    cin >> N >> L;\n\n    vector<int> target(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> target[i];\n    }\n\n    int iterations = 10000;\n    vector<Employee> best_employees = hill_climbing(target, N, L, iterations);\n\n    for (const auto& employee : best_employees) {\n        cout << employee.a << \" \" << employee.b << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <limits>\n#include <functional>\n\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double cx, cy; // Center coordinates\n};\n\nstruct Edge {\n    int u, v;\n    double distance;\n};\n\nstruct CompareEdge {\n    bool operator()(const Edge& a, const Edge& b) {\n        return a.distance > b.distance;\n    }\n};\n\nvector<Edge> query(const vector<int>& cities) {\n    cout << \"? \" << cities.size();\n    for (int city : cities) {\n        cout << \" \" << city;\n    }\n    cout << endl;\n    cout.flush();\n\n    vector<Edge> edges;\n    for (size_t i = 0; i < cities.size() - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        edges.push_back({u, v, 0.0}); // Distance will be calculated later\n    }\n    return edges;\n}\n\nvoid answer(const vector<vector<int>>& groups, const vector<vector<Edge>>& edges) {\n    cout << \"!\" << endl;\n    for (size_t i = 0; i < groups.size(); ++i) {\n        for (int city : groups[i]) {\n            cout << city << \" \";\n        }\n        cout << endl;\n        for (const Edge& edge : edges[i]) {\n            cout << edge.u << \" \" << edge.v << endl;\n        }\n    }\n}\n\nvector<vector<int>> greedyGrouping(const vector<City>& cities, const vector<int>& G) {\n    vector<City> sortedCities = cities;\n    sort(sortedCities.begin(), sortedCities.end(), [](const City& a, const City& b) {\n        return a.cx < b.cx || (a.cx == b.cx && a.cy < b.cy);\n    });\n\n    vector<vector<int>> groups;\n    size_t startIdx = 0;\n    for (int g : G) {\n        vector<int> group;\n        for (size_t i = startIdx; i < startIdx + g; ++i) {\n            group.push_back(sortedCities[i].id);\n        }\n        groups.push_back(group);\n        startIdx += g;\n    }\n    return groups;\n}\n\nvector<Edge> calculateMST(const vector<int>& group, const vector<City>& cities) {\n    unordered_map<int, int> cityToIndex;\n    for (size_t i = 0; i < cities.size(); ++i) {\n        cityToIndex[cities[i].id] = i;\n    }\n\n    vector<vector<double>> dist(group.size(), vector<double>(group.size(), 0.0));\n    for (size_t i = 0; i < group.size(); ++i) {\n        for (size_t j = i + 1; j < group.size(); ++j) {\n            const City& a = cities[cityToIndex[group[i]]];\n            const City& b = cities[cityToIndex[group[j]]];\n            double dx = a.cx - b.cx;\n            double dy = a.cy - b.cy;\n            dist[i][j] = dist[j][i] = sqrt(dx * dx + dy * dy);\n        }\n    }\n\n    priority_queue<Edge, vector<Edge>, CompareEdge> pq;\n    for (size_t i = 0; i < group.size(); ++i) {\n        for (size_t j = i + 1; j < group.size(); ++j) {\n            pq.push({group[i], group[j], dist[i][j]});\n        }\n    }\n\n    vector<Edge> mstEdges;\n    vector<int> parent(group.size(), -1);\n    vector<int> rank(group.size(), 0);\n\n    function<int(int)> find = [&](int u) {\n        if (parent[u] == -1) return u;\n        return parent[u] = find(parent[u]);\n    };\n\n    while (!pq.empty() && mstEdges.size() < group.size() - 1) {\n        Edge edge = pq.top();\n        pq.pop();\n        int u = find(edge.u);\n        int v = find(edge.v);\n        if (u != v) {\n            mstEdges.push_back(edge);\n            if (rank[u] > rank[v]) {\n                parent[v] = u;\n            } else {\n                parent[u] = v;\n                if (rank[u] == rank[v]) {\n                    rank[v]++;\n                }\n            }\n        }\n    }\n    return mstEdges;\n}\n\nint main() {\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> G[i];\n    }\n\n    vector<City> cities(N);\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cities[i] = {i, lx, rx, ly, ry, (lx + rx) / 2.0, (ly + ry) / 2.0};\n    }\n\n    vector<vector<int>> groups = greedyGrouping(cities, G);\n    vector<vector<Edge>> edges(M);\n\n    for (int k = 0; k < M; ++k) {\n        for (size_t i = 0; i < groups[k].size() - 1; i += 2) {\n            if (i < groups[k].size() - 2) {\n                vector<int> queryCities = {groups[k][i], groups[k][i + 1], groups[k][i + 2]};\n                vector<Edge> queryEdges = query(queryCities);\n                edges[k].insert(edges[k].end(), queryEdges.begin(), queryEdges.end());\n            } else {\n                edges[k].push_back({groups[k][i], groups[k][i + 1], 0.0});\n            }\n        }\n    }\n\n    answer(groups, edges);\n\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 20;\nconst int M = 40;\nconst int MAX_ACTIONS = 2 * N * M;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct State {\n    Point pos;\n    unordered_set<Point> blocks;\n    int visited;\n    int actions;\n    State(Point pos, unordered_set<Point> blocks, int visited, int actions)\n        : pos(pos), blocks(blocks), visited(visited), actions(actions) {}\n};\n\nstruct Action {\n    char type;\n    char direction;\n    Action(char type, char direction) : type(type), direction(direction) {}\n};\n\nvector<Action> directions = {\n    {'U', 'U'}, {'D', 'D'}, {'L', 'L'}, {'R', 'R'}\n};\n\nvector<Action> actions = {\n    {'M', 'U'}, {'M', 'D'}, {'M', 'L'}, {'M', 'R'},\n    {'S', 'U'}, {'S', 'D'}, {'S', 'L'}, {'S', 'R'},\n    {'A', 'U'}, {'A', 'D'}, {'A', 'L'}, {'A', 'R'}\n};\n\nbool isValid(Point p) {\n    return p.x >= 0 && p.x < N && p.y >= 0 && p.y < N;\n}\n\nPoint move(Point p, char direction) {\n    switch (direction) {\n        case 'U': return Point(p.x - 1, p.y);\n        case 'D': return Point(p.x + 1, p.y);\n        case 'L': return Point(p.x, p.y - 1);\n        case 'R': return Point(p.x, p.y + 1);\n    }\n    return p;\n}\n\nPoint slide(Point p, char direction, const unordered_set<Point>& blocks) {\n    Point next = p;\n    while (true) {\n        Point newPos = move(next, direction);\n        if (!isValid(newPos) || blocks.count(newPos)) break;\n        next = newPos;\n    }\n    return next;\n}\n\nunordered_set<Point> alter(Point p, char direction, unordered_set<Point> blocks) {\n    Point target = move(p, direction);\n    if (isValid(target)) {\n        if (blocks.count(target)) {\n            blocks.erase(target);\n        } else {\n            blocks.insert(target);\n        }\n    }\n    return blocks;\n}\n\nint heuristic(Point a, Point b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvector<Action> solve(vector<Point> targets) {\n    vector<Action> result;\n    unordered_set<Point> blocks;\n    Point current = targets[0];\n    int visited = 0;\n\n    for (int i = 1; i < targets.size(); ++i) {\n        Point target = targets[i];\n        priority_queue<pair<int, State>, vector<pair<int, State>>, greater<pair<int, State>>> pq;\n        unordered_set<Point> initialBlocks = blocks;\n        pq.push({heuristic(current, target), State(current, initialBlocks, visited, 0)});\n\n        while (!pq.empty()) {\n            auto [cost, state] = pq.top();\n            pq.pop();\n\n            if (state.pos == target) {\n                current = target;\n                visited = i;\n                blocks = state.blocks;\n                break;\n            }\n\n            if (state.actions >= MAX_ACTIONS) continue;\n\n            for (auto& action : actions) {\n                Point newPos = state.pos;\n                unordered_set<Point> newBlocks = state.blocks;\n                int newVisited = state.visited;\n                int newActions = state.actions + 1;\n\n                if (action.type == 'M') {\n                    newPos = move(state.pos, action.direction);\n                    if (!isValid(newPos) || newBlocks.count(newPos)) continue;\n                } else if (action.type == 'S') {\n                    newPos = slide(state.pos, action.direction, newBlocks);\n                } else if (action.type == 'A') {\n                    newBlocks = alter(state.pos, action.direction, newBlocks);\n                }\n\n                if (newPos == target) newVisited = i;\n\n                int newCost = newActions + heuristic(newPos, target);\n                pq.push({newCost, State(newPos, newBlocks, newVisited, newActions)});\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<Point> targets;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        targets.emplace_back(x, y);\n    }\n\n    vector<Action> result = solve(targets);\n    for (auto& action : result) {\n        cout << action.type << \" \" << action.direction << endl;\n    }\n\n    return 0;\n}"},"8":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nstruct Rectangle {\n    int a, b, c, d; // Coordinates of the rectangle\n    int area;       // Area of the rectangle\n};\n\nstruct Company {\n    int x, y;       // Desired location\n    int r;          // Desired area\n};\n\ndouble satisfaction_level(const Rectangle& rect, const Company& company) {\n    if (rect.a > company.x || rect.c <= company.x || rect.b > company.y || rect.d <= company.y) {\n        return 0.0;\n    }\n    double s_i = rect.area;\n    double r_i = company.r;\n    double min_val = min(r_i, s_i);\n    double max_val = max(r_i, s_i);\n    double p_i = 1.0 - pow(1.0 - min_val / max_val, 2.0);\n    return p_i;\n}\n\nbool is_overlapping(const Rectangle& rect1, const Rectangle& rect2) {\n    return !(rect1.c <= rect2.a || rect2.c <= rect1.a || rect1.d <= rect2.b || rect2.d <= rect1.b);\n}\n\nvector<Rectangle> generate_initial_solution(const vector<Company>& companies) {\n    vector<Rectangle> rectangles;\n    for (const auto& company : companies) {\n        int width = static_cast<int>(sqrt(company.r));\n        int height = company.r / width;\n        if (width * height < company.r) {\n            height++;\n        }\n        int a = max(0, company.x - width / 2);\n        int b = max(0, company.y - height / 2);\n        int c = min(10000, a + width);\n        int d = min(10000, b + height);\n        Rectangle rect = {a, b, c, d, (c - a) * (d - b)};\n        rectangles.push_back(rect);\n    }\n    return rectangles;\n}\n\ndouble total_satisfaction(const vector<Rectangle>& rectangles, const vector<Company>& companies) {\n    double total = 0.0;\n    for (size_t i = 0; i < companies.size(); ++i) {\n        total += satisfaction_level(rectangles[i], companies[i]);\n    }\n    return total;\n}\n\nvector<Rectangle> simulated_annealing(const vector<Company>& companies, vector<Rectangle> initial_rectangles, double initial_temp, double cooling_rate, int iterations) {\n    vector<Rectangle> current_rectangles = initial_rectangles;\n    double current_satisfaction = total_satisfaction(current_rectangles, companies);\n    vector<Rectangle> best_rectangles = current_rectangles;\n    double best_satisfaction = current_satisfaction;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    for (double temp = initial_temp; temp > 1e-6; temp *= cooling_rate) {\n        for (int i = 0; i < iterations; ++i) {\n            vector<Rectangle> new_rectangles = current_rectangles;\n            int idx = dis(gen) * companies.size();\n            int delta_x = (dis(gen) * 2 - 1) * 10;\n            int delta_y = (dis(gen) * 2 - 1) * 10;\n            new_rectangles[idx].a = max(0, new_rectangles[idx].a + delta_x);\n            new_rectangles[idx].b = max(0, new_rectangles[idx].b + delta_y);\n            new_rectangles[idx].c = min(10000, new_rectangles[idx].c + delta_x);\n            new_rectangles[idx].d = min(10000, new_rectangles[idx].d + delta_y);\n            new_rectangles[idx].area = (new_rectangles[idx].c - new_rectangles[idx].a) * (new_rectangles[idx].d - new_rectangles[idx].b);\n\n            bool valid = true;\n            for (size_t j = 0; j < new_rectangles.size(); ++j) {\n                if (j != idx && is_overlapping(new_rectangles[idx], new_rectangles[j])) {\n                    valid = false;\n                    break;\n                }\n            }\n\n            if (valid) {\n                double new_satisfaction = total_satisfaction(new_rectangles, companies);\n                double delta = new_satisfaction - current_satisfaction;\n                if (delta > 0 || dis(gen) < exp(delta / temp)) {\n                    current_rectangles = new_rectangles;\n                    current_satisfaction = new_satisfaction;\n                    if (current_satisfaction > best_satisfaction) {\n                        best_rectangles = current_rectangles;\n                        best_satisfaction = current_satisfaction;\n                    }\n                }\n            }\n        }\n    }\n    return best_rectangles;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector<Company> companies(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n\n    vector<Rectangle> initial_rectangles = generate_initial_solution(companies);\n    vector<Rectangle> best_rectangles = simulated_annealing(companies, initial_rectangles, 1000.0, 0.99, 1000);\n\n    for (const auto& rect : best_rectangles) {\n        cout << rect.a << \" \" << rect.b << \" \" << rect.c << \" \" << rect.d << endl;\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <unordered_set>\n#include <queue>\n#include <utility>\n#include <unordered_map>\n\nusing namespace std;\n\nconst int SIZE = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\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\nbool is_valid(int x, int y) {\n    return x >= 0 && x < SIZE && y >= 0 && y < SIZE;\n}\n\nint heuristic(int x, int y, const vector<vector<int>>& points) {\n    int max_score = 0;\n    for (int i = max(0, x - 2); i < min(SIZE, x + 3); ++i) {\n        for (int j = max(0, y - 2); j < min(SIZE, y + 3); ++j) {\n            max_score = max(max_score, points[i][j]);\n        }\n    }\n    return max_score;\n}\n\nstruct CompareState {\n    bool operator()(const pair<int, State>& a, const pair<int, State>& b) {\n        return a.first < b.first;\n    }\n};\n\nstring find_max_score_path(int si, int sj, const vector<vector<int>>& tiles, const vector<vector<int>>& points) {\n    unordered_set<int> initial_visited_tiles;\n    initial_visited_tiles.insert(tiles[si][sj]);\n    priority_queue<pair<int, State>, vector<pair<int, State>>, CompareState> pq;\n    pq.emplace(points[si][sj] + heuristic(si, sj, points), State(si, sj, points[si][sj], \"\", initial_visited_tiles));\n\n    unordered_map<int, unordered_map<int, int>> best_scores;\n    best_scores[si][sj] = points[si][sj];\n\n    int max_score = points[si][sj];\n    string best_path;\n\n    while (!pq.empty()) {\n        auto [current_priority, current] = pq.top();\n        pq.pop();\n\n        if (current.score > max_score) {\n            max_score = current.score;\n            best_path = current.path;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = current.x + dx[i];\n            int ny = current.y + dy[i];\n\n            if (is_valid(nx, ny) && current.visited_tiles.find(tiles[nx][ny]) == current.visited_tiles.end()) {\n                int new_score = current.score + points[nx][ny];\n                if (best_scores[nx][ny] < new_score) {\n                    best_scores[nx][ny] = new_score;\n                    unordered_set<int> new_visited_tiles = current.visited_tiles;\n                    new_visited_tiles.insert(tiles[nx][ny]);\n                    pq.emplace(new_score + heuristic(nx, ny, points), State(nx, ny, new_score, current.path + dir[i], new_visited_tiles));\n                }\n            }\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> tiles(SIZE, vector<int>(SIZE));\n    for (int i = 0; i < SIZE; ++i) {\n        for (int j = 0; j < SIZE; ++j) {\n            cin >> tiles[i][j];\n        }\n    }\n\n    vector<vector<int>> points(SIZE, vector<int>(SIZE));\n    for (int i = 0; i < SIZE; ++i) {\n        for (int j = 0; j < SIZE; ++j) {\n            cin >> points[i][j];\n        }\n    }\n\n    string path = find_max_score_path(si, sj, tiles, points);\n    cout << path << endl;\n\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <unordered_map>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int QUERY_COUNT = 1000;\nconst double DECAY_FACTOR = 0.998;\nconst double SCORE_MULTIPLIER = 2312311;\n\nstruct Vertex {\n    int i, j;\n    Vertex(int i, int j) : i(i), j(j) {}\n    bool operator==(const Vertex& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Vertex> {\n        size_t operator()(const Vertex& v) const {\n            return hash<int>()(v.i) ^ hash<int>()(v.j);\n        }\n    };\n}\n\nstruct Edge {\n    Vertex from, to;\n    double estimated_length;\n    Edge(Vertex from, Vertex to, double estimated_length) : from(from), to(to), estimated_length(estimated_length) {}\n};\n\nclass Graph {\nprivate:\n    vector<vector<Vertex>> vertices;\n    unordered_map<Vertex, vector<Edge>> edges;\n    unordered_map<Vertex, unordered_map<Vertex, double>> estimated_lengths;\n\npublic:\n    Graph() {\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            vector<Vertex> row;\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                row.emplace_back(i, j);\n            }\n            vertices.push_back(row);\n        }\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                Vertex from(i, j);\n                if (i > 0) {\n                    Vertex to(i - 1, j);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (i < GRID_SIZE - 1) {\n                    Vertex to(i + 1, j);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (j > 0) {\n                    Vertex to(i, j - 1);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (j < GRID_SIZE - 1) {\n                    Vertex to(i, j + 1);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n            }\n        }\n    }\n\n    void update_estimated_lengths(const vector<Vertex>& path, double actual_length) {\n        double path_length = 0.0;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            path_length += estimated_lengths[path[k]][path[k + 1]];\n        }\n        double factor = actual_length / path_length;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            estimated_lengths[path[k]][path[k + 1]] *= factor;\n            estimated_lengths[path[k + 1]][path[k]] *= factor;\n        }\n    }\n\n    vector<Vertex> a_star_search(const Vertex& start, const Vertex& goal) {\n        auto heuristic = [&](const Vertex& v) {\n            return abs(v.i - goal.i) + abs(v.j - goal.j);\n        };\n\n        priority_queue<pair<double, Vertex>, vector<pair<double, Vertex>>, greater<pair<double, Vertex>>> open_set;\n        unordered_map<Vertex, Vertex> came_from;\n        unordered_map<Vertex, double> g_score;\n        unordered_map<Vertex, double> f_score;\n\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                Vertex v(i, j);\n                g_score[v] = numeric_limits<double>::infinity();\n                f_score[v] = numeric_limits<double>::infinity();\n            }\n        }\n\n        g_score[start] = 0.0;\n        f_score[start] = heuristic(start);\n        open_set.push({f_score[start], start});\n\n        while (!open_set.empty()) {\n            Vertex current = open_set.top().second;\n            open_set.pop();\n\n            if (current == goal) {\n                vector<Vertex> path;\n                while (came_from.find(current) != came_from.end()) {\n                    path.push_back(current);\n                    current = came_from[current];\n                }\n                path.push_back(start);\n                reverse(path.begin(), path.end());\n                return path;\n            }\n\n            for (const Edge& edge : edges[current]) {\n                Vertex neighbor = edge.to;\n                double tentative_g_score = g_score[current] + estimated_lengths[current][neighbor];\n\n                if (tentative_g_score < g_score[neighbor]) {\n                    came_from[neighbor] = current;\n                    g_score[neighbor] = tentative_g_score;\n                    f_score[neighbor] = g_score[neighbor] + heuristic(neighbor);\n                    open_set.push({f_score[neighbor], neighbor});\n                }\n            }\n        }\n\n        return {};\n    }\n\n    string path_to_string(const vector<Vertex>& path) {\n        stringstream ss;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            Vertex from = path[k];\n            Vertex to = path[k + 1];\n            if (to.i == from.i - 1) {\n                ss << \"U\";\n            } else if (to.i == from.i + 1) {\n                ss << \"D\";\n            } else if (to.j == from.j - 1) {\n                ss << \"L\";\n            } else if (to.j == from.j + 1) {\n                ss << \"R\";\n            }\n        }\n        return ss.str();\n    }\n};\n\nint main() {\n    Graph graph;\n    double score = 0.0;\n    int prev_result = 0;\n\n    for (int k = 0; k < QUERY_COUNT; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        Vertex start(si, sj);\n        Vertex goal(ti, tj);\n\n        vector<Vertex> path = graph.a_star_search(start, goal);\n        string path_str = graph.path_to_string(path);\n        cout << path_str << endl;\n        cout.flush();\n\n        int actual_length;\n        cin >> actual_length;\n\n        graph.update_estimated_lengths(path, actual_length);\n\n        double path_length = 0.0;\n        for (size_t i = 0; i < path.size() - 1; ++i) {\n            path_length += graph.estimated_lengths[path[i]][path[i + 1]];\n        }\n\n        double ratio = actual_length / path_length;\n        score = score * DECAY_FACTOR + ratio;\n    }\n\n    cout << round(SCORE_MULTIPLIER * score) << endl;\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <unordered_set>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int ALPHABET_SIZE = 8;\nconst char ALPHABET[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};\nconst char EMPTY = '.';\n\nstruct Matrix {\n    vector<vector<char>> data;\n\n    Matrix() : data(N, vector<char>(N, EMPTY)) {}\n\n    void randomize() {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, ALPHABET_SIZE - 1);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                data[i][j] = ALPHABET[dis(gen)];\n            }\n        }\n    }\n\n    void mutate(double rate) {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_real_distribution<> prob(0.0, 1.0);\n        uniform_int_distribution<> dis(0, ALPHABET_SIZE - 1);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (prob(gen) < rate) {\n                    data[i][j] = ALPHABET[dis(gen)];\n                }\n            }\n        }\n    }\n\n    bool is_subsequence(const string& s) {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                // Check horizontal subsequence\n                bool match = true;\n                for (int k = 0; k < s.size(); ++k) {\n                    if (data[i][(j + k) % N] != s[k]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) return true;\n\n                // Check vertical subsequence\n                match = true;\n                for (int k = 0; k < s.size(); ++k) {\n                    if (data[(i + k) % N][j] != s[k]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) return true;\n            }\n        }\n        return false;\n    }\n\n    int count_subsequences(const vector<string>& strings) {\n        int count = 0;\n        for (const auto& s : strings) {\n            if (is_subsequence(s)) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    int count_empty() {\n        int count = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (data[i][j] == EMPTY) {\n                    count++;\n                }\n            }\n        }\n        return count;\n    }\n\n    void print() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << data[i][j];\n            }\n            cout << endl;\n        }\n    }\n};\n\ndouble evaluate(const Matrix& matrix, const vector<string>& strings) {\n    int c = matrix.count_subsequences(strings);\n    if (c < strings.size()) {\n        return static_cast<double>(c) / strings.size();\n    } else {\n        int d = matrix.count_empty();\n        return static_cast<double>(2 * N * N) / (2 * N * N - d);\n    }\n}\n\nMatrix genetic_algorithm(const vector<string>& strings, int population_size, int generations, double mutation_rate) {\n    random_device rd;\n    mt19937 gen(rd());\n    vector<Matrix> population(population_size);\n\n    for (auto& matrix : population) {\n        matrix.randomize();\n    }\n\n    for (int gen = 0; gen < generations; ++gen) {\n        vector<double> fitness(population_size);\n        for (int i = 0; i < population_size; ++i) {\n            fitness[i] = evaluate(population[i], strings);\n        }\n\n        vector<Matrix> new_population;\n        for (int i = 0; i < population_size; ++i) {\n            uniform_int_distribution<> dis(0, population_size - 1);\n            int parent1 = dis(gen);\n            int parent2 = dis(gen);\n\n            Matrix child;\n            for (int x = 0; x < N; ++x) {\n                for (int y = 0; y < N; ++y) {\n                    if (fitness[parent1] > fitness[parent2]) {\n                        child.data[x][y] = population[parent1].data[x][y];\n                    } else {\n                        child.data[x][y] = population[parent2].data[x][y];\n                    }\n                }\n            }\n\n            child.mutate(mutation_rate);\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n    }\n\n    auto best = max_element(population.begin(), population.end(), [&](const Matrix& a, const Matrix& b) {\n        return evaluate(a, strings) < evaluate(b, strings);\n    });\n\n    return *best;\n}\n\nMatrix simulated_annealing(const vector<string>& strings, double initial_temp, double cooling_rate, int iterations) {\n    Matrix current;\n    current.randomize();\n    double current_score = evaluate(current, strings);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> prob(0.0, 1.0);\n\n    double temp = initial_temp;\n    for (int i = 0; i < iterations; ++i) {\n        Matrix neighbor = current;\n        neighbor.mutate(0.1);\n\n        double neighbor_score = evaluate(neighbor, strings);\n        double delta = neighbor_score - current_score;\n\n        if (delta > 0 || prob(gen) < exp(delta / temp)) {\n            current = neighbor;\n            current_score = neighbor_score;\n        }\n\n        temp *= cooling_rate;\n    }\n\n    return current;\n}\n\nint main() {\n    int M;\n    cin >> M;\n    vector<string> strings(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i];\n    }\n\n    // Run genetic algorithm\n    Matrix best_matrix = genetic_algorithm(strings, 50, 100, 0.01);\n\n    // Run simulated annealing\n    Matrix sa_matrix = simulated_annealing(strings, 1000.0, 0.99, 10000);\n\n    // Choose the best solution\n    if (evaluate(sa_matrix, strings) > evaluate(best_matrix, strings)) {\n        best_matrix = sa_matrix;\n    }\n\n    best_matrix.print();\n\n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int i, j;\n    Point(int i, int j) : i(i), j(j) {}\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.i) ^ hash<int>()(p.j);\n        }\n    };\n}\n\nclass PatrolRoute {\nprivate:\n    int N;\n    Point start;\n    vector<string> grid;\n    vector<vector<unordered_set<Point>>> visibility;\n    vector<Point> roadSquares;\n    vector<vector<int>> moveTime;\n    vector<vector<int>> dist;\n\n    void precomputeVisibility() {\n        visibility.resize(N, vector<unordered_set<Point>>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == '#') continue;\n                // Horizontal visibility\n                for (int k = j - 1; k >= 0; --k) {\n                    if (grid[i][k] == '#') break;\n                    visibility[i][j].insert(Point(i, k));\n                }\n                for (int k = j + 1; k < N; ++k) {\n                    if (grid[i][k] == '#') break;\n                    visibility[i][j].insert(Point(i, k));\n                }\n                // Vertical visibility\n                for (int k = i - 1; k >= 0; --k) {\n                    if (grid[k][j] == '#') break;\n                    visibility[i][j].insert(Point(k, j));\n                }\n                for (int k = i + 1; k < N; ++k) {\n                    if (grid[k][j] == '#') break;\n                    visibility[i][j].insert(Point(k, j));\n                }\n            }\n        }\n    }\n\n    void precomputeRoadSquares() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] != '#') {\n                    roadSquares.emplace_back(i, j);\n                }\n            }\n        }\n    }\n\n    void precomputeMoveTime() {\n        moveTime.resize(N, vector<int>(N, 0));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] != '#') {\n                    moveTime[i][j] = grid[i][j] - '0';\n                }\n            }\n        }\n    }\n\n    void precomputeDistances() {\n        dist.resize(N, vector<int>(N, -1));\n        queue<Point> q;\n        q.push(start);\n        dist[start.i][start.j] = 0;\n        while (!q.empty()) {\n            Point current = q.front();\n            q.pop();\n            for (const auto& neighbor : getNeighbors(current)) {\n                if (dist[neighbor.i][neighbor.j] == -1) {\n                    dist[neighbor.i][neighbor.j] = dist[current.i][current.j] + moveTime[neighbor.i][neighbor.j];\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n\n    vector<Point> getNeighbors(const Point& p) {\n        vector<Point> neighbors;\n        if (p.i > 0 && grid[p.i - 1][p.j] != '#') neighbors.emplace_back(p.i - 1, p.j);\n        if (p.i < N - 1 && grid[p.i + 1][p.j] != '#') neighbors.emplace_back(p.i + 1, p.j);\n        if (p.j > 0 && grid[p.i][p.j - 1] != '#') neighbors.emplace_back(p.i, p.j - 1);\n        if (p.j < N - 1 && grid[p.i][p.j + 1] != '#') neighbors.emplace_back(p.i, p.j + 1);\n        return neighbors;\n    }\n\n    vector<Point> greedyInitialization() {\n        unordered_set<Point> covered;\n        vector<Point> path;\n        Point current = start;\n        path.push_back(current);\n        covered.insert(visibility[current.i][current.j].begin(), visibility[current.i][current.j].end());\n        while (covered.size() < roadSquares.size()) {\n            Point next;\n            int maxNewCovered = -1;\n            for (const auto& neighbor : getNeighbors(current)) {\n                int newCovered = 0;\n                for (const auto& visible : visibility[neighbor.i][neighbor.j]) {\n                    if (covered.find(visible) == covered.end()) {\n                        newCovered++;\n                    }\n                }\n                if (newCovered > maxNewCovered) {\n                    maxNewCovered = newCovered;\n                    next = neighbor;\n                }\n            }\n            if (maxNewCovered == 0) break; // No progress, break to avoid infinite loop\n            current = next;\n            path.push_back(current);\n            covered.insert(visibility[current.i][current.j].begin(), visibility[current.i][current.j].end());\n        }\n        return path;\n    }\n\n    vector<Point> geneticAlgorithm(const vector<Point>& initialPath) {\n        vector<Point> bestPath = initialPath;\n        int bestScore = calculateScore(bestPath);\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, roadSquares.size() - 1);\n        for (int iter = 0; iter < 1000; ++iter) {\n            vector<Point> newPath = bestPath;\n            int a = dis(gen);\n            int b = dis(gen);\n            if (a > b) swap(a, b);\n            reverse(newPath.begin() + a, newPath.begin() + b);\n            int newScore = calculateScore(newPath);\n            if (newScore > bestScore) {\n                bestPath = newPath;\n                bestScore = newScore;\n            }\n        }\n        return bestPath;\n    }\n\n    int calculateScore(const vector<Point>& path) {\n        unordered_set<Point> covered;\n        for (const auto& point : path) {\n            covered.insert(visibility[point.i][point.j].begin(), visibility[point.i][point.j].end());\n        }\n        int v = covered.size();\n        int r = roadSquares.size();\n        if (v < r) {\n            return round(10000 * v / r);\n        } else {\n            int t = 0;\n            for (size_t i = 1; i < path.size(); ++i) {\n                t += moveTime[path[i].i][path[i].j];\n            }\n            return round(10000 + 10000000 * N / t);\n        }\n    }\n\npublic:\n    PatrolRoute(int N, int si, int sj, const vector<string>& grid) : N(N), start(si, sj), grid(grid) {\n        precomputeVisibility();\n        precomputeRoadSquares();\n        precomputeMoveTime();\n        precomputeDistances();\n    }\n\n    string findRoute() {\n        vector<Point> initialPath = greedyInitialization();\n        vector<Point> optimizedPath = geneticAlgorithm(initialPath);\n        string route;\n        for (size_t i = 1; i < optimizedPath.size(); ++i) {\n            Point prev = optimizedPath[i - 1];\n            Point curr = optimizedPath[i];\n            if (curr.i == prev.i - 1) route += 'U';\n            else if (curr.i == prev.i + 1) route += 'D';\n            else if (curr.j == prev.j - 1) route += 'L';\n            else if (curr.j == prev.j + 1) route += 'R';\n        }\n        return route;\n    }\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n    PatrolRoute patrolRoute(N, si, sj, grid);\n    cout << patrolRoute.findRoute() << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <unordered_set>\n#include <queue>\n#include <cmath>\n\nusing namespace std;\n\nstruct Task {\n    vector<int> required_skills;\n    vector<int> dependencies;\n    int duration;\n    bool completed;\n};\n\nstruct TeamMember {\n    vector<int> skills;\n    int current_task;\n    int days_left;\n};\n\nvector<Task> tasks;\nvector<TeamMember> team_members;\nvector<vector<int>> task_dependencies;\nvector<int> in_degree;\nvector<int> completed_tasks;\nvector<int> available_tasks;\n\nvoid initialize(int N, int M, int K, int R) {\n    tasks.resize(N);\n    team_members.resize(M);\n    task_dependencies.resize(N);\n    in_degree.resize(N, 0);\n    completed_tasks.resize(N, 0);\n    available_tasks.resize(N, 0);\n\n    for (int i = 0; i < N; ++i) {\n        tasks[i].required_skills.resize(K);\n        tasks[i].dependencies.clear();\n        tasks[i].duration = 0;\n        tasks[i].completed = false;\n    }\n\n    for (int i = 0; i < M; ++i) {\n        team_members[i].skills.resize(K, 0);\n        team_members[i].current_task = -1;\n        team_members[i].days_left = 0;\n    }\n\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        task_dependencies[u - 1].push_back(v - 1);\n        in_degree[v - 1]++;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        if (in_degree[i] == 0) {\n            available_tasks[i] = 1;\n        }\n    }\n}\n\nvoid update_skills(int member, const vector<int>& completed_tasks) {\n    for (int task : completed_tasks) {\n        for (int k = 0; k < team_members[member].skills.size(); ++k) {\n            team_members[member].skills[k] = max(team_members[member].skills[k], tasks[task].required_skills[k]);\n        }\n    }\n}\n\nint calculate_duration(int task, int member) {\n    int w = 0;\n    for (int k = 0; k < tasks[task].required_skills.size(); ++k) {\n        w += max(0, tasks[task].required_skills[k] - team_members[member].skills[k]);\n    }\n\n    if (w == 0) {\n        return 1;\n    } else {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(-3, 3);\n        int r = dis(gen);\n        return max(1, w + r);\n    }\n}\n\nvoid assign_tasks() {\n    vector<pair<int, int>> assignments;\n\n    for (int i = 0; i < team_members.size(); ++i) {\n        if (team_members[i].current_task == -1) {\n            for (int j = 0; j < tasks.size(); ++j) {\n                if (available_tasks[j] && !tasks[j].completed) {\n                    int duration = calculate_duration(j, i);\n                    if (duration < tasks[j].duration || tasks[j].duration == 0) {\n                        tasks[j].duration = duration;\n                        team_members[i].current_task = j;\n                        team_members[i].days_left = duration;\n                        assignments.emplace_back(i + 1, j + 1);\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    cout << assignments.size();\n    for (const auto& assignment : assignments) {\n        cout << \" \" << assignment.first << \" \" << assignment.second;\n    }\n    cout << endl;\n    cout.flush();\n}\n\nvoid process_completed_tasks(const vector<int>& completed_members) {\n    vector<int> completed_tasks;\n\n    for (int member : completed_members) {\n        int task = team_members[member - 1].current_task;\n        if (task != -1) {\n            tasks[task].completed = true;\n            completed_tasks.push_back(task);\n            team_members[member - 1].current_task = -1;\n            team_members[member - 1].days_left = 0;\n        }\n    }\n\n    for (int task : completed_tasks) {\n        for (int dependent_task : task_dependencies[task]) {\n            in_degree[dependent_task]--;\n            if (in_degree[dependent_task] == 0) {\n                available_tasks[dependent_task] = 1;\n            }\n        }\n    }\n\n    for (int member : completed_members) {\n        update_skills(member - 1, completed_tasks);\n    }\n}\n\nint main() {\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    initialize(N, M, K, R);\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> tasks[i].required_skills[j];\n        }\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n        assign_tasks();\n\n        int n;\n        cin >> n;\n        if (n == -1) {\n            break;\n        }\n\n        vector<int> completed_members(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> completed_members[i];\n        }\n\n        process_completed_tasks(completed_members);\n\n        if (all_of(tasks.begin(), tasks.end(), [](const Task& task) { return task.completed; })) {\n            break;\n        }\n\n        if (day >= 2000) {\n            break;\n        }\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <unordered_set>\n#include <climits>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nstruct Order {\n    Point restaurant;\n    Point destination;\n    Order(Point restaurant, Point destination) : restaurant(restaurant), destination(destination) {}\n};\n\nstruct Individual {\n    vector<int> orders;\n    vector<Point> route;\n    int fitness;\n};\n\nint manhattanDistance(const Point& a, const Point& b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nint calculateFitness(const Individual& individual, const vector<Order>& allOrders) {\n    int totalDistance = 0;\n    unordered_set<int> selectedOrders(individual.orders.begin(), individual.orders.end());\n\n    // Check if the route starts and ends at the office\n    if (individual.route.front() != Point(400, 400) || individual.route.back() != Point(400, 400)) {\n        return INT_MAX;\n    }\n\n    // Check if all selected orders are visited in the correct order\n    for (size_t i = 0; i < individual.orders.size(); ++i) {\n        int orderIndex = individual.orders[i];\n        const Order& order = allOrders[orderIndex];\n        bool restaurantVisited = false;\n        bool destinationVisited = false;\n\n        for (size_t j = 0; j < individual.route.size(); ++j) {\n            if (individual.route[j] == order.restaurant) {\n                restaurantVisited = true;\n            }\n            if (individual.route[j] == order.destination) {\n                if (!restaurantVisited) {\n                    return INT_MAX;\n                }\n                destinationVisited = true;\n            }\n        }\n\n        if (!restaurantVisited || !destinationVisited) {\n            return INT_MAX;\n        }\n    }\n\n    // Calculate total travel time\n    for (size_t i = 0; i < individual.route.size() - 1; ++i) {\n        totalDistance += manhattanDistance(individual.route[i], individual.route[i + 1]);\n    }\n\n    return totalDistance;\n}\n\nvector<Individual> initializePopulation(int populationSize, const vector<Order>& allOrders) {\n    vector<Individual> population;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n\n    for (int i = 0; i < populationSize; ++i) {\n        Individual individual;\n        unordered_set<int> selectedOrders;\n\n        // Select 50 unique orders\n        while (selectedOrders.size() < 50) {\n            int orderIndex = orderDist(gen);\n            selectedOrders.insert(orderIndex);\n        }\n\n        individual.orders.assign(selectedOrders.begin(), selectedOrders.end());\n\n        // Generate a random route\n        vector<Point> route;\n        route.push_back(Point(400, 400)); // Start at the office\n\n        for (int orderIndex : individual.orders) {\n            const Order& order = allOrders[orderIndex];\n            route.push_back(order.restaurant);\n            route.push_back(order.destination);\n        }\n\n        route.push_back(Point(400, 400)); // End at the office\n\n        individual.route = route;\n        individual.fitness = calculateFitness(individual, allOrders);\n        population.push_back(individual);\n    }\n\n    return population;\n}\n\nIndividual selectParent(const vector<Individual>& population) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dist(0, population.size() - 1);\n\n    int index1 = dist(gen);\n    int index2 = dist(gen);\n\n    return population[index1].fitness < population[index2].fitness ? population[index1] : population[index2];\n}\n\nIndividual crossover(const Individual& parent1, const Individual& parent2, const vector<Order>& allOrders) {\n    Individual child;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dist(0, 49);\n\n    // Select a random subset of orders from parent1\n    unordered_set<int> selectedOrders(parent1.orders.begin(), parent1.orders.begin() + dist(gen));\n\n    // Add the remaining orders from parent2\n    for (int orderIndex : parent2.orders) {\n        if (selectedOrders.size() >= 50) break;\n        if (selectedOrders.find(orderIndex) == selectedOrders.end()) {\n            selectedOrders.insert(orderIndex);\n        }\n    }\n\n    child.orders.assign(selectedOrders.begin(), selectedOrders.end());\n\n    // Generate a random route\n    vector<Point> route;\n    route.push_back(Point(400, 400)); // Start at the office\n\n    for (int orderIndex : child.orders) {\n        const Order& order = allOrders[orderIndex];\n        route.push_back(order.restaurant);\n        route.push_back(order.destination);\n    }\n\n    route.push_back(Point(400, 400)); // End at the office\n\n    child.route = route;\n    child.fitness = calculateFitness(child, allOrders);\n\n    return child;\n}\n\nvoid mutate(Individual& individual, const vector<Order>& allOrders) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n    uniform_int_distribution<> mutationDist(0, 1);\n\n    // Mutate orders\n    for (int& orderIndex : individual.orders) {\n        if (mutationDist(gen) == 0) {\n            orderIndex = orderDist(gen);\n        }\n    }\n\n    // Ensure all orders are unique\n    unordered_set<int> uniqueOrders(individual.orders.begin(), individual.orders.end());\n    if (uniqueOrders.size() < individual.orders.size()) {\n        vector<int> tempOrders(uniqueOrders.begin(), uniqueOrders.end());\n        while (tempOrders.size() < 50) {\n            int orderIndex = orderDist(gen);\n            if (uniqueOrders.find(orderIndex) == uniqueOrders.end()) {\n                tempOrders.push_back(orderIndex);\n                uniqueOrders.insert(orderIndex);\n            }\n        }\n        individual.orders = tempOrders;\n    }\n\n    // Mutate route\n    for (size_t i = 1; i < individual.route.size() - 1; ++i) {\n        if (mutationDist(gen) == 0) {\n            size_t j = uniform_int_distribution<>(1, individual.route.size() - 2)(gen);\n            swap(individual.route[i], individual.route[j]);\n        }\n    }\n\n    individual.fitness = calculateFitness(individual, allOrders);\n}\n\nvoid localSearch(Individual& individual, const vector<Order>& allOrders) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n\n    for (int i = 0; i < 5; ++i) {\n        Individual newIndividual = individual;\n        int orderIndex = orderDist(gen);\n        newIndividual.orders[i % 50] = orderIndex;\n\n        // Ensure all orders are unique\n        unordered_set<int> uniqueOrders(newIndividual.orders.begin(), newIndividual.orders.end());\n        if (uniqueOrders.size() < newIndividual.orders.size()) {\n            vector<int> tempOrders(uniqueOrders.begin(), uniqueOrders.end());\n            while (tempOrders.size() < 50) {\n                int orderIndex = orderDist(gen);\n                if (uniqueOrders.find(orderIndex) == uniqueOrders.end()) {\n                    tempOrders.push_back(orderIndex);\n                    uniqueOrders.insert(orderIndex);\n                }\n            }\n            newIndividual.orders = tempOrders;\n        }\n\n        // Generate a new route\n        vector<Point> route;\n        route.push_back(Point(400, 400)); // Start at the office\n\n        for (int orderIndex : newIndividual.orders) {\n            const Order& order = allOrders[orderIndex];\n            route.push_back(order.restaurant);\n            route.push_back(order.destination);\n        }\n\n        route.push_back(Point(400, 400)); // End at the office\n\n        newIndividual.route = route;\n        newIndividual.fitness = calculateFitness(newIndividual, allOrders);\n\n        if (newIndividual.fitness < individual.fitness) {\n            individual = newIndividual;\n        }\n    }\n}\n\nvector<Individual> evolvePopulation(vector<Individual>& population, const vector<Order>& allOrders) {\n    vector<Individual> newPopulation;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> mutationRate(0.0, 1.0);\n\n    for (size_t i = 0; i < population.size(); ++i) {\n        Individual parent1 = selectParent(population);\n        Individual parent2 = selectParent(population);\n        Individual child = crossover(parent1, parent2, allOrders);\n\n        if (mutationRate(gen) < 0.1) {\n            mutate(child, allOrders);\n        }\n\n        localSearch(child, allOrders);\n        newPopulation.push_back(child);\n    }\n\n    return newPopulation;\n}\n\nint main() {\n    vector<Order> allOrders;\n    for (int i = 0; i < 1000; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        allOrders.emplace_back(Point(a, b), Point(c, d));\n    }\n\n    const int populationSize = 20;\n    const int generations = 200;\n\n    vector<Individual> population = initializePopulation(populationSize, allOrders);\n\n    for (int generation = 0; generation < generations; ++generation) {\n        population = evolvePopulation(population, allOrders);\n\n        // Find the best individual in the current population\n        Individual bestIndividual = *min_element(population.begin(), population.end(),\n            [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; });\n\n        // Output the best fitness for debugging\n        cerr << \"Generation \" << generation << \": Best Fitness = \" << bestIndividual.fitness << endl;\n    }\n\n    // Find the best individual in the final population\n    Individual bestIndividual = *min_element(population.begin(), population.end(),\n        [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; });\n\n    // Output the best solution in the required format\n    cout << bestIndividual.orders.size() << \" \";\n    for (int orderIndex : bestIndividual.orders) {\n        cout << orderIndex + 1 << \" \";\n    }\n    cout << endl;\n\n    cout << bestIndividual.route.size() << \" \";\n    for (const Point& point : bestIndividual.route) {\n        cout << point.x << \" \" << point.y << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <atcoder/dsu>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v;\n    double d; // Euclidean distance rounded to the nearest integer\n    int index; // Original index to keep track of the order\n};\n\nint main() {\n    int N = 400;\n    int M = 1995;\n\n    vector<pair<int, int>> coordinates(N);\n    vector<Edge> edges(M);\n\n    // Read coordinates\n    for (int i = 0; i < N; ++i) {\n        cin >> coordinates[i].first >> coordinates[i].second;\n    }\n\n    // Read edges and compute d_i\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        edges[i].index = i;\n        int dx = coordinates[edges[i].u].first - coordinates[edges[i].v].first;\n        int dy = coordinates[edges[i].u].second - coordinates[edges[i].v].second;\n        edges[i].d = round(sqrt(dx * dx + dy * dy));\n    }\n\n    // Sort edges by d_i in ascending order\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.d < b.d;\n    });\n\n    dsu uf(N);\n    vector<bool> adopted(M, false);\n\n    // Process edges in order of increasing d_i\n    for (const Edge& edge : edges) {\n        int l;\n        cin >> l;\n        if (!uf.same(edge.u, edge.v)) {\n            uf.merge(edge.u, edge.v);\n            adopted[edge.index] = true;\n            cout << \"1\" << endl;\n        } else {\n            cout << \"0\" << endl;\n        }\n        cout.flush();\n    }\n\n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n#include <cmath>\n#include <unordered_set>\n#include <map>\n#include <cassert>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int TURNS = 300;\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nstruct GridState {\n    vector<vector<bool>> passable;\n    vector<Pet> pets;\n    vector<Human> humans;\n};\n\nvector<vector<int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nvector<vector<int>> bfs(const GridState& state, int startX, int startY) {\n    vector<vector<int>> distance(GRID_SIZE, vector<int>(GRID_SIZE, -1));\n    queue<pair<int, int>> q;\n    q.push({startX, startY});\n    distance[startX][startY] = 0;\n\n    while (!q.empty()) {\n        auto current = q.front();\n        int x = current.first;\n        int y = current.second;\n        q.pop();\n\n        for (size_t i = 0; i < directions.size(); ++i) {\n            int dx = directions[i][0];\n            int dy = directions[i][1];\n            int nx = x + dx;\n            int ny = y + dy;\n            if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny] && distance[nx][ny] == -1) {\n                distance[nx][ny] = distance[x][y] + 1;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return distance;\n}\n\nvector<pair<int, int>> findReachableArea(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    auto distance = bfs(state, hx, hy);\n    vector<pair<int, int>> reachableArea;\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (distance[i][j] != -1) {\n                reachableArea.emplace_back(i, j);\n            }\n        }\n    }\n    return reachableArea;\n}\n\nint countPetsInArea(const GridState& state, const vector<pair<int, int>>& area) {\n    unordered_set<string> petPositions;\n    for (const auto& pet : state.pets) {\n        petPositions.insert(to_string(pet.x) + \",\" + to_string(pet.y));\n    }\n    int count = 0;\n    for (const auto& pos : area) {\n        int x = pos.first;\n        int y = pos.second;\n        if (petPositions.count(to_string(x) + \",\" + to_string(y))) {\n            count++;\n        }\n    }\n    return count;\n}\n\ndouble calculateSatisfaction(const GridState& state, int humanIndex) {\n    auto reachableArea = findReachableArea(state, humanIndex);\n    int areaSize = reachableArea.size();\n    int petCount = countPetsInArea(state, reachableArea);\n    return (areaSize / 900.0) * pow(2, -petCount);\n}\n\nbool isSquareSafeToBlock(const GridState& state, int x, int y) {\n    for (const auto& pet : state.pets) {\n        if (pet.x == x && pet.y == y) {\n            return false;\n        }\n    }\n    for (size_t i = 0; i < directions.size(); ++i) {\n        int dx = directions[i][0];\n        int dy = directions[i][1];\n        int nx = x + dx;\n        int ny = y + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE) {\n            for (const auto& pet : state.pets) {\n                if (pet.x == nx && pet.y == ny) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nvector<pair<int, int>> findBestSquareToBlock(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    vector<pair<int, int>> candidates;\n    for (size_t i = 0; i < directions.size(); ++i) {\n        int dx = directions[i][0];\n        int dy = directions[i][1];\n        int nx = hx + dx;\n        int ny = hy + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny] && isSquareSafeToBlock(state, nx, ny)) {\n            candidates.emplace_back(nx, ny);\n        }\n    }\n    if (candidates.empty()) {\n        return {};\n    }\n    vector<double> scores;\n    for (const auto& candidate : candidates) {\n        int nx = candidate.first;\n        int ny = candidate.second;\n        GridState newState = state;\n        newState.passable[nx][ny] = false;\n        auto reachableArea = findReachableArea(newState, humanIndex);\n        int areaSize = reachableArea.size();\n        int petCount = countPetsInArea(newState, reachableArea);\n        scores.push_back((areaSize / 900.0) * pow(2, -petCount));\n    }\n    int bestIndex = max_element(scores.begin(), scores.end()) - scores.begin();\n    return {candidates[bestIndex]};\n}\n\nvector<pair<int, int>> findBestMove(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    vector<pair<int, int>> candidates;\n    for (size_t i = 0; i < directions.size(); ++i) {\n        int dx = directions[i][0];\n        int dy = directions[i][1];\n        int nx = hx + dx;\n        int ny = hy + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n            candidates.emplace_back(nx, ny);\n        }\n    }\n    if (candidates.empty()) {\n        return {};\n    }\n    vector<double> scores;\n    for (const auto& candidate : candidates) {\n        int nx = candidate.first;\n        int ny = candidate.second;\n        GridState newState = state;\n        newState.humans[humanIndex] = {nx, ny};\n        auto reachableArea = findReachableArea(newState, humanIndex);\n        int areaSize = reachableArea.size();\n        int petCount = countPetsInArea(newState, reachableArea);\n        scores.push_back((areaSize / 900.0) * pow(2, -petCount));\n    }\n    int bestIndex = max_element(scores.begin(), scores.end()) - scores.begin();\n    return {candidates[bestIndex]};\n}\n\nstring decideAction(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    auto blockSquares = findBestSquareToBlock(state, humanIndex);\n    auto moveSquares = findBestMove(state, humanIndex);\n\n    double currentSatisfaction = calculateSatisfaction(state, humanIndex);\n\n    double blockSatisfaction = -1;\n    if (!blockSquares.empty()) {\n        auto blockSquare = blockSquares[0];\n        int nx = blockSquare.first;\n        int ny = blockSquare.second;\n        GridState newState = state;\n        newState.passable[nx][ny] = false;\n        blockSatisfaction = calculateSatisfaction(newState, humanIndex);\n    }\n\n    double moveSatisfaction = -1;\n    if (!moveSquares.empty()) {\n        auto moveSquare = moveSquares[0];\n        int nx = moveSquare.first;\n        int ny = moveSquare.second;\n        GridState newState = state;\n        newState.humans[humanIndex] = {nx, ny};\n        moveSatisfaction = calculateSatisfaction(newState, humanIndex);\n    }\n\n    if (blockSatisfaction > currentSatisfaction && blockSatisfaction >= moveSatisfaction) {\n        auto blockSquare = blockSquares[0];\n        int nx = blockSquare.first;\n        int ny = blockSquare.second;\n        if (nx == hx - 1 && ny == hy) return \"u\";\n        if (nx == hx + 1 && ny == hy) return \"d\";\n        if (nx == hx && ny == hy - 1) return \"l\";\n        if (nx == hx && ny == hy + 1) return \"r\";\n    } else if (moveSatisfaction > currentSatisfaction && moveSatisfaction >= blockSatisfaction) {\n        auto moveSquare = moveSquares[0];\n        int nx = moveSquare.first;\n        int ny = moveSquare.second;\n        if (nx == hx - 1 && ny == hy) return \"U\";\n        if (nx == hx + 1 && ny == hy) return \"D\";\n        if (nx == hx && ny == hy - 1) return \"L\";\n        if (nx == hx && ny == hy + 1) return \"R\";\n    }\n    return \".\";\n}\n\nvoid simulatePetMovement(GridState& state, const vector<string>& petMoves) {\n    for (size_t i = 0; i < state.pets.size(); ++i) {\n        auto& pet = state.pets[i];\n        const string& move = petMoves[i];\n        if (move == \".\") continue;\n\n        for (char c : move) {\n            int dx = 0, dy = 0;\n            if (c == 'U') dx = -1;\n            else if (c == 'D') dx = 1;\n            else if (c == 'L') dy = -1;\n            else if (c == 'R') dy = 1;\n\n            int nx = pet.x + dx;\n            int ny = pet.y + dy;\n            if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n                pet.x = nx;\n                pet.y = ny;\n            }\n        }\n    }\n}\n\nint main() {\n    int N, M;\n    cin >> N;\n    vector<Pet> pets(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    vector<Human> humans(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\n    GridState state;\n    state.passable = vector<vector<bool>>(GRID_SIZE, vector<bool>(GRID_SIZE, true));\n    state.pets = pets;\n    state.humans = humans;\n\n    for (int turn = 0; turn < TURNS; ++turn) {\n        string actions;\n        for (int i = 0; i < M; ++i) {\n            actions += decideAction(state, i);\n        }\n        cout << actions << endl;\n        cout.flush();\n\n        vector<string> petMoves(N);\n        for (int i = 0; i < N; ++i) {\n            cin >> petMoves[i];\n        }\n        simulatePetMovement(state, petMoves);\n    }\n\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <tuple>\n#include <algorithm>\n#include <cmath>\n#include <unordered_map>\n#include <map>\n#include <set>\n#include <string>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MAX_N = 20;\nconst int MAX_M = 20;\nconst int MAX_T = 200;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct State {\n    int x, y, t;\n    double prob;\n    string path;\n\n    bool operator<(const State& other) const {\n        return prob < other.prob;\n    }\n};\n\ndouble simulate(int si, int sj, int ti, int tj, double p, const string& path, const vector<string>& h, const vector<string>& v) {\n    int x = si, y = sj;\n    double prob = 1.0;\n\n    for (char c : path) {\n        if (c == 'S') {\n            prob *= p;\n            continue;\n        }\n\n        int i;\n        for (i = 0; i < 4; ++i) {\n            if (dir[i] == c) break;\n        }\n\n        int nx = x + dx[i];\n        int ny = y + dy[i];\n\n        if (nx < 0 || nx >= MAX_N || ny < 0 || ny >= MAX_M) {\n            prob *= p;\n            continue;\n        }\n\n        if (i == 0 && v[x - 1][y] == '1') {\n            prob *= p;\n            continue;\n        }\n        if (i == 1 && v[x][y] == '1') {\n            prob *= p;\n            continue;\n        }\n        if (i == 2 && h[x][y - 1] == '1') {\n            prob *= p;\n            continue;\n        }\n        if (i == 3 && h[x][y] == '1') {\n            prob *= p;\n            continue;\n        }\n\n        x = nx;\n        y = ny;\n        prob *= (1 - p);\n\n        if (x == ti && y == tj) {\n            return prob * (401 - path.size());\n        }\n    }\n\n    return 0.0;\n}\n\nstring generate_random_path(int length) {\n    static random_device rd;\n    static mt19937 gen(rd());\n    static uniform_int_distribution<> dis(0, 3);\n\n    string path;\n    for (int i = 0; i < length; ++i) {\n        path += dir[dis(gen)];\n    }\n    return path;\n}\n\nstring monte_carlo_simulation(int si, int sj, int ti, int tj, double p, const vector<string>& h, const vector<string>& v, int iterations = 1000) {\n    string best_path;\n    double max_score = 0.0;\n\n    for (int i = 0; i < iterations; ++i) {\n        string path = generate_random_path(200);\n        double score = simulate(si, sj, ti, tj, p, path, h, v);\n\n        if (score > max_score) {\n            max_score = score;\n            best_path = path;\n        }\n    }\n\n    return best_path;\n}\n\nstring genetic_algorithm(int si, int sj, int ti, int tj, double p, const vector<string>& h, const vector<string>& v, int population_size = 100, int generations = 100) {\n    vector<string> population;\n    for (int i = 0; i < population_size; ++i) {\n        population.push_back(generate_random_path(200));\n    }\n\n    for (int gen = 0; gen < generations; ++gen) {\n        vector<double> scores;\n        for (const string& path : population) {\n            scores.push_back(simulate(si, sj, ti, tj, p, path, h, v));\n        }\n\n        vector<string> new_population;\n        for (int i = 0; i < population_size; ++i) {\n            int parent1 = max_element(scores.begin(), scores.end()) - scores.begin();\n            scores[parent1] = -1;\n            int parent2 = max_element(scores.begin(), scores.end()) - scores.begin();\n            scores[parent2] = -1;\n\n            string child;\n            for (int j = 0; j < 200; ++j) {\n                if (j < 100) {\n                    child += population[parent1][j];\n                } else {\n                    child += population[parent2][j];\n                }\n            }\n\n            // Mutation\n            if (rand() % 100 < 10) {\n                int pos = rand() % 200;\n                child[pos] = dir[rand() % 4];\n            }\n\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n    }\n\n    double max_score = 0.0;\n    string best_path;\n    for (const string& path : population) {\n        double score = simulate(si, sj, ti, tj, p, path, h, v);\n        if (score > max_score) {\n            max_score = score;\n            best_path = path;\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    vector<string> h(MAX_N), v(MAX_N);\n\n    cin >> si >> sj >> ti >> tj >> p;\n    for (int i = 0; i < MAX_N; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < MAX_N; ++i) {\n        cin >> v[i];\n    }\n\n    string best_path = genetic_algorithm(si, sj, ti, tj, p, h, v);\n\n    cout << best_path << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <unordered_set>\n#include <queue>\n#include <tuple>\n#include <thread>\n#include <mutex>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int POPULATION_SIZE = 50;\nconst int MAX_GENERATIONS = 50;\nconst double MUTATION_RATE = 0.1;\nconst double CROSSOVER_RATE = 0.7;\n\nvector<vector<int>> tiles(GRID_SIZE, vector<int>(GRID_SIZE));\nvector<vector<int>> rotations(GRID_SIZE, vector<int>(GRID_SIZE));\n\n// Directions: left, up, right, down\nconst int di[] = {0, -1, 0, 1};\nconst int dj[] = {-1, 0, 1, 0};\n\n// Transition table for tile types and directions\nconst vector<vector<int>> to = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\n\nmutex mtx;\n\nint simple_fitness_function() {\n    int connected_tiles = 0;\n    vector<vector<vector<bool>>> visited(GRID_SIZE, vector<vector<bool>>(GRID_SIZE, vector<bool>(4, false)));\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            for (int d = 0; d < 4; ++d) {\n                if (!visited[i][j][d]) {\n                    int d2 = to[tiles[i][j]][d];\n                    if (d2 != -1) {\n                        int ni = i + di[d2];\n                        int nj = j + dj[d2];\n                        if (ni >= 0 && ni < GRID_SIZE && nj >= 0 && nj < GRID_SIZE) {\n                            connected_tiles++;\n                            visited[i][j][d] = true;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    return connected_tiles;\n}\n\nvoid initialize_population(vector<vector<vector<int>>>& population) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                population[p][i][j] = dis(gen);\n            }\n        }\n    }\n}\n\nvoid mutate(vector<vector<int>>& individual) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> rot_dis(0, 3);\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (dis(gen) < MUTATION_RATE) {\n                individual[i][j] = rot_dis(gen);\n            }\n        }\n    }\n}\n\nvector<vector<int>> crossover(const vector<vector<int>>& parent1, const vector<vector<int>>& parent2) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> row_dis(0, GRID_SIZE - 1);\n    uniform_int_distribution<> col_dis(0, GRID_SIZE - 1);\n\n    vector<vector<int>> child(GRID_SIZE, vector<int>(GRID_SIZE));\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (dis(gen) < CROSSOVER_RATE) {\n                child[i][j] = parent1[i][j];\n            } else {\n                child[i][j] = parent2[i][j];\n            }\n        }\n    }\n\n    return child;\n}\n\nvoid evaluate_fitness(vector<vector<vector<int>>>& population, vector<int>& fitness_scores) {\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        rotations = population[p];\n        fitness_scores[p] = simple_fitness_function();\n    }\n}\n\nvoid genetic_algorithm() {\n    vector<vector<vector<int>>> population(POPULATION_SIZE, vector<vector<int>>(GRID_SIZE, vector<int>(GRID_SIZE)));\n    initialize_population(population);\n\n    vector<int> fitness_scores(POPULATION_SIZE);\n    evaluate_fitness(population, fitness_scores);\n\n    for (int gen = 0; gen < MAX_GENERATIONS; ++gen) {\n        vector<vector<vector<int>>> new_population;\n        for (int p = 0; p < POPULATION_SIZE; ++p) {\n            int parent1_idx = distance(fitness_scores.begin(), max_element(fitness_scores.begin(), fitness_scores.end()));\n            fitness_scores[parent1_idx] = -1;\n            int parent2_idx = distance(fitness_scores.begin(), max_element(fitness_scores.begin(), fitness_scores.end()));\n            fitness_scores[parent2_idx] = -1;\n\n            vector<vector<int>> child = crossover(population[parent1_idx], population[parent2_idx]);\n            mutate(child);\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n        evaluate_fitness(population, fitness_scores);\n    }\n\n    // Find the best solution\n    int best_fitness = -1;\n    vector<vector<int>> best_rotations;\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        rotations = population[p];\n        int current_fitness = simple_fitness_function();\n        if (current_fitness > best_fitness) {\n            best_fitness = current_fitness;\n            best_rotations = population[p];\n        }\n    }\n\n    rotations = best_rotations;\n}\n\nint main() {\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            tiles[i][j] = row[j] - '0';\n        }\n    }\n\n    genetic_algorithm();\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            cout << rotations[i][j];\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <atcoder/dsu>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\n\nstruct State {\n    vector<vector<int>> board;\n    pair<int, int> empty;\n    int cost;\n    int heuristic;\n    string path;\n\n    bool operator==(const State& other) const {\n        return board == other.board && empty == other.empty;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<State> {\n        size_t operator()(const State& state) const {\n            size_t seed = 0;\n            for (const auto& row : state.board) {\n                for (int tile : row) {\n                    seed ^= hash<int>{}(tile) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n                }\n            }\n            seed ^= hash<int>{}(state.empty.first) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            seed ^= hash<int>{}(state.empty.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            return seed;\n        }\n    };\n}\n\nint calculate_heuristic(const vector<vector<int>>& board, int N) {\n    dsu d(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0) continue;\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N || board[ni][nj] == 0) continue;\n                if ((board[i][j] & (1 << k)) && (board[ni][nj] & (1 << ((k + 2) % 4)))) {\n                    d.merge(i * N + j, ni * N + nj);\n                }\n            }\n        }\n    }\n    unordered_set<int> roots;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] != 0) {\n                roots.insert(d.leader(i * N + j));\n            }\n        }\n    }\n    return roots.size();\n}\n\nvector<State> get_neighbors(const State& state, int N) {\n    vector<State> neighbors;\n    int x = state.empty.first;\n    int y = state.empty.second;\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + dx[i];\n        int ny = y + dy[i];\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n        State neighbor = state;\n        neighbor.board[x][y] = neighbor.board[nx][ny];\n        neighbor.board[nx][ny] = 0;\n        neighbor.empty = {nx, ny};\n        neighbor.cost = state.cost + 1;\n        neighbor.heuristic = calculate_heuristic(neighbor.board, N);\n        neighbor.path += dir[i];\n        neighbors.push_back(neighbor);\n    }\n    return neighbors;\n}\n\nstring simulated_annealing(State initial, int N, int T) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    State current = initial;\n    double temperature = 1.0;\n    double cooling_rate = 0.99;\n\n    while (temperature > 0.001 && current.cost < T) {\n        if (current.heuristic == 1) {\n            return current.path;\n        }\n        vector<State> neighbors = get_neighbors(current, N);\n        if (neighbors.empty()) break;\n        State next = neighbors[rand() % neighbors.size()];\n        double delta = next.heuristic - current.heuristic;\n        if (delta < 0 || dis(gen) < exp(-delta / temperature)) {\n            current = next;\n        }\n        temperature *= cooling_rate;\n    }\n    return current.path;\n}\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    pair<int, int> empty;\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            char c = row[j];\n            if (c >= '0' && c <= '9') {\n                board[i][j] = c - '0';\n            } else {\n                board[i][j] = 10 + (c - 'a');\n            }\n            if (board[i][j] == 0) {\n                empty = {i, j};\n            }\n        }\n    }\n    State initial = {board, empty, 0, calculate_heuristic(board, N), \"\"};\n    string solution = simulated_annealing(initial, N, T);\n    cout << solution << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <limits>\n#include <unordered_set>\n#include <utility>\n#include <map>\n#include <numeric>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct Line {\n    Point p, q;\n    Line(Point p, Point q) : p(p), q(q) {}\n    bool operator==(const Line& other) const {\n        return (p == other.p && q == other.q) || (p == other.q && q == other.p);\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Line> {\n        size_t operator()(const Line& l) const {\n            return hash<Point>()(l.p) ^ hash<Point>()(l.q);\n        }\n    };\n}\n\nstruct Strawberry {\n    int x, y;\n    Strawberry(int x, int y) : x(x), y(y) {}\n};\n\nvector<Strawberry> strawberries;\nvector<int> a_d(10);\nint K;\n\ndouble distance(const Point& p1, const Point& p2) {\n    return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));\n}\n\nbool isInside(const Point& p, const Line& line) {\n    // Check if point p is inside the cake and not cut by the line\n    if (distance(p, Point(0, 0)) >= 10000) {\n        return false;\n    }\n    // Check if the point is on the line\n    int x1 = line.p.x, y1 = line.p.y;\n    int x2 = line.q.x, y2 = line.q.y;\n    int x = p.x, y = p.y;\n    if ((y2 - y1) * (x - x1) == (y - y1) * (x2 - x1)) {\n        return false;\n    }\n    return true;\n}\n\nint countPieces(const vector<Line>& lines, int d) {\n    vector<vector<bool>> inside(strawberries.size(), vector<bool>(lines.size() + 1, true));\n    for (int i = 0; i < lines.size(); ++i) {\n        for (int j = 0; j < strawberries.size(); ++j) {\n            if (!isInside(Point(strawberries[j].x, strawberries[j].y), lines[i])) {\n                inside[j][i + 1] = false;\n            }\n        }\n    }\n    int count = 0;\n    for (int i = 0; i < strawberries.size(); ++i) {\n        int c = 0;\n        for (int j = 0; j <= lines.size(); ++j) {\n            if (inside[i][j]) {\n                c++;\n            }\n        }\n        if (c == d) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvector<Line> enhancedAdaptiveLineGeneration() {\n    vector<Line> lines;\n    unordered_set<Line> uniqueLines;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(-1e9, 1e9);\n\n    // Generate lines through pairs of strawberries\n    for (int i = 0; i < min(30, (int)strawberries.size()); ++i) {\n        for (int j = i + 1; j < min(30, (int)strawberries.size()); ++j) {\n            Point p(strawberries[i].x, strawberries[i].y);\n            Point q(strawberries[j].x, strawberries[j].y);\n            Line line(p, q);\n            if (uniqueLines.find(line) == uniqueLines.end()) {\n                uniqueLines.insert(line);\n                lines.push_back(line);\n            }\n        }\n    }\n\n    // Generate random lines\n    for (int i = 0; i < 30; ++i) {\n        Point p(dis(gen), dis(gen));\n        Point q(dis(gen), dis(gen));\n        Line line(p, q);\n        if (uniqueLines.find(line) == uniqueLines.end()) {\n            uniqueLines.insert(line);\n            lines.push_back(line);\n        }\n    }\n\n    // Generate lines based on the distribution of strawberries\n    map<int, vector<Strawberry>> xMap;\n    map<int, vector<Strawberry>> yMap;\n    for (const auto& s : strawberries) {\n        xMap[s.x].push_back(s);\n        yMap[s.y].push_back(s);\n    }\n\n    for (const auto& pair : xMap) {\n        if (pair.second.size() > 1) {\n            Point p(pair.second[0].x, pair.second[0].y);\n            Point q(pair.second[1].x, pair.second[1].y);\n            Line line(p, q);\n            if (uniqueLines.find(line) == uniqueLines.end()) {\n                uniqueLines.insert(line);\n                lines.push_back(line);\n            }\n        }\n    }\n\n    for (const auto& pair : yMap) {\n        if (pair.second.size() > 1) {\n            Point p(pair.second[0].x, pair.second[0].y);\n            Point q(pair.second[1].x, pair.second[1].y);\n            Line line(p, q);\n            if (uniqueLines.find(line) == uniqueLines.end()) {\n                uniqueLines.insert(line);\n                lines.push_back(line);\n            }\n        }\n    }\n\n    // Generate lines based on the number of attendees for each d\n    for (int d = 1; d <= 10; ++d) {\n        if (a_d[d - 1] == 0) continue;\n        for (int i = 0; i < min(10, (int)strawberries.size()); ++i) {\n            Point p(strawberries[i].x, strawberries[i].y);\n            Point q(strawberries[i].x + d, strawberries[i].y + d);\n            Line line(p, q);\n            if (uniqueLines.find(line) == uniqueLines.end()) {\n                uniqueLines.insert(line);\n                lines.push_back(line);\n            }\n        }\n    }\n\n    return lines;\n}\n\nvector<Line> enhancedHybridAlgorithm() {\n    vector<Line> lines;\n    vector<Line> candidateLines = enhancedAdaptiveLineGeneration();\n\n    for (int d = 1; d <= 10; ++d) {\n        if (a_d[d - 1] == 0) continue;\n        int maxPieces = 0;\n        Line bestLine(Point(0, 0), Point(0, 0));\n        for (const auto& line : candidateLines) {\n            vector<Line> tempLines = lines;\n            tempLines.push_back(line);\n            int pieces = countPieces(tempLines, d);\n            if (pieces > maxPieces) {\n                maxPieces = pieces;\n                bestLine = line;\n            }\n        }\n        if (maxPieces > 0) {\n            lines.push_back(bestLine);\n            if (lines.size() >= K) break;\n        }\n    }\n    return lines;\n}\n\nint main() {\n    int N;\n    cin >> N >> K;\n    for (int i = 0; i < 10; ++i) {\n        cin >> a_d[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        strawberries.emplace_back(x, y);\n    }\n    vector<Line> lines = enhancedHybridAlgorithm();\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line.p.x << \" \" << line.p.y << \" \" << line.q.x << \" \" << line.q.y << endl;\n    }\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n#include <unordered_set>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nclass RectJoinGame {\nprivate:\n    int N, M;\n    unordered_set<Point> dots;\n    vector<Rectangle> rectangles;\n    int c;\n    double S;\n    mt19937 rng;\n\n    double weight(int x, int y) {\n        return (x - c) * (x - c) + (y - c) * (y - c) + 1;\n    }\n\n    bool isValidRectangle(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        // Check if the points form a valid rectangle (axis-aligned or 45-degree)\n        int dx1 = p2.x - p1.x;\n        int dy1 = p2.y - p1.y;\n        int dx2 = p3.x - p2.x;\n        int dy2 = p3.y - p2.y;\n        int dx3 = p4.x - p3.x;\n        int dy3 = p4.y - p3.y;\n        int dx4 = p1.x - p4.x;\n        int dy4 = p1.y - p4.y;\n\n        // Check if the sides are equal and perpendicular\n        if ((dx1 == dx3 && dy1 == dy3) && (dx2 == dx4 && dy2 == dy4) &&\n            (dx1 * dx2 + dy1 * dy2 == 0)) {\n            // Check if the rectangle is axis-aligned or 45-degree\n            if ((dx1 == 0 || dy1 == 0 || abs(dx1) == abs(dy1)) &&\n                (dx2 == 0 || dy2 == 0 || abs(dx2) == abs(dy2))) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    bool isValidOperation(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        if (dots.count(p1)) return false;\n        if (!dots.count(p2) || !dots.count(p3) || !dots.count(p4)) return false;\n        if (!isValidRectangle(p1, p2, p3, p4)) return false;\n\n        // Check if the perimeter of the rectangle contains any other dots\n        set<Point> perimeter;\n        int dx = p2.x - p1.x;\n        int dy = p2.y - p1.y;\n        for (int i = 0; i <= 1; ++i) {\n            for (int j = 0; j <= 1; ++j) {\n                int x = p1.x + i * dx;\n                int y = p1.y + i * dy;\n                for (int k = 0; k <= 1; ++k) {\n                    int nx = x + k * dy;\n                    int ny = y - k * dx;\n                    perimeter.insert(Point(nx, ny));\n                }\n            }\n        }\n        for (const auto& p : perimeter) {\n            if (dots.count(p) && !(p == p1 || p == p2 || p == p3 || p == p4)) {\n                return false;\n            }\n        }\n\n        // Check if the perimeter of the rectangle shares a common segment with any previously drawn rectangle\n        for (const auto& rect : rectangles) {\n            set<Point> rectPerimeter;\n            int rdx = rect.p2.x - rect.p1.x;\n            int rdy = rect.p2.y - rect.p1.y;\n            for (int i = 0; i <= 1; ++i) {\n                for (int j = 0; j <= 1; ++j) {\n                    int x = rect.p1.x + i * rdx;\n                    int y = rect.p1.y + i * rdy;\n                    for (int k = 0; k <= 1; ++k) {\n                        int nx = x + k * rdy;\n                        int ny = y - k * rdx;\n                        rectPerimeter.insert(Point(nx, ny));\n                    }\n                }\n            }\n            set<Point> intersection;\n            set_intersection(perimeter.begin(), perimeter.end(), rectPerimeter.begin(), rectPerimeter.end(), inserter(intersection, intersection.begin()));\n            if (intersection.size() > 2) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    double calculateScore() {\n        double sum = 0;\n        for (const auto& p : dots) {\n            sum += weight(p.x, p.y);\n        }\n        return round(1e6 * N * N / M * sum / S);\n    }\n\n    vector<Point> getNeighbors(const Point& p) {\n        vector<Point> neighbors;\n        for (int dx = -1; dx <= 1; ++dx) {\n            for (int dy = -1; dy <= 1; ++dy) {\n                if (dx == 0 && dy == 0) continue;\n                int nx = p.x + dx;\n                int ny = p.y + dy;\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N) {\n                    neighbors.emplace_back(nx, ny);\n                }\n            }\n        }\n        return neighbors;\n    }\n\n    pair<Point, vector<Point>> findBestOperation() {\n        double bestScore = -1;\n        Point bestP1(-1, -1); // Initialize with default values\n        vector<Point> bestP234;\n\n        for (const auto& p1 : dots) {\n            auto neighbors = getNeighbors(p1);\n            for (const auto& p2 : neighbors) {\n                if (!dots.count(p2)) continue;\n                for (const auto& p3 : neighbors) {\n                    if (!dots.count(p3) || p3 == p2) continue;\n                    for (const auto& p4 : neighbors) {\n                        if (!dots.count(p4) || p4 == p2 || p4 == p3) continue;\n                        if (isValidOperation(p1, p2, p3, p4)) {\n                            dots.insert(p1);\n                            rectangles.emplace_back(p1, p2, p3, p4);\n                            double score = calculateScore();\n                            dots.erase(p1);\n                            rectangles.pop_back();\n                            if (score > bestScore) {\n                                bestScore = score;\n                                bestP1 = p1;\n                                bestP234 = {p2, p3, p4};\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        return {bestP1, bestP234};\n    }\n\n    void simulatedAnnealing(double initialTemp, double finalTemp, double alpha) {\n        double temp = initialTemp;\n        auto currentScore = calculateScore();\n        auto bestScore = currentScore;\n        vector<Rectangle> bestRectangles = rectangles;\n\n        while (temp > finalTemp) {\n            auto [p1, p234] = findBestOperation();\n            if (p234.empty()) break;\n\n            dots.insert(p1);\n            rectangles.emplace_back(p1, p234[0], p234[1], p234[2]);\n            auto newScore = calculateScore();\n\n            if (newScore > currentScore || exp((newScore - currentScore) / temp) > uniform_real_distribution<double>(0, 1)(rng)) {\n                currentScore = newScore;\n                if (newScore > bestScore) {\n                    bestScore = newScore;\n                    bestRectangles = rectangles;\n                }\n            } else {\n                dots.erase(p1);\n                rectangles.pop_back();\n            }\n\n            temp *= alpha;\n        }\n\n        rectangles = bestRectangles;\n    }\n\npublic:\n    RectJoinGame(int N, int M, const vector<Point>& initialDots) : N(N), M(M), dots(initialDots.begin(), initialDots.end()), c((N - 1) / 2), rng(chrono::steady_clock::now().time_since_epoch().count()) {\n        S = 0;\n        for (int x = 0; x < N; ++x) {\n            for (int y = 0; y < N; ++y) {\n                S += weight(x, y);\n            }\n        }\n    }\n\n    void play() {\n        simulatedAnnealing(1000, 0.1, 0.99);\n    }\n\n    void output() const {\n        cout << rectangles.size() << endl;\n        for (const auto& rect : rectangles) {\n            cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n                 << rect.p2.x << \" \" << rect.p2.y << \" \"\n                 << rect.p3.x << \" \" << rect.p3.y << \" \"\n                 << rect.p4.x << \" \" << rect.p4.y << endl;\n        }\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<Point> initialDots;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        initialDots.emplace_back(x, y);\n    }\n\n    RectJoinGame game(N, M, initialDots);\n    game.play();\n    game.output();\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <array>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <queue>\n#include <unordered_map>\n\nusing namespace std;\n\nconst int GRID_SIZE = 10;\nconst int NUM_FLAVORS = 3;\nconst int NUM_CANDIES = 100;\nconst int LOOKAHEAD_STEPS = 3;\nconst int NUM_SIMULATIONS = 5;\n\nenum Direction { FORWARD, BACKWARD, LEFT, RIGHT };\n\nstruct Candy {\n    int flavor;\n    int row;\n    int col;\n};\n\nstruct Grid {\n    array<array<int, GRID_SIZE>, GRID_SIZE> cells;\n    vector<Candy> candies;\n\n    Grid() {\n        for (auto& row : cells) {\n            fill(row.begin(), row.end(), 0);\n        }\n    }\n\n    void place_candy(int flavor, int row, int col) {\n        cells[row][col] = flavor;\n        candies.push_back({flavor, row, col});\n    }\n\n    void tilt(Direction dir) {\n        switch (dir) {\n            case FORWARD:\n                tilt_forward();\n                break;\n            case BACKWARD:\n                tilt_backward();\n                break;\n            case LEFT:\n                tilt_left();\n                break;\n            case RIGHT:\n                tilt_right();\n                break;\n        }\n    }\n\n    void tilt_forward() {\n        for (int col = 0; col < GRID_SIZE; ++col) {\n            int empty_row = GRID_SIZE - 1;\n            for (int row = GRID_SIZE - 1; row >= 0; --row) {\n                if (cells[row][col] != 0) {\n                    cells[empty_row][col] = cells[row][col];\n                    if (empty_row != row) {\n                        cells[row][col] = 0;\n                    }\n                    --empty_row;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_backward() {\n        for (int col = 0; col < GRID_SIZE; ++col) {\n            int empty_row = 0;\n            for (int row = 0; row < GRID_SIZE; ++row) {\n                if (cells[row][col] != 0) {\n                    cells[empty_row][col] = cells[row][col];\n                    if (empty_row != row) {\n                        cells[row][col] = 0;\n                    }\n                    ++empty_row;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_left() {\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            int empty_col = 0;\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0) {\n                    cells[row][empty_col] = cells[row][col];\n                    if (empty_col != col) {\n                        cells[row][col] = 0;\n                    }\n                    ++empty_col;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_right() {\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            int empty_col = GRID_SIZE - 1;\n            for (int col = GRID_SIZE - 1; col >= 0; --col) {\n                if (cells[row][col] != 0) {\n                    cells[row][empty_col] = cells[row][col];\n                    if (empty_col != col) {\n                        cells[row][col] = 0;\n                    }\n                    --empty_col;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void update_candies() {\n        candies.clear();\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0) {\n                    candies.push_back({cells[row][col], row, col});\n                }\n            }\n        }\n    }\n\n    int calculate_score() {\n        array<int, NUM_FLAVORS + 1> flavor_counts = {0};\n        for (const auto& candy : candies) {\n            flavor_counts[candy.flavor]++;\n        }\n\n        int sum_squares = 0;\n        for (int i = 1; i <= NUM_FLAVORS; ++i) {\n            sum_squares += flavor_counts[i] * flavor_counts[i];\n        }\n\n        array<array<bool, GRID_SIZE>, GRID_SIZE> visited = {false};\n        int connectivity = 0;\n\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0 && !visited[row][col]) {\n                    int flavor = cells[row][col];\n                    int component_size = 0;\n                    vector<pair<int, int>> stack = {{row, col}};\n                    visited[row][col] = true;\n\n                    while (!stack.empty()) {\n                        auto [r, c] = stack.back();\n                        stack.pop_back();\n                        component_size++;\n\n                        for (const auto& [dr, dc] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                            int nr = r + dr;\n                            int nc = c + dc;\n                            if (nr >= 0 && nr < GRID_SIZE && nc >= 0 && nc < GRID_SIZE && cells[nr][nc] == flavor && !visited[nr][nc]) {\n                                visited[nr][nc] = true;\n                                stack.emplace_back(nr, nc);\n                            }\n                        }\n                    }\n\n                    connectivity += component_size * component_size;\n                }\n            }\n        }\n\n        return round(1e6 * static_cast<double>(connectivity) / sum_squares);\n    }\n};\n\nDirection choose_direction(const Grid& grid, int flavor, const vector<int>& remaining_flavors) {\n    array<int, 4> scores = {0};\n    array<Grid, 4> grids;\n\n    for (int i = 0; i < 4; ++i) {\n        grids[i] = grid;\n        grids[i].tilt(static_cast<Direction>(i));\n\n        // Simulate lookahead steps with multiple simulations\n        for (int sim = 0; sim < NUM_SIMULATIONS; ++sim) {\n            Grid lookahead_grid = grids[i];\n            for (int step = 0; step < LOOKAHEAD_STEPS && step < remaining_flavors.size(); ++step) {\n                // Place the next candy in a random empty cell\n                vector<pair<int, int>> empty_cells;\n                for (int row = 0; row < GRID_SIZE; ++row) {\n                    for (int col = 0; col < GRID_SIZE; ++col) {\n                        if (lookahead_grid.cells[row][col] == 0) {\n                            empty_cells.emplace_back(row, col);\n                        }\n                    }\n                }\n\n                if (!empty_cells.empty()) {\n                    random_device rd;\n                    mt19937 gen(rd());\n                    uniform_int_distribution<> dis(0, empty_cells.size() - 1);\n                    auto [row, col] = empty_cells[dis(gen)];\n                    lookahead_grid.place_candy(remaining_flavors[step], row, col);\n\n                    // Choose a random tilt direction for the next step\n                    uniform_int_distribution<> tilt_dis(0, 3);\n                    lookahead_grid.tilt(static_cast<Direction>(tilt_dis(gen)));\n                }\n            }\n            scores[i] += lookahead_grid.calculate_score();\n        }\n    }\n\n    int max_score = *max_element(scores.begin(), scores.end());\n    vector<Direction> best_directions;\n\n    for (int i = 0; i < 4; ++i) {\n        if (scores[i] == max_score) {\n            best_directions.push_back(static_cast<Direction>(i));\n        }\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, best_directions.size() - 1);\n\n    return best_directions[dis(gen)];\n}\n\nint main() {\n    vector<int> flavors(NUM_CANDIES);\n    for (int& flavor : flavors) {\n        cin >> flavor;\n    }\n\n    Grid grid;\n    for (int t = 0; t < NUM_CANDIES; ++t) {\n        int p;\n        cin >> p;\n\n        int empty_cell = 0;\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (grid.cells[row][col] == 0) {\n                    empty_cell++;\n                    if (empty_cell == p) {\n                        grid.place_candy(flavors[t], row, col);\n                        break;\n                    }\n                }\n            }\n            if (empty_cell == p) {\n                break;\n            }\n        }\n\n        if (t < NUM_CANDIES - 1) {\n            vector<int> remaining_flavors(flavors.begin() + t + 1, flavors.end());\n            Direction dir = choose_direction(grid, flavors[t], remaining_flavors);\n            grid.tilt(dir);\n\n            switch (dir) {\n                case FORWARD:\n                    cout << \"F\" << endl;\n                    break;\n                case BACKWARD:\n                    cout << \"B\" << endl;\n                    break;\n                case LEFT:\n                    cout << \"L\" << endl;\n                    break;\n                case RIGHT:\n                    cout << \"R\" << endl;\n                    break;\n            }\n            cout.flush();\n        }\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int MAX_N = 100;\nconst int MAX_M = 100;\nconst int MAX_QUERIES = 100;\n\nmt19937 rng(random_device{}());\n\nint M;\ndouble epsilon;\nint N;\nvector<vector<vector<bool>>> G;\nvector<vector<bool>> H;\n\nvoid generate_graphs() {\n    // Use a combination of edge patterns and vertex orderings to encode numbers\n    for (int k = 0; k < M; ++k) {\n        vector<vector<bool>> graph(N, vector<bool>(N, false));\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                // Use a combination of edge patterns to encode the number k\n                if ((k & (1 << (i + j))) != 0) {\n                    graph[i][j] = true;\n                    graph[j][i] = true;\n                }\n            }\n        }\n        G.push_back(graph);\n    }\n}\n\nvoid output_graphs() {\n    cout << N << endl;\n    for (const auto& graph : G) {\n        string s;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                s += graph[i][j] ? '1' : '0';\n            }\n        }\n        cout << s << endl;\n    }\n    cout.flush();\n}\n\nvoid read_graph() {\n    string s;\n    cin >> s;\n    H.assign(N, vector<bool>(N, false));\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            H[i][j] = (s[idx++] == '1');\n            H[j][i] = H[i][j];\n        }\n    }\n}\n\nint calculate_similarity(const vector<vector<bool>>& a, const vector<vector<bool>>& b) {\n    int similarity = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (a[i][j] == b[i][j]) {\n                similarity++;\n            }\n        }\n    }\n    return similarity;\n}\n\nint predict_graph() {\n    int best_match = -1;\n    int max_similarity = -1;\n    for (int k = 0; k < M; ++k) {\n        int similarity = calculate_similarity(H, G[k]);\n        if (similarity > max_similarity) {\n            max_similarity = similarity;\n            best_match = k;\n        }\n    }\n    return best_match;\n}\n\nint main() {\n    cin >> M >> epsilon;\n    N = 20; // Choose a reasonable N within the constraints\n\n    generate_graphs();\n    output_graphs();\n\n    for (int q = 0; q < MAX_QUERIES; ++q) {\n        read_graph();\n        int t = predict_graph();\n        cout << t << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <limits>\n#include <unordered_map>\n#include <unordered_set>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v, w;\n    int day;\n    bool operator<(const Edge& other) const {\n        return w > other.w;\n    }\n};\n\nstruct Vertex {\n    int id;\n    double betweenness;\n    Vertex(int id) : id(id), betweenness(0.0) {}\n};\n\nclass Graph {\nprivate:\n    int N, M, D, K;\n    vector<vector<pair<int, int>>> adj;\n    vector<Edge> edges;\n    vector<Vertex> vertices;\n\n    void computeBetweennessCentrality() {\n        for (int s = 0; s < N; ++s) {\n            vector<int> numSP(N, 0);\n            vector<double> bc(N, 0.0);\n            vector<vector<int>> predecessors(N);\n            vector<int> stack;\n            vector<int> sigma(N, 0);\n            vector<int> distance(N, -1);\n\n            queue<int> q;\n            q.push(s);\n            sigma[s] = 1;\n            distance[s] = 0;\n\n            while (!q.empty()) {\n                int v = q.front();\n                q.pop();\n                stack.push_back(v);\n                for (const auto& neighbor : adj[v]) {\n                    int w = neighbor.first;\n                    if (distance[w] < 0) {\n                        q.push(w);\n                        distance[w] = distance[v] + 1;\n                    }\n                    if (distance[w] == distance[v] + 1) {\n                        sigma[w] += sigma[v];\n                        predecessors[w].push_back(v);\n                    }\n                }\n            }\n\n            while (!stack.empty()) {\n                int w = stack.back();\n                stack.pop_back();\n                for (int v : predecessors[w]) {\n                    bc[v] += (sigma[v] / static_cast<double>(sigma[w])) * (1.0 + bc[w]);\n                }\n                if (w != s) {\n                    vertices[w].betweenness += bc[w];\n                }\n            }\n        }\n    }\n\n    void prioritizeEdges() {\n        computeBetweennessCentrality();\n        sort(edges.begin(), edges.end(), [this](const Edge& a, const Edge& b) {\n            double a_betweenness = vertices[a.u].betweenness + vertices[a.v].betweenness;\n            double b_betweenness = vertices[b.u].betweenness + vertices[b.v].betweenness;\n            return a_betweenness > b_betweenness;\n        });\n    }\n\n    void assignDays() {\n        vector<int> dayCounts(D, 0);\n        for (auto& edge : edges) {\n            int bestDay = -1;\n            double minIncrease = numeric_limits<double>::max();\n            for (int day = 0; day < D; ++day) {\n                if (dayCounts[day] >= K) continue;\n                double increase = calculateFrustrationIncrease(edge, day);\n                if (increase < minIncrease) {\n                    minIncrease = increase;\n                    bestDay = day;\n                }\n            }\n            edge.day = bestDay;\n            dayCounts[bestDay]++;\n        }\n    }\n\n    double calculateFrustrationIncrease(const Edge& edge, int day) {\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            for (const auto& neighbor : adj[i]) {\n                int v = neighbor.first;\n                int w = neighbor.second;\n                dist[i][v] = min(dist[i][v], w);\n            }\n        }\n\n        for (int k = 0; k < N; ++k) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (dist[i][k] != numeric_limits<int>::max() && dist[k][j] != numeric_limits<int>::max()) {\n                        dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n                    }\n                }\n            }\n        }\n\n        vector<vector<int>> newDist = dist;\n        newDist[edge.u][edge.v] = numeric_limits<int>::max();\n        newDist[edge.v][edge.u] = numeric_limits<int>::max();\n\n        for (int k = 0; k < N; ++k) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (newDist[i][k] != numeric_limits<int>::max() && newDist[k][j] != numeric_limits<int>::max()) {\n                        newDist[i][j] = min(newDist[i][j], newDist[i][k] + newDist[k][j]);\n                    }\n                }\n            }\n        }\n\n        double totalIncrease = 0.0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (i != j) {\n                    int originalDist = dist[i][j];\n                    int newDistVal = newDist[i][j];\n                    if (newDistVal == numeric_limits<int>::max()) {\n                        newDistVal = 1e9;\n                    }\n                    totalIncrease += (newDistVal - originalDist);\n                }\n            }\n        }\n\n        return totalIncrease / (N * (N - 1));\n    }\n\npublic:\n    Graph(int N, int M, int D, int K) : N(N), M(M), D(D), K(K), adj(N), vertices(N) {\n        for (int i = 0; i < N; ++i) {\n            vertices[i].id = i;\n        }\n    }\n\n    void addEdge(int u, int v, int w) {\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n        edges.push_back({u, v, w, -1});\n    }\n\n    void solve() {\n        prioritizeEdges();\n        assignDays();\n    }\n\n    void printSolution() {\n        for (const auto& edge : edges) {\n            cout << edge.day + 1 << \" \";\n        }\n        cout << endl;\n    }\n};\n\nint main() {\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    Graph graph(N, M, D, K);\n\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        graph.addEdge(u - 1, v - 1, w);\n    }\n\n    // Skip reading the coordinates if not needed\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    graph.solve();\n    graph.printSolution();\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Block {\n    vector<vector<vector<bool>>> shape;\n    int volume;\n\n    Block(const vector<vector<vector<bool>>>& s) : shape(s) {\n        volume = 0;\n        for (const auto& layer : shape) {\n            for (const auto& row : layer) {\n                for (bool cell : row) {\n                    if (cell) volume++;\n                }\n            }\n        }\n    }\n\n    void rotateX() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[x][D - 1 - z][y] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n\n    void rotateY() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[z][y][D - 1 - x] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n\n    void rotateZ() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[D - 1 - y][x][z] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n};\n\nstruct Individual {\n    vector<Block> blocks;\n    vector<vector<vector<int>>> arrangement1;\n    vector<vector<vector<int>>> arrangement2;\n    double fitness;\n\n    Individual(const vector<Block>& b, int D) : blocks(b) {\n        arrangement1 = vector<vector<vector<int>>>(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        arrangement2 = vector<vector<vector<int>>>(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        fitness = 0.0;\n    }\n};\n\nvector<Block> generateInitialBlocks(int D) {\n    vector<Block> blocks;\n    // Generate some initial blocks, e.g., single cubes, 2x2x2 cubes, etc.\n    // This is a placeholder; actual block generation should be more sophisticated.\n    vector<vector<vector<bool>>> singleCube(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    singleCube[0][0][0] = true;\n    blocks.emplace_back(singleCube);\n\n    vector<vector<vector<bool>>> twoCube(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    twoCube[0][0][0] = true;\n    twoCube[0][0][1] = true;\n    blocks.emplace_back(twoCube);\n\n    return blocks;\n}\n\nvector<vector<vector<bool>>> createSilhouette(int D, const vector<string>& f, const vector<string>& r) {\n    vector<vector<vector<bool>>> silhouette(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    for (int z = 0; z < D; ++z) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                if (f[z][x] == '1' && r[z][y] == '1') {\n                    silhouette[x][y][z] = true;\n                }\n            }\n        }\n    }\n    return silhouette;\n}\n\ndouble evaluateFitness(const Individual& ind, const vector<vector<vector<bool>>>& silhouette1, const vector<vector<vector<bool>>>& silhouette2) {\n    int D = silhouette1.size();\n    double fitness = 0.0;\n\n    // Check silhouette1\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 (silhouette1[x][y][z]) {\n                    bool covered = false;\n                    for (const auto& block : ind.blocks) {\n                        if (ind.arrangement1[x][y][z] != 0) {\n                            covered = true;\n                            break;\n                        }\n                    }\n                    if (!covered) fitness += 1.0;\n                }\n            }\n        }\n    }\n\n    // Check silhouette2\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 (silhouette2[x][y][z]) {\n                    bool covered = false;\n                    for (const auto& block : ind.blocks) {\n                        if (ind.arrangement2[x][y][z] != 0) {\n                            covered = true;\n                            break;\n                        }\n                    }\n                    if (!covered) fitness += 1.0;\n                }\n            }\n        }\n    }\n\n    // Penalize unused blocks\n    unordered_set<int> usedBlocks1, usedBlocks2;\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 (ind.arrangement1[x][y][z] != 0) usedBlocks1.insert(ind.arrangement1[x][y][z]);\n                if (ind.arrangement2[x][y][z] != 0) usedBlocks2.insert(ind.arrangement2[x][y][z]);\n            }\n        }\n    }\n    for (int i = 1; i <= ind.blocks.size(); ++i) {\n        if (usedBlocks1.find(i) == usedBlocks1.end() && usedBlocks2.find(i) == usedBlocks2.end()) {\n            fitness += ind.blocks[i - 1].volume;\n        }\n    }\n\n    // Penalize blocks used in both arrangements\n    unordered_set<int> commonBlocks;\n    for (int block : usedBlocks1) {\n        if (usedBlocks2.find(block) != usedBlocks2.end()) {\n            commonBlocks.insert(block);\n        }\n    }\n    for (int block : commonBlocks) {\n        fitness += 1.0 / ind.blocks[block - 1].volume;\n    }\n\n    return fitness;\n}\n\nIndividual geneticAlgorithm(int D, const vector<vector<vector<bool>>>& silhouette1, const vector<vector<vector<bool>>>& silhouette2, int populationSize, int generations) {\n    vector<Block> initialBlocks = generateInitialBlocks(D);\n    vector<Individual> population;\n    for (int i = 0; i < populationSize; ++i) {\n        population.emplace_back(initialBlocks, D);\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> blockDist(0, initialBlocks.size() - 1);\n    uniform_int_distribution<> posDist(0, D - 1);\n\n    for (int gen = 0; gen < generations; ++gen) {\n        // Evaluate fitness\n        for (auto& ind : population) {\n            ind.fitness = evaluateFitness(ind, silhouette1, silhouette2);\n        }\n\n        // Sort by fitness\n        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n            return a.fitness < b.fitness;\n        });\n\n        // Select top individuals\n        vector<Individual> newPopulation;\n        for (int i = 0; i < populationSize / 2; ++i) {\n            newPopulation.push_back(population[i]);\n        }\n\n        // Crossover and mutation\n        while (newPopulation.size() < populationSize) {\n            Individual parent1 = population[rand() % (populationSize / 2)];\n            Individual parent2 = population[rand() % (populationSize / 2)];\n            Individual child(parent1.blocks, D);\n\n            // Crossover: randomly select arrangements from parents\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 (rand() % 2) {\n                            child.arrangement1[x][y][z] = parent1.arrangement1[x][y][z];\n                            child.arrangement2[x][y][z] = parent1.arrangement2[x][y][z];\n                        } else {\n                            child.arrangement1[x][y][z] = parent2.arrangement1[x][y][z];\n                            child.arrangement2[x][y][z] = parent2.arrangement2[x][y][z];\n                        }\n                    }\n                }\n            }\n\n            // Mutation: randomly change some blocks\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 (rand() % 100 < 5) { // 5% mutation rate\n                            child.arrangement1[x][y][z] = blockDist(gen) + 1;\n                            child.arrangement2[x][y][z] = blockDist(gen) + 1;\n                        }\n                    }\n                }\n            }\n\n            newPopulation.push_back(child);\n        }\n\n        population = newPopulation;\n    }\n\n    // Return the best individual\n    sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n        return a.fitness < b.fitness;\n    });\n\n    return population[0];\n}\n\nint main() {\n    int D;\n    cin >> D;\n\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for (int i = 0; i < D; ++i) cin >> f1[i];\n    for (int i = 0; i < D; ++i) cin >> r1[i];\n    for (int i = 0; i < D; ++i) cin >> f2[i];\n    for (int i = 0; i < D; ++i) cin >> r2[i];\n\n    vector<vector<vector<bool>>> silhouette1 = createSilhouette(D, f1, r1);\n    vector<vector<vector<bool>>> silhouette2 = createSilhouette(D, f2, r2);\n\n    Individual bestIndividual = geneticAlgorithm(D, silhouette1, silhouette2, 50, 100);\n\n    // Output the best individual\n    int n = bestIndividual.blocks.size();\n    cout << n << endl;\n\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                cout << bestIndividual.arrangement1[x][y][z] << \" \";\n            }\n        }\n    }\n    cout << endl;\n\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                cout << bestIndividual.arrangement2[x][y][z] << \" \";\n            }\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <limits>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\nusing namespace std;\nusing namespace boost;\n\ntypedef adjacency_list<vecS, vecS, undirectedS,\n                       no_property,\n                       property<edge_weight_t, int> > Graph;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef graph_traits<Graph>::edge_descriptor Edge;\ntypedef graph_traits<Graph>::edge_iterator EdgeIterator;\ntypedef graph_traits<Graph>::vertex_iterator VertexIterator;\n\nstruct Point {\n    int x, y;\n    Point() : x(0), y(0) {} // Default constructor\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Resident {\n    int a, b;\n    Resident() : a(0), b(0) {} // Default constructor\n    Resident(int a, int b) : a(a), b(b) {}\n};\n\nstruct EdgeInfo {\n    int u, v, w;\n    EdgeInfo() : u(0), v(0), w(0) {} // Default constructor\n    EdgeInfo(int u, int v, int w) : u(u), v(v), w(w) {}\n};\n\n// Custom hash function for Edge\nstruct EdgeHash {\n    size_t operator()(const Edge& e) const {\n        return std::hash<size_t>()(e.m_source) ^ std::hash<size_t>()(e.m_target);\n    }\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<Point> stations(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> stations[i].x >> stations[i].y;\n    }\n\n    vector<EdgeInfo> edges(M);\n    for (int j = 0; j < M; ++j) {\n        cin >> edges[j].u >> edges[j].v >> edges[j].w;\n        edges[j].u--; // Convert to 0-based index\n        edges[j].v--;\n    }\n\n    vector<Resident> residents(K);\n    for (int k = 0; k < K; ++k) {\n        cin >> residents[k].a >> residents[k].b;\n    }\n\n    // Build the graph\n    Graph g(N);\n    vector<Edge> edge_map(M);\n    for (int j = 0; j < M; ++j) {\n        edge_map[j] = add_edge(edges[j].u, edges[j].v, edges[j].w, g).first;\n    }\n\n    // Find the Minimum Spanning Tree (MST)\n    vector<Edge> mst_edges;\n    kruskal_minimum_spanning_tree(g, back_inserter(mst_edges));\n\n    // Create a subgraph with MST edges\n    Graph mst(N);\n    for (const auto& e : mst_edges) {\n        add_edge(source(e, g), target(e, g), get(edge_weight, g, e), mst);\n    }\n\n    // Calculate the minimum output strength for each station\n    vector<int> P(N, 0);\n    for (int i = 0; i < N; ++i) {\n        double max_dist = 0.0;\n        for (const auto& resident : residents) {\n            double dist = sqrt(pow(stations[i].x - resident.a, 2) + pow(stations[i].y - resident.b, 2));\n            if (dist > max_dist) {\n                max_dist = dist;\n            }\n        }\n        P[i] = static_cast<int>(ceil(max_dist));\n        // Cap the output strength at 5000\n        if (P[i] > 5000) {\n            P[i] = 5000;\n        }\n    }\n\n    // Ensure all residents are covered\n    std::unordered_set<int> covered_residents;\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            double dist = sqrt(pow(stations[i].x - residents[k].a, 2) + pow(stations[i].y - residents[k].b, 2));\n            if (dist <= P[i]) {\n                covered_residents.insert(k);\n            }\n        }\n    }\n\n    // If not all residents are covered, increase the output strength of the nearest station\n    while (static_cast<int>(covered_residents.size()) < K) {\n        for (int k = 0; k < K; ++k) {\n            if (covered_residents.find(k) == covered_residents.end()) {\n                double min_dist = numeric_limits<double>::max();\n                int nearest_station = -1;\n                for (int i = 0; i < N; ++i) {\n                    double dist = sqrt(pow(stations[i].x - residents[k].a, 2) + pow(stations[i].y - residents[k].b, 2));\n                    if (dist < min_dist) {\n                        min_dist = dist;\n                        nearest_station = i;\n                    }\n                }\n                P[nearest_station] = static_cast<int>(ceil(min_dist));\n                // Cap the output strength at 5000\n                if (P[nearest_station] > 5000) {\n                    P[nearest_station] = 5000;\n                }\n                for (int kk = 0; kk < K; ++kk) {\n                    double dist = sqrt(pow(stations[nearest_station].x - residents[kk].a, 2) + pow(stations[nearest_station].y - residents[kk].b, 2));\n                    if (dist <= P[nearest_station]) {\n                        covered_residents.insert(kk);\n                    }\n                }\n            }\n        }\n    }\n\n    // Output the results\n    for (int i = 0; i < N; ++i) {\n        cout << P[i] << \" \";\n    }\n    cout << endl;\n\n    // Create a set of edges in the MST for quick lookup\n    std::unordered_set<Edge, EdgeHash> mst_edge_set;\n    for (const auto& e : mst_edges) {\n        mst_edge_set.insert(e);\n    }\n\n    // Output the power status of each edge\n    for (int j = 0; j < M; ++j) {\n        Edge e = edge(edges[j].u, edges[j].v, g).first;\n        if (mst_edge_set.find(e) != mst_edge_set.end()) {\n            cout << \"1 \";\n        } else {\n            cout << \"0 \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 30;\nconst int MAX_OPERATIONS = 10000;\n\nvector<vector<int>> pyramid;\n\nstruct Operation {\n    int x1, y1, x2, y2;\n};\n\nvector<Operation> operations;\n\nbool is_adjacent(int x1, int y1, int x2, int y2) {\n    if (x1 == x2 - 1 && y1 == y2 - 1) return true;\n    if (x1 == x2 - 1 && y1 == y2) return true;\n    if (x1 == x2 && y1 == y2 - 1) return true;\n    if (x1 == x2 && y1 == y2 + 1) return true;\n    if (x1 == x2 + 1 && y1 == y2) return true;\n    if (x1 == x2 + 1 && y1 == y2 + 1) return true;\n    return false;\n}\n\nvoid swap_balls(int x1, int y1, int x2, int y2) {\n    swap(pyramid[x1][y1], pyramid[x2][y2]);\n    operations.push_back({x1, y1, x2, y2});\n}\n\nint count_violations() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] > pyramid[x + 1][y]) violations++;\n            if (pyramid[x][y] > pyramid[x + 1][y + 1]) violations++;\n        }\n    }\n    return violations;\n}\n\nvoid greedy_algorithm() {\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] > pyramid[x + 1][y]) {\n                if (is_adjacent(x, y, x + 1, y)) {\n                    swap_balls(x, y, x + 1, y);\n                } else {\n                    // Find a path to swap\n                    // This is a simplified approach; a more sophisticated pathfinding algorithm can be used here\n                    for (int i = x + 1; i < N; ++i) {\n                        if (is_adjacent(i, y, i + 1, y)) {\n                            swap_balls(i, y, i + 1, y);\n                        }\n                    }\n                }\n            }\n            if (pyramid[x][y] > pyramid[x + 1][y + 1]) {\n                if (is_adjacent(x, y, x + 1, y + 1)) {\n                    swap_balls(x, y, x + 1, y + 1);\n                } else {\n                    // Find a path to swap\n                    // This is a simplified approach; a more sophisticated pathfinding algorithm can be used here\n                    for (int i = x + 1; i < N; ++i) {\n                        if (is_adjacent(i, y + 1, i + 1, y + 1)) {\n                            swap_balls(i, y + 1, i + 1, y + 1);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid simulated_annealing() {\n    int current_violations = count_violations();\n    if (current_violations == 0) return;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    double temperature = 1.0;\n    double cooling_rate = 0.999;\n    int max_iterations = 10000;\n\n    for (int iter = 0; iter < max_iterations && current_violations > 0; ++iter) {\n        // Randomly select two adjacent balls to swap\n        int x1 = dis(gen) * N;\n        int y1 = dis(gen) * (x1 + 1);\n        int direction = dis(gen) * 6;\n\n        int x2, y2;\n        switch (direction) {\n            case 0: x2 = x1 - 1; y2 = y1 - 1; break;\n            case 1: x2 = x1 - 1; y2 = y1; break;\n            case 2: x2 = x1; y2 = y1 - 1; break;\n            case 3: x2 = x1; y2 = y1 + 1; break;\n            case 4: x2 = x1 + 1; y2 = y1; break;\n            case 5: x2 = x1 + 1; y2 = y1 + 1; break;\n        }\n\n        if (x2 < 0 || x2 >= N || y2 < 0 || y2 > x2) continue;\n\n        swap_balls(x1, y1, x2, y2);\n        int new_violations = count_violations();\n\n        if (new_violations < current_violations) {\n            current_violations = new_violations;\n        } else {\n            double probability = exp((current_violations - new_violations) / temperature);\n            if (dis(gen) > probability) {\n                swap_balls(x1, y1, x2, y2); // Revert the swap\n            } else {\n                current_violations = new_violations;\n            }\n        }\n\n        temperature *= cooling_rate;\n    }\n}\n\nint main() {\n    pyramid.resize(N);\n    for (int x = 0; x < N; ++x) {\n        pyramid[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> pyramid[x][y];\n        }\n    }\n\n    greedy_algorithm();\n    simulated_annealing();\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.x1 << \" \" << op.y1 << \" \" << op.x2 << \" \" << op.y2 << 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#include <utility>\n#include <cmath>\n\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = (D - 1) / 2;\n\nstruct Point {\n    int i, j;\n    Point(int i, int j) : i(i), j(j) {}\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.i) ^ hash<int>()(p.j);\n        }\n    };\n}\n\nvector<Point> get_neighbors(const Point& p, const unordered_set<Point>& obstacles) {\n    vector<Point> neighbors;\n    int di[] = {-1, 1, 0, 0};\n    int dj[] = {0, 0, -1, 1};\n    for (int k = 0; k < 4; ++k) {\n        Point neighbor(p.i + di[k], p.j + dj[k]);\n        if (neighbor.i >= 0 && neighbor.i < D && neighbor.j >= 0 && neighbor.j < D &&\n            obstacles.find(neighbor) == obstacles.end()) {\n            neighbors.push_back(neighbor);\n        }\n    }\n    return neighbors;\n}\n\nvector<vector<int>> bfs(const unordered_set<Point>& obstacles) {\n    vector<vector<int>> distance(D, vector<int>(D, -1));\n    queue<Point> q;\n    Point entrance(ENTRANCE_I, ENTRANCE_J);\n    distance[entrance.i][entrance.j] = 0;\n    q.push(entrance);\n\n    while (!q.empty()) {\n        Point current = q.front();\n        q.pop();\n        for (const Point& neighbor : get_neighbors(current, obstacles)) {\n            if (distance[neighbor.i][neighbor.j] == -1) {\n                distance[neighbor.i][neighbor.j] = distance[current.i][current.j] + 1;\n                q.push(neighbor);\n            }\n        }\n    }\n    return distance;\n}\n\nPoint find_storage_location(const unordered_set<Point>& obstacles, const vector<vector<int>>& distance, const unordered_set<Point>& occupied) {\n    vector<Point> candidates;\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            Point p(i, j);\n            if (distance[i][j] != -1 && obstacles.find(p) == obstacles.end() && occupied.find(p) == occupied.end()) {\n                candidates.push_back(p);\n            }\n        }\n    }\n    if (candidates.empty()) {\n        return Point(-1, -1); // No valid storage location\n    }\n    // Sort candidates by distance from entrance and then by some heuristic\n    sort(candidates.begin(), candidates.end(), [&distance](const Point& a, const Point& b) {\n        return distance[a.i][a.j] < distance[b.i][b.j];\n    });\n    return candidates[0];\n}\n\nvector<Point> find_retrieval_order(const unordered_set<Point>& obstacles, const vector<vector<Point>>& storage_order) {\n    vector<vector<int>> distance = bfs(obstacles);\n    unordered_set<Point> occupied;\n    for (const auto& row : storage_order) {\n        for (const Point& p : row) {\n            if (p.i != -1 && p.j != -1) {\n                occupied.insert(p);\n            }\n        }\n    }\n    vector<Point> retrieval_order;\n    while (!occupied.empty()) {\n        vector<Point> candidates;\n        for (const Point& p : occupied) {\n            if (distance[p.i][p.j] != -1) {\n                candidates.push_back(p);\n            }\n        }\n        if (candidates.empty()) {\n            break; // No more reachable containers\n        }\n        // Sort candidates by distance from entrance and then by some heuristic\n        sort(candidates.begin(), candidates.end(), [&distance](const Point& a, const Point& b) {\n            return distance[a.i][a.j] < distance[b.i][b.j];\n        });\n        Point next = candidates[0];\n        retrieval_order.push_back(next);\n        occupied.erase(next);\n        // Update distance for adjacent squares\n        for (const Point& neighbor : get_neighbors(next, obstacles)) {\n            if (occupied.find(neighbor) == occupied.end()) {\n                distance[neighbor.i][neighbor.j] = -1;\n            }\n        }\n    }\n    return retrieval_order;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    unordered_set<Point> obstacles;\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        obstacles.insert(Point(ri, rj));\n    }\n    vector<vector<int>> distance = bfs(obstacles);\n    unordered_set<Point> occupied;\n    vector<vector<Point>> storage_order(D, vector<Point>(D, Point(-1, -1)));\n    for (int d = 0; d < D * D - 1 - N; ++d) {\n        int t_d;\n        cin >> t_d;\n        Point storage_location = find_storage_location(obstacles, distance, occupied);\n        if (storage_location.i == -1 && storage_location.j == -1) {\n            cerr << \"No valid storage location found for container \" << t_d << endl;\n            return 1;\n        }\n        storage_order[storage_location.i][storage_location.j] = Point(t_d, d);\n        occupied.insert(storage_location);\n        cout << storage_location.i << \" \" << storage_location.j << endl;\n        cout.flush();\n    }\n    vector<Point> retrieval_order = find_retrieval_order(obstacles, storage_order);\n    for (const Point& p : retrieval_order) {\n        cout << p.i << \" \" << p.j << endl;\n    }\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <unordered_set>\n#include <algorithm>\n#include <atcoder/dsu>\n#include <atcoder/maxflow>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nvector<vector<int>> grid;\nvector<vector<int>> simplified_grid;\nint n, m;\n\nvoid bfs(int x, int y, int color, vector<vector<bool>>& visited) {\n    queue<Point> q;\n    q.push(Point(x, y));\n    visited[x][y] = true;\n    simplified_grid[x][y] = color;\n\n    while (!q.empty()) {\n        Point p = q.front();\n        q.pop();\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = p.x + dx[i];\n            int ny = p.y + dy[i];\n\n            if (nx >= 0 && nx < n && ny >= 0 && ny < n && !visited[nx][ny] && grid[nx][ny] == color) {\n                visited[nx][ny] = true;\n                simplified_grid[nx][ny] = color;\n                q.push(Point(nx, ny));\n            }\n        }\n    }\n}\n\nvoid simplify_map() {\n    simplified_grid = vector<vector<int>>(n, vector<int>(n, 0));\n    vector<vector<bool>> visited(n, vector<bool>(n, false));\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (!visited[i][j] && grid[i][j] != 0) {\n                bfs(i, j, grid[i][j], visited);\n            }\n        }\n    }\n}\n\nvoid connect_components() {\n    dsu d(n * n);\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] != 0) {\n                for (int k = 0; k < 4; ++k) {\n                    int ni = i + dx[k];\n                    int nj = j + dy[k];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && simplified_grid[ni][nj] != 0) {\n                        d.merge(i * n + j, ni * n + nj);\n                    }\n                }\n            }\n        }\n    }\n\n    unordered_map<int, vector<Point>> components;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] != 0) {\n                components[d.leader(i * n + j)].push_back(Point(i, j));\n            }\n        }\n    }\n\n    for (auto& [leader, points] : components) {\n        for (auto& p : points) {\n            simplified_grid[p.x][p.y] = simplified_grid[points[0].x][points[0].y];\n        }\n    }\n}\n\nvoid minimize_connectors() {\n    // This is a placeholder for a more sophisticated heuristic\n    // For simplicity, we'll just ensure that the connectors are minimal\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] == 0) {\n                bool is_connector = false;\n                for (int k = 0; k < 4; ++k) {\n                    int ni = i + dx[k];\n                    int nj = j + dy[k];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && simplified_grid[ni][nj] != 0) {\n                        is_connector = true;\n                        break;\n                    }\n                }\n                if (!is_connector) {\n                    simplified_grid[i][j] = 0;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> n >> m;\n    grid.resize(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    simplify_map();\n    connect_components();\n    minimize_connectors();\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cout << simplified_grid[i][j] << (j == n - 1 ? \"\\n\" : \" \");\n        }\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <iomanip>\n#include <climits>\n#include <cfloat>\n#include <cstring>\n#include <cassert>\n#include <chrono>\n#include <fstream>\n#include <sstream>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<pii> vpii;\ntypedef vector<pll> vpll;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef vector<vpii> vvpii;\ntypedef vector<vpll> vvpll;\ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\ntypedef tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;\n\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define lb lower_bound\n#define ub upper_bound\n\nconst int INF = 1e9;\nconst ll LINF = 1e18;\nconst ld EPS = 1e-9;\nconst int MOD = 1e9 + 7;\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint n, d, q;\nvector<double> weights;\nvector<int> groups;\n\nchar compare(const vector<int>& l, const vector<int>& r) {\n    cout << l.size() << \" \" << r.size();\n    for (int i : l) cout << \" \" << i;\n    for (int i : r) cout << \" \" << i;\n    cout << endl;\n    char res;\n    cin >> res;\n    return res;\n}\n\nvoid estimate_weights() {\n    weights.resize(n, 0.0);\n    for (int i = 0; i < n; ++i) {\n        for (int j = i + 1; j < n; ++j) {\n            char res = compare({i}, {j});\n            if (res == '<') {\n                weights[j] += 1.0;\n            } else if (res == '>') {\n                weights[i] += 1.0;\n            } else {\n                weights[i] += 0.5;\n                weights[j] += 0.5;\n            }\n        }\n    }\n}\n\nvoid assign_groups() {\n    groups.resize(n, 0);\n    vector<double> group_weights(d, 0.0);\n    for (int i = 0; i < n; ++i) {\n        int best_group = 0;\n        double min_diff = fabs(group_weights[0] - weights[i]);\n        for (int j = 1; j < d; ++j) {\n            double diff = fabs(group_weights[j] - weights[i]);\n            if (diff < min_diff) {\n                min_diff = diff;\n                best_group = j;\n            }\n        }\n        groups[i] = best_group;\n        group_weights[best_group] += weights[i];\n    }\n}\n\nvoid refine_weights() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = i + 1; j < n; ++j) {\n            if (groups[i] != groups[j]) {\n                char res = compare({i}, {j});\n                if (res == '<') {\n                    weights[j] += 1.0;\n                } else if (res == '>') {\n                    weights[i] += 1.0;\n                } else {\n                    weights[i] += 0.5;\n                    weights[j] += 0.5;\n                }\n            }\n        }\n    }\n}\n\nvoid solve() {\n    estimate_weights();\n    assign_groups();\n    refine_weights();\n    assign_groups();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> n >> d >> q;\n    solve();\n\n    for (int i = 0; i < n; ++i) {\n        cout << groups[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cassert>\n\nusing namespace std;\n\nconst int n = 200;\nconst int m = 10;\nconst int max_operations = 5000;\n\nvector<vector<int>> stacks(m, vector<int>(n / m));\n\nvoid read_input() {\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < n / m; ++j) {\n            cin >> stacks[i][j];\n        }\n    }\n}\n\nint find_stack(int v) {\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < stacks[i].size(); ++j) {\n            if (stacks[i][j] == v) {\n                return i;\n            }\n        }\n    }\n    return -1;\n}\n\nint find_position(int i, int v) {\n    for (int j = 0; j < stacks[i].size(); ++j) {\n        if (stacks[i][j] == v) {\n            return j;\n        }\n    }\n    return -1;\n}\n\nvoid move_box(int v, int dest_stack) {\n    int src_stack = find_stack(v);\n    int pos = find_position(src_stack, v);\n\n    vector<int> moved_boxes(stacks[src_stack].begin() + pos, stacks[src_stack].end());\n    stacks[src_stack].erase(stacks[src_stack].begin() + pos, stacks[src_stack].end());\n\n    stacks[dest_stack].insert(stacks[dest_stack].end(), moved_boxes.begin(), moved_boxes.end());\n}\n\nint find_smallest_remaining() {\n    int smallest = n + 1;\n    for (int i = 0; i < m; ++i) {\n        if (!stacks[i].empty()) {\n            smallest = min(smallest, stacks[i][0]);\n        }\n    }\n    return smallest;\n}\n\nbool is_smallest_at_top(int v) {\n    for (int i = 0; i < m; ++i) {\n        if (!stacks[i].empty() && stacks[i][0] == v) {\n            return true;\n        }\n    }\n    return false;\n}\n\nvector<pair<int, int>> solve() {\n    vector<pair<int, int>> operations;\n    int current_smallest = 1;\n\n    while (current_smallest <= n) {\n        if (is_smallest_at_top(current_smallest)) {\n            operations.emplace_back(current_smallest, 0);\n            current_smallest++;\n        } else {\n            int src_stack = find_stack(current_smallest);\n            int dest_stack = -1;\n            int min_size = n + 1;\n\n            for (int i = 0; i < m; ++i) {\n                if (i != src_stack && stacks[i].size() < min_size) {\n                    min_size = stacks[i].size();\n                    dest_stack = i;\n                }\n            }\n\n            if (dest_stack == -1) {\n                // No other stack available, move to any other stack\n                for (int i = 0; i < m; ++i) {\n                    if (i != src_stack) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n\n            operations.emplace_back(current_smallest, dest_stack + 1);\n            move_box(current_smallest, dest_stack);\n        }\n    }\n\n    return operations;\n}\n\nint main() {\n    read_input();\n    auto operations = solve();\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 <queue>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Square {\n    int i, j;\n    int dirtiness;\n    bool operator<(const Square& other) const {\n        return dirtiness < other.dirtiness;\n    }\n};\n\nvector<vector<int>> generateRoute(int N, const vector<vector<int>>& h, const vector<vector<int>>& v, const vector<vector<int>>& d) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    vector<vector<int>> route;\n    priority_queue<Square> pq;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            pq.push({i, j, d[i][j]});\n        }\n    }\n\n    auto isValidMove = [&](int i, int j, int di, int dj) {\n        if (di == 0) {\n            if (dj == 1) return j < N - 1 && v[i][j] == 0;\n            else return j > 0 && v[i][j - 1] == 0;\n        } else {\n            if (di == 1) return i < N - 1 && h[i][j] == 0;\n            else return i > 0 && h[i - 1][j] == 0;\n        }\n    };\n\n    auto dfs = [&](auto&& self, int i, int j) -> void {\n        visited[i][j] = true;\n        vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        vector<char> dirChars = {'R', 'D', 'L', 'U'};\n\n        // Prioritize high-dirtiness squares\n        vector<pair<int, int>> highDirtinessSquares;\n        for (const auto& dir : directions) {\n            int ni = i + dir.first;\n            int nj = j + dir.second;\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj] && isValidMove(i, j, dir.first, dir.second)) {\n                highDirtinessSquares.emplace_back(ni, nj);\n            }\n        }\n        sort(highDirtinessSquares.begin(), highDirtinessSquares.end(), [&](const auto& a, const auto& b) {\n            return d[a.first][a.second] > d[b.first][b.second];\n        });\n\n        for (const auto& sq : highDirtinessSquares) {\n            int ni = sq.first;\n            int nj = sq.second;\n            if (!visited[ni][nj]) {\n                for (size_t k = 0; k < directions.size(); ++k) {\n                    if (ni == i + directions[k].first && nj == j + directions[k].second) {\n                        route.push_back({i, j, ni, nj, dirChars[k]});\n                        break;\n                    }\n                }\n                self(self, ni, nj);\n            }\n        }\n    };\n\n    dfs(dfs, 0, 0);\n\n    // Ensure all squares are visited\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!visited[i][j]) {\n                // Find a path to the unvisited square\n                vector<vector<int>> dist(N, vector<int>(N, -1));\n                queue<pair<int, int>> q;\n                q.push({i, j});\n                dist[i][j] = 0;\n                vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n\n                while (!q.empty()) {\n                    auto [ci, cj] = q.front();\n                    q.pop();\n                    for (const auto& dir : directions) {\n                        int ni = ci + dir.first;\n                        int nj = cj + dir.second;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist[ni][nj] == -1 && isValidMove(ci, cj, dir.first, dir.second)) {\n                            dist[ni][nj] = dist[ci][cj] + 1;\n                            parent[ni][nj] = {ci, cj};\n                            q.push({ni, nj});\n                        }\n                    }\n                }\n\n                // Reconstruct path\n                vector<pair<int, int>> path;\n                for (int x = 0; x < N; ++x) {\n                    for (int y = 0; y < N; ++y) {\n                        if (visited[x][y]) {\n                            int current_i = x, current_j = y;\n                            while (current_i != -1 && current_j != -1) {\n                                path.emplace_back(current_i, current_j);\n                                auto [pi, pj] = parent[current_i][current_j];\n                                current_i = pi;\n                                current_j = pj;\n                            }\n                            reverse(path.begin(), path.end());\n                            break;\n                        }\n                    }\n                    if (!path.empty()) break;\n                }\n\n                for (size_t k = 1; k < path.size(); ++k) {\n                    auto [pi, pj] = path[k - 1];\n                    auto [ci, cj] = path[k];\n                    for (size_t l = 0; l < directions.size(); ++l) {\n                        if (ci == pi + directions[l].first && cj == pj + directions[l].second) {\n                            route.push_back({pi, pj, ci, cj, dirChars[l]});\n                            break;\n                        }\n                    }\n                }\n                dfs(dfs, i, j);\n            }\n        }\n    }\n\n    // Convert route to string\n    vector<char> result;\n    for (const auto& move : route) {\n        result.push_back(move[4]);\n    }\n\n    // Ensure the route returns to (0, 0)\n    if (route.back()[2] != 0 || route.back()[3] != 0) {\n        // Find a path back to (0, 0)\n        vector<vector<int>> dist(N, vector<int>(N, -1));\n        queue<pair<int, int>> q;\n        q.push({route.back()[2], route.back()[3]});\n        dist[route.back()[2]][route.back()[3]] = 0;\n        vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n\n        while (!q.empty()) {\n            auto [ci, cj] = q.front();\n            q.pop();\n            for (const auto& dir : directions) {\n                int ni = ci + dir.first;\n                int nj = cj + dir.second;\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist[ni][nj] == -1 && isValidMove(ci, cj, dir.first, dir.second)) {\n                    dist[ni][nj] = dist[ci][cj] + 1;\n                    parent[ni][nj] = {ci, cj};\n                    q.push({ni, nj});\n                }\n            }\n        }\n\n        // Reconstruct path\n        vector<pair<int, int>> path;\n        int current_i = 0, current_j = 0;\n        while (current_i != -1 && current_j != -1) {\n            path.emplace_back(current_i, current_j);\n            auto [pi, pj] = parent[current_i][current_j];\n            current_i = pi;\n            current_j = pj;\n        }\n        reverse(path.begin(), path.end());\n\n        for (size_t k = 1; k < path.size(); ++k) {\n            auto [pi, pj] = path[k - 1];\n            auto [ci, cj] = path[k];\n            for (size_t l = 0; l < directions.size(); ++l) {\n                if (ci == pi + directions[l].first && cj == pj + directions[l].second) {\n                    result.push_back(dirChars[l]);\n                    break;\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int N;\n    cin >> N;\n\n    vector<vector<int>> h(N - 1, vector<int>(N));\n    for (int i = 0; i < N - 1; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            h[i][j] = row[j] - '0';\n        }\n    }\n\n    vector<vector<int>> v(N, vector<int>(N - 1));\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N - 1; ++j) {\n            v[i][j] = row[j] - '0';\n        }\n    }\n\n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    vector<char> route = generateRoute(N, h, v, d);\n\n    for (char move : route) {\n        cout << move;\n    }\n    cout << endl;\n\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nstruct State {\n    int i, j;\n    unordered_set<int> included;\n    int cost;\n\n    bool operator>(const State& other) const {\n        return cost > other.cost;\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int s_i, s_j;\n    cin >> s_i >> s_j;\n\n    vector<vector<char>> keyboard(N, vector<char>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> keyboard[i][j];\n        }\n    }\n\n    vector<string> t(M);\n    for (int k = 0; k < M; ++k) {\n        cin >> t[k];\n    }\n\n    // Preprocess the positions of each character\n    unordered_map<char, vector<pair<int, int>>> char_positions;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char_positions[keyboard[i][j]].emplace_back(i, j);\n        }\n    }\n\n    // Priority queue for Dijkstra's algorithm\n    priority_queue<State, vector<State>, greater<State>> pq;\n    pq.push({s_i, s_j, {}, 0});\n\n    // Visited set to avoid revisiting the same state\n    unordered_map<int, unordered_map<int, unordered_set<int>>> visited;\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.included.size() == M) {\n            // Found a solution, output the path\n            // (In a real implementation, you would need to reconstruct the path)\n            // For simplicity, we assume the path is stored and output here\n            cout << \"Solution found with cost \" << current.cost << endl;\n            return 0;\n        }\n\n        if (visited[current.i][current.j].count(current.included.size())) {\n            continue;\n        }\n        visited[current.i][current.j].insert(current.included.size());\n\n        // Explore all possible next characters\n        for (const auto& entry : char_positions) {\n            char c = entry.first;\n            for (const auto& pos : entry.second) {\n                int next_i = pos.first;\n                int next_j = pos.second;\n\n                // Calculate the cost to move to this character\n                int move_cost = abs(next_i - current.i) + abs(next_j - current.j) + 1;\n\n                // Check if adding this character includes any new lucky words\n                unordered_set<int> new_included = current.included;\n                for (int k = 0; k < M; ++k) {\n                    if (new_included.count(k)) continue;\n                    // Check if the new character includes the k-th lucky word\n                    // This is a simplified check; in practice, you would need a more efficient way\n                    // For example, using a suffix automaton or a rolling hash\n                    string s;\n                    // Reconstruct the string from the current state (simplified)\n                    // In a real implementation, you would need to keep track of the string\n                    if (s.find(t[k]) != string::npos) {\n                        new_included.insert(k);\n                    }\n                }\n\n                if (new_included.size() > current.included.size()) {\n                    pq.push({next_i, next_j, new_included, current.cost + move_cost});\n                }\n            }\n        }\n    }\n\n    cout << \"No solution found within the operation limit.\" << endl;\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <set>\n#include <random>\n#include <cmath>\n#include <algorithm>\n#include <atcoder/random>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Square {\n    int i, j;\n    Square(int i, int j) : i(i), j(j) {}\n    bool operator<(const Square& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nstruct OilField {\n    vector<Square> squares;\n    int di, dj;\n};\n\nvector<OilField> fields;\nint N, M;\ndouble epsilon;\n\nvoid read_input() {\n    cin >> N >> M >> epsilon;\n    fields.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        fields[k].squares.resize(d);\n        for (int l = 0; l < d; ++l) {\n            cin >> fields[k].squares[l].i >> fields[k].squares[l].j;\n        }\n    }\n}\n\nvoid drill(int i, int j) {\n    cout << \"q 1 \" << i << \" \" << j << endl;\n    cout.flush();\n    int v;\n    cin >> v;\n    // Update the oil reserves for the square (i, j)\n}\n\nint divinate(const vector<Square>& squares) {\n    cout << \"q \" << squares.size();\n    for (const auto& sq : squares) {\n        cout << \" \" << sq.i << \" \" << sq.j;\n    }\n    cout << endl;\n    cout.flush();\n    int v;\n    cin >> v;\n    return v;\n}\n\nvoid guess(const set<Square>& squares) {\n    cout << \"a \" << squares.size();\n    for (const auto& sq : squares) {\n        cout << \" \" << sq.i << \" \" << sq.j;\n    }\n    cout << endl;\n    cout.flush();\n    int correct;\n    cin >> correct;\n    if (correct) {\n        exit(0);\n    }\n}\n\nint main() {\n    read_input();\n\n    // Initial random drilling\n    set<Square> drilled;\n    mt19937 rng(random_device{}());\n    uniform_int_distribution<int> dist(0, N - 1);\n    for (int k = 0; k < 10; ++k) {\n        int i = dist(rng);\n        int j = dist(rng);\n        drill(i, j);\n        drilled.insert(Square(i, j));\n    }\n\n    // Divination to estimate total oil reserves\n    vector<Square> all_squares;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            all_squares.emplace_back(i, j);\n        }\n    }\n    int total_estimate = divinate(all_squares);\n\n    // Heuristic guided drilling\n    set<Square> candidates;\n    for (const auto& field : fields) {\n        for (const auto& sq : field.squares) {\n            candidates.insert(sq);\n        }\n    }\n\n    while (true) {\n        // Prioritize squares that are part of the polyominoes with the highest estimated oil reserves\n        vector<Square> to_divinate;\n        for (const auto& sq : candidates) {\n            if (drilled.find(sq) == drilled.end()) {\n                to_divinate.push_back(sq);\n            }\n        }\n\n        if (to_divinate.empty()) break;\n\n        // Divinate a subset of candidates\n        int k = min(10, (int)to_divinate.size());\n        vector<Square> subset(to_divinate.begin(), to_divinate.begin() + k);\n        int estimate = divinate(subset);\n\n        // Update the set of candidates based on the estimate\n        for (const auto& sq : subset) {\n            if (estimate > 0) {\n                candidates.insert(sq);\n            } else {\n                candidates.erase(sq);\n            }\n        }\n\n        // Drill a square from the candidates\n        if (!candidates.empty()) {\n            auto it = candidates.begin();\n            advance(it, dist(rng) % candidates.size());\n            Square sq = *it;\n            drill(sq.i, sq.j);\n            drilled.insert(sq);\n        }\n\n        // Guess the set of squares with oil reserves\n        if (drilled.size() >= 10) {\n            guess(drilled);\n        }\n    }\n\n    return 0;\n}","ahc031":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <climits>\n\nusing namespace std;\n\nstruct Rectangle {\n    int i0, j0, i1, j1;\n    Rectangle(int i0, int j0, int i1, int j1) : i0(i0), j0(j0), i1(i1), j1(j1) {}\n    int area() const { return (i1 - i0) * (j1 - j0); }\n};\n\nstruct Solution {\n    vector<vector<Rectangle>> rectangles;\n    int total_cost;\n};\n\nint calculate_area_cost(const vector<vector<int>>& a, const Solution& sol) {\n    int cost = 0;\n    for (int d = 0; d < sol.rectangles.size(); ++d) {\n        for (int k = 0; k < sol.rectangles[d].size(); ++k) {\n            int b = sol.rectangles[d][k].area();\n            if (a[d][k] > b) {\n                cost += 100 * (a[d][k] - b);\n            }\n        }\n    }\n    return cost;\n}\n\nint calculate_partition_cost(const Solution& prev_sol, const Solution& curr_sol) {\n    int cost = 0;\n    for (int d = 0; d < curr_sol.rectangles.size(); ++d) {\n        if (d == 0) continue; // No partition cost on the first day\n        for (int i = 1; i < 1000; ++i) {\n            for (int j = 0; j < 999; ++j) {\n                bool prev_has_horizontal = false;\n                bool curr_has_horizontal = false;\n                for (const auto& rect : prev_sol.rectangles[d-1]) {\n                    if ((rect.i0 == i && rect.j0 <= j && rect.j1 > j) ||\n                        (rect.i1 == i && rect.j0 <= j && rect.j1 > j)) {\n                        prev_has_horizontal = true;\n                        break;\n                    }\n                }\n                for (const auto& rect : curr_sol.rectangles[d]) {\n                    if ((rect.i0 == i && rect.j0 <= j && rect.j1 > j) ||\n                        (rect.i1 == i && rect.j0 <= j && rect.j1 > j)) {\n                        curr_has_horizontal = true;\n                        break;\n                    }\n                }\n                if (prev_has_horizontal != curr_has_horizontal) {\n                    cost++;\n                }\n            }\n        }\n        for (int i = 0; i < 999; ++i) {\n            for (int j = 1; j < 1000; ++j) {\n                bool prev_has_vertical = false;\n                bool curr_has_vertical = false;\n                for (const auto& rect : prev_sol.rectangles[d-1]) {\n                    if ((rect.j0 == j && rect.i0 <= i && rect.i1 > i) ||\n                        (rect.j1 == j && rect.i0 <= i && rect.i1 > i)) {\n                        prev_has_vertical = true;\n                        break;\n                    }\n                }\n                for (const auto& rect : curr_sol.rectangles[d]) {\n                    if ((rect.j0 == j && rect.i0 <= i && rect.i1 > i) ||\n                        (rect.j1 == j && rect.i0 <= i && rect.i1 > i)) {\n                        curr_has_vertical = true;\n                        break;\n                    }\n                }\n                if (prev_has_vertical != curr_has_vertical) {\n                    cost++;\n                }\n            }\n        }\n    }\n    return cost;\n}\n\nSolution greedy_solution(const vector<vector<int>>& a) {\n    Solution sol;\n    sol.rectangles.resize(a.size());\n    for (int d = 0; d < a.size(); ++d) {\n        vector<int> remaining_area = a[d];\n        sort(remaining_area.rbegin(), remaining_area.rend());\n        vector<pair<int, int>> positions;\n        for (int i = 0; i < 1000; ++i) {\n            for (int j = 0; j < 1000; ++j) {\n                positions.emplace_back(i, j);\n            }\n        }\n        random_device rd;\n        mt19937 g(rd());\n        shuffle(positions.begin(), positions.end(), g);\n        for (int k = 0; k < a[d].size(); ++k) {\n            int best_area = 0;\n            Rectangle best_rect(0, 0, 0, 0);\n            for (const auto& pos : positions) {\n                int i0 = pos.first;\n                int j0 = pos.second;\n                for (int i1 = i0 + 1; i1 <= 1000; ++i1) {\n                    for (int j1 = j0 + 1; j1 <= 1000; ++j1) {\n                        int area = (i1 - i0) * (j1 - j0);\n                        if (area > remaining_area[k]) continue;\n                        if (area > best_area) {\n                            best_area = area;\n                            best_rect = Rectangle(i0, j0, i1, j1);\n                        }\n                    }\n                }\n            }\n            sol.rectangles[d].push_back(best_rect);\n            remaining_area[k] -= best_area;\n        }\n    }\n    sol.total_cost = calculate_area_cost(a, sol) + calculate_partition_cost(sol, sol);\n    return sol;\n}\n\nSolution simulated_annealing(const vector<vector<int>>& a, const Solution& initial_sol, double initial_temp, double cooling_rate, int iterations) {\n    Solution current_sol = initial_sol;\n    Solution best_sol = initial_sol;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    double temp = initial_temp;\n    for (int iter = 0; iter < iterations; ++iter) {\n        Solution new_sol = current_sol;\n        int d = rand() % a.size();\n        int k = rand() % a[d].size();\n        int i0 = rand() % 1000;\n        int j0 = rand() % 1000;\n        int i1 = i0 + 1 + rand() % (1000 - i0);\n        int j1 = j0 + 1 + rand() % (1000 - j0);\n        new_sol.rectangles[d][k] = Rectangle(i0, j0, i1, j1);\n        int new_area_cost = calculate_area_cost(a, new_sol);\n        int new_partition_cost = calculate_partition_cost(current_sol, new_sol);\n        int new_total_cost = new_area_cost + new_partition_cost;\n        if (new_total_cost < current_sol.total_cost || dis(gen) < exp((current_sol.total_cost - new_total_cost) / temp)) {\n            current_sol = new_sol;\n            current_sol.total_cost = new_total_cost;\n            if (new_total_cost < best_sol.total_cost) {\n                best_sol = new_sol;\n                best_sol.total_cost = new_total_cost;\n            }\n        }\n        temp *= cooling_rate;\n    }\n    return best_sol;\n}\n\nint main() {\n    int W, D, N;\n    cin >> W >> D >> N;\n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cin >> a[d][k];\n        }\n    }\n    Solution initial_sol = greedy_solution(a);\n    Solution best_sol = simulated_annealing(a, initial_sol, 1000.0, 0.999, 10000);\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << best_sol.rectangles[d][k].i0 << \" \" << best_sol.rectangles[d][k].j0 << \" \"\n                 << best_sol.rectangles[d][k].i1 << \" \" << best_sol.rectangles[d][k].j1 << endl;\n        }\n    }\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\n\nstruct Stamp {\n    int s[3][3];\n};\n\nstruct Operation {\n    int m, p, q;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int a[N][N];\n    Stamp stamps[M];\n\n    // Read initial grid\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> a[i][j];\n        }\n    }\n\n    // Read stamps\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].s[i][j];\n            }\n        }\n    }\n\n    vector<Operation> operations;\n    int current_sum = 0;\n\n    // Calculate initial sum\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            current_sum = (current_sum + a[i][j] % MOD) % MOD;\n        }\n    }\n\n    // Greedy approach\n    for (int op = 0; op < K; ++op) {\n        int best_m = -1, best_p = -1, best_q = -1;\n        int max_increase = 0;\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    int increase = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            int new_val = (a[p + i][q + j] + stamps[m].s[i][j]) % MOD;\n                            increase += (new_val - (a[p + i][q + j] % MOD)) % MOD;\n                        }\n                    }\n                    if (increase > max_increase) {\n                        max_increase = increase;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_m == -1) break; // No more beneficial operations\n\n        operations.push_back({best_m, best_p, best_q});\n\n        // Apply the best operation\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                a[best_p + i][best_q + j] = (a[best_p + i][best_q + j] + stamps[best_m].s[i][j]) % MOD;\n            }\n        }\n\n        current_sum = (current_sum + max_increase) % MOD;\n    }\n\n    // Output the operations\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.m << \" \" << op.p << \" \" << op.q << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_map>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURNS = 10000;\n\nstruct Crane {\n    int x, y;\n    bool is_large;\n    bool holding;\n    int container;\n};\n\nstruct Container {\n    int x, y;\n    int number;\n};\n\nvector<vector<int>> A(N, vector<int>(N));\nvector<Crane> cranes;\nvector<vector<int>> grid(N, vector<int>(N, -1));\nvector<vector<int>> next_container(N, vector<int>(N, 0));\nvector<string> actions(N, string(MAX_TURNS, '.'));\n\nint calculate_score() {\n    // Implement scoring logic here\n    return 0;\n}\n\nvoid simulate_turn() {\n    // Step 1: Bring in new containers\n    for (int i = 0; i < N; ++i) {\n        if (next_container[i][0] < N && grid[i][0] == -1) {\n            grid[i][0] = A[i][next_container[i][0]];\n            next_container[i][0]++;\n        }\n    }\n\n    // Step 2: Perform crane actions\n    vector<vector<int>> new_grid(N, vector<int>(N, -1));\n    vector<Crane> new_cranes;\n    for (int i = 0; i < N; ++i) {\n        Crane c = cranes[i];\n        char action = actions[i][0];\n        actions[i].erase(0, 1);\n\n        if (action == 'B' && !c.holding) {\n            continue; // Crane is bombed\n        }\n\n        switch (action) {\n            case 'P':\n                if (!c.holding && grid[c.x][c.y] != -1) {\n                    c.holding = true;\n                    c.container = grid[c.x][c.y];\n                    grid[c.x][c.y] = -1;\n                }\n                break;\n            case 'Q':\n                if (c.holding && grid[c.x][c.y] == -1) {\n                    grid[c.x][c.y] = c.container;\n                    c.holding = false;\n                }\n                break;\n            case 'U':\n                if (c.x > 0 && (grid[c.x - 1][c.y] == -1 || c.is_large)) {\n                    c.x--;\n                }\n                break;\n            case 'D':\n                if (c.x < N - 1 && (grid[c.x + 1][c.y] == -1 || c.is_large)) {\n                    c.x++;\n                }\n                break;\n            case 'L':\n                if (c.y > 0 && (grid[c.x][c.y - 1] == -1 || c.is_large)) {\n                    c.y--;\n                }\n                break;\n            case 'R':\n                if (c.y < N - 1 && (grid[c.x][c.y + 1] == -1 || c.is_large)) {\n                    c.y++;\n                }\n                break;\n            case '.':\n                break;\n        }\n\n        if (action != 'B') {\n            new_cranes.push_back(c);\n        }\n    }\n    cranes = new_cranes;\n\n    // Step 3: Dispatch containers\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][N - 1] != -1) {\n            grid[i][N - 1] = -1;\n        }\n    }\n}\n\nvoid heuristic_solution() {\n    // Initialize cranes\n    for (int i = 0; i < N; ++i) {\n        cranes.push_back({i, 0, i == 0, false, -1});\n    }\n\n    // Simulate turns\n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        simulate_turn();\n\n        // Simple heuristic: Move cranes towards the right edge\n        for (int i = 0; i < N; ++i) {\n            Crane &c = cranes[i];\n            if (c.y < N - 1) {\n                actions[i][turn] = 'R';\n            } else if (c.y == N - 1 && c.holding) {\n                actions[i][turn] = 'Q';\n            } else if (c.y == N - 1 && !c.holding && grid[c.x][c.y] != -1) {\n                actions[i][turn] = 'P';\n            } else if (c.y == N - 1 && !c.holding && grid[c.x][c.y] == -1) {\n                actions[i][turn] = '.';\n            }\n        }\n    }\n}\n\nint main() {\n    // Read input\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n        }\n    }\n\n    // Run heuristic solution\n    heuristic_solution();\n\n    // Output actions\n    for (int i = 0; i < N; ++i) {\n        cout << actions[i] << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <climits>\n#include <unordered_map>\n#include <tuple>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_OPERATIONS = 100000;\nconst int MAX_SOIL = 1000000;\n\nstruct State {\n    int x, y;\n    int soil;\n    int cost;\n    vector<string> operations;\n\n    bool operator>(const State& other) const {\n        return cost > other.cost;\n    }\n};\n\nint heuristic(int x1, int y1, int x2, int y2, int soil) {\n    return abs(x1 - x2) + abs(y1 - y2) + soil;\n}\n\nvector<string> findPath(int startX, int startY, int endX, int endY, int soil) {\n    priority_queue<State, vector<State>, greater<State>> pq;\n    unordered_map<int, unordered_map<int, int>> visited;\n\n    pq.push({startX, startY, soil, 0, {}});\n    visited[startX][startY] = 0;\n\n    vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n    vector<string> dirChars = {\"U\", \"D\", \"L\", \"R\"};\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.x == endX && current.y == endY) {\n            return current.operations;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int newX = current.x + directions[i].first;\n            int newY = current.y + directions[i].second;\n\n            if (newX >= 0 && newX < N && newY >= 0 && newY < N) {\n                int newCost = current.cost + 100 + current.soil;\n                if (visited[newX][newY] == 0 || newCost < visited[newX][newY]) {\n                    visited[newX][newY] = newCost;\n                    vector<string> newOperations = current.operations;\n                    newOperations.push_back(dirChars[i]);\n                    pq.push({newX, newY, current.soil, newCost, newOperations});\n                }\n            }\n        }\n    }\n\n    return {};\n}\n\nvector<string> solve(vector<vector<int>>& grid) {\n    vector<string> operations;\n    int totalOperations = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == 0) continue;\n\n            int currentX = 0, currentY = 0;\n            int soil = 0;\n\n            // Move to the target square\n            vector<string> path = findPath(currentX, currentY, i, j, soil);\n            operations.insert(operations.end(), path.begin(), path.end());\n            currentX = i;\n            currentY = j;\n\n            // Load or unload soil\n            if (grid[i][j] > 0) {\n                int d = min(grid[i][j], MAX_SOIL);\n                operations.push_back(\"+\" + to_string(d));\n                soil += d;\n                grid[i][j] -= d;\n            } else {\n                int d = min(-grid[i][j], soil);\n                operations.push_back(\"-\" + to_string(d));\n                soil -= d;\n                grid[i][j] += d;\n            }\n\n            // Move back to the origin if there's soil to carry\n            if (soil > 0) {\n                path = findPath(currentX, currentY, 0, 0, soil);\n                operations.insert(operations.end(), path.begin(), path.end());\n                currentX = 0;\n                currentY = 0;\n            }\n\n            if (operations.size() >= MAX_OPERATIONS) break;\n        }\n        if (operations.size() >= MAX_OPERATIONS) break;\n    }\n\n    return operations;\n}\n\nint main() {\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<string> operations = solve(grid);\n    for (const string& op : operations) {\n        cout << op << endl;\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 6;\nconst int M = 15;\nconst int T = 10;\nconst int SEED_COUNT = 2 * N * (N - 1);\nconst int POPULATION_SIZE = 50;\nconst int GENERATIONS = 10;\nconst double MUTATION_RATE = 0.1;\n\nvector<vector<int>> X(SEED_COUNT, vector<int>(M, 0));\nvector<int> X_max(M, 0);\n\nstruct Individual {\n    vector<vector<int>> grid;\n    int fitness;\n\n    Individual() : grid(N, vector<int>(N, 0)), fitness(0) {}\n};\n\nvector<Individual> population(POPULATION_SIZE);\n\nvoid initializePopulation() {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, SEED_COUNT - 1);\n\n    for (auto& individual : population) {\n        vector<int> seeds(SEED_COUNT);\n        iota(seeds.begin(), seeds.end(), 0);\n        shuffle(seeds.begin(), seeds.end(), gen);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                individual.grid[i][j] = seeds[i * N + j];\n            }\n        }\n    }\n}\n\nvector<vector<int>> generateNewSeeds(const vector<vector<int>>& grid) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, 1);\n\n    vector<vector<int>> newSeeds(SEED_COUNT, vector<int>(M, 0));\n\n    int index = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N - 1; ++j) {\n            int seed1 = grid[i][j];\n            int seed2 = grid[i][j + 1];\n            for (int l = 0; l < M; ++l) {\n                newSeeds[index][l] = dist(gen) ? X[seed1][l] : X[seed2][l];\n            }\n            ++index;\n        }\n    }\n\n    for (int i = 0; i < N - 1; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int seed1 = grid[i][j];\n            int seed2 = grid[i + 1][j];\n            for (int l = 0; l < M; ++l) {\n                newSeeds[index][l] = dist(gen) ? X[seed1][l] : X[seed2][l];\n            }\n            ++index;\n        }\n    }\n\n    return newSeeds;\n}\n\nint calculateFitness(const vector<vector<int>>& grid) {\n    vector<vector<int>> currentSeeds = X;\n    for (int t = 0; t < T; ++t) {\n        currentSeeds = generateNewSeeds(grid);\n    }\n\n    int maxValue = 0;\n    for (const auto& seed : currentSeeds) {\n        int value = accumulate(seed.begin(), seed.end(), 0);\n        if (value > maxValue) {\n            maxValue = value;\n        }\n    }\n\n    int sumXMax = accumulate(X_max.begin(), X_max.end(), 0);\n    return round(1e6 * maxValue / sumXMax);\n}\n\nvoid evaluatePopulation() {\n    for (auto& individual : population) {\n        individual.fitness = calculateFitness(individual.grid);\n    }\n}\n\nvector<Individual> selectParents() {\n    vector<Individual> parents;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, POPULATION_SIZE - 1);\n\n    for (int i = 0; i < POPULATION_SIZE; ++i) {\n        int idx1 = dist(gen);\n        int idx2 = dist(gen);\n        parents.push_back(population[idx1].fitness > population[idx2].fitness ? population[idx1] : population[idx2]);\n    }\n\n    return parents;\n}\n\nvector<Individual> crossover(const vector<Individual>& parents) {\n    vector<Individual> offspring;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, N * N - 1);\n\n    for (int i = 0; i < POPULATION_SIZE; i += 2) {\n        Individual child1, child2;\n        int crossoverPoint = dist(gen);\n\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < N; ++k) {\n                if (j * N + k < crossoverPoint) {\n                    child1.grid[j][k] = parents[i].grid[j][k];\n                    child2.grid[j][k] = parents[i + 1].grid[j][k];\n                } else {\n                    child1.grid[j][k] = parents[i + 1].grid[j][k];\n                    child2.grid[j][k] = parents[i].grid[j][k];\n                }\n            }\n        }\n\n        offspring.push_back(child1);\n        offspring.push_back(child2);\n    }\n\n    return offspring;\n}\n\nvoid mutate(vector<Individual>& offspring) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<double> dist(0.0, 1.0);\n    uniform_int_distribution<int> seedDist(0, SEED_COUNT - 1);\n\n    for (auto& individual : offspring) {\n        if (dist(gen) < MUTATION_RATE) {\n            int i1 = seedDist(gen) / N;\n            int j1 = seedDist(gen) % N;\n            int i2 = seedDist(gen) / N;\n            int j2 = seedDist(gen) % N;\n            swap(individual.grid[i1][j1], individual.grid[i2][j2]);\n        }\n    }\n}\n\nvoid geneticAlgorithm() {\n    initializePopulation();\n    evaluatePopulation();\n\n    for (int gen = 0; gen < GENERATIONS; ++gen) {\n        vector<Individual> parents = selectParents();\n        vector<Individual> offspring = crossover(parents);\n        mutate(offspring);\n\n        for (auto& individual : offspring) {\n            individual.fitness = calculateFitness(individual.grid);\n        }\n\n        population.insert(population.end(), offspring.begin(), offspring.end());\n        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n            return a.fitness > b.fitness;\n        });\n        population.resize(POPULATION_SIZE);\n    }\n}\n\nint main() {\n    // Read input\n    for (int i = 0; i < SEED_COUNT; ++i) {\n        for (int j = 0; j < M; ++j) {\n            cin >> X[i][j];\n            if (X[i][j] > X_max[j]) {\n                X_max[j] = X[i][j];\n            }\n        }\n    }\n\n    // Run genetic algorithm\n    geneticAlgorithm();\n\n    // Output the best solution\n    Individual best = *max_element(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n        return a.fitness < b.fitness;\n    });\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << best.grid[i][j];\n            if (j < N - 1) {\n                cout << \" \";\n            } else {\n                cout << endl;\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct TreeNode {\n    int id;\n    int parent;\n    int length;\n    vector<int> children;\n    Point position;\n    Point direction;\n    bool isFingertip;\n    bool holding;\n\n    TreeNode(int id, int parent, int length, const Point& position, const Point& direction, bool isFingertip)\n        : id(id), parent(parent), length(length), position(position), direction(direction), isFingertip(isFingertip), holding(false) {}\n};\n\nclass RoboticArm {\nprivate:\n    int N, M, V;\n    vector<vector<int>> grid;\n    vector<vector<int>> target;\n    vector<TreeNode> tree;\n    Point rootPosition;\n    vector<string> operations;\n    unordered_map<Point, bool> occupied;\n\n    void designTree() {\n        // Design a star-shaped tree\n        tree.emplace_back(0, -1, 0, rootPosition, Point(1, 0), false);\n        for (int i = 1; i < V; ++i) {\n            int parent = 0;\n            int length = 1;\n            Point direction = Point(1, 0);\n            tree.emplace_back(i, parent, length, rootPosition, direction, true);\n            tree[parent].children.push_back(i);\n        }\n    }\n\n    void moveRoot(int dx, int dy) {\n        rootPosition.x += dx;\n        rootPosition.y += dy;\n        for (auto& node : tree) {\n            node.position.x += dx;\n            node.position.y += dy;\n        }\n    }\n\n    void rotateSubtree(int nodeId, int rotation) {\n        if (rotation == 0) return;\n        TreeNode& node = tree[nodeId];\n        int newDirX = node.direction.x;\n        int newDirY = node.direction.y;\n        if (rotation == 1) { // Counterclockwise\n            newDirX = -node.direction.y;\n            newDirY = node.direction.x;\n        } else if (rotation == 2) { // Clockwise\n            newDirX = node.direction.y;\n            newDirY = -node.direction.x;\n        }\n        node.direction.x = newDirX;\n        node.direction.y = newDirY;\n        for (int childId : node.children) {\n            rotateSubtree(childId, rotation);\n        }\n    }\n\n    void grabOrRelease(int nodeId) {\n        TreeNode& node = tree[nodeId];\n        if (!node.isFingertip) return;\n        Point fingertipPos = node.position;\n        fingertipPos.x += node.direction.x * node.length;\n        fingertipPos.y += node.direction.y * node.length;\n        if (fingertipPos.x < 0 || fingertipPos.x >= N || fingertipPos.y < 0 || fingertipPos.y >= N) return;\n        if (grid[fingertipPos.x][fingertipPos.y] == 1 && target[fingertipPos.x][fingertipPos.y] == 0 && !node.holding) {\n            grid[fingertipPos.x][fingertipPos.y] = 0;\n            node.holding = true;\n        } else if (grid[fingertipPos.x][fingertipPos.y] == 0 && target[fingertipPos.x][fingertipPos.y] == 1 && node.holding) {\n            grid[fingertipPos.x][fingertipPos.y] = 1;\n            node.holding = false;\n        }\n    }\n\n    void performOperation(const string& op) {\n        operations.push_back(op);\n        char move = op[0];\n        if (move == 'U') moveRoot(-1, 0);\n        else if (move == 'D') moveRoot(1, 0);\n        else if (move == 'L') moveRoot(0, -1);\n        else if (move == 'R') moveRoot(0, 1);\n        for (int i = 1; i < V; ++i) {\n            char rot = op[i];\n            if (rot == 'L') rotateSubtree(i, 1);\n            else if (rot == 'R') rotateSubtree(i, 2);\n        }\n        for (int i = 0; i < V; ++i) {\n            char action = op[V + i];\n            if (action == 'P') grabOrRelease(i);\n        }\n    }\n\n    void moveTakoyaki(const Point& start, const Point& end) {\n        // Simplified path planning: move directly to the target\n        int dx = end.x - start.x;\n        int dy = end.y - start.y;\n        string op(V * 2, '.');\n        if (dx > 0) op[0] = 'D';\n        else if (dx < 0) op[0] = 'U';\n        else if (dy > 0) op[0] = 'R';\n        else if (dy < 0) op[0] = 'L';\n        performOperation(op);\n        op = string(V * 2, '.');\n        op[V + 1] = 'P'; // Grab or release\n        performOperation(op);\n        if (dx > 0) op[0] = 'U';\n        else if (dx < 0) op[0] = 'D';\n        else if (dy > 0) op[0] = 'L';\n        else if (dy < 0) op[0] = 'R';\n        performOperation(op);\n        op[V + 1] = 'P'; // Grab or release\n        performOperation(op);\n    }\n\npublic:\n    RoboticArm(int N, int M, int V, const vector<vector<int>>& grid, const vector<vector<int>>& target)\n        : N(N), M(M), V(V), grid(grid), target(target), rootPosition(0, 0) {\n        designTree();\n    }\n\n    void solve() {\n        vector<Point> takoyakiPositions;\n        vector<Point> targetPositions;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == 1) {\n                    takoyakiPositions.emplace_back(i, j);\n                }\n                if (target[i][j] == 1) {\n                    targetPositions.emplace_back(i, j);\n                }\n            }\n        }\n        for (size_t i = 0; i < takoyakiPositions.size(); ++i) {\n            moveTakoyaki(takoyakiPositions[i], targetPositions[i]);\n        }\n    }\n\n    void printSolution() {\n        cout << tree.size() << endl;\n        for (size_t i = 1; i < tree.size(); ++i) {\n            cout << tree[i].parent << \" \" << tree[i].length << endl;\n        }\n        cout << rootPosition.x << \" \" << rootPosition.y << endl;\n        for (const string& op : operations) {\n            cout << op << endl;\n        }\n    }\n};\n\nint main() {\n    int N, M, V;\n    cin >> N >> M >> V;\n    vector<vector<int>> grid(N, vector<int>(N));\n    vector<vector<int>> target(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = row[j] - '0';\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            target[i][j] = row[j] - '0';\n        }\n    }\n    RoboticArm arm(N, M, V, grid, target);\n    arm.solve();\n    arm.printSolution();\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Polygon {\n    vector<Point> vertices;\n    int mackerels, sardines;\n    Polygon() : mackerels(0), sardines(0) {}\n};\n\nint cross(const Point &O, const Point &A, const Point &B) {\n    return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);\n}\n\nvector<Point> convex_hull(vector<Point> points) {\n    int n = points.size(), k = 0;\n    vector<Point> hull(2 * n);\n    sort(points.begin(), points.end(), [](const Point &a, const Point &b) {\n        return a.x < b.x || (a.x == b.x && a.y < b.y);\n    });\n    for (int i = 0; i < n; ++i) {\n        while (k >= 2 && cross(hull[k-2], hull[k-1], points[i]) <= 0) k--;\n        hull[k++] = points[i];\n    }\n    for (int i = n-2, t = k+1; i >= 0; --i) {\n        while (k >= t && cross(hull[k-2], hull[k-1], points[i]) <= 0) k--;\n        hull[k++] = points[i];\n    }\n    hull.resize(k-1);\n    return hull;\n}\n\nbool is_point_in_polygon(const Point &p, const Polygon &poly) {\n    int n = poly.vertices.size();\n    if (n < 3) return false;\n    bool inside = false;\n    for (int i = 0, j = n - 1; i < n; j = i++) {\n        if (((poly.vertices[i].y > p.y) != (poly.vertices[j].y > p.y)) &&\n            (p.x < (poly.vertices[j].x - poly.vertices[i].x) * (p.y - poly.vertices[i].y) / (poly.vertices[j].y - poly.vertices[i].y) + poly.vertices[i].x))\n            inside = !inside;\n    }\n    return inside;\n}\n\nint count_points_in_polygon(const vector<Point> &points, const Polygon &poly) {\n    int count = 0;\n    for (const auto &p : points) {\n        if (is_point_in_polygon(p, poly)) {\n            count++;\n        }\n    }\n    return count;\n}\n\nPolygon generate_random_polygon(const vector<Point> &hull, int max_vertices, int max_edge_length) {\n    Polygon poly;\n    int n = hull.size();\n    if (n < 4) return poly;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, n - 1);\n\n    int start = dis(gen);\n    poly.vertices.push_back(hull[start]);\n\n    int current = start;\n    int total_length = 0;\n    while (poly.vertices.size() < max_vertices) {\n        int next = (current + 1) % n;\n        int dx = hull[next].x - hull[current].x;\n        int dy = hull[next].y - hull[current].y;\n        int edge_length = abs(dx) + abs(dy);\n\n        if (total_length + edge_length > max_edge_length) {\n            break;\n        }\n\n        if (dx != 0 && dy != 0) {\n            // Ensure edges are parallel to x-axis or y-axis\n            if (abs(dx) > abs(dy)) {\n                poly.vertices.emplace_back(hull[current].x + dx, hull[current].y);\n            } else {\n                poly.vertices.emplace_back(hull[current].x, hull[current].y + dy);\n            }\n        } else {\n            poly.vertices.push_back(hull[next]);\n        }\n\n        total_length += edge_length;\n        current = next;\n    }\n\n    // Close the polygon\n    if (poly.vertices.size() >= 3) {\n        int dx = poly.vertices.back().x - poly.vertices[0].x;\n        int dy = poly.vertices.back().y - poly.vertices[0].y;\n        if (dx != 0 && dy != 0) {\n            if (abs(dx) > abs(dy)) {\n                poly.vertices.emplace_back(poly.vertices.back().x, poly.vertices[0].y);\n            } else {\n                poly.vertices.emplace_back(poly.vertices[0].x, poly.vertices.back().y);\n            }\n        }\n    }\n\n    return poly;\n}\n\nint evaluate_polygon(const Polygon &poly, const vector<Point> &mackerels, const vector<Point> &sardines) {\n    int m = count_points_in_polygon(mackerels, poly);\n    int s = count_points_in_polygon(sardines, poly);\n    return max(0, m - s + 1);\n}\n\nPolygon simulated_annealing(const vector<Point> &hull, const vector<Point> &mackerels, const vector<Point> &sardines, int max_vertices, int max_edge_length, int iterations) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    Polygon current = generate_random_polygon(hull, max_vertices, max_edge_length);\n    current.mackerels = count_points_in_polygon(mackerels, current);\n    current.sardines = count_points_in_polygon(sardines, current);\n    int current_score = evaluate_polygon(current, mackerels, sardines);\n\n    Polygon best = current;\n    int best_score = current_score;\n\n    double temperature = 1.0;\n    double cooling_rate = 0.999;\n\n    for (int i = 0; i < iterations; ++i) {\n        Polygon neighbor = generate_random_polygon(hull, max_vertices, max_edge_length);\n        neighbor.mackerels = count_points_in_polygon(mackerels, neighbor);\n        neighbor.sardines = count_points_in_polygon(sardines, neighbor);\n        int neighbor_score = evaluate_polygon(neighbor, mackerels, sardines);\n\n        if (neighbor_score > current_score || dis(gen) < exp((neighbor_score - current_score) / temperature)) {\n            current = neighbor;\n            current_score = neighbor_score;\n        }\n\n        if (current_score > best_score) {\n            best = current;\n            best_score = current_score;\n        }\n\n        temperature *= cooling_rate;\n    }\n\n    return best;\n}\n\nint main() {\n    int N;\n    cin >> N;\n\n    vector<Point> mackerels;\n    vector<Point> sardines;\n    vector<Point> all_points;\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        mackerels.emplace_back(x, y);\n        all_points.emplace_back(x, y);\n    }\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        sardines.emplace_back(x, y);\n        all_points.emplace_back(x, y);\n    }\n\n    vector<Point> hull = convex_hull(all_points);\n    int max_vertices = 1000;\n    int max_edge_length = 400000;\n    int iterations = 10000;\n\n    Polygon best_polygon = simulated_annealing(hull, mackerels, sardines, max_vertices, max_edge_length, iterations);\n\n    cout << best_polygon.vertices.size() << endl;\n    for (const auto &p : best_polygon.vertices) {\n        cout << p.x << \" \" << p.y << endl;\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <limits>\n#include <chrono>\n\nusing namespace std;\n\nstruct Rectangle {\n    int w, h;\n    int w_prime, h_prime;\n};\n\nstruct Placement {\n    int p; // index of the rectangle\n    int r; // rotation (0 or 1)\n    char d; // direction ('U' or 'L')\n    int b; // reference rectangle index or -1\n};\n\nstruct Solution {\n    vector<Placement> placements;\n    int width, height;\n    int score;\n};\n\nclass RectanglePacker {\nprivate:\n    int N, T, sigma;\n    vector<Rectangle> rectangles;\n    mt19937 rng;\n    uniform_real_distribution<double> dist;\n\n    Solution generateInitialSolution() {\n        Solution solution;\n        vector<int> indices(N);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), rng);\n\n        for (int i = 0; i < N; ++i) {\n            int p = indices[i];\n            int r = uniform_int_distribution<int>(0, 1)(rng);\n            char d = uniform_int_distribution<int>(0, 1)(rng) ? 'U' : 'L';\n            int b = i == 0 ? -1 : uniform_int_distribution<int>(-1, i - 1)(rng);\n            solution.placements.push_back({p, r, d, b});\n        }\n\n        return solution;\n    }\n\n    Solution placeRectangles(const Solution& solution) {\n        Solution result = solution;\n        vector<pair<int, int>> positions(N, {-1, -1});\n        int max_x = 0, max_y = 0;\n\n        for (const auto& placement : solution.placements) {\n            int p = placement.p;\n            int r = placement.r;\n            char d = placement.d;\n            int b = placement.b;\n\n            int w = r == 0 ? rectangles[p].w_prime : rectangles[p].h_prime;\n            int h = r == 0 ? rectangles[p].h_prime : rectangles[p].w_prime;\n\n            int x, y;\n            if (d == 'U') {\n                if (b == -1) {\n                    x = 0;\n                } else {\n                    x = positions[b].first + (r == 0 ? rectangles[b].w_prime : rectangles[b].h_prime);\n                }\n                y = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (positions[i].first != -1 && positions[i].first < x + w && positions[i].first + (r == 0 ? rectangles[i].w_prime : rectangles[i].h_prime) > x) {\n                        y = max(y, positions[i].second + (r == 0 ? rectangles[i].h_prime : rectangles[i].w_prime));\n                    }\n                }\n            } else { // d == 'L'\n                if (b == -1) {\n                    y = 0;\n                } else {\n                    y = positions[b].second + (r == 0 ? rectangles[b].h_prime : rectangles[b].w_prime);\n                }\n                x = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (positions[i].second != -1 && positions[i].second < y + h && positions[i].second + (r == 0 ? rectangles[i].h_prime : rectangles[i].w_prime) > y) {\n                        x = max(x, positions[i].first + (r == 0 ? rectangles[i].w_prime : rectangles[i].h_prime));\n                    }\n                }\n            }\n\n            positions[p] = {x, y};\n            max_x = max(max_x, x + w);\n            max_y = max(max_y, y + h);\n        }\n\n        result.width = max_x;\n        result.height = max_y;\n        result.score = max_x + max_y;\n\n        return result;\n    }\n\n    Solution mutateSolution(const Solution& solution) {\n        Solution new_solution = solution;\n        int mutation_type = uniform_int_distribution<int>(0, 2)(rng);\n\n        if (mutation_type == 0) { // Change rotation\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            new_solution.placements[idx].r = 1 - new_solution.placements[idx].r;\n        } else if (mutation_type == 1) { // Change direction\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            new_solution.placements[idx].d = new_solution.placements[idx].d == 'U' ? 'L' : 'U';\n        } else { // Change reference\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            int b = idx == 0 ? -1 : uniform_int_distribution<int>(-1, idx - 1)(rng);\n            new_solution.placements[idx].b = b;\n        }\n\n        return new_solution;\n    }\n\n    Solution simulatedAnnealing() {\n        Solution current_solution = generateInitialSolution();\n        current_solution = placeRectangles(current_solution);\n        Solution best_solution = current_solution;\n\n        double temperature = 1000.0;\n        double cooling_rate = 0.99;\n        int iterations = 1000;\n\n        for (int i = 0; i < iterations; ++i) {\n            Solution new_solution = mutateSolution(current_solution);\n            new_solution = placeRectangles(new_solution);\n\n            double delta = new_solution.score - current_solution.score;\n            if (delta < 0 || exp(-delta / temperature) > dist(rng)) {\n                current_solution = new_solution;\n                if (new_solution.score < best_solution.score) {\n                    best_solution = new_solution;\n                }\n            }\n\n            temperature *= cooling_rate;\n        }\n\n        return best_solution;\n    }\n\npublic:\n    RectanglePacker(int N, int T, int sigma, const vector<Rectangle>& rectangles)\n        : N(N), T(T), sigma(sigma), rectangles(rectangles), rng(chrono::steady_clock::now().time_since_epoch().count()), dist(0.0, 1.0) {}\n\n    Solution findBestSolution() {\n        Solution best_solution;\n        best_solution.score = numeric_limits<int>::max();\n\n        for (int t = 0; t < T; ++t) {\n            Solution solution = simulatedAnnealing();\n            if (solution.score < best_solution.score) {\n                best_solution = solution;\n            }\n        }\n\n        return best_solution;\n    }\n};\n\nint main() {\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n\n    vector<Rectangle> rectangles(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> rectangles[i].w_prime >> rectangles[i].h_prime;\n    }\n\n    RectanglePacker packer(N, T, sigma, rectangles);\n    Solution best_solution = packer.findBestSolution();\n\n    cout << best_solution.placements.size() << endl;\n    for (const auto& placement : best_solution.placements) {\n        cout << placement.p << \" \" << placement.r << \" \" << placement.d << \" \" << placement.b << endl;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_set>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n};\n\nstruct Vertex {\n    int id;\n    int beauty;\n    vector<int> neighbors;\n};\n\nstruct Tree {\n    int root;\n    vector<int> parent;\n    vector<int> height;\n};\n\nint N, M, H;\nvector<Vertex> vertices;\nvector<Edge> edges;\nvector<int> x, y;\n\nvoid input() {\n    cin >> N >> M >> H;\n    vertices.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> vertices[i].beauty;\n        vertices[i].id = i;\n    }\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        vertices[edges[i].u].neighbors.push_back(edges[i].v);\n        vertices[edges[i].v].neighbors.push_back(edges[i].u);\n    }\n    x.resize(N);\n    y.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> x[i] >> y[i];\n    }\n}\n\nvector<int> solve() {\n    vector<int> parent(N, -1);\n    vector<bool> visited(N, false);\n    priority_queue<pair<int, int>> pq; // (beauty, id)\n\n    for (int i = 0; i < N; ++i) {\n        pq.push({vertices[i].beauty, i});\n    }\n\n    while (!pq.empty()) {\n        auto current = pq.top();\n        pq.pop();\n        int u = current.second;\n\n        if (visited[u]) continue;\n        visited[u] = true;\n\n        queue<pair<int, int>> q; // (vertex, parent)\n        q.push({u, -1});\n        int current_height = 0;\n\n        while (!q.empty() && current_height <= H) {\n            int size = q.size();\n            for (int i = 0; i < size; ++i) {\n                auto front = q.front();\n                q.pop();\n                int v = front.first;\n                int p = front.second;\n\n                if (visited[v]) continue;\n                visited[v] = true;\n                parent[v] = p;\n\n                for (int neighbor : vertices[v].neighbors) {\n                    if (!visited[neighbor]) {\n                        q.push({neighbor, v});\n                    }\n                }\n            }\n            current_height++;\n        }\n    }\n\n    return parent;\n}\n\nint main() {\n    input();\n    auto parent = solve();\n    for (int p : parent) {\n        cout << p << \" \";\n    }\n    cout << endl;\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cassert>\n\nusing namespace std;\n\nstruct Move {\n    char direction;\n    int index;\n};\n\nvector<Move> solve(const vector<string>& board) {\n    int N = board.size();\n    vector<Move> moves;\n    vector<vector<char>> current_board(N, vector<char>(N));\n\n    // Convert the input board to a 2D vector of characters\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            current_board[i][j] = board[i][j];\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (current_board[i][j] == 'x') {\n                // Check if we can remove the Oni by shifting the row left\n                bool can_remove_left = true;\n                for (int k = 0; k < i; ++k) {\n                    if (current_board[k][j] == 'o') {\n                        can_remove_left = false;\n                        break;\n                    }\n                }\n                if (can_remove_left) {\n                    // Shift the row left to remove the Oni\n                    for (int k = 0; k <= i; ++k) {\n                        moves.push_back({'L', i});\n                    }\n                    for (int k = 0; k <= i; ++k) {\n                        moves.push_back({'R', i});\n                    }\n                    // Update the board state\n                    for (int k = 0; k < N - 1; ++k) {\n                        current_board[i][k] = current_board[i][k + 1];\n                    }\n                    current_board[i][N - 1] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the row right\n                bool can_remove_right = true;\n                for (int k = i + 1; k < N; ++k) {\n                    if (current_board[k][j] == 'o') {\n                        can_remove_right = false;\n                        break;\n                    }\n                }\n                if (can_remove_right) {\n                    // Shift the row right to remove the Oni\n                    for (int k = 0; k <= N - 1 - i; ++k) {\n                        moves.push_back({'R', i});\n                    }\n                    for (int k = 0; k <= N - 1 - i; ++k) {\n                        moves.push_back({'L', i});\n                    }\n                    // Update the board state\n                    for (int k = N - 1; k > 0; --k) {\n                        current_board[i][k] = current_board[i][k - 1];\n                    }\n                    current_board[i][0] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the column up\n                bool can_remove_up = true;\n                for (int k = 0; k < j; ++k) {\n                    if (current_board[i][k] == 'o') {\n                        can_remove_up = false;\n                        break;\n                    }\n                }\n                if (can_remove_up) {\n                    // Shift the column up to remove the Oni\n                    for (int k = 0; k <= j; ++k) {\n                        moves.push_back({'U', j});\n                    }\n                    for (int k = 0; k <= j; ++k) {\n                        moves.push_back({'D', j});\n                    }\n                    // Update the board state\n                    for (int k = 0; k < N - 1; ++k) {\n                        current_board[k][j] = current_board[k + 1][j];\n                    }\n                    current_board[N - 1][j] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the column down\n                bool can_remove_down = true;\n                for (int k = j + 1; k < N; ++k) {\n                    if (current_board[i][k] == 'o') {\n                        can_remove_down = false;\n                        break;\n                    }\n                }\n                if (can_remove_down) {\n                    // Shift the column down to remove the Oni\n                    for (int k = 0; k <= N - 1 - j; ++k) {\n                        moves.push_back({'D', j});\n                    }\n                    for (int k = 0; k <= N - 1 - j; ++k) {\n                        moves.push_back({'U', j});\n                    }\n                    // Update the board state\n                    for (int k = N - 1; k > 0; --k) {\n                        current_board[k][j] = current_board[k - 1][j];\n                    }\n                    current_board[0][j] = '.';\n                }\n            }\n        }\n    }\n\n    return moves;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n    }\n\n    vector<Move> moves = solve(board);\n\n    for (const auto& move : moves) {\n        cout << move.direction << \" \" << move.index << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nstruct Employee {\n    int a;\n    int b;\n};\n\nvector<int> simulate_cleaning_plan(const vector<Employee>& employees, int L) {\n    vector<int> actual(employees.size(), 0);\n    unordered_map<int, int> cycle_counts;\n    vector<bool> visited(employees.size(), false);\n    vector<int> path;\n\n    for (int i = 0; i < employees.size(); ++i) {\n        if (!visited[i]) {\n            int current = i;\n            path.clear();\n            while (!visited[current]) {\n                visited[current] = true;\n                path.push_back(current);\n                int t = count(actual.begin(), actual.end(), current);\n                if (t % 2 == 1) {\n                    current = employees[current].a;\n                } else {\n                    current = employees[current].b;\n                }\n            }\n\n            // Check if the current path is a cycle\n            auto it = find(path.begin(), path.end(), current);\n            if (it != path.end()) {\n                int cycle_length = distance(it, path.end());\n                int cycle_start = distance(path.begin(), it);\n                int cycle_repeats = (L - cycle_start) / cycle_length;\n                int remaining = (L - cycle_start) % cycle_length;\n\n                for (int j = cycle_start; j < path.size(); ++j) {\n                    actual[path[j]] += cycle_repeats;\n                }\n                for (int j = 0; j < remaining; ++j) {\n                    actual[path[cycle_start + j]]++;\n                }\n            } else {\n                for (int j = 0; j < path.size(); ++j) {\n                    actual[path[j]]++;\n                }\n            }\n        }\n    }\n\n    return actual;\n}\n\nint calculate_error(const vector<int>& actual, const vector<int>& target) {\n    int error = 0;\n    for (size_t i = 0; i < actual.size(); ++i) {\n        error += abs(actual[i] - target[i]);\n    }\n    return error;\n}\n\nvector<Employee> generate_initial_state(int N) {\n    vector<Employee> employees(N);\n    for (int i = 0; i < N; ++i) {\n        employees[i].a = i;\n        employees[i].b = i;\n    }\n    return employees;\n}\n\nvector<Employee> hill_climbing(const vector<int>& target, int N, int L, int iterations) {\n    vector<Employee> current_employees = generate_initial_state(N);\n    vector<int> current_actual = simulate_cleaning_plan(current_employees, L);\n    int current_error = calculate_error(current_actual, target);\n\n    for (int i = 0; i < iterations; ++i) {\n        vector<Employee> new_employees = current_employees;\n        int employee = rand() % N;\n        int choice = rand() % 2;\n\n        if (choice == 0) {\n            new_employees[employee].a = rand() % N;\n        } else {\n            new_employees[employee].b = rand() % N;\n        }\n\n        vector<int> new_actual = simulate_cleaning_plan(new_employees, L);\n        int new_error = calculate_error(new_actual, target);\n\n        if (new_error < current_error) {\n            current_employees = new_employees;\n            current_error = new_error;\n        }\n    }\n\n    return current_employees;\n}\n\nint main() {\n    int N, L;\n    cin >> N >> L;\n\n    vector<int> target(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> target[i];\n    }\n\n    int iterations = 10000;\n    vector<Employee> best_employees = hill_climbing(target, N, L, iterations);\n\n    for (const auto& employee : best_employees) {\n        cout << employee.a << \" \" << employee.b << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <limits>\n#include <functional>\n\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double cx, cy; // Center coordinates\n};\n\nstruct Edge {\n    int u, v;\n    double distance;\n};\n\nstruct CompareEdge {\n    bool operator()(const Edge& a, const Edge& b) {\n        return a.distance > b.distance;\n    }\n};\n\nvector<Edge> query(const vector<int>& cities) {\n    cout << \"? \" << cities.size();\n    for (int city : cities) {\n        cout << \" \" << city;\n    }\n    cout << endl;\n    cout.flush();\n\n    vector<Edge> edges;\n    for (size_t i = 0; i < cities.size() - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        edges.push_back({u, v, 0.0}); // Distance will be calculated later\n    }\n    return edges;\n}\n\nvoid answer(const vector<vector<int>>& groups, const vector<vector<Edge>>& edges) {\n    cout << \"!\" << endl;\n    for (size_t i = 0; i < groups.size(); ++i) {\n        for (int city : groups[i]) {\n            cout << city << \" \";\n        }\n        cout << endl;\n        for (const Edge& edge : edges[i]) {\n            cout << edge.u << \" \" << edge.v << endl;\n        }\n    }\n}\n\nvector<vector<int>> greedyGrouping(const vector<City>& cities, const vector<int>& G) {\n    vector<City> sortedCities = cities;\n    sort(sortedCities.begin(), sortedCities.end(), [](const City& a, const City& b) {\n        return a.cx < b.cx || (a.cx == b.cx && a.cy < b.cy);\n    });\n\n    vector<vector<int>> groups;\n    size_t startIdx = 0;\n    for (int g : G) {\n        vector<int> group;\n        for (size_t i = startIdx; i < startIdx + g; ++i) {\n            group.push_back(sortedCities[i].id);\n        }\n        groups.push_back(group);\n        startIdx += g;\n    }\n    return groups;\n}\n\nvector<Edge> calculateMST(const vector<int>& group, const vector<City>& cities) {\n    unordered_map<int, int> cityToIndex;\n    for (size_t i = 0; i < cities.size(); ++i) {\n        cityToIndex[cities[i].id] = i;\n    }\n\n    vector<vector<double>> dist(group.size(), vector<double>(group.size(), 0.0));\n    for (size_t i = 0; i < group.size(); ++i) {\n        for (size_t j = i + 1; j < group.size(); ++j) {\n            const City& a = cities[cityToIndex[group[i]]];\n            const City& b = cities[cityToIndex[group[j]]];\n            double dx = a.cx - b.cx;\n            double dy = a.cy - b.cy;\n            dist[i][j] = dist[j][i] = sqrt(dx * dx + dy * dy);\n        }\n    }\n\n    priority_queue<Edge, vector<Edge>, CompareEdge> pq;\n    for (size_t i = 0; i < group.size(); ++i) {\n        for (size_t j = i + 1; j < group.size(); ++j) {\n            pq.push({group[i], group[j], dist[i][j]});\n        }\n    }\n\n    vector<Edge> mstEdges;\n    vector<int> parent(group.size(), -1);\n    vector<int> rank(group.size(), 0);\n\n    function<int(int)> find = [&](int u) {\n        if (parent[u] == -1) return u;\n        return parent[u] = find(parent[u]);\n    };\n\n    while (!pq.empty() && mstEdges.size() < group.size() - 1) {\n        Edge edge = pq.top();\n        pq.pop();\n        int u = find(edge.u);\n        int v = find(edge.v);\n        if (u != v) {\n            mstEdges.push_back(edge);\n            if (rank[u] > rank[v]) {\n                parent[v] = u;\n            } else {\n                parent[u] = v;\n                if (rank[u] == rank[v]) {\n                    rank[v]++;\n                }\n            }\n        }\n    }\n    return mstEdges;\n}\n\nint main() {\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> G[i];\n    }\n\n    vector<City> cities(N);\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cities[i] = {i, lx, rx, ly, ry, (lx + rx) / 2.0, (ly + ry) / 2.0};\n    }\n\n    vector<vector<int>> groups = greedyGrouping(cities, G);\n    vector<vector<Edge>> edges(M);\n\n    for (int k = 0; k < M; ++k) {\n        for (size_t i = 0; i < groups[k].size() - 1; i += 2) {\n            if (i < groups[k].size() - 2) {\n                vector<int> queryCities = {groups[k][i], groups[k][i + 1], groups[k][i + 2]};\n                vector<Edge> queryEdges = query(queryCities);\n                edges[k].insert(edges[k].end(), queryEdges.begin(), queryEdges.end());\n            } else {\n                edges[k].push_back({groups[k][i], groups[k][i + 1], 0.0});\n            }\n        }\n    }\n\n    answer(groups, edges);\n\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 20;\nconst int M = 40;\nconst int MAX_ACTIONS = 2 * N * M;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct State {\n    Point pos;\n    unordered_set<Point> blocks;\n    int visited;\n    int actions;\n    State(Point pos, unordered_set<Point> blocks, int visited, int actions)\n        : pos(pos), blocks(blocks), visited(visited), actions(actions) {}\n};\n\nstruct Action {\n    char type;\n    char direction;\n    Action(char type, char direction) : type(type), direction(direction) {}\n};\n\nvector<Action> directions = {\n    {'U', 'U'}, {'D', 'D'}, {'L', 'L'}, {'R', 'R'}\n};\n\nvector<Action> actions = {\n    {'M', 'U'}, {'M', 'D'}, {'M', 'L'}, {'M', 'R'},\n    {'S', 'U'}, {'S', 'D'}, {'S', 'L'}, {'S', 'R'},\n    {'A', 'U'}, {'A', 'D'}, {'A', 'L'}, {'A', 'R'}\n};\n\nbool isValid(Point p) {\n    return p.x >= 0 && p.x < N && p.y >= 0 && p.y < N;\n}\n\nPoint move(Point p, char direction) {\n    switch (direction) {\n        case 'U': return Point(p.x - 1, p.y);\n        case 'D': return Point(p.x + 1, p.y);\n        case 'L': return Point(p.x, p.y - 1);\n        case 'R': return Point(p.x, p.y + 1);\n    }\n    return p;\n}\n\nPoint slide(Point p, char direction, const unordered_set<Point>& blocks) {\n    Point next = p;\n    while (true) {\n        Point newPos = move(next, direction);\n        if (!isValid(newPos) || blocks.count(newPos)) break;\n        next = newPos;\n    }\n    return next;\n}\n\nunordered_set<Point> alter(Point p, char direction, unordered_set<Point> blocks) {\n    Point target = move(p, direction);\n    if (isValid(target)) {\n        if (blocks.count(target)) {\n            blocks.erase(target);\n        } else {\n            blocks.insert(target);\n        }\n    }\n    return blocks;\n}\n\nint heuristic(Point a, Point b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvector<Action> solve(vector<Point> targets) {\n    vector<Action> result;\n    unordered_set<Point> blocks;\n    Point current = targets[0];\n    int visited = 0;\n\n    for (int i = 1; i < targets.size(); ++i) {\n        Point target = targets[i];\n        priority_queue<pair<int, State>, vector<pair<int, State>>, greater<pair<int, State>>> pq;\n        unordered_set<Point> initialBlocks = blocks;\n        pq.push({heuristic(current, target), State(current, initialBlocks, visited, 0)});\n\n        while (!pq.empty()) {\n            auto [cost, state] = pq.top();\n            pq.pop();\n\n            if (state.pos == target) {\n                current = target;\n                visited = i;\n                blocks = state.blocks;\n                break;\n            }\n\n            if (state.actions >= MAX_ACTIONS) continue;\n\n            for (auto& action : actions) {\n                Point newPos = state.pos;\n                unordered_set<Point> newBlocks = state.blocks;\n                int newVisited = state.visited;\n                int newActions = state.actions + 1;\n\n                if (action.type == 'M') {\n                    newPos = move(state.pos, action.direction);\n                    if (!isValid(newPos) || newBlocks.count(newPos)) continue;\n                } else if (action.type == 'S') {\n                    newPos = slide(state.pos, action.direction, newBlocks);\n                } else if (action.type == 'A') {\n                    newBlocks = alter(state.pos, action.direction, newBlocks);\n                }\n\n                if (newPos == target) newVisited = i;\n\n                int newCost = newActions + heuristic(newPos, target);\n                pq.push({newCost, State(newPos, newBlocks, newVisited, newActions)});\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<Point> targets;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        targets.emplace_back(x, y);\n    }\n\n    vector<Action> result = solve(targets);\n    for (auto& action : result) {\n        cout << action.type << \" \" << action.direction << endl;\n    }\n\n    return 0;\n}"},"16":{"ahc001":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nstruct Rectangle {\n    int a, b, c, d; // Coordinates of the rectangle\n    int area;       // Area of the rectangle\n};\n\nstruct Company {\n    int x, y;       // Desired location\n    int r;          // Desired area\n};\n\ndouble satisfaction_level(const Rectangle& rect, const Company& company) {\n    if (rect.a > company.x || rect.c <= company.x || rect.b > company.y || rect.d <= company.y) {\n        return 0.0;\n    }\n    double s_i = rect.area;\n    double r_i = company.r;\n    double min_val = min(r_i, s_i);\n    double max_val = max(r_i, s_i);\n    double p_i = 1.0 - pow(1.0 - min_val / max_val, 2.0);\n    return p_i;\n}\n\nbool is_overlapping(const Rectangle& rect1, const Rectangle& rect2) {\n    return !(rect1.c <= rect2.a || rect2.c <= rect1.a || rect1.d <= rect2.b || rect2.d <= rect1.b);\n}\n\nvector<Rectangle> generate_initial_solution(const vector<Company>& companies) {\n    vector<Rectangle> rectangles;\n    for (const auto& company : companies) {\n        int width = static_cast<int>(sqrt(company.r));\n        int height = company.r / width;\n        if (width * height < company.r) {\n            height++;\n        }\n        int a = max(0, company.x - width / 2);\n        int b = max(0, company.y - height / 2);\n        int c = min(10000, a + width);\n        int d = min(10000, b + height);\n        Rectangle rect = {a, b, c, d, (c - a) * (d - b)};\n        rectangles.push_back(rect);\n    }\n    return rectangles;\n}\n\ndouble total_satisfaction(const vector<Rectangle>& rectangles, const vector<Company>& companies) {\n    double total = 0.0;\n    for (size_t i = 0; i < companies.size(); ++i) {\n        total += satisfaction_level(rectangles[i], companies[i]);\n    }\n    return total;\n}\n\nvector<Rectangle> simulated_annealing(const vector<Company>& companies, vector<Rectangle> initial_rectangles, double initial_temp, double cooling_rate, int iterations) {\n    vector<Rectangle> current_rectangles = initial_rectangles;\n    double current_satisfaction = total_satisfaction(current_rectangles, companies);\n    vector<Rectangle> best_rectangles = current_rectangles;\n    double best_satisfaction = current_satisfaction;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    for (double temp = initial_temp; temp > 1e-6; temp *= cooling_rate) {\n        for (int i = 0; i < iterations; ++i) {\n            vector<Rectangle> new_rectangles = current_rectangles;\n            int idx = dis(gen) * companies.size();\n            int delta_x = (dis(gen) * 2 - 1) * 10;\n            int delta_y = (dis(gen) * 2 - 1) * 10;\n            new_rectangles[idx].a = max(0, new_rectangles[idx].a + delta_x);\n            new_rectangles[idx].b = max(0, new_rectangles[idx].b + delta_y);\n            new_rectangles[idx].c = min(10000, new_rectangles[idx].c + delta_x);\n            new_rectangles[idx].d = min(10000, new_rectangles[idx].d + delta_y);\n            new_rectangles[idx].area = (new_rectangles[idx].c - new_rectangles[idx].a) * (new_rectangles[idx].d - new_rectangles[idx].b);\n\n            bool valid = true;\n            for (size_t j = 0; j < new_rectangles.size(); ++j) {\n                if (j != idx && is_overlapping(new_rectangles[idx], new_rectangles[j])) {\n                    valid = false;\n                    break;\n                }\n            }\n\n            if (valid) {\n                double new_satisfaction = total_satisfaction(new_rectangles, companies);\n                double delta = new_satisfaction - current_satisfaction;\n                if (delta > 0 || dis(gen) < exp(delta / temp)) {\n                    current_rectangles = new_rectangles;\n                    current_satisfaction = new_satisfaction;\n                    if (current_satisfaction > best_satisfaction) {\n                        best_rectangles = current_rectangles;\n                        best_satisfaction = current_satisfaction;\n                    }\n                }\n            }\n        }\n    }\n    return best_rectangles;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector<Company> companies(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n\n    vector<Rectangle> initial_rectangles = generate_initial_solution(companies);\n    vector<Rectangle> best_rectangles = simulated_annealing(companies, initial_rectangles, 1000.0, 0.99, 1000);\n\n    for (const auto& rect : best_rectangles) {\n        cout << rect.a << \" \" << rect.b << \" \" << rect.c << \" \" << rect.d << endl;\n    }\n\n    return 0;\n}","ahc002":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <unordered_set>\n#include <queue>\n#include <utility>\n#include <unordered_map>\n\nusing namespace std;\n\nconst int SIZE = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\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\nbool is_valid(int x, int y) {\n    return x >= 0 && x < SIZE && y >= 0 && y < SIZE;\n}\n\nint heuristic(int x, int y, const vector<vector<int>>& points) {\n    int max_score = 0;\n    for (int i = max(0, x - 2); i < min(SIZE, x + 3); ++i) {\n        for (int j = max(0, y - 2); j < min(SIZE, y + 3); ++j) {\n            max_score = max(max_score, points[i][j]);\n        }\n    }\n    return max_score;\n}\n\nstruct CompareState {\n    bool operator()(const pair<int, State>& a, const pair<int, State>& b) {\n        return a.first < b.first;\n    }\n};\n\nstring find_max_score_path(int si, int sj, const vector<vector<int>>& tiles, const vector<vector<int>>& points) {\n    unordered_set<int> initial_visited_tiles;\n    initial_visited_tiles.insert(tiles[si][sj]);\n    priority_queue<pair<int, State>, vector<pair<int, State>>, CompareState> pq;\n    pq.emplace(points[si][sj] + heuristic(si, sj, points), State(si, sj, points[si][sj], \"\", initial_visited_tiles));\n\n    unordered_map<int, unordered_map<int, int>> best_scores;\n    best_scores[si][sj] = points[si][sj];\n\n    int max_score = points[si][sj];\n    string best_path;\n\n    while (!pq.empty()) {\n        auto [current_priority, current] = pq.top();\n        pq.pop();\n\n        if (current.score > max_score) {\n            max_score = current.score;\n            best_path = current.path;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = current.x + dx[i];\n            int ny = current.y + dy[i];\n\n            if (is_valid(nx, ny) && current.visited_tiles.find(tiles[nx][ny]) == current.visited_tiles.end()) {\n                int new_score = current.score + points[nx][ny];\n                if (best_scores[nx][ny] < new_score) {\n                    best_scores[nx][ny] = new_score;\n                    unordered_set<int> new_visited_tiles = current.visited_tiles;\n                    new_visited_tiles.insert(tiles[nx][ny]);\n                    pq.emplace(new_score + heuristic(nx, ny, points), State(nx, ny, new_score, current.path + dir[i], new_visited_tiles));\n                }\n            }\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<vector<int>> tiles(SIZE, vector<int>(SIZE));\n    for (int i = 0; i < SIZE; ++i) {\n        for (int j = 0; j < SIZE; ++j) {\n            cin >> tiles[i][j];\n        }\n    }\n\n    vector<vector<int>> points(SIZE, vector<int>(SIZE));\n    for (int i = 0; i < SIZE; ++i) {\n        for (int j = 0; j < SIZE; ++j) {\n            cin >> points[i][j];\n        }\n    }\n\n    string path = find_max_score_path(si, sj, tiles, points);\n    cout << path << endl;\n\n    return 0;\n}","ahc003":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <random>\n#include <unordered_map>\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int QUERY_COUNT = 1000;\nconst double DECAY_FACTOR = 0.998;\nconst double SCORE_MULTIPLIER = 2312311;\n\nstruct Vertex {\n    int i, j;\n    Vertex(int i, int j) : i(i), j(j) {}\n    bool operator==(const Vertex& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Vertex> {\n        size_t operator()(const Vertex& v) const {\n            return hash<int>()(v.i) ^ hash<int>()(v.j);\n        }\n    };\n}\n\nstruct Edge {\n    Vertex from, to;\n    double estimated_length;\n    Edge(Vertex from, Vertex to, double estimated_length) : from(from), to(to), estimated_length(estimated_length) {}\n};\n\nclass Graph {\nprivate:\n    vector<vector<Vertex>> vertices;\n    unordered_map<Vertex, vector<Edge>> edges;\n    unordered_map<Vertex, unordered_map<Vertex, double>> estimated_lengths;\n\npublic:\n    Graph() {\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            vector<Vertex> row;\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                row.emplace_back(i, j);\n            }\n            vertices.push_back(row);\n        }\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                Vertex from(i, j);\n                if (i > 0) {\n                    Vertex to(i - 1, j);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (i < GRID_SIZE - 1) {\n                    Vertex to(i + 1, j);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (j > 0) {\n                    Vertex to(i, j - 1);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n                if (j < GRID_SIZE - 1) {\n                    Vertex to(i, j + 1);\n                    edges[from].emplace_back(from, to, 1.0);\n                    estimated_lengths[from][to] = 1.0;\n                }\n            }\n        }\n    }\n\n    void update_estimated_lengths(const vector<Vertex>& path, double actual_length) {\n        double path_length = 0.0;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            path_length += estimated_lengths[path[k]][path[k + 1]];\n        }\n        double factor = actual_length / path_length;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            estimated_lengths[path[k]][path[k + 1]] *= factor;\n            estimated_lengths[path[k + 1]][path[k]] *= factor;\n        }\n    }\n\n    vector<Vertex> a_star_search(const Vertex& start, const Vertex& goal) {\n        auto heuristic = [&](const Vertex& v) {\n            return abs(v.i - goal.i) + abs(v.j - goal.j);\n        };\n\n        priority_queue<pair<double, Vertex>, vector<pair<double, Vertex>>, greater<pair<double, Vertex>>> open_set;\n        unordered_map<Vertex, Vertex> came_from;\n        unordered_map<Vertex, double> g_score;\n        unordered_map<Vertex, double> f_score;\n\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                Vertex v(i, j);\n                g_score[v] = numeric_limits<double>::infinity();\n                f_score[v] = numeric_limits<double>::infinity();\n            }\n        }\n\n        g_score[start] = 0.0;\n        f_score[start] = heuristic(start);\n        open_set.push({f_score[start], start});\n\n        while (!open_set.empty()) {\n            Vertex current = open_set.top().second;\n            open_set.pop();\n\n            if (current == goal) {\n                vector<Vertex> path;\n                while (came_from.find(current) != came_from.end()) {\n                    path.push_back(current);\n                    current = came_from[current];\n                }\n                path.push_back(start);\n                reverse(path.begin(), path.end());\n                return path;\n            }\n\n            for (const Edge& edge : edges[current]) {\n                Vertex neighbor = edge.to;\n                double tentative_g_score = g_score[current] + estimated_lengths[current][neighbor];\n\n                if (tentative_g_score < g_score[neighbor]) {\n                    came_from[neighbor] = current;\n                    g_score[neighbor] = tentative_g_score;\n                    f_score[neighbor] = g_score[neighbor] + heuristic(neighbor);\n                    open_set.push({f_score[neighbor], neighbor});\n                }\n            }\n        }\n\n        return {};\n    }\n\n    string path_to_string(const vector<Vertex>& path) {\n        stringstream ss;\n        for (size_t k = 0; k < path.size() - 1; ++k) {\n            Vertex from = path[k];\n            Vertex to = path[k + 1];\n            if (to.i == from.i - 1) {\n                ss << \"U\";\n            } else if (to.i == from.i + 1) {\n                ss << \"D\";\n            } else if (to.j == from.j - 1) {\n                ss << \"L\";\n            } else if (to.j == from.j + 1) {\n                ss << \"R\";\n            }\n        }\n        return ss.str();\n    }\n};\n\nint main() {\n    Graph graph;\n    double score = 0.0;\n    int prev_result = 0;\n\n    for (int k = 0; k < QUERY_COUNT; ++k) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        Vertex start(si, sj);\n        Vertex goal(ti, tj);\n\n        vector<Vertex> path = graph.a_star_search(start, goal);\n        string path_str = graph.path_to_string(path);\n        cout << path_str << endl;\n        cout.flush();\n\n        int actual_length;\n        cin >> actual_length;\n\n        graph.update_estimated_lengths(path, actual_length);\n\n        double path_length = 0.0;\n        for (size_t i = 0; i < path.size() - 1; ++i) {\n            path_length += graph.estimated_lengths[path[i]][path[i + 1]];\n        }\n\n        double ratio = actual_length / path_length;\n        score = score * DECAY_FACTOR + ratio;\n    }\n\n    cout << round(SCORE_MULTIPLIER * score) << endl;\n    return 0;\n}","ahc004":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <unordered_set>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int N = 20;\nconst int ALPHABET_SIZE = 8;\nconst char ALPHABET[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};\nconst char EMPTY = '.';\n\nstruct Matrix {\n    vector<vector<char>> data;\n\n    Matrix() : data(N, vector<char>(N, EMPTY)) {}\n\n    void randomize() {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, ALPHABET_SIZE - 1);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                data[i][j] = ALPHABET[dis(gen)];\n            }\n        }\n    }\n\n    void mutate(double rate) {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_real_distribution<> prob(0.0, 1.0);\n        uniform_int_distribution<> dis(0, ALPHABET_SIZE - 1);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (prob(gen) < rate) {\n                    data[i][j] = ALPHABET[dis(gen)];\n                }\n            }\n        }\n    }\n\n    bool is_subsequence(const string& s) {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                // Check horizontal subsequence\n                bool match = true;\n                for (int k = 0; k < s.size(); ++k) {\n                    if (data[i][(j + k) % N] != s[k]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) return true;\n\n                // Check vertical subsequence\n                match = true;\n                for (int k = 0; k < s.size(); ++k) {\n                    if (data[(i + k) % N][j] != s[k]) {\n                        match = false;\n                        break;\n                    }\n                }\n                if (match) return true;\n            }\n        }\n        return false;\n    }\n\n    int count_subsequences(const vector<string>& strings) {\n        int count = 0;\n        for (const auto& s : strings) {\n            if (is_subsequence(s)) {\n                count++;\n            }\n        }\n        return count;\n    }\n\n    int count_empty() {\n        int count = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (data[i][j] == EMPTY) {\n                    count++;\n                }\n            }\n        }\n        return count;\n    }\n\n    void print() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                cout << data[i][j];\n            }\n            cout << endl;\n        }\n    }\n};\n\ndouble evaluate(const Matrix& matrix, const vector<string>& strings) {\n    int c = matrix.count_subsequences(strings);\n    if (c < strings.size()) {\n        return static_cast<double>(c) / strings.size();\n    } else {\n        int d = matrix.count_empty();\n        return static_cast<double>(2 * N * N) / (2 * N * N - d);\n    }\n}\n\nMatrix genetic_algorithm(const vector<string>& strings, int population_size, int generations, double mutation_rate) {\n    random_device rd;\n    mt19937 gen(rd());\n    vector<Matrix> population(population_size);\n\n    for (auto& matrix : population) {\n        matrix.randomize();\n    }\n\n    for (int gen = 0; gen < generations; ++gen) {\n        vector<double> fitness(population_size);\n        for (int i = 0; i < population_size; ++i) {\n            fitness[i] = evaluate(population[i], strings);\n        }\n\n        vector<Matrix> new_population;\n        for (int i = 0; i < population_size; ++i) {\n            uniform_int_distribution<> dis(0, population_size - 1);\n            int parent1 = dis(gen);\n            int parent2 = dis(gen);\n\n            Matrix child;\n            for (int x = 0; x < N; ++x) {\n                for (int y = 0; y < N; ++y) {\n                    if (fitness[parent1] > fitness[parent2]) {\n                        child.data[x][y] = population[parent1].data[x][y];\n                    } else {\n                        child.data[x][y] = population[parent2].data[x][y];\n                    }\n                }\n            }\n\n            child.mutate(mutation_rate);\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n    }\n\n    auto best = max_element(population.begin(), population.end(), [&](const Matrix& a, const Matrix& b) {\n        return evaluate(a, strings) < evaluate(b, strings);\n    });\n\n    return *best;\n}\n\nMatrix simulated_annealing(const vector<string>& strings, double initial_temp, double cooling_rate, int iterations) {\n    Matrix current;\n    current.randomize();\n    double current_score = evaluate(current, strings);\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> prob(0.0, 1.0);\n\n    double temp = initial_temp;\n    for (int i = 0; i < iterations; ++i) {\n        Matrix neighbor = current;\n        neighbor.mutate(0.1);\n\n        double neighbor_score = evaluate(neighbor, strings);\n        double delta = neighbor_score - current_score;\n\n        if (delta > 0 || prob(gen) < exp(delta / temp)) {\n            current = neighbor;\n            current_score = neighbor_score;\n        }\n\n        temp *= cooling_rate;\n    }\n\n    return current;\n}\n\nint main() {\n    int M;\n    cin >> M;\n    vector<string> strings(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> strings[i];\n    }\n\n    // Run genetic algorithm\n    Matrix best_matrix = genetic_algorithm(strings, 50, 100, 0.01);\n\n    // Run simulated annealing\n    Matrix sa_matrix = simulated_annealing(strings, 1000.0, 0.99, 10000);\n\n    // Choose the best solution\n    if (evaluate(sa_matrix, strings) > evaluate(best_matrix, strings)) {\n        best_matrix = sa_matrix;\n    }\n\n    best_matrix.print();\n\n    return 0;\n}","ahc005":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int i, j;\n    Point(int i, int j) : i(i), j(j) {}\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.i) ^ hash<int>()(p.j);\n        }\n    };\n}\n\nclass PatrolRoute {\nprivate:\n    int N;\n    Point start;\n    vector<string> grid;\n    vector<vector<unordered_set<Point>>> visibility;\n    vector<Point> roadSquares;\n    vector<vector<int>> moveTime;\n    vector<vector<int>> dist;\n\n    void precomputeVisibility() {\n        visibility.resize(N, vector<unordered_set<Point>>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == '#') continue;\n                // Horizontal visibility\n                for (int k = j - 1; k >= 0; --k) {\n                    if (grid[i][k] == '#') break;\n                    visibility[i][j].insert(Point(i, k));\n                }\n                for (int k = j + 1; k < N; ++k) {\n                    if (grid[i][k] == '#') break;\n                    visibility[i][j].insert(Point(i, k));\n                }\n                // Vertical visibility\n                for (int k = i - 1; k >= 0; --k) {\n                    if (grid[k][j] == '#') break;\n                    visibility[i][j].insert(Point(k, j));\n                }\n                for (int k = i + 1; k < N; ++k) {\n                    if (grid[k][j] == '#') break;\n                    visibility[i][j].insert(Point(k, j));\n                }\n            }\n        }\n    }\n\n    void precomputeRoadSquares() {\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] != '#') {\n                    roadSquares.emplace_back(i, j);\n                }\n            }\n        }\n    }\n\n    void precomputeMoveTime() {\n        moveTime.resize(N, vector<int>(N, 0));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] != '#') {\n                    moveTime[i][j] = grid[i][j] - '0';\n                }\n            }\n        }\n    }\n\n    void precomputeDistances() {\n        dist.resize(N, vector<int>(N, -1));\n        queue<Point> q;\n        q.push(start);\n        dist[start.i][start.j] = 0;\n        while (!q.empty()) {\n            Point current = q.front();\n            q.pop();\n            for (const auto& neighbor : getNeighbors(current)) {\n                if (dist[neighbor.i][neighbor.j] == -1) {\n                    dist[neighbor.i][neighbor.j] = dist[current.i][current.j] + moveTime[neighbor.i][neighbor.j];\n                    q.push(neighbor);\n                }\n            }\n        }\n    }\n\n    vector<Point> getNeighbors(const Point& p) {\n        vector<Point> neighbors;\n        if (p.i > 0 && grid[p.i - 1][p.j] != '#') neighbors.emplace_back(p.i - 1, p.j);\n        if (p.i < N - 1 && grid[p.i + 1][p.j] != '#') neighbors.emplace_back(p.i + 1, p.j);\n        if (p.j > 0 && grid[p.i][p.j - 1] != '#') neighbors.emplace_back(p.i, p.j - 1);\n        if (p.j < N - 1 && grid[p.i][p.j + 1] != '#') neighbors.emplace_back(p.i, p.j + 1);\n        return neighbors;\n    }\n\n    vector<Point> greedyInitialization() {\n        unordered_set<Point> covered;\n        vector<Point> path;\n        Point current = start;\n        path.push_back(current);\n        covered.insert(visibility[current.i][current.j].begin(), visibility[current.i][current.j].end());\n        while (covered.size() < roadSquares.size()) {\n            Point next;\n            int maxNewCovered = -1;\n            for (const auto& neighbor : getNeighbors(current)) {\n                int newCovered = 0;\n                for (const auto& visible : visibility[neighbor.i][neighbor.j]) {\n                    if (covered.find(visible) == covered.end()) {\n                        newCovered++;\n                    }\n                }\n                if (newCovered > maxNewCovered) {\n                    maxNewCovered = newCovered;\n                    next = neighbor;\n                }\n            }\n            if (maxNewCovered == 0) break; // No progress, break to avoid infinite loop\n            current = next;\n            path.push_back(current);\n            covered.insert(visibility[current.i][current.j].begin(), visibility[current.i][current.j].end());\n        }\n        return path;\n    }\n\n    vector<Point> geneticAlgorithm(const vector<Point>& initialPath) {\n        vector<Point> bestPath = initialPath;\n        int bestScore = calculateScore(bestPath);\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(0, roadSquares.size() - 1);\n        for (int iter = 0; iter < 1000; ++iter) {\n            vector<Point> newPath = bestPath;\n            int a = dis(gen);\n            int b = dis(gen);\n            if (a > b) swap(a, b);\n            reverse(newPath.begin() + a, newPath.begin() + b);\n            int newScore = calculateScore(newPath);\n            if (newScore > bestScore) {\n                bestPath = newPath;\n                bestScore = newScore;\n            }\n        }\n        return bestPath;\n    }\n\n    int calculateScore(const vector<Point>& path) {\n        unordered_set<Point> covered;\n        for (const auto& point : path) {\n            covered.insert(visibility[point.i][point.j].begin(), visibility[point.i][point.j].end());\n        }\n        int v = covered.size();\n        int r = roadSquares.size();\n        if (v < r) {\n            return round(10000 * v / r);\n        } else {\n            int t = 0;\n            for (size_t i = 1; i < path.size(); ++i) {\n                t += moveTime[path[i].i][path[i].j];\n            }\n            return round(10000 + 10000000 * N / t);\n        }\n    }\n\npublic:\n    PatrolRoute(int N, int si, int sj, const vector<string>& grid) : N(N), start(si, sj), grid(grid) {\n        precomputeVisibility();\n        precomputeRoadSquares();\n        precomputeMoveTime();\n        precomputeDistances();\n    }\n\n    string findRoute() {\n        vector<Point> initialPath = greedyInitialization();\n        vector<Point> optimizedPath = geneticAlgorithm(initialPath);\n        string route;\n        for (size_t i = 1; i < optimizedPath.size(); ++i) {\n            Point prev = optimizedPath[i - 1];\n            Point curr = optimizedPath[i];\n            if (curr.i == prev.i - 1) route += 'U';\n            else if (curr.i == prev.i + 1) route += 'D';\n            else if (curr.j == prev.j - 1) route += 'L';\n            else if (curr.j == prev.j + 1) route += 'R';\n        }\n        return route;\n    }\n};\n\nint main() {\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n    PatrolRoute patrolRoute(N, si, sj, grid);\n    cout << patrolRoute.findRoute() << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <unordered_set>\n#include <queue>\n#include <cmath>\n\nusing namespace std;\n\nstruct Task {\n    vector<int> required_skills;\n    vector<int> dependencies;\n    int duration;\n    bool completed;\n};\n\nstruct TeamMember {\n    vector<int> skills;\n    int current_task;\n    int days_left;\n};\n\nvector<Task> tasks;\nvector<TeamMember> team_members;\nvector<vector<int>> task_dependencies;\nvector<int> in_degree;\nvector<int> completed_tasks;\nvector<int> available_tasks;\n\nvoid initialize(int N, int M, int K, int R) {\n    tasks.resize(N);\n    team_members.resize(M);\n    task_dependencies.resize(N);\n    in_degree.resize(N, 0);\n    completed_tasks.resize(N, 0);\n    available_tasks.resize(N, 0);\n\n    for (int i = 0; i < N; ++i) {\n        tasks[i].required_skills.resize(K);\n        tasks[i].dependencies.clear();\n        tasks[i].duration = 0;\n        tasks[i].completed = false;\n    }\n\n    for (int i = 0; i < M; ++i) {\n        team_members[i].skills.resize(K, 0);\n        team_members[i].current_task = -1;\n        team_members[i].days_left = 0;\n    }\n\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        task_dependencies[u - 1].push_back(v - 1);\n        in_degree[v - 1]++;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        if (in_degree[i] == 0) {\n            available_tasks[i] = 1;\n        }\n    }\n}\n\nvoid update_skills(int member, const vector<int>& completed_tasks) {\n    for (int task : completed_tasks) {\n        for (int k = 0; k < team_members[member].skills.size(); ++k) {\n            team_members[member].skills[k] = max(team_members[member].skills[k], tasks[task].required_skills[k]);\n        }\n    }\n}\n\nint calculate_duration(int task, int member) {\n    int w = 0;\n    for (int k = 0; k < tasks[task].required_skills.size(); ++k) {\n        w += max(0, tasks[task].required_skills[k] - team_members[member].skills[k]);\n    }\n\n    if (w == 0) {\n        return 1;\n    } else {\n        random_device rd;\n        mt19937 gen(rd());\n        uniform_int_distribution<> dis(-3, 3);\n        int r = dis(gen);\n        return max(1, w + r);\n    }\n}\n\nvoid assign_tasks() {\n    vector<pair<int, int>> assignments;\n\n    for (int i = 0; i < team_members.size(); ++i) {\n        if (team_members[i].current_task == -1) {\n            for (int j = 0; j < tasks.size(); ++j) {\n                if (available_tasks[j] && !tasks[j].completed) {\n                    int duration = calculate_duration(j, i);\n                    if (duration < tasks[j].duration || tasks[j].duration == 0) {\n                        tasks[j].duration = duration;\n                        team_members[i].current_task = j;\n                        team_members[i].days_left = duration;\n                        assignments.emplace_back(i + 1, j + 1);\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    cout << assignments.size();\n    for (const auto& assignment : assignments) {\n        cout << \" \" << assignment.first << \" \" << assignment.second;\n    }\n    cout << endl;\n    cout.flush();\n}\n\nvoid process_completed_tasks(const vector<int>& completed_members) {\n    vector<int> completed_tasks;\n\n    for (int member : completed_members) {\n        int task = team_members[member - 1].current_task;\n        if (task != -1) {\n            tasks[task].completed = true;\n            completed_tasks.push_back(task);\n            team_members[member - 1].current_task = -1;\n            team_members[member - 1].days_left = 0;\n        }\n    }\n\n    for (int task : completed_tasks) {\n        for (int dependent_task : task_dependencies[task]) {\n            in_degree[dependent_task]--;\n            if (in_degree[dependent_task] == 0) {\n                available_tasks[dependent_task] = 1;\n            }\n        }\n    }\n\n    for (int member : completed_members) {\n        update_skills(member - 1, completed_tasks);\n    }\n}\n\nint main() {\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    initialize(N, M, K, R);\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cin >> tasks[i].required_skills[j];\n        }\n    }\n\n    int day = 0;\n    while (true) {\n        day++;\n        assign_tasks();\n\n        int n;\n        cin >> n;\n        if (n == -1) {\n            break;\n        }\n\n        vector<int> completed_members(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> completed_members[i];\n        }\n\n        process_completed_tasks(completed_members);\n\n        if (all_of(tasks.begin(), tasks.end(), [](const Task& task) { return task.completed; })) {\n            break;\n        }\n\n        if (day >= 2000) {\n            break;\n        }\n    }\n\n    return 0;\n}","ahc006":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <unordered_set>\n#include <climits>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nstruct Order {\n    Point restaurant;\n    Point destination;\n    Order(Point restaurant, Point destination) : restaurant(restaurant), destination(destination) {}\n};\n\nstruct Individual {\n    vector<int> orders;\n    vector<Point> route;\n    int fitness;\n};\n\nint manhattanDistance(const Point& a, const Point& b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nint calculateFitness(const Individual& individual, const vector<Order>& allOrders) {\n    int totalDistance = 0;\n    unordered_set<int> selectedOrders(individual.orders.begin(), individual.orders.end());\n\n    // Check if the route starts and ends at the office\n    if (individual.route.front() != Point(400, 400) || individual.route.back() != Point(400, 400)) {\n        return INT_MAX;\n    }\n\n    // Check if all selected orders are visited in the correct order\n    for (size_t i = 0; i < individual.orders.size(); ++i) {\n        int orderIndex = individual.orders[i];\n        const Order& order = allOrders[orderIndex];\n        bool restaurantVisited = false;\n        bool destinationVisited = false;\n\n        for (size_t j = 0; j < individual.route.size(); ++j) {\n            if (individual.route[j] == order.restaurant) {\n                restaurantVisited = true;\n            }\n            if (individual.route[j] == order.destination) {\n                if (!restaurantVisited) {\n                    return INT_MAX;\n                }\n                destinationVisited = true;\n            }\n        }\n\n        if (!restaurantVisited || !destinationVisited) {\n            return INT_MAX;\n        }\n    }\n\n    // Calculate total travel time\n    for (size_t i = 0; i < individual.route.size() - 1; ++i) {\n        totalDistance += manhattanDistance(individual.route[i], individual.route[i + 1]);\n    }\n\n    return totalDistance;\n}\n\nvector<Individual> initializePopulation(int populationSize, const vector<Order>& allOrders) {\n    vector<Individual> population;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n\n    for (int i = 0; i < populationSize; ++i) {\n        Individual individual;\n        unordered_set<int> selectedOrders;\n\n        // Select 50 unique orders\n        while (selectedOrders.size() < 50) {\n            int orderIndex = orderDist(gen);\n            selectedOrders.insert(orderIndex);\n        }\n\n        individual.orders.assign(selectedOrders.begin(), selectedOrders.end());\n\n        // Generate a random route\n        vector<Point> route;\n        route.push_back(Point(400, 400)); // Start at the office\n\n        for (int orderIndex : individual.orders) {\n            const Order& order = allOrders[orderIndex];\n            route.push_back(order.restaurant);\n            route.push_back(order.destination);\n        }\n\n        route.push_back(Point(400, 400)); // End at the office\n\n        individual.route = route;\n        individual.fitness = calculateFitness(individual, allOrders);\n        population.push_back(individual);\n    }\n\n    return population;\n}\n\nIndividual selectParent(const vector<Individual>& population) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dist(0, population.size() - 1);\n\n    int index1 = dist(gen);\n    int index2 = dist(gen);\n\n    return population[index1].fitness < population[index2].fitness ? population[index1] : population[index2];\n}\n\nIndividual crossover(const Individual& parent1, const Individual& parent2, const vector<Order>& allOrders) {\n    Individual child;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dist(0, 49);\n\n    // Select a random subset of orders from parent1\n    unordered_set<int> selectedOrders(parent1.orders.begin(), parent1.orders.begin() + dist(gen));\n\n    // Add the remaining orders from parent2\n    for (int orderIndex : parent2.orders) {\n        if (selectedOrders.size() >= 50) break;\n        if (selectedOrders.find(orderIndex) == selectedOrders.end()) {\n            selectedOrders.insert(orderIndex);\n        }\n    }\n\n    child.orders.assign(selectedOrders.begin(), selectedOrders.end());\n\n    // Generate a random route\n    vector<Point> route;\n    route.push_back(Point(400, 400)); // Start at the office\n\n    for (int orderIndex : child.orders) {\n        const Order& order = allOrders[orderIndex];\n        route.push_back(order.restaurant);\n        route.push_back(order.destination);\n    }\n\n    route.push_back(Point(400, 400)); // End at the office\n\n    child.route = route;\n    child.fitness = calculateFitness(child, allOrders);\n\n    return child;\n}\n\nvoid mutate(Individual& individual, const vector<Order>& allOrders) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n    uniform_int_distribution<> mutationDist(0, 1);\n\n    // Mutate orders\n    for (int& orderIndex : individual.orders) {\n        if (mutationDist(gen) == 0) {\n            orderIndex = orderDist(gen);\n        }\n    }\n\n    // Ensure all orders are unique\n    unordered_set<int> uniqueOrders(individual.orders.begin(), individual.orders.end());\n    if (uniqueOrders.size() < individual.orders.size()) {\n        vector<int> tempOrders(uniqueOrders.begin(), uniqueOrders.end());\n        while (tempOrders.size() < 50) {\n            int orderIndex = orderDist(gen);\n            if (uniqueOrders.find(orderIndex) == uniqueOrders.end()) {\n                tempOrders.push_back(orderIndex);\n                uniqueOrders.insert(orderIndex);\n            }\n        }\n        individual.orders = tempOrders;\n    }\n\n    // Mutate route\n    for (size_t i = 1; i < individual.route.size() - 1; ++i) {\n        if (mutationDist(gen) == 0) {\n            size_t j = uniform_int_distribution<>(1, individual.route.size() - 2)(gen);\n            swap(individual.route[i], individual.route[j]);\n        }\n    }\n\n    individual.fitness = calculateFitness(individual, allOrders);\n}\n\nvoid localSearch(Individual& individual, const vector<Order>& allOrders) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> orderDist(0, allOrders.size() - 1);\n\n    for (int i = 0; i < 5; ++i) {\n        Individual newIndividual = individual;\n        int orderIndex = orderDist(gen);\n        newIndividual.orders[i % 50] = orderIndex;\n\n        // Ensure all orders are unique\n        unordered_set<int> uniqueOrders(newIndividual.orders.begin(), newIndividual.orders.end());\n        if (uniqueOrders.size() < newIndividual.orders.size()) {\n            vector<int> tempOrders(uniqueOrders.begin(), uniqueOrders.end());\n            while (tempOrders.size() < 50) {\n                int orderIndex = orderDist(gen);\n                if (uniqueOrders.find(orderIndex) == uniqueOrders.end()) {\n                    tempOrders.push_back(orderIndex);\n                    uniqueOrders.insert(orderIndex);\n                }\n            }\n            newIndividual.orders = tempOrders;\n        }\n\n        // Generate a new route\n        vector<Point> route;\n        route.push_back(Point(400, 400)); // Start at the office\n\n        for (int orderIndex : newIndividual.orders) {\n            const Order& order = allOrders[orderIndex];\n            route.push_back(order.restaurant);\n            route.push_back(order.destination);\n        }\n\n        route.push_back(Point(400, 400)); // End at the office\n\n        newIndividual.route = route;\n        newIndividual.fitness = calculateFitness(newIndividual, allOrders);\n\n        if (newIndividual.fitness < individual.fitness) {\n            individual = newIndividual;\n        }\n    }\n}\n\nvector<Individual> evolvePopulation(vector<Individual>& population, const vector<Order>& allOrders) {\n    vector<Individual> newPopulation;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> mutationRate(0.0, 1.0);\n\n    for (size_t i = 0; i < population.size(); ++i) {\n        Individual parent1 = selectParent(population);\n        Individual parent2 = selectParent(population);\n        Individual child = crossover(parent1, parent2, allOrders);\n\n        if (mutationRate(gen) < 0.1) {\n            mutate(child, allOrders);\n        }\n\n        localSearch(child, allOrders);\n        newPopulation.push_back(child);\n    }\n\n    return newPopulation;\n}\n\nint main() {\n    vector<Order> allOrders;\n    for (int i = 0; i < 1000; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        allOrders.emplace_back(Point(a, b), Point(c, d));\n    }\n\n    const int populationSize = 20;\n    const int generations = 200;\n\n    vector<Individual> population = initializePopulation(populationSize, allOrders);\n\n    for (int generation = 0; generation < generations; ++generation) {\n        population = evolvePopulation(population, allOrders);\n\n        // Find the best individual in the current population\n        Individual bestIndividual = *min_element(population.begin(), population.end(),\n            [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; });\n\n        // Output the best fitness for debugging\n        cerr << \"Generation \" << generation << \": Best Fitness = \" << bestIndividual.fitness << endl;\n    }\n\n    // Find the best individual in the final population\n    Individual bestIndividual = *min_element(population.begin(), population.end(),\n        [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; });\n\n    // Output the best solution in the required format\n    cout << bestIndividual.orders.size() << \" \";\n    for (int orderIndex : bestIndividual.orders) {\n        cout << orderIndex + 1 << \" \";\n    }\n    cout << endl;\n\n    cout << bestIndividual.route.size() << \" \";\n    for (const Point& point : bestIndividual.route) {\n        cout << point.x << \" \" << point.y << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc007":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <atcoder/dsu>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Edge {\n    int u, v;\n    double d; // Euclidean distance rounded to the nearest integer\n    int index; // Original index to keep track of the order\n};\n\nint main() {\n    int N = 400;\n    int M = 1995;\n\n    vector<pair<int, int>> coordinates(N);\n    vector<Edge> edges(M);\n\n    // Read coordinates\n    for (int i = 0; i < N; ++i) {\n        cin >> coordinates[i].first >> coordinates[i].second;\n    }\n\n    // Read edges and compute d_i\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        edges[i].index = i;\n        int dx = coordinates[edges[i].u].first - coordinates[edges[i].v].first;\n        int dy = coordinates[edges[i].u].second - coordinates[edges[i].v].second;\n        edges[i].d = round(sqrt(dx * dx + dy * dy));\n    }\n\n    // Sort edges by d_i in ascending order\n    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {\n        return a.d < b.d;\n    });\n\n    dsu uf(N);\n    vector<bool> adopted(M, false);\n\n    // Process edges in order of increasing d_i\n    for (const Edge& edge : edges) {\n        int l;\n        cin >> l;\n        if (!uf.same(edge.u, edge.v)) {\n            uf.merge(edge.u, edge.v);\n            adopted[edge.index] = true;\n            cout << \"1\" << endl;\n        } else {\n            cout << \"0\" << endl;\n        }\n        cout.flush();\n    }\n\n    return 0;\n}","ahc008":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <random>\n#include <algorithm>\n#include <cmath>\n#include <unordered_set>\n#include <map>\n#include <cassert>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int TURNS = 300;\n\nstruct Pet {\n    int x, y, type;\n};\n\nstruct Human {\n    int x, y;\n};\n\nstruct GridState {\n    vector<vector<bool>> passable;\n    vector<Pet> pets;\n    vector<Human> humans;\n};\n\nvector<vector<int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\nvector<vector<int>> bfs(const GridState& state, int startX, int startY) {\n    vector<vector<int>> distance(GRID_SIZE, vector<int>(GRID_SIZE, -1));\n    queue<pair<int, int>> q;\n    q.push({startX, startY});\n    distance[startX][startY] = 0;\n\n    while (!q.empty()) {\n        auto current = q.front();\n        int x = current.first;\n        int y = current.second;\n        q.pop();\n\n        for (size_t i = 0; i < directions.size(); ++i) {\n            int dx = directions[i][0];\n            int dy = directions[i][1];\n            int nx = x + dx;\n            int ny = y + dy;\n            if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny] && distance[nx][ny] == -1) {\n                distance[nx][ny] = distance[x][y] + 1;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return distance;\n}\n\nvector<pair<int, int>> findReachableArea(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    auto distance = bfs(state, hx, hy);\n    vector<pair<int, int>> reachableArea;\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (distance[i][j] != -1) {\n                reachableArea.emplace_back(i, j);\n            }\n        }\n    }\n    return reachableArea;\n}\n\nint countPetsInArea(const GridState& state, const vector<pair<int, int>>& area) {\n    unordered_set<string> petPositions;\n    for (const auto& pet : state.pets) {\n        petPositions.insert(to_string(pet.x) + \",\" + to_string(pet.y));\n    }\n    int count = 0;\n    for (const auto& pos : area) {\n        int x = pos.first;\n        int y = pos.second;\n        if (petPositions.count(to_string(x) + \",\" + to_string(y))) {\n            count++;\n        }\n    }\n    return count;\n}\n\ndouble calculateSatisfaction(const GridState& state, int humanIndex) {\n    auto reachableArea = findReachableArea(state, humanIndex);\n    int areaSize = reachableArea.size();\n    int petCount = countPetsInArea(state, reachableArea);\n    return (areaSize / 900.0) * pow(2, -petCount);\n}\n\nbool isSquareSafeToBlock(const GridState& state, int x, int y) {\n    for (const auto& pet : state.pets) {\n        if (pet.x == x && pet.y == y) {\n            return false;\n        }\n    }\n    for (size_t i = 0; i < directions.size(); ++i) {\n        int dx = directions[i][0];\n        int dy = directions[i][1];\n        int nx = x + dx;\n        int ny = y + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE) {\n            for (const auto& pet : state.pets) {\n                if (pet.x == nx && pet.y == ny) {\n                    return false;\n                }\n            }\n        }\n    }\n    return true;\n}\n\nvector<pair<int, int>> findBestSquareToBlock(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    vector<pair<int, int>> candidates;\n    for (size_t i = 0; i < directions.size(); ++i) {\n        int dx = directions[i][0];\n        int dy = directions[i][1];\n        int nx = hx + dx;\n        int ny = hy + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny] && isSquareSafeToBlock(state, nx, ny)) {\n            candidates.emplace_back(nx, ny);\n        }\n    }\n    if (candidates.empty()) {\n        return {};\n    }\n    vector<double> scores;\n    for (const auto& candidate : candidates) {\n        int nx = candidate.first;\n        int ny = candidate.second;\n        GridState newState = state;\n        newState.passable[nx][ny] = false;\n        auto reachableArea = findReachableArea(newState, humanIndex);\n        int areaSize = reachableArea.size();\n        int petCount = countPetsInArea(newState, reachableArea);\n        scores.push_back((areaSize / 900.0) * pow(2, -petCount));\n    }\n    int bestIndex = max_element(scores.begin(), scores.end()) - scores.begin();\n    return {candidates[bestIndex]};\n}\n\nvector<pair<int, int>> findBestMove(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    vector<pair<int, int>> candidates;\n    for (size_t i = 0; i < directions.size(); ++i) {\n        int dx = directions[i][0];\n        int dy = directions[i][1];\n        int nx = hx + dx;\n        int ny = hy + dy;\n        if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n            candidates.emplace_back(nx, ny);\n        }\n    }\n    if (candidates.empty()) {\n        return {};\n    }\n    vector<double> scores;\n    for (const auto& candidate : candidates) {\n        int nx = candidate.first;\n        int ny = candidate.second;\n        GridState newState = state;\n        newState.humans[humanIndex] = {nx, ny};\n        auto reachableArea = findReachableArea(newState, humanIndex);\n        int areaSize = reachableArea.size();\n        int petCount = countPetsInArea(newState, reachableArea);\n        scores.push_back((areaSize / 900.0) * pow(2, -petCount));\n    }\n    int bestIndex = max_element(scores.begin(), scores.end()) - scores.begin();\n    return {candidates[bestIndex]};\n}\n\nstring decideAction(const GridState& state, int humanIndex) {\n    auto human = state.humans[humanIndex];\n    int hx = human.x;\n    int hy = human.y;\n    auto blockSquares = findBestSquareToBlock(state, humanIndex);\n    auto moveSquares = findBestMove(state, humanIndex);\n\n    double currentSatisfaction = calculateSatisfaction(state, humanIndex);\n\n    double blockSatisfaction = -1;\n    if (!blockSquares.empty()) {\n        auto blockSquare = blockSquares[0];\n        int nx = blockSquare.first;\n        int ny = blockSquare.second;\n        GridState newState = state;\n        newState.passable[nx][ny] = false;\n        blockSatisfaction = calculateSatisfaction(newState, humanIndex);\n    }\n\n    double moveSatisfaction = -1;\n    if (!moveSquares.empty()) {\n        auto moveSquare = moveSquares[0];\n        int nx = moveSquare.first;\n        int ny = moveSquare.second;\n        GridState newState = state;\n        newState.humans[humanIndex] = {nx, ny};\n        moveSatisfaction = calculateSatisfaction(newState, humanIndex);\n    }\n\n    if (blockSatisfaction > currentSatisfaction && blockSatisfaction >= moveSatisfaction) {\n        auto blockSquare = blockSquares[0];\n        int nx = blockSquare.first;\n        int ny = blockSquare.second;\n        if (nx == hx - 1 && ny == hy) return \"u\";\n        if (nx == hx + 1 && ny == hy) return \"d\";\n        if (nx == hx && ny == hy - 1) return \"l\";\n        if (nx == hx && ny == hy + 1) return \"r\";\n    } else if (moveSatisfaction > currentSatisfaction && moveSatisfaction >= blockSatisfaction) {\n        auto moveSquare = moveSquares[0];\n        int nx = moveSquare.first;\n        int ny = moveSquare.second;\n        if (nx == hx - 1 && ny == hy) return \"U\";\n        if (nx == hx + 1 && ny == hy) return \"D\";\n        if (nx == hx && ny == hy - 1) return \"L\";\n        if (nx == hx && ny == hy + 1) return \"R\";\n    }\n    return \".\";\n}\n\nvoid simulatePetMovement(GridState& state, const vector<string>& petMoves) {\n    for (size_t i = 0; i < state.pets.size(); ++i) {\n        auto& pet = state.pets[i];\n        const string& move = petMoves[i];\n        if (move == \".\") continue;\n\n        for (char c : move) {\n            int dx = 0, dy = 0;\n            if (c == 'U') dx = -1;\n            else if (c == 'D') dx = 1;\n            else if (c == 'L') dy = -1;\n            else if (c == 'R') dy = 1;\n\n            int nx = pet.x + dx;\n            int ny = pet.y + dy;\n            if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE && state.passable[nx][ny]) {\n                pet.x = nx;\n                pet.y = ny;\n            }\n        }\n    }\n}\n\nint main() {\n    int N, M;\n    cin >> N;\n    vector<Pet> pets(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    vector<Human> humans(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\n    GridState state;\n    state.passable = vector<vector<bool>>(GRID_SIZE, vector<bool>(GRID_SIZE, true));\n    state.pets = pets;\n    state.humans = humans;\n\n    for (int turn = 0; turn < TURNS; ++turn) {\n        string actions;\n        for (int i = 0; i < M; ++i) {\n            actions += decideAction(state, i);\n        }\n        cout << actions << endl;\n        cout.flush();\n\n        vector<string> petMoves(N);\n        for (int i = 0; i < N; ++i) {\n            cin >> petMoves[i];\n        }\n        simulatePetMovement(state, petMoves);\n    }\n\n    return 0;\n}","ahc009":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <tuple>\n#include <algorithm>\n#include <cmath>\n#include <unordered_map>\n#include <map>\n#include <set>\n#include <string>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MAX_N = 20;\nconst int MAX_M = 20;\nconst int MAX_T = 200;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir[] = {'U', 'D', 'L', 'R'};\n\nstruct State {\n    int x, y, t;\n    double prob;\n    string path;\n\n    bool operator<(const State& other) const {\n        return prob < other.prob;\n    }\n};\n\ndouble simulate(int si, int sj, int ti, int tj, double p, const string& path, const vector<string>& h, const vector<string>& v) {\n    int x = si, y = sj;\n    double prob = 1.0;\n\n    for (char c : path) {\n        if (c == 'S') {\n            prob *= p;\n            continue;\n        }\n\n        int i;\n        for (i = 0; i < 4; ++i) {\n            if (dir[i] == c) break;\n        }\n\n        int nx = x + dx[i];\n        int ny = y + dy[i];\n\n        if (nx < 0 || nx >= MAX_N || ny < 0 || ny >= MAX_M) {\n            prob *= p;\n            continue;\n        }\n\n        if (i == 0 && v[x - 1][y] == '1') {\n            prob *= p;\n            continue;\n        }\n        if (i == 1 && v[x][y] == '1') {\n            prob *= p;\n            continue;\n        }\n        if (i == 2 && h[x][y - 1] == '1') {\n            prob *= p;\n            continue;\n        }\n        if (i == 3 && h[x][y] == '1') {\n            prob *= p;\n            continue;\n        }\n\n        x = nx;\n        y = ny;\n        prob *= (1 - p);\n\n        if (x == ti && y == tj) {\n            return prob * (401 - path.size());\n        }\n    }\n\n    return 0.0;\n}\n\nstring generate_random_path(int length) {\n    static random_device rd;\n    static mt19937 gen(rd());\n    static uniform_int_distribution<> dis(0, 3);\n\n    string path;\n    for (int i = 0; i < length; ++i) {\n        path += dir[dis(gen)];\n    }\n    return path;\n}\n\nstring monte_carlo_simulation(int si, int sj, int ti, int tj, double p, const vector<string>& h, const vector<string>& v, int iterations = 1000) {\n    string best_path;\n    double max_score = 0.0;\n\n    for (int i = 0; i < iterations; ++i) {\n        string path = generate_random_path(200);\n        double score = simulate(si, sj, ti, tj, p, path, h, v);\n\n        if (score > max_score) {\n            max_score = score;\n            best_path = path;\n        }\n    }\n\n    return best_path;\n}\n\nstring genetic_algorithm(int si, int sj, int ti, int tj, double p, const vector<string>& h, const vector<string>& v, int population_size = 100, int generations = 100) {\n    vector<string> population;\n    for (int i = 0; i < population_size; ++i) {\n        population.push_back(generate_random_path(200));\n    }\n\n    for (int gen = 0; gen < generations; ++gen) {\n        vector<double> scores;\n        for (const string& path : population) {\n            scores.push_back(simulate(si, sj, ti, tj, p, path, h, v));\n        }\n\n        vector<string> new_population;\n        for (int i = 0; i < population_size; ++i) {\n            int parent1 = max_element(scores.begin(), scores.end()) - scores.begin();\n            scores[parent1] = -1;\n            int parent2 = max_element(scores.begin(), scores.end()) - scores.begin();\n            scores[parent2] = -1;\n\n            string child;\n            for (int j = 0; j < 200; ++j) {\n                if (j < 100) {\n                    child += population[parent1][j];\n                } else {\n                    child += population[parent2][j];\n                }\n            }\n\n            // Mutation\n            if (rand() % 100 < 10) {\n                int pos = rand() % 200;\n                child[pos] = dir[rand() % 4];\n            }\n\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n    }\n\n    double max_score = 0.0;\n    string best_path;\n    for (const string& path : population) {\n        double score = simulate(si, sj, ti, tj, p, path, h, v);\n        if (score > max_score) {\n            max_score = score;\n            best_path = path;\n        }\n    }\n\n    return best_path;\n}\n\nint main() {\n    int si, sj, ti, tj;\n    double p;\n    vector<string> h(MAX_N), v(MAX_N);\n\n    cin >> si >> sj >> ti >> tj >> p;\n    for (int i = 0; i < MAX_N; ++i) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < MAX_N; ++i) {\n        cin >> v[i];\n    }\n\n    string best_path = genetic_algorithm(si, sj, ti, tj, p, h, v);\n\n    cout << best_path << endl;\n\n    return 0;\n}","ahc010":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <unordered_set>\n#include <queue>\n#include <tuple>\n#include <thread>\n#include <mutex>\n\nusing namespace std;\n\nconst int GRID_SIZE = 30;\nconst int POPULATION_SIZE = 50;\nconst int MAX_GENERATIONS = 50;\nconst double MUTATION_RATE = 0.1;\nconst double CROSSOVER_RATE = 0.7;\n\nvector<vector<int>> tiles(GRID_SIZE, vector<int>(GRID_SIZE));\nvector<vector<int>> rotations(GRID_SIZE, vector<int>(GRID_SIZE));\n\n// Directions: left, up, right, down\nconst int di[] = {0, -1, 0, 1};\nconst int dj[] = {-1, 0, 1, 0};\n\n// Transition table for tile types and directions\nconst vector<vector<int>> to = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\n\nmutex mtx;\n\nint simple_fitness_function() {\n    int connected_tiles = 0;\n    vector<vector<vector<bool>>> visited(GRID_SIZE, vector<vector<bool>>(GRID_SIZE, vector<bool>(4, false)));\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            for (int d = 0; d < 4; ++d) {\n                if (!visited[i][j][d]) {\n                    int d2 = to[tiles[i][j]][d];\n                    if (d2 != -1) {\n                        int ni = i + di[d2];\n                        int nj = j + dj[d2];\n                        if (ni >= 0 && ni < GRID_SIZE && nj >= 0 && nj < GRID_SIZE) {\n                            connected_tiles++;\n                            visited[i][j][d] = true;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    return connected_tiles;\n}\n\nvoid initialize_population(vector<vector<vector<int>>>& population) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, 3);\n\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        for (int i = 0; i < GRID_SIZE; ++i) {\n            for (int j = 0; j < GRID_SIZE; ++j) {\n                population[p][i][j] = dis(gen);\n            }\n        }\n    }\n}\n\nvoid mutate(vector<vector<int>>& individual) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> rot_dis(0, 3);\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (dis(gen) < MUTATION_RATE) {\n                individual[i][j] = rot_dis(gen);\n            }\n        }\n    }\n}\n\nvector<vector<int>> crossover(const vector<vector<int>>& parent1, const vector<vector<int>>& parent2) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    uniform_int_distribution<> row_dis(0, GRID_SIZE - 1);\n    uniform_int_distribution<> col_dis(0, GRID_SIZE - 1);\n\n    vector<vector<int>> child(GRID_SIZE, vector<int>(GRID_SIZE));\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            if (dis(gen) < CROSSOVER_RATE) {\n                child[i][j] = parent1[i][j];\n            } else {\n                child[i][j] = parent2[i][j];\n            }\n        }\n    }\n\n    return child;\n}\n\nvoid evaluate_fitness(vector<vector<vector<int>>>& population, vector<int>& fitness_scores) {\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        rotations = population[p];\n        fitness_scores[p] = simple_fitness_function();\n    }\n}\n\nvoid genetic_algorithm() {\n    vector<vector<vector<int>>> population(POPULATION_SIZE, vector<vector<int>>(GRID_SIZE, vector<int>(GRID_SIZE)));\n    initialize_population(population);\n\n    vector<int> fitness_scores(POPULATION_SIZE);\n    evaluate_fitness(population, fitness_scores);\n\n    for (int gen = 0; gen < MAX_GENERATIONS; ++gen) {\n        vector<vector<vector<int>>> new_population;\n        for (int p = 0; p < POPULATION_SIZE; ++p) {\n            int parent1_idx = distance(fitness_scores.begin(), max_element(fitness_scores.begin(), fitness_scores.end()));\n            fitness_scores[parent1_idx] = -1;\n            int parent2_idx = distance(fitness_scores.begin(), max_element(fitness_scores.begin(), fitness_scores.end()));\n            fitness_scores[parent2_idx] = -1;\n\n            vector<vector<int>> child = crossover(population[parent1_idx], population[parent2_idx]);\n            mutate(child);\n            new_population.push_back(child);\n        }\n\n        population = new_population;\n        evaluate_fitness(population, fitness_scores);\n    }\n\n    // Find the best solution\n    int best_fitness = -1;\n    vector<vector<int>> best_rotations;\n    for (int p = 0; p < POPULATION_SIZE; ++p) {\n        rotations = population[p];\n        int current_fitness = simple_fitness_function();\n        if (current_fitness > best_fitness) {\n            best_fitness = current_fitness;\n            best_rotations = population[p];\n        }\n    }\n\n    rotations = best_rotations;\n}\n\nint main() {\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            tiles[i][j] = row[j] - '0';\n        }\n    }\n\n    genetic_algorithm();\n\n    for (int i = 0; i < GRID_SIZE; ++i) {\n        for (int j = 0; j < GRID_SIZE; ++j) {\n            cout << rotations[i][j];\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc011":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n#include <atcoder/dsu>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dir[] = {'R', 'D', 'L', 'U'};\n\nstruct State {\n    vector<vector<int>> board;\n    pair<int, int> empty;\n    int cost;\n    int heuristic;\n    string path;\n\n    bool operator==(const State& other) const {\n        return board == other.board && empty == other.empty;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<State> {\n        size_t operator()(const State& state) const {\n            size_t seed = 0;\n            for (const auto& row : state.board) {\n                for (int tile : row) {\n                    seed ^= hash<int>{}(tile) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n                }\n            }\n            seed ^= hash<int>{}(state.empty.first) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            seed ^= hash<int>{}(state.empty.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n            return seed;\n        }\n    };\n}\n\nint calculate_heuristic(const vector<vector<int>>& board, int N) {\n    dsu d(N * N);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 0) continue;\n            for (int k = 0; k < 4; ++k) {\n                int ni = i + dx[k];\n                int nj = j + dy[k];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N || board[ni][nj] == 0) continue;\n                if ((board[i][j] & (1 << k)) && (board[ni][nj] & (1 << ((k + 2) % 4)))) {\n                    d.merge(i * N + j, ni * N + nj);\n                }\n            }\n        }\n    }\n    unordered_set<int> roots;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] != 0) {\n                roots.insert(d.leader(i * N + j));\n            }\n        }\n    }\n    return roots.size();\n}\n\nvector<State> get_neighbors(const State& state, int N) {\n    vector<State> neighbors;\n    int x = state.empty.first;\n    int y = state.empty.second;\n    for (int i = 0; i < 4; ++i) {\n        int nx = x + dx[i];\n        int ny = y + dy[i];\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n        State neighbor = state;\n        neighbor.board[x][y] = neighbor.board[nx][ny];\n        neighbor.board[nx][ny] = 0;\n        neighbor.empty = {nx, ny};\n        neighbor.cost = state.cost + 1;\n        neighbor.heuristic = calculate_heuristic(neighbor.board, N);\n        neighbor.path += dir[i];\n        neighbors.push_back(neighbor);\n    }\n    return neighbors;\n}\n\nstring simulated_annealing_with_genetic_algorithm(State initial, int N, int T) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    vector<State> population;\n    population.push_back(initial);\n\n    double temperature = 1.0;\n    double cooling_rate = 0.99;\n\n    for (int generation = 0; generation < 100; ++generation) {\n        vector<State> new_population;\n        for (const State& state : population) {\n            if (state.heuristic == 1) {\n                return state.path;\n            }\n            vector<State> neighbors = get_neighbors(state, N);\n            for (State& neighbor : neighbors) {\n                if (neighbor.cost <= T) {\n                    double delta = neighbor.heuristic - state.heuristic;\n                    if (delta < 0 || dis(gen) < exp(-delta / temperature)) {\n                        new_population.push_back(neighbor);\n                    }\n                }\n            }\n        }\n        if (new_population.empty()) break;\n        sort(new_population.begin(), new_population.end(), [](const State& a, const State& b) {\n            return a.heuristic < b.heuristic;\n        });\n        population = vector<State>(new_population.begin(), new_population.begin() + min(10, (int)new_population.size()));\n        temperature *= cooling_rate;\n    }\n    return population.empty() ? \"\" : population[0].path;\n}\n\nint main() {\n    int N, T;\n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    pair<int, int> empty;\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            char c = row[j];\n            if (c >= '0' && c <= '9') {\n                board[i][j] = c - '0';\n            } else {\n                board[i][j] = 10 + (c - 'a');\n            }\n            if (board[i][j] == 0) {\n                empty = {i, j};\n            }\n        }\n    }\n    State initial = {board, empty, 0, calculate_heuristic(board, N), \"\"};\n    string solution = simulated_annealing_with_genetic_algorithm(initial, N, T);\n    cout << solution << endl;\n    return 0;\n}","ahc012":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <limits>\n#include <unordered_set>\n#include <utility>\n#include <map>\n#include <numeric>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct Line {\n    Point p, q;\n    Line(Point p, Point q) : p(p), q(q) {}\n    bool operator==(const Line& other) const {\n        return (p == other.p && q == other.q) || (p == other.q && q == other.p);\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Line> {\n        size_t operator()(const Line& l) const {\n            return hash<Point>()(l.p) ^ hash<Point>()(l.q);\n        }\n    };\n}\n\nstruct Strawberry {\n    int x, y;\n    Strawberry(int x, int y) : x(x), y(y) {}\n};\n\nvector<Strawberry> strawberries;\nvector<int> a_d(10);\nint K;\n\ndouble distance(const Point& p1, const Point& p2) {\n    return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));\n}\n\nbool isInside(const Point& p, const Line& line) {\n    // Check if point p is inside the cake and not cut by the line\n    if (distance(p, Point(0, 0)) >= 10000) {\n        return false;\n    }\n    // Check if the point is on the line\n    int x1 = line.p.x, y1 = line.p.y;\n    int x2 = line.q.x, y2 = line.q.y;\n    int x = p.x, y = p.y;\n    if ((y2 - y1) * (x - x1) == (y - y1) * (x2 - x1)) {\n        return false;\n    }\n    return true;\n}\n\nint countPieces(const vector<Line>& lines, int d) {\n    vector<vector<bool>> inside(strawberries.size(), vector<bool>(lines.size() + 1, true));\n    for (int i = 0; i < lines.size(); ++i) {\n        for (int j = 0; j < strawberries.size(); ++j) {\n            if (!isInside(Point(strawberries[j].x, strawberries[j].y), lines[i])) {\n                inside[j][i + 1] = false;\n            }\n        }\n    }\n    int count = 0;\n    for (int i = 0; i < strawberries.size(); ++i) {\n        int c = 0;\n        for (int j = 0; j <= lines.size(); ++j) {\n            if (inside[i][j]) {\n                c++;\n            }\n        }\n        if (c == d) {\n            count++;\n        }\n    }\n    return count;\n}\n\nvector<Line> enhancedAdaptiveLineGeneration() {\n    vector<Line> lines;\n    unordered_set<Line> uniqueLines;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(-1e9, 1e9);\n\n    // Generate lines through pairs of strawberries\n    for (int i = 0; i < min(30, (int)strawberries.size()); ++i) {\n        for (int j = i + 1; j < min(30, (int)strawberries.size()); ++j) {\n            Point p(strawberries[i].x, strawberries[i].y);\n            Point q(strawberries[j].x, strawberries[j].y);\n            Line line(p, q);\n            if (uniqueLines.find(line) == uniqueLines.end()) {\n                uniqueLines.insert(line);\n                lines.push_back(line);\n            }\n        }\n    }\n\n    // Generate random lines\n    for (int i = 0; i < 30; ++i) {\n        Point p(dis(gen), dis(gen));\n        Point q(dis(gen), dis(gen));\n        Line line(p, q);\n        if (uniqueLines.find(line) == uniqueLines.end()) {\n            uniqueLines.insert(line);\n            lines.push_back(line);\n        }\n    }\n\n    // Generate lines based on the distribution of strawberries\n    map<int, vector<Strawberry>> xMap;\n    map<int, vector<Strawberry>> yMap;\n    for (const auto& s : strawberries) {\n        xMap[s.x].push_back(s);\n        yMap[s.y].push_back(s);\n    }\n\n    for (const auto& pair : xMap) {\n        if (pair.second.size() > 1) {\n            Point p(pair.second[0].x, pair.second[0].y);\n            Point q(pair.second[1].x, pair.second[1].y);\n            Line line(p, q);\n            if (uniqueLines.find(line) == uniqueLines.end()) {\n                uniqueLines.insert(line);\n                lines.push_back(line);\n            }\n        }\n    }\n\n    for (const auto& pair : yMap) {\n        if (pair.second.size() > 1) {\n            Point p(pair.second[0].x, pair.second[0].y);\n            Point q(pair.second[1].x, pair.second[1].y);\n            Line line(p, q);\n            if (uniqueLines.find(line) == uniqueLines.end()) {\n                uniqueLines.insert(line);\n                lines.push_back(line);\n            }\n        }\n    }\n\n    // Generate lines based on the number of attendees for each d\n    for (int d = 1; d <= 10; ++d) {\n        if (a_d[d - 1] == 0) continue;\n        for (int i = 0; i < min(10, (int)strawberries.size()); ++i) {\n            Point p(strawberries[i].x, strawberries[i].y);\n            Point q(strawberries[i].x + d, strawberries[i].y + d);\n            Line line(p, q);\n            if (uniqueLines.find(line) == uniqueLines.end()) {\n                uniqueLines.insert(line);\n                lines.push_back(line);\n            }\n        }\n    }\n\n    return lines;\n}\n\nvector<Line> enhancedHybridAlgorithm() {\n    vector<Line> lines;\n    vector<Line> candidateLines = enhancedAdaptiveLineGeneration();\n\n    for (int d = 1; d <= 10; ++d) {\n        if (a_d[d - 1] == 0) continue;\n        int maxPieces = 0;\n        Line bestLine(Point(0, 0), Point(0, 0));\n        for (const auto& line : candidateLines) {\n            vector<Line> tempLines = lines;\n            tempLines.push_back(line);\n            int pieces = countPieces(tempLines, d);\n            if (pieces > maxPieces) {\n                maxPieces = pieces;\n                bestLine = line;\n            }\n        }\n        if (maxPieces > 0) {\n            lines.push_back(bestLine);\n            if (lines.size() >= K) break;\n        }\n    }\n    return lines;\n}\n\nint main() {\n    int N;\n    cin >> N >> K;\n    for (int i = 0; i < 10; ++i) {\n        cin >> a_d[i];\n    }\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        strawberries.emplace_back(x, y);\n    }\n    vector<Line> lines = enhancedHybridAlgorithm();\n    cout << lines.size() << endl;\n    for (const auto& line : lines) {\n        cout << line.p.x << \" \" << line.p.y << \" \" << line.q.x << \" \" << line.q.y << endl;\n    }\n    return 0;\n}","ahc014":"#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n#include <unordered_set>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n    bool operator<(const Point& other) const {\n        if (x != other.x) return x < other.x;\n        return y < other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct Rectangle {\n    Point p1, p2, p3, p4;\n    Rectangle(Point p1, Point p2, Point p3, Point p4) : p1(p1), p2(p2), p3(p3), p4(p4) {}\n};\n\nclass RectJoinGame {\nprivate:\n    int N, M;\n    unordered_set<Point> dots;\n    vector<Rectangle> rectangles;\n    int c;\n    double S;\n    mt19937 rng;\n\n    double weight(int x, int y) {\n        return (x - c) * (x - c) + (y - c) * (y - c) + 1;\n    }\n\n    bool isValidRectangle(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        // Check if the points form a valid rectangle (axis-aligned or 45-degree)\n        int dx1 = p2.x - p1.x;\n        int dy1 = p2.y - p1.y;\n        int dx2 = p3.x - p2.x;\n        int dy2 = p3.y - p2.y;\n        int dx3 = p4.x - p3.x;\n        int dy3 = p4.y - p3.y;\n        int dx4 = p1.x - p4.x;\n        int dy4 = p1.y - p4.y;\n\n        // Check if the sides are equal and perpendicular\n        if ((dx1 == dx3 && dy1 == dy3) && (dx2 == dx4 && dy2 == dy4) &&\n            (dx1 * dx2 + dy1 * dy2 == 0)) {\n            // Check if the rectangle is axis-aligned or 45-degree\n            if ((dx1 == 0 || dy1 == 0 || abs(dx1) == abs(dy1)) &&\n                (dx2 == 0 || dy2 == 0 || abs(dx2) == abs(dy2))) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    bool isValidOperation(const Point& p1, const Point& p2, const Point& p3, const Point& p4) {\n        if (dots.count(p1)) return false;\n        if (!dots.count(p2) || !dots.count(p3) || !dots.count(p4)) return false;\n        if (!isValidRectangle(p1, p2, p3, p4)) return false;\n\n        // Check if the perimeter of the rectangle contains any other dots\n        set<Point> perimeter;\n        int dx = p2.x - p1.x;\n        int dy = p2.y - p1.y;\n        for (int i = 0; i <= 1; ++i) {\n            for (int j = 0; j <= 1; ++j) {\n                int x = p1.x + i * dx;\n                int y = p1.y + i * dy;\n                for (int k = 0; k <= 1; ++k) {\n                    int nx = x + k * dy;\n                    int ny = y - k * dx;\n                    perimeter.insert(Point(nx, ny));\n                }\n            }\n        }\n        for (const auto& p : perimeter) {\n            if (dots.count(p) && !(p == p1 || p == p2 || p == p3 || p == p4)) {\n                return false;\n            }\n        }\n\n        // Check if the perimeter of the rectangle shares a common segment with any previously drawn rectangle\n        for (const auto& rect : rectangles) {\n            set<Point> rectPerimeter;\n            int rdx = rect.p2.x - rect.p1.x;\n            int rdy = rect.p2.y - rect.p1.y;\n            for (int i = 0; i <= 1; ++i) {\n                for (int j = 0; j <= 1; ++j) {\n                    int x = rect.p1.x + i * rdx;\n                    int y = rect.p1.y + i * rdy;\n                    for (int k = 0; k <= 1; ++k) {\n                        int nx = x + k * rdy;\n                        int ny = y - k * rdx;\n                        rectPerimeter.insert(Point(nx, ny));\n                    }\n                }\n            }\n            set<Point> intersection;\n            set_intersection(perimeter.begin(), perimeter.end(), rectPerimeter.begin(), rectPerimeter.end(), inserter(intersection, intersection.begin()));\n            if (intersection.size() > 2) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    double calculateScore() {\n        double sum = 0;\n        for (const auto& p : dots) {\n            sum += weight(p.x, p.y);\n        }\n        return round(1e6 * N * N / M * sum / S);\n    }\n\n    vector<Point> getNeighbors(const Point& p) {\n        vector<Point> neighbors;\n        for (int dx = -1; dx <= 1; ++dx) {\n            for (int dy = -1; dy <= 1; ++dy) {\n                if (dx == 0 && dy == 0) continue;\n                int nx = p.x + dx;\n                int ny = p.y + dy;\n                if (nx >= 0 && nx < N && ny >= 0 && ny < N) {\n                    neighbors.emplace_back(nx, ny);\n                }\n            }\n        }\n        return neighbors;\n    }\n\n    pair<Point, vector<Point>> findBestOperation() {\n        double bestScore = -1;\n        Point bestP1(-1, -1); // Initialize with default values\n        vector<Point> bestP234;\n\n        for (const auto& p1 : dots) {\n            auto neighbors = getNeighbors(p1);\n            for (const auto& p2 : neighbors) {\n                if (!dots.count(p2)) continue;\n                for (const auto& p3 : neighbors) {\n                    if (!dots.count(p3) || p3 == p2) continue;\n                    for (const auto& p4 : neighbors) {\n                        if (!dots.count(p4) || p4 == p2 || p4 == p3) continue;\n                        if (isValidOperation(p1, p2, p3, p4)) {\n                            dots.insert(p1);\n                            rectangles.emplace_back(p1, p2, p3, p4);\n                            double score = calculateScore();\n                            dots.erase(p1);\n                            rectangles.pop_back();\n                            if (score > bestScore) {\n                                bestScore = score;\n                                bestP1 = p1;\n                                bestP234 = {p2, p3, p4};\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        return {bestP1, bestP234};\n    }\n\n    void simulatedAnnealing(double initialTemp, double finalTemp, double alpha) {\n        double temp = initialTemp;\n        auto currentScore = calculateScore();\n        auto bestScore = currentScore;\n        vector<Rectangle> bestRectangles = rectangles;\n\n        while (temp > finalTemp) {\n            auto [p1, p234] = findBestOperation();\n            if (p234.empty()) break;\n\n            dots.insert(p1);\n            rectangles.emplace_back(p1, p234[0], p234[1], p234[2]);\n            auto newScore = calculateScore();\n\n            if (newScore > currentScore || exp((newScore - currentScore) / temp) > uniform_real_distribution<double>(0, 1)(rng)) {\n                currentScore = newScore;\n                if (newScore > bestScore) {\n                    bestScore = newScore;\n                    bestRectangles = rectangles;\n                }\n            } else {\n                dots.erase(p1);\n                rectangles.pop_back();\n            }\n\n            temp *= alpha;\n        }\n\n        rectangles = bestRectangles;\n    }\n\npublic:\n    RectJoinGame(int N, int M, const vector<Point>& initialDots) : N(N), M(M), dots(initialDots.begin(), initialDots.end()), c((N - 1) / 2), rng(chrono::steady_clock::now().time_since_epoch().count()) {\n        S = 0;\n        for (int x = 0; x < N; ++x) {\n            for (int y = 0; y < N; ++y) {\n                S += weight(x, y);\n            }\n        }\n    }\n\n    void play() {\n        simulatedAnnealing(1000, 0.1, 0.99);\n    }\n\n    void output() const {\n        cout << rectangles.size() << endl;\n        for (const auto& rect : rectangles) {\n            cout << rect.p1.x << \" \" << rect.p1.y << \" \"\n                 << rect.p2.x << \" \" << rect.p2.y << \" \"\n                 << rect.p3.x << \" \" << rect.p3.y << \" \"\n                 << rect.p4.x << \" \" << rect.p4.y << endl;\n        }\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<Point> initialDots;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        initialDots.emplace_back(x, y);\n    }\n\n    RectJoinGame game(N, M, initialDots);\n    game.play();\n    game.output();\n\n    return 0;\n}","ahc015":"#include <iostream>\n#include <vector>\n#include <array>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <queue>\n#include <unordered_map>\n\nusing namespace std;\n\nconst int GRID_SIZE = 10;\nconst int NUM_FLAVORS = 3;\nconst int NUM_CANDIES = 100;\nconst int LOOKAHEAD_STEPS = 3;\nconst int NUM_SIMULATIONS = 5;\n\nenum Direction { FORWARD, BACKWARD, LEFT, RIGHT };\n\nstruct Candy {\n    int flavor;\n    int row;\n    int col;\n};\n\nstruct Grid {\n    array<array<int, GRID_SIZE>, GRID_SIZE> cells;\n    vector<Candy> candies;\n\n    Grid() {\n        for (auto& row : cells) {\n            fill(row.begin(), row.end(), 0);\n        }\n    }\n\n    void place_candy(int flavor, int row, int col) {\n        cells[row][col] = flavor;\n        candies.push_back({flavor, row, col});\n    }\n\n    void tilt(Direction dir) {\n        switch (dir) {\n            case FORWARD:\n                tilt_forward();\n                break;\n            case BACKWARD:\n                tilt_backward();\n                break;\n            case LEFT:\n                tilt_left();\n                break;\n            case RIGHT:\n                tilt_right();\n                break;\n        }\n    }\n\n    void tilt_forward() {\n        for (int col = 0; col < GRID_SIZE; ++col) {\n            int empty_row = GRID_SIZE - 1;\n            for (int row = GRID_SIZE - 1; row >= 0; --row) {\n                if (cells[row][col] != 0) {\n                    cells[empty_row][col] = cells[row][col];\n                    if (empty_row != row) {\n                        cells[row][col] = 0;\n                    }\n                    --empty_row;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_backward() {\n        for (int col = 0; col < GRID_SIZE; ++col) {\n            int empty_row = 0;\n            for (int row = 0; row < GRID_SIZE; ++row) {\n                if (cells[row][col] != 0) {\n                    cells[empty_row][col] = cells[row][col];\n                    if (empty_row != row) {\n                        cells[row][col] = 0;\n                    }\n                    ++empty_row;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_left() {\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            int empty_col = 0;\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0) {\n                    cells[row][empty_col] = cells[row][col];\n                    if (empty_col != col) {\n                        cells[row][col] = 0;\n                    }\n                    ++empty_col;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void tilt_right() {\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            int empty_col = GRID_SIZE - 1;\n            for (int col = GRID_SIZE - 1; col >= 0; --col) {\n                if (cells[row][col] != 0) {\n                    cells[row][empty_col] = cells[row][col];\n                    if (empty_col != col) {\n                        cells[row][col] = 0;\n                    }\n                    --empty_col;\n                }\n            }\n        }\n        update_candies();\n    }\n\n    void update_candies() {\n        candies.clear();\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0) {\n                    candies.push_back({cells[row][col], row, col});\n                }\n            }\n        }\n    }\n\n    int calculate_score() {\n        array<int, NUM_FLAVORS + 1> flavor_counts = {0};\n        for (const auto& candy : candies) {\n            flavor_counts[candy.flavor]++;\n        }\n\n        int sum_squares = 0;\n        for (int i = 1; i <= NUM_FLAVORS; ++i) {\n            sum_squares += flavor_counts[i] * flavor_counts[i];\n        }\n\n        array<array<bool, GRID_SIZE>, GRID_SIZE> visited = {false};\n        int connectivity = 0;\n\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (cells[row][col] != 0 && !visited[row][col]) {\n                    int flavor = cells[row][col];\n                    int component_size = 0;\n                    vector<pair<int, int>> stack = {{row, col}};\n                    visited[row][col] = true;\n\n                    while (!stack.empty()) {\n                        auto [r, c] = stack.back();\n                        stack.pop_back();\n                        component_size++;\n\n                        for (const auto& [dr, dc] : vector<pair<int, int>>{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {\n                            int nr = r + dr;\n                            int nc = c + dc;\n                            if (nr >= 0 && nr < GRID_SIZE && nc >= 0 && nc < GRID_SIZE && cells[nr][nc] == flavor && !visited[nr][nc]) {\n                                visited[nr][nc] = true;\n                                stack.emplace_back(nr, nc);\n                            }\n                        }\n                    }\n\n                    connectivity += component_size * component_size;\n                }\n            }\n        }\n\n        return round(1e6 * static_cast<double>(connectivity) / sum_squares);\n    }\n};\n\nDirection choose_direction(const Grid& grid, int flavor, const vector<int>& remaining_flavors) {\n    array<int, 4> scores = {0};\n    array<Grid, 4> grids;\n\n    for (int i = 0; i < 4; ++i) {\n        grids[i] = grid;\n        grids[i].tilt(static_cast<Direction>(i));\n\n        // Simulate lookahead steps with multiple simulations\n        for (int sim = 0; sim < NUM_SIMULATIONS; ++sim) {\n            Grid lookahead_grid = grids[i];\n            for (int step = 0; step < LOOKAHEAD_STEPS && step < remaining_flavors.size(); ++step) {\n                // Place the next candy in a random empty cell\n                vector<pair<int, int>> empty_cells;\n                for (int row = 0; row < GRID_SIZE; ++row) {\n                    for (int col = 0; col < GRID_SIZE; ++col) {\n                        if (lookahead_grid.cells[row][col] == 0) {\n                            empty_cells.emplace_back(row, col);\n                        }\n                    }\n                }\n\n                if (!empty_cells.empty()) {\n                    random_device rd;\n                    mt19937 gen(rd());\n                    uniform_int_distribution<> dis(0, empty_cells.size() - 1);\n                    auto [row, col] = empty_cells[dis(gen)];\n                    lookahead_grid.place_candy(remaining_flavors[step], row, col);\n\n                    // Choose a random tilt direction for the next step\n                    uniform_int_distribution<> tilt_dis(0, 3);\n                    lookahead_grid.tilt(static_cast<Direction>(tilt_dis(gen)));\n                }\n            }\n            scores[i] += lookahead_grid.calculate_score();\n        }\n    }\n\n    int max_score = *max_element(scores.begin(), scores.end());\n    vector<Direction> best_directions;\n\n    for (int i = 0; i < 4; ++i) {\n        if (scores[i] == max_score) {\n            best_directions.push_back(static_cast<Direction>(i));\n        }\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, best_directions.size() - 1);\n\n    return best_directions[dis(gen)];\n}\n\nint main() {\n    vector<int> flavors(NUM_CANDIES);\n    for (int& flavor : flavors) {\n        cin >> flavor;\n    }\n\n    Grid grid;\n    for (int t = 0; t < NUM_CANDIES; ++t) {\n        int p;\n        cin >> p;\n\n        int empty_cell = 0;\n        for (int row = 0; row < GRID_SIZE; ++row) {\n            for (int col = 0; col < GRID_SIZE; ++col) {\n                if (grid.cells[row][col] == 0) {\n                    empty_cell++;\n                    if (empty_cell == p) {\n                        grid.place_candy(flavors[t], row, col);\n                        break;\n                    }\n                }\n            }\n            if (empty_cell == p) {\n                break;\n            }\n        }\n\n        if (t < NUM_CANDIES - 1) {\n            vector<int> remaining_flavors(flavors.begin() + t + 1, flavors.end());\n            Direction dir = choose_direction(grid, flavors[t], remaining_flavors);\n            grid.tilt(dir);\n\n            switch (dir) {\n                case FORWARD:\n                    cout << \"F\" << endl;\n                    break;\n                case BACKWARD:\n                    cout << \"B\" << endl;\n                    break;\n                case LEFT:\n                    cout << \"L\" << endl;\n                    break;\n                case RIGHT:\n                    cout << \"R\" << endl;\n                    break;\n            }\n            cout.flush();\n        }\n    }\n\n    return 0;\n}","ahc016":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int MAX_N = 100;\nconst int MAX_M = 100;\nconst int MAX_QUERIES = 100;\n\nmt19937 rng(random_device{}());\n\nint M;\ndouble epsilon;\nint N;\nvector<vector<vector<bool>>> G;\nvector<vector<bool>> H;\n\nvoid generate_graphs() {\n    // Use a combination of edge patterns and vertex orderings to encode numbers\n    for (int k = 0; k < M; ++k) {\n        vector<vector<bool>> graph(N, vector<bool>(N, false));\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                // Use a combination of edge patterns to encode the number k\n                if ((k & (1 << (i + j))) != 0) {\n                    graph[i][j] = true;\n                    graph[j][i] = true;\n                }\n            }\n        }\n        G.push_back(graph);\n    }\n}\n\nvoid output_graphs() {\n    cout << N << endl;\n    for (const auto& graph : G) {\n        string s;\n        for (int i = 0; i < N; ++i) {\n            for (int j = i + 1; j < N; ++j) {\n                s += graph[i][j] ? '1' : '0';\n            }\n        }\n        cout << s << endl;\n    }\n    cout.flush();\n}\n\nvoid read_graph() {\n    string s;\n    cin >> s;\n    H.assign(N, vector<bool>(N, false));\n    int idx = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            H[i][j] = (s[idx++] == '1');\n            H[j][i] = H[i][j];\n        }\n    }\n}\n\nint calculate_similarity(const vector<vector<bool>>& a, const vector<vector<bool>>& b) {\n    int similarity = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = i + 1; j < N; ++j) {\n            if (a[i][j] == b[i][j]) {\n                similarity++;\n            }\n        }\n    }\n    return similarity;\n}\n\nint predict_graph() {\n    int best_match = -1;\n    int max_similarity = -1;\n    for (int k = 0; k < M; ++k) {\n        int similarity = calculate_similarity(H, G[k]);\n        if (similarity > max_similarity) {\n            max_similarity = similarity;\n            best_match = k;\n        }\n    }\n    return best_match;\n}\n\nint main() {\n    cin >> M >> epsilon;\n    N = 20; // Choose a reasonable N within the constraints\n\n    generate_graphs();\n    output_graphs();\n\n    for (int q = 0; q < MAX_QUERIES; ++q) {\n        read_graph();\n        int t = predict_graph();\n        cout << t << endl;\n        cout.flush();\n    }\n\n    return 0;\n}","ahc017":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <limits>\n#include <unordered_map>\n#include <unordered_set>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v, w;\n    int day;\n    bool operator<(const Edge& other) const {\n        return w > other.w;\n    }\n};\n\nstruct Vertex {\n    int id;\n    double betweenness;\n    Vertex(int id) : id(id), betweenness(0.0) {}\n};\n\nclass Graph {\nprivate:\n    int N, M, D, K;\n    vector<vector<pair<int, int>>> adj;\n    vector<Edge> edges;\n    vector<Vertex> vertices;\n\n    void computeBetweennessCentrality() {\n        for (int s = 0; s < N; ++s) {\n            vector<int> numSP(N, 0);\n            vector<double> bc(N, 0.0);\n            vector<vector<int>> predecessors(N);\n            vector<int> stack;\n            vector<int> sigma(N, 0);\n            vector<int> distance(N, -1);\n\n            queue<int> q;\n            q.push(s);\n            sigma[s] = 1;\n            distance[s] = 0;\n\n            while (!q.empty()) {\n                int v = q.front();\n                q.pop();\n                stack.push_back(v);\n                for (const auto& neighbor : adj[v]) {\n                    int w = neighbor.first;\n                    if (distance[w] < 0) {\n                        q.push(w);\n                        distance[w] = distance[v] + 1;\n                    }\n                    if (distance[w] == distance[v] + 1) {\n                        sigma[w] += sigma[v];\n                        predecessors[w].push_back(v);\n                    }\n                }\n            }\n\n            while (!stack.empty()) {\n                int w = stack.back();\n                stack.pop_back();\n                for (int v : predecessors[w]) {\n                    bc[v] += (sigma[v] / static_cast<double>(sigma[w])) * (1.0 + bc[w]);\n                }\n                if (w != s) {\n                    vertices[w].betweenness += bc[w];\n                }\n            }\n        }\n    }\n\n    void prioritizeEdges() {\n        computeBetweennessCentrality();\n        sort(edges.begin(), edges.end(), [this](const Edge& a, const Edge& b) {\n            double a_betweenness = vertices[a.u].betweenness + vertices[a.v].betweenness;\n            double b_betweenness = vertices[b.u].betweenness + vertices[b.v].betweenness;\n            return a_betweenness > b_betweenness;\n        });\n    }\n\n    void assignDays() {\n        vector<int> dayCounts(D, 0);\n        for (auto& edge : edges) {\n            int bestDay = -1;\n            double minIncrease = numeric_limits<double>::max();\n            for (int day = 0; day < D; ++day) {\n                if (dayCounts[day] >= K) continue;\n                double increase = calculateFrustrationIncrease(edge, day);\n                if (increase < minIncrease) {\n                    minIncrease = increase;\n                    bestDay = day;\n                }\n            }\n            edge.day = bestDay;\n            dayCounts[bestDay]++;\n        }\n    }\n\n    double calculateFrustrationIncrease(const Edge& edge, int day) {\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            for (const auto& neighbor : adj[i]) {\n                int v = neighbor.first;\n                int w = neighbor.second;\n                dist[i][v] = min(dist[i][v], w);\n            }\n        }\n\n        for (int k = 0; k < N; ++k) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (dist[i][k] != numeric_limits<int>::max() && dist[k][j] != numeric_limits<int>::max()) {\n                        dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n                    }\n                }\n            }\n        }\n\n        vector<vector<int>> newDist = dist;\n        newDist[edge.u][edge.v] = numeric_limits<int>::max();\n        newDist[edge.v][edge.u] = numeric_limits<int>::max();\n\n        for (int k = 0; k < N; ++k) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (newDist[i][k] != numeric_limits<int>::max() && newDist[k][j] != numeric_limits<int>::max()) {\n                        newDist[i][j] = min(newDist[i][j], newDist[i][k] + newDist[k][j]);\n                    }\n                }\n            }\n        }\n\n        double totalIncrease = 0.0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (i != j) {\n                    int originalDist = dist[i][j];\n                    int newDistVal = newDist[i][j];\n                    if (newDistVal == numeric_limits<int>::max()) {\n                        newDistVal = 1e9;\n                    }\n                    totalIncrease += (newDistVal - originalDist);\n                }\n            }\n        }\n\n        return totalIncrease / (N * (N - 1));\n    }\n\npublic:\n    Graph(int N, int M, int D, int K) : N(N), M(M), D(D), K(K), adj(N), vertices(N) {\n        for (int i = 0; i < N; ++i) {\n            vertices[i].id = i;\n        }\n    }\n\n    void addEdge(int u, int v, int w) {\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n        edges.push_back({u, v, w, -1});\n    }\n\n    void solve() {\n        prioritizeEdges();\n        assignDays();\n    }\n\n    void printSolution() {\n        for (const auto& edge : edges) {\n            cout << edge.day + 1 << \" \";\n        }\n        cout << endl;\n    }\n};\n\nint main() {\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n\n    Graph graph(N, M, D, K);\n\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        graph.addEdge(u - 1, v - 1, w);\n    }\n\n    // Skip reading the coordinates if not needed\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    graph.solve();\n    graph.printSolution();\n\n    return 0;\n}","ahc019":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <cmath>\n#include <numeric>\n#include <atcoder/all>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Block {\n    vector<vector<vector<bool>>> shape;\n    int volume;\n\n    Block(const vector<vector<vector<bool>>>& s) : shape(s) {\n        volume = 0;\n        for (const auto& layer : shape) {\n            for (const auto& row : layer) {\n                for (bool cell : row) {\n                    if (cell) volume++;\n                }\n            }\n        }\n    }\n\n    void rotateX() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[x][D - 1 - z][y] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n\n    void rotateY() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[z][y][D - 1 - x] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n\n    void rotateZ() {\n        int D = shape.size();\n        vector<vector<vector<bool>>> newShape(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                for (int z = 0; z < D; ++z) {\n                    newShape[D - 1 - y][x][z] = shape[x][y][z];\n                }\n            }\n        }\n        shape = newShape;\n    }\n};\n\nstruct Individual {\n    vector<Block> blocks;\n    vector<vector<vector<int>>> arrangement1;\n    vector<vector<vector<int>>> arrangement2;\n    double fitness;\n\n    Individual(const vector<Block>& b, int D) : blocks(b) {\n        arrangement1 = vector<vector<vector<int>>>(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        arrangement2 = vector<vector<vector<int>>>(D, vector<vector<int>>(D, vector<int>(D, 0)));\n        fitness = 0.0;\n    }\n};\n\nvector<Block> generateInitialBlocks(int D) {\n    vector<Block> blocks;\n    // Generate some initial blocks, e.g., single cubes, 2x2x2 cubes, etc.\n    // This is a placeholder; actual block generation should be more sophisticated.\n    vector<vector<vector<bool>>> singleCube(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    singleCube[0][0][0] = true;\n    blocks.emplace_back(singleCube);\n\n    vector<vector<vector<bool>>> twoCube(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    twoCube[0][0][0] = true;\n    twoCube[0][0][1] = true;\n    blocks.emplace_back(twoCube);\n\n    return blocks;\n}\n\nvector<vector<vector<bool>>> createSilhouette(int D, const vector<string>& f, const vector<string>& r) {\n    vector<vector<vector<bool>>> silhouette(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    for (int z = 0; z < D; ++z) {\n        for (int x = 0; x < D; ++x) {\n            for (int y = 0; y < D; ++y) {\n                if (f[z][x] == '1' && r[z][y] == '1') {\n                    silhouette[x][y][z] = true;\n                }\n            }\n        }\n    }\n    return silhouette;\n}\n\ndouble evaluateFitness(const Individual& ind, const vector<vector<vector<bool>>>& silhouette1, const vector<vector<vector<bool>>>& silhouette2) {\n    int D = silhouette1.size();\n    double fitness = 0.0;\n\n    // Check silhouette1\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 (silhouette1[x][y][z]) {\n                    bool covered = false;\n                    for (const auto& block : ind.blocks) {\n                        if (ind.arrangement1[x][y][z] != 0) {\n                            covered = true;\n                            break;\n                        }\n                    }\n                    if (!covered) fitness += 1.0;\n                }\n            }\n        }\n    }\n\n    // Check silhouette2\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 (silhouette2[x][y][z]) {\n                    bool covered = false;\n                    for (const auto& block : ind.blocks) {\n                        if (ind.arrangement2[x][y][z] != 0) {\n                            covered = true;\n                            break;\n                        }\n                    }\n                    if (!covered) fitness += 1.0;\n                }\n            }\n        }\n    }\n\n    // Penalize unused blocks\n    unordered_set<int> usedBlocks1, usedBlocks2;\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 (ind.arrangement1[x][y][z] != 0) usedBlocks1.insert(ind.arrangement1[x][y][z]);\n                if (ind.arrangement2[x][y][z] != 0) usedBlocks2.insert(ind.arrangement2[x][y][z]);\n            }\n        }\n    }\n    for (int i = 1; i <= ind.blocks.size(); ++i) {\n        if (usedBlocks1.find(i) == usedBlocks1.end() && usedBlocks2.find(i) == usedBlocks2.end()) {\n            fitness += ind.blocks[i - 1].volume;\n        }\n    }\n\n    // Penalize blocks used in both arrangements\n    unordered_set<int> commonBlocks;\n    for (int block : usedBlocks1) {\n        if (usedBlocks2.find(block) != usedBlocks2.end()) {\n            commonBlocks.insert(block);\n        }\n    }\n    for (int block : commonBlocks) {\n        fitness += 1.0 / ind.blocks[block - 1].volume;\n    }\n\n    return fitness;\n}\n\nIndividual geneticAlgorithm(int D, const vector<vector<vector<bool>>>& silhouette1, const vector<vector<vector<bool>>>& silhouette2, int populationSize, int generations) {\n    vector<Block> initialBlocks = generateInitialBlocks(D);\n    vector<Individual> population;\n    for (int i = 0; i < populationSize; ++i) {\n        population.emplace_back(initialBlocks, D);\n    }\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> blockDist(0, initialBlocks.size() - 1);\n    uniform_int_distribution<> posDist(0, D - 1);\n\n    for (int gen = 0; gen < generations; ++gen) {\n        // Evaluate fitness\n        for (auto& ind : population) {\n            ind.fitness = evaluateFitness(ind, silhouette1, silhouette2);\n        }\n\n        // Sort by fitness\n        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n            return a.fitness < b.fitness;\n        });\n\n        // Select top individuals\n        vector<Individual> newPopulation;\n        for (int i = 0; i < populationSize / 2; ++i) {\n            newPopulation.push_back(population[i]);\n        }\n\n        // Crossover and mutation\n        while (newPopulation.size() < populationSize) {\n            Individual parent1 = population[rand() % (populationSize / 2)];\n            Individual parent2 = population[rand() % (populationSize / 2)];\n            Individual child(parent1.blocks, D);\n\n            // Crossover: randomly select arrangements from parents\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 (rand() % 2) {\n                            child.arrangement1[x][y][z] = parent1.arrangement1[x][y][z];\n                            child.arrangement2[x][y][z] = parent1.arrangement2[x][y][z];\n                        } else {\n                            child.arrangement1[x][y][z] = parent2.arrangement1[x][y][z];\n                            child.arrangement2[x][y][z] = parent2.arrangement2[x][y][z];\n                        }\n                    }\n                }\n            }\n\n            // Mutation: randomly change some blocks\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 (rand() % 100 < 5) { // 5% mutation rate\n                            child.arrangement1[x][y][z] = blockDist(gen) + 1;\n                            child.arrangement2[x][y][z] = blockDist(gen) + 1;\n                        }\n                    }\n                }\n            }\n\n            newPopulation.push_back(child);\n        }\n\n        population = newPopulation;\n    }\n\n    // Return the best individual\n    sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n        return a.fitness < b.fitness;\n    });\n\n    return population[0];\n}\n\nint main() {\n    int D;\n    cin >> D;\n\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for (int i = 0; i < D; ++i) cin >> f1[i];\n    for (int i = 0; i < D; ++i) cin >> r1[i];\n    for (int i = 0; i < D; ++i) cin >> f2[i];\n    for (int i = 0; i < D; ++i) cin >> r2[i];\n\n    vector<vector<vector<bool>>> silhouette1 = createSilhouette(D, f1, r1);\n    vector<vector<vector<bool>>> silhouette2 = createSilhouette(D, f2, r2);\n\n    Individual bestIndividual = geneticAlgorithm(D, silhouette1, silhouette2, 50, 100);\n\n    // Output the best individual\n    int n = bestIndividual.blocks.size();\n    cout << n << endl;\n\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                cout << bestIndividual.arrangement1[x][y][z] << \" \";\n            }\n        }\n    }\n    cout << endl;\n\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                cout << bestIndividual.arrangement2[x][y][z] << \" \";\n            }\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc020":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <limits>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\nusing namespace std;\nusing namespace boost;\n\ntypedef adjacency_list<vecS, vecS, undirectedS,\n                       no_property,\n                       property<edge_weight_t, int> > Graph;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef graph_traits<Graph>::edge_descriptor Edge;\ntypedef graph_traits<Graph>::edge_iterator EdgeIterator;\ntypedef graph_traits<Graph>::vertex_iterator VertexIterator;\n\nstruct Point {\n    int x, y;\n    Point() : x(0), y(0) {} // Default constructor\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Resident {\n    int a, b;\n    Resident() : a(0), b(0) {} // Default constructor\n    Resident(int a, int b) : a(a), b(b) {}\n};\n\nstruct EdgeInfo {\n    int u, v, w;\n    EdgeInfo() : u(0), v(0), w(0) {} // Default constructor\n    EdgeInfo(int u, int v, int w) : u(u), v(v), w(w) {}\n};\n\n// Custom hash function for Edge\nstruct EdgeHash {\n    size_t operator()(const Edge& e) const {\n        return std::hash<size_t>()(e.m_source) ^ std::hash<size_t>()(e.m_target);\n    }\n};\n\nint main() {\n    int N, M, K;\n    cin >> N >> M >> K;\n\n    vector<Point> stations(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> stations[i].x >> stations[i].y;\n    }\n\n    vector<EdgeInfo> edges(M);\n    for (int j = 0; j < M; ++j) {\n        cin >> edges[j].u >> edges[j].v >> edges[j].w;\n        edges[j].u--; // Convert to 0-based index\n        edges[j].v--;\n    }\n\n    vector<Resident> residents(K);\n    for (int k = 0; k < K; ++k) {\n        cin >> residents[k].a >> residents[k].b;\n    }\n\n    // Build the graph\n    Graph g(N);\n    vector<Edge> edge_map(M);\n    for (int j = 0; j < M; ++j) {\n        edge_map[j] = add_edge(edges[j].u, edges[j].v, edges[j].w, g).first;\n    }\n\n    // Find the Minimum Spanning Tree (MST)\n    vector<Edge> mst_edges;\n    kruskal_minimum_spanning_tree(g, back_inserter(mst_edges));\n\n    // Create a subgraph with MST edges\n    Graph mst(N);\n    for (const auto& e : mst_edges) {\n        add_edge(source(e, g), target(e, g), get(edge_weight, g, e), mst);\n    }\n\n    // Calculate the minimum output strength for each station\n    vector<int> P(N, 0);\n    for (int i = 0; i < N; ++i) {\n        double max_dist = 0.0;\n        for (const auto& resident : residents) {\n            double dist = sqrt(pow(stations[i].x - resident.a, 2) + pow(stations[i].y - resident.b, 2));\n            if (dist > max_dist) {\n                max_dist = dist;\n            }\n        }\n        P[i] = static_cast<int>(ceil(max_dist));\n        // Cap the output strength at 5000\n        if (P[i] > 5000) {\n            P[i] = 5000;\n        }\n    }\n\n    // Ensure all residents are covered\n    std::unordered_set<int> covered_residents;\n    for (int i = 0; i < N; ++i) {\n        for (int k = 0; k < K; ++k) {\n            double dist = sqrt(pow(stations[i].x - residents[k].a, 2) + pow(stations[i].y - residents[k].b, 2));\n            if (dist <= P[i]) {\n                covered_residents.insert(k);\n            }\n        }\n    }\n\n    // If not all residents are covered, increase the output strength of the nearest station\n    while (static_cast<int>(covered_residents.size()) < K) {\n        for (int k = 0; k < K; ++k) {\n            if (covered_residents.find(k) == covered_residents.end()) {\n                double min_dist = numeric_limits<double>::max();\n                int nearest_station = -1;\n                for (int i = 0; i < N; ++i) {\n                    double dist = sqrt(pow(stations[i].x - residents[k].a, 2) + pow(stations[i].y - residents[k].b, 2));\n                    if (dist < min_dist) {\n                        min_dist = dist;\n                        nearest_station = i;\n                    }\n                }\n                P[nearest_station] = static_cast<int>(ceil(min_dist));\n                // Cap the output strength at 5000\n                if (P[nearest_station] > 5000) {\n                    P[nearest_station] = 5000;\n                }\n                for (int kk = 0; kk < K; ++kk) {\n                    double dist = sqrt(pow(stations[nearest_station].x - residents[kk].a, 2) + pow(stations[nearest_station].y - residents[kk].b, 2));\n                    if (dist <= P[nearest_station]) {\n                        covered_residents.insert(kk);\n                    }\n                }\n            }\n        }\n    }\n\n    // Output the results\n    for (int i = 0; i < N; ++i) {\n        cout << P[i] << \" \";\n    }\n    cout << endl;\n\n    // Create a set of edges in the MST for quick lookup\n    std::unordered_set<Edge, EdgeHash> mst_edge_set;\n    for (const auto& e : mst_edges) {\n        mst_edge_set.insert(e);\n    }\n\n    // Output the power status of each edge\n    for (int j = 0; j < M; ++j) {\n        Edge e = edge(edges[j].u, edges[j].v, g).first;\n        if (mst_edge_set.find(e) != mst_edge_set.end()) {\n            cout << \"1 \";\n        } else {\n            cout << \"0 \";\n        }\n    }\n    cout << endl;\n\n    return 0;\n}","ahc021":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 30;\nconst int MAX_OPERATIONS = 10000;\n\nvector<vector<int>> pyramid;\n\nstruct Operation {\n    int x1, y1, x2, y2;\n};\n\nvector<Operation> operations;\n\nbool is_adjacent(int x1, int y1, int x2, int y2) {\n    if (x1 == x2 - 1 && y1 == y2 - 1) return true;\n    if (x1 == x2 - 1 && y1 == y2) return true;\n    if (x1 == x2 && y1 == y2 - 1) return true;\n    if (x1 == x2 && y1 == y2 + 1) return true;\n    if (x1 == x2 + 1 && y1 == y2) return true;\n    if (x1 == x2 + 1 && y1 == y2 + 1) return true;\n    return false;\n}\n\nvoid swap_balls(int x1, int y1, int x2, int y2) {\n    swap(pyramid[x1][y1], pyramid[x2][y2]);\n    operations.push_back({x1, y1, x2, y2});\n}\n\nint count_violations() {\n    int violations = 0;\n    for (int x = 0; x < N - 1; ++x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] > pyramid[x + 1][y]) violations++;\n            if (pyramid[x][y] > pyramid[x + 1][y + 1]) violations++;\n        }\n    }\n    return violations;\n}\n\nvoid greedy_algorithm() {\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            if (pyramid[x][y] > pyramid[x + 1][y]) {\n                if (is_adjacent(x, y, x + 1, y)) {\n                    swap_balls(x, y, x + 1, y);\n                } else {\n                    // Find a path to swap\n                    // This is a simplified approach; a more sophisticated pathfinding algorithm can be used here\n                    for (int i = x + 1; i < N; ++i) {\n                        if (is_adjacent(i, y, i + 1, y)) {\n                            swap_balls(i, y, i + 1, y);\n                        }\n                    }\n                }\n            }\n            if (pyramid[x][y] > pyramid[x + 1][y + 1]) {\n                if (is_adjacent(x, y, x + 1, y + 1)) {\n                    swap_balls(x, y, x + 1, y + 1);\n                } else {\n                    // Find a path to swap\n                    // This is a simplified approach; a more sophisticated pathfinding algorithm can be used here\n                    for (int i = x + 1; i < N; ++i) {\n                        if (is_adjacent(i, y + 1, i + 1, y + 1)) {\n                            swap_balls(i, y + 1, i + 1, y + 1);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid simulated_annealing() {\n    int current_violations = count_violations();\n    if (current_violations == 0) return;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    double temperature = 1.0;\n    double cooling_rate = 0.999;\n    int max_iterations = 10000;\n\n    for (int iter = 0; iter < max_iterations && current_violations > 0; ++iter) {\n        // Randomly select two adjacent balls to swap\n        int x1 = dis(gen) * N;\n        int y1 = dis(gen) * (x1 + 1);\n        int direction = dis(gen) * 6;\n\n        int x2, y2;\n        switch (direction) {\n            case 0: x2 = x1 - 1; y2 = y1 - 1; break;\n            case 1: x2 = x1 - 1; y2 = y1; break;\n            case 2: x2 = x1; y2 = y1 - 1; break;\n            case 3: x2 = x1; y2 = y1 + 1; break;\n            case 4: x2 = x1 + 1; y2 = y1; break;\n            case 5: x2 = x1 + 1; y2 = y1 + 1; break;\n        }\n\n        if (x2 < 0 || x2 >= N || y2 < 0 || y2 > x2) continue;\n\n        swap_balls(x1, y1, x2, y2);\n        int new_violations = count_violations();\n\n        if (new_violations < current_violations) {\n            current_violations = new_violations;\n        } else {\n            double probability = exp((current_violations - new_violations) / temperature);\n            if (dis(gen) > probability) {\n                swap_balls(x1, y1, x2, y2); // Revert the swap\n            } else {\n                current_violations = new_violations;\n            }\n        }\n\n        temperature *= cooling_rate;\n    }\n}\n\nint main() {\n    pyramid.resize(N);\n    for (int x = 0; x < N; ++x) {\n        pyramid[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> pyramid[x][y];\n        }\n    }\n\n    greedy_algorithm();\n    simulated_annealing();\n\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.x1 << \" \" << op.y1 << \" \" << op.x2 << \" \" << op.y2 << 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#include <utility>\n#include <cmath>\n\nusing namespace std;\n\nconst int D = 9;\nconst int ENTRANCE_I = 0;\nconst int ENTRANCE_J = (D - 1) / 2;\n\nstruct Point {\n    int i, j;\n    Point(int i, int j) : i(i), j(j) {}\n    bool operator==(const Point& other) const {\n        return i == other.i && j == other.j;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.i) ^ hash<int>()(p.j);\n        }\n    };\n}\n\nvector<Point> get_neighbors(const Point& p, const unordered_set<Point>& obstacles) {\n    vector<Point> neighbors;\n    int di[] = {-1, 1, 0, 0};\n    int dj[] = {0, 0, -1, 1};\n    for (int k = 0; k < 4; ++k) {\n        Point neighbor(p.i + di[k], p.j + dj[k]);\n        if (neighbor.i >= 0 && neighbor.i < D && neighbor.j >= 0 && neighbor.j < D &&\n            obstacles.find(neighbor) == obstacles.end()) {\n            neighbors.push_back(neighbor);\n        }\n    }\n    return neighbors;\n}\n\nvector<vector<int>> bfs(const unordered_set<Point>& obstacles) {\n    vector<vector<int>> distance(D, vector<int>(D, -1));\n    queue<Point> q;\n    Point entrance(ENTRANCE_I, ENTRANCE_J);\n    distance[entrance.i][entrance.j] = 0;\n    q.push(entrance);\n\n    while (!q.empty()) {\n        Point current = q.front();\n        q.pop();\n        for (const Point& neighbor : get_neighbors(current, obstacles)) {\n            if (distance[neighbor.i][neighbor.j] == -1) {\n                distance[neighbor.i][neighbor.j] = distance[current.i][current.j] + 1;\n                q.push(neighbor);\n            }\n        }\n    }\n    return distance;\n}\n\nPoint find_storage_location(const unordered_set<Point>& obstacles, const vector<vector<int>>& distance, const unordered_set<Point>& occupied) {\n    vector<Point> candidates;\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            Point p(i, j);\n            if (distance[i][j] != -1 && obstacles.find(p) == obstacles.end() && occupied.find(p) == occupied.end()) {\n                candidates.push_back(p);\n            }\n        }\n    }\n    if (candidates.empty()) {\n        return Point(-1, -1); // No valid storage location\n    }\n    // Sort candidates by distance from entrance and then by some heuristic\n    sort(candidates.begin(), candidates.end(), [&distance](const Point& a, const Point& b) {\n        return distance[a.i][a.j] < distance[b.i][b.j];\n    });\n    return candidates[0];\n}\n\nvector<Point> find_retrieval_order(const unordered_set<Point>& obstacles, const vector<vector<Point>>& storage_order) {\n    vector<vector<int>> distance = bfs(obstacles);\n    unordered_set<Point> occupied;\n    for (const auto& row : storage_order) {\n        for (const Point& p : row) {\n            if (p.i != -1 && p.j != -1) {\n                occupied.insert(p);\n            }\n        }\n    }\n    vector<Point> retrieval_order;\n    while (!occupied.empty()) {\n        vector<Point> candidates;\n        for (const Point& p : occupied) {\n            if (distance[p.i][p.j] != -1) {\n                candidates.push_back(p);\n            }\n        }\n        if (candidates.empty()) {\n            break; // No more reachable containers\n        }\n        // Sort candidates by distance from entrance and then by some heuristic\n        sort(candidates.begin(), candidates.end(), [&distance](const Point& a, const Point& b) {\n            return distance[a.i][a.j] < distance[b.i][b.j];\n        });\n        Point next = candidates[0];\n        retrieval_order.push_back(next);\n        occupied.erase(next);\n        // Update distance for adjacent squares\n        for (const Point& neighbor : get_neighbors(next, obstacles)) {\n            if (occupied.find(neighbor) == occupied.end()) {\n                distance[neighbor.i][neighbor.j] = -1;\n            }\n        }\n    }\n    return retrieval_order;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    unordered_set<Point> obstacles;\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        obstacles.insert(Point(ri, rj));\n    }\n    vector<vector<int>> distance = bfs(obstacles);\n    unordered_set<Point> occupied;\n    vector<vector<Point>> storage_order(D, vector<Point>(D, Point(-1, -1)));\n    for (int d = 0; d < D * D - 1 - N; ++d) {\n        int t_d;\n        cin >> t_d;\n        Point storage_location = find_storage_location(obstacles, distance, occupied);\n        if (storage_location.i == -1 && storage_location.j == -1) {\n            cerr << \"No valid storage location found for container \" << t_d << endl;\n            return 1;\n        }\n        storage_order[storage_location.i][storage_location.j] = Point(t_d, d);\n        occupied.insert(storage_location);\n        cout << storage_location.i << \" \" << storage_location.j << endl;\n        cout.flush();\n    }\n    vector<Point> retrieval_order = find_retrieval_order(obstacles, storage_order);\n    for (const Point& p : retrieval_order) {\n        cout << p.i << \" \" << p.j << endl;\n    }\n    return 0;\n}","ahc024":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <unordered_set>\n#include <algorithm>\n#include <atcoder/dsu>\n#include <atcoder/maxflow>\n\nusing namespace std;\nusing namespace atcoder;\n\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nvector<vector<int>> grid;\nvector<vector<int>> simplified_grid;\nint n, m;\n\nvoid bfs(int x, int y, int color, vector<vector<bool>>& visited) {\n    queue<Point> q;\n    q.push(Point(x, y));\n    visited[x][y] = true;\n    simplified_grid[x][y] = color;\n\n    while (!q.empty()) {\n        Point p = q.front();\n        q.pop();\n\n        for (int i = 0; i < 4; ++i) {\n            int nx = p.x + dx[i];\n            int ny = p.y + dy[i];\n\n            if (nx >= 0 && nx < n && ny >= 0 && ny < n && !visited[nx][ny] && grid[nx][ny] == color) {\n                visited[nx][ny] = true;\n                simplified_grid[nx][ny] = color;\n                q.push(Point(nx, ny));\n            }\n        }\n    }\n}\n\nvoid simplify_map() {\n    simplified_grid = vector<vector<int>>(n, vector<int>(n, 0));\n    vector<vector<bool>> visited(n, vector<bool>(n, false));\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (!visited[i][j] && grid[i][j] != 0) {\n                bfs(i, j, grid[i][j], visited);\n            }\n        }\n    }\n}\n\nvoid connect_components() {\n    dsu d(n * n);\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] != 0) {\n                for (int k = 0; k < 4; ++k) {\n                    int ni = i + dx[k];\n                    int nj = j + dy[k];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && simplified_grid[ni][nj] != 0) {\n                        d.merge(i * n + j, ni * n + nj);\n                    }\n                }\n            }\n        }\n    }\n\n    unordered_map<int, vector<Point>> components;\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] != 0) {\n                components[d.leader(i * n + j)].push_back(Point(i, j));\n            }\n        }\n    }\n\n    for (auto& [leader, points] : components) {\n        for (auto& p : points) {\n            simplified_grid[p.x][p.y] = simplified_grid[points[0].x][points[0].y];\n        }\n    }\n}\n\nvoid minimize_connectors() {\n    // This is a placeholder for a more sophisticated heuristic\n    // For simplicity, we'll just ensure that the connectors are minimal\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (simplified_grid[i][j] == 0) {\n                bool is_connector = false;\n                for (int k = 0; k < 4; ++k) {\n                    int ni = i + dx[k];\n                    int nj = j + dy[k];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && simplified_grid[ni][nj] != 0) {\n                        is_connector = true;\n                        break;\n                    }\n                }\n                if (!is_connector) {\n                    simplified_grid[i][j] = 0;\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    cin >> n >> m;\n    grid.resize(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    simplify_map();\n    connect_components();\n    minimize_connectors();\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cout << simplified_grid[i][j] << (j == n - 1 ? \"\\n\" : \" \");\n        }\n    }\n\n    return 0;\n}","ahc025":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <random>\n#include <cmath>\n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <iomanip>\n#include <climits>\n#include <cfloat>\n#include <cstring>\n#include <cassert>\n#include <chrono>\n#include <fstream>\n#include <sstream>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<pii> vpii;\ntypedef vector<pll> vpll;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef vector<vpii> vvpii;\ntypedef vector<vpll> vvpll;\ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\ntypedef tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;\n\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define lb lower_bound\n#define ub upper_bound\n\nconst int INF = 1e9;\nconst ll LINF = 1e18;\nconst ld EPS = 1e-9;\nconst int MOD = 1e9 + 7;\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint n, d, q;\nvector<double> weights;\nvector<int> groups;\n\nchar compare(const vector<int>& l, const vector<int>& r) {\n    cout << l.size() << \" \" << r.size();\n    for (int i : l) cout << \" \" << i;\n    for (int i : r) cout << \" \" << i;\n    cout << endl;\n    char res;\n    cin >> res;\n    return res;\n}\n\nvoid estimate_weights() {\n    weights.resize(n, 0.0);\n    for (int i = 0; i < n; ++i) {\n        for (int j = i + 1; j < n; ++j) {\n            char res = compare({i}, {j});\n            if (res == '<') {\n                weights[j] += 1.0;\n            } else if (res == '>') {\n                weights[i] += 1.0;\n            } else {\n                weights[i] += 0.5;\n                weights[j] += 0.5;\n            }\n        }\n    }\n}\n\nvoid assign_groups() {\n    groups.resize(n, 0);\n    vector<double> group_weights(d, 0.0);\n    for (int i = 0; i < n; ++i) {\n        int best_group = 0;\n        double min_diff = fabs(group_weights[0] - weights[i]);\n        for (int j = 1; j < d; ++j) {\n            double diff = fabs(group_weights[j] - weights[i]);\n            if (diff < min_diff) {\n                min_diff = diff;\n                best_group = j;\n            }\n        }\n        groups[i] = best_group;\n        group_weights[best_group] += weights[i];\n    }\n}\n\nvoid refine_weights() {\n    for (int i = 0; i < n; ++i) {\n        for (int j = i + 1; j < n; ++j) {\n            if (groups[i] != groups[j]) {\n                char res = compare({i}, {j});\n                if (res == '<') {\n                    weights[j] += 1.0;\n                } else if (res == '>') {\n                    weights[i] += 1.0;\n                } else {\n                    weights[i] += 0.5;\n                    weights[j] += 0.5;\n                }\n            }\n        }\n    }\n}\n\nvoid solve() {\n    estimate_weights();\n    assign_groups();\n    refine_weights();\n    assign_groups();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> n >> d >> q;\n    solve();\n\n    for (int i = 0; i < n; ++i) {\n        cout << groups[i] << \" \";\n    }\n    cout << endl;\n\n    return 0;\n}","ahc026":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cassert>\n\nusing namespace std;\n\nconst int n = 200;\nconst int m = 10;\nconst int max_operations = 5000;\n\nvector<vector<int>> stacks(m, vector<int>(n / m));\n\nvoid read_input() {\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < n / m; ++j) {\n            cin >> stacks[i][j];\n        }\n    }\n}\n\nint find_stack(int v) {\n    for (int i = 0; i < m; ++i) {\n        for (int j = 0; j < stacks[i].size(); ++j) {\n            if (stacks[i][j] == v) {\n                return i;\n            }\n        }\n    }\n    return -1;\n}\n\nint find_position(int i, int v) {\n    for (int j = 0; j < stacks[i].size(); ++j) {\n        if (stacks[i][j] == v) {\n            return j;\n        }\n    }\n    return -1;\n}\n\nvoid move_box(int v, int dest_stack) {\n    int src_stack = find_stack(v);\n    int pos = find_position(src_stack, v);\n\n    vector<int> moved_boxes(stacks[src_stack].begin() + pos, stacks[src_stack].end());\n    stacks[src_stack].erase(stacks[src_stack].begin() + pos, stacks[src_stack].end());\n\n    stacks[dest_stack].insert(stacks[dest_stack].end(), moved_boxes.begin(), moved_boxes.end());\n}\n\nint find_smallest_remaining() {\n    int smallest = n + 1;\n    for (int i = 0; i < m; ++i) {\n        if (!stacks[i].empty()) {\n            smallest = min(smallest, stacks[i][0]);\n        }\n    }\n    return smallest;\n}\n\nbool is_smallest_at_top(int v) {\n    for (int i = 0; i < m; ++i) {\n        if (!stacks[i].empty() && stacks[i][0] == v) {\n            return true;\n        }\n    }\n    return false;\n}\n\nvector<pair<int, int>> solve() {\n    vector<pair<int, int>> operations;\n    int current_smallest = 1;\n\n    while (current_smallest <= n) {\n        if (is_smallest_at_top(current_smallest)) {\n            operations.emplace_back(current_smallest, 0);\n            current_smallest++;\n        } else {\n            int src_stack = find_stack(current_smallest);\n            int dest_stack = -1;\n            int min_size = n + 1;\n\n            for (int i = 0; i < m; ++i) {\n                if (i != src_stack && stacks[i].size() < min_size) {\n                    min_size = stacks[i].size();\n                    dest_stack = i;\n                }\n            }\n\n            if (dest_stack == -1) {\n                // No other stack available, move to any other stack\n                for (int i = 0; i < m; ++i) {\n                    if (i != src_stack) {\n                        dest_stack = i;\n                        break;\n                    }\n                }\n            }\n\n            operations.emplace_back(current_smallest, dest_stack + 1);\n            move_box(current_smallest, dest_stack);\n        }\n    }\n\n    return operations;\n}\n\nint main() {\n    read_input();\n    auto operations = solve();\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 <queue>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Square {\n    int i, j;\n    int dirtiness;\n    bool operator<(const Square& other) const {\n        return dirtiness < other.dirtiness;\n    }\n};\n\nvector<vector<int>> generateRoute(int N, const vector<vector<int>>& h, const vector<vector<int>>& v, const vector<vector<int>>& d) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    vector<vector<int>> route;\n    priority_queue<Square> pq;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            pq.push({i, j, d[i][j]});\n        }\n    }\n\n    auto isValidMove = [&](int i, int j, int di, int dj) {\n        if (di == 0) {\n            if (dj == 1) return j < N - 1 && v[i][j] == 0;\n            else return j > 0 && v[i][j - 1] == 0;\n        } else {\n            if (di == 1) return i < N - 1 && h[i][j] == 0;\n            else return i > 0 && h[i - 1][j] == 0;\n        }\n    };\n\n    auto dfs = [&](auto&& self, int i, int j) -> void {\n        visited[i][j] = true;\n        vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n        vector<char> dirChars = {'R', 'D', 'L', 'U'};\n\n        // Prioritize high-dirtiness squares\n        vector<pair<int, int>> highDirtinessSquares;\n        for (const auto& dir : directions) {\n            int ni = i + dir.first;\n            int nj = j + dir.second;\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj] && isValidMove(i, j, dir.first, dir.second)) {\n                highDirtinessSquares.emplace_back(ni, nj);\n            }\n        }\n        sort(highDirtinessSquares.begin(), highDirtinessSquares.end(), [&](const auto& a, const auto& b) {\n            return d[a.first][a.second] > d[b.first][b.second];\n        });\n\n        for (const auto& sq : highDirtinessSquares) {\n            int ni = sq.first;\n            int nj = sq.second;\n            if (!visited[ni][nj]) {\n                for (size_t k = 0; k < directions.size(); ++k) {\n                    if (ni == i + directions[k].first && nj == j + directions[k].second) {\n                        route.push_back({i, j, ni, nj, dirChars[k]});\n                        break;\n                    }\n                }\n                self(self, ni, nj);\n            }\n        }\n    };\n\n    dfs(dfs, 0, 0);\n\n    // Ensure all squares are visited\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (!visited[i][j]) {\n                // Find a path to the unvisited square\n                vector<vector<int>> dist(N, vector<int>(N, -1));\n                queue<pair<int, int>> q;\n                q.push({i, j});\n                dist[i][j] = 0;\n                vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n\n                while (!q.empty()) {\n                    auto [ci, cj] = q.front();\n                    q.pop();\n                    for (const auto& dir : directions) {\n                        int ni = ci + dir.first;\n                        int nj = cj + dir.second;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist[ni][nj] == -1 && isValidMove(ci, cj, dir.first, dir.second)) {\n                            dist[ni][nj] = dist[ci][cj] + 1;\n                            parent[ni][nj] = {ci, cj};\n                            q.push({ni, nj});\n                        }\n                    }\n                }\n\n                // Reconstruct path\n                vector<pair<int, int>> path;\n                for (int x = 0; x < N; ++x) {\n                    for (int y = 0; y < N; ++y) {\n                        if (visited[x][y]) {\n                            int current_i = x, current_j = y;\n                            while (current_i != -1 && current_j != -1) {\n                                path.emplace_back(current_i, current_j);\n                                auto [pi, pj] = parent[current_i][current_j];\n                                current_i = pi;\n                                current_j = pj;\n                            }\n                            reverse(path.begin(), path.end());\n                            break;\n                        }\n                    }\n                    if (!path.empty()) break;\n                }\n\n                for (size_t k = 1; k < path.size(); ++k) {\n                    auto [pi, pj] = path[k - 1];\n                    auto [ci, cj] = path[k];\n                    for (size_t l = 0; l < directions.size(); ++l) {\n                        if (ci == pi + directions[l].first && cj == pj + directions[l].second) {\n                            route.push_back({pi, pj, ci, cj, dirChars[l]});\n                            break;\n                        }\n                    }\n                }\n                dfs(dfs, i, j);\n            }\n        }\n    }\n\n    // Convert route to string\n    vector<char> result;\n    for (const auto& move : route) {\n        result.push_back(move[4]);\n    }\n\n    // Ensure the route returns to (0, 0)\n    if (route.back()[2] != 0 || route.back()[3] != 0) {\n        // Find a path back to (0, 0)\n        vector<vector<int>> dist(N, vector<int>(N, -1));\n        queue<pair<int, int>> q;\n        q.push({route.back()[2], route.back()[3]});\n        dist[route.back()[2]][route.back()[3]] = 0;\n        vector<vector<pair<int, int>>> parent(N, vector<pair<int, int>>(N, {-1, -1}));\n\n        while (!q.empty()) {\n            auto [ci, cj] = q.front();\n            q.pop();\n            for (const auto& dir : directions) {\n                int ni = ci + dir.first;\n                int nj = cj + dir.second;\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist[ni][nj] == -1 && isValidMove(ci, cj, dir.first, dir.second)) {\n                    dist[ni][nj] = dist[ci][cj] + 1;\n                    parent[ni][nj] = {ci, cj};\n                    q.push({ni, nj});\n                }\n            }\n        }\n\n        // Reconstruct path\n        vector<pair<int, int>> path;\n        int current_i = 0, current_j = 0;\n        while (current_i != -1 && current_j != -1) {\n            path.emplace_back(current_i, current_j);\n            auto [pi, pj] = parent[current_i][current_j];\n            current_i = pi;\n            current_j = pj;\n        }\n        reverse(path.begin(), path.end());\n\n        for (size_t k = 1; k < path.size(); ++k) {\n            auto [pi, pj] = path[k - 1];\n            auto [ci, cj] = path[k];\n            for (size_t l = 0; l < directions.size(); ++l) {\n                if (ci == pi + directions[l].first && cj == pj + directions[l].second) {\n                    result.push_back(dirChars[l]);\n                    break;\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int N;\n    cin >> N;\n\n    vector<vector<int>> h(N - 1, vector<int>(N));\n    for (int i = 0; i < N - 1; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            h[i][j] = row[j] - '0';\n        }\n    }\n\n    vector<vector<int>> v(N, vector<int>(N - 1));\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N - 1; ++j) {\n            v[i][j] = row[j] - '0';\n        }\n    }\n\n    vector<vector<int>> d(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> d[i][j];\n        }\n    }\n\n    vector<char> route = generateRoute(N, h, v, d);\n\n    for (char move : route) {\n        cout << move;\n    }\n    cout << endl;\n\n    return 0;\n}","ahc028":"#include <iostream>\n#include <vector>\n#include <string>\n#include <queue>\n#include <unordered_set>\n#include <unordered_map>\n#include <algorithm>\n#include <climits>\n\nusing namespace std;\n\nstruct State {\n    int i, j;\n    unordered_set<int> included;\n    int cost;\n\n    bool operator>(const State& other) const {\n        return cost > other.cost;\n    }\n};\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    int s_i, s_j;\n    cin >> s_i >> s_j;\n\n    vector<vector<char>> keyboard(N, vector<char>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> keyboard[i][j];\n        }\n    }\n\n    vector<string> t(M);\n    for (int k = 0; k < M; ++k) {\n        cin >> t[k];\n    }\n\n    // Preprocess the positions of each character\n    unordered_map<char, vector<pair<int, int>>> char_positions;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            char_positions[keyboard[i][j]].emplace_back(i, j);\n        }\n    }\n\n    // Priority queue for Dijkstra's algorithm\n    priority_queue<State, vector<State>, greater<State>> pq;\n    pq.push({s_i, s_j, {}, 0});\n\n    // Visited set to avoid revisiting the same state\n    unordered_map<int, unordered_map<int, unordered_set<int>>> visited;\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.included.size() == M) {\n            // Found a solution, output the path\n            // (In a real implementation, you would need to reconstruct the path)\n            // For simplicity, we assume the path is stored and output here\n            cout << \"Solution found with cost \" << current.cost << endl;\n            return 0;\n        }\n\n        if (visited[current.i][current.j].count(current.included.size())) {\n            continue;\n        }\n        visited[current.i][current.j].insert(current.included.size());\n\n        // Explore all possible next characters\n        for (const auto& entry : char_positions) {\n            char c = entry.first;\n            for (const auto& pos : entry.second) {\n                int next_i = pos.first;\n                int next_j = pos.second;\n\n                // Calculate the cost to move to this character\n                int move_cost = abs(next_i - current.i) + abs(next_j - current.j) + 1;\n\n                // Check if adding this character includes any new lucky words\n                unordered_set<int> new_included = current.included;\n                for (int k = 0; k < M; ++k) {\n                    if (new_included.count(k)) continue;\n                    // Check if the new character includes the k-th lucky word\n                    // This is a simplified check; in practice, you would need a more efficient way\n                    // For example, using a suffix automaton or a rolling hash\n                    string s;\n                    // Reconstruct the string from the current state (simplified)\n                    // In a real implementation, you would need to keep track of the string\n                    if (s.find(t[k]) != string::npos) {\n                        new_included.insert(k);\n                    }\n                }\n\n                if (new_included.size() > current.included.size()) {\n                    pq.push({next_i, next_j, new_included, current.cost + move_cost});\n                }\n            }\n        }\n    }\n\n    cout << \"No solution found within the operation limit.\" << endl;\n    return 0;\n}","ahc030":"#include <iostream>\n#include <vector>\n#include <set>\n#include <random>\n#include <cmath>\n#include <algorithm>\n#include <atcoder/random>\n\nusing namespace std;\nusing namespace atcoder;\n\nstruct Square {\n    int i, j;\n    Square(int i, int j) : i(i), j(j) {}\n    bool operator<(const Square& other) const {\n        if (i != other.i) return i < other.i;\n        return j < other.j;\n    }\n};\n\nstruct OilField {\n    vector<Square> squares;\n    int di, dj;\n};\n\nvector<OilField> fields;\nint N, M;\ndouble epsilon;\n\nvoid read_input() {\n    cin >> N >> M >> epsilon;\n    fields.resize(M);\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        fields[k].squares.resize(d);\n        for (int l = 0; l < d; ++l) {\n            cin >> fields[k].squares[l].i >> fields[k].squares[l].j;\n        }\n    }\n}\n\nvoid drill(int i, int j) {\n    cout << \"q 1 \" << i << \" \" << j << endl;\n    cout.flush();\n    int v;\n    cin >> v;\n    // Update the oil reserves for the square (i, j)\n}\n\nint divinate(const vector<Square>& squares) {\n    cout << \"q \" << squares.size();\n    for (const auto& sq : squares) {\n        cout << \" \" << sq.i << \" \" << sq.j;\n    }\n    cout << endl;\n    cout.flush();\n    int v;\n    cin >> v;\n    return v;\n}\n\nvoid guess(const set<Square>& squares) {\n    cout << \"a \" << squares.size();\n    for (const auto& sq : squares) {\n        cout << \" \" << sq.i << \" \" << sq.j;\n    }\n    cout << endl;\n    cout.flush();\n    int correct;\n    cin >> correct;\n    if (correct) {\n        exit(0);\n    }\n}\n\nint main() {\n    read_input();\n\n    // Initial random drilling\n    set<Square> drilled;\n    mt19937 rng(random_device{}());\n    uniform_int_distribution<int> dist(0, N - 1);\n    for (int k = 0; k < 10; ++k) {\n        int i = dist(rng);\n        int j = dist(rng);\n        drill(i, j);\n        drilled.insert(Square(i, j));\n    }\n\n    // Divination to estimate total oil reserves\n    vector<Square> all_squares;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            all_squares.emplace_back(i, j);\n        }\n    }\n    int total_estimate = divinate(all_squares);\n\n    // Heuristic guided drilling\n    set<Square> candidates;\n    for (const auto& field : fields) {\n        for (const auto& sq : field.squares) {\n            candidates.insert(sq);\n        }\n    }\n\n    while (true) {\n        // Prioritize squares that are part of the polyominoes with the highest estimated oil reserves\n        vector<Square> to_divinate;\n        for (const auto& sq : candidates) {\n            if (drilled.find(sq) == drilled.end()) {\n                to_divinate.push_back(sq);\n            }\n        }\n\n        if (to_divinate.empty()) break;\n\n        // Divinate a subset of candidates\n        int k = min(10, (int)to_divinate.size());\n        vector<Square> subset(to_divinate.begin(), to_divinate.begin() + k);\n        int estimate = divinate(subset);\n\n        // Update the set of candidates based on the estimate\n        for (const auto& sq : subset) {\n            if (estimate > 0) {\n                candidates.insert(sq);\n            } else {\n                candidates.erase(sq);\n            }\n        }\n\n        // Drill a square from the candidates\n        if (!candidates.empty()) {\n            auto it = candidates.begin();\n            advance(it, dist(rng) % candidates.size());\n            Square sq = *it;\n            drill(sq.i, sq.j);\n            drilled.insert(sq);\n        }\n\n        // Guess the set of squares with oil reserves\n        if (drilled.size() >= 10) {\n            guess(drilled);\n        }\n    }\n\n    return 0;\n}","ahc031":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <climits>\n\nusing namespace std;\n\nstruct Rectangle {\n    int i0, j0, i1, j1;\n    Rectangle(int i0, int j0, int i1, int j1) : i0(i0), j0(j0), i1(i1), j1(j1) {}\n    int area() const { return (i1 - i0) * (j1 - j0); }\n};\n\nstruct Solution {\n    vector<vector<Rectangle>> rectangles;\n    int total_cost;\n};\n\nint calculate_area_cost(const vector<vector<int>>& a, const Solution& sol) {\n    int cost = 0;\n    for (int d = 0; d < sol.rectangles.size(); ++d) {\n        for (int k = 0; k < sol.rectangles[d].size(); ++k) {\n            int b = sol.rectangles[d][k].area();\n            if (a[d][k] > b) {\n                cost += 100 * (a[d][k] - b);\n            }\n        }\n    }\n    return cost;\n}\n\nint calculate_partition_cost(const Solution& prev_sol, const Solution& curr_sol) {\n    int cost = 0;\n    for (int d = 0; d < curr_sol.rectangles.size(); ++d) {\n        if (d == 0) continue; // No partition cost on the first day\n        for (int i = 1; i < 1000; ++i) {\n            for (int j = 0; j < 999; ++j) {\n                bool prev_has_horizontal = false;\n                bool curr_has_horizontal = false;\n                for (const auto& rect : prev_sol.rectangles[d-1]) {\n                    if ((rect.i0 == i && rect.j0 <= j && rect.j1 > j) ||\n                        (rect.i1 == i && rect.j0 <= j && rect.j1 > j)) {\n                        prev_has_horizontal = true;\n                        break;\n                    }\n                }\n                for (const auto& rect : curr_sol.rectangles[d]) {\n                    if ((rect.i0 == i && rect.j0 <= j && rect.j1 > j) ||\n                        (rect.i1 == i && rect.j0 <= j && rect.j1 > j)) {\n                        curr_has_horizontal = true;\n                        break;\n                    }\n                }\n                if (prev_has_horizontal != curr_has_horizontal) {\n                    cost++;\n                }\n            }\n        }\n        for (int i = 0; i < 999; ++i) {\n            for (int j = 1; j < 1000; ++j) {\n                bool prev_has_vertical = false;\n                bool curr_has_vertical = false;\n                for (const auto& rect : prev_sol.rectangles[d-1]) {\n                    if ((rect.j0 == j && rect.i0 <= i && rect.i1 > i) ||\n                        (rect.j1 == j && rect.i0 <= i && rect.i1 > i)) {\n                        prev_has_vertical = true;\n                        break;\n                    }\n                }\n                for (const auto& rect : curr_sol.rectangles[d]) {\n                    if ((rect.j0 == j && rect.i0 <= i && rect.i1 > i) ||\n                        (rect.j1 == j && rect.i0 <= i && rect.i1 > i)) {\n                        curr_has_vertical = true;\n                        break;\n                    }\n                }\n                if (prev_has_vertical != curr_has_vertical) {\n                    cost++;\n                }\n            }\n        }\n    }\n    return cost;\n}\n\nSolution greedy_solution(const vector<vector<int>>& a) {\n    Solution sol;\n    sol.rectangles.resize(a.size());\n    for (int d = 0; d < a.size(); ++d) {\n        vector<int> remaining_area = a[d];\n        sort(remaining_area.rbegin(), remaining_area.rend());\n        vector<pair<int, int>> positions;\n        for (int i = 0; i < 1000; ++i) {\n            for (int j = 0; j < 1000; ++j) {\n                positions.emplace_back(i, j);\n            }\n        }\n        random_device rd;\n        mt19937 g(rd());\n        shuffle(positions.begin(), positions.end(), g);\n        for (int k = 0; k < a[d].size(); ++k) {\n            int best_area = 0;\n            Rectangle best_rect(0, 0, 0, 0);\n            for (const auto& pos : positions) {\n                int i0 = pos.first;\n                int j0 = pos.second;\n                for (int i1 = i0 + 1; i1 <= 1000; ++i1) {\n                    for (int j1 = j0 + 1; j1 <= 1000; ++j1) {\n                        int area = (i1 - i0) * (j1 - j0);\n                        if (area > remaining_area[k]) continue;\n                        if (area > best_area) {\n                            best_area = area;\n                            best_rect = Rectangle(i0, j0, i1, j1);\n                        }\n                    }\n                }\n            }\n            sol.rectangles[d].push_back(best_rect);\n            remaining_area[k] -= best_area;\n        }\n    }\n    sol.total_cost = calculate_area_cost(a, sol) + calculate_partition_cost(sol, sol);\n    return sol;\n}\n\nSolution simulated_annealing(const vector<vector<int>>& a, const Solution& initial_sol, double initial_temp, double cooling_rate, int iterations) {\n    Solution current_sol = initial_sol;\n    Solution best_sol = initial_sol;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n    double temp = initial_temp;\n    for (int iter = 0; iter < iterations; ++iter) {\n        Solution new_sol = current_sol;\n        int d = rand() % a.size();\n        int k = rand() % a[d].size();\n        int i0 = rand() % 1000;\n        int j0 = rand() % 1000;\n        int i1 = i0 + 1 + rand() % (1000 - i0);\n        int j1 = j0 + 1 + rand() % (1000 - j0);\n        new_sol.rectangles[d][k] = Rectangle(i0, j0, i1, j1);\n        int new_area_cost = calculate_area_cost(a, new_sol);\n        int new_partition_cost = calculate_partition_cost(current_sol, new_sol);\n        int new_total_cost = new_area_cost + new_partition_cost;\n        if (new_total_cost < current_sol.total_cost || dis(gen) < exp((current_sol.total_cost - new_total_cost) / temp)) {\n            current_sol = new_sol;\n            current_sol.total_cost = new_total_cost;\n            if (new_total_cost < best_sol.total_cost) {\n                best_sol = new_sol;\n                best_sol.total_cost = new_total_cost;\n            }\n        }\n        temp *= cooling_rate;\n    }\n    return best_sol;\n}\n\nint main() {\n    int W, D, N;\n    cin >> W >> D >> N;\n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cin >> a[d][k];\n        }\n    }\n    Solution initial_sol = greedy_solution(a);\n    Solution best_sol = simulated_annealing(a, initial_sol, 1000.0, 0.999, 10000);\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            cout << best_sol.rectangles[d][k].i0 << \" \" << best_sol.rectangles[d][k].j0 << \" \"\n                 << best_sol.rectangles[d][k].i1 << \" \" << best_sol.rectangles[d][k].j1 << endl;\n        }\n    }\n    return 0;\n}","ahc032":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 9;\nconst int M = 20;\nconst int K = 81;\n\nstruct Stamp {\n    int s[3][3];\n};\n\nstruct Operation {\n    int m, p, q;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int a[N][N];\n    Stamp stamps[M];\n\n    // Read initial grid\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> a[i][j];\n        }\n    }\n\n    // Read stamps\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].s[i][j];\n            }\n        }\n    }\n\n    vector<Operation> operations;\n    int current_sum = 0;\n\n    // Calculate initial sum\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            current_sum = (current_sum + a[i][j] % MOD) % MOD;\n        }\n    }\n\n    // Greedy approach\n    for (int op = 0; op < K; ++op) {\n        int best_m = -1, best_p = -1, best_q = -1;\n        int max_increase = 0;\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    int increase = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            int new_val = (a[p + i][q + j] + stamps[m].s[i][j]) % MOD;\n                            increase += (new_val - (a[p + i][q + j] % MOD)) % MOD;\n                        }\n                    }\n                    if (increase > max_increase) {\n                        max_increase = increase;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_m == -1) break; // No more beneficial operations\n\n        operations.push_back({best_m, best_p, best_q});\n\n        // Apply the best operation\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                a[best_p + i][best_q + j] = (a[best_p + i][best_q + j] + stamps[best_m].s[i][j]) % MOD;\n            }\n        }\n\n        current_sum = (current_sum + max_increase) % MOD;\n    }\n\n    // Output the operations\n    cout << operations.size() << endl;\n    for (const auto& op : operations) {\n        cout << op.m << \" \" << op.p << \" \" << op.q << endl;\n    }\n\n    return 0;\n}","ahc033":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_map>\n#include <cmath>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 5;\nconst int MAX_TURNS = 10000;\n\nstruct Crane {\n    int x, y;\n    bool is_large;\n    bool holding;\n    int container;\n};\n\nstruct Container {\n    int x, y;\n    int number;\n};\n\nvector<vector<int>> A(N, vector<int>(N));\nvector<Crane> cranes;\nvector<vector<int>> grid(N, vector<int>(N, -1));\nvector<vector<int>> next_container(N, vector<int>(N, 0));\nvector<string> actions(N, string(MAX_TURNS, '.'));\n\nint calculate_score() {\n    // Implement scoring logic here\n    return 0;\n}\n\nvoid simulate_turn() {\n    // Step 1: Bring in new containers\n    for (int i = 0; i < N; ++i) {\n        if (next_container[i][0] < N && grid[i][0] == -1) {\n            grid[i][0] = A[i][next_container[i][0]];\n            next_container[i][0]++;\n        }\n    }\n\n    // Step 2: Perform crane actions\n    vector<vector<int>> new_grid(N, vector<int>(N, -1));\n    vector<Crane> new_cranes;\n    for (int i = 0; i < N; ++i) {\n        Crane c = cranes[i];\n        char action = actions[i][0];\n        actions[i].erase(0, 1);\n\n        if (action == 'B' && !c.holding) {\n            continue; // Crane is bombed\n        }\n\n        switch (action) {\n            case 'P':\n                if (!c.holding && grid[c.x][c.y] != -1) {\n                    c.holding = true;\n                    c.container = grid[c.x][c.y];\n                    grid[c.x][c.y] = -1;\n                }\n                break;\n            case 'Q':\n                if (c.holding && grid[c.x][c.y] == -1) {\n                    grid[c.x][c.y] = c.container;\n                    c.holding = false;\n                }\n                break;\n            case 'U':\n                if (c.x > 0 && (grid[c.x - 1][c.y] == -1 || c.is_large)) {\n                    c.x--;\n                }\n                break;\n            case 'D':\n                if (c.x < N - 1 && (grid[c.x + 1][c.y] == -1 || c.is_large)) {\n                    c.x++;\n                }\n                break;\n            case 'L':\n                if (c.y > 0 && (grid[c.x][c.y - 1] == -1 || c.is_large)) {\n                    c.y--;\n                }\n                break;\n            case 'R':\n                if (c.y < N - 1 && (grid[c.x][c.y + 1] == -1 || c.is_large)) {\n                    c.y++;\n                }\n                break;\n            case '.':\n                break;\n        }\n\n        if (action != 'B') {\n            new_cranes.push_back(c);\n        }\n    }\n    cranes = new_cranes;\n\n    // Step 3: Dispatch containers\n    for (int i = 0; i < N; ++i) {\n        if (grid[i][N - 1] != -1) {\n            grid[i][N - 1] = -1;\n        }\n    }\n}\n\nvoid heuristic_solution() {\n    // Initialize cranes\n    for (int i = 0; i < N; ++i) {\n        cranes.push_back({i, 0, i == 0, false, -1});\n    }\n\n    // Simulate turns\n    for (int turn = 0; turn < MAX_TURNS; ++turn) {\n        simulate_turn();\n\n        // Simple heuristic: Move cranes towards the right edge\n        for (int i = 0; i < N; ++i) {\n            Crane &c = cranes[i];\n            if (c.y < N - 1) {\n                actions[i][turn] = 'R';\n            } else if (c.y == N - 1 && c.holding) {\n                actions[i][turn] = 'Q';\n            } else if (c.y == N - 1 && !c.holding && grid[c.x][c.y] != -1) {\n                actions[i][turn] = 'P';\n            } else if (c.y == N - 1 && !c.holding && grid[c.x][c.y] == -1) {\n                actions[i][turn] = '.';\n            }\n        }\n    }\n}\n\nint main() {\n    // Read input\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> A[i][j];\n        }\n    }\n\n    // Run heuristic solution\n    heuristic_solution();\n\n    // Output actions\n    for (int i = 0; i < N; ++i) {\n        cout << actions[i] << endl;\n    }\n\n    return 0;\n}","ahc034":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <climits>\n#include <unordered_map>\n#include <tuple>\n\nusing namespace std;\n\nconst int N = 20;\nconst int MAX_OPERATIONS = 100000;\nconst int MAX_SOIL = 1000000;\n\nstruct State {\n    int x, y;\n    int soil;\n    int cost;\n    vector<string> operations;\n\n    bool operator>(const State& other) const {\n        return cost > other.cost;\n    }\n};\n\nint heuristic(int x1, int y1, int x2, int y2, int soil) {\n    return abs(x1 - x2) + abs(y1 - y2) + soil;\n}\n\nvector<string> findPath(int startX, int startY, int endX, int endY, int soil) {\n    priority_queue<State, vector<State>, greater<State>> pq;\n    unordered_map<int, unordered_map<int, int>> visited;\n\n    pq.push({startX, startY, soil, 0, {}});\n    visited[startX][startY] = 0;\n\n    vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n    vector<string> dirChars = {\"U\", \"D\", \"L\", \"R\"};\n\n    while (!pq.empty()) {\n        State current = pq.top();\n        pq.pop();\n\n        if (current.x == endX && current.y == endY) {\n            return current.operations;\n        }\n\n        for (int i = 0; i < 4; ++i) {\n            int newX = current.x + directions[i].first;\n            int newY = current.y + directions[i].second;\n\n            if (newX >= 0 && newX < N && newY >= 0 && newY < N) {\n                int newCost = current.cost + 100 + current.soil;\n                if (visited[newX][newY] == 0 || newCost < visited[newX][newY]) {\n                    visited[newX][newY] = newCost;\n                    vector<string> newOperations = current.operations;\n                    newOperations.push_back(dirChars[i]);\n                    pq.push({newX, newY, current.soil, newCost, newOperations});\n                }\n            }\n        }\n    }\n\n    return {};\n}\n\nvector<string> solve(vector<vector<int>>& grid) {\n    vector<string> operations;\n    int totalOperations = 0;\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] == 0) continue;\n\n            int currentX = 0, currentY = 0;\n            int soil = 0;\n\n            // Move to the target square\n            vector<string> path = findPath(currentX, currentY, i, j, soil);\n            operations.insert(operations.end(), path.begin(), path.end());\n            currentX = i;\n            currentY = j;\n\n            // Load or unload soil\n            if (grid[i][j] > 0) {\n                int d = min(grid[i][j], MAX_SOIL);\n                operations.push_back(\"+\" + to_string(d));\n                soil += d;\n                grid[i][j] -= d;\n            } else {\n                int d = min(-grid[i][j], soil);\n                operations.push_back(\"-\" + to_string(d));\n                soil -= d;\n                grid[i][j] += d;\n            }\n\n            // Move back to the origin if there's soil to carry\n            if (soil > 0) {\n                path = findPath(currentX, currentY, 0, 0, soil);\n                operations.insert(operations.end(), path.begin(), path.end());\n                currentX = 0;\n                currentY = 0;\n            }\n\n            if (operations.size() >= MAX_OPERATIONS) break;\n        }\n        if (operations.size() >= MAX_OPERATIONS) break;\n    }\n\n    return operations;\n}\n\nint main() {\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<string> operations = solve(grid);\n    for (const string& op : operations) {\n        cout << op << endl;\n    }\n\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <numeric>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nconst int N = 6;\nconst int M = 15;\nconst int T = 10;\nconst int SEED_COUNT = 2 * N * (N - 1);\nconst int POPULATION_SIZE = 50;\nconst int GENERATIONS = 10;\nconst double MUTATION_RATE = 0.1;\n\nvector<vector<int>> X(SEED_COUNT, vector<int>(M, 0));\nvector<int> X_max(M, 0);\n\nstruct Individual {\n    vector<vector<int>> grid;\n    int fitness;\n\n    Individual() : grid(N, vector<int>(N, 0)), fitness(0) {}\n};\n\nvector<Individual> population(POPULATION_SIZE);\n\nvoid initializePopulation() {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, SEED_COUNT - 1);\n\n    for (auto& individual : population) {\n        vector<int> seeds(SEED_COUNT);\n        iota(seeds.begin(), seeds.end(), 0);\n        shuffle(seeds.begin(), seeds.end(), gen);\n\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                individual.grid[i][j] = seeds[i * N + j];\n            }\n        }\n    }\n}\n\nvector<vector<int>> generateNewSeeds(const vector<vector<int>>& grid) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, 1);\n\n    vector<vector<int>> newSeeds(SEED_COUNT, vector<int>(M, 0));\n\n    int index = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N - 1; ++j) {\n            int seed1 = grid[i][j];\n            int seed2 = grid[i][j + 1];\n            for (int l = 0; l < M; ++l) {\n                newSeeds[index][l] = dist(gen) ? X[seed1][l] : X[seed2][l];\n            }\n            ++index;\n        }\n    }\n\n    for (int i = 0; i < N - 1; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int seed1 = grid[i][j];\n            int seed2 = grid[i + 1][j];\n            for (int l = 0; l < M; ++l) {\n                newSeeds[index][l] = dist(gen) ? X[seed1][l] : X[seed2][l];\n            }\n            ++index;\n        }\n    }\n\n    return newSeeds;\n}\n\nint calculateFitness(const vector<vector<int>>& grid) {\n    vector<vector<int>> currentSeeds = X;\n    for (int t = 0; t < T; ++t) {\n        currentSeeds = generateNewSeeds(grid);\n    }\n\n    int maxValue = 0;\n    for (const auto& seed : currentSeeds) {\n        int value = accumulate(seed.begin(), seed.end(), 0);\n        if (value > maxValue) {\n            maxValue = value;\n        }\n    }\n\n    int sumXMax = accumulate(X_max.begin(), X_max.end(), 0);\n    return round(1e6 * maxValue / sumXMax);\n}\n\nvoid evaluatePopulation() {\n    for (auto& individual : population) {\n        individual.fitness = calculateFitness(individual.grid);\n    }\n}\n\nvector<Individual> selectParents() {\n    vector<Individual> parents;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, POPULATION_SIZE - 1);\n\n    for (int i = 0; i < POPULATION_SIZE; ++i) {\n        int idx1 = dist(gen);\n        int idx2 = dist(gen);\n        parents.push_back(population[idx1].fitness > population[idx2].fitness ? population[idx1] : population[idx2]);\n    }\n\n    return parents;\n}\n\nvector<Individual> crossover(const vector<Individual>& parents) {\n    vector<Individual> offspring;\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<int> dist(0, N * N - 1);\n\n    for (int i = 0; i < POPULATION_SIZE; i += 2) {\n        Individual child1, child2;\n        int crossoverPoint = dist(gen);\n\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < N; ++k) {\n                if (j * N + k < crossoverPoint) {\n                    child1.grid[j][k] = parents[i].grid[j][k];\n                    child2.grid[j][k] = parents[i + 1].grid[j][k];\n                } else {\n                    child1.grid[j][k] = parents[i + 1].grid[j][k];\n                    child2.grid[j][k] = parents[i].grid[j][k];\n                }\n            }\n        }\n\n        offspring.push_back(child1);\n        offspring.push_back(child2);\n    }\n\n    return offspring;\n}\n\nvoid mutate(vector<Individual>& offspring) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<double> dist(0.0, 1.0);\n    uniform_int_distribution<int> seedDist(0, SEED_COUNT - 1);\n\n    for (auto& individual : offspring) {\n        if (dist(gen) < MUTATION_RATE) {\n            int i1 = seedDist(gen) / N;\n            int j1 = seedDist(gen) % N;\n            int i2 = seedDist(gen) / N;\n            int j2 = seedDist(gen) % N;\n            swap(individual.grid[i1][j1], individual.grid[i2][j2]);\n        }\n    }\n}\n\nvoid geneticAlgorithm() {\n    initializePopulation();\n    evaluatePopulation();\n\n    for (int gen = 0; gen < GENERATIONS; ++gen) {\n        vector<Individual> parents = selectParents();\n        vector<Individual> offspring = crossover(parents);\n        mutate(offspring);\n\n        for (auto& individual : offspring) {\n            individual.fitness = calculateFitness(individual.grid);\n        }\n\n        population.insert(population.end(), offspring.begin(), offspring.end());\n        sort(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n            return a.fitness > b.fitness;\n        });\n        population.resize(POPULATION_SIZE);\n    }\n}\n\nint main() {\n    // Read input\n    for (int i = 0; i < SEED_COUNT; ++i) {\n        for (int j = 0; j < M; ++j) {\n            cin >> X[i][j];\n            if (X[i][j] > X_max[j]) {\n                X_max[j] = X[i][j];\n            }\n        }\n    }\n\n    // Run genetic algorithm\n    geneticAlgorithm();\n\n    // Output the best solution\n    Individual best = *max_element(population.begin(), population.end(), [](const Individual& a, const Individual& b) {\n        return a.fitness < b.fitness;\n    });\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cout << best.grid[i][j];\n            if (j < N - 1) {\n                cout << \" \";\n            } else {\n                cout << endl;\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <cmath>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct TreeNode {\n    int id;\n    int parent;\n    int length;\n    vector<int> children;\n    Point position;\n    Point direction;\n    bool isFingertip;\n    bool holding;\n\n    TreeNode(int id, int parent, int length, const Point& position, const Point& direction, bool isFingertip)\n        : id(id), parent(parent), length(length), position(position), direction(direction), isFingertip(isFingertip), holding(false) {}\n};\n\nclass RoboticArm {\nprivate:\n    int N, M, V;\n    vector<vector<int>> grid;\n    vector<vector<int>> target;\n    vector<TreeNode> tree;\n    Point rootPosition;\n    vector<string> operations;\n    unordered_map<Point, bool> occupied;\n\n    void designTree() {\n        // Design a star-shaped tree\n        tree.emplace_back(0, -1, 0, rootPosition, Point(1, 0), false);\n        for (int i = 1; i < V; ++i) {\n            int parent = 0;\n            int length = 1;\n            Point direction = Point(1, 0);\n            tree.emplace_back(i, parent, length, rootPosition, direction, true);\n            tree[parent].children.push_back(i);\n        }\n    }\n\n    void moveRoot(int dx, int dy) {\n        rootPosition.x += dx;\n        rootPosition.y += dy;\n        for (auto& node : tree) {\n            node.position.x += dx;\n            node.position.y += dy;\n        }\n    }\n\n    void rotateSubtree(int nodeId, int rotation) {\n        if (rotation == 0) return;\n        TreeNode& node = tree[nodeId];\n        int newDirX = node.direction.x;\n        int newDirY = node.direction.y;\n        if (rotation == 1) { // Counterclockwise\n            newDirX = -node.direction.y;\n            newDirY = node.direction.x;\n        } else if (rotation == 2) { // Clockwise\n            newDirX = node.direction.y;\n            newDirY = -node.direction.x;\n        }\n        node.direction.x = newDirX;\n        node.direction.y = newDirY;\n        for (int childId : node.children) {\n            rotateSubtree(childId, rotation);\n        }\n    }\n\n    void grabOrRelease(int nodeId) {\n        TreeNode& node = tree[nodeId];\n        if (!node.isFingertip) return;\n        Point fingertipPos = node.position;\n        fingertipPos.x += node.direction.x * node.length;\n        fingertipPos.y += node.direction.y * node.length;\n        if (fingertipPos.x < 0 || fingertipPos.x >= N || fingertipPos.y < 0 || fingertipPos.y >= N) return;\n        if (grid[fingertipPos.x][fingertipPos.y] == 1 && target[fingertipPos.x][fingertipPos.y] == 0 && !node.holding) {\n            grid[fingertipPos.x][fingertipPos.y] = 0;\n            node.holding = true;\n        } else if (grid[fingertipPos.x][fingertipPos.y] == 0 && target[fingertipPos.x][fingertipPos.y] == 1 && node.holding) {\n            grid[fingertipPos.x][fingertipPos.y] = 1;\n            node.holding = false;\n        }\n    }\n\n    void performOperation(const string& op) {\n        operations.push_back(op);\n        char move = op[0];\n        if (move == 'U') moveRoot(-1, 0);\n        else if (move == 'D') moveRoot(1, 0);\n        else if (move == 'L') moveRoot(0, -1);\n        else if (move == 'R') moveRoot(0, 1);\n        for (int i = 1; i < V; ++i) {\n            char rot = op[i];\n            if (rot == 'L') rotateSubtree(i, 1);\n            else if (rot == 'R') rotateSubtree(i, 2);\n        }\n        for (int i = 0; i < V; ++i) {\n            char action = op[V + i];\n            if (action == 'P') grabOrRelease(i);\n        }\n    }\n\n    void moveTakoyaki(const Point& start, const Point& end) {\n        // Simplified path planning: move directly to the target\n        int dx = end.x - start.x;\n        int dy = end.y - start.y;\n        string op(V * 2, '.');\n        if (dx > 0) op[0] = 'D';\n        else if (dx < 0) op[0] = 'U';\n        else if (dy > 0) op[0] = 'R';\n        else if (dy < 0) op[0] = 'L';\n        performOperation(op);\n        op = string(V * 2, '.');\n        op[V + 1] = 'P'; // Grab or release\n        performOperation(op);\n        if (dx > 0) op[0] = 'U';\n        else if (dx < 0) op[0] = 'D';\n        else if (dy > 0) op[0] = 'L';\n        else if (dy < 0) op[0] = 'R';\n        performOperation(op);\n        op[V + 1] = 'P'; // Grab or release\n        performOperation(op);\n    }\n\npublic:\n    RoboticArm(int N, int M, int V, const vector<vector<int>>& grid, const vector<vector<int>>& target)\n        : N(N), M(M), V(V), grid(grid), target(target), rootPosition(0, 0) {\n        designTree();\n    }\n\n    void solve() {\n        vector<Point> takoyakiPositions;\n        vector<Point> targetPositions;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (grid[i][j] == 1) {\n                    takoyakiPositions.emplace_back(i, j);\n                }\n                if (target[i][j] == 1) {\n                    targetPositions.emplace_back(i, j);\n                }\n            }\n        }\n        for (size_t i = 0; i < takoyakiPositions.size(); ++i) {\n            moveTakoyaki(takoyakiPositions[i], targetPositions[i]);\n        }\n    }\n\n    void printSolution() {\n        cout << tree.size() << endl;\n        for (size_t i = 1; i < tree.size(); ++i) {\n            cout << tree[i].parent << \" \" << tree[i].length << endl;\n        }\n        cout << rootPosition.x << \" \" << rootPosition.y << endl;\n        for (const string& op : operations) {\n            cout << op << endl;\n        }\n    }\n};\n\nint main() {\n    int N, M, V;\n    cin >> N >> M >> V;\n    vector<vector<int>> grid(N, vector<int>(N));\n    vector<vector<int>> target(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            grid[i][j] = row[j] - '0';\n        }\n    }\n    for (int i = 0; i < N; ++i) {\n        string row;\n        cin >> row;\n        for (int j = 0; j < N; ++j) {\n            target[i][j] = row[j] - '0';\n        }\n    }\n    RoboticArm arm(N, M, V, grid, target);\n    arm.solve();\n    arm.printSolution();\n    return 0;\n}","ahc039":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n};\n\nstruct Polygon {\n    vector<Point> vertices;\n    int mackerels, sardines;\n    Polygon() : mackerels(0), sardines(0) {}\n};\n\nint cross(const Point &O, const Point &A, const Point &B) {\n    return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);\n}\n\nvector<Point> convex_hull(vector<Point> points) {\n    int n = points.size(), k = 0;\n    vector<Point> hull(2 * n);\n    sort(points.begin(), points.end(), [](const Point &a, const Point &b) {\n        return a.x < b.x || (a.x == b.x && a.y < b.y);\n    });\n    for (int i = 0; i < n; ++i) {\n        while (k >= 2 && cross(hull[k-2], hull[k-1], points[i]) <= 0) k--;\n        hull[k++] = points[i];\n    }\n    for (int i = n-2, t = k+1; i >= 0; --i) {\n        while (k >= t && cross(hull[k-2], hull[k-1], points[i]) <= 0) k--;\n        hull[k++] = points[i];\n    }\n    hull.resize(k-1);\n    return hull;\n}\n\nbool is_point_in_polygon(const Point &p, const Polygon &poly) {\n    int n = poly.vertices.size();\n    if (n < 3) return false;\n    bool inside = false;\n    for (int i = 0, j = n - 1; i < n; j = i++) {\n        if (((poly.vertices[i].y > p.y) != (poly.vertices[j].y > p.y)) &&\n            (p.x < (poly.vertices[j].x - poly.vertices[i].x) * (p.y - poly.vertices[i].y) / (poly.vertices[j].y - poly.vertices[i].y) + poly.vertices[i].x))\n            inside = !inside;\n    }\n    return inside;\n}\n\nint count_points_in_polygon(const vector<Point> &points, const Polygon &poly) {\n    int count = 0;\n    for (const auto &p : points) {\n        if (is_point_in_polygon(p, poly)) {\n            count++;\n        }\n    }\n    return count;\n}\n\nPolygon generate_random_polygon(const vector<Point> &hull, int max_vertices, int max_edge_length) {\n    Polygon poly;\n    int n = hull.size();\n    if (n < 4) return poly;\n\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_int_distribution<> dis(0, n - 1);\n\n    int start = dis(gen);\n    poly.vertices.push_back(hull[start]);\n\n    int current = start;\n    int total_length = 0;\n    while (poly.vertices.size() < max_vertices) {\n        int next = (current + 1) % n;\n        int dx = hull[next].x - hull[current].x;\n        int dy = hull[next].y - hull[current].y;\n        int edge_length = abs(dx) + abs(dy);\n\n        if (total_length + edge_length > max_edge_length) {\n            break;\n        }\n\n        if (dx != 0 && dy != 0) {\n            // Ensure edges are parallel to x-axis or y-axis\n            if (abs(dx) > abs(dy)) {\n                poly.vertices.emplace_back(hull[current].x + dx, hull[current].y);\n            } else {\n                poly.vertices.emplace_back(hull[current].x, hull[current].y + dy);\n            }\n        } else {\n            poly.vertices.push_back(hull[next]);\n        }\n\n        total_length += edge_length;\n        current = next;\n    }\n\n    // Close the polygon\n    if (poly.vertices.size() >= 3) {\n        int dx = poly.vertices.back().x - poly.vertices[0].x;\n        int dy = poly.vertices.back().y - poly.vertices[0].y;\n        if (dx != 0 && dy != 0) {\n            if (abs(dx) > abs(dy)) {\n                poly.vertices.emplace_back(poly.vertices.back().x, poly.vertices[0].y);\n            } else {\n                poly.vertices.emplace_back(poly.vertices[0].x, poly.vertices.back().y);\n            }\n        }\n    }\n\n    return poly;\n}\n\nint evaluate_polygon(const Polygon &poly, const vector<Point> &mackerels, const vector<Point> &sardines) {\n    int m = count_points_in_polygon(mackerels, poly);\n    int s = count_points_in_polygon(sardines, poly);\n    return max(0, m - s + 1);\n}\n\nPolygon simulated_annealing(const vector<Point> &hull, const vector<Point> &mackerels, const vector<Point> &sardines, int max_vertices, int max_edge_length, int iterations) {\n    random_device rd;\n    mt19937 gen(rd());\n    uniform_real_distribution<> dis(0.0, 1.0);\n\n    Polygon current = generate_random_polygon(hull, max_vertices, max_edge_length);\n    current.mackerels = count_points_in_polygon(mackerels, current);\n    current.sardines = count_points_in_polygon(sardines, current);\n    int current_score = evaluate_polygon(current, mackerels, sardines);\n\n    Polygon best = current;\n    int best_score = current_score;\n\n    double temperature = 1.0;\n    double cooling_rate = 0.999;\n\n    for (int i = 0; i < iterations; ++i) {\n        Polygon neighbor = generate_random_polygon(hull, max_vertices, max_edge_length);\n        neighbor.mackerels = count_points_in_polygon(mackerels, neighbor);\n        neighbor.sardines = count_points_in_polygon(sardines, neighbor);\n        int neighbor_score = evaluate_polygon(neighbor, mackerels, sardines);\n\n        if (neighbor_score > current_score || dis(gen) < exp((neighbor_score - current_score) / temperature)) {\n            current = neighbor;\n            current_score = neighbor_score;\n        }\n\n        if (current_score > best_score) {\n            best = current;\n            best_score = current_score;\n        }\n\n        temperature *= cooling_rate;\n    }\n\n    return best;\n}\n\nint main() {\n    int N;\n    cin >> N;\n\n    vector<Point> mackerels;\n    vector<Point> sardines;\n    vector<Point> all_points;\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        mackerels.emplace_back(x, y);\n        all_points.emplace_back(x, y);\n    }\n\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        sardines.emplace_back(x, y);\n        all_points.emplace_back(x, y);\n    }\n\n    vector<Point> hull = convex_hull(all_points);\n    int max_vertices = 1000;\n    int max_edge_length = 400000;\n    int iterations = 10000;\n\n    Polygon best_polygon = simulated_annealing(hull, mackerels, sardines, max_vertices, max_edge_length, iterations);\n\n    cout << best_polygon.vertices.size() << endl;\n    for (const auto &p : best_polygon.vertices) {\n        cout << p.x << \" \" << p.y << endl;\n    }\n\n    return 0;\n}","ahc040":"#include <iostream>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <limits>\n#include <chrono>\n\nusing namespace std;\n\nstruct Rectangle {\n    int w, h;\n    int w_prime, h_prime;\n};\n\nstruct Placement {\n    int p; // index of the rectangle\n    int r; // rotation (0 or 1)\n    char d; // direction ('U' or 'L')\n    int b; // reference rectangle index or -1\n};\n\nstruct Solution {\n    vector<Placement> placements;\n    int width, height;\n    int score;\n};\n\nclass RectanglePacker {\nprivate:\n    int N, T, sigma;\n    vector<Rectangle> rectangles;\n    mt19937 rng;\n    uniform_real_distribution<double> dist;\n\n    Solution generateInitialSolution() {\n        Solution solution;\n        vector<int> indices(N);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), rng);\n\n        for (int i = 0; i < N; ++i) {\n            int p = indices[i];\n            int r = uniform_int_distribution<int>(0, 1)(rng);\n            char d = uniform_int_distribution<int>(0, 1)(rng) ? 'U' : 'L';\n            int b = i == 0 ? -1 : uniform_int_distribution<int>(-1, i - 1)(rng);\n            solution.placements.push_back({p, r, d, b});\n        }\n\n        return solution;\n    }\n\n    Solution placeRectangles(const Solution& solution) {\n        Solution result = solution;\n        vector<pair<int, int>> positions(N, {-1, -1});\n        int max_x = 0, max_y = 0;\n\n        for (const auto& placement : solution.placements) {\n            int p = placement.p;\n            int r = placement.r;\n            char d = placement.d;\n            int b = placement.b;\n\n            int w = r == 0 ? rectangles[p].w_prime : rectangles[p].h_prime;\n            int h = r == 0 ? rectangles[p].h_prime : rectangles[p].w_prime;\n\n            int x, y;\n            if (d == 'U') {\n                if (b == -1) {\n                    x = 0;\n                } else {\n                    x = positions[b].first + (r == 0 ? rectangles[b].w_prime : rectangles[b].h_prime);\n                }\n                y = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (positions[i].first != -1 && positions[i].first < x + w && positions[i].first + (r == 0 ? rectangles[i].w_prime : rectangles[i].h_prime) > x) {\n                        y = max(y, positions[i].second + (r == 0 ? rectangles[i].h_prime : rectangles[i].w_prime));\n                    }\n                }\n            } else { // d == 'L'\n                if (b == -1) {\n                    y = 0;\n                } else {\n                    y = positions[b].second + (r == 0 ? rectangles[b].h_prime : rectangles[b].w_prime);\n                }\n                x = 0;\n                for (int i = 0; i < N; ++i) {\n                    if (positions[i].second != -1 && positions[i].second < y + h && positions[i].second + (r == 0 ? rectangles[i].h_prime : rectangles[i].w_prime) > y) {\n                        x = max(x, positions[i].first + (r == 0 ? rectangles[i].w_prime : rectangles[i].h_prime));\n                    }\n                }\n            }\n\n            positions[p] = {x, y};\n            max_x = max(max_x, x + w);\n            max_y = max(max_y, y + h);\n        }\n\n        result.width = max_x;\n        result.height = max_y;\n        result.score = max_x + max_y;\n\n        return result;\n    }\n\n    Solution mutateSolution(const Solution& solution) {\n        Solution new_solution = solution;\n        int mutation_type = uniform_int_distribution<int>(0, 2)(rng);\n\n        if (mutation_type == 0) { // Change rotation\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            new_solution.placements[idx].r = 1 - new_solution.placements[idx].r;\n        } else if (mutation_type == 1) { // Change direction\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            new_solution.placements[idx].d = new_solution.placements[idx].d == 'U' ? 'L' : 'U';\n        } else { // Change reference\n            int idx = uniform_int_distribution<int>(0, N - 1)(rng);\n            int b = idx == 0 ? -1 : uniform_int_distribution<int>(-1, idx - 1)(rng);\n            new_solution.placements[idx].b = b;\n        }\n\n        return new_solution;\n    }\n\n    Solution simulatedAnnealing() {\n        Solution current_solution = generateInitialSolution();\n        current_solution = placeRectangles(current_solution);\n        Solution best_solution = current_solution;\n\n        double temperature = 1000.0;\n        double cooling_rate = 0.99;\n        int iterations = 1000;\n\n        for (int i = 0; i < iterations; ++i) {\n            Solution new_solution = mutateSolution(current_solution);\n            new_solution = placeRectangles(new_solution);\n\n            double delta = new_solution.score - current_solution.score;\n            if (delta < 0 || exp(-delta / temperature) > dist(rng)) {\n                current_solution = new_solution;\n                if (new_solution.score < best_solution.score) {\n                    best_solution = new_solution;\n                }\n            }\n\n            temperature *= cooling_rate;\n        }\n\n        return best_solution;\n    }\n\npublic:\n    RectanglePacker(int N, int T, int sigma, const vector<Rectangle>& rectangles)\n        : N(N), T(T), sigma(sigma), rectangles(rectangles), rng(chrono::steady_clock::now().time_since_epoch().count()), dist(0.0, 1.0) {}\n\n    Solution findBestSolution() {\n        Solution best_solution;\n        best_solution.score = numeric_limits<int>::max();\n\n        for (int t = 0; t < T; ++t) {\n            Solution solution = simulatedAnnealing();\n            if (solution.score < best_solution.score) {\n                best_solution = solution;\n            }\n        }\n\n        return best_solution;\n    }\n};\n\nint main() {\n    int N, T, sigma;\n    cin >> N >> T >> sigma;\n\n    vector<Rectangle> rectangles(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> rectangles[i].w_prime >> rectangles[i].h_prime;\n    }\n\n    RectanglePacker packer(N, T, sigma, rectangles);\n    Solution best_solution = packer.findBestSolution();\n\n    cout << best_solution.placements.size() << endl;\n    for (const auto& placement : best_solution.placements) {\n        cout << placement.p << \" \" << placement.r << \" \" << placement.d << \" \" << placement.b << endl;\n    }\n\n    return 0;\n}","ahc041":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n#include <unordered_set>\n#include <random>\n#include <chrono>\n\nusing namespace std;\n\nstruct Edge {\n    int u, v;\n};\n\nstruct Vertex {\n    int id;\n    int beauty;\n    vector<int> neighbors;\n};\n\nstruct Tree {\n    int root;\n    vector<int> parent;\n    vector<int> height;\n};\n\nint N, M, H;\nvector<Vertex> vertices;\nvector<Edge> edges;\nvector<int> x, y;\n\nvoid input() {\n    cin >> N >> M >> H;\n    vertices.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> vertices[i].beauty;\n        vertices[i].id = i;\n    }\n    edges.resize(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> edges[i].u >> edges[i].v;\n        vertices[edges[i].u].neighbors.push_back(edges[i].v);\n        vertices[edges[i].v].neighbors.push_back(edges[i].u);\n    }\n    x.resize(N);\n    y.resize(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> x[i] >> y[i];\n    }\n}\n\nvector<int> solve() {\n    vector<int> parent(N, -1);\n    vector<bool> visited(N, false);\n    priority_queue<pair<int, int>> pq; // (beauty, id)\n\n    for (int i = 0; i < N; ++i) {\n        pq.push({vertices[i].beauty, i});\n    }\n\n    while (!pq.empty()) {\n        auto current = pq.top();\n        pq.pop();\n        int u = current.second;\n\n        if (visited[u]) continue;\n        visited[u] = true;\n\n        queue<pair<int, int>> q; // (vertex, parent)\n        q.push({u, -1});\n        int current_height = 0;\n\n        while (!q.empty() && current_height <= H) {\n            int size = q.size();\n            for (int i = 0; i < size; ++i) {\n                auto front = q.front();\n                q.pop();\n                int v = front.first;\n                int p = front.second;\n\n                if (visited[v]) continue;\n                visited[v] = true;\n                parent[v] = p;\n\n                for (int neighbor : vertices[v].neighbors) {\n                    if (!visited[neighbor]) {\n                        q.push({neighbor, v});\n                    }\n                }\n            }\n            current_height++;\n        }\n    }\n\n    return parent;\n}\n\nint main() {\n    input();\n    auto parent = solve();\n    for (int p : parent) {\n        cout << p << \" \";\n    }\n    cout << endl;\n    return 0;\n}","ahc042":"#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cassert>\n\nusing namespace std;\n\nstruct Move {\n    char direction;\n    int index;\n};\n\nvector<Move> solve(const vector<string>& board) {\n    int N = board.size();\n    vector<Move> moves;\n    vector<vector<char>> current_board(N, vector<char>(N));\n\n    // Convert the input board to a 2D vector of characters\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            current_board[i][j] = board[i][j];\n        }\n    }\n\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (current_board[i][j] == 'x') {\n                // Check if we can remove the Oni by shifting the row left\n                bool can_remove_left = true;\n                for (int k = 0; k < i; ++k) {\n                    if (current_board[k][j] == 'o') {\n                        can_remove_left = false;\n                        break;\n                    }\n                }\n                if (can_remove_left) {\n                    // Shift the row left to remove the Oni\n                    for (int k = 0; k <= i; ++k) {\n                        moves.push_back({'L', i});\n                    }\n                    for (int k = 0; k <= i; ++k) {\n                        moves.push_back({'R', i});\n                    }\n                    // Update the board state\n                    for (int k = 0; k < N - 1; ++k) {\n                        current_board[i][k] = current_board[i][k + 1];\n                    }\n                    current_board[i][N - 1] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the row right\n                bool can_remove_right = true;\n                for (int k = i + 1; k < N; ++k) {\n                    if (current_board[k][j] == 'o') {\n                        can_remove_right = false;\n                        break;\n                    }\n                }\n                if (can_remove_right) {\n                    // Shift the row right to remove the Oni\n                    for (int k = 0; k <= N - 1 - i; ++k) {\n                        moves.push_back({'R', i});\n                    }\n                    for (int k = 0; k <= N - 1 - i; ++k) {\n                        moves.push_back({'L', i});\n                    }\n                    // Update the board state\n                    for (int k = N - 1; k > 0; --k) {\n                        current_board[i][k] = current_board[i][k - 1];\n                    }\n                    current_board[i][0] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the column up\n                bool can_remove_up = true;\n                for (int k = 0; k < j; ++k) {\n                    if (current_board[i][k] == 'o') {\n                        can_remove_up = false;\n                        break;\n                    }\n                }\n                if (can_remove_up) {\n                    // Shift the column up to remove the Oni\n                    for (int k = 0; k <= j; ++k) {\n                        moves.push_back({'U', j});\n                    }\n                    for (int k = 0; k <= j; ++k) {\n                        moves.push_back({'D', j});\n                    }\n                    // Update the board state\n                    for (int k = 0; k < N - 1; ++k) {\n                        current_board[k][j] = current_board[k + 1][j];\n                    }\n                    current_board[N - 1][j] = '.';\n                    continue;\n                }\n\n                // Check if we can remove the Oni by shifting the column down\n                bool can_remove_down = true;\n                for (int k = j + 1; k < N; ++k) {\n                    if (current_board[i][k] == 'o') {\n                        can_remove_down = false;\n                        break;\n                    }\n                }\n                if (can_remove_down) {\n                    // Shift the column down to remove the Oni\n                    for (int k = 0; k <= N - 1 - j; ++k) {\n                        moves.push_back({'D', j});\n                    }\n                    for (int k = 0; k <= N - 1 - j; ++k) {\n                        moves.push_back({'U', j});\n                    }\n                    // Update the board state\n                    for (int k = N - 1; k > 0; --k) {\n                        current_board[k][j] = current_board[k - 1][j];\n                    }\n                    current_board[0][j] = '.';\n                }\n            }\n        }\n    }\n\n    return moves;\n}\n\nint main() {\n    int N;\n    cin >> N;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n    }\n\n    vector<Move> moves = solve(board);\n\n    for (const auto& move : moves) {\n        cout << move.direction << \" \" << move.index << endl;\n    }\n\n    return 0;\n}","ahc044":"#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nstruct Employee {\n    int a;\n    int b;\n};\n\nvector<int> simulate_cleaning_plan(const vector<Employee>& employees, int L) {\n    vector<int> actual(employees.size(), 0);\n    unordered_map<int, int> cycle_counts;\n    vector<bool> visited(employees.size(), false);\n    vector<int> path;\n\n    for (int i = 0; i < employees.size(); ++i) {\n        if (!visited[i]) {\n            int current = i;\n            path.clear();\n            while (!visited[current]) {\n                visited[current] = true;\n                path.push_back(current);\n                int t = count(actual.begin(), actual.end(), current);\n                if (t % 2 == 1) {\n                    current = employees[current].a;\n                } else {\n                    current = employees[current].b;\n                }\n            }\n\n            // Check if the current path is a cycle\n            auto it = find(path.begin(), path.end(), current);\n            if (it != path.end()) {\n                int cycle_length = distance(it, path.end());\n                int cycle_start = distance(path.begin(), it);\n                int cycle_repeats = (L - cycle_start) / cycle_length;\n                int remaining = (L - cycle_start) % cycle_length;\n\n                for (int j = cycle_start; j < path.size(); ++j) {\n                    actual[path[j]] += cycle_repeats;\n                }\n                for (int j = 0; j < remaining; ++j) {\n                    actual[path[cycle_start + j]]++;\n                }\n            } else {\n                for (int j = 0; j < path.size(); ++j) {\n                    actual[path[j]]++;\n                }\n            }\n        }\n    }\n\n    return actual;\n}\n\nint calculate_error(const vector<int>& actual, const vector<int>& target) {\n    int error = 0;\n    for (size_t i = 0; i < actual.size(); ++i) {\n        error += abs(actual[i] - target[i]);\n    }\n    return error;\n}\n\nvector<Employee> generate_initial_state(int N) {\n    vector<Employee> employees(N);\n    for (int i = 0; i < N; ++i) {\n        employees[i].a = i;\n        employees[i].b = i;\n    }\n    return employees;\n}\n\nvector<Employee> hill_climbing(const vector<int>& target, int N, int L, int iterations) {\n    vector<Employee> current_employees = generate_initial_state(N);\n    vector<int> current_actual = simulate_cleaning_plan(current_employees, L);\n    int current_error = calculate_error(current_actual, target);\n\n    for (int i = 0; i < iterations; ++i) {\n        vector<Employee> new_employees = current_employees;\n        int employee = rand() % N;\n        int choice = rand() % 2;\n\n        if (choice == 0) {\n            new_employees[employee].a = rand() % N;\n        } else {\n            new_employees[employee].b = rand() % N;\n        }\n\n        vector<int> new_actual = simulate_cleaning_plan(new_employees, L);\n        int new_error = calculate_error(new_actual, target);\n\n        if (new_error < current_error) {\n            current_employees = new_employees;\n            current_error = new_error;\n        }\n    }\n\n    return current_employees;\n}\n\nint main() {\n    int N, L;\n    cin >> N >> L;\n\n    vector<int> target(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> target[i];\n    }\n\n    int iterations = 10000;\n    vector<Employee> best_employees = hill_climbing(target, N, L, iterations);\n\n    for (const auto& employee : best_employees) {\n        cout << employee.a << \" \" << employee.b << endl;\n    }\n\n    return 0;\n}","ahc045":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <random>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <limits>\n#include <functional>\n\nusing namespace std;\n\nstruct City {\n    int id;\n    int lx, rx, ly, ry;\n    double cx, cy; // Center coordinates\n};\n\nstruct Edge {\n    int u, v;\n    double distance;\n};\n\nstruct CompareEdge {\n    bool operator()(const Edge& a, const Edge& b) {\n        return a.distance > b.distance;\n    }\n};\n\nvector<Edge> query(const vector<int>& cities) {\n    cout << \"? \" << cities.size();\n    for (int city : cities) {\n        cout << \" \" << city;\n    }\n    cout << endl;\n    cout.flush();\n\n    vector<Edge> edges;\n    for (size_t i = 0; i < cities.size() - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        edges.push_back({u, v, 0.0}); // Distance will be calculated later\n    }\n    return edges;\n}\n\nvoid answer(const vector<vector<int>>& groups, const vector<vector<Edge>>& edges) {\n    cout << \"!\" << endl;\n    for (size_t i = 0; i < groups.size(); ++i) {\n        for (int city : groups[i]) {\n            cout << city << \" \";\n        }\n        cout << endl;\n        for (const Edge& edge : edges[i]) {\n            cout << edge.u << \" \" << edge.v << endl;\n        }\n    }\n}\n\nvector<vector<int>> greedyGrouping(const vector<City>& cities, const vector<int>& G) {\n    vector<City> sortedCities = cities;\n    sort(sortedCities.begin(), sortedCities.end(), [](const City& a, const City& b) {\n        return a.cx < b.cx || (a.cx == b.cx && a.cy < b.cy);\n    });\n\n    vector<vector<int>> groups;\n    size_t startIdx = 0;\n    for (int g : G) {\n        vector<int> group;\n        for (size_t i = startIdx; i < startIdx + g; ++i) {\n            group.push_back(sortedCities[i].id);\n        }\n        groups.push_back(group);\n        startIdx += g;\n    }\n    return groups;\n}\n\nvector<Edge> calculateMST(const vector<int>& group, const vector<City>& cities) {\n    unordered_map<int, int> cityToIndex;\n    for (size_t i = 0; i < cities.size(); ++i) {\n        cityToIndex[cities[i].id] = i;\n    }\n\n    vector<vector<double>> dist(group.size(), vector<double>(group.size(), 0.0));\n    for (size_t i = 0; i < group.size(); ++i) {\n        for (size_t j = i + 1; j < group.size(); ++j) {\n            const City& a = cities[cityToIndex[group[i]]];\n            const City& b = cities[cityToIndex[group[j]]];\n            double dx = a.cx - b.cx;\n            double dy = a.cy - b.cy;\n            dist[i][j] = dist[j][i] = sqrt(dx * dx + dy * dy);\n        }\n    }\n\n    priority_queue<Edge, vector<Edge>, CompareEdge> pq;\n    for (size_t i = 0; i < group.size(); ++i) {\n        for (size_t j = i + 1; j < group.size(); ++j) {\n            pq.push({group[i], group[j], dist[i][j]});\n        }\n    }\n\n    vector<Edge> mstEdges;\n    vector<int> parent(group.size(), -1);\n    vector<int> rank(group.size(), 0);\n\n    function<int(int)> find = [&](int u) {\n        if (parent[u] == -1) return u;\n        return parent[u] = find(parent[u]);\n    };\n\n    while (!pq.empty() && mstEdges.size() < group.size() - 1) {\n        Edge edge = pq.top();\n        pq.pop();\n        int u = find(edge.u);\n        int v = find(edge.v);\n        if (u != v) {\n            mstEdges.push_back(edge);\n            if (rank[u] > rank[v]) {\n                parent[v] = u;\n            } else {\n                parent[u] = v;\n                if (rank[u] == rank[v]) {\n                    rank[v]++;\n                }\n            }\n        }\n    }\n    return mstEdges;\n}\n\nint main() {\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> G[i];\n    }\n\n    vector<City> cities(N);\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cities[i] = {i, lx, rx, ly, ry, (lx + rx) / 2.0, (ly + ry) / 2.0};\n    }\n\n    vector<vector<int>> groups = greedyGrouping(cities, G);\n    vector<vector<Edge>> edges(M);\n\n    for (int k = 0; k < M; ++k) {\n        for (size_t i = 0; i < groups[k].size() - 1; i += 2) {\n            if (i < groups[k].size() - 2) {\n                vector<int> queryCities = {groups[k][i], groups[k][i + 1], groups[k][i + 2]};\n                vector<Edge> queryEdges = query(queryCities);\n                edges[k].insert(edges[k].end(), queryEdges.begin(), queryEdges.end());\n            } else {\n                edges[k].push_back({groups[k][i], groups[k][i + 1], 0.0});\n            }\n        }\n    }\n\n    answer(groups, edges);\n\n    return 0;\n}","ahc046":"#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nconst int N = 20;\nconst int M = 40;\nconst int MAX_ACTIONS = 2 * N * M;\n\nstruct Point {\n    int x, y;\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point& other) const {\n        return x == other.x && y == other.y;\n    }\n};\n\nnamespace std {\n    template<>\n    struct hash<Point> {\n        size_t operator()(const Point& p) const {\n            return hash<int>()(p.x) ^ hash<int>()(p.y);\n        }\n    };\n}\n\nstruct State {\n    Point pos;\n    unordered_set<Point> blocks;\n    int visited;\n    int actions;\n    State(Point pos, unordered_set<Point> blocks, int visited, int actions)\n        : pos(pos), blocks(blocks), visited(visited), actions(actions) {}\n};\n\nstruct Action {\n    char type;\n    char direction;\n    Action(char type, char direction) : type(type), direction(direction) {}\n};\n\nvector<Action> directions = {\n    {'U', 'U'}, {'D', 'D'}, {'L', 'L'}, {'R', 'R'}\n};\n\nvector<Action> actions = {\n    {'M', 'U'}, {'M', 'D'}, {'M', 'L'}, {'M', 'R'},\n    {'S', 'U'}, {'S', 'D'}, {'S', 'L'}, {'S', 'R'},\n    {'A', 'U'}, {'A', 'D'}, {'A', 'L'}, {'A', 'R'}\n};\n\nbool isValid(Point p) {\n    return p.x >= 0 && p.x < N && p.y >= 0 && p.y < N;\n}\n\nPoint move(Point p, char direction) {\n    switch (direction) {\n        case 'U': return Point(p.x - 1, p.y);\n        case 'D': return Point(p.x + 1, p.y);\n        case 'L': return Point(p.x, p.y - 1);\n        case 'R': return Point(p.x, p.y + 1);\n    }\n    return p;\n}\n\nPoint slide(Point p, char direction, const unordered_set<Point>& blocks) {\n    Point next = p;\n    while (true) {\n        Point newPos = move(next, direction);\n        if (!isValid(newPos) || blocks.count(newPos)) break;\n        next = newPos;\n    }\n    return next;\n}\n\nunordered_set<Point> alter(Point p, char direction, unordered_set<Point> blocks) {\n    Point target = move(p, direction);\n    if (isValid(target)) {\n        if (blocks.count(target)) {\n            blocks.erase(target);\n        } else {\n            blocks.insert(target);\n        }\n    }\n    return blocks;\n}\n\nint heuristic(Point a, Point b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\nvector<Action> solve(vector<Point> targets) {\n    vector<Action> result;\n    unordered_set<Point> blocks;\n    Point current = targets[0];\n    int visited = 0;\n\n    for (int i = 1; i < targets.size(); ++i) {\n        Point target = targets[i];\n        priority_queue<pair<int, State>, vector<pair<int, State>>, greater<pair<int, State>>> pq;\n        unordered_set<Point> initialBlocks = blocks;\n        pq.push({heuristic(current, target), State(current, initialBlocks, visited, 0)});\n\n        while (!pq.empty()) {\n            auto [cost, state] = pq.top();\n            pq.pop();\n\n            if (state.pos == target) {\n                current = target;\n                visited = i;\n                blocks = state.blocks;\n                break;\n            }\n\n            if (state.actions >= MAX_ACTIONS) continue;\n\n            for (auto& action : actions) {\n                Point newPos = state.pos;\n                unordered_set<Point> newBlocks = state.blocks;\n                int newVisited = state.visited;\n                int newActions = state.actions + 1;\n\n                if (action.type == 'M') {\n                    newPos = move(state.pos, action.direction);\n                    if (!isValid(newPos) || newBlocks.count(newPos)) continue;\n                } else if (action.type == 'S') {\n                    newPos = slide(state.pos, action.direction, newBlocks);\n                } else if (action.type == 'A') {\n                    newBlocks = alter(state.pos, action.direction, newBlocks);\n                }\n\n                if (newPos == target) newVisited = i;\n\n                int newCost = newActions + heuristic(newPos, target);\n                pq.push({newCost, State(newPos, newBlocks, newVisited, newActions)});\n            }\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    vector<Point> targets;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        targets.emplace_back(x, y);\n    }\n\n    vector<Action> result = solve(targets);\n    for (auto& action : result) {\n        cout << action.type << \" \" << action.direction << endl;\n    }\n\n    return 0;\n}"}}}