{"model_name":"claude-4.5-haiku","codes":{"1":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int id;\n    long long x, y, r;\n};\n\nvector<array<long long, 4>> result(205);\n\nvoid assign(vector<int> indices, const vector<Company>& companies, \n            long long x1, long long y1, long long x2, long long y2) {\n    if (indices.empty()) return;\n    if (indices.size() == 1) {\n        result[indices[0]] = {x1, y1, x2, y2};\n        return;\n    }\n    \n    // Try vertical split at median x coordinate\n    vector<long long> xs;\n    for (int idx : indices) {\n        xs.push_back(companies[idx].x);\n    }\n    sort(xs.begin(), xs.end());\n    \n    long long split_x = xs[xs.size() / 2] + 1;\n    split_x = max(x1 + 1, min(x2 - 1, split_x));\n    \n    vector<int> left, right;\n    for (int idx : indices) {\n        if (companies[idx].x < split_x) {\n            left.push_back(idx);\n        } else {\n            right.push_back(idx);\n        }\n    }\n    \n    if (!left.empty() && !right.empty()) {\n        assign(left, companies, x1, y1, split_x, y2);\n        assign(right, companies, split_x, y1, x2, y2);\n    } else {\n        // Try horizontal split at median y coordinate\n        vector<long long> ys;\n        for (int idx : indices) {\n            ys.push_back(companies[idx].y);\n        }\n        sort(ys.begin(), ys.end());\n        \n        long long split_y = ys[ys.size() / 2] + 1;\n        split_y = max(y1 + 1, min(y2 - 1, split_y));\n        \n        vector<int> bottom, top;\n        for (int idx : indices) {\n            if (companies[idx].y < split_y) {\n                bottom.push_back(idx);\n            } else {\n                top.push_back(idx);\n            }\n        }\n        \n        assign(bottom, companies, x1, y1, x2, split_y);\n        assign(top, companies, x1, split_y, x2, y2);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    vector<Company> companies(n);\n    \n    for (int i = 0; i < n; i++) {\n        companies[i].id = i;\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n    \n    vector<int> indices(n);\n    iota(indices.begin(), indices.end(), 0);\n    \n    assign(indices, companies, 0, 0, 10000, 10000);\n    \n    for (int i = 0; i < n; i++) {\n        cout << result[i][0] << \" \" << result[i][1] << \" \" \n             << result[i][2] << \" \" << result[i][3] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint si, sj;\nvector<vector<int>> tile;\nvector<vector<int>> value;\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dc[] = {'U', 'D', 'L', 'R'};\n\nint best_score = 0;\nstring best_path = \"\";\nchrono::high_resolution_clock::time_point start_time;\nconst double TIME_LIMIT = 1.95;\nint call_count = 0;\n\nbool time_exceeded() {\n    call_count++;\n    if (call_count % 100000 == 0) {\n        auto now = chrono::high_resolution_clock::now();\n        double elapsed = chrono::duration<double>(now - start_time).count();\n        return elapsed > TIME_LIMIT;\n    }\n    return false;\n}\n\nvoid dfs(int i, int j, vector<bool>& visited_tiles, string& path, int score) {\n    if (time_exceeded()) return;\n    \n    if (score > best_score) {\n        best_score = score;\n        best_path = path;\n    }\n    \n    for (int d = 0; d < 4; d++) {\n        int ni = i + dx[d];\n        int nj = j + dy[d];\n        \n        if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n            int new_tile = tile[ni][nj];\n            if (!visited_tiles[new_tile]) {\n                visited_tiles[new_tile] = true;\n                path.push_back(dc[d]);\n                dfs(ni, nj, visited_tiles, path, score + value[ni][nj]);\n                path.pop_back();\n                visited_tiles[new_tile] = false;\n            }\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> si >> sj;\n    \n    tile.assign(50, vector<int>(50));\n    value.assign(50, vector<int>(50));\n    \n    int max_tile = 0;\n    for (int i = 0; i < 50; i++) {\n        for (int j = 0; j < 50; j++) {\n            cin >> tile[i][j];\n            max_tile = max(max_tile, tile[i][j]);\n        }\n    }\n    \n    for (int i = 0; i < 50; i++) {\n        for (int j = 0; j < 50; j++) {\n            cin >> value[i][j];\n        }\n    }\n    \n    start_time = chrono::high_resolution_clock::now();\n    best_score = value[si][sj];\n    vector<bool> visited_tiles(max_tile + 1, false);\n    visited_tiles[tile[si][sj]] = true;\n    string path = \"\";\n    dfs(si, sj, visited_tiles, path, value[si][sj]);\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\n#include <queue>\nusing namespace std;\n\nconst int N = 30;\nconst double INF = 1e18;\n\ndouble h[N][N-1], v[N-1][N];\n\nstruct State {\n    double dist;\n    int i, j;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\npair<string, double> dijkstra(int si, int sj, int ti, int tj) {\n    vector<vector<double>> dist(N, vector<double>(N, INF));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1, -1}));\n    vector<vector<char>> dir(N, vector<char>(N));\n    \n    priority_queue<State, vector<State>, greater<State>> pq;\n    dist[si][sj] = 0;\n    pq.push({0, si, sj});\n    \n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top();\n        pq.pop();\n        \n        if (d > dist[i][j]) continue;\n        \n        // Up\n        if (i > 0) {\n            double new_dist = d + v[i-1][j];\n            if (new_dist < dist[i-1][j]) {\n                dist[i-1][j] = new_dist;\n                parent[i-1][j] = {i, j};\n                dir[i-1][j] = 'U';\n                pq.push({new_dist, i-1, j});\n            }\n        }\n        \n        // Down\n        if (i < N-1) {\n            double new_dist = d + v[i][j];\n            if (new_dist < dist[i+1][j]) {\n                dist[i+1][j] = new_dist;\n                parent[i+1][j] = {i, j};\n                dir[i+1][j] = 'D';\n                pq.push({new_dist, i+1, j});\n            }\n        }\n        \n        // Left\n        if (j > 0) {\n            double new_dist = d + h[i][j-1];\n            if (new_dist < dist[i][j-1]) {\n                dist[i][j-1] = new_dist;\n                parent[i][j-1] = {i, j};\n                dir[i][j-1] = 'L';\n                pq.push({new_dist, i, j-1});\n            }\n        }\n        \n        // Right\n        if (j < N-1) {\n            double new_dist = d + h[i][j];\n            if (new_dist < dist[i][j+1]) {\n                dist[i][j+1] = new_dist;\n                parent[i][j+1] = {i, j};\n                dir[i][j+1] = 'R';\n                pq.push({new_dist, i, j+1});\n            }\n        }\n    }\n    \n    string path;\n    int ci = ti, cj = tj;\n    while (parent[ci][cj].first != -1) {\n        path += dir[ci][cj];\n        auto [pi, pj] = parent[ci][cj];\n        ci = pi;\n        cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    \n    return {path, dist[ti][tj]};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Initialize edge weights to 5000 (middle of expected range)\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N-1; j++) {\n            h[i][j] = 5000.0;\n        }\n    }\n    for (int i = 0; i < N-1; i++) {\n        for (int j = 0; j < N; j++) {\n            v[i][j] = 5000.0;\n        }\n    }\n    \n    for (int q = 0; q < 1000; q++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        auto [path, computed_length] = dijkstra(si, sj, ti, tj);\n        \n        cout << path << endl;\n        cout.flush();\n        \n        long long feedback;\n        cin >> feedback;\n        \n        // Update edge weights based on feedback\n        if (!path.empty()) {\n            double edge_estimate = (double)feedback / path.length();\n            double alpha = 0.05;  // Weight for new data\n            \n            int ci = si, cj = sj;\n            for (char c : path) {\n                if (c == 'U') {\n                    v[ci-1][cj] = (1 - alpha) * v[ci-1][cj] + alpha * edge_estimate;\n                    ci--;\n                } else if (c == 'D') {\n                    v[ci][cj] = (1 - alpha) * v[ci][cj] + alpha * edge_estimate;\n                    ci++;\n                } else if (c == 'L') {\n                    h[ci][cj-1] = (1 - alpha) * h[ci][cj-1] + alpha * edge_estimate;\n                    cj--;\n                } else if (c == 'R') {\n                    h[ci][cj] = (1 - alpha) * h[ci][cj] + alpha * edge_estimate;\n                    cj++;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc004":"#include<bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<string> strings;\nchar matrix[20][20];\nchar bestMatrix[20][20];\nint bestMatches = 0;\n\nbool isSubsequence(const string& s) {\n    int len = (int)s.length();\n    \n    // Check horizontal\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            bool found = true;\n            for(int p = 0; p < len; p++) {\n                if(matrix[i][(j+p)%N] != s[p]) {\n                    found = false;\n                    break;\n                }\n            }\n            if(found) return true;\n        }\n    }\n    \n    // Check vertical\n    for(int j = 0; j < N; j++) {\n        for(int i = 0; i < N; i++) {\n            bool found = true;\n            for(int p = 0; p < len; p++) {\n                if(matrix[(i+p)%N][j] != s[p]) {\n                    found = false;\n                    break;\n                }\n            }\n            if(found) return true;\n        }\n    }\n    \n    return false;\n}\n\nint countMatches() {\n    int c = 0;\n    for(const auto& s : strings) {\n        if(isSubsequence(s)) c++;\n    }\n    return c;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    strings.resize(M);\n    for(int i = 0; i < M; i++) {\n        cin >> strings[i];\n    }\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> charDist(0, 7);\n    uniform_int_distribution<int> posDist(0, N-1);\n    uniform_int_distribution<int> dirDist(0, 1);\n    uniform_real_distribution<double> realDist(0, 1);\n    \n    // Initialize matrix\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            matrix[i][j] = 'A' + charDist(rng);\n        }\n    }\n    \n    // Warm start: place some strings\n    for(const auto& s : strings) {\n        if(realDist(rng) < 0.3) {\n            int i = posDist(rng);\n            int j = posDist(rng);\n            int dir = dirDist(rng);\n            int len = (int)s.length();\n            \n            if(dir == 0) {  // horizontal\n                for(int p = 0; p < len; p++) {\n                    matrix[i][(j+p)%N] = s[p];\n                }\n            } else {  // vertical\n                for(int p = 0; p < len; p++) {\n                    matrix[(i+p)%N][j] = s[p];\n                }\n            }\n        }\n    }\n    \n    int currentMatches = countMatches();\n    memcpy(bestMatrix, matrix, sizeof(matrix));\n    bestMatches = currentMatches;\n    \n    // Simulated annealing\n    double temp = 10.0;\n    const double coolingRate = 0.999998;\n    \n    auto deadline = chrono::steady_clock::now() + chrono::milliseconds(2850);\n    \n    while(chrono::steady_clock::now() < deadline && temp > 0.0001) {\n        int i = posDist(rng);\n        int j = posDist(rng);\n        \n        char old = matrix[i][j];\n        char newChar = 'A' + charDist(rng);\n        \n        if(newChar == old) continue;\n        \n        matrix[i][j] = newChar;\n        \n        int newMatches = countMatches();\n        int delta = newMatches - currentMatches;\n        \n        if(delta >= 0) {\n            currentMatches = newMatches;\n            if(currentMatches > bestMatches) {\n                bestMatches = currentMatches;\n                memcpy(bestMatrix, matrix, sizeof(matrix));\n            }\n        } else {\n            if(realDist(rng) < exp((double)delta / temp)) {\n                currentMatches = newMatches;\n            } else {\n                matrix[i][j] = old;\n            }\n        }\n        \n        temp *= coolingRate;\n    }\n    \n    // Output best result\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            cout << bestMatrix[i][j];\n        }\n        cout << '\\n';\n    }\n    \n    return 0;\n}","ahc005":"#include<bits/stdc++.h>\nusing namespace std;\n\nint N, si, sj;\nvector<string> grid;\n\nset<pair<int,int>> getVisible(int i, int j) {\n    set<pair<int,int>> result;\n    if (grid[i][j] == '#') return result;\n    \n    // Check in all 4 directions: right, left, down, up\n    for (int jj = j; jj < N && grid[i][jj] != '#'; jj++) {\n        result.insert({i, jj});\n    }\n    for (int jj = j - 1; jj >= 0 && grid[i][jj] != '#'; jj--) {\n        result.insert({i, jj});\n    }\n    for (int ii = i; ii < N && grid[ii][j] != '#'; ii++) {\n        result.insert({ii, j});\n    }\n    for (int ii = i - 1; ii >= 0 && grid[ii][j] != '#'; ii--) {\n        result.insert({ii, j});\n    }\n    \n    return result;\n}\n\nvector<pair<int,int>> getPath(pair<int,int> from, pair<int,int> to) {\n    if (from == to) return {from};\n    \n    map<pair<int,int>, pair<int,int>> parent;\n    queue<pair<int,int>> q;\n    q.push(from);\n    parent[from] = {-1, -1};\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        if (make_pair(i, j) == to) {\n            vector<pair<int,int>> path;\n            auto cur = to;\n            while (cur != make_pair(-1, -1)) {\n                path.push_back(cur);\n                cur = parent[cur];\n            }\n            reverse(path.begin(), path.end());\n            return path;\n        }\n        \n        int di[] = {-1, 1, 0, 0};\n        int dj[] = {0, 0, -1, 1};\n        for (int d = 0; d < 4; d++) {\n            int ni = i + di[d];\n            int nj = j + dj[d];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && \n                grid[ni][nj] != '#' && !parent.count({ni, nj})) {\n                parent[{ni, nj}] = {i, j};\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    return {};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> si >> sj;\n    grid.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    \n    // Collect all roads\n    vector<pair<int,int>> allRoads;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                allRoads.push_back({i, j});\n            }\n        }\n    }\n    \n    // Greedy waypoint selection\n    set<pair<int,int>> covered;\n    for (auto cell : getVisible(si, sj)) {\n        covered.insert(cell);\n    }\n    \n    vector<pair<int,int>> waypoints;\n    waypoints.push_back({si, sj});\n    \n    int maxIter = min(500, (int)allRoads.size());\n    \n    while ((int)covered.size() < (int)allRoads.size() && waypoints.size() < maxIter) {\n        pair<int,int> best = {-1, -1};\n        int bestNew = -1;\n        \n        // Find cell that covers most uncovered roads\n        for (auto [i, j] : allRoads) {\n            int newCount = 0;\n            for (auto cell : getVisible(i, j)) {\n                if (covered.find(cell) == covered.end()) {\n                    newCount++;\n                }\n            }\n            if (newCount > bestNew) {\n                bestNew = newCount;\n                best = {i, j};\n            }\n        }\n        \n        if (bestNew <= 0) break;\n        \n        for (auto cell : getVisible(best.first, best.second)) {\n            covered.insert(cell);\n        }\n        waypoints.push_back(best);\n    }\n    \n    // Return to start\n    waypoints.push_back({si, sj});\n    \n    // Convert waypoints to movement sequence\n    string result = \"\";\n    for (size_t idx = 0; idx + 1 < waypoints.size(); idx++) {\n        auto path = getPath(waypoints[idx], waypoints[idx + 1]);\n        \n        for (size_t pos = 1; pos < path.size(); pos++) {\n            auto [pi, pj] = path[pos - 1];\n            auto [ni, nj] = path[pos];\n            \n            if (ni < pi) result += 'U';\n            else if (ni > pi) result += 'D';\n            else if (nj < pj) result += 'L';\n            else result += 'R';\n        }\n    }\n    \n    cout << result << endl;\n    \n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n    \n    vector<vector<int>> d(N, vector<int>(K));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < K; j++) {\n            cin >> d[i][j];\n        }\n    }\n    \n    vector<vector<int>> rev_deps(N);\n    vector<set<int>> deps(N);\n    vector<int> indeg(N, 0);\n    \n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        deps[v].insert(u);\n        rev_deps[u].push_back(v);\n        indeg[v]++;\n    }\n    \n    // Compute critical path depth for prioritization\n    vector<int> depth(N, 0);\n    vector<int> indeg_copy = indeg;\n    queue<int> q;\n    for (int i = 0; i < N; i++) {\n        if (indeg_copy[i] == 0) q.push(i);\n    }\n    while (!q.empty()) {\n        int u = q.front(); q.pop();\n        for (int v : rev_deps[u]) {\n            depth[v] = max(depth[v], depth[u] + 1);\n            indeg_copy[v]--;\n            if (indeg_copy[v] == 0) q.push(v);\n        }\n    }\n    \n    vector<int> task_status(N, -1); // -1: not started, day: started, 2000+: completed\n    vector<int> task_start_day(N, -1);\n    vector<int> member_task(M, -1);\n    \n    vector<vector<double>> skills(M, vector<double>(K, 10.0));\n    \n    auto estimate_time = [&](int member, int task) {\n        double w = 0.0;\n        for (int k = 0; k < K; k++) {\n            w += max(0.0, (double)d[task][k] - skills[member][k]);\n        }\n        return max(1.0, w);\n    };\n    \n    int day = 0, completed = 0;\n    \n    while (day < 2000 && completed < N) {\n        day++;\n        \n        vector<pair<int, int>> assignments;\n        \n        // Assign tasks to idle members\n        for (int j = 0; j < M; j++) {\n            if (member_task[j] != -1) continue;\n            \n            int best_task = -1;\n            double best_score = 1e18;\n            \n            for (int i = 0; i < N; i++) {\n                if (task_status[i] != -1) continue;\n                \n                // Check dependencies\n                bool deps_ok = true;\n                for (int dep : deps[i]) {\n                    if (task_status[dep] < 2000) {\n                        deps_ok = false;\n                        break;\n                    }\n                }\n                if (!deps_ok) continue;\n                \n                double time = estimate_time(j, i);\n                double score = time - 0.1 * depth[i];\n                \n                if (score < best_score) {\n                    best_score = score;\n                    best_task = i;\n                }\n            }\n            \n            if (best_task != -1) {\n                assignments.push_back({j + 1, best_task + 1});\n                member_task[j] = best_task;\n                task_status[best_task] = day;\n                task_start_day[best_task] = day;\n            }\n        }\n        \n        cout << assignments.size();\n        for (auto [j, i] : assignments) {\n            cout << \" \" << j << \" \" << i;\n        }\n        cout << \"\\n\";\n        cout.flush();\n        \n        int n;\n        cin >> n;\n        if (n == -1) break;\n        \n        for (int i = 0; i < n; i++) {\n            int j;\n            cin >> j;\n            j--;\n            \n            if (member_task[j] != -1) {\n                int task = member_task[j];\n                int duration = day - task_start_day[task] + 1;\n                \n                task_status[task] = 2000 + day;\n                member_task[j] = -1;\n                completed++;\n                \n                // Learn skills from completion time\n                double w_est = max(0.0, (double)duration - 2.0);\n                \n                double total_req = 0.0;\n                for (int k = 0; k < K; k++) {\n                    total_req += d[task][k];\n                }\n                \n                if (total_req > 0.0) {\n                    for (int k = 0; k < K; k++) {\n                        double frac = (double)d[task][k] / total_req;\n                        skills[j][k] = max(skills[j][k], d[task][k] - frac * w_est);\n                    }\n                }\n                \n                if (duration == 1) {\n                    for (int k = 0; k < K; k++) {\n                        skills[j][k] = max(skills[j][k], (double)d[task][k]);\n                    }\n                }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nll manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    struct Order {\n        int a, b, c, d;\n    };\n    \n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; i++) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n    }\n    \n    // Select 50 orders based on estimated cost\n    vector<pair<ll, int>> costs;\n    for (int i = 0; i < 1000; i++) {\n        ll cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                  manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d) +\n                  manhattan(orders[i].c, orders[i].d, 400, 400);\n        costs.push_back({cost, i});\n    }\n    \n    sort(costs.begin(), costs.end());\n    \n    vector<int> selected(50);\n    for (int i = 0; i < 50; i++) {\n        selected[i] = costs[i].second;\n    }\n    \n    // Build route with nearest neighbor respecting constraints\n    vector<pair<int, int>> route;\n    route.push_back({400, 400});\n    \n    vector<bool> pickup_done(50, false);\n    vector<bool> delivery_done(50, false);\n    \n    int cx = 400, cy = 400;\n    \n    for (int step = 0; step < 100; step++) {\n        int best_i = -1, best_type = -1;\n        ll best_dist = LLONG_MAX;\n        \n        for (int i = 0; i < 50; i++) {\n            // Try picking up this order if not yet done\n            if (!pickup_done[i]) {\n                ll d = manhattan(cx, cy, orders[selected[i]].a, orders[selected[i]].b);\n                if (d < best_dist) {\n                    best_dist = d;\n                    best_i = i;\n                    best_type = 0;\n                }\n            }\n            // Try delivering if pickup is done but delivery is not\n            if (pickup_done[i] && !delivery_done[i]) {\n                ll d = manhattan(cx, cy, orders[selected[i]].c, orders[selected[i]].d);\n                if (d < best_dist) {\n                    best_dist = d;\n                    best_i = i;\n                    best_type = 1;\n                }\n            }\n        }\n        \n        if (best_i == -1) break;\n        \n        if (best_type == 0) {\n            cx = orders[selected[best_i]].a;\n            cy = orders[selected[best_i]].b;\n            pickup_done[best_i] = true;\n        } else {\n            cx = orders[selected[best_i]].c;\n            cy = orders[selected[best_i]].d;\n            delivery_done[best_i] = true;\n        }\n        \n        route.push_back({cx, cy});\n    }\n    \n    route.push_back({400, 400});\n    \n    // Output\n    cout << \"50\";\n    for (int i = 0; i < 50; i++) {\n        cout << \" \" << (selected[i] + 1);\n    }\n    cout << \"\\n\";\n    \n    cout << route.size();\n    for (const auto& p : route) {\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass UnionFind {\npublic:\n    vector<int> parent;\n    \n    UnionFind(int n) : parent(n) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    \n    int find(int x) {\n        if (parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    \n    bool unite(int x, int y) {\n        x = find(x);\n        y = find(y);\n        if (x == y) return false;\n        parent[y] = x;\n        return true;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N = 400, M = 1995;\n    vector<pair<int, int>> coords(N);\n    vector<pair<int, int>> edges(M);\n    vector<int> d(M);\n    \n    for (int i = 0; i < N; i++) {\n        cin >> coords[i].first >> coords[i].second;\n    }\n    \n    for (int i = 0; i < M; i++) {\n        cin >> edges[i].first >> edges[i].second;\n        int u = edges[i].first, v = edges[i].second;\n        long long dx = (long long)coords[u].first - coords[v].first;\n        long long dy = (long long)coords[u].second - coords[v].second;\n        d[i] = (int)round(sqrt((double)(dx*dx + dy*dy)));\n    }\n    \n    UnionFind uf(N);\n    int edges_needed = N - 1;\n    \n    for (int i = 0; i < M; i++) {\n        int length;\n        cin >> length;\n        \n        int u = edges[i].first, v = edges[i].second;\n        \n        bool accept = false;\n        if (uf.find(u) != uf.find(v)) {\n            // Tree edge: connects different components\n            if (M - i <= edges_needed || length <= 2 * d[i]) {\n                accept = true;\n            }\n        }\n        // Cycle edges are always rejected\n        \n        if (accept) {\n            uf.unite(u, v);\n            edges_needed--;\n        }\n        \n        cout << (accept ? 1 : 0) << '\\n';\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    \n    int N;\n    cin >> N;\n    vector<pair<int,int>> pets(N);\n    vector<int> pet_types(N);\n    for(int i = 0; i < N; i++){\n        int x, y, t;\n        cin >> x >> y >> t;\n        pets[i] = {x-1, y-1};\n        pet_types[i] = t;\n    }\n    \n    int M;\n    cin >> M;\n    vector<pair<int,int>> humans(M);\n    for(int i = 0; i < M; i++){\n        int x, y;\n        cin >> x >> y;\n        humans[i] = {x-1, y-1};\n    }\n    \n    for(int turn = 0; turn < 300; turn++){\n        string actions(M, '.');\n        \n        // Dynamic target based on game phase\n        int target_x, target_y;\n        if(turn < 80){\n            // Phase 1: Move toward top-left corner\n            target_x = 5;\n            target_y = 5;\n        } else if(turn < 200){\n            // Phase 2: Consolidate and expand slightly\n            target_x = 8;\n            target_y = 8;\n        } else {\n            // Phase 3: Hold position\n            target_x = 8;\n            target_y = 8;\n        }\n        \n        // Each human moves toward the target\n        for(int i = 0; i < M; i++){\n            int x = humans[i].first;\n            int y = humans[i].second;\n            \n            if(x > target_x) actions[i] = 'U';\n            else if(x < target_x) actions[i] = 'D';\n            else if(y > target_y) actions[i] = 'L';\n            else if(y < target_y) actions[i] = 'R';\n            else actions[i] = '.';\n        }\n        \n        cout << actions << endl;\n        cout.flush();\n        \n        // Read pet movements\n        for(int i = 0; i < N; i++){\n            string move;\n            cin >> move;\n            \n            // Apply movement to each pet\n            for(char c : move){\n                if(c == 'U' && pets[i].first > 0) pets[i].first--;\n                else if(c == 'D' && pets[i].first < 29) pets[i].first++;\n                else if(c == 'L' && pets[i].second > 0) pets[i].second--;\n                else if(c == 'R' && pets[i].second < 29) pets[i].second++;\n            }\n        }\n        \n        // Update human positions based on executed actions\n        for(int i = 0; i < M; i++){\n            if(actions[i] == 'U' && humans[i].first > 0) humans[i].first--;\n            else if(actions[i] == 'D' && humans[i].first < 29) humans[i].first++;\n            else if(actions[i] == 'L' && humans[i].second > 0) humans[i].second--;\n            else if(actions[i] == 'R' && humans[i].second < 29) humans[i].second++;\n        }\n    }\n    \n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n    \n    vector<string> h(20), v(19);\n    for (int i = 0; i < 20; i++) cin >> h[i];\n    for (int i = 0; i < 19; i++) cin >> v[i];\n    \n    // BFS to find shortest path\n    map<pair<int,int>, pair<pair<int,int>, char>> parent;\n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    parent[{si, sj}] = {{-1, -1}, ' '};\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        vector<tuple<int, int, char, bool>> moves = {\n            {i-1, j, 'U', i > 0 && v[i-1][j] == '0'},\n            {i+1, j, 'D', i < 19 && v[i][j] == '0'},\n            {i, j-1, 'L', j > 0 && h[i][j-1] == '0'},\n            {i, j+1, 'R', j < 19 && h[i][j] == '0'}\n        };\n        \n        for (auto [ni, nj, dir, valid] : moves) {\n            if (valid && parent.find({ni, nj}) == parent.end()) {\n                parent[{ni, nj}] = {{i, j}, dir};\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    // Reconstruct path\n    string path = \"\";\n    {\n        int i = ti, j = tj;\n        while (parent[{i, j}].first.first != -1) {\n            char c = parent[{i, j}].second;\n            path = c + path;\n            auto [pi, pj] = parent[{i, j}].first;\n            i = pi;\n            j = pj;\n        }\n    }\n    \n    // Try different repetition factors\n    int n = path.length();\n    string best_path = path;\n    double best_score = 0;\n    \n    for (int r = 1; r * n <= 200; r++) {\n        // Probability of success: (1 - p^r)^n\n        double p_fail = pow(p, (double)r);\n        double p_succ_one = 1.0 - p_fail;\n        double p_succ_all = pow(p_succ_one, (double)n);\n        \n        int length = r * n;\n        double expected_score = p_succ_all * (401.0 - length);\n        \n        if (expected_score > best_score) {\n            best_score = expected_score;\n            best_path = \"\";\n            for (int k = 0; k < r; k++) best_path += path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\n\nint di[] = {0, -1, 0, 1};\nint dj[] = {-1, 0, 1, 0};\n\nint to[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1},\n};\n\nint grid[N][N];\nint rotations[N][N];\n\ninline int getTileType(int i, int j) {\n    int base = grid[i][j];\n    int rot = rotations[i][j];\n    if (base < 4) return (base + rot) % 4;\n    if (base < 6) return 4 + (rot % 2);\n    return 6 + (rot % 2);\n}\n\nint computeLoopLength(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    for (int iter = 0; iter < 100000; iter++) {\n        int cur = getTileType(i, j);\n        int d2 = to[cur][d];\n        if (d2 == -1) return 0;\n        i += di[d2];\n        j += dj[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (i == si && j == sj && d == sd) return length;\n    }\n    return 0;\n}\n\nlong long computeScore() {\n    vector<int> loops;\n    bool visited[N][N][4] = {};\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            for (int d = 0; d < 4; d++) {\n                if (!visited[i][j][d]) {\n                    int len = computeLoopLength(i, j, d);\n                    if (len > 0) {\n                        loops.push_back(len);\n                        int ii = i, jj = j, dd = d;\n                        for (int step = 0; step < len; step++) {\n                            visited[ii][jj][dd] = true;\n                            int cur = getTileType(ii, jj);\n                            int d2 = to[cur][dd];\n                            ii += di[d2];\n                            jj += dj[d2];\n                            dd = (d2 + 2) % 4;\n                        }\n                    } else {\n                        visited[i][j][d] = true;\n                    }\n                }\n            }\n        }\n    }\n    if (loops.size() < 2) return 0;\n    sort(loops.rbegin(), loops.rend());\n    return (long long)loops[0] * loops[1];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    string line;\n    for (int i = 0; i < N; i++) {\n        cin >> line;\n        for (int j = 0; j < N; j++) {\n            grid[i][j] = line[j] - '0';\n        }\n    }\n    \n    memset(rotations, 0, sizeof(rotations));\n    long long bestScore = computeScore();\n    int best_rotations[N][N];\n    memcpy(best_rotations, rotations, sizeof(rotations));\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto start = chrono::steady_clock::now();\n    \n    while (chrono::duration_cast<chrono::milliseconds>(\n            chrono::steady_clock::now() - start).count() < 1950) {\n        int i = rng() % N;\n        int j = rng() % N;\n        int oldRot = rotations[i][j];\n        rotations[i][j] = rng() % 4;\n        \n        long long newScore = computeScore();\n        if (newScore > bestScore) {\n            bestScore = newScore;\n            memcpy(best_rotations, rotations, sizeof(rotations));\n        } else if ((rng() % 10000) < 500) {\n            memcpy(best_rotations, rotations, sizeof(rotations));\n        } else {\n            rotations[i][j] = oldRot;\n        }\n    }\n    \n    memcpy(rotations, best_rotations, sizeof(rotations));\n    \n    string output(N * N, '0');\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            output[i * N + j] = '0' + rotations[i][j];\n        }\n    }\n    cout << output << endl;\n    \n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\n\nbool hasEdge(const vector<vector<int>>& board, int i1, int j1, int i2, int j2) {\n    if (i2 < 0 || i2 >= N || j2 < 0 || j2 >= N) return false;\n    if (board[i1][j1] == 0 || board[i2][j2] == 0) return false;\n    \n    int dy = i2 - i1, dx = j2 - j1;\n    if (dy == -1 && dx == 0) return (board[i1][j1] & 2) && (board[i2][j2] & 8);\n    if (dy == 1 && dx == 0) return (board[i1][j1] & 8) && (board[i2][j2] & 2);\n    if (dy == 0 && dx == -1) return (board[i1][j1] & 1) && (board[i2][j2] & 4);\n    if (dy == 0 && dx == 1) return (board[i1][j1] & 4) && (board[i2][j2] & 1);\n    return false;\n}\n\nint largestTree(const vector<vector<int>>& board) {\n    vector<vector<int>> comp(N, vector<int>(N, -1));\n    vector<int> vcount, ecount;\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (board[i][j] == 0 || comp[i][j] != -1) continue;\n            \n            int cid = vcount.size();\n            vcount.push_back(0);\n            ecount.push_back(0);\n            \n            queue<pair<int,int>> q;\n            q.push({i, j});\n            comp[i][j] = cid;\n            \n            while (!q.empty()) {\n                auto [ci, cj] = q.front();\n                q.pop();\n                vcount[cid]++;\n                \n                int di[] = {-1, 1, 0, 0};\n                int dj[] = {0, 0, -1, 1};\n                for (int d = 0; d < 4; d++) {\n                    int ni = ci + di[d];\n                    int nj = cj + dj[d];\n                    if (ni >= 0 && ni < N && nj >= 0 && nj < N && \n                        board[ni][nj] != 0 && comp[ni][nj] == -1 &&\n                        hasEdge(board, ci, cj, ni, nj)) {\n                        comp[ni][nj] = cid;\n                        q.push({ni, nj});\n                    }\n                }\n            }\n        }\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            if (j + 1 < N && hasEdge(board, i, j, i, j+1) && comp[i][j] == comp[i][j+1]) {\n                ecount[comp[i][j]]++;\n            }\n            if (i + 1 < N && hasEdge(board, i, j, i+1, j) && comp[i][j] == comp[i+1][j]) {\n                ecount[comp[i][j]]++;\n            }\n        }\n    }\n    \n    int ans = 0;\n    for (size_t c = 0; c < vcount.size(); c++) {\n        if (ecount[c] == vcount[c] - 1) {\n            ans = max(ans, vcount[c]);\n        }\n    }\n    return ans;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    \n    int ei = 0, ej = 0;\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            int v = s[j] >= 'a' ? s[j] - 'a' + 10 : s[j] - '0';\n            board[i][j] = v;\n            if (v == 0) ei = i, ej = j;\n        }\n    }\n    \n    string result = \"\";\n    int best_tree = largestTree(board);\n    int consecutive_no_improve = 0;\n    \n    while ((int)result.length() < T && best_tree < N * N - 1 && consecutive_no_improve < 20000) {\n        int best_score = best_tree - 1;\n        int best_dir = -1;\n        \n        int di[] = {-1, 1, 0, 0};\n        int dj[] = {0, 0, -1, 1};\n        char dirs[] = {'U', 'D', 'L', 'R'};\n        \n        vector<int> valid_dirs;\n        for (int d = 0; d < 4; d++) {\n            int ni = ei + di[d];\n            int nj = ej + dj[d];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                valid_dirs.push_back(d);\n                swap(board[ei][ej], board[ni][nj]);\n                int score = largestTree(board);\n                swap(board[ei][ej], board[ni][nj]);\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_dir = d;\n                }\n            }\n        }\n        \n        if (best_dir == -1) best_dir = valid_dirs[rand() % valid_dirs.size()];\n        \n        int ni = ei + di[best_dir];\n        int nj = ej + dj[best_dir];\n        swap(board[ei][ej], board[ni][nj]);\n        result += dirs[best_dir];\n        ei = ni;\n        ej = nj;\n        \n        int new_tree = largestTree(board);\n        if (new_tree > best_tree) {\n            best_tree = new_tree;\n            consecutive_no_improve = 0;\n        } else {\n            consecutive_no_improve++;\n        }\n    }\n    \n    cout << result << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, K;\n    cin >> N >> K;\n    \n    vector<int> a(11);\n    for (int d = 1; d <= 10; d++) {\n        cin >> a[d];\n    }\n    \n    vector<pair<long long, long long>> berries(N);\n    double cx = 0, cy = 0;\n    \n    for (int i = 0; i < N; i++) {\n        cin >> berries[i].first >> berries[i].second;\n        cx += berries[i].first;\n        cy += berries[i].second;\n    }\n    cx /= N;\n    cy /= N;\n    \n    vector<tuple<long long, long long, long long, long long>> cuts;\n    \n    // Create radial cuts emanating from center of mass\n    // These lines go through the center and radiate outward\n    // This creates a sectoral partition of the cake\n    int numCuts = min(K, 70);\n    \n    for (int i = 0; i < numCuts; i++) {\n        // Angle for the perpendicular direction of this cut\n        double angle = 2.0 * M_PI * i / numCuts;\n        \n        // Direction perpendicular to radial direction\n        double dx = cos(angle);\n        double dy = sin(angle);\n        \n        // Two points on the cutting line, far away to ensure they're outside the circle\n        long long px = (long long)round(cx + 500000 * dx);\n        long long py = (long long)round(cy + 500000 * dy);\n        long long qx = (long long)round(cx - 500000 * dx);\n        long long qy = (long long)round(cy - 500000 * dy);\n        \n        cuts.push_back({px, py, qx, qy});\n    }\n    \n    // Output the cuts\n    cout << (int)cuts.size() << \"\\n\";\n    for (const auto& [px, py, qx, qy] : cuts) {\n        cout << px << \" \" << py << \" \" << qx << \" \" << qy << \"\\n\";\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nset<pair<int,int>> dots;\nset<tuple<int,int,int,int>> used_edges;\n\nbool is_valid_point(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_segment_clear(int x1, int y1, int x2, int y2) {\n    if (x1 == x2) {\n        int miny = min(y1, y2), maxy = max(y1, y2);\n        for (int y = miny + 1; y < maxy; y++) {\n            if (dots.count({x1, y})) return false;\n        }\n    } else if (y1 == y2) {\n        int minx = min(x1, x2), maxx = max(x1, x2);\n        for (int x = minx + 1; x < maxx; x++) {\n            if (dots.count({x, y1})) return false;\n        }\n    } else {\n        int dx = (x2 > x1) ? 1 : -1;\n        int dy = (y2 > y1) ? 1 : -1;\n        int x = x1 + dx, y = y1 + dy;\n        while (x != x2 || y != y2) {\n            if (dots.count({x, y})) return false;\n            x += dx; y += dy;\n        }\n    }\n    return true;\n}\n\nauto normalize_edge = [](int x1, int y1, int x2, int y2) {\n    if (x1 > x2 || (x1 == x2 && y1 > y2)) swap(x1, x2), swap(y1, y2);\n    return make_tuple(x1, y1, x2, y2);\n};\n\nbool check_edge_overlap(int x1, int y1, int x2, int y2) {\n    return used_edges.count(normalize_edge(x1, y1, x2, y2));\n}\n\nbool is_valid_rect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (dots.count({x1, y1})) return false;\n    if (!dots.count({x2, y2}) || !dots.count({x3, y3}) || !dots.count({x4, y4})) return false;\n    \n    if (!check_segment_clear(x1, y1, x2, y2) || !check_segment_clear(x2, y2, x3, y3) ||\n        !check_segment_clear(x3, y3, x4, y4) || !check_segment_clear(x4, y4, x1, y1)) \n        return false;\n    \n    if (check_edge_overlap(x1, y1, x2, y2) || check_edge_overlap(x2, y2, x3, y3) ||\n        check_edge_overlap(x3, y3, x4, y4) || check_edge_overlap(x4, y4, x1, y1))\n        return false;\n    \n    return true;\n}\n\nvoid record_rect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    used_edges.insert(normalize_edge(x1, y1, x2, y2));\n    used_edges.insert(normalize_edge(x2, y2, x3, y3));\n    used_edges.insert(normalize_edge(x3, y3, x4, y4));\n    used_edges.insert(normalize_edge(x4, y4, x1, y1));\n}\n\ndouble weight(int x, int y) {\n    double c = (N - 1) / 2.0;\n    return (x - c) * (x - c) + (y - c) * (y - c) + 1;\n}\n\nint main() {\n    cin >> N >> M;\n    \n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        dots.insert({x, y});\n    }\n    \n    vector<tuple<int,int,int,int,int,int,int,int>> ops;\n    auto start = chrono::high_resolution_clock::now();\n    \n    bool found = true;\n    while (found) {\n        auto now = chrono::high_resolution_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - start).count() > 4800) break;\n        \n        found = false;\n        int bx1 = -1, by1 = -1, bx2 = -1, by2 = -1, bx3 = -1, by3 = -1, bx4 = -1, by4 = -1;\n        double best_w = -1;\n        \n        vector<pair<int,int>> dot_list(dots.begin(), dots.end());\n        \n        for (int i = 0; i < (int)dot_list.size(); i++) {\n            for (int j = i + 1; j < (int)dot_list.size(); j++) {\n                for (int k = j + 1; k < (int)dot_list.size(); k++) {\n                    auto [x2, y2] = dot_list[i];\n                    auto [x3, y3] = dot_list[j];\n                    auto [x4, y4] = dot_list[k];\n                    \n                    set<int> xs = {x2, x3, x4}, ys = {y2, y3, y4};\n                    if (xs.size() == 2 && ys.size() == 2) {\n                        vector<int> xs_v(xs.begin(), xs.end()), ys_v(ys.begin(), ys.end());\n                        for (int x1 : xs_v) {\n                            for (int y1 : ys_v) {\n                                if (!dots.count({x1, y1})) {\n                                    vector<pair<int,int>> pts = {{x2,y2}, {x3,y3}, {x4,y4}};\n                                    for (int a = 0; a < 3; a++) {\n                                        for (int b = 0; b < 3; b++) {\n                                            if (a == b) continue;\n                                            int c = 3 - a - b;\n                                            if (is_valid_rect(x1, y1, pts[a].first, pts[a].second, \n                                                             pts[b].first, pts[b].second, \n                                                             pts[c].first, pts[c].second)) {\n                                                double w = weight(x1, y1);\n                                                if (w > best_w) {\n                                                    best_w = w;\n                                                    bx1 = x1; by1 = y1;\n                                                    bx2 = pts[a].first; by2 = pts[a].second;\n                                                    bx3 = pts[b].first; by3 = pts[b].second;\n                                                    bx4 = pts[c].first; by4 = pts[c].second;\n                                                }\n                                            }\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        if (best_w > 0) {\n            found = true;\n            dots.insert({bx1, by1});\n            record_rect(bx1, by1, bx2, by2, bx3, by3, bx4, by4);\n            ops.push_back({bx1, by1, bx2, by2, bx3, by3, bx4, by4});\n        }\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto [x1, y1, x2, y2, x3, y3, x4, y4] : ops) {\n        cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \" \"\n             << x3 << \" \" << y3 << \" \" << x4 << \" \" << y4 << \"\\n\";\n    }\n    \n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nint grid[10][10];\n\nvoid place_candy(int pos, int flavor) {\n    int count = 0;\n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (grid[i][j] == 0) {\n                count++;\n                if (count == pos) {\n                    grid[i][j] = flavor;\n                    return;\n                }\n            }\n        }\n    }\n}\n\nvoid tilt(char dir) {\n    int temp[10][10];\n    memcpy(temp, grid, sizeof(grid));\n    memset(grid, 0, sizeof(grid));\n    \n    if (dir == 'F') {\n        for (int j = 0; j < 10; j++) {\n            vector<int> candies;\n            for (int i = 0; i < 10; i++) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t i = 0; i < candies.size(); i++) {\n                grid[i][j] = candies[i];\n            }\n        }\n    } else if (dir == 'B') {\n        for (int j = 0; j < 10; j++) {\n            vector<int> candies;\n            for (int i = 9; i >= 0; i--) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t i = 0; i < candies.size(); i++) {\n                grid[9 - i][j] = candies[i];\n            }\n        }\n    } else if (dir == 'L') {\n        for (int i = 0; i < 10; i++) {\n            vector<int> candies;\n            for (int j = 0; j < 10; j++) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t j = 0; j < candies.size(); j++) {\n                grid[i][j] = candies[j];\n            }\n        }\n    } else if (dir == 'R') {\n        for (int i = 0; i < 10; i++) {\n            vector<int> candies;\n            for (int j = 9; j >= 0; j--) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t j = 0; j < candies.size(); j++) {\n                grid[i][9 - j] = candies[j];\n            }\n        }\n    }\n}\n\nint compute_heuristic() {\n    int count = 0;\n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (grid[i][j] > 0) {\n                if (i + 1 < 10 && grid[i+1][j] == grid[i][j]) count++;\n                if (j + 1 < 10 && grid[i][j+1] == grid[i][j]) count++;\n            }\n        }\n    }\n    return count;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    memset(grid, 0, sizeof(grid));\n    \n    vector<int> flavors(100);\n    for (int i = 0; i < 100; i++) {\n        cin >> flavors[i];\n    }\n    \n    for (int t = 0; t < 100; t++) {\n        int pos;\n        cin >> pos;\n        \n        place_candy(pos, flavors[t]);\n        \n        if (t < 99) {\n            int h[4];\n            char dirs[4] = {'F', 'B', 'L', 'R'};\n            \n            for (int d = 0; d < 4; d++) {\n                int backup[10][10];\n                memcpy(backup, grid, sizeof(grid));\n                \n                tilt(dirs[d]);\n                h[d] = compute_heuristic();\n                \n                memcpy(grid, backup, sizeof(grid));\n            }\n            \n            int best_d = 0;\n            for (int d = 1; d < 4; d++) {\n                if (h[d] > h[best_d]) best_d = d;\n            }\n            \n            cout << dirs[best_d] << \"\\n\";\n            cout.flush();\n            \n            tilt(dirs[best_d]);\n        }\n    }\n    \n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int M;\n    double eps;\n    cin >> M >> eps;\n    \n    // Choose N based on M to balance score (1/N factor) and discrimination ability\n    int N;\n    if (M <= 20) N = 10;\n    else if (M <= 50) N = 15;\n    else N = 20;\n    N = max(4, min(100, N));\n    \n    int max_edges = N * (N - 1) / 2;\n    \n    cout << N << endl;\n    cout.flush();\n    \n    // Compute target edge counts for each graph (evenly distributed)\n    vector<int> target(M);\n    for (int k = 0; k < M; k++) {\n        target[k] = k * max_edges / M;\n    }\n    \n    // Output the M graphs with different edge counts\n    for (int k = 0; k < M; k++) {\n        string graph(max_edges, '0');\n        // Add the first target[k] edges\n        for (int i = 0; i < target[k]; i++) {\n            graph[i] = '1';\n        }\n        cout << graph << endl;\n        cout.flush();\n    }\n    \n    // Process 100 queries\n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n        \n        // Count edges in received graph\n        int edge_count = count(H.begin(), H.end(), '1');\n        \n        // Find the target with closest edge count\n        int best = 0;\n        int best_dist = abs(edge_count - target[0]);\n        for (int k = 1; k < M; k++) {\n            int dist = abs(edge_count - target[k]);\n            if (dist < best_dist) {\n                best_dist = dist;\n                best = k;\n            }\n        }\n        \n        cout << best << endl;\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long INF = 1e9;\n\nint N, M, D, K;\nvector<tuple<int, int, long long>> edges;\nvector<vector<long long>> dist;\n\nlong long compute_frustration(const vector<int>& assignment){\n    long long total = 0;\n    \n    for(int day = 1; day <= D; day++){\n        vector<vector<pair<int, long long>>> adj(N);\n        for(int i = 0; i < M; i++){\n            if(assignment[i] != day){\n                auto [u, v, w] = edges[i];\n                adj[u].push_back({v, w});\n                adj[v].push_back({u, w});\n            }\n        }\n        \n        for(int src = 0; src < N; src++){\n            vector<long long> d(N, INF);\n            d[src] = 0;\n            priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n            pq.push({0, src});\n            \n            while(!pq.empty()){\n                auto [cd, u] = pq.top();\n                pq.pop();\n                if(cd > d[u]) continue;\n                \n                for(auto& [v, w] : adj[u]){\n                    long long nd = d[u] + w;\n                    if(nd < d[v]){\n                        d[v] = nd;\n                        pq.push({nd, v});\n                    }\n                }\n            }\n            \n            for(int dst = 0; dst < N; dst++){\n                if(src != dst && d[dst] < INF){\n                    long long inc = d[dst] - dist[src][dst];\n                    if(inc > 0) total += inc;\n                }\n            }\n        }\n    }\n    \n    return total;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> D >> K;\n    \n    edges.resize(M);\n    vector<vector<pair<int, long long>>> adj(N);\n    \n    for(int i = 0; i < M; i++){\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edges[i] = {u, v, w};\n        adj[u].push_back({v, w});\n        adj[v].push_back({u, w});\n    }\n    \n    for(int i = 0; i < N; i++){\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    // Compute original shortest paths\n    dist.assign(N, vector<long long>(N, INF));\n    for(int i = 0; i < N; i++){\n        dist[i][i] = 0;\n        priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n        pq.push({0, i});\n        \n        while(!pq.empty()){\n            auto [d, u] = pq.top();\n            pq.pop();\n            if(d > dist[i][u]) continue;\n            \n            for(auto& [v, w] : adj[u]){\n                long long nd = dist[i][u] + w;\n                if(nd < dist[i][v]){\n                    dist[i][v] = nd;\n                    pq.push({nd, v});\n                }\n            }\n        }\n    }\n    \n    // Initial assignment - round robin\n    vector<int> best(M);\n    for(int i = 0; i < M; i++){\n        best[i] = (i % D) + 1;\n    }\n    \n    long long best_score = compute_frustration(best);\n    \n    // Local search with random restarts\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto start = chrono::steady_clock::now();\n    \n    while(chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count() < 5500){\n        vector<int> cur = best;\n        \n        int idx = uniform_int_distribution<int>(0, M-1)(rng);\n        int new_day = uniform_int_distribution<int>(1, D)(rng);\n        cur[idx] = new_day;\n        \n        long long score = compute_frustration(cur);\n        \n        if(score < best_score){\n            best = cur;\n            best_score = score;\n        }\n    }\n    \n    for(int i = 0; i < M; i++){\n        cout << best[i];\n        if(i + 1 < M) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef array<int, 3> Pos;\n\nint D;\n\nstruct Block {\n    set<Pos> voxels;\n    \n    Block() {}\n    Block(const set<Pos>& v) : voxels(v) {}\n    \n    void normalize() {\n        if (voxels.empty()) return;\n        int minx = INT_MAX, miny = INT_MAX, minz = INT_MAX;\n        for (auto p : voxels) {\n            minx = min(minx, p[0]);\n            miny = min(miny, p[1]);\n            minz = min(minz, p[2]);\n        }\n        set<Pos> normalized;\n        for (auto p : voxels) {\n            normalized.insert({p[0] - minx, p[1] - miny, p[2] - minz});\n        }\n        voxels = normalized;\n    }\n    \n    bool operator==(const Block& other) const {\n        return voxels == other.voxels;\n    }\n};\n\nvoid extract_blocks(vector<vector<vector<int>>>& grid, vector<Block>& blocks, vector<vector<vector<int>>>& result) {\n    vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    \n    for (int x = 0; x < D; x++) {\n        for (int y = 0; y < D; y++) {\n            for (int z = 0; z < D; z++) {\n                if (grid[x][y][z] == 1 && !visited[x][y][z]) {\n                    set<Pos> voxels;\n                    queue<Pos> q;\n                    q.push({x, y, z});\n                    visited[x][y][z] = true;\n                    \n                    while (!q.empty()) {\n                        auto p = q.front();\n                        q.pop();\n                        voxels.insert(p);\n                        \n                        int dx[] = {1, -1, 0, 0, 0, 0};\n                        int dy[] = {0, 0, 1, -1, 0, 0};\n                        int dz[] = {0, 0, 0, 0, 1, -1};\n                        \n                        for (int i = 0; i < 6; i++) {\n                            int nx = p[0] + dx[i], ny = p[1] + dy[i], nz = p[2] + dz[i];\n                            if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                grid[nx][ny][nz] == 1 && !visited[nx][ny][nz]) {\n                                visited[nx][ny][nz] = true;\n                                q.push({nx, ny, nz});\n                            }\n                        }\n                    }\n                    \n                    Block block(voxels);\n                    block.normalize();\n                    blocks.push_back(block);\n                    int bid = blocks.size();\n                    \n                    for (auto p : voxels) {\n                        result[p[0]][p[1]][p[2]] = bid;\n                    }\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D;\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    \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<int>>> grid1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> grid2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    \n    for (int x = 0; x < D; x++) {\n        for (int y = 0; y < D; y++) {\n            for (int z = 0; z < D; z++) {\n                if (f1[z][x] == '1' && r1[z][y] == '1') grid1[x][y][z] = 1;\n                if (f2[z][x] == '1' && r2[z][y] == '1') grid2[x][y][z] = 1;\n            }\n        }\n    }\n    \n    vector<Block> blocks;\n    vector<vector<vector<int>>> result1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> result2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    \n    extract_blocks(grid1, blocks, result1);\n    \n    vector<vector<vector<bool>>> visited2(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    for (int x = 0; x < D; x++) {\n        for (int y = 0; y < D; y++) {\n            for (int z = 0; z < D; z++) {\n                if (grid2[x][y][z] == 1 && !visited2[x][y][z]) {\n                    set<Pos> voxels;\n                    queue<Pos> q;\n                    q.push({x, y, z});\n                    visited2[x][y][z] = true;\n                    \n                    while (!q.empty()) {\n                        auto p = q.front();\n                        q.pop();\n                        voxels.insert(p);\n                        int dx[] = {1, -1, 0, 0, 0, 0};\n                        int dy[] = {0, 0, 1, -1, 0, 0};\n                        int dz[] = {0, 0, 0, 0, 1, -1};\n                        for (int i = 0; i < 6; i++) {\n                            int nx = p[0] + dx[i], ny = p[1] + dy[i], nz = p[2] + dz[i];\n                            if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                grid2[nx][ny][nz] == 1 && !visited2[nx][ny][nz]) {\n                                visited2[nx][ny][nz] = true;\n                                q.push({nx, ny, nz});\n                            }\n                        }\n                    }\n                    \n                    Block block2(voxels);\n                    block2.normalize();\n                    \n                    int bid = -1;\n                    for (int i = 0; i < blocks.size(); i++) {\n                        if (blocks[i] == block2) {\n                            bid = i + 1;\n                            break;\n                        }\n                    }\n                    if (bid == -1) {\n                        blocks.push_back(block2);\n                        bid = blocks.size();\n                    }\n                    \n                    for (auto p : voxels) {\n                        result2[p[0]][p[1]][p[2]] = bid;\n                    }\n                }\n            }\n        }\n    }\n    \n    cout << blocks.size() << \"\\n\";\n    for (int x = 0; x < D; x++)\n        for (int y = 0; y < D; y++)\n            for (int z = 0; z < D; z++) {\n                if (x || y || z) cout << \" \";\n                cout << result1[x][y][z];\n            }\n    cout << \"\\n\";\n    for (int x = 0; x < D; x++)\n        for (int y = 0; y < D; y++)\n            for (int z = 0; z < D; z++) {\n                if (x || y || z) cout << \" \";\n                cout << result2[x][y][z];\n            }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc020":"#include<bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    double x, y;\n};\n\ndouble dist(Point a, Point b) {\n    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\nint N, M, K;\nvector<Point> stations;\nvector<pair<int,int>> edgeEndpoints;\nvector<long long> weights;\nvector<Point> residents;\n\nvector<bool> getReachable(const vector<bool>& enabled) {\n    vector<bool> reachable(N, false);\n    reachable[0] = true;\n    queue<int> q;\n    q.push(0);\n    while(!q.empty()){\n        int u = q.front();\n        q.pop();\n        for(int e = 0; e < M; e++){\n            if(!enabled[e]) continue;\n            int v = -1;\n            if(edgeEndpoints[e].first == u) v = edgeEndpoints[e].second;\n            else if(edgeEndpoints[e].second == u) v = edgeEndpoints[e].first;\n            if(v != -1 && !reachable[v]){\n                reachable[v] = true;\n                q.push(v);\n            }\n        }\n    }\n    return reachable;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    \n    stations.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> stations[i].x >> stations[i].y;\n    }\n    \n    edgeEndpoints.resize(M);\n    weights.resize(M);\n    for(int i = 0; i < M; i++){\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edgeEndpoints[i] = {u, v};\n        weights[i] = w;\n    }\n    \n    residents.resize(K);\n    for(int i = 0; i < K; i++){\n        cin >> residents[i].x >> residents[i].y;\n    }\n    \n    vector<long long> P(N, 0);\n    vector<bool> enabled(M, false);\n    \n    // Initial: cover nearby residents with station 0\n    for(int k = 0; k < K; k++){\n        long long d = (long long)round(dist(stations[0], residents[k]));\n        if(d <= 5000){\n            P[0] = max(P[0], d);\n        }\n    }\n    \n    // Greedy: add edges until all residents are covered\n    while(true) {\n        auto reachable = getReachable(enabled);\n        \n        // Find uncovered residents\n        set<int> uncovered;\n        for(int k = 0; k < K; k++){\n            bool covered = false;\n            for(int i = 0; i < N; i++){\n                if(reachable[i] && P[i] >= (long long)round(dist(stations[i], residents[k]))){\n                    covered = true;\n                    break;\n                }\n            }\n            if(!covered) uncovered.insert(k);\n        }\n        \n        if(uncovered.empty()) break;\n        \n        // Find best edge to enable\n        double bestScore = 1e18;\n        int bestEdge = -1;\n        int bestVertex = -1;\n        \n        for(int e = 0; e < M; e++){\n            if(enabled[e]) continue;\n            \n            int u = edgeEndpoints[e].first;\n            int v = edgeEndpoints[e].second;\n            \n            bool u_reach = reachable[u];\n            bool v_reach = reachable[v];\n            \n            if(!u_reach && !v_reach) continue;\n            \n            int newV = u_reach ? v : u;\n            \n            long long maxP = 0;\n            int covered = 0;\n            for(int k : uncovered){\n                long long d = (long long)round(dist(stations[newV], residents[k]));\n                if(d <= 5000){\n                    maxP = max(maxP, d);\n                    covered++;\n                }\n            }\n            \n            if(covered == 0) continue;\n            \n            long long cost = weights[e] + maxP * maxP;\n            double score = (double)cost / covered;\n            \n            if(score < bestScore){\n                bestScore = score;\n                bestEdge = e;\n                bestVertex = newV;\n            }\n        }\n        \n        if(bestEdge == -1) break;\n        \n        enabled[bestEdge] = true;\n        for(int k : uncovered){\n            long long d = (long long)round(dist(stations[bestVertex], residents[k]));\n            if(d <= 5000){\n                P[bestVertex] = max(P[bestVertex], d);\n            }\n        }\n    }\n    \n    // Optimize: assign each resident to closest reachable station\n    auto reachable = getReachable(enabled);\n    fill(P.begin(), P.end(), 0);\n    for(int k = 0; k < K; k++){\n        long long minDist = LLONG_MAX;\n        int bestV = -1;\n        for(int i = 0; i < N; i++){\n            if(reachable[i]){\n                long long d = (long long)round(dist(stations[i], residents[k]));\n                if(d < minDist){\n                    minDist = d;\n                    bestV = i;\n                }\n            }\n        }\n        if(bestV != -1) P[bestV] = max(P[bestV], minDist);\n    }\n    \n    // Output\n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << P[i];\n    }\n    cout << \"\\n\";\n    \n    for(int i = 0; i < M; i++){\n        if(i > 0) cout << \" \";\n        cout << (enabled[i] ? 1 : 0);\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 30;\n    vector<vector<int>> pyramid(N);\n    \n    // Read input\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    vector<tuple<int,int,int,int>> operations;\n    \n    // Bubble sort: keep iterating until all constraints are satisfied\n    while ((int)operations.size() < 10000) {\n        bool changed = false;\n        \n        // Check all parent-child constraints from top to bottom\n        for (int x = 0; x < N - 1; x++) {\n            for (int y = 0; y <= x; y++) {\n                int parent = pyramid[x][y];\n                int left_child = pyramid[x+1][y];\n                int right_child = pyramid[x+1][y+1];\n                \n                // Fix violation with left child\n                if (parent > left_child) {\n                    swap(pyramid[x][y], pyramid[x+1][y]);\n                    operations.push_back({x, y, x+1, y});\n                    changed = true;\n                }\n                // Fix violation with right child\n                else if (parent > right_child) {\n                    swap(pyramid[x][y], pyramid[x+1][y+1]);\n                    operations.push_back({x, y, x+1, y+1});\n                    changed = true;\n                }\n                \n                // Stop if operation limit reached\n                if ((int)operations.size() >= 10000) {\n                    x = N;\n                    break;\n                }\n            }\n        }\n        \n        // If no changes were made, all constraints are satisfied\n        if (!changed) break;\n    }\n    \n    // Output result\n    cout << (int)operations.size() << \"\\n\";\n    for (auto [x1, y1, x2, y2] : operations) {\n        cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \"\\n\";\n    }\n    \n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D, N;\n    cin >> D >> N;\n    \n    set<pair<int,int>> obstacles;\n    for(int i = 0; i < N; i++){\n        int r, c;\n        cin >> r >> c;\n        obstacles.insert({r, c});\n    }\n    \n    pair<int,int> entrance = {0, (D-1)/2};\n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    \n    // Place containers\n    map<pair<int,int>, int> container_at;\n    \n    for(int i = 0; i < D*D - 1 - N; i++){\n        int t;\n        cin >> t;\n        \n        // Find reachable empty squares in BFS order\n        vector<pair<int,int>> reachable_empty;\n        queue<pair<int,int>> q;\n        set<pair<int,int>> visited;\n        q.push(entrance);\n        visited.insert(entrance);\n        \n        while(!q.empty()){\n            auto [r, c] = q.front();\n            q.pop();\n            \n            if(!(r == 0 && c == (D-1)/2)){\n                reachable_empty.push_back({r, c});\n            }\n            \n            for(int dir = 0; dir < 4; dir++){\n                int nr = r + dr[dir];\n                int nc = c + dc[dir];\n                \n                if(nr >= 0 && nr < D && nc >= 0 && nc < D &&\n                   !visited.count({nr, nc}) &&\n                   !obstacles.count({nr, nc}) &&\n                   !container_at.count({nr, nc})){\n                    visited.insert({nr, nc});\n                    q.push({nr, nc});\n                }\n            }\n        }\n        \n        auto chosen = reachable_empty[0];\n        container_at[chosen] = t;\n        cout << chosen.first << \" \" << chosen.second << \"\\n\";\n        cout.flush();\n    }\n    \n    // Retrieve containers optimally\n    for(int extracted = 0; extracted < D*D - 1 - N; extracted++){\n        // Find all reachable container positions\n        set<pair<int,int>> reachable;\n        queue<pair<int,int>> q;\n        set<pair<int,int>> visited_empty;\n        q.push(entrance);\n        visited_empty.insert(entrance);\n        \n        while(!q.empty()){\n            auto [r, c] = q.front();\n            q.pop();\n            \n            for(int dir = 0; dir < 4; dir++){\n                int nr = r + dr[dir];\n                int nc = c + dc[dir];\n                \n                if(nr >= 0 && nr < D && nc >= 0 && nc < D &&\n                   !visited_empty.count({nr, nc}) &&\n                   !obstacles.count({nr, nc})){\n                    \n                    if(!container_at.count({nr, nc})){\n                        visited_empty.insert({nr, nc});\n                        q.push({nr, nc});\n                    } else {\n                        reachable.insert({nr, nc});\n                    }\n                }\n            }\n        }\n        \n        // Find reachable container with smallest number\n        pair<int,int> best_pos;\n        int best_num = INT_MAX;\n        for(auto& [pos, num] : container_at){\n            if(reachable.count(pos) && num < best_num){\n                best_num = num;\n                best_pos = pos;\n            }\n        }\n        \n        cout << best_pos.first << \" \" << best_pos.second << \"\\n\";\n        container_at.erase(best_pos);\n    }\n    \n    cout.flush();\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N = 50, m = 100;\nint original[50][50];\nint current[50][50];\n\nvector<pair<int,int>> dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};\n\nbool isValid(int i, int j) {\n    return i >= 0 && i < N && j >= 0 && j < N;\n}\n\nbool isConnected(int color) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int,int>> q;\n    int count = 0;\n    pair<int,int> start = {-1, -1};\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(current[i][j] == color) {\n                count++;\n                if(start.first == -1) start = {i, j};\n            }\n        }\n    }\n    \n    if(count == 0) return true;\n    \n    q.push(start);\n    visited[start.first][start.second] = true;\n    int visited_count = 1;\n    \n    while(!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for(auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if(isValid(ni, nj) && !visited[ni][nj] && current[ni][nj] == color) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                visited_count++;\n            }\n        }\n    }\n    \n    return visited_count == count;\n}\n\nset<pair<int,int>> getAdjacencies(int grid[50][50]) {\n    set<pair<int,int>> adj;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            // Internal adjacencies\n            for(auto [di, dj] : dirs) {\n                int ni = i + di, nj = j + dj;\n                if(isValid(ni, nj)) {\n                    int c1 = grid[i][j], c2 = grid[ni][nj];\n                    if(c1 != c2) {\n                        adj.insert({min(c1, c2), max(c1, c2)});\n                    }\n                }\n            }\n        }\n    }\n    \n    // Boundary adjacencies to color 0\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if((i == 0 || i == N-1 || j == 0 || j == N-1) && grid[i][j] != 0) {\n                adj.insert({0, grid[i][j]});\n            }\n        }\n    }\n    \n    return adj;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> m;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            cin >> original[i][j];\n            current[i][j] = original[i][j];\n        }\n    }\n    \n    auto orig_adj = getAdjacencies(original);\n    \n    bool improved = true;\n    \n    while(improved) {\n        improved = false;\n        \n        for(int i = 0; i < N; i++) {\n            for(int j = 0; j < N; j++) {\n                if(current[i][j] != 0) {\n                    int color = current[i][j];\n                    current[i][j] = 0;\n                    \n                    if(isConnected(color) && getAdjacencies(current) == orig_adj) {\n                        improved = true;\n                    } else {\n                        current[i][j] = color;\n                    }\n                }\n            }\n        }\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(j > 0) cout << \" \";\n            cout << current[i][j];\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, D, Q;\n    cin >> N >> D >> Q;\n    \n    vector<vector<int>> cmp(N, vector<int>(N, -2)); // -2 = unknown\n    for(int i = 0; i < N; i++) cmp[i][i] = 0;\n    \n    // Generate all unique pairs\n    vector<pair<int,int>> pairs;\n    for(int i = 0; i < N; i++){\n        for(int j = i+1; j < N; j++){\n            pairs.push_back({i, j});\n        }\n    }\n    \n    // Shuffle for variety\n    shuffle(pairs.begin(), pairs.end(), mt19937(0));\n    \n    // Perform Q queries\n    for(int q = 0; q < Q; q++){\n        int idx = q % (int)pairs.size();\n        int i = pairs[idx].first;\n        int j = pairs[idx].second;\n        \n        cout << \"1 1 \" << i << \" \" << j << \"\\n\";\n        cout.flush();\n        \n        string result;\n        cin >> result;\n        \n        if(result == \"<\"){\n            cmp[i][j] = -1;\n            cmp[j][i] = 1;\n        } else if(result == \">\"){\n            cmp[i][j] = 1;\n            cmp[j][i] = -1;\n        } else {\n            cmp[i][j] = 0;\n            cmp[j][i] = 0;\n        }\n    }\n    \n    // Estimate weights: count comparison wins and losses\n    vector<double> weight(N, 0.0);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(cmp[i][j] == 1) weight[i] += 1.0;\n            else if(cmp[i][j] == -1) weight[i] -= 1.0;\n        }\n    }\n    \n    // Greedy partition: assign items to lightest set\n    vector<int> division(N);\n    vector<double> setWeight(D, 0.0);\n    \n    // Sort items by weight (descending)\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b){\n        return weight[a] > weight[b];\n    });\n    \n    // Assign each item to the set with minimum current weight\n    for(int item : order){\n        int best = 0;\n        for(int d = 1; d < D; d++){\n            if(setWeight[d] < setWeight[best]) best = d;\n        }\n        division[item] = best;\n        setWeight[best] += weight[item];\n    }\n    \n    // Output division\n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << division[i];\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n  ios_base::sync_with_stdio(false);\n  cin.tie(nullptr);\n  \n  int n, m;\n  cin >> n >> m;\n  \n  vector<vector<int>> stacks(m);\n  \n  for(int i = 0; i < m; i++){\n    int s = n / m;\n    for(int j = 0; j < s; j++){\n      int x;\n      cin >> x;\n      stacks[i].push_back(x);\n    }\n  }\n  \n  vector<pair<int,int>> operations;\n  \n  for(int box = 1; box <= n; box++){\n    // Find which stack contains this box\n    int src_stack = -1;\n    \n    for(int i = 0; i < m; i++){\n      for(int j = 0; j < (int)stacks[i].size(); j++){\n        if(stacks[i][j] == box){\n          src_stack = i;\n          break;\n        }\n      }\n      if(src_stack != -1) break;\n    }\n    \n    // Move all boxes above this box away\n    while(stacks[src_stack].back() != box){\n      int top_box = stacks[src_stack].back();\n      \n      // Find destination stack with minimum size (excluding source)\n      int dest_stack = -1;\n      int min_size = INT_MAX;\n      \n      for(int i = 0; i < m; i++){\n        if(i == src_stack) continue;\n        if((int)stacks[i].size() < min_size){\n          min_size = stacks[i].size();\n          dest_stack = i;\n        }\n      }\n      \n      // Move the top box to destination\n      stacks[dest_stack].push_back(top_box);\n      stacks[src_stack].pop_back();\n      \n      operations.push_back({top_box, dest_stack + 1});\n    }\n    \n    // Now box is at the top - extract it\n    operations.push_back({box, 0});\n    stacks[src_stack].pop_back();\n  }\n  \n  for(auto [v, i] : operations){\n    cout << v << \" \" << i << \"\\n\";\n  }\n  \n  return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<bool>> visited;\nstring result;\n\nint di[] = {0, 1, 0, -1};\nint dj[] = {1, 0, -1, 0};\nchar dir_char[] = {'R', 'D', 'L', 'U'};\n\nvoid dfs(int i, int j) {\n    visited[i][j] = true;\n    \n    vector<pair<int, int>> moves; // (direction, d_value of neighbor)\n    \n    for (int dir = 0; dir < 4; dir++) {\n        int ni = i + di[dir];\n        int nj = j + dj[dir];\n        \n        if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj]) {\n            bool canMove = false;\n            if (dir == 0) canMove = (v[i][j] == '0');           // Right\n            else if (dir == 1) canMove = (h[i][j] == '0');      // Down\n            else if (dir == 2) canMove = (v[i][nj] == '0');     // Left\n            else canMove = (h[ni][j] == '0');                   // Up\n            \n            if (canMove) {\n                moves.push_back({dir, d[ni][nj]});\n            }\n        }\n    }\n    \n    // Sort by d_value descending (visit high-susceptibility areas first)\n    sort(moves.begin(), moves.end(), \n         [](const pair<int,int> &a, const pair<int,int> &b) { \n             return a.second > b.second; \n         });\n    \n    for (const auto &[dir, _] : moves) {\n        int ni = i + di[dir];\n        int nj = j + dj[dir];\n        \n        result += dir_char[dir];\n        dfs(ni, nj);\n        result += dir_char[(dir + 2) % 4];  // Opposite direction\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    \n    h.resize(N-1);\n    v.resize(N);\n    d.resize(N, vector<int>(N));\n    visited.assign(N, vector<bool>(N, false));\n    \n    for (int i = 0; i < N-1; i++) cin >> h[i];\n    for (int i = 0; i < N; i++) cin >> v[i];\n    \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    dfs(0, 0);\n    cout << result << endl;\n    \n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int N, M;\n    cin >> N >> M;\n    \n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> grid(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    \n    vector<string> words(M);\n    for (int i = 0; i < M; i++) {\n        cin >> words[i];\n    }\n    \n    // Find positions of each character\n    map<char, vector<pair<int, int>>> charPos;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            charPos[grid[i][j]].push_back({i, j});\n        }\n    }\n    \n    // Compute overlaps between words\n    auto getOverlap = [](const string& a, const string& b) {\n        int maxOverlap = 0;\n        for (int o = 1; o <= min((int)a.size(), (int)b.size()); o++) {\n            if (a.substr(a.size() - o) == b.substr(0, o)) {\n                maxOverlap = o;\n            }\n        }\n        return maxOverlap;\n    };\n    \n    // Build word order greedily (nearest neighbor on word overlap graph)\n    vector<int> order;\n    set<int> used;\n    order.push_back(0);\n    used.insert(0);\n    \n    while ((int)used.size() < M) {\n        int lastWord = order.back();\n        int bestWord = -1;\n        int bestOverlap = -1;\n        \n        // Find word with maximum overlap with last word\n        for (int w = 0; w < M; w++) {\n            if (used.count(w)) continue;\n            int ov = getOverlap(words[lastWord], words[w]);\n            if (ov > bestOverlap) {\n                bestOverlap = ov;\n                bestWord = w;\n            }\n        }\n        \n        if (bestWord == -1) {\n            // Pick any unused word\n            for (int w = 0; w < M; w++) {\n                if (!used.count(w)) {\n                    bestWord = w;\n                    break;\n                }\n            }\n        }\n        \n        if (bestWord != -1) {\n            order.push_back(bestWord);\n            used.insert(bestWord);\n        } else {\n            break;\n        }\n    }\n    \n    // Type the words in order\n    vector<pair<int, int>> operations;\n    int ci = si, cj = sj;\n    \n    for (int widx = 0; widx < (int)order.size(); widx++) {\n        string word = words[order[widx]];\n        \n        int startPos = 0;\n        if (widx > 0) {\n            startPos = getOverlap(words[order[widx-1]], word);\n        }\n        \n        // Type characters from startPos onwards\n        for (int i = startPos; i < 5; i++) {\n            char c = word[i];\n            \n            // Find nearest position of c\n            int bestI = -1, bestJ = -1;\n            int minDist = INT_MAX;\n            for (auto [ii, jj] : charPos[c]) {\n                int dist = abs(ii - ci) + abs(jj - cj);\n                if (dist < minDist) {\n                    minDist = dist;\n                    bestI = ii;\n                    bestJ = jj;\n                }\n            }\n            \n            operations.push_back({bestI, bestJ});\n            ci = bestI;\n            cj = bestJ;\n        }\n    }\n    \n    for (auto [i, j] : operations) {\n        cout << i << \" \" << j << \"\\n\";\n    }\n    \n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n    \n    // Read field shapes\n    vector<vector<pair<int, int>>> fields(M);\n    for (int k = 0; k < M; k++) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < d; i++) {\n            int r, c;\n            cin >> r >> c;\n            fields[k].push_back({r, c});\n        }\n    }\n    \n    // Drill all squares to identify which have oil reserves\n    vector<pair<int, int>> oil_squares;\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            // Drill this square\n            cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n            cout.flush();\n            \n            int oil_value;\n            cin >> oil_value;\n            \n            // Record if this square has oil\n            if (oil_value > 0) {\n                oil_squares.push_back({i, j});\n            }\n        }\n    }\n    \n    // Output answer: all squares with v(i,j) > 0\n    cout << \"a \" << oil_squares.size();\n    for (auto [i, j] : oil_squares) {\n        cout << \" \" << i << \" \" << j;\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    // Read verification result\n    int is_correct;\n    cin >> is_correct;\n    \n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<long long>> a(D, vector<long long>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    // Allocate N vertical strips of equal width\n    // Each strip k spans from column k*W/N to (k+1)*W/N\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            long long j0 = (long long)k * W / N;\n            long long j1 = (long long)(k + 1) * W / N;\n            long long width = j1 - j0;\n            \n            long long needed = a[d][k];\n            // Calculate minimum height to meet area requirement\n            long long height = (needed + width - 1) / width;  // Ceiling division\n            height = min(height, (long long)W);  // Cap at grid height\n            \n            cout << 0 << \" \" << j0 << \" \" << height << \" \" << j1 << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long MOD = 998244353;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, K;\n    cin >> N >> M >> K;\n    \n    vector<vector<long long>> board(N, vector<long long>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> board[i][j];\n        }\n    }\n    \n    vector<vector<vector<long long>>> stamps(M, vector<vector<long long>>(3, vector<long long>(3)));\n    for(int m = 0; m < M; m++){\n        for(int i = 0; i < 3; i++){\n            for(int j = 0; j < 3; j++){\n                cin >> stamps[m][i][j];\n            }\n        }\n    }\n    \n    auto delta_score = [&](int m, int p, int q) {\n        long long delta = 0;\n        for(int i = 0; i < 3; i++){\n            for(int j = 0; j < 3; j++){\n                int ni = p + i, nj = q + j;\n                long long old_mod = board[ni][nj] % MOD;\n                long long new_mod = (board[ni][nj] + stamps[m][i][j]) % MOD;\n                delta += new_mod - old_mod;\n            }\n        }\n        return delta;\n    };\n    \n    vector<tuple<int, int, int>> operations;\n    \n    for(int op = 0; op < K; op++){\n        long long best_delta = 0;\n        int best_m = -1, best_p = -1, best_q = -1;\n        \n        for(int m = 0; m < M; m++){\n            for(int p = 0; p <= N - 3; p++){\n                for(int q = 0; q <= N - 3; q++){\n                    long long d = delta_score(m, p, q);\n                    if(d > best_delta){\n                        best_delta = d;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n        \n        if(best_m == -1) break;\n        \n        for(int i = 0; i < 3; i++){\n            for(int j = 0; j < 3; j++){\n                board[best_p+i][best_q+j] += stamps[best_m][i][j];\n            }\n        }\n        \n        operations.push_back({best_m, best_p, best_q});\n    }\n    \n    cout << operations.size() << \"\\n\";\n    for(auto [m, p, q] : operations){\n        cout << m << \" \" << p << \" \" << q << \"\\n\";\n    }\n    \n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int N;\n    cin >> N;\n    \n    vector<vector<int>> A(N, vector<int>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> A[i][j];\n        }\n    }\n    \n    vector<vector<int>> grid(N, vector<int>(N, -1));\n    vector<pair<int,int>> pos(N);\n    vector<int> carry(N, -1);\n    \n    for(int i = 0; i < N; i++) pos[i] = {i, 0};\n    \n    vector<int> next_in(N, 0);\n    vector<string> res(N, \"\");\n    \n    for(int t = 0; t < 10000; t++){\n        // Step 1: Place arriving containers at receiving gates\n        for(int i = 0; i < N; i++){\n            if(next_in[i] < N && grid[i][0] == -1){\n                bool blocked = false;\n                for(int k = 0; k < N; k++){\n                    if(pos[k].first == i && pos[k].second == 0 && carry[k] != -1){\n                        blocked = true;\n                    }\n                }\n                if(!blocked){\n                    grid[i][0] = A[i][next_in[i]];\n                    next_in[i]++;\n                }\n            }\n        }\n        \n        // Step 2: Decide crane actions\n        vector<char> act(N);\n        \n        for(int k = 0; k < N; k++){\n            auto [r, c] = pos[k];\n            \n            if(carry[k] >= 0){\n                // Carrying container - move to target dispatch gate\n                int tr = carry[k] / N;\n                int tc = N - 1;\n                \n                if(r == tr && c == tc){\n                    act[k] = 'Q';  // Release at dispatch gate\n                } else if(c < tc){\n                    act[k] = 'R';  // Move right\n                } else if(r < tr){\n                    act[k] = 'D';  // Move down\n                } else if(r > tr){\n                    act[k] = 'U';  // Move up\n                } else {\n                    act[k] = '.';\n                }\n            } else {\n                // Not carrying - try to pick something or move left\n                if(grid[r][c] >= 0){\n                    act[k] = 'P';  // Pick up container\n                } else if(c > 0){\n                    act[k] = 'L';  // Move toward receiving gates\n                } else {\n                    act[k] = '.';\n                }\n            }\n        }\n        \n        // Apply P actions (pick up)\n        for(int k = 0; k < N; k++){\n            if(act[k] == 'P' && carry[k] == -1 && grid[pos[k].first][pos[k].second] >= 0){\n                carry[k] = grid[pos[k].first][pos[k].second];\n                grid[pos[k].first][pos[k].second] = -1;\n            }\n        }\n        \n        // Apply Q actions (release)\n        for(int k = 0; k < N; k++){\n            if(act[k] == 'Q' && carry[k] >= 0 && grid[pos[k].first][pos[k].second] == -1){\n                grid[pos[k].first][pos[k].second] = carry[k];\n                carry[k] = -1;\n            }\n        }\n        \n        // Apply movement actions\n        for(int k = 0; k < N; k++){\n            if(act[k] == 'U' && pos[k].first > 0) pos[k].first--;\n            else if(act[k] == 'D' && pos[k].first < N-1) pos[k].first++;\n            else if(act[k] == 'L' && pos[k].second > 0) pos[k].second--;\n            else if(act[k] == 'R' && pos[k].second < N-1) pos[k].second++;\n        }\n        \n        for(int k = 0; k < N; k++) res[k] += act[k];\n        \n        // Step 3: Auto-dispatch containers at dispatch gates\n        for(int i = 0; i < N; i++){\n            if(grid[i][N-1] >= 0) grid[i][N-1] = -1;\n        }\n    }\n    \n    for(int i = 0; i < N; i++){\n        cout << res[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    \n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h[i][j];\n        }\n    }\n    \n    vector<string> operations;\n    int x = 0, y = 0;\n    int load = 0;\n    \n    auto move_to = [&](int nx, int ny) {\n        while (x != nx) {\n            if (x < nx) {\n                operations.push_back(\"D\");\n                x++;\n            } else {\n                operations.push_back(\"U\");\n                x--;\n            }\n        }\n        while (y != ny) {\n            if (y < ny) {\n                operations.push_back(\"R\");\n                y++;\n            } else {\n                operations.push_back(\"L\");\n                y--;\n            }\n        }\n    };\n    \n    // Phase 1: Collect all positive soil using snake pattern\n    for (int i = 0; i < N; i++) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; j++) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    operations.push_back(\"+\" + to_string(h[i][j]));\n                    load += h[i][j];\n                }\n            }\n        } else {\n            for (int j = N - 1; j >= 0; j--) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    operations.push_back(\"+\" + to_string(h[i][j]));\n                    load += h[i][j];\n                }\n            }\n        }\n    }\n    \n    // Phase 2: Distribute to negative cells using same snake pattern\n    for (int i = 0; i < N; i++) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; j++) {\n                move_to(i, j);\n                if (h[i][j] < 0) {\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                    }\n                }\n            }\n        } else {\n            for (int j = N - 1; j >= 0; j--) {\n                move_to(i, j);\n                if (h[i][j] < 0) {\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                    }\n                }\n            }\n        }\n    }\n    \n    for (const auto& op : operations) {\n        cout << op << \"\\n\";\n    }\n    \n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\nint main() {\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> X(seed_count, vector<int>(M));\n\n    // Read initial seeds\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> X[i][j];\n        }\n    }\n\n    // Perform T operations\n    for (int t = 0; t < T; t++) {\n        // Calculate total value for each seed\n        vector<long long> values(seed_count, 0);\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                values[i] += X[i][j];\n            }\n        }\n        \n        // Sort seeds by total value (descending)\n        vector<int> indices(seed_count);\n        iota(indices.begin(), indices.end(), 0);\n        sort(indices.begin(), indices.end(), [&](int a, int b) {\n            return values[a] > values[b];\n        });\n\n        // Output placement of top N*N seeds in row-major order\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (j > 0) cout << \" \";\n                cout << indices[i * N + j];\n            }\n            cout << \"\\n\";\n        }\n        cout.flush();\n\n        // Read new generation seeds\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> X[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, V;\n    cin >> N >> M >> V;\n    \n    vector<string> s(N), t(N);\n    for(int i = 0; i < N; i++) cin >> s[i];\n    for(int i = 0; i < N; i++) cin >> t[i];\n    \n    vector<pair<int,int>> src, dst;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(s[i][j] == '1') src.push_back({i, j});\n            if(t[i][j] == '1') dst.push_back({i, j});\n        }\n    }\n    \n    cout << \"2\\n\";\n    cout << \"0 1\\n\";\n    cout << \"0 0\\n\";\n    \n    int rx = 0, ry = 0;\n    int rot = 0; // 0=right, 1=down, 2=left, 3=up\n    int turns = 0;\n    \n    auto get_finger = [&]() -> pair<int,int> {\n        if(rot == 0) return {rx, ry + 1};\n        if(rot == 1) return {rx + 1, ry};\n        if(rot == 2) return {rx, ry - 1};\n        return {rx - 1, ry};\n    };\n    \n    auto can_reach = [&](int sx, int sy, int r) -> bool {\n        int target_rx = sx, target_ry = sy;\n        if(r == 0) target_ry--;\n        else if(r == 1) target_rx--;\n        else if(r == 2) target_ry++;\n        else target_rx++;\n        return target_rx >= 0 && target_rx < N && target_ry >= 0 && target_ry < N;\n    };\n    \n    for(int i = 0; i < M && turns < 100000; i++){\n        auto [sx, sy] = src[i];\n        auto [tx, ty] = dst[i];\n        \n        // Find and move to source\n        int best_rot = rot;\n        for(int r = 0; r < 4; r++){\n            if(can_reach(sx, sy, r)){\n                best_rot = r;\n                break;\n            }\n        }\n        \n        while(rot != best_rot && turns < 100000){\n            string op = \"....\";\n            op[1] = ((best_rot - rot + 4) % 4 == 1) ? 'L' : 'R';\n            rot = ((best_rot - rot + 4) % 4 == 1) ? (rot + 3) % 4 : (rot + 1) % 4;\n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        while(turns < 100000){\n            auto [fx, fy] = get_finger();\n            if(fx == sx && fy == sy) break;\n            \n            string op = \"....\";\n            int target_rx = sx, target_ry = sy;\n            if(rot == 0) target_ry--;\n            else if(rot == 1) target_rx--;\n            else if(rot == 2) target_ry++;\n            else target_rx++;\n            \n            if(rx < target_rx) { rx++; op[0] = 'D'; }\n            else if(rx > target_rx) { rx--; op[0] = 'U'; }\n            else if(ry < target_ry) { ry++; op[0] = 'R'; }\n            else if(ry > target_ry) { ry--; op[0] = 'L'; }\n            \n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        if(turns >= 100000) break;\n        cout << \"..P\\n\";\n        turns++;\n        \n        // Find and move to target\n        best_rot = rot;\n        for(int r = 0; r < 4; r++){\n            if(can_reach(tx, ty, r)){\n                best_rot = r;\n                break;\n            }\n        }\n        \n        while(rot != best_rot && turns < 100000){\n            string op = \"....\";\n            op[1] = ((best_rot - rot + 4) % 4 == 1) ? 'L' : 'R';\n            rot = ((best_rot - rot + 4) % 4 == 1) ? (rot + 3) % 4 : (rot + 1) % 4;\n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        while(turns < 100000){\n            auto [fx, fy] = get_finger();\n            if(fx == tx && fy == ty) break;\n            \n            string op = \"....\";\n            int target_rx = tx, target_ry = ty;\n            if(rot == 0) target_ry--;\n            else if(rot == 1) target_rx--;\n            else if(rot == 2) target_ry++;\n            else target_rx++;\n            \n            if(rx < target_rx) { rx++; op[0] = 'D'; }\n            else if(rx > target_rx) { rx--; op[0] = 'U'; }\n            else if(ry < target_ry) { ry++; op[0] = 'R'; }\n            else if(ry > target_ry) { ry--; op[0] = 'L'; }\n            \n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        if(turns >= 100000) break;\n        cout << \"..P\\n\";\n        turns++;\n    }\n    \n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    \n    vector<pair<long long, long long>> mackerel(N);\n    vector<pair<long long, long long>> sardine(N);\n    \n    for(int i = 0; i < N; i++){\n        cin >> mackerel[i].first >> mackerel[i].second;\n    }\n    \n    for(int i = 0; i < N; i++){\n        cin >> sardine[i].first >> sardine[i].second;\n    }\n    \n    // Find bounding box of mackerels\n    long long minX = LLONG_MAX, maxX = LLONG_MIN;\n    long long minY = LLONG_MAX, maxY = LLONG_MIN;\n    \n    for(auto& p : mackerel){\n        minX = min(minX, p.first);\n        maxX = max(maxX, p.first);\n        minY = min(minY, p.second);\n        maxY = max(maxY, p.second);\n    }\n    \n    // Output a rectangular polygon enclosing all mackerels\n    cout << 4 << \"\\n\";\n    cout << minX << \" \" << minY << \"\\n\";\n    cout << maxX << \" \" << minY << \"\\n\";\n    cout << maxX << \" \" << maxY << \"\\n\";\n    cout << minX << \" \" << maxY << \"\\n\";\n    \n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, T;\n    long long sigma;\n    cin >> N >> T >> sigma;\n    \n    vector<pair<long long, long long>> rects(N);\n    for (int i = 0; i < N; i++) {\n        cin >> rects[i].first >> rects[i].second;\n    }\n    \n    mt19937 rng(0);\n    \n    auto simulate = [&](const vector<tuple<int, int, char, int>>& placement) {\n        map<int, tuple<long long, long long, long long, long long>> pos;\n        long long max_x = 0, max_y = 0;\n        \n        for (auto [idx, rot, dir, ref] : placement) {\n            long long w = rects[idx].first;\n            long long h = rects[idx].second;\n            if (rot) swap(w, h);\n            \n            long long x = 0, y = 0;\n            \n            if (dir == 'U') {\n                if (ref != -1) x = get<0>(pos[ref]) + get<2>(pos[ref]);\n                for (auto& [i, p] : pos) {\n                    long long px = get<0>(p), py = get<1>(p), pw = get<2>(p), ph = get<3>(p);\n                    if (px < x + w && x < px + pw) {\n                        y = max(y, py + ph);\n                    }\n                }\n            } else {\n                if (ref != -1) y = get<1>(pos[ref]) + get<3>(pos[ref]);\n                for (auto& [i, p] : pos) {\n                    long long px = get<0>(p), py = get<1>(p), pw = get<2>(p), ph = get<3>(p);\n                    if (py < y + h && y < py + ph) {\n                        x = max(x, px + pw);\n                    }\n                }\n            }\n            \n            pos[idx] = {x, y, w, h};\n            max_x = max(max_x, x + w);\n            max_y = max(max_y, y + h);\n        }\n        \n        return make_pair(max_x, max_y);\n    };\n    \n    for (int t = 0; t < T; t++) {\n        vector<tuple<int, int, char, int>> best;\n        long long best_score = LLONG_MAX;\n        \n        for (int att = 0; att < 1000; att++) {\n            vector<tuple<int, int, char, int>> placement;\n            \n            int max_n = N;\n            if (att % 4 == 0) max_n = (N + 1) / 2 + rng() % ((N + 1) / 2);\n            \n            for (int i = 0; i < max_n; i++) {\n                int r = rng() % 2;\n                char d = \"UL\"[rng() % 2];\n                int b = -1;\n                if (i > 0 && rng() % 2) b = rng() % i;\n                placement.push_back({i, r, d, b});\n            }\n            \n            auto [w, h] = simulate(placement);\n            long long cost = w + h;\n            for (int i = max_n; i < N; i++) {\n                cost += rects[i].first + rects[i].second;\n            }\n            \n            if (cost < best_score) {\n                best_score = cost;\n                best = placement;\n            }\n        }\n        \n        cout << best.size() << \"\\n\";\n        for (auto [p, r, d, b] : best) {\n            cout << p << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        }\n        cout.flush();\n        \n        long long W, H;\n        cin >> W >> H;\n    }\n    \n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, H;\n    cin >> N >> M >> H;\n    \n    vector<int> A(N);\n    for(int i = 0; i < N; i++){\n        cin >> A[i];\n    }\n    \n    vector<vector<int>> adj(N);\n    for(int i = 0; i < M; i++){\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    vector<double> x(N), y(N);\n    for(int i = 0; i < N; i++){\n        cin >> x[i] >> y[i];\n    }\n    \n    auto buildTree = [&](int root, vector<int>& parent) {\n        queue<int> q;\n        q.push(root);\n        parent[root] = -1;\n        vector<int> depth(N, -1);\n        depth[root] = 0;\n        \n        while(!q.empty()){\n            int u = q.front();\n            q.pop();\n            \n            if(depth[u] >= H) continue;\n            \n            vector<int> candidates;\n            for(int v : adj[u]){\n                if(parent[v] == -2){\n                    candidates.push_back(v);\n                }\n            }\n            \n            sort(candidates.begin(), candidates.end(), \n                 [&](int a, int b){ return A[a] > A[b]; });\n            \n            for(int v : candidates){\n                parent[v] = u;\n                depth[v] = depth[u] + 1;\n                q.push(v);\n            }\n        }\n    };\n    \n    auto evaluateSolution = [&](const vector<int>& parent) {\n        vector<vector<int>> children(N);\n        for(int i = 0; i < N; i++){\n            if(parent[i] >= 0){\n                children[parent[i]].push_back(i);\n            }\n        }\n        \n        vector<int> depth(N, -1);\n        long long score = 0;\n        \n        function<void(int)> dfs = [&](int u) {\n            score += (long long)(depth[u] + 1) * A[u];\n            for(int v : children[u]){\n                depth[v] = depth[u] + 1;\n                dfs(v);\n            }\n        };\n        \n        for(int i = 0; i < N; i++){\n            if(parent[i] == -1){\n                depth[i] = 0;\n                dfs(i);\n            }\n        }\n        return score;\n    };\n    \n    vector<int> best_parent(N);\n    long long best_score = -1;\n    \n    for(int strategy = 0; strategy < 3; strategy++){\n        vector<int> parent(N, -2);\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        \n        if(strategy == 0){\n            sort(order.begin(), order.end(), [&](int a, int b){ return A[a] > A[b]; });\n        } else if(strategy == 1){\n            sort(order.begin(), order.end(), [&](int a, int b){ return adj[a].size() > adj[b].size(); });\n        } else {\n            sort(order.begin(), order.end(), [&](int a, int b){ \n                return A[a] * sqrt(adj[a].size()) > A[b] * sqrt(adj[b].size());\n            });\n        }\n        \n        for(int root : order){\n            if(parent[root] == -2){\n                buildTree(root, parent);\n            }\n        }\n        \n        long long score = evaluateSolution(parent);\n        if(score > best_score){\n            best_score = score;\n            best_parent = parent;\n        }\n    }\n    \n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << best_parent[i];\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int N;\n    cin >> N;\n    \n    vector<string> board(N);\n    for (int i = 0; i < N; i++) {\n        cin >> board[i];\n    }\n    \n    vector<pair<char, int>> operations;\n    \n    auto findOni = [&]() -> pair<int, int> {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (board[i][j] == 'x') return {i, j};\n            }\n        }\n        return {-1, -1};\n    };\n    \n    auto shiftUp = [&](int j) {\n        for (int i = 0; i < N - 1; i++) board[i][j] = board[i + 1][j];\n        board[N - 1][j] = '.';\n        operations.push_back({'U', j});\n    };\n    \n    auto shiftDown = [&](int j) {\n        for (int i = N - 1; i > 0; i--) board[i][j] = board[i - 1][j];\n        board[0][j] = '.';\n        operations.push_back({'D', j});\n    };\n    \n    auto shiftLeft = [&](int i) {\n        for (int j = 0; j < N - 1; j++) board[i][j] = board[i][j + 1];\n        board[i][N - 1] = '.';\n        operations.push_back({'L', i});\n    };\n    \n    auto shiftRight = [&](int i) {\n        for (int j = N - 1; j > 0; j--) board[i][j] = board[i][j - 1];\n        board[i][0] = '.';\n        operations.push_back({'R', i});\n    };\n    \n    while (true) {\n        auto [i, j] = findOni();\n        if (i == -1) break;\n        \n        // Check upward direction\n        bool clearUp = true;\n        for (int k = 0; k < i; k++) {\n            if (board[k][j] == 'o') { clearUp = false; break; }\n        }\n        if (clearUp) {\n            for (int k = 0; k <= i; k++) shiftUp(j);\n            for (int k = 0; k <= i; k++) shiftDown(j);\n            continue;\n        }\n        \n        // Check downward direction\n        bool clearDown = true;\n        for (int k = i + 1; k < N; k++) {\n            if (board[k][j] == 'o') { clearDown = false; break; }\n        }\n        if (clearDown) {\n            for (int k = 0; k < N - i; k++) shiftDown(j);\n            for (int k = 0; k < N - i; k++) shiftUp(j);\n            continue;\n        }\n        \n        // Check leftward direction\n        bool clearLeft = true;\n        for (int k = 0; k < j; k++) {\n            if (board[i][k] == 'o') { clearLeft = false; break; }\n        }\n        if (clearLeft) {\n            for (int k = 0; k <= j; k++) shiftLeft(i);\n            for (int k = 0; k <= j; k++) shiftRight(i);\n            continue;\n        }\n        \n        // Must be clear rightward by problem guarantee\n        for (int k = 0; k < N - j; k++) shiftRight(i);\n        for (int k = 0; k < N - j; k++) shiftLeft(i);\n    }\n    \n    for (auto [d, p] : operations) {\n        cout << d << \" \" << p << \"\\n\";\n    }\n    \n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nlong long computeError(const vector<int>& a, const vector<int>& b, int N, int L, const vector<int>& T) {\n    vector<int> count(N, 0);\n    int current = 0;\n    count[0]++;\n    \n    for (int week = 1; week < L; week++) {\n        int next = (count[current] & 1) ? a[current] : b[current];\n        count[next]++;\n        current = next;\n    }\n    \n    long long error = 0;\n    for (int i = 0; i < N; i++) {\n        error += abs(count[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, L;\n    cin >> N >> L;\n    \n    vector<int> T(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n    \n    vector<int> best_a(N), best_b(N);\n    long long best_error = LLONG_MAX;\n    \n    mt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n    \n    for (int trial = 0; trial < 50; trial++) {\n        vector<int> a(N), b(N);\n        \n        if (trial == 0) {\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 1) % N;\n            }\n        } else if (trial == 1) {\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 2) % N;\n            }\n        } else if (trial == 2) {\n            for (int i = 0; i < N; i++) {\n                a[i] = (N - 1 - i + N) % N;\n                b[i] = (N - 2 - i + N) % N;\n            }\n        } else {\n            for (int i = 0; i < N; i++) {\n                a[i] = rng() % N;\n                b[i] = rng() % N;\n            }\n        }\n        \n        long long error = computeError(a, b, N, L, T);\n        \n        int no_improve = 0;\n        for (int iter = 0; iter < 2000 && no_improve < 300; iter++) {\n            int emp = rng() % N;\n            int param = rng() % 2;\n            int old_val = (param == 0) ? a[emp] : b[emp];\n            int new_val = rng() % N;\n            \n            if (param == 0) {\n                a[emp] = new_val;\n            } else {\n                b[emp] = new_val;\n            }\n            \n            long long new_error = computeError(a, b, N, L, T);\n            \n            if (new_error < error) {\n                error = new_error;\n                no_improve = 0;\n            } else {\n                if (param == 0) {\n                    a[emp] = old_val;\n                } else {\n                    b[emp] = old_val;\n                }\n                no_improve++;\n            }\n        }\n        \n        if (error < best_error) {\n            best_error = error;\n            best_a = a;\n            best_b = b;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    \n    vector<int> G(M);\n    for(int i = 0; i < M; i++){\n        cin >> G[i];\n    }\n    \n    vector<double> lx(N), rx(N), ly(N), ry(N);\n    for(int i = 0; i < N; i++){\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n    \n    // Estimate positions using rectangle centers\n    vector<pair<pair<double,double>, int>> cities;\n    for(int i = 0; i < N; i++){\n        double cx = (lx[i] + rx[i]) / 2.0;\n        double cy = (ly[i] + ry[i]) / 2.0;\n        cities.push_back({{cx, cy}, i});\n    }\n    sort(cities.begin(), cities.end());\n    \n    // Assign to groups in sorted order\n    vector<vector<int>> groups(M);\n    int idx = 0;\n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g]; i++){\n            groups[g].push_back(cities[idx++].second);\n        }\n    }\n    \n    // For each group, query MST edges\n    vector<vector<pair<int,int>>> edges(M);\n    \n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g] - 1; i += 2){\n            if(i < G[g] - 2){\n                // Query 3 cities\n                cout << \"? 3 \" << groups[g][i] << \" \" << groups[g][i+1] << \" \" << groups[g][i+2] << \"\\n\";\n                cout.flush();\n                \n                // Read response\n                for(int j = 0; j < 2; j++){\n                    int a, b;\n                    cin >> a >> b;\n                    edges[g].push_back({a, b});\n                }\n            } else {\n                // Add edge directly for last 2 cities if not covered\n                edges[g].push_back({groups[g][i], groups[g][i+1]});\n            }\n        }\n    }\n    \n    // Output answer\n    cout << \"!\\n\";\n    cout.flush();\n    \n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g]; i++){\n            if(i > 0) cout << \" \";\n            cout << groups[g][i];\n        }\n        cout << \"\\n\";\n        \n        for(auto [a, b] : edges[g]){\n            cout << a << \" \" << b << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<pair<int, int>> targets;\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dchar[] = {'U', 'D', 'L', 'R'};\n\nbool valid(int x, int y) {\n    return 0 <= x && x < N && 0 <= y && y < N;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    targets.resize(M);\n    for (int i = 0; i < M; i++) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n    \n    vector<pair<char, char>> result;\n    int x = targets[0].first;\n    int y = targets[0].second;\n    set<pair<int, int>> blocks;\n    \n    // Navigate from target to target\n    for (int t = 1; t < M; t++) {\n        int tx = targets[t].first;\n        int ty = targets[t].second;\n        \n        // BFS from (x, y) to (tx, ty)\n        map<pair<int, int>, pair<pair<int, int>, pair<char, char>>> parent;\n        queue<pair<int, int>> q;\n        q.push({x, y});\n        parent[{x, y}] = {{-1, -1}, {'X', 'X'}};\n        \n        while (!q.empty()) {\n            auto [cx, cy] = q.front();\n            q.pop();\n            \n            if (cx == tx && cy == ty) {\n                // Found target - reconstruct path\n                vector<pair<char, char>> path;\n                pair<int, int> p = {cx, cy};\n                while (parent[p].second.first != 'X') {\n                    path.push_back(parent[p].second);\n                    p = parent[p].first;\n                }\n                reverse(path.begin(), path.end());\n                \n                for (auto action : path) {\n                    result.push_back(action);\n                }\n                \n                x = tx;\n                y = ty;\n                break;\n            }\n            \n            // Try moving in all 4 directions\n            for (int d = 0; d < 4; d++) {\n                int nx = cx + dx[d];\n                int ny = cy + dy[d];\n                if (valid(nx, ny) && !blocks.count({nx, ny}) && !parent.count({nx, ny})) {\n                    parent[{nx, ny}] = {{cx, cy}, {'M', dchar[d]}};\n                    q.push({nx, ny});\n                }\n            }\n        }\n    }\n    \n    for (auto [a, d] : result) {\n        cout << a << \" \" << d << \"\\n\";\n    }\n    \n    return 0;\n}"},"2":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int id;\n    long long x, y, r;\n};\n\nvector<array<long long, 4>> result(205);\n\nlong long get_area(long long x1, long long y1, long long x2, long long y2) {\n    return (x2 - x1) * (y2 - y1);\n}\n\nvoid assign(vector<int> indices, const vector<Company>& companies, \n            long long x1, long long y1, long long x2, long long y2) {\n    if (indices.empty()) return;\n    if (indices.size() == 1) {\n        result[indices[0]] = {x1, y1, x2, y2};\n        return;\n    }\n    \n    // Try vertical split with weighted areas\n    double best_score = -1e18;\n    int best_strategy = -1;\n    long long best_split = x1;\n    bool best_is_vertical = true;\n    \n    // Strategy: Weighted vertical split\n    {\n        set<long long> x_coords;\n        for (int idx : indices) {\n            long long cx = companies[idx].x + 1;\n            if (cx > x1 && cx < x2) {\n                x_coords.insert(cx);\n            }\n        }\n        \n        for (long long split_coord : x_coords) {\n            long long left_desired = 0, right_desired = 0;\n            int left_count = 0, right_count = 0;\n            \n            for (int idx : indices) {\n                if (companies[idx].x < split_coord) {\n                    left_desired += companies[idx].r;\n                    left_count++;\n                } else {\n                    right_desired += companies[idx].r;\n                    right_count++;\n                }\n            }\n            \n            if (left_count == 0 || right_count == 0) continue;\n            \n            long long left_area = get_area(x1, y1, split_coord, y2);\n            long long right_area = get_area(split_coord, y1, x2, y2);\n            \n            // Prefer splits where area ratios match desired ratios\n            double left_ratio = left_desired > 0 ? (double)left_area / left_desired : 1.0;\n            double right_ratio = right_desired > 0 ? (double)right_area / right_desired : 1.0;\n            \n            // Scoring: prefer balanced ratios and ratios near 1.0\n            double score = -abs(left_ratio - right_ratio) - abs(log(left_ratio)) - abs(log(right_ratio));\n            \n            if (score > best_score) {\n                best_score = score;\n                best_strategy = 0;\n                best_split = split_coord;\n                best_is_vertical = true;\n            }\n        }\n    }\n    \n    // Strategy: Weighted horizontal split\n    {\n        set<long long> y_coords;\n        for (int idx : indices) {\n            long long cy = companies[idx].y + 1;\n            if (cy > y1 && cy < y2) {\n                y_coords.insert(cy);\n            }\n        }\n        \n        for (long long split_coord : y_coords) {\n            long long bottom_desired = 0, top_desired = 0;\n            int bottom_count = 0, top_count = 0;\n            \n            for (int idx : indices) {\n                if (companies[idx].y < split_coord) {\n                    bottom_desired += companies[idx].r;\n                    bottom_count++;\n                } else {\n                    top_desired += companies[idx].r;\n                    top_count++;\n                }\n            }\n            \n            if (bottom_count == 0 || top_count == 0) continue;\n            \n            long long bottom_area = get_area(x1, y1, x2, split_coord);\n            long long top_area = get_area(x1, split_coord, x2, y2);\n            \n            double bottom_ratio = bottom_desired > 0 ? (double)bottom_area / bottom_desired : 1.0;\n            double top_ratio = top_desired > 0 ? (double)top_area / top_desired : 1.0;\n            \n            double score = -abs(bottom_ratio - top_ratio) - abs(log(bottom_ratio)) - abs(log(top_ratio));\n            \n            if (score > best_score) {\n                best_score = score;\n                best_strategy = 1;\n                best_split = split_coord;\n                best_is_vertical = false;\n            }\n        }\n    }\n    \n    // Fallback to median split if no valid split found\n    if (best_strategy == -1) {\n        vector<long long> xs;\n        for (int idx : indices) {\n            xs.push_back(companies[idx].x);\n        }\n        sort(xs.begin(), xs.end());\n        long long med_x = xs[xs.size() / 2] + 1;\n        med_x = max(x1 + 1, min(x2 - 1, med_x));\n        \n        vector<int> left, right;\n        for (int idx : indices) {\n            if (companies[idx].x < med_x) left.push_back(idx);\n            else right.push_back(idx);\n        }\n        \n        if (!left.empty() && !right.empty()) {\n            assign(left, companies, x1, y1, med_x, y2);\n            assign(right, companies, med_x, y1, x2, y2);\n            return;\n        }\n        \n        long long mid_y = (y1 + y2) / 2;\n        vector<int> bottom, top;\n        for (int idx : indices) {\n            if (companies[idx].y < mid_y) bottom.push_back(idx);\n            else top.push_back(idx);\n        }\n        assign(bottom, companies, x1, y1, x2, mid_y);\n        assign(top, companies, x1, mid_y, x2, y2);\n        return;\n    }\n    \n    // Apply best split\n    if (best_is_vertical) {\n        vector<int> left, right;\n        for (int idx : indices) {\n            if (companies[idx].x < best_split) left.push_back(idx);\n            else right.push_back(idx);\n        }\n        assign(left, companies, x1, y1, best_split, y2);\n        assign(right, companies, best_split, y1, x2, y2);\n    } else {\n        vector<int> bottom, top;\n        for (int idx : indices) {\n            if (companies[idx].y < best_split) bottom.push_back(idx);\n            else top.push_back(idx);\n        }\n        assign(bottom, companies, x1, y1, x2, best_split);\n        assign(top, companies, x1, best_split, x2, y2);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    vector<Company> companies(n);\n    \n    for (int i = 0; i < n; i++) {\n        companies[i].id = i;\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n    \n    vector<int> indices(n);\n    iota(indices.begin(), indices.end(), 0);\n    \n    assign(indices, companies, 0, 0, 10000, 10000);\n    \n    for (int i = 0; i < n; i++) {\n        cout << result[i][0] << \" \" << result[i][1] << \" \" \n             << result[i][2] << \" \" << result[i][3] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint si, sj;\nint tile[50][50];\nint value[50][50];\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dc[] = {'U', 'D', 'L', 'R'};\n\nint best_score = 0;\nstring best_path = \"\";\nchrono::high_resolution_clock::time_point start_time;\nconst double TIME_LIMIT = 1.95;\n\nbool time_exceeded() {\n    auto now = chrono::high_resolution_clock::now();\n    double elapsed = chrono::duration<double>(now - start_time).count();\n    return elapsed > TIME_LIMIT;\n}\n\npair<int, string> walk(vector<bool>& visited_tiles, mt19937& rng) {\n    int score = value[si][sj];\n    int cur_i = si, cur_j = sj;\n    string path = \"\";\n    \n    while (true) {\n        vector<int> valid_dirs;\n        \n        // Find all valid moves (adjacent unvisited tiles)\n        for (int d = 0; d < 4; d++) {\n            int ni = cur_i + dx[d];\n            int nj = cur_j + dy[d];\n            \n            if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n                int new_tile = tile[ni][nj];\n                if (!visited_tiles[new_tile]) {\n                    valid_dirs.push_back(d);\n                }\n            }\n        }\n        \n        if (valid_dirs.empty()) break;\n        \n        int d;\n        // 70% greedy (pick highest value), 30% random exploration\n        if (uniform_real_distribution<>(0, 1)(rng) < 0.7) {\n            d = valid_dirs[0];\n            int best_v = value[cur_i + dx[d]][cur_j + dy[d]];\n            \n            // Find direction with highest value\n            for (int dd : valid_dirs) {\n                int ni = cur_i + dx[dd];\n                int nj = cur_j + dy[dd];\n                if (value[ni][nj] > best_v) {\n                    d = dd;\n                    best_v = value[ni][nj];\n                }\n            }\n        } else {\n            // Random exploration\n            d = valid_dirs[uniform_int_distribution<>(0, valid_dirs.size() - 1)(rng)];\n        }\n        \n        int ni = cur_i + dx[d];\n        int nj = cur_j + dy[d];\n        visited_tiles[tile[ni][nj]] = true;\n        path.push_back(dc[d]);\n        score += value[ni][nj];\n        cur_i = ni;\n        cur_j = nj;\n    }\n    \n    return {score, path};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> si >> sj;\n    \n    int max_tile = 0;\n    for (int i = 0; i < 50; i++) {\n        for (int j = 0; j < 50; j++) {\n            cin >> tile[i][j];\n            max_tile = max(max_tile, tile[i][j]);\n        }\n    }\n    \n    for (int i = 0; i < 50; i++) {\n        for (int j = 0; j < 50; j++) {\n            cin >> value[i][j];\n        }\n    }\n    \n    start_time = chrono::high_resolution_clock::now();\n    best_score = value[si][sj];\n    best_path = \"\";\n    \n    mt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n    \n    // Run multiple random walks until time limit\n    while (!time_exceeded()) {\n        vector<bool> visited_tiles(max_tile + 1, false);\n        visited_tiles[tile[si][sj]] = true;\n        auto [score, path] = walk(visited_tiles, rng);\n        \n        if (score > best_score) {\n            best_score = score;\n            best_path = path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\n#include <queue>\nusing namespace std;\n\nconst int N = 30;\nconst double INF = 1e18;\n\ndouble h[N][N-1], v[N-1][N];\n\nstruct State {\n    double dist;\n    int i, j;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\npair<string, double> dijkstra(int si, int sj, int ti, int tj) {\n    vector<vector<double>> dist(N, vector<double>(N, INF));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1, -1}));\n    vector<vector<char>> dir(N, vector<char>(N));\n    \n    priority_queue<State, vector<State>, greater<State>> pq;\n    dist[si][sj] = 0;\n    pq.push({0, si, sj});\n    \n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top();\n        pq.pop();\n        \n        if (d > dist[i][j]) continue;\n        \n        // Up\n        if (i > 0) {\n            double new_dist = d + v[i-1][j];\n            if (new_dist < dist[i-1][j]) {\n                dist[i-1][j] = new_dist;\n                parent[i-1][j] = {i, j};\n                dir[i-1][j] = 'U';\n                pq.push({new_dist, i-1, j});\n            }\n        }\n        \n        // Down\n        if (i < N-1) {\n            double new_dist = d + v[i][j];\n            if (new_dist < dist[i+1][j]) {\n                dist[i+1][j] = new_dist;\n                parent[i+1][j] = {i, j};\n                dir[i+1][j] = 'D';\n                pq.push({new_dist, i+1, j});\n            }\n        }\n        \n        // Left\n        if (j > 0) {\n            double new_dist = d + h[i][j-1];\n            if (new_dist < dist[i][j-1]) {\n                dist[i][j-1] = new_dist;\n                parent[i][j-1] = {i, j};\n                dir[i][j-1] = 'L';\n                pq.push({new_dist, i, j-1});\n            }\n        }\n        \n        // Right\n        if (j < N-1) {\n            double new_dist = d + h[i][j];\n            if (new_dist < dist[i][j+1]) {\n                dist[i][j+1] = new_dist;\n                parent[i][j+1] = {i, j};\n                dir[i][j+1] = 'R';\n                pq.push({new_dist, i, j+1});\n            }\n        }\n    }\n    \n    string path;\n    int ci = ti, cj = tj;\n    while (parent[ci][cj].first != -1) {\n        path += dir[ci][cj];\n        auto [pi, pj] = parent[ci][cj];\n        ci = pi;\n        cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    \n    return {path, dist[ti][tj]};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Initialize edge weights to 5000 (middle of expected range)\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N-1; j++) {\n            h[i][j] = 5000.0;\n        }\n    }\n    for (int i = 0; i < N-1; i++) {\n        for (int j = 0; j < N; j++) {\n            v[i][j] = 5000.0;\n        }\n    }\n    \n    for (int q = 0; q < 1000; q++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        auto [path, computed_length] = dijkstra(si, sj, ti, tj);\n        \n        cout << path << endl;\n        cout.flush();\n        \n        long long feedback;\n        cin >> feedback;\n        \n        // Update edge weights based on feedback\n        if (!path.empty()) {\n            double edge_estimate = (double)feedback / path.length();\n            double alpha = 0.05;  // Weight for new data\n            \n            int ci = si, cj = sj;\n            for (char c : path) {\n                if (c == 'U') {\n                    v[ci-1][cj] = (1 - alpha) * v[ci-1][cj] + alpha * edge_estimate;\n                    ci--;\n                } else if (c == 'D') {\n                    v[ci][cj] = (1 - alpha) * v[ci][cj] + alpha * edge_estimate;\n                    ci++;\n                } else if (c == 'L') {\n                    h[ci][cj-1] = (1 - alpha) * h[ci][cj-1] + alpha * edge_estimate;\n                    cj--;\n                } else if (c == 'R') {\n                    h[ci][cj] = (1 - alpha) * h[ci][cj] + alpha * edge_estimate;\n                    cj++;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc004":"#include<bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<string> strings;\nchar bestMatrix[20][20];\nint bestMatches = 0;\n\nbool isSubsequence(const string& s, char mat[20][20]) {\n    int len = (int)s.length();\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            bool found = true;\n            for(int p = 0; p < len; p++) {\n                if(mat[i][(j+p)%N] != s[p]) {\n                    found = false;\n                    break;\n                }\n            }\n            if(found) return true;\n        }\n    }\n    \n    for(int j = 0; j < N; j++) {\n        for(int i = 0; i < N; i++) {\n            bool found = true;\n            for(int p = 0; p < len; p++) {\n                if(mat[(i+p)%N][j] != s[p]) {\n                    found = false;\n                    break;\n                }\n            }\n            if(found) return true;\n        }\n    }\n    \n    return false;\n}\n\nint countMatches(char mat[20][20]) {\n    int c = 0;\n    for(const auto& s : strings) {\n        if(isSubsequence(s, mat)) c++;\n    }\n    return c;\n}\n\nvoid runSA(mt19937& rng, chrono::steady_clock::time_point deadline) {\n    char currentMatrix[20][20];\n    \n    uniform_int_distribution<int> charDist(0, 7);\n    uniform_int_distribution<int> posDist(0, N-1);\n    uniform_int_distribution<int> dirDist(0, 1);\n    uniform_real_distribution<double> realDist(0, 1);\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            currentMatrix[i][j] = 'A' + charDist(rng);\n        }\n    }\n    \n    // Aggressive warm-start: place 75% of strings at random positions\n    int numPlace = (M * 3) / 4;\n    for(int idx = 0; idx < numPlace; idx++) {\n        const auto& s = strings[idx];\n        int i = posDist(rng);\n        int j = posDist(rng);\n        int dir = dirDist(rng);\n        int len = (int)s.length();\n        \n        if(dir == 0) {  // horizontal\n            for(int p = 0; p < len; p++) {\n                currentMatrix[i][(j+p)%N] = s[p];\n            }\n        } else {  // vertical\n            for(int p = 0; p < len; p++) {\n                currentMatrix[(i+p)%N][j] = s[p];\n            }\n        }\n    }\n    \n    int currentMatches = countMatches(currentMatrix);\n    if(currentMatches > bestMatches) {\n        bestMatches = currentMatches;\n        memcpy(bestMatrix, currentMatrix, sizeof(currentMatrix));\n    }\n    \n    // Simulated annealing with optimized parameters\n    double temp = 25.0;  // Higher initial temperature\n    const double coolingRate = 0.9999;  // Slower cooling\n    \n    while(chrono::steady_clock::now() < deadline && temp > 0.0001) {\n        int i = posDist(rng);\n        int j = posDist(rng);\n        \n        char old = currentMatrix[i][j];\n        char newChar = 'A' + charDist(rng);\n        \n        if(newChar == old) continue;\n        \n        currentMatrix[i][j] = newChar;\n        int newMatches = countMatches(currentMatrix);\n        int delta = newMatches - currentMatches;\n        \n        if(delta >= 0) {\n            currentMatches = newMatches;\n            if(currentMatches > bestMatches) {\n                bestMatches = currentMatches;\n                memcpy(bestMatrix, currentMatrix, sizeof(currentMatrix));\n            }\n        } else {\n            // Metropolis criterion - accept worse moves with probability based on temperature\n            if(realDist(rng) < exp((double)delta / temp)) {\n                currentMatches = newMatches;\n            } else {\n                currentMatrix[i][j] = old;\n            }\n        }\n        \n        temp *= coolingRate;\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    strings.resize(M);\n    for(int i = 0; i < M; i++) {\n        cin >> strings[i];\n    }\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto deadline = chrono::steady_clock::now() + chrono::milliseconds(2900);\n    \n    // Multiple restarts to avoid local optima\n    while(chrono::steady_clock::now() < deadline) {\n        runSA(rng, deadline);\n    }\n    \n    // Output best result\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            cout << bestMatrix[i][j];\n        }\n        cout << '\\n';\n    }\n    \n    return 0;\n}","ahc005":"#include<bits/stdc++.h>\nusing namespace std;\n\nint N, si, sj;\nvector<string> grid;\nmap<pair<int,int>, set<pair<int,int>>> visibilityCache;\n\nset<pair<int,int>> getVisible(int i, int j) {\n    if (visibilityCache.count({i, j})) {\n        return visibilityCache[{i, j}];\n    }\n    \n    set<pair<int,int>> result;\n    if (i < 0 || i >= N || j < 0 || j >= N || grid[i][j] == '#') \n        return result;\n    \n    // Check all 4 directions from (i,j)\n    for (int jj = j; jj < N && grid[i][jj] != '#'; jj++) \n        result.insert({i, jj});\n    for (int jj = j - 1; jj >= 0 && grid[i][jj] != '#'; jj--) \n        result.insert({i, jj});\n    for (int ii = i; ii < N && grid[ii][j] != '#'; ii++) \n        result.insert({ii, j});\n    for (int ii = i - 1; ii >= 0 && grid[ii][j] != '#'; ii--) \n        result.insert({ii, j});\n    \n    return visibilityCache[{i, j}] = result;\n}\n\nvector<pair<int,int>> getPath(pair<int,int> from, pair<int,int> to) {\n    if (from == to) return {from};\n    \n    map<pair<int,int>, pair<int,int>> parent;\n    map<pair<int,int>, int> dist;\n    priority_queue<pair<int, pair<int,int>>, vector<pair<int, pair<int,int>>>, greater<>> pq;\n    \n    pq.push({0, from});\n    dist[from] = 0;\n    parent[from] = {-1, -1};\n    \n    while (!pq.empty()) {\n        auto [d, pos] = pq.top();\n        pq.pop();\n        auto [i, j] = pos;\n        \n        if (dist.count(pos) && dist[pos] < d) continue;\n        if (pos == to) break;\n        \n        int di[] = {-1, 1, 0, 0};\n        int dj[] = {0, 0, -1, 1};\n        for (int dd = 0; dd < 4; dd++) {\n            int ni = i + di[dd];\n            int nj = j + dj[dd];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && grid[ni][nj] != '#') {\n                int cost = grid[ni][nj] - '0';\n                int newDist = d + cost;\n                if (!dist.count({ni, nj}) || dist[{ni, nj}] > newDist) {\n                    dist[{ni, nj}] = newDist;\n                    parent[{ni, nj}] = {i, j};\n                    pq.push({newDist, {ni, nj}});\n                }\n            }\n        }\n    }\n    \n    vector<pair<int,int>> path;\n    auto cur = to;\n    while (cur != make_pair(-1, -1)) {\n        path.push_back(cur);\n        cur = parent[cur];\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> si >> sj;\n    grid.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    \n    vector<pair<int,int>> allRoads;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                allRoads.push_back({i, j});\n            }\n        }\n    }\n    \n    // Precompute all visibility maps\n    for (auto road : allRoads) {\n        getVisible(road.first, road.second);\n    }\n    \n    set<pair<int,int>> covered;\n    vector<pair<int,int>> waypoints;\n    \n    waypoints.push_back({si, sj});\n    for (auto cell : getVisible(si, sj)) {\n        covered.insert(cell);\n    }\n    \n    // Greedy set cover - no iteration limit\n    while ((int)covered.size() < (int)allRoads.size()) {\n        pair<int,int> best = {-1, -1};\n        int bestCover = -1;\n        \n        for (auto road : allRoads) {\n            int cover = 0;\n            for (auto vis : getVisible(road.first, road.second)) {\n                if (!covered.count(vis)) cover++;\n            }\n            if (cover > bestCover) {\n                bestCover = cover;\n                best = road;\n            }\n        }\n        \n        if (bestCover <= 0) break;\n        \n        waypoints.push_back(best);\n        for (auto cell : getVisible(best.first, best.second)) {\n            covered.insert(cell);\n        }\n    }\n    \n    waypoints.push_back({si, sj});\n    \n    string result = \"\";\n    for (size_t i = 0; i + 1 < waypoints.size(); i++) {\n        auto path = getPath(waypoints[i], waypoints[i + 1]);\n        for (size_t j = 1; j < path.size(); j++) {\n            int pi = path[j - 1].first, pj = path[j - 1].second;\n            int ni = path[j].first, nj = path[j].second;\n            if (ni < pi) result += 'U';\n            else if (ni > pi) result += 'D';\n            else if (nj < pj) result += 'L';\n            else result += 'R';\n        }\n    }\n    \n    cout << result << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n    \n    vector<vector<int>> d(N, vector<int>(K));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < K; j++) {\n            cin >> d[i][j];\n        }\n    }\n    \n    vector<set<int>> deps(N);\n    vector<vector<int>> rev_deps(N);\n    \n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        deps[v].insert(u);\n        rev_deps[u].push_back(v);\n    }\n    \n    // Calculate number of descendant tasks (transitively) for criticality\n    vector<int> num_descendants(N, -1);\n    function<int(int)> calc_descendants = [&](int u) -> int {\n        if (num_descendants[u] != -1) return num_descendants[u];\n        int count = 0;\n        for (int v : rev_deps[u]) {\n            count += 1 + calc_descendants(v);\n        }\n        return num_descendants[u] = count;\n    };\n    for (int i = 0; i < N; i++) calc_descendants(i);\n    \n    vector<int> task_status(N, -1);\n    vector<int> task_start_day(N, -1);\n    vector<int> member_task(M, -1);\n    vector<vector<double>> member_skills(M, vector<double>(K, 1.0));\n    \n    auto estimate_time = [&](int member, int task) -> double {\n        double total_deficit = 0.0;\n        for (int k = 0; k < K; k++) {\n            total_deficit += max(0.0, (double)d[task][k] - member_skills[member][k]);\n        }\n        return max(1.0, total_deficit);\n    };\n    \n    int day = 0, completed_tasks = 0;\n    \n    while (day < 2000 && completed_tasks < N) {\n        day++;\n        \n        vector<pair<int, int>> assignments;\n        \n        // Assign tasks to idle members\n        for (int member = 0; member < M; member++) {\n            if (member_task[member] != -1) continue;\n            \n            int best_task = -1;\n            double best_score = -1e18;\n            \n            // Find best available task for this member\n            for (int task = 0; task < N; task++) {\n                if (task_status[task] != -1) continue;\n                \n                // Check if all dependencies are met\n                bool deps_satisfied = true;\n                for (int dep_task : deps[task]) {\n                    if (task_status[dep_task] < 2000) {\n                        deps_satisfied = false;\n                        break;\n                    }\n                }\n                if (!deps_satisfied) continue;\n                \n                double est_time = estimate_time(member, task);\n                // Priority: high criticality + inverse of time (prefer quick tasks on critical path)\n                double score = (double)num_descendants[task] * 10.0 - est_time;\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_task = task;\n                }\n            }\n            \n            if (best_task != -1) {\n                assignments.push_back({member + 1, best_task + 1});\n                member_task[member] = best_task;\n                task_status[best_task] = day;\n                task_start_day[best_task] = day;\n            }\n        }\n        \n        cout << assignments.size();\n        for (auto [m, t] : assignments) {\n            cout << \" \" << m << \" \" << t;\n        }\n        cout << \"\\n\";\n        cout.flush();\n        \n        int n;\n        cin >> n;\n        if (n == -1) break;\n        \n        // Process completed tasks\n        for (int i = 0; i < n; i++) {\n            int member;\n            cin >> member;\n            member--;\n            \n            if (member_task[member] != -1) {\n                int task = member_task[member];\n                int duration = day - task_start_day[task] + 1;\n                \n                task_status[task] = 2000 + day;\n                member_task[member] = -1;\n                completed_tasks++;\n                \n                // Learn member skills from task completion\n                if (duration == 1) {\n                    // Task completed instantly: member has all required skills\n                    for (int k = 0; k < K; k++) {\n                        member_skills[member][k] = max(member_skills[member][k], \n                                                       (double)d[task][k] * 0.95);\n                    }\n                } else {\n                    // Estimate skill deficit from duration\n                    // Expected w = duration - 1\n                    double estimated_deficit = max(0.0, (double)(duration - 1) - 0.5);\n                    \n                    double total_requirement = 0.0;\n                    for (int k = 0; k < K; k++) {\n                        total_requirement += d[task][k];\n                    }\n                    \n                    if (total_requirement > 0.01) {\n                        // Distribute skill inference proportionally\n                        for (int k = 0; k < K; k++) {\n                            double proportion = (double)d[task][k] / total_requirement;\n                            double inferred_skill = d[task][k] - proportion * estimated_deficit;\n                            member_skills[member][k] = max(member_skills[member][k], \n                                                          max(0.0, inferred_skill * 0.9));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nll manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    struct Order {\n        int a, b, c, d;\n    };\n    \n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; i++) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n    }\n    \n    auto buildRoute = [&](const vector<int>& orders_to_use) {\n        vector<pair<int, int>> route;\n        route.push_back({400, 400});\n        \n        vector<bool> pickup_done(orders_to_use.size(), false);\n        vector<bool> delivery_done(orders_to_use.size(), false);\n        \n        int cx = 400, cy = 400;\n        \n        for (int step = 0; step < (int)orders_to_use.size() * 2; step++) {\n            int best_i = -1, best_type = -1;\n            ll best_dist = LLONG_MAX;\n            \n            for (int i = 0; i < (int)orders_to_use.size(); i++) {\n                if (!pickup_done[i]) {\n                    ll d = manhattan(cx, cy, orders[orders_to_use[i]].a, orders[orders_to_use[i]].b);\n                    if (d < best_dist) {\n                        best_dist = d;\n                        best_i = i;\n                        best_type = 0;\n                    }\n                }\n                if (pickup_done[i] && !delivery_done[i]) {\n                    ll d = manhattan(cx, cy, orders[orders_to_use[i]].c, orders[orders_to_use[i]].d);\n                    if (d < best_dist) {\n                        best_dist = d;\n                        best_i = i;\n                        best_type = 1;\n                    }\n                }\n            }\n            \n            if (best_i == -1) break;\n            \n            if (best_type == 0) {\n                cx = orders[orders_to_use[best_i]].a;\n                cy = orders[orders_to_use[best_i]].b;\n                pickup_done[best_i] = true;\n            } else {\n                cx = orders[orders_to_use[best_i]].c;\n                cy = orders[orders_to_use[best_i]].d;\n                delivery_done[best_i] = true;\n            }\n            \n            route.push_back({cx, cy});\n        }\n        \n        route.push_back({400, 400});\n        return route;\n    };\n    \n    auto calcDist = [](const vector<pair<int, int>>& route) {\n        ll total = 0;\n        for (size_t i = 0; i < route.size() - 1; i++) {\n            total += manhattan(route[i].first, route[i].second, \n                             route[i+1].first, route[i+1].second);\n        }\n        return total;\n    };\n    \n    // Try multiple order selection criteria\n    ll bestOverallDist = LLONG_MAX;\n    vector<int> bestSelected;\n    auto bestRoute = vector<pair<int, int>>();\n    \n    // Criterion 1: Closest to office\n    {\n        vector<pair<ll, int>> costs;\n        for (int i = 0; i < 1000; i++) {\n            ll cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                      manhattan(400, 400, orders[i].c, orders[i].d);\n            costs.push_back({cost, i});\n        }\n        sort(costs.begin(), costs.end());\n        \n        vector<int> selected(50);\n        for (int i = 0; i < 50; i++) {\n            selected[i] = costs[i].second;\n        }\n        \n        auto route = buildRoute(selected);\n        ll dist = calcDist(route);\n        \n        if (dist < bestOverallDist) {\n            bestOverallDist = dist;\n            bestSelected = selected;\n            bestRoute = route;\n        }\n    }\n    \n    // Criterion 2: Short pickup-delivery distance\n    {\n        vector<pair<ll, int>> costs;\n        for (int i = 0; i < 1000; i++) {\n            ll cost = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n            costs.push_back({cost, i});\n        }\n        sort(costs.begin(), costs.end());\n        \n        vector<int> selected(50);\n        for (int i = 0; i < 50; i++) {\n            selected[i] = costs[i].second;\n        }\n        \n        auto route = buildRoute(selected);\n        ll dist = calcDist(route);\n        \n        if (dist < bestOverallDist) {\n            bestOverallDist = dist;\n            bestSelected = selected;\n            bestRoute = route;\n        }\n    }\n    \n    // Criterion 3: Balanced total distance\n    {\n        vector<pair<ll, int>> costs;\n        for (int i = 0; i < 1000; i++) {\n            ll cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                      manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d) +\n                      manhattan(orders[i].c, orders[i].d, 400, 400);\n            costs.push_back({cost, i});\n        }\n        sort(costs.begin(), costs.end());\n        \n        vector<int> selected(50);\n        for (int i = 0; i < 50; i++) {\n            selected[i] = costs[i].second;\n        }\n        \n        auto route = buildRoute(selected);\n        ll dist = calcDist(route);\n        \n        if (dist < bestOverallDist) {\n            bestOverallDist = dist;\n            bestSelected = selected;\n            bestRoute = route;\n        }\n    }\n    \n    // Criterion 4: Combined distance with location variance\n    {\n        vector<pair<ll, int>> costs;\n        for (int i = 0; i < 1000; i++) {\n            ll ax = abs(orders[i].a - 400);\n            ll ay = abs(orders[i].b - 400);\n            ll cx = abs(orders[i].c - 400);\n            ll cy = abs(orders[i].d - 400);\n            ll cost = ax + ay + cx + cy;\n            costs.push_back({cost, i});\n        }\n        sort(costs.begin(), costs.end());\n        \n        vector<int> selected(50);\n        for (int i = 0; i < 50; i++) {\n            selected[i] = costs[i].second;\n        }\n        \n        auto route = buildRoute(selected);\n        ll dist = calcDist(route);\n        \n        if (dist < bestOverallDist) {\n            bestOverallDist = dist;\n            bestSelected = selected;\n            bestRoute = route;\n        }\n    }\n    \n    // Output\n    cout << \"50\";\n    for (int i = 0; i < 50; i++) {\n        cout << \" \" << (bestSelected[i] + 1);\n    }\n    cout << \"\\n\";\n    \n    cout << bestRoute.size();\n    for (const auto& p : bestRoute) {\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass UnionFind {\npublic:\n    vector<int> parent;\n    \n    UnionFind(int n) : parent(n) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    \n    int find(int x) {\n        if (parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    \n    bool unite(int x, int y) {\n        x = find(x);\n        y = find(y);\n        if (x == y) return false;\n        parent[y] = x;\n        return true;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N = 400, M = 1995;\n    vector<pair<int, int>> coords(N);\n    vector<pair<int, int>> edges(M);\n    vector<int> d(M);\n    \n    for (int i = 0; i < N; i++) {\n        cin >> coords[i].first >> coords[i].second;\n    }\n    \n    for (int i = 0; i < M; i++) {\n        cin >> edges[i].first >> edges[i].second;\n        int u = edges[i].first, v = edges[i].second;\n        long long dx = (long long)coords[u].first - coords[v].first;\n        long long dy = (long long)coords[u].second - coords[v].second;\n        d[i] = (int)round(sqrt((double)(dx*dx + dy*dy)));\n    }\n    \n    UnionFind uf(N);\n    int edges_needed = N - 1;\n    \n    for (int i = 0; i < M; i++) {\n        int length;\n        cin >> length;\n        \n        int u = edges[i].first, v = edges[i].second;\n        \n        bool accept = false;\n        if (uf.find(u) != uf.find(v)) {\n            // Tree edge: connects different components\n            if (M - i <= edges_needed || length <= 2 * d[i]) {\n                accept = true;\n            }\n        }\n        // Cycle edges are always rejected\n        \n        if (accept) {\n            uf.unite(u, v);\n            edges_needed--;\n        }\n        \n        cout << (accept ? 1 : 0) << '\\n';\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    \n    int N;\n    cin >> N;\n    vector<pair<int,int>> pets(N);\n    vector<int> pet_types(N);\n    for(int i = 0; i < N; i++){\n        int x, y, t;\n        cin >> x >> y >> t;\n        pets[i] = {x-1, y-1};\n        pet_types[i] = t;\n    }\n    \n    int M;\n    cin >> M;\n    vector<pair<int,int>> humans(M);\n    for(int i = 0; i < M; i++){\n        int x, y;\n        cin >> x >> y;\n        humans[i] = {x-1, y-1};\n    }\n    \n    for(int turn = 0; turn < 300; turn++){\n        string actions(M, '.');\n        \n        // Dynamic target based on game phase\n        int target_x, target_y;\n        if(turn < 80){\n            // Phase 1: Move toward top-left corner\n            target_x = 5;\n            target_y = 5;\n        } else if(turn < 200){\n            // Phase 2: Consolidate and expand slightly\n            target_x = 8;\n            target_y = 8;\n        } else {\n            // Phase 3: Hold position\n            target_x = 8;\n            target_y = 8;\n        }\n        \n        // Each human moves toward the target\n        for(int i = 0; i < M; i++){\n            int x = humans[i].first;\n            int y = humans[i].second;\n            \n            if(x > target_x) actions[i] = 'U';\n            else if(x < target_x) actions[i] = 'D';\n            else if(y > target_y) actions[i] = 'L';\n            else if(y < target_y) actions[i] = 'R';\n            else actions[i] = '.';\n        }\n        \n        cout << actions << endl;\n        cout.flush();\n        \n        // Read pet movements\n        for(int i = 0; i < N; i++){\n            string move;\n            cin >> move;\n            \n            // Apply movement to each pet\n            for(char c : move){\n                if(c == 'U' && pets[i].first > 0) pets[i].first--;\n                else if(c == 'D' && pets[i].first < 29) pets[i].first++;\n                else if(c == 'L' && pets[i].second > 0) pets[i].second--;\n                else if(c == 'R' && pets[i].second < 29) pets[i].second++;\n            }\n        }\n        \n        // Update human positions based on executed actions\n        for(int i = 0; i < M; i++){\n            if(actions[i] == 'U' && humans[i].first > 0) humans[i].first--;\n            else if(actions[i] == 'D' && humans[i].first < 29) humans[i].first++;\n            else if(actions[i] == 'L' && humans[i].second > 0) humans[i].second--;\n            else if(actions[i] == 'R' && humans[i].second < 29) humans[i].second++;\n        }\n    }\n    \n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n    \n    vector<string> h(20), v(19);\n    for (int i = 0; i < 20; i++) cin >> h[i];\n    for (int i = 0; i < 19; i++) cin >> v[i];\n    \n    // BFS to find shortest path\n    map<pair<int,int>, pair<pair<int,int>, char>> parent;\n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    parent[{si, sj}] = {{-1, -1}, ' '};\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        vector<tuple<int, int, char, bool>> moves = {\n            {i-1, j, 'U', i > 0 && v[i-1][j] == '0'},\n            {i+1, j, 'D', i < 19 && v[i][j] == '0'},\n            {i, j-1, 'L', j > 0 && h[i][j-1] == '0'},\n            {i, j+1, 'R', j < 19 && h[i][j] == '0'}\n        };\n        \n        for (auto [ni, nj, dir, valid] : moves) {\n            if (valid && parent.find({ni, nj}) == parent.end()) {\n                parent[{ni, nj}] = {{i, j}, dir};\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    // Reconstruct path\n    string path = \"\";\n    {\n        int i = ti, j = tj;\n        while (parent[{i, j}].first.first != -1) {\n            char c = parent[{i, j}].second;\n            path = c + path;\n            auto [pi, pj] = parent[{i, j}].first;\n            i = pi;\n            j = pj;\n        }\n    }\n    \n    // Try different repetition factors\n    int n = path.length();\n    string best_path = path;\n    double best_score = 0;\n    \n    for (int r = 1; r * n <= 200; r++) {\n        // Probability of success: (1 - p^r)^n\n        double p_fail = pow(p, (double)r);\n        double p_succ_one = 1.0 - p_fail;\n        double p_succ_all = pow(p_succ_one, (double)n);\n        \n        int length = r * n;\n        double expected_score = p_succ_all * (401.0 - length);\n        \n        if (expected_score > best_score) {\n            best_score = expected_score;\n            best_path = \"\";\n            for (int k = 0; k < r; k++) best_path += path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\n\nint di[] = {0, -1, 0, 1};\nint dj[] = {-1, 0, 1, 0};\n\nint to[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1},\n};\n\nint grid[N][N];\nint rotations[N][N];\n\ninline int getTileType(int i, int j) {\n    int base = grid[i][j];\n    int rot = rotations[i][j];\n    if (base < 4) return (base + rot) % 4;\n    if (base < 6) return 4 + (rot % 2);\n    return 6 + (rot % 2);\n}\n\nint computeLoopLength(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    for (int iter = 0; iter < 100000; iter++) {\n        int cur = getTileType(i, j);\n        int d2 = to[cur][d];\n        if (d2 == -1) return 0;\n        i += di[d2];\n        j += dj[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (i == si && j == sj && d == sd) return length;\n    }\n    return 0;\n}\n\nlong long computeScore() {\n    vector<int> loops;\n    bool visited[N][N][4] = {};\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            for (int d = 0; d < 4; d++) {\n                if (!visited[i][j][d]) {\n                    int len = computeLoopLength(i, j, d);\n                    if (len > 0) {\n                        loops.push_back(len);\n                        int ii = i, jj = j, dd = d;\n                        for (int step = 0; step < len; step++) {\n                            visited[ii][jj][dd] = true;\n                            int cur = getTileType(ii, jj);\n                            int d2 = to[cur][dd];\n                            ii += di[d2];\n                            jj += dj[d2];\n                            dd = (d2 + 2) % 4;\n                        }\n                    } else {\n                        visited[i][j][d] = true;\n                    }\n                }\n            }\n        }\n    }\n    if (loops.size() < 2) return 0;\n    sort(loops.rbegin(), loops.rend());\n    return (long long)loops[0] * loops[1];\n}\n\nvoid simulatedAnnealing(mt19937& rng, long long& bestScore, int best_rotations[N][N], \n                        const chrono::steady_clock::time_point& start, int timeLimit) {\n    long long currentScore = computeScore();\n    if (currentScore > bestScore) {\n        bestScore = currentScore;\n        memcpy(best_rotations, rotations, sizeof(int) * N * N);\n    }\n    \n    double temperature = 1000.0;\n    int iteration = 0;\n    \n    while (chrono::duration_cast<chrono::milliseconds>(\n            chrono::steady_clock::now() - start).count() < timeLimit) {\n        \n        // Try multiple moves at current temperature\n        for (int attempt = 0; attempt < 5; attempt++) {\n            int i = rng() % N;\n            int j = rng() % N;\n            int oldRot = rotations[i][j];\n            int newRot = rng() % 4;\n            \n            rotations[i][j] = newRot;\n            long long newScore = computeScore();\n            \n            double delta = (double)(newScore - currentScore);\n            \n            if (delta > 0 || exp(delta / (temperature + 1e-9)) > (double)rng() / rng.max()) {\n                currentScore = newScore;\n                if (newScore > bestScore) {\n                    bestScore = newScore;\n                    memcpy(best_rotations, rotations, sizeof(int) * N * N);\n                }\n            } else {\n                rotations[i][j] = oldRot;\n            }\n        }\n        \n        iteration++;\n        // Exponential cooling schedule\n        temperature *= 0.9995;\n        \n        if (temperature < 0.01) break;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    string line;\n    for (int i = 0; i < N; i++) {\n        cin >> line;\n        for (int j = 0; j < N; j++) {\n            grid[i][j] = line[j] - '0';\n        }\n    }\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto start = chrono::steady_clock::now();\n    \n    long long bestScore = 0;\n    int best_rotations[N][N];\n    memset(best_rotations, 0, sizeof(best_rotations));\n    \n    // Try multiple starting configurations\n    for (int restart = 0; restart < 20; restart++) {\n        if (chrono::duration_cast<chrono::milliseconds>(\n                chrono::steady_clock::now() - start).count() > 1900) break;\n        \n        if (restart == 0) {\n            // Start with all zeros\n            memset(rotations, 0, sizeof(rotations));\n        } else {\n            // Random initialization\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    rotations[i][j] = rng() % 4;\n                }\n            }\n        }\n        \n        int remainingTime = 1900 - chrono::duration_cast<chrono::milliseconds>(\n                chrono::steady_clock::now() - start).count();\n        simulatedAnnealing(rng, bestScore, best_rotations, start, remainingTime / (20 - restart));\n    }\n    \n    memcpy(rotations, best_rotations, sizeof(rotations));\n    \n    string output(N * N, '0');\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            output[i * N + j] = '0' + rotations[i][j];\n        }\n    }\n    cout << output << endl;\n    \n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nchrono::high_resolution_clock::time_point start_time;\n\nbool hasEdge(const vector<vector<int>>& board, int i1, int j1, int i2, int j2) {\n    if (i2 < 0 || i2 >= N || j2 < 0 || j2 >= N) return false;\n    if (board[i1][j1] == 0 || board[i2][j2] == 0) return false;\n    \n    int dy = i2 - i1, dx = j2 - j1;\n    if (dy == -1 && dx == 0) return (board[i1][j1] & 2) && (board[i2][j2] & 8);\n    if (dy == 1 && dx == 0) return (board[i1][j1] & 8) && (board[i2][j2] & 2);\n    if (dy == 0 && dx == -1) return (board[i1][j1] & 1) && (board[i2][j2] & 4);\n    if (dy == 0 && dx == 1) return (board[i1][j1] & 4) && (board[i2][j2] & 1);\n    return false;\n}\n\nint largestTree(const vector<vector<int>>& board) {\n    vector<vector<int>> comp(N, vector<int>(N, -1));\n    vector<int> vcount, ecount;\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (board[i][j] == 0 || comp[i][j] != -1) continue;\n            \n            int cid = vcount.size();\n            vcount.push_back(0);\n            ecount.push_back(0);\n            \n            queue<pair<int,int>> q;\n            q.push({i, j});\n            comp[i][j] = cid;\n            \n            while (!q.empty()) {\n                auto [ci, cj] = q.front();\n                q.pop();\n                vcount[cid]++;\n                \n                int di[] = {-1, 1, 0, 0};\n                int dj[] = {0, 0, -1, 1};\n                for (int d = 0; d < 4; d++) {\n                    int ni = ci + di[d];\n                    int nj = cj + dj[d];\n                    if (ni >= 0 && ni < N && nj >= 0 && nj < N && \n                        board[ni][nj] != 0 && comp[ni][nj] == -1 &&\n                        hasEdge(board, ci, cj, ni, nj)) {\n                        comp[ni][nj] = cid;\n                        q.push({ni, nj});\n                    }\n                }\n            }\n        }\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            if (j + 1 < N && hasEdge(board, i, j, i, j+1) && comp[i][j] == comp[i][j+1]) {\n                ecount[comp[i][j]]++;\n            }\n            if (i + 1 < N && hasEdge(board, i, j, i+1, j) && comp[i][j] == comp[i+1][j]) {\n                ecount[comp[i][j]]++;\n            }\n        }\n    }\n    \n    int ans = 0;\n    for (size_t c = 0; c < vcount.size(); c++) {\n        if (ecount[c] == vcount[c] - 1) {\n            ans = max(ans, vcount[c]);\n        }\n    }\n    return ans;\n}\n\ndouble getElapsedTime() {\n    auto now = chrono::high_resolution_clock::now();\n    return chrono::duration<double>(now - start_time).count();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    start_time = chrono::high_resolution_clock::now();\n    \n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    \n    int ei = 0, ej = 0;\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            int v = s[j] >= 'a' ? s[j] - 'a' + 10 : s[j] - '0';\n            board[i][j] = v;\n            if (v == 0) ei = i, ej = j;\n        }\n    }\n    \n    string result = \"\";\n    int best_tree = largestTree(board);\n    int di[] = {-1, 1, 0, 0};\n    int dj[] = {0, 0, -1, 1};\n    char dirs[] = {'U', 'D', 'L', 'R'};\n    \n    int last_improved = 0;\n    int restart_interval = max(100, T / 20);\n    \n    while ((int)result.length() < T && best_tree < N * N - 1 && getElapsedTime() < 2.8) {\n        vector<pair<int, int>> moves;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = ei + di[d];\n            int nj = ej + dj[d];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                swap(board[ei][ej], board[ni][nj]);\n                int score = largestTree(board);\n                swap(board[ei][ej], board[ni][nj]);\n                moves.push_back({score, d});\n            }\n        }\n        \n        if (moves.empty()) break;\n        \n        sort(moves.rbegin(), moves.rend());\n        \n        // Simulated annealing\n        int best_dir = moves[0].second;\n        double progress = (double)result.length() / T;\n        double temperature = 2.0 * (1.0 - progress);\n        \n        // Accept top 1-3 moves with probability based on temperature\n        if (moves.size() > 1 && temperature > 0.1) {\n            double rand_val = (double)rand() / RAND_MAX;\n            int accept_rank = 0;\n            double prob = exp(-0.5 * accept_rank / max(0.1, temperature));\n            \n            for (size_t i = 1; i < moves.size() && i < 3; i++) {\n                prob += exp(-0.5 * (double)i / max(0.1, temperature));\n            }\n            \n            rand_val *= prob;\n            for (size_t i = 0; i < moves.size() && i < 3; i++) {\n                rand_val -= exp(-0.5 * (double)i / max(0.1, temperature));\n                if (rand_val < 0) {\n                    best_dir = moves[i].second;\n                    break;\n                }\n            }\n        }\n        \n        int ni = ei + di[best_dir];\n        int nj = ej + dj[best_dir];\n        swap(board[ei][ej], board[ni][nj]);\n        result += dirs[best_dir];\n        ei = ni;\n        ej = nj;\n        \n        int new_tree = largestTree(board);\n        if (new_tree > best_tree) {\n            best_tree = new_tree;\n            last_improved = result.length();\n        }\n        \n        // Periodic restart from best configuration\n        if ((int)result.length() - last_improved > restart_interval && \n            (int)result.length() < T - 200) {\n            // Do some random moves to diversify\n            for (int r = 0; r < min(50, (T - (int)result.length()) / 4); r++) {\n                vector<int> valid;\n                for (int d = 0; d < 4; d++) {\n                    if (ei + di[d] >= 0 && ei + di[d] < N && \n                        ej + dj[d] >= 0 && ej + dj[d] < N) {\n                        valid.push_back(d);\n                    }\n                }\n                if (valid.empty()) break;\n                int d = valid[rand() % valid.size()];\n                swap(board[ei][ej], board[ei + di[d]][ej + dj[d]]);\n                ei += di[d];\n                ej += dj[d];\n                result += dirs[d];\n            }\n            last_improved = result.length();\n        }\n    }\n    \n    cout << result << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<tuple<long long, long long, long long, long long>> cuts;\nvector<pair<long long, long long>> berries;\n\nvoid recursivePartition(vector<int> indices, int depth) {\n    if (indices.size() <= 1 || (int)cuts.size() >= 100 || depth >= 15) return;\n    \n    // Find bounding box of strawberries in this region\n    long long minX = LLONG_MAX, maxX = LLONG_MIN;\n    long long minY = LLONG_MAX, maxY = LLONG_MIN;\n    \n    for (int i : indices) {\n        minX = min(minX, berries[i].first);\n        maxX = max(maxX, berries[i].first);\n        minY = min(minY, berries[i].second);\n        maxY = max(maxY, berries[i].second);\n    }\n    \n    long long rangeX = maxX - minX;\n    long long rangeY = maxY - minY;\n    \n    // If all strawberries are at the same point or very close, stop splitting\n    if (rangeX <= 1 && rangeY <= 1) return;\n    \n    vector<int> left, right;\n    \n    if (rangeX >= rangeY) {\n        // Make a vertical cut\n        long long cutX = (minX + maxX) / 2;\n        // Offset slightly to ensure we don't cut exactly on a strawberry center\n        if (rangeX > 0) cutX += 1;\n        \n        cuts.push_back({cutX, -1000000000LL, cutX, 1000000000LL});\n        \n        for (int i : indices) {\n            if (berries[i].first < cutX) {\n                left.push_back(i);\n            } else {\n                right.push_back(i);\n            }\n        }\n    } else {\n        // Make a horizontal cut\n        long long cutY = (minY + maxY) / 2;\n        if (rangeY > 0) cutY += 1;\n        \n        cuts.push_back({-1000000000LL, cutY, 1000000000LL, cutY});\n        \n        for (int i : indices) {\n            if (berries[i].second < cutY) {\n                left.push_back(i);\n            } else {\n                right.push_back(i);\n            }\n        }\n    }\n    \n    // Recursively partition left and right regions\n    if (!left.empty() && left.size() < indices.size()) {\n        recursivePartition(left, depth + 1);\n    }\n    if (!right.empty() && right.size() < indices.size()) {\n        recursivePartition(right, depth + 1);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, K;\n    cin >> N >> K;\n    \n    vector<int> a(11);\n    for (int d = 1; d <= 10; d++) {\n        cin >> a[d];\n    }\n    \n    berries.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> berries[i].first >> berries[i].second;\n    }\n    \n    // Start recursive partitioning with all indices\n    vector<int> allIndices;\n    for (int i = 0; i < N; i++) {\n        allIndices.push_back(i);\n    }\n    \n    recursivePartition(allIndices, 0);\n    \n    // Output cuts\n    cout << (int)cuts.size() << \"\\n\";\n    for (const auto& [px, py, qx, qy] : cuts) {\n        cout << px << \" \" << py << \" \" << qx << \" \" << qy << \"\\n\";\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nset<pair<int,int>> dots;\nset<tuple<int,int,int,int>> used_edges;\n\nbool is_valid_point(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_segment_clear(int x1, int y1, int x2, int y2) {\n    if (x1 == x2) {\n        int miny = min(y1, y2), maxy = max(y1, y2);\n        for (int y = miny + 1; y < maxy; y++) {\n            if (dots.count({x1, y})) return false;\n        }\n    } else if (y1 == y2) {\n        int minx = min(x1, x2), maxx = max(x1, x2);\n        for (int x = minx + 1; x < maxx; x++) {\n            if (dots.count({x, y1})) return false;\n        }\n    } else {\n        int dx = (x2 > x1) ? 1 : -1;\n        int dy = (y2 > y1) ? 1 : -1;\n        int x = x1 + dx, y = y1 + dy;\n        while (x != x2 || y != y2) {\n            if (dots.count({x, y})) return false;\n            x += dx; y += dy;\n        }\n    }\n    return true;\n}\n\nauto normalize_edge = [](int x1, int y1, int x2, int y2) {\n    if (x1 > x2 || (x1 == x2 && y1 > y2)) swap(x1, x2), swap(y1, y2);\n    return make_tuple(x1, y1, x2, y2);\n};\n\nbool check_edge_overlap(int x1, int y1, int x2, int y2) {\n    return used_edges.count(normalize_edge(x1, y1, x2, y2));\n}\n\nbool is_valid_rect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (dots.count({x1, y1})) return false;\n    if (!dots.count({x2, y2}) || !dots.count({x3, y3}) || !dots.count({x4, y4})) return false;\n    \n    if (!check_segment_clear(x1, y1, x2, y2) || !check_segment_clear(x2, y2, x3, y3) ||\n        !check_segment_clear(x3, y3, x4, y4) || !check_segment_clear(x4, y4, x1, y1)) \n        return false;\n    \n    if (check_edge_overlap(x1, y1, x2, y2) || check_edge_overlap(x2, y2, x3, y3) ||\n        check_edge_overlap(x3, y3, x4, y4) || check_edge_overlap(x4, y4, x1, y1))\n        return false;\n    \n    return true;\n}\n\nvoid record_rect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    used_edges.insert(normalize_edge(x1, y1, x2, y2));\n    used_edges.insert(normalize_edge(x2, y2, x3, y3));\n    used_edges.insert(normalize_edge(x3, y3, x4, y4));\n    used_edges.insert(normalize_edge(x4, y4, x1, y1));\n}\n\ndouble weight(int x, int y) {\n    double c = (N - 1) / 2.0;\n    return (x - c) * (x - c) + (y - c) * (y - c) + 1;\n}\n\nint main() {\n    cin >> N >> M;\n    \n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        dots.insert({x, y});\n    }\n    \n    vector<tuple<int,int,int,int,int,int,int,int>> ops;\n    auto start = chrono::high_resolution_clock::now();\n    \n    bool found = true;\n    while (found) {\n        auto now = chrono::high_resolution_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - start).count() > 4800) break;\n        \n        found = false;\n        int bx1 = -1, by1 = -1, bx2 = -1, by2 = -1, bx3 = -1, by3 = -1, bx4 = -1, by4 = -1;\n        double best_w = -1;\n        \n        vector<pair<int,int>> dot_list(dots.begin(), dots.end());\n        \n        for (int i = 0; i < (int)dot_list.size(); i++) {\n            for (int j = i + 1; j < (int)dot_list.size(); j++) {\n                for (int k = j + 1; k < (int)dot_list.size(); k++) {\n                    auto [x2, y2] = dot_list[i];\n                    auto [x3, y3] = dot_list[j];\n                    auto [x4, y4] = dot_list[k];\n                    \n                    set<int> xs = {x2, x3, x4}, ys = {y2, y3, y4};\n                    if (xs.size() == 2 && ys.size() == 2) {\n                        vector<int> xs_v(xs.begin(), xs.end()), ys_v(ys.begin(), ys.end());\n                        for (int x1 : xs_v) {\n                            for (int y1 : ys_v) {\n                                if (!dots.count({x1, y1})) {\n                                    vector<pair<int,int>> pts = {{x2,y2}, {x3,y3}, {x4,y4}};\n                                    for (int a = 0; a < 3; a++) {\n                                        for (int b = 0; b < 3; b++) {\n                                            if (a == b) continue;\n                                            int c = 3 - a - b;\n                                            if (is_valid_rect(x1, y1, pts[a].first, pts[a].second, \n                                                             pts[b].first, pts[b].second, \n                                                             pts[c].first, pts[c].second)) {\n                                                double w = weight(x1, y1);\n                                                if (w > best_w) {\n                                                    best_w = w;\n                                                    bx1 = x1; by1 = y1;\n                                                    bx2 = pts[a].first; by2 = pts[a].second;\n                                                    bx3 = pts[b].first; by3 = pts[b].second;\n                                                    bx4 = pts[c].first; by4 = pts[c].second;\n                                                }\n                                            }\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        if (best_w > 0) {\n            found = true;\n            dots.insert({bx1, by1});\n            record_rect(bx1, by1, bx2, by2, bx3, by3, bx4, by4);\n            ops.push_back({bx1, by1, bx2, by2, bx3, by3, bx4, by4});\n        }\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto [x1, y1, x2, y2, x3, y3, x4, y4] : ops) {\n        cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \" \"\n             << x3 << \" \" << y3 << \" \" << x4 << \" \" << y4 << \"\\n\";\n    }\n    \n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nint grid[10][10];\nvector<int> flavors;\n\nvoid place_candy(int pos, int flavor) {\n    int count = 0;\n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (grid[i][j] == 0) {\n                count++;\n                if (count == pos) {\n                    grid[i][j] = flavor;\n                    return;\n                }\n            }\n        }\n    }\n}\n\nvoid tilt(char dir, int target[10][10]) {\n    int temp[10][10];\n    memcpy(temp, grid, sizeof(grid));\n    memset(target, 0, sizeof(int) * 100);\n    \n    if (dir == 'F') {\n        for (int j = 0; j < 10; j++) {\n            vector<int> candies;\n            for (int i = 0; i < 10; i++) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t i = 0; i < candies.size(); i++) {\n                target[i][j] = candies[i];\n            }\n        }\n    } else if (dir == 'B') {\n        for (int j = 0; j < 10; j++) {\n            vector<int> candies;\n            for (int i = 9; i >= 0; i--) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t i = 0; i < candies.size(); i++) {\n                target[9 - i][j] = candies[i];\n            }\n        }\n    } else if (dir == 'L') {\n        for (int i = 0; i < 10; i++) {\n            vector<int> candies;\n            for (int j = 0; j < 10; j++) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t j = 0; j < candies.size(); j++) {\n                target[i][j] = candies[j];\n            }\n        }\n    } else if (dir == 'R') {\n        for (int i = 0; i < 10; i++) {\n            vector<int> candies;\n            for (int j = 9; j >= 0; j--) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t j = 0; j < candies.size(); j++) {\n                target[i][9 - j] = candies[j];\n            }\n        }\n    }\n}\n\npair<long long, int> compute_score(int test_grid[10][10]) {\n    bool visited[10][10] = {};\n    long long sum_sq = 0;\n    int num_components = 0;\n    \n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (test_grid[i][j] > 0 && !visited[i][j]) {\n                int flavor = test_grid[i][j];\n                int component_size = 0;\n                \n                queue<pair<int, int>> q;\n                q.push({i, j});\n                visited[i][j] = true;\n                \n                while (!q.empty()) {\n                    auto [r, c] = q.front();\n                    q.pop();\n                    component_size++;\n                    \n                    int dr[] = {-1, 1, 0, 0};\n                    int dc[] = {0, 0, -1, 1};\n                    \n                    for (int d = 0; d < 4; d++) {\n                        int nr = r + dr[d];\n                        int nc = c + dc[d];\n                        if (nr >= 0 && nr < 10 && nc >= 0 && nc < 10 && \n                            test_grid[nr][nc] == flavor && !visited[nr][nc]) {\n                            visited[nr][nc] = true;\n                            q.push({nr, nc});\n                        }\n                    }\n                }\n                \n                sum_sq += (long long)component_size * component_size;\n                num_components++;\n            }\n        }\n    }\n    \n    return {sum_sq, num_components};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    memset(grid, 0, sizeof(grid));\n    flavors.resize(100);\n    \n    for (int i = 0; i < 100; i++) {\n        cin >> flavors[i];\n    }\n    \n    for (int t = 0; t < 100; t++) {\n        int pos;\n        cin >> pos;\n        place_candy(pos, flavors[t]);\n        \n        if (t < 99) {\n            char dirs[] = {'F', 'B', 'L', 'R'};\n            long long best_score = -1;\n            int best_components = INT_MAX;\n            char best_dir = 'F';\n            \n            for (int d = 0; d < 4; d++) {\n                int temp[10][10];\n                tilt(dirs[d], temp);\n                auto [score, num_comp] = compute_score(temp);\n                \n                // Primary: maximize sum of squares\n                // Secondary: minimize number of components (tie-breaker)\n                if (score > best_score || \n                    (score == best_score && num_comp < best_components)) {\n                    best_score = score;\n                    best_components = num_comp;\n                    best_dir = dirs[d];\n                }\n            }\n            \n            cout << best_dir << \"\\n\";\n            cout.flush();\n            \n            // Apply the best move\n            int temp[10][10];\n            tilt(best_dir, temp);\n            memcpy(grid, temp, sizeof(grid));\n        }\n    }\n    \n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int M;\n    double eps;\n    cin >> M >> eps;\n    \n    // Choose N based on M to balance score (1/N factor) and discrimination ability\n    int N;\n    if (M <= 20) N = 10;\n    else if (M <= 50) N = 15;\n    else N = 20;\n    N = max(4, min(100, N));\n    \n    int max_edges = N * (N - 1) / 2;\n    \n    cout << N << endl;\n    cout.flush();\n    \n    // Compute target edge counts for each graph (evenly distributed)\n    vector<int> target(M);\n    for (int k = 0; k < M; k++) {\n        target[k] = k * max_edges / M;\n    }\n    \n    // Output the M graphs with different edge counts\n    for (int k = 0; k < M; k++) {\n        string graph(max_edges, '0');\n        // Add the first target[k] edges\n        for (int i = 0; i < target[k]; i++) {\n            graph[i] = '1';\n        }\n        cout << graph << endl;\n        cout.flush();\n    }\n    \n    // Process 100 queries\n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n        \n        // Count edges in received graph\n        int edge_count = count(H.begin(), H.end(), '1');\n        \n        // Find the target with closest edge count\n        int best = 0;\n        int best_dist = abs(edge_count - target[0]);\n        for (int k = 1; k < M; k++) {\n            int dist = abs(edge_count - target[k]);\n            if (dist < best_dist) {\n                best_dist = dist;\n                best = k;\n            }\n        }\n        \n        cout << best << endl;\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long INF = 1e9;\n\nint N, M, D, K;\nvector<tuple<int, int, long long>> edges;\nvector<vector<long long>> dist;\n\nlong long compute_frustration(const vector<int>& assignment){\n    long long total = 0;\n    \n    for(int day = 1; day <= D; day++){\n        vector<vector<pair<int, long long>>> adj(N);\n        for(int i = 0; i < M; i++){\n            if(assignment[i] != day){\n                auto [u, v, w] = edges[i];\n                adj[u].push_back({v, w});\n                adj[v].push_back({u, w});\n            }\n        }\n        \n        for(int src = 0; src < N; src++){\n            vector<long long> d(N, INF);\n            d[src] = 0;\n            priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n            pq.push({0, src});\n            \n            while(!pq.empty()){\n                auto [cd, u] = pq.top();\n                pq.pop();\n                if(cd > d[u]) continue;\n                \n                for(auto& [v, w] : adj[u]){\n                    long long nd = d[u] + w;\n                    if(nd < d[v]){\n                        d[v] = nd;\n                        pq.push({nd, v});\n                    }\n                }\n            }\n            \n            for(int dst = 0; dst < N; dst++){\n                if(src != dst && d[dst] < INF){\n                    long long inc = d[dst] - dist[src][dst];\n                    if(inc > 0) total += inc;\n                }\n            }\n        }\n    }\n    \n    return total;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> D >> K;\n    \n    edges.resize(M);\n    vector<vector<pair<int, long long>>> adj(N);\n    \n    for(int i = 0; i < M; i++){\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edges[i] = {u, v, w};\n        adj[u].push_back({v, w});\n        adj[v].push_back({u, w});\n    }\n    \n    for(int i = 0; i < N; i++){\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    // Compute original shortest paths\n    dist.assign(N, vector<long long>(N, INF));\n    for(int i = 0; i < N; i++){\n        dist[i][i] = 0;\n        priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n        pq.push({0, i});\n        \n        while(!pq.empty()){\n            auto [d, u] = pq.top();\n            pq.pop();\n            if(d > dist[i][u]) continue;\n            \n            for(auto& [v, w] : adj[u]){\n                long long nd = dist[i][u] + w;\n                if(nd < dist[i][v]){\n                    dist[i][v] = nd;\n                    pq.push({nd, v});\n                }\n            }\n        }\n    }\n    \n    // Initial assignment - round robin\n    vector<int> best(M);\n    for(int i = 0; i < M; i++){\n        best[i] = (i % D) + 1;\n    }\n    \n    long long best_score = compute_frustration(best);\n    \n    // Local search with random restarts\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto start = chrono::steady_clock::now();\n    \n    while(chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count() < 5500){\n        vector<int> cur = best;\n        \n        int idx = uniform_int_distribution<int>(0, M-1)(rng);\n        int new_day = uniform_int_distribution<int>(1, D)(rng);\n        cur[idx] = new_day;\n        \n        long long score = compute_frustration(cur);\n        \n        if(score < best_score){\n            best = cur;\n            best_score = score;\n        }\n    }\n    \n    for(int i = 0; i < M; i++){\n        cout << best[i];\n        if(i + 1 < M) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef array<int, 3> Pos;\n\nint D;\n\nstruct Block {\n    set<Pos> voxels;\n    \n    Block() {}\n    Block(const set<Pos>& v) : voxels(v) {}\n    \n    void normalize() {\n        if (voxels.empty()) return;\n        int minx = INT_MAX, miny = INT_MAX, minz = INT_MAX;\n        for (auto p : voxels) {\n            minx = min(minx, p[0]);\n            miny = min(miny, p[1]);\n            minz = min(minz, p[2]);\n        }\n        set<Pos> normalized;\n        for (auto p : voxels) {\n            normalized.insert({p[0] - minx, p[1] - miny, p[2] - minz});\n        }\n        voxels = normalized;\n    }\n    \n    bool operator==(const Block& other) const {\n        return voxels == other.voxels;\n    }\n};\n\nvoid extract_blocks(vector<vector<vector<int>>>& grid, vector<Block>& blocks, vector<vector<vector<int>>>& result) {\n    vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    \n    for (int x = 0; x < D; x++) {\n        for (int y = 0; y < D; y++) {\n            for (int z = 0; z < D; z++) {\n                if (grid[x][y][z] == 1 && !visited[x][y][z]) {\n                    set<Pos> voxels;\n                    queue<Pos> q;\n                    q.push({x, y, z});\n                    visited[x][y][z] = true;\n                    \n                    while (!q.empty()) {\n                        auto p = q.front();\n                        q.pop();\n                        voxels.insert(p);\n                        \n                        int dx[] = {1, -1, 0, 0, 0, 0};\n                        int dy[] = {0, 0, 1, -1, 0, 0};\n                        int dz[] = {0, 0, 0, 0, 1, -1};\n                        \n                        for (int i = 0; i < 6; i++) {\n                            int nx = p[0] + dx[i], ny = p[1] + dy[i], nz = p[2] + dz[i];\n                            if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                grid[nx][ny][nz] == 1 && !visited[nx][ny][nz]) {\n                                visited[nx][ny][nz] = true;\n                                q.push({nx, ny, nz});\n                            }\n                        }\n                    }\n                    \n                    Block block(voxels);\n                    block.normalize();\n                    blocks.push_back(block);\n                    int bid = blocks.size();\n                    \n                    for (auto p : voxels) {\n                        result[p[0]][p[1]][p[2]] = bid;\n                    }\n                }\n            }\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D;\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    \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<int>>> grid1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> grid2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    \n    for (int x = 0; x < D; x++) {\n        for (int y = 0; y < D; y++) {\n            for (int z = 0; z < D; z++) {\n                if (f1[z][x] == '1' && r1[z][y] == '1') grid1[x][y][z] = 1;\n                if (f2[z][x] == '1' && r2[z][y] == '1') grid2[x][y][z] = 1;\n            }\n        }\n    }\n    \n    vector<Block> blocks;\n    vector<vector<vector<int>>> result1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> result2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    \n    extract_blocks(grid1, blocks, result1);\n    \n    vector<vector<vector<bool>>> visited2(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    for (int x = 0; x < D; x++) {\n        for (int y = 0; y < D; y++) {\n            for (int z = 0; z < D; z++) {\n                if (grid2[x][y][z] == 1 && !visited2[x][y][z]) {\n                    set<Pos> voxels;\n                    queue<Pos> q;\n                    q.push({x, y, z});\n                    visited2[x][y][z] = true;\n                    \n                    while (!q.empty()) {\n                        auto p = q.front();\n                        q.pop();\n                        voxels.insert(p);\n                        int dx[] = {1, -1, 0, 0, 0, 0};\n                        int dy[] = {0, 0, 1, -1, 0, 0};\n                        int dz[] = {0, 0, 0, 0, 1, -1};\n                        for (int i = 0; i < 6; i++) {\n                            int nx = p[0] + dx[i], ny = p[1] + dy[i], nz = p[2] + dz[i];\n                            if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                grid2[nx][ny][nz] == 1 && !visited2[nx][ny][nz]) {\n                                visited2[nx][ny][nz] = true;\n                                q.push({nx, ny, nz});\n                            }\n                        }\n                    }\n                    \n                    Block block2(voxels);\n                    block2.normalize();\n                    \n                    int bid = -1;\n                    for (int i = 0; i < blocks.size(); i++) {\n                        if (blocks[i] == block2) {\n                            bid = i + 1;\n                            break;\n                        }\n                    }\n                    if (bid == -1) {\n                        blocks.push_back(block2);\n                        bid = blocks.size();\n                    }\n                    \n                    for (auto p : voxels) {\n                        result2[p[0]][p[1]][p[2]] = bid;\n                    }\n                }\n            }\n        }\n    }\n    \n    cout << blocks.size() << \"\\n\";\n    for (int x = 0; x < D; x++)\n        for (int y = 0; y < D; y++)\n            for (int z = 0; z < D; z++) {\n                if (x || y || z) cout << \" \";\n                cout << result1[x][y][z];\n            }\n    cout << \"\\n\";\n    for (int x = 0; x < D; x++)\n        for (int y = 0; y < D; y++)\n            for (int z = 0; z < D; z++) {\n                if (x || y || z) cout << \" \";\n                cout << result2[x][y][z];\n            }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc020":"#include<bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    double x, y;\n};\n\ndouble dist(Point a, Point b) {\n    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\nint N, M, K;\nvector<Point> stations;\nvector<pair<int,int>> edgeEndpoints;\nvector<long long> weights;\nvector<Point> residents;\n\nvector<bool> getReachable(const vector<bool>& enabled) {\n    vector<bool> reachable(N, false);\n    reachable[0] = true;\n    queue<int> q;\n    q.push(0);\n    while(!q.empty()){\n        int u = q.front();\n        q.pop();\n        for(int e = 0; e < M; e++){\n            if(!enabled[e]) continue;\n            int v = -1;\n            if(edgeEndpoints[e].first == u) v = edgeEndpoints[e].second;\n            else if(edgeEndpoints[e].second == u) v = edgeEndpoints[e].first;\n            if(v != -1 && !reachable[v]){\n                reachable[v] = true;\n                q.push(v);\n            }\n        }\n    }\n    return reachable;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    \n    stations.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> stations[i].x >> stations[i].y;\n    }\n    \n    edgeEndpoints.resize(M);\n    weights.resize(M);\n    for(int i = 0; i < M; i++){\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edgeEndpoints[i] = {u, v};\n        weights[i] = w;\n    }\n    \n    residents.resize(K);\n    for(int i = 0; i < K; i++){\n        cin >> residents[i].x >> residents[i].y;\n    }\n    \n    vector<long long> P(N, 0);\n    vector<bool> enabled(M, false);\n    \n    // Initial: cover nearby residents with station 0\n    for(int k = 0; k < K; k++){\n        long long d = (long long)round(dist(stations[0], residents[k]));\n        if(d <= 5000){\n            P[0] = max(P[0], d);\n        }\n    }\n    \n    // Greedy: add edges until all residents are covered\n    while(true) {\n        auto reachable = getReachable(enabled);\n        \n        // Find uncovered residents\n        set<int> uncovered;\n        for(int k = 0; k < K; k++){\n            bool covered = false;\n            for(int i = 0; i < N; i++){\n                if(reachable[i] && P[i] >= (long long)round(dist(stations[i], residents[k]))){\n                    covered = true;\n                    break;\n                }\n            }\n            if(!covered) uncovered.insert(k);\n        }\n        \n        if(uncovered.empty()) break;\n        \n        // Find best edge to enable\n        double bestScore = 1e18;\n        int bestEdge = -1;\n        int bestVertex = -1;\n        \n        for(int e = 0; e < M; e++){\n            if(enabled[e]) continue;\n            \n            int u = edgeEndpoints[e].first;\n            int v = edgeEndpoints[e].second;\n            \n            bool u_reach = reachable[u];\n            bool v_reach = reachable[v];\n            \n            if(!u_reach && !v_reach) continue;\n            \n            int newV = u_reach ? v : u;\n            \n            long long maxP = 0;\n            int covered = 0;\n            for(int k : uncovered){\n                long long d = (long long)round(dist(stations[newV], residents[k]));\n                if(d <= 5000){\n                    maxP = max(maxP, d);\n                    covered++;\n                }\n            }\n            \n            if(covered == 0) continue;\n            \n            long long cost = weights[e] + maxP * maxP;\n            double score = (double)cost / covered;\n            \n            if(score < bestScore){\n                bestScore = score;\n                bestEdge = e;\n                bestVertex = newV;\n            }\n        }\n        \n        if(bestEdge == -1) break;\n        \n        enabled[bestEdge] = true;\n        for(int k : uncovered){\n            long long d = (long long)round(dist(stations[bestVertex], residents[k]));\n            if(d <= 5000){\n                P[bestVertex] = max(P[bestVertex], d);\n            }\n        }\n    }\n    \n    // Optimize: assign each resident to closest reachable station\n    auto reachable = getReachable(enabled);\n    fill(P.begin(), P.end(), 0);\n    for(int k = 0; k < K; k++){\n        long long minDist = LLONG_MAX;\n        int bestV = -1;\n        for(int i = 0; i < N; i++){\n            if(reachable[i]){\n                long long d = (long long)round(dist(stations[i], residents[k]));\n                if(d < minDist){\n                    minDist = d;\n                    bestV = i;\n                }\n            }\n        }\n        if(bestV != -1) P[bestV] = max(P[bestV], minDist);\n    }\n    \n    // Output\n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << P[i];\n    }\n    cout << \"\\n\";\n    \n    for(int i = 0; i < M; i++){\n        if(i > 0) cout << \" \";\n        cout << (enabled[i] ? 1 : 0);\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 30;\n    vector<vector<int>> pyramid(N);\n    \n    // Read input\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    vector<tuple<int,int,int,int>> operations;\n    \n    // Build min-heap structure using heapify algorithm\n    // Process from second-to-last level upwards (bottom-up)\n    for (int x = N - 2; x >= 0; x--) {\n        for (int y = 0; y <= x; y++) {\n            // Sift down from position (x, y)\n            int curr_x = x, curr_y = y;\n            while (curr_x + 1 < N && (int)operations.size() < 10000) {\n                int parent_val = pyramid[curr_x][curr_y];\n                int left_child_val = pyramid[curr_x + 1][curr_y];\n                int right_child_val = pyramid[curr_x + 1][curr_y + 1];\n                \n                // If parent is smaller than both children, heap property satisfied\n                if (parent_val <= left_child_val && parent_val <= right_child_val) {\n                    break;\n                }\n                \n                // Swap with the smaller child\n                if (left_child_val <= right_child_val) {\n                    swap(pyramid[curr_x][curr_y], pyramid[curr_x + 1][curr_y]);\n                    operations.push_back({curr_x, curr_y, curr_x + 1, curr_y});\n                    curr_x++;\n                } else {\n                    swap(pyramid[curr_x][curr_y], pyramid[curr_x + 1][curr_y + 1]);\n                    operations.push_back({curr_x, curr_y, curr_x + 1, curr_y + 1});\n                    curr_x++;\n                    curr_y++;\n                }\n            }\n        }\n    }\n    \n    // Output result\n    cout << (int)operations.size() << \"\\n\";\n    for (auto [x1, y1, x2, y2] : operations) {\n        cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \"\\n\";\n    }\n    \n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D, N;\n    cin >> D >> N;\n    \n    set<pair<int,int>> obstacles;\n    for(int i = 0; i < N; i++){\n        int r, c;\n        cin >> r >> c;\n        obstacles.insert({r, c});\n    }\n    \n    pair<int,int> entrance = {0, (D-1)/2};\n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    \n    // Place containers\n    map<pair<int,int>, int> container_at;\n    \n    for(int i = 0; i < D*D - 1 - N; i++){\n        int t;\n        cin >> t;\n        \n        // Find reachable empty squares in BFS order\n        vector<pair<int,int>> reachable_empty;\n        queue<pair<int,int>> q;\n        set<pair<int,int>> visited;\n        q.push(entrance);\n        visited.insert(entrance);\n        \n        while(!q.empty()){\n            auto [r, c] = q.front();\n            q.pop();\n            \n            if(!(r == 0 && c == (D-1)/2)){\n                reachable_empty.push_back({r, c});\n            }\n            \n            for(int dir = 0; dir < 4; dir++){\n                int nr = r + dr[dir];\n                int nc = c + dc[dir];\n                \n                if(nr >= 0 && nr < D && nc >= 0 && nc < D &&\n                   !visited.count({nr, nc}) &&\n                   !obstacles.count({nr, nc}) &&\n                   !container_at.count({nr, nc})){\n                    visited.insert({nr, nc});\n                    q.push({nr, nc});\n                }\n            }\n        }\n        \n        auto chosen = reachable_empty[0];\n        container_at[chosen] = t;\n        cout << chosen.first << \" \" << chosen.second << \"\\n\";\n        cout.flush();\n    }\n    \n    // Retrieve containers optimally\n    for(int extracted = 0; extracted < D*D - 1 - N; extracted++){\n        // Find all reachable container positions\n        set<pair<int,int>> reachable;\n        queue<pair<int,int>> q;\n        set<pair<int,int>> visited_empty;\n        q.push(entrance);\n        visited_empty.insert(entrance);\n        \n        while(!q.empty()){\n            auto [r, c] = q.front();\n            q.pop();\n            \n            for(int dir = 0; dir < 4; dir++){\n                int nr = r + dr[dir];\n                int nc = c + dc[dir];\n                \n                if(nr >= 0 && nr < D && nc >= 0 && nc < D &&\n                   !visited_empty.count({nr, nc}) &&\n                   !obstacles.count({nr, nc})){\n                    \n                    if(!container_at.count({nr, nc})){\n                        visited_empty.insert({nr, nc});\n                        q.push({nr, nc});\n                    } else {\n                        reachable.insert({nr, nc});\n                    }\n                }\n            }\n        }\n        \n        // Find reachable container with smallest number\n        pair<int,int> best_pos;\n        int best_num = INT_MAX;\n        for(auto& [pos, num] : container_at){\n            if(reachable.count(pos) && num < best_num){\n                best_num = num;\n                best_pos = pos;\n            }\n        }\n        \n        cout << best_pos.first << \" \" << best_pos.second << \"\\n\";\n        container_at.erase(best_pos);\n    }\n    \n    cout.flush();\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, m;\nint original[50][50];\nint current[50][50];\n\nvector<pair<int,int>> dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};\n\nbool isValid(int i, int j) {\n    return i >= 0 && i < N && j >= 0 && j < N;\n}\n\nbool isConnected(int color) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int,int>> q;\n    int count = 0;\n    pair<int,int> start = {-1, -1};\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(current[i][j] == color) {\n                count++;\n                if(start.first == -1) start = {i, j};\n            }\n        }\n    }\n    \n    if(count == 0) return true;\n    \n    q.push(start);\n    visited[start.first][start.second] = true;\n    int visited_count = 1;\n    \n    while(!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for(auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if(isValid(ni, nj) && !visited[ni][nj] && current[ni][nj] == color) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                visited_count++;\n            }\n        }\n    }\n    \n    return visited_count == count;\n}\n\nbool isConnected0() {\n    int count0 = 0;\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(current[i][j] == 0) count0++;\n        }\n    }\n    \n    if(count0 == 0) return true;\n    \n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int,int>> q;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if((i == 0 || i == N-1 || j == 0 || j == N-1) && current[i][j] == 0) {\n                q.push({i, j});\n                visited[i][j] = true;\n            }\n        }\n    }\n    \n    int visited_count = q.size();\n    \n    while(!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for(auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if(isValid(ni, nj) && !visited[ni][nj] && current[ni][nj] == 0) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                visited_count++;\n            }\n        }\n    }\n    \n    return visited_count == count0;\n}\n\nset<pair<int,int>> getAdjacencies() {\n    set<pair<int,int>> adj;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            for(auto [di, dj] : dirs) {\n                int ni = i + di, nj = j + dj;\n                if(isValid(ni, nj)) {\n                    int c1 = current[i][j], c2 = current[ni][nj];\n                    if(c1 != c2) {\n                        adj.insert({min(c1, c2), max(c1, c2)});\n                    }\n                }\n            }\n        }\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if((i == 0 || i == N-1 || j == 0 || j == N-1) && current[i][j] != 0) {\n                adj.insert({0, current[i][j]});\n            }\n        }\n    }\n    \n    return adj;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> m;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            cin >> original[i][j];\n            current[i][j] = original[i][j];\n        }\n    }\n    \n    auto orig_adj = getAdjacencies();\n    \n    bool improved = true;\n    \n    while(improved) {\n        improved = false;\n        \n        for(int i = 0; i < N; i++) {\n            for(int j = 0; j < N; j++) {\n                if(current[i][j] == 0) continue;\n                \n                int color = current[i][j];\n                \n                int color_count = 0;\n                for(int ii = 0; ii < N; ii++) {\n                    for(int jj = 0; jj < N; jj++) {\n                        if(current[ii][jj] == color) color_count++;\n                    }\n                }\n                if(color_count == 1) continue;\n                \n                bool is_boundary = (i == 0 || i == N-1 || j == 0 || j == N-1);\n                if(is_boundary) {\n                    int boundary_count = 0;\n                    for(int ii = 0; ii < N; ii++) {\n                        for(int jj = 0; jj < N; jj++) {\n                            if((ii == 0 || ii == N-1 || jj == 0 || jj == N-1) && current[ii][jj] == color) {\n                                boundary_count++;\n                            }\n                        }\n                    }\n                    if(boundary_count == 1) continue;\n                }\n                \n                current[i][j] = 0;\n                \n                if(isConnected(color) && isConnected0() && getAdjacencies() == orig_adj) {\n                    improved = true;\n                } else {\n                    current[i][j] = color;\n                }\n            }\n        }\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(j > 0) cout << \" \";\n            cout << current[i][j];\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, D, Q;\n    cin >> N >> D >> Q;\n    \n    vector<vector<int>> cmp(N, vector<int>(N, -2)); // -2 = unknown\n    for(int i = 0; i < N; i++) cmp[i][i] = 0;\n    \n    // Generate all unique pairs\n    vector<pair<int,int>> pairs;\n    for(int i = 0; i < N; i++){\n        for(int j = i+1; j < N; j++){\n            pairs.push_back({i, j});\n        }\n    }\n    \n    // Shuffle for variety\n    shuffle(pairs.begin(), pairs.end(), mt19937(0));\n    \n    // Perform Q queries\n    for(int q = 0; q < Q; q++){\n        int idx = q % (int)pairs.size();\n        int i = pairs[idx].first;\n        int j = pairs[idx].second;\n        \n        cout << \"1 1 \" << i << \" \" << j << \"\\n\";\n        cout.flush();\n        \n        string result;\n        cin >> result;\n        \n        if(result == \"<\"){\n            cmp[i][j] = -1;\n            cmp[j][i] = 1;\n        } else if(result == \">\"){\n            cmp[i][j] = 1;\n            cmp[j][i] = -1;\n        } else {\n            cmp[i][j] = 0;\n            cmp[j][i] = 0;\n        }\n    }\n    \n    // Estimate weights: count comparison wins and losses\n    vector<double> weight(N, 0.0);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(cmp[i][j] == 1) weight[i] += 1.0;\n            else if(cmp[i][j] == -1) weight[i] -= 1.0;\n        }\n    }\n    \n    // Greedy partition: assign items to lightest set\n    vector<int> division(N);\n    vector<double> setWeight(D, 0.0);\n    \n    // Sort items by weight (descending)\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b){\n        return weight[a] > weight[b];\n    });\n    \n    // Assign each item to the set with minimum current weight\n    for(int item : order){\n        int best = 0;\n        for(int d = 1; d < D; d++){\n            if(setWeight[d] < setWeight[best]) best = d;\n        }\n        division[item] = best;\n        setWeight[best] += weight[item];\n    }\n    \n    // Output division\n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << division[i];\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n  ios_base::sync_with_stdio(false);\n  cin.tie(nullptr);\n  \n  int n, m;\n  cin >> n >> m;\n  \n  vector<vector<int>> stacks(m);\n  \n  for(int i = 0; i < m; i++){\n    int s = n / m;\n    for(int j = 0; j < s; j++){\n      int x;\n      cin >> x;\n      stacks[i].push_back(x);\n    }\n  }\n  \n  vector<pair<int,int>> operations;\n  \n  for(int box = 1; box <= n; box++){\n    // Find which stack contains this box\n    int src_stack = -1;\n    \n    for(int i = 0; i < m; i++){\n      for(int j = 0; j < (int)stacks[i].size(); j++){\n        if(stacks[i][j] == box){\n          src_stack = i;\n          break;\n        }\n      }\n      if(src_stack != -1) break;\n    }\n    \n    // Move all boxes above this box away\n    while(stacks[src_stack].back() != box){\n      int top_box = stacks[src_stack].back();\n      \n      // Find destination stack with minimum size (excluding source)\n      int dest_stack = -1;\n      int min_size = INT_MAX;\n      \n      for(int i = 0; i < m; i++){\n        if(i == src_stack) continue;\n        if((int)stacks[i].size() < min_size){\n          min_size = stacks[i].size();\n          dest_stack = i;\n        }\n      }\n      \n      // Move the top box to destination\n      stacks[dest_stack].push_back(top_box);\n      stacks[src_stack].pop_back();\n      \n      operations.push_back({top_box, dest_stack + 1});\n    }\n    \n    // Now box is at the top - extract it\n    operations.push_back({box, 0});\n    stacks[src_stack].pop_back();\n  }\n  \n  for(auto [v, i] : operations){\n    cout << v << \" \" << i << \"\\n\";\n  }\n  \n  return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\nvector<vector<bool>> visited;\nstring result;\n\nint di[] = {0, 1, 0, -1};\nint dj[] = {1, 0, -1, 0};\nchar dir_char[] = {'R', 'D', 'L', 'U'};\n\nvoid dfs(int i, int j) {\n    visited[i][j] = true;\n    \n    vector<pair<int, int>> moves; // (direction, d_value of neighbor)\n    \n    for (int dir = 0; dir < 4; dir++) {\n        int ni = i + di[dir];\n        int nj = j + dj[dir];\n        \n        if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj]) {\n            bool canMove = false;\n            if (dir == 0) canMove = (v[i][j] == '0');           // Right\n            else if (dir == 1) canMove = (h[i][j] == '0');      // Down\n            else if (dir == 2) canMove = (v[i][nj] == '0');     // Left\n            else canMove = (h[ni][j] == '0');                   // Up\n            \n            if (canMove) {\n                moves.push_back({dir, d[ni][nj]});\n            }\n        }\n    }\n    \n    // Sort by d_value descending (visit high-susceptibility areas first)\n    sort(moves.begin(), moves.end(), \n         [](const pair<int,int> &a, const pair<int,int> &b) { \n             return a.second > b.second; \n         });\n    \n    for (const auto &[dir, _] : moves) {\n        int ni = i + di[dir];\n        int nj = j + dj[dir];\n        \n        result += dir_char[dir];\n        dfs(ni, nj);\n        result += dir_char[(dir + 2) % 4];  // Opposite direction\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    \n    h.resize(N-1);\n    v.resize(N);\n    d.resize(N, vector<int>(N));\n    visited.assign(N, vector<bool>(N, false));\n    \n    for (int i = 0; i < N-1; i++) cin >> h[i];\n    for (int i = 0; i < N; i++) cin >> v[i];\n    \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    dfs(0, 0);\n    cout << result << endl;\n    \n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nint si, sj;\nvector<string> grid;\nvector<string> words;\nmap<char, vector<pair<int, int>>> charPos;\n\nint getOverlap(const string& a, const string& b) {\n    int maxOverlap = 0;\n    for (int o = 1; o <= min((int)a.size(), (int)b.size()); o++) {\n        if (a.substr(a.size() - o) == b.substr(0, o)) {\n            maxOverlap = o;\n        }\n    }\n    return maxOverlap;\n}\n\nstring buildSuperstring(const vector<int>& order) {\n    string result = words[order[0]];\n    for (int i = 1; i < (int)order.size(); i++) {\n        string& word = words[order[i]];\n        int overlap = getOverlap(words[order[i-1]], word);\n        result += word.substr(overlap);\n    }\n    return result;\n}\n\nlong long calculateCost(const string& superstring) {\n    long long cost = 0;\n    int ci = si, cj = sj;\n    \n    for (int pos = 0; pos < (int)superstring.size(); pos++) {\n        char c = superstring[pos];\n        \n        int bestI = -1, bestJ = -1;\n        long long minCost = LLONG_MAX;\n        \n        for (auto [ii, jj] : charPos[c]) {\n            long long moveCost = abs(ii - ci) + abs(jj - cj) + 1;\n            \n            // Lookahead: prefer positions close to next character\n            long long lookCost = 0;\n            if (pos + 1 < (int)superstring.size()) {\n                char next = superstring[pos + 1];\n                int nextMinDist = INT_MAX;\n                for (auto [ni, nj] : charPos[next]) {\n                    nextMinDist = min(nextMinDist, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost = nextMinDist;\n            }\n            \n            long long totalCost = moveCost + lookCost * 0.1;\n            if (totalCost < minCost) {\n                minCost = totalCost;\n                bestI = ii;\n                bestJ = jj;\n            }\n        }\n        \n        cost += abs(bestI - ci) + abs(bestJ - cj) + 1;\n        ci = bestI;\n        cj = bestJ;\n    }\n    return cost;\n}\n\nvector<int> greedyOrder(int startWord) {\n    vector<int> order;\n    set<int> used;\n    order.push_back(startWord);\n    used.insert(startWord);\n    \n    while ((int)used.size() < M) {\n        int lastWord = order.back();\n        int bestWord = -1;\n        int bestOverlap = -1;\n        \n        for (int w = 0; w < M; w++) {\n            if (used.count(w)) continue;\n            int ov = getOverlap(words[lastWord], words[w]);\n            if (ov > bestOverlap) {\n                bestOverlap = ov;\n                bestWord = w;\n            }\n        }\n        \n        if (bestWord == -1) {\n            for (int w = 0; w < M; w++) {\n                if (!used.count(w)) {\n                    bestWord = w;\n                    break;\n                }\n            }\n        }\n        \n        if (bestWord != -1) {\n            order.push_back(bestWord);\n            used.insert(bestWord);\n        }\n    }\n    return order;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    cin >> si >> sj;\n    \n    grid.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    \n    words.resize(M);\n    for (int i = 0; i < M; i++) {\n        cin >> words[i];\n    }\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            charPos[grid[i][j]].push_back({i, j});\n        }\n    }\n    \n    // Find best ordering by trying all starting points\n    string bestSuperstring;\n    long long bestCost = LLONG_MAX;\n    \n    for (int start = 0; start < M; start++) {\n        auto order = greedyOrder(start);\n        auto superstring = buildSuperstring(order);\n        auto cost = calculateCost(superstring);\n        if (cost < bestCost) {\n            bestCost = cost;\n            bestSuperstring = superstring;\n        }\n    }\n    \n    // Generate output with smart character selection\n    vector<pair<int, int>> operations;\n    int ci = si, cj = sj;\n    \n    for (int pos = 0; pos < (int)bestSuperstring.size(); pos++) {\n        char c = bestSuperstring[pos];\n        \n        int bestI = -1, bestJ = -1;\n        long long minCost = LLONG_MAX;\n        \n        for (auto [ii, jj] : charPos[c]) {\n            long long moveCost = abs(ii - ci) + abs(jj - cj);\n            \n            long long lookCost = 0;\n            if (pos + 1 < (int)bestSuperstring.size()) {\n                char next = bestSuperstring[pos + 1];\n                int nextMinDist = INT_MAX;\n                for (auto [ni, nj] : charPos[next]) {\n                    nextMinDist = min(nextMinDist, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost = nextMinDist;\n            }\n            \n            long long totalCost = moveCost + lookCost * 0.1;\n            if (totalCost < minCost) {\n                minCost = totalCost;\n                bestI = ii;\n                bestJ = jj;\n            }\n        }\n        \n        operations.push_back({bestI, bestJ});\n        ci = bestI;\n        cj = bestJ;\n    }\n    \n    for (auto [i, j] : operations) {\n        cout << i << \" \" << j << \"\\n\";\n    }\n    \n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n    \n    // Read field shapes\n    vector<vector<pair<int, int>>> fields(M);\n    for (int k = 0; k < M; k++) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < d; i++) {\n            int r, c;\n            cin >> r >> c;\n            fields[k].push_back({r, c});\n        }\n    }\n    \n    // Drill all squares to identify which have oil reserves\n    vector<pair<int, int>> oil_squares;\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            // Drill this square\n            cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n            cout.flush();\n            \n            int oil_value;\n            cin >> oil_value;\n            \n            // Record if this square has oil\n            if (oil_value > 0) {\n                oil_squares.push_back({i, j});\n            }\n        }\n    }\n    \n    // Output answer: all squares with v(i,j) > 0\n    cout << \"a \" << oil_squares.size();\n    for (auto [i, j] : oil_squares) {\n        cout << \" \" << i << \" \" << j;\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    // Read verification result\n    int is_correct;\n    cin >> is_correct;\n    \n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<long long>> a(D, vector<long long>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    // Allocate N vertical strips of equal width\n    // Each strip k spans from column k*W/N to (k+1)*W/N\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            long long j0 = (long long)k * W / N;\n            long long j1 = (long long)(k + 1) * W / N;\n            long long width = j1 - j0;\n            \n            long long needed = a[d][k];\n            // Calculate minimum height to meet area requirement\n            long long height = (needed + width - 1) / width;  // Ceiling division\n            height = min(height, (long long)W);  // Cap at grid height\n            \n            cout << 0 << \" \" << j0 << \" \" << height << \" \" << j1 << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long MOD = 998244353;\n\nint N, M, K;\nvector<vector<vector<long long>>> stamps;\n\nlong long calculate_score(const vector<vector<long long>>& board) {\n    long long score = 0;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            score += board[i][j] % MOD;\n        }\n    }\n    return score;\n}\n\nlong long delta_score(const vector<vector<long long>>& board, int m, int p, int q) {\n    long long delta = 0;\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            int ni = p + i, nj = q + j;\n            long long old_mod = board[ni][nj] % MOD;\n            long long new_mod = (board[ni][nj] + stamps[m][i][j]) % MOD;\n            delta += new_mod - old_mod;\n        }\n    }\n    return delta;\n}\n\nvoid apply_operation(vector<vector<long long>>& board, int m, int p, int q) {\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            board[p+i][q+j] += stamps[m][i][j];\n        }\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    \n    vector<vector<long long>> initial_board(N, vector<long long>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> initial_board[i][j];\n        }\n    }\n    \n    stamps.assign(M, vector<vector<long long>>(3, vector<long long>(3)));\n    vector<long long> stamp_sums(M, 0);\n    \n    for(int m = 0; m < M; m++){\n        for(int i = 0; i < 3; i++){\n            for(int j = 0; j < 3; j++){\n                cin >> stamps[m][i][j];\n                stamp_sums[m] += stamps[m][i][j];\n            }\n        }\n    }\n    \n    vector<tuple<int, int, int>> best_operations;\n    long long best_score = calculate_score(initial_board);\n    \n    mt19937 rng(42);\n    \n    for(int trial = 0; trial < 20; trial++){\n        auto board = initial_board;\n        vector<tuple<int, int, int>> operations;\n        \n        // Random initialization (skip for first trial - pure greedy)\n        if(trial > 0){\n            int num_random = min(trial, K / 3);\n            \n            for(int i = 0; i < num_random; i++){\n                // Probabilistically choose better stamps\n                int m;\n                if(trial > 10 && rng() % 2 == 0){\n                    m = max_element(stamp_sums.begin(), stamp_sums.end()) - stamp_sums.begin();\n                } else {\n                    m = rng() % M;\n                }\n                int p = rng() % (N - 2);\n                int q = rng() % (N - 2);\n                apply_operation(board, m, p, q);\n                operations.push_back({m, p, q});\n            }\n        }\n        \n        // Greedy phase\n        for(int op = operations.size(); op < K; op++){\n            long long best_delta = 0;\n            int best_m = -1, best_p = -1, best_q = -1;\n            \n            for(int m = 0; m < M; m++){\n                for(int p = 0; p <= N - 3; p++){\n                    for(int q = 0; q <= N - 3; q++){\n                        long long d = delta_score(board, m, p, q);\n                        if(d > best_delta){\n                            best_delta = d;\n                            best_m = m;\n                            best_p = p;\n                            best_q = q;\n                        }\n                    }\n                }\n            }\n            \n            if(best_m == -1) break;\n            \n            apply_operation(board, best_m, best_p, best_q);\n            operations.push_back({best_m, best_p, best_q});\n        }\n        \n        long long score = calculate_score(board);\n        if(score > best_score){\n            best_score = score;\n            best_operations = operations;\n        }\n    }\n    \n    cout << best_operations.size() << \"\\n\";\n    for(auto [m, p, q] : best_operations){\n        cout << m << \" \" << p << \" \" << q << \"\\n\";\n    }\n    \n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<vector<int>> grid;\nvector<pair<int,int>> pos;\nvector<int> carry;\nvector<int> active;\n\nint main(){\n    cin >> N;\n    \n    vector<vector<int>> A(N, vector<int>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> A[i][j];\n        }\n    }\n    \n    grid.assign(N, vector<int>(N, -1));\n    pos.resize(N);\n    carry.assign(N, -1);\n    active.assign(N, 1);\n    \n    for(int i = 0; i < N; i++) pos[i] = {i, 0};\n    \n    vector<int> next_in(N, 0);\n    vector<string> res(N, \"\");\n    \n    for(int t = 0; t < 10000; t++){\n        // Step 1: Place arriving containers\n        for(int i = 0; i < N; i++){\n            if(next_in[i] < N && grid[i][0] == -1){\n                bool blocked = false;\n                for(int k = 0; k < N; k++){\n                    if(active[k] && pos[k].first == i && pos[k].second == 0 && carry[k] != -1){\n                        blocked = true;\n                    }\n                }\n                if(!blocked){\n                    grid[i][0] = A[i][next_in[i]];\n                    next_in[i]++;\n                }\n            }\n        }\n        \n        // Step 2: Cranes perform actions\n        vector<char> act(N);\n        vector<pair<int,int>> new_pos(N);\n        \n        // Decide actions for each crane\n        for(int k = 0; k < N; k++){\n            if(!active[k]){\n                act[k] = '.';\n                new_pos[k] = pos[k];\n                continue;\n            }\n            \n            auto [r, c] = pos[k];\n            \n            if(carry[k] >= 0){\n                // Carrying container - move to dispatch gate\n                int tr = carry[k] / N;\n                int tc = N - 1;\n                \n                if(r == tr && c == tc){\n                    act[k] = 'Q';\n                    new_pos[k] = {r, c};\n                } else if(c < tc){\n                    act[k] = 'R';\n                    new_pos[k] = {r, c+1};\n                } else if(r < tr){\n                    act[k] = 'D';\n                    new_pos[k] = {r+1, c};\n                } else {\n                    act[k] = 'U';\n                    new_pos[k] = {r-1, c};\n                }\n            } else {\n                // Try to pick or move left\n                if(grid[r][c] >= 0){\n                    act[k] = 'P';\n                    new_pos[k] = {r, c};\n                } else if(c > 0){\n                    act[k] = 'L';\n                    new_pos[k] = {r, c-1};\n                } else {\n                    act[k] = '.';\n                    new_pos[k] = {r, c};\n                }\n            }\n        }\n        \n        // Validate movements iteratively\n        bool changed = true;\n        while(changed){\n            changed = false;\n            \n            // Check mutual collision (two cranes to same destination)\n            map<pair<int,int>, vector<int>> dests;\n            for(int k = 0; k < N; k++){\n                if(active[k] && act[k] != 'P' && act[k] != 'Q' && act[k] != '.'){\n                    dests[new_pos[k]].push_back(k);\n                }\n            }\n            \n            for(auto& [d, cranes] : dests){\n                if(cranes.size() > 1){\n                    for(int k : cranes){\n                        act[k] = '.';\n                        new_pos[k] = pos[k];\n                        changed = true;\n                    }\n                }\n            }\n            \n            // Check swaps (two cranes exchanging positions)\n            for(int k = 0; k < N; k++){\n                if(!active[k] || (act[k] == 'P' || act[k] == 'Q' || act[k] == '.')) continue;\n                for(int m = k+1; m < N; m++){\n                    if(!active[m] || (act[m] == 'P' || act[m] == 'Q' || act[m] == '.')) continue;\n                    if(new_pos[k] == pos[m] && new_pos[m] == pos[k]){\n                        act[k] = '.';\n                        act[m] = '.';\n                        new_pos[k] = pos[k];\n                        new_pos[m] = pos[m];\n                        changed = true;\n                    }\n                }\n            }\n            \n            // Check blocking (moving to square with stationary crane)\n            for(int k = 0; k < N; k++){\n                if(!active[k] || (act[k] == 'P' || act[k] == 'Q' || act[k] == '.')) continue;\n                for(int m = 0; m < N; m++){\n                    if(!active[m] || m == k) continue;\n                    if(act[m] == 'P' || act[m] == 'Q' || act[m] == '.'){\n                        if(new_pos[k] == pos[m]){\n                            act[k] = '.';\n                            new_pos[k] = pos[k];\n                            changed = true;\n                        }\n                    }\n                }\n            }\n            \n            // Check small crane constraint\n            for(int k = 1; k < N; k++){\n                if(!active[k] || carry[k] == -1) continue;\n                if(act[k] != 'P' && act[k] != 'Q' && act[k] != '.'){\n                    if(grid[new_pos[k].first][new_pos[k].second] >= 0){\n                        act[k] = '.';\n                        new_pos[k] = pos[k];\n                        changed = true;\n                    }\n                }\n            }\n        }\n        \n        // Apply P actions\n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] == 'P'){\n                if(carry[k] == -1 && grid[pos[k].first][pos[k].second] >= 0){\n                    carry[k] = grid[pos[k].first][pos[k].second];\n                    grid[pos[k].first][pos[k].second] = -1;\n                } else {\n                    act[k] = '.';\n                }\n            }\n        }\n        \n        // Apply movements\n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] != 'P' && act[k] != 'Q' && act[k] != '.' && act[k] != 'B'){\n                pos[k] = new_pos[k];\n            }\n        }\n        \n        // Apply Q actions\n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] == 'Q'){\n                if(carry[k] >= 0 && grid[pos[k].first][pos[k].second] == -1){\n                    grid[pos[k].first][pos[k].second] = carry[k];\n                    carry[k] = -1;\n                } else {\n                    act[k] = '.';\n                }\n            }\n        }\n        \n        // Apply B actions\n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] == 'B'){\n                if(carry[k] == -1){\n                    active[k] = 0;\n                } else {\n                    act[k] = '.';\n                }\n            }\n        }\n        \n        for(int k = 0; k < N; k++) res[k] += act[k];\n        \n        // Step 3: Dispatch\n        for(int i = 0; i < N; i++){\n            if(grid[i][N-1] >= 0) grid[i][N-1] = -1;\n        }\n    }\n    \n    for(int i = 0; i < N; i++){\n        cout << res[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    \n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h[i][j];\n        }\n    }\n    \n    vector<string> operations;\n    int x = 0, y = 0;\n    int load = 0;\n    \n    auto move_to = [&](int nx, int ny) {\n        while (x != nx) {\n            if (x < nx) {\n                operations.push_back(\"D\");\n                x++;\n            } else {\n                operations.push_back(\"U\");\n                x--;\n            }\n        }\n        while (y != ny) {\n            if (y < ny) {\n                operations.push_back(\"R\");\n                y++;\n            } else {\n                operations.push_back(\"L\");\n                y--;\n            }\n        }\n    };\n    \n    // Phase 1: Collect all positive soil using snake pattern\n    for (int i = 0; i < N; i++) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; j++) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    operations.push_back(\"+\" + to_string(h[i][j]));\n                    load += h[i][j];\n                }\n            }\n        } else {\n            for (int j = N - 1; j >= 0; j--) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    operations.push_back(\"+\" + to_string(h[i][j]));\n                    load += h[i][j];\n                }\n            }\n        }\n    }\n    \n    // Phase 2: Distribute to negative cells using same snake pattern\n    for (int i = 0; i < N; i++) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; j++) {\n                move_to(i, j);\n                if (h[i][j] < 0) {\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                    }\n                }\n            }\n        } else {\n            for (int j = N - 1; j >= 0; j--) {\n                move_to(i, j);\n                if (h[i][j] < 0) {\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                    }\n                }\n            }\n        }\n    }\n    \n    for (const auto& op : operations) {\n        cout << op << \"\\n\";\n    }\n    \n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> X(seed_count, vector<int>(M));\n\n    // Read initial seeds\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> X[i][j];\n        }\n    }\n\n    // Precompute grid positions ordered by neighbor count (interior first)\n    vector<pair<int, int>> position_order;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            position_order.push_back({i, j});\n        }\n    }\n    \n    sort(position_order.begin(), position_order.end(), [&](const auto& a, const auto& b) {\n        auto neighbor_count = [&](const pair<int,int>& p) {\n            return (p.first > 0) + (p.first < N-1) + (p.second > 0) + (p.second < N-1);\n        };\n        return neighbor_count(a) > neighbor_count(b);\n    });\n\n    // Perform T operations\n    for (int t = 0; t < T; t++) {\n        // Calculate total value and per-criterion max for each seed\n        vector<long long> values(seed_count, 0);\n        vector<int> max_criterion(seed_count, -1);\n        \n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                values[i] += X[i][j];\n                if (max_criterion[i] == -1 || X[i][j] > X[i][max_criterion[i]]) {\n                    max_criterion[i] = j;\n                }\n            }\n        }\n        \n        // Select seeds: prioritize high total value, with criterion diversity\n        vector<bool> selected_mask(seed_count, false);\n        vector<int> selected_seeds;\n        \n        // First, for each criterion, reserve a seed that excels in it\n        vector<int> criterion_best(M, -1);\n        for (int crit = 0; crit < M; crit++) {\n            int best_seed = -1;\n            int best_value = -1;\n            for (int i = 0; i < seed_count; i++) {\n                if (X[i][crit] > best_value) {\n                    best_value = X[i][crit];\n                    best_seed = i;\n                }\n            }\n            if (best_seed != -1 && !selected_mask[best_seed] && selected_seeds.size() < N * N) {\n                selected_mask[best_seed] = true;\n                selected_seeds.push_back(best_seed);\n                criterion_best[crit] = best_seed;\n            }\n        }\n        \n        // Then fill remaining slots with highest total-value seeds\n        vector<int> sorted_by_value(seed_count);\n        iota(sorted_by_value.begin(), sorted_by_value.end(), 0);\n        sort(sorted_by_value.begin(), sorted_by_value.end(), [&](int a, int b) {\n            return values[a] > values[b];\n        });\n        \n        for (int seed_id : sorted_by_value) {\n            if (selected_seeds.size() >= (size_t)(N * N)) break;\n            if (!selected_mask[seed_id]) {\n                selected_mask[seed_id] = true;\n                selected_seeds.push_back(seed_id);\n            }\n        }\n\n        // Assign seeds to grid positions (high-value seeds go to high-neighbor positions)\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (size_t idx = 0; idx < selected_seeds.size(); idx++) {\n            int seed_id = selected_seeds[idx];\n            int pos_i = position_order[idx].first;\n            int pos_j = position_order[idx].second;\n            grid[pos_i][pos_j] = seed_id;\n        }\n\n        // Output grid\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (j > 0) cout << \" \";\n                cout << grid[i][j];\n            }\n            cout << \"\\n\";\n        }\n        cout.flush();\n\n        // Read new generation seeds\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> X[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, V;\n    cin >> N >> M >> V;\n    \n    vector<string> s(N), t(N);\n    for(int i = 0; i < N; i++) cin >> s[i];\n    for(int i = 0; i < N; i++) cin >> t[i];\n    \n    vector<pair<int,int>> src, dst;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(s[i][j] == '1') src.push_back({i, j});\n            if(t[i][j] == '1') dst.push_back({i, j});\n        }\n    }\n    \n    cout << \"2\\n\";\n    cout << \"0 1\\n\";\n    cout << \"0 0\\n\";\n    \n    int rx = 0, ry = 0;\n    int rot = 0; // 0=right, 1=down, 2=left, 3=up\n    int turns = 0;\n    \n    auto get_finger = [&]() -> pair<int,int> {\n        if(rot == 0) return {rx, ry + 1};\n        if(rot == 1) return {rx + 1, ry};\n        if(rot == 2) return {rx, ry - 1};\n        return {rx - 1, ry};\n    };\n    \n    auto can_reach = [&](int sx, int sy, int r) -> bool {\n        int target_rx = sx, target_ry = sy;\n        if(r == 0) target_ry--;\n        else if(r == 1) target_rx--;\n        else if(r == 2) target_ry++;\n        else target_rx++;\n        return target_rx >= 0 && target_rx < N && target_ry >= 0 && target_ry < N;\n    };\n    \n    for(int i = 0; i < M && turns < 100000; i++){\n        auto [sx, sy] = src[i];\n        auto [tx, ty] = dst[i];\n        \n        // Find and move to source\n        int best_rot = rot;\n        for(int r = 0; r < 4; r++){\n            if(can_reach(sx, sy, r)){\n                best_rot = r;\n                break;\n            }\n        }\n        \n        while(rot != best_rot && turns < 100000){\n            string op = \"....\";\n            op[1] = ((best_rot - rot + 4) % 4 == 1) ? 'L' : 'R';\n            rot = ((best_rot - rot + 4) % 4 == 1) ? (rot + 3) % 4 : (rot + 1) % 4;\n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        while(turns < 100000){\n            auto [fx, fy] = get_finger();\n            if(fx == sx && fy == sy) break;\n            \n            string op = \"....\";\n            int target_rx = sx, target_ry = sy;\n            if(rot == 0) target_ry--;\n            else if(rot == 1) target_rx--;\n            else if(rot == 2) target_ry++;\n            else target_rx++;\n            \n            if(rx < target_rx) { rx++; op[0] = 'D'; }\n            else if(rx > target_rx) { rx--; op[0] = 'U'; }\n            else if(ry < target_ry) { ry++; op[0] = 'R'; }\n            else if(ry > target_ry) { ry--; op[0] = 'L'; }\n            \n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        if(turns >= 100000) break;\n        cout << \"..P\\n\";\n        turns++;\n        \n        // Find and move to target\n        best_rot = rot;\n        for(int r = 0; r < 4; r++){\n            if(can_reach(tx, ty, r)){\n                best_rot = r;\n                break;\n            }\n        }\n        \n        while(rot != best_rot && turns < 100000){\n            string op = \"....\";\n            op[1] = ((best_rot - rot + 4) % 4 == 1) ? 'L' : 'R';\n            rot = ((best_rot - rot + 4) % 4 == 1) ? (rot + 3) % 4 : (rot + 1) % 4;\n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        while(turns < 100000){\n            auto [fx, fy] = get_finger();\n            if(fx == tx && fy == ty) break;\n            \n            string op = \"....\";\n            int target_rx = tx, target_ry = ty;\n            if(rot == 0) target_ry--;\n            else if(rot == 1) target_rx--;\n            else if(rot == 2) target_ry++;\n            else target_rx++;\n            \n            if(rx < target_rx) { rx++; op[0] = 'D'; }\n            else if(rx > target_rx) { rx--; op[0] = 'U'; }\n            else if(ry < target_ry) { ry++; op[0] = 'R'; }\n            else if(ry > target_ry) { ry--; op[0] = 'L'; }\n            \n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        if(turns >= 100000) break;\n        cout << \"..P\\n\";\n        turns++;\n    }\n    \n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    \n    vector<pair<int, int>> mackerel(N), sardine(N);\n    \n    for(int i = 0; i < N; i++){\n        cin >> mackerel[i].first >> mackerel[i].second;\n    }\n    \n    for(int i = 0; i < N; i++){\n        cin >> sardine[i].first >> sardine[i].second;\n    }\n    \n    auto count_in_rect = [](const vector<pair<int, int>>& pts, int x1, int y1, int x2, int y2) {\n        int count = 0;\n        for(auto [x, y] : pts) {\n            if(x >= x1 && x <= x2 && y >= y1 && y <= y2) {\n                count++;\n            }\n        }\n        return count;\n    };\n    \n    auto score_rect = [&](int x1, int y1, int x2, int y2) {\n        int m = count_in_rect(mackerel, x1, y1, x2, y2);\n        int s = count_in_rect(sardine, x1, y1, x2, y2);\n        return max(0, m - s + 1);\n    };\n    \n    // Find bounding box of all mackerels\n    int minX = INT_MAX, maxX = INT_MIN;\n    int minY = INT_MAX, maxY = INT_MIN;\n    \n    for(auto [x, y] : mackerel){\n        minX = min(minX, x);\n        maxX = max(maxX, x);\n        minY = min(minY, y);\n        maxY = max(maxY, y);\n    }\n    \n    int bestX1 = minX, bestY1 = minY, bestX2 = maxX, bestY2 = maxY;\n    int bestScore = score_rect(bestX1, bestY1, bestX2, bestY2);\n    \n    // Iterative local search with progressively finer granularity\n    for(int phase = 0; phase < 5; phase++) {\n        bool improved = true;\n        \n        while(improved) {\n            improved = false;\n            \n            int dx = max(1, (bestX2 - bestX1) >> (5 - phase));\n            int dy = max(1, (bestY2 - bestY1) >> (5 - phase));\n            \n            // Try shrinking from left\n            for(int x = bestX1; x < bestX2; x += dx) {\n                int s = score_rect(x, bestY1, bestX2, bestY2);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestX1 = x;\n                    improved = true;\n                    break;\n                }\n            }\n            \n            // Try shrinking from right\n            for(int x = bestX2; x > bestX1; x -= dx) {\n                int s = score_rect(bestX1, bestY1, x, bestY2);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestX2 = x;\n                    improved = true;\n                    break;\n                }\n            }\n            \n            // Try shrinking from bottom\n            for(int y = bestY1; y < bestY2; y += dy) {\n                int s = score_rect(bestX1, y, bestX2, bestY2);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestY1 = y;\n                    improved = true;\n                    break;\n                }\n            }\n            \n            // Try shrinking from top\n            for(int y = bestY2; y > bestY1; y -= dy) {\n                int s = score_rect(bestX1, bestY1, bestX2, y);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestY2 = y;\n                    improved = true;\n                    break;\n                }\n            }\n        }\n    }\n    \n    cout << 4 << \"\\n\";\n    cout << bestX1 << \" \" << bestY1 << \"\\n\";\n    cout << bestX2 << \" \" << bestY1 << \"\\n\";\n    cout << bestX2 << \" \" << bestY2 << \"\\n\";\n    cout << bestX1 << \" \" << bestY2 << \"\\n\";\n    \n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, T;\n    long long sigma;\n    cin >> N >> T >> sigma;\n    \n    vector<pair<long long, long long>> rects(N);\n    for (int i = 0; i < N; i++) {\n        cin >> rects[i].first >> rects[i].second;\n    }\n    \n    mt19937 rng(12345);\n    \n    auto simulate = [&](const vector<tuple<int, int, char, int>>& placement) {\n        map<int, array<long long, 4>> pos;\n        long long max_x = 0, max_y = 0;\n        \n        for (auto [idx, rot, dir, ref] : placement) {\n            long long w = rects[idx].first;\n            long long h = rects[idx].second;\n            if (rot) swap(w, h);\n            \n            long long x = 0, y = 0;\n            \n            if (dir == 'U') {\n                if (ref != -1 && pos.count(ref)) {\n                    x = pos[ref][0] + pos[ref][2];\n                }\n                for (auto& [i, p] : pos) {\n                    if (p[0] < x + w && x < p[0] + p[2]) {\n                        y = max(y, p[1] + p[3]);\n                    }\n                }\n            } else { // 'L'\n                if (ref != -1 && pos.count(ref)) {\n                    y = pos[ref][1] + pos[ref][3];\n                }\n                for (auto& [i, p] : pos) {\n                    if (p[1] < y + h && y < p[1] + p[3]) {\n                        x = max(x, p[0] + p[2]);\n                    }\n                }\n            }\n            \n            pos[idx] = {x, y, w, h};\n            max_x = max(max_x, x + w);\n            max_y = max(max_y, y + h);\n        }\n        \n        return make_pair(max_x, max_y);\n    };\n    \n    auto start_time = chrono::high_resolution_clock::now();\n    \n    for (int t = 0; t < T; t++) {\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(\n            chrono::high_resolution_clock::now() - start_time).count();\n        \n        // Safety check: if we're running out of time, just output simple placement\n        if (elapsed > 2900) {\n            vector<tuple<int, int, char, int>> p;\n            for (int i = 0; i < N; i++) {\n                p.push_back({i, 0, 'U', -1});\n            }\n            cout << p.size() << \"\\n\";\n            for (auto [a, b, c, d] : p) {\n                cout << a << \" \" << b << \" \" << c << \" \" << d << \"\\n\";\n            }\n            cout.flush();\n            long long W, H;\n            cin >> W >> H;\n            break;\n        }\n        \n        vector<tuple<int, int, char, int>> best;\n        long long best_score = LLONG_MAX;\n        \n        // Reduce iterations: 20-25 attempts per turn\n        int max_attempts = 25;\n        \n        for (int att = 0; att < max_attempts; att++) {\n            vector<tuple<int, int, char, int>> placement;\n            \n            // Vary whether we use all rectangles or a subset\n            int use_count = N;\n            if (att >= 5 && att < 20) {\n                // Try smaller subsets\n                use_count = (N + 1) / 2 + rng() % ((N + 1) / 2);\n            }\n            \n            for (int i = 0; i < use_count; i++) {\n                int r = rng() % 2;\n                char d = (rng() % 2) ? 'U' : 'L';\n                int b = -1;\n                if (i > 0 && rng() % 2) {\n                    b = rng() % i;\n                }\n                placement.push_back({i, r, d, b});\n            }\n            \n            auto [w, h] = simulate(placement);\n            long long cost = w + h;\n            for (int i = use_count; i < N; i++) {\n                cost += rects[i].first + rects[i].second;\n            }\n            \n            if (cost < best_score) {\n                best_score = cost;\n                best = placement;\n            }\n        }\n        \n        cout << best.size() << \"\\n\";\n        for (auto [p, r, d, b] : best) {\n            cout << p << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        }\n        cout.flush();\n        \n        long long W, H;\n        cin >> W >> H;\n    }\n    \n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, H;\nvector<int> A;\nvector<vector<int>> adj;\n\nlong long evaluateSolution(const vector<int>& parent) {\n    vector<int> depth(N, -1);\n    long long score = 0;\n    \n    function<void(int)> dfs = [&](int u) {\n        score += (long long)(depth[u] + 1) * A[u];\n        for(int v : adj[u]){\n            if(parent[v] == u && depth[v] == -1){\n                depth[v] = depth[u] + 1;\n                dfs(v);\n            }\n        }\n    };\n    \n    for(int i = 0; i < N; i++){\n        if(parent[i] == -1){\n            depth[i] = 0;\n            dfs(i);\n        }\n    }\n    return score;\n}\n\nvector<int> buildTree(const vector<int>& rootOrder) {\n    vector<int> parent(N, -2);\n    \n    for(int root : rootOrder){\n        if(parent[root] != -2) continue;\n        \n        queue<int> q;\n        q.push(root);\n        parent[root] = -1;\n        vector<int> depth(N, -1);\n        depth[root] = 0;\n        \n        while(!q.empty()){\n            int u = q.front();\n            q.pop();\n            \n            if(depth[u] >= H) continue;\n            \n            // Collect unvisited neighbors and sort by beauty\n            vector<pair<int, int>> neighbors;\n            for(int v : adj[u]){\n                if(parent[v] == -2){\n                    neighbors.push_back({A[v], v});\n                }\n            }\n            \n            sort(neighbors.rbegin(), neighbors.rend());\n            \n            for(auto [_, v] : neighbors){\n                parent[v] = u;\n                depth[v] = depth[u] + 1;\n                q.push(v);\n            }\n        }\n    }\n    return parent;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int H_input;\n    cin >> N >> M >> H_input;\n    H = H_input;\n    \n    A.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> A[i];\n    }\n    \n    adj.resize(N);\n    for(int i = 0; i < M; i++){\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    vector<double> x(N), y(N);\n    for(int i = 0; i < N; i++){\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<int> best_parent(N);\n    long long best_score = -1;\n    \n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    \n    // Strategy 1: Sort by beauty descending\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return A[a] > A[b]; });\n        auto parent = buildTree(ord);\n        long long score = evaluateSolution(parent);\n        if(score > best_score){\n            best_score = score;\n            best_parent = parent;\n        }\n    }\n    \n    // Strategy 2: Sort by degree descending\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return adj[a].size() > adj[b].size(); });\n        auto parent = buildTree(ord);\n        long long score = evaluateSolution(parent);\n        if(score > best_score){\n            best_score = score;\n            best_parent = parent;\n        }\n    }\n    \n    // Strategy 3: Beauty * sqrt(degree)\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            return (double)A[a] * sqrt(1 + adj[a].size()) > (double)A[b] * sqrt(1 + adj[b].size());\n        });\n        auto parent = buildTree(ord);\n        long long score = evaluateSolution(parent);\n        if(score > best_score){\n            best_score = score;\n            best_parent = parent;\n        }\n    }\n    \n    // Strategy 4: Beauty / (degree+1)\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            return (double)A[a] / (1.0 + adj[a].size()) > (double)A[b] / (1.0 + adj[b].size());\n        });\n        auto parent = buildTree(ord);\n        long long score = evaluateSolution(parent);\n        if(score > best_score){\n            best_score = score;\n            best_parent = parent;\n        }\n    }\n    \n    // Strategy 5-7: Weighted combinations\n    for(double weight = 0.5; weight <= 1.5; weight += 0.5){\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double sa = A[a] + weight * adj[a].size();\n            double sb = A[b] + weight * adj[b].size();\n            return sa > sb;\n        });\n        auto parent = buildTree(ord);\n        long long score = evaluateSolution(parent);\n        if(score > best_score){\n            best_score = score;\n            best_parent = parent;\n        }\n    }\n    \n    // Random attempts with different seeds\n    mt19937 rng(42);\n    for(int attempt = 0; attempt < 40; attempt++){\n        auto ord = order;\n        shuffle(ord.begin(), ord.end(), rng);\n        auto parent = buildTree(ord);\n        long long score = evaluateSolution(parent);\n        if(score > best_score){\n            best_score = score;\n            best_parent = parent;\n        }\n    }\n    \n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << best_parent[i];\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int N;\n    cin >> N;\n    \n    vector<string> board(N);\n    for (int i = 0; i < N; i++) {\n        cin >> board[i];\n    }\n    \n    vector<pair<char, int>> operations;\n    \n    auto findOni = [&]() -> pair<int, int> {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (board[i][j] == 'x') return {i, j};\n            }\n        }\n        return {-1, -1};\n    };\n    \n    auto shiftUp = [&](int j) {\n        for (int i = 0; i < N - 1; i++) board[i][j] = board[i + 1][j];\n        board[N - 1][j] = '.';\n        operations.push_back({'U', j});\n    };\n    \n    auto shiftDown = [&](int j) {\n        for (int i = N - 1; i > 0; i--) board[i][j] = board[i - 1][j];\n        board[0][j] = '.';\n        operations.push_back({'D', j});\n    };\n    \n    auto shiftLeft = [&](int i) {\n        for (int j = 0; j < N - 1; j++) board[i][j] = board[i][j + 1];\n        board[i][N - 1] = '.';\n        operations.push_back({'L', i});\n    };\n    \n    auto shiftRight = [&](int i) {\n        for (int j = N - 1; j > 0; j--) board[i][j] = board[i][j - 1];\n        board[i][0] = '.';\n        operations.push_back({'R', i});\n    };\n    \n    while (true) {\n        auto [i, j] = findOni();\n        if (i == -1) break;\n        \n        // Check all four directions and pick the one with minimum cost\n        int minCost = INT_MAX;\n        int bestDir = -1; // 0=up, 1=down, 2=left, 3=right\n        \n        // Check upward direction\n        bool clearUp = true;\n        for (int k = 0; k < i; k++) {\n            if (board[k][j] == 'o') { clearUp = false; break; }\n        }\n        if (clearUp) {\n            int cost = 2 * (i + 1);\n            if (cost < minCost) { minCost = cost; bestDir = 0; }\n        }\n        \n        // Check downward direction\n        bool clearDown = true;\n        for (int k = i + 1; k < N; k++) {\n            if (board[k][j] == 'o') { clearDown = false; break; }\n        }\n        if (clearDown) {\n            int cost = 2 * (N - i);\n            if (cost < minCost) { minCost = cost; bestDir = 1; }\n        }\n        \n        // Check leftward direction\n        bool clearLeft = true;\n        for (int k = 0; k < j; k++) {\n            if (board[i][k] == 'o') { clearLeft = false; break; }\n        }\n        if (clearLeft) {\n            int cost = 2 * (j + 1);\n            if (cost < minCost) { minCost = cost; bestDir = 2; }\n        }\n        \n        // Check rightward direction\n        bool clearRight = true;\n        for (int k = j + 1; k < N; k++) {\n            if (board[i][k] == 'o') { clearRight = false; break; }\n        }\n        if (clearRight) {\n            int cost = 2 * (N - j);\n            if (cost < minCost) { minCost = cost; bestDir = 3; }\n        }\n        \n        // Apply the best direction (guaranteed to exist by problem statement)\n        if (bestDir == 0) {\n            for (int k = 0; k <= i; k++) shiftUp(j);\n            for (int k = 0; k <= i; k++) shiftDown(j);\n        } else if (bestDir == 1) {\n            for (int k = 0; k < N - i; k++) shiftDown(j);\n            for (int k = 0; k < N - i; k++) shiftUp(j);\n        } else if (bestDir == 2) {\n            for (int k = 0; k <= j; k++) shiftLeft(i);\n            for (int k = 0; k <= j; k++) shiftRight(i);\n        } else if (bestDir == 3) {\n            for (int k = 0; k < N - j; k++) shiftRight(i);\n            for (int k = 0; k < N - j; k++) shiftLeft(i);\n        }\n    }\n    \n    for (auto [d, p] : operations) {\n        cout << d << \" \" << p << \"\\n\";\n    }\n    \n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nlong long computeError(const vector<int>& a, const vector<int>& b, int N, int L, const vector<int>& T) {\n    vector<int> count(N, 0);\n    int current = 0;\n    count[0]++;\n    \n    for (int week = 1; week < L; week++) {\n        int next = (count[current] & 1) ? a[current] : b[current];\n        count[next]++;\n        current = next;\n    }\n    \n    long long error = 0;\n    for (int i = 0; i < N; i++) {\n        error += abs(count[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, L;\n    cin >> N >> L;\n    \n    vector<int> T(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n    \n    vector<int> best_a(N), best_b(N);\n    long long best_error = LLONG_MAX;\n    \n    mt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n    \n    for (int trial = 0; trial < 50; trial++) {\n        vector<int> a(N), b(N);\n        \n        if (trial == 0) {\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 1) % N;\n            }\n        } else if (trial == 1) {\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 2) % N;\n            }\n        } else if (trial == 2) {\n            for (int i = 0; i < N; i++) {\n                a[i] = (N - 1 - i + N) % N;\n                b[i] = (N - 2 - i + N) % N;\n            }\n        } else {\n            for (int i = 0; i < N; i++) {\n                a[i] = rng() % N;\n                b[i] = rng() % N;\n            }\n        }\n        \n        long long error = computeError(a, b, N, L, T);\n        \n        int no_improve = 0;\n        for (int iter = 0; iter < 2000 && no_improve < 300; iter++) {\n            int emp = rng() % N;\n            int param = rng() % 2;\n            int old_val = (param == 0) ? a[emp] : b[emp];\n            int new_val = rng() % N;\n            \n            if (param == 0) {\n                a[emp] = new_val;\n            } else {\n                b[emp] = new_val;\n            }\n            \n            long long new_error = computeError(a, b, N, L, T);\n            \n            if (new_error < error) {\n                error = new_error;\n                no_improve = 0;\n            } else {\n                if (param == 0) {\n                    a[emp] = old_val;\n                } else {\n                    b[emp] = old_val;\n                }\n                no_improve++;\n            }\n        }\n        \n        if (error < best_error) {\n            best_error = error;\n            best_a = a;\n            best_b = b;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    \n    vector<int> G(M);\n    for(int i = 0; i < M; i++){\n        cin >> G[i];\n    }\n    \n    vector<double> lx(N), rx(N), ly(N), ry(N);\n    for(int i = 0; i < N; i++){\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n    \n    // Estimate positions using rectangle centers\n    vector<pair<double,double>> pos(N);\n    double minx = 1e18, maxx = -1e18, miny = 1e18, maxy = -1e18;\n    for(int i = 0; i < N; i++){\n        pos[i] = {(lx[i] + rx[i]) / 2.0, (ly[i] + ry[i]) / 2.0};\n        minx = min(minx, pos[i].first);\n        maxx = max(maxx, pos[i].first);\n        miny = min(miny, pos[i].second);\n        maxy = max(maxy, pos[i].second);\n    }\n    \n    // Compute geometric center\n    double cx = (minx + maxx) / 2.0;\n    double cy = (miny + maxy) / 2.0;\n    \n    // Sort by polar angle from center (groups nearby cities angularly)\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int i, int j){\n        double angle_i = atan2(pos[i].second - cy, pos[i].first - cx);\n        double angle_j = atan2(pos[j].second - cy, pos[j].first - cx);\n        if(abs(angle_i - angle_j) > 1e-9) return angle_i < angle_j;\n        \n        // Secondary sort by distance from center\n        double dist_i = (pos[i].first - cx) * (pos[i].first - cx) + \n                       (pos[i].second - cy) * (pos[i].second - cy);\n        double dist_j = (pos[j].first - cx) * (pos[j].first - cx) + \n                       (pos[j].second - cy) * (pos[j].second - cy);\n        return dist_i < dist_j;\n    });\n    \n    // Partition into groups\n    vector<vector<int>> groups(M);\n    int idx = 0;\n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g]; i++){\n            groups[g].push_back(order[idx++]);\n        }\n    }\n    \n    // Query MST edges for each group using overlapping windows\n    vector<vector<pair<int,int>>> edges(M);\n    \n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g] - 1; i += 2){\n            if(i < G[g] - 2){\n                // Query 3 cities\n                cout << \"? 3 \" << groups[g][i] << \" \" << groups[g][i+1] << \" \" << groups[g][i+2] << \"\\n\";\n                cout.flush();\n                \n                // Read MST edges\n                for(int j = 0; j < 2; j++){\n                    int a, b;\n                    cin >> a >> b;\n                    edges[g].push_back({a, b});\n                }\n            } else {\n                // Direct edge for remaining cities\n                edges[g].push_back({groups[g][i], groups[g][i+1]});\n            }\n        }\n    }\n    \n    // Output final answer\n    cout << \"!\\n\";\n    cout.flush();\n    \n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g]; i++){\n            if(i > 0) cout << \" \";\n            cout << groups[g][i];\n        }\n        cout << \"\\n\";\n        \n        for(auto [a, b] : edges[g]){\n            cout << a << \" \" << b << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<pair<int, int>> targets;\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dchar[] = {'U', 'D', 'L', 'R'};\n\nbool valid(int x, int y) {\n    return 0 <= x && x < N && 0 <= y && y < N;\n}\n\npair<int, int> slideUntilBlock(int x, int y, int dir, const set<pair<int, int>>& blocks) {\n    int nx = x + dx[dir];\n    int ny = y + dy[dir];\n    while (valid(nx, ny) && !blocks.count({nx, ny})) {\n        x = nx;\n        y = ny;\n        nx = x + dx[dir];\n        ny = y + dy[dir];\n    }\n    return {x, y};\n}\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    targets.resize(M);\n    for (int i = 0; i < M; i++) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n    \n    vector<pair<char, char>> result;\n    int x = targets[0].first;\n    int y = targets[0].second;\n    set<pair<int, int>> blocks;\n    \n    // Navigate from target to target\n    for (int t = 1; t < M; t++) {\n        int tx = targets[t].first;\n        int ty = targets[t].second;\n        \n        // A* search considering Move and Slide actions\n        // State: (f_score, g_score, x, y)\n        map<pair<int, int>, int> g_score;  // distance from start\n        priority_queue<tuple<int, int, int, int>,\n                       vector<tuple<int, int, int, int>>,\n                       greater<tuple<int, int, int, int>>> pq;\n        \n        int h = manhattan(x, y, tx, ty);\n        pq.push({h, 0, x, y});\n        g_score[{x, y}] = 0;\n        \n        map<pair<int, int>, pair<pair<int, int>, pair<char, char>>> parent;\n        parent[{x, y}] = {{-1, -1}, {'X', 'X'}};\n        \n        while (!pq.empty()) {\n            auto [f, g, cx, cy] = pq.top();\n            pq.pop();\n            \n            if (cx == tx && cy == ty) break;\n            if (g_score.count({cx, cy}) && g_score[{cx, cy}] < g) continue;\n            \n            // Try all directions with Move and Slide actions\n            for (int dir = 0; dir < 4; dir++) {\n                // Move action: move one square\n                {\n                    int nx = cx + dx[dir];\n                    int ny = cy + dy[dir];\n                    if (valid(nx, ny) && !blocks.count({nx, ny})) {\n                        int new_g = g + 1;\n                        if (!g_score.count({nx, ny}) || g_score[{nx, ny}] > new_g) {\n                            g_score[{nx, ny}] = new_g;\n                            parent[{nx, ny}] = {{cx, cy}, {'M', dchar[dir]}};\n                            int new_h = manhattan(nx, ny, tx, ty);\n                            pq.push({new_g + new_h, new_g, nx, ny});\n                        }\n                    }\n                }\n                \n                // Slide action: slide until hitting a block\n                {\n                    int nx = cx + dx[dir];\n                    int ny = cy + dy[dir];\n                    if (valid(nx, ny) && !blocks.count({nx, ny})) {\n                        auto [sx, sy] = slideUntilBlock(cx, cy, dir, blocks);\n                        if (sx != cx || sy != cy) {  // Only if we actually slid\n                            int new_g = g + 1;\n                            if (!g_score.count({sx, sy}) || g_score[{sx, sy}] > new_g) {\n                                g_score[{sx, sy}] = new_g;\n                                parent[{sx, sy}] = {{cx, cy}, {'S', dchar[dir]}};\n                                int new_h = manhattan(sx, sy, tx, ty);\n                                pq.push({new_g + new_h, new_g, sx, sy});\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        // Reconstruct path\n        vector<pair<char, char>> path;\n        pair<int, int> p = {tx, ty};\n        while (parent[p].second.first != 'X') {\n            path.push_back(parent[p].second);\n            p = parent[p].first;\n        }\n        reverse(path.begin(), path.end());\n        \n        for (auto action : path) {\n            result.push_back(action);\n        }\n        \n        x = tx;\n        y = ty;\n    }\n    \n    for (auto [a, d] : result) {\n        cout << a << \" \" << d << \"\\n\";\n    }\n    \n    return 0;\n}"},"4":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int id;\n    long long x, y, r;\n};\n\nvector<array<long long, 4>> result(205);\n\nvoid assign(vector<int> indices, const vector<Company>& companies, \n            long long x1, long long y1, long long x2, long long y2) {\n    if (indices.empty()) return;\n    if (indices.size() == 1) {\n        result[indices[0]] = {x1, y1, x2, y2};\n        return;\n    }\n    \n    double best_score = -1e18;\n    int best_strategy = -1;\n    long long best_split = x1;\n    vector<int> best_left, best_right;\n    \n    // Try vertical splits at company x-coordinates\n    {\n        set<long long> x_coords;\n        for (int idx : indices) {\n            x_coords.insert(companies[idx].x);\n            x_coords.insert(companies[idx].x + 1);\n        }\n        \n        for (long long cx : x_coords) {\n            if (cx <= x1 || cx >= x2) continue;\n            \n            vector<int> left, right;\n            long long left_desired = 0, right_desired = 0;\n            \n            for (int idx : indices) {\n                if (companies[idx].x < cx) {\n                    left.push_back(idx);\n                    left_desired += companies[idx].r;\n                } else {\n                    right.push_back(idx);\n                    right_desired += companies[idx].r;\n                }\n            }\n            \n            if (left.empty() || right.empty()) continue;\n            \n            long long left_area = (cx - x1) * (y2 - y1);\n            long long right_area = (x2 - cx) * (y2 - y1);\n            \n            double left_ratio = (double)left_area / max(1LL, left_desired);\n            double right_ratio = (double)right_area / max(1LL, right_desired);\n            \n            double score = -abs(log(left_ratio)) - abs(log(right_ratio));\n            \n            if (score > best_score) {\n                best_score = score;\n                best_strategy = 0;\n                best_split = cx;\n                best_left = left;\n                best_right = right;\n            }\n        }\n    }\n    \n    // Try horizontal splits at company y-coordinates\n    {\n        set<long long> y_coords;\n        for (int idx : indices) {\n            y_coords.insert(companies[idx].y);\n            y_coords.insert(companies[idx].y + 1);\n        }\n        \n        for (long long cy : y_coords) {\n            if (cy <= y1 || cy >= y2) continue;\n            \n            vector<int> bottom, top;\n            long long bottom_desired = 0, top_desired = 0;\n            \n            for (int idx : indices) {\n                if (companies[idx].y < cy) {\n                    bottom.push_back(idx);\n                    bottom_desired += companies[idx].r;\n                } else {\n                    top.push_back(idx);\n                    top_desired += companies[idx].r;\n                }\n            }\n            \n            if (bottom.empty() || top.empty()) continue;\n            \n            long long bottom_area = (x2 - x1) * (cy - y1);\n            long long top_area = (x2 - x1) * (y2 - cy);\n            \n            double bottom_ratio = (double)bottom_area / max(1LL, bottom_desired);\n            double top_ratio = (double)top_area / max(1LL, top_desired);\n            \n            double score = -abs(log(bottom_ratio)) - abs(log(top_ratio));\n            \n            if (score > best_score) {\n                best_score = score;\n                best_strategy = 1;\n                best_split = cy;\n                best_left = bottom;\n                best_right = top;\n            }\n        }\n    }\n    \n    // Apply best split\n    if (best_strategy == 0) {\n        assign(best_left, companies, x1, y1, best_split, y2);\n        assign(best_right, companies, best_split, y1, x2, y2);\n    } else if (best_strategy == 1) {\n        assign(best_left, companies, x1, y1, x2, best_split);\n        assign(best_right, companies, x1, best_split, x2, y2);\n    } else {\n        // Fallback: median split\n        vector<long long> xs;\n        for (int idx : indices) xs.push_back(companies[idx].x);\n        sort(xs.begin(), xs.end());\n        long long med_x = xs[xs.size() / 2] + 1;\n        med_x = max(x1 + 1, min(x2 - 1, med_x));\n        \n        vector<int> left, right;\n        for (int idx : indices) {\n            if (companies[idx].x < med_x) left.push_back(idx);\n            else right.push_back(idx);\n        }\n        \n        if (!left.empty() && !right.empty()) {\n            assign(left, companies, x1, y1, med_x, y2);\n            assign(right, companies, med_x, y1, x2, y2);\n        } else {\n            long long mid_y = (y1 + y2) / 2;\n            for (int idx : indices) {\n                if (companies[idx].y < mid_y) left.push_back(idx);\n                else right.push_back(idx);\n            }\n            assign(left, companies, x1, y1, x2, mid_y);\n            assign(right, companies, x1, mid_y, x2, y2);\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    vector<Company> companies(n);\n    \n    for (int i = 0; i < n; i++) {\n        companies[i].id = i;\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n    \n    vector<int> indices(n);\n    iota(indices.begin(), indices.end(), 0);\n    \n    assign(indices, companies, 0, 0, 10000, 10000);\n    \n    for (int i = 0; i < n; i++) {\n        cout << result[i][0] << \" \" << result[i][1] << \" \" \n             << result[i][2] << \" \" << result[i][3] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint si, sj;\nint tile[50][50];\nint value[50][50];\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dc[] = {'U', 'D', 'L', 'R'};\n\nint best_score = 0;\nstring best_path = \"\";\nchrono::high_resolution_clock::time_point start_time;\nconst double TIME_LIMIT = 1.95;\n\nbool time_exceeded() {\n    auto now = chrono::high_resolution_clock::now();\n    double elapsed = chrono::duration<double>(now - start_time).count();\n    return elapsed > TIME_LIMIT;\n}\n\npair<int, string> walk(vector<bool>& visited_tiles, mt19937& rng) {\n    int score = value[si][sj];\n    int cur_i = si, cur_j = sj;\n    string path = \"\";\n    \n    while (true) {\n        vector<int> valid_dirs;\n        \n        // Find all valid moves (adjacent unvisited tiles)\n        for (int d = 0; d < 4; d++) {\n            int ni = cur_i + dx[d];\n            int nj = cur_j + dy[d];\n            \n            if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n                int new_tile = tile[ni][nj];\n                if (!visited_tiles[new_tile]) {\n                    valid_dirs.push_back(d);\n                }\n            }\n        }\n        \n        if (valid_dirs.empty()) break;\n        \n        int d;\n        // 70% greedy (pick highest value), 30% random exploration\n        if (uniform_real_distribution<>(0, 1)(rng) < 0.7) {\n            d = valid_dirs[0];\n            int best_v = value[cur_i + dx[d]][cur_j + dy[d]];\n            \n            // Find direction with highest value\n            for (int dd : valid_dirs) {\n                int ni = cur_i + dx[dd];\n                int nj = cur_j + dy[dd];\n                if (value[ni][nj] > best_v) {\n                    d = dd;\n                    best_v = value[ni][nj];\n                }\n            }\n        } else {\n            // Random exploration\n            d = valid_dirs[uniform_int_distribution<>(0, valid_dirs.size() - 1)(rng)];\n        }\n        \n        int ni = cur_i + dx[d];\n        int nj = cur_j + dy[d];\n        visited_tiles[tile[ni][nj]] = true;\n        path.push_back(dc[d]);\n        score += value[ni][nj];\n        cur_i = ni;\n        cur_j = nj;\n    }\n    \n    return {score, path};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> si >> sj;\n    \n    int max_tile = 0;\n    for (int i = 0; i < 50; i++) {\n        for (int j = 0; j < 50; j++) {\n            cin >> tile[i][j];\n            max_tile = max(max_tile, tile[i][j]);\n        }\n    }\n    \n    for (int i = 0; i < 50; i++) {\n        for (int j = 0; j < 50; j++) {\n            cin >> value[i][j];\n        }\n    }\n    \n    start_time = chrono::high_resolution_clock::now();\n    best_score = value[si][sj];\n    best_path = \"\";\n    \n    mt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n    \n    // Run multiple random walks until time limit\n    while (!time_exceeded()) {\n        vector<bool> visited_tiles(max_tile + 1, false);\n        visited_tiles[tile[si][sj]] = true;\n        auto [score, path] = walk(visited_tiles, rng);\n        \n        if (score > best_score) {\n            best_score = score;\n            best_path = path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\n#include <queue>\nusing namespace std;\n\nconst int N = 30;\nconst double INF = 1e18;\nconst double EDGE_MIN = 800.0;\nconst double EDGE_MAX = 10000.0;\n\ndouble h[N][N-1], v[N-1][N];\nint h_count[N][N-1], v_count[N-1][N];\n\nstruct State {\n    double dist;\n    int i, j;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\npair<string, double> dijkstra(int si, int sj, int ti, int tj) {\n    vector<vector<double>> dist(N, vector<double>(N, INF));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1, -1}));\n    vector<vector<char>> dir(N, vector<char>(N));\n    \n    priority_queue<State, vector<State>, greater<State>> pq;\n    dist[si][sj] = 0;\n    pq.push({0, si, sj});\n    \n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top();\n        pq.pop();\n        \n        if (d > dist[i][j]) continue;\n        \n        // Up\n        if (i > 0) {\n            double new_dist = d + v[i-1][j];\n            if (new_dist < dist[i-1][j]) {\n                dist[i-1][j] = new_dist;\n                parent[i-1][j] = {i, j};\n                dir[i-1][j] = 'U';\n                pq.push({new_dist, i-1, j});\n            }\n        }\n        \n        // Down\n        if (i < N-1) {\n            double new_dist = d + v[i][j];\n            if (new_dist < dist[i+1][j]) {\n                dist[i+1][j] = new_dist;\n                parent[i+1][j] = {i, j};\n                dir[i+1][j] = 'D';\n                pq.push({new_dist, i+1, j});\n            }\n        }\n        \n        // Left\n        if (j > 0) {\n            double new_dist = d + h[i][j-1];\n            if (new_dist < dist[i][j-1]) {\n                dist[i][j-1] = new_dist;\n                parent[i][j-1] = {i, j};\n                dir[i][j-1] = 'L';\n                pq.push({new_dist, i, j-1});\n            }\n        }\n        \n        // Right\n        if (j < N-1) {\n            double new_dist = d + h[i][j];\n            if (new_dist < dist[i][j+1]) {\n                dist[i][j+1] = new_dist;\n                parent[i][j+1] = {i, j};\n                dir[i][j+1] = 'R';\n                pq.push({new_dist, i, j+1});\n            }\n        }\n    }\n    \n    string path;\n    int ci = ti, cj = tj;\n    while (parent[ci][cj].first != -1) {\n        path += dir[ci][cj];\n        auto [pi, pj] = parent[ci][cj];\n        ci = pi;\n        cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    \n    return {path, dist[ti][tj]};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Initialize edge weights and observation counts\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N-1; j++) {\n            h[i][j] = 5000.0;\n            h_count[i][j] = 0;\n        }\n    }\n    for (int i = 0; i < N-1; i++) {\n        for (int j = 0; j < N; j++) {\n            v[i][j] = 5000.0;\n            v_count[i][j] = 0;\n        }\n    }\n    \n    for (int q = 0; q < 1000; q++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        auto [path, computed_length] = dijkstra(si, sj, ti, tj);\n        \n        cout << path << endl;\n        cout.flush();\n        \n        long long feedback;\n        cin >> feedback;\n        \n        // Base learning rate with linear decay: 0.15 -> 0.05\n        double base_alpha = 0.15 - 0.10 * q / 1000.0;\n        base_alpha = max(0.05, base_alpha);\n        \n        // Update edge weights based on feedback\n        if (!path.empty()) {\n            double edge_estimate = (double)feedback / path.length();\n            \n            int ci = si, cj = sj;\n            for (char c : path) {\n                if (c == 'U') {\n                    // Per-edge adaptive alpha: reduce confidence for frequently-seen edges\n                    double adaptive_alpha = base_alpha * exp(-0.04 * v_count[ci-1][cj]);\n                    v[ci-1][cj] = (1 - adaptive_alpha) * v[ci-1][cj] + adaptive_alpha * edge_estimate;\n                    v[ci-1][cj] = max(EDGE_MIN, min(EDGE_MAX, v[ci-1][cj]));\n                    v_count[ci-1][cj]++;\n                    ci--;\n                } else if (c == 'D') {\n                    double adaptive_alpha = base_alpha * exp(-0.04 * v_count[ci][cj]);\n                    v[ci][cj] = (1 - adaptive_alpha) * v[ci][cj] + adaptive_alpha * edge_estimate;\n                    v[ci][cj] = max(EDGE_MIN, min(EDGE_MAX, v[ci][cj]));\n                    v_count[ci][cj]++;\n                    ci++;\n                } else if (c == 'L') {\n                    double adaptive_alpha = base_alpha * exp(-0.04 * h_count[ci][cj-1]);\n                    h[ci][cj-1] = (1 - adaptive_alpha) * h[ci][cj-1] + adaptive_alpha * edge_estimate;\n                    h[ci][cj-1] = max(EDGE_MIN, min(EDGE_MAX, h[ci][cj-1]));\n                    h_count[ci][cj-1]++;\n                    cj--;\n                } else if (c == 'R') {\n                    double adaptive_alpha = base_alpha * exp(-0.04 * h_count[ci][cj]);\n                    h[ci][cj] = (1 - adaptive_alpha) * h[ci][cj] + adaptive_alpha * edge_estimate;\n                    h[ci][cj] = max(EDGE_MIN, min(EDGE_MAX, h[ci][cj]));\n                    h_count[ci][cj]++;\n                    cj++;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc004":"#include<bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<string> strings;\nchar bestMatrix[20][20];\nint bestMatches = 0;\n\nbool isSubsequence(const string& s, char mat[20][20]) {\n    int len = (int)s.length();\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            bool found = true;\n            for(int p = 0; p < len; p++) {\n                if(mat[i][(j+p)%N] != s[p]) {\n                    found = false;\n                    break;\n                }\n            }\n            if(found) return true;\n        }\n    }\n    \n    for(int j = 0; j < N; j++) {\n        for(int i = 0; i < N; i++) {\n            bool found = true;\n            for(int p = 0; p < len; p++) {\n                if(mat[(i+p)%N][j] != s[p]) {\n                    found = false;\n                    break;\n                }\n            }\n            if(found) return true;\n        }\n    }\n    \n    return false;\n}\n\nint countMatches(char mat[20][20]) {\n    int c = 0;\n    for(const auto& s : strings) {\n        if(isSubsequence(s, mat)) c++;\n    }\n    return c;\n}\n\nvoid runSA(mt19937& rng, chrono::steady_clock::time_point deadline, double timeLimit) {\n    char currentMatrix[20][20];\n    \n    uniform_int_distribution<int> charDist(0, 7);\n    uniform_int_distribution<int> posDist(0, N-1);\n    uniform_int_distribution<int> dirDist(0, 1);\n    uniform_int_distribution<int> stringDist(0, M-1);\n    uniform_real_distribution<double> realDist(0, 1);\n    \n    // Initialize with random matrix\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            currentMatrix[i][j] = 'A' + charDist(rng);\n        }\n    }\n    \n    // Selective warm-start: place about 45% of strings\n    int numPlace = (M * 9) / 20;  // 45% of strings\n    vector<int> indices(M);\n    iota(indices.begin(), indices.end(), 0);\n    shuffle(indices.begin(), indices.end(), rng);\n    \n    for(int k = 0; k < numPlace; k++) {\n        const auto& s = strings[indices[k]];\n        int len = (int)s.length();\n        int i = posDist(rng);\n        int j = posDist(rng);\n        int dir = dirDist(rng);\n        \n        if(dir == 0) {  // horizontal\n            for(int p = 0; p < len; p++) {\n                currentMatrix[i][(j+p)%N] = s[p];\n            }\n        } else {  // vertical\n            for(int p = 0; p < len; p++) {\n                currentMatrix[(i+p)%N][j] = s[p];\n            }\n        }\n    }\n    \n    int currentMatches = countMatches(currentMatrix);\n    if(currentMatches > bestMatches) {\n        bestMatches = currentMatches;\n        memcpy(bestMatrix, currentMatrix, sizeof(currentMatrix));\n    }\n    \n    // Simulated annealing with optimized parameters\n    double temp = 30.0;\n    const double coolingRate = 0.99993;  // Smooth gradual cooling\n    \n    auto runDeadline = chrono::steady_clock::now() + chrono::milliseconds((long long)(timeLimit * 1000));\n    \n    while(chrono::steady_clock::now() < runDeadline && chrono::steady_clock::now() < deadline && temp > 0.0001) {\n        int i = posDist(rng);\n        int j = posDist(rng);\n        \n        char old = currentMatrix[i][j];\n        char newChar = 'A' + charDist(rng);\n        \n        if(newChar == old) continue;\n        \n        currentMatrix[i][j] = newChar;\n        int newMatches = countMatches(currentMatrix);\n        int delta = newMatches - currentMatches;\n        \n        if(delta >= 0) {\n            currentMatches = newMatches;\n            if(currentMatches > bestMatches) {\n                bestMatches = currentMatches;\n                memcpy(bestMatrix, currentMatrix, sizeof(currentMatrix));\n            }\n        } else {\n            if(realDist(rng) < exp((double)delta / max(temp, 0.0001))) {\n                currentMatches = newMatches;\n            } else {\n                currentMatrix[i][j] = old;\n            }\n        }\n        \n        temp *= coolingRate;\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    strings.resize(M);\n    for(int i = 0; i < M; i++) {\n        cin >> strings[i];\n    }\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto deadline = chrono::steady_clock::now() + chrono::milliseconds(2850);\n    \n    // Multiple restarts with different random seeds and starting states\n    // Allocate time budget: first run gets 1200ms, subsequent runs get 550ms each\n    double firstRunTime = 1.2;\n    double otherRunTime = 0.55;\n    \n    runSA(rng, deadline, firstRunTime);\n    \n    while(chrono::steady_clock::now() < deadline) {\n        runSA(rng, deadline, otherRunTime);\n    }\n    \n    // Output best result found\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            cout << bestMatrix[i][j];\n        }\n        cout << '\\n';\n    }\n    \n    return 0;\n}","ahc005":"#include<bits/stdc++.h>\nusing namespace std;\n\nint N, si, sj;\nvector<string> grid;\nmap<pair<int,int>, set<pair<int,int>>> visibilityCache;\n\nset<pair<int,int>> getVisible(int i, int j) {\n    if (visibilityCache.count({i, j})) {\n        return visibilityCache[{i, j}];\n    }\n    \n    set<pair<int,int>> result;\n    if (i < 0 || i >= N || j < 0 || j >= N || grid[i][j] == '#') \n        return result;\n    \n    // Check all 4 directions from (i,j)\n    for (int jj = j; jj < N && grid[i][jj] != '#'; jj++) \n        result.insert({i, jj});\n    for (int jj = j - 1; jj >= 0 && grid[i][jj] != '#'; jj--) \n        result.insert({i, jj});\n    for (int ii = i; ii < N && grid[ii][j] != '#'; ii++) \n        result.insert({ii, j});\n    for (int ii = i - 1; ii >= 0 && grid[ii][j] != '#'; ii--) \n        result.insert({ii, j});\n    \n    return visibilityCache[{i, j}] = result;\n}\n\nvector<pair<int,int>> getPath(pair<int,int> from, pair<int,int> to) {\n    if (from == to) return {from};\n    \n    map<pair<int,int>, pair<int,int>> parent;\n    map<pair<int,int>, int> dist;\n    priority_queue<pair<int, pair<int,int>>, vector<pair<int, pair<int,int>>>, greater<>> pq;\n    \n    pq.push({0, from});\n    dist[from] = 0;\n    parent[from] = {-1, -1};\n    \n    while (!pq.empty()) {\n        auto [d, pos] = pq.top();\n        pq.pop();\n        auto [i, j] = pos;\n        \n        if (dist.count(pos) && dist[pos] < d) continue;\n        if (pos == to) break;\n        \n        int di[] = {-1, 1, 0, 0};\n        int dj[] = {0, 0, -1, 1};\n        for (int dd = 0; dd < 4; dd++) {\n            int ni = i + di[dd];\n            int nj = j + dj[dd];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && grid[ni][nj] != '#') {\n                int cost = grid[ni][nj] - '0';\n                int newDist = d + cost;\n                if (!dist.count({ni, nj}) || dist[{ni, nj}] > newDist) {\n                    dist[{ni, nj}] = newDist;\n                    parent[{ni, nj}] = {i, j};\n                    pq.push({newDist, {ni, nj}});\n                }\n            }\n        }\n    }\n    \n    vector<pair<int,int>> path;\n    auto cur = to;\n    while (cur != make_pair(-1, -1)) {\n        path.push_back(cur);\n        cur = parent[cur];\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> si >> sj;\n    grid.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    \n    vector<pair<int,int>> allRoads;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] != '#') {\n                allRoads.push_back({i, j});\n            }\n        }\n    }\n    \n    // Precompute all visibility maps\n    for (auto road : allRoads) {\n        getVisible(road.first, road.second);\n    }\n    \n    set<pair<int,int>> covered;\n    vector<pair<int,int>> waypoints;\n    \n    waypoints.push_back({si, sj});\n    for (auto cell : getVisible(si, sj)) {\n        covered.insert(cell);\n    }\n    \n    // Greedy set cover - no iteration limit\n    while ((int)covered.size() < (int)allRoads.size()) {\n        pair<int,int> best = {-1, -1};\n        int bestCover = -1;\n        \n        for (auto road : allRoads) {\n            int cover = 0;\n            for (auto vis : getVisible(road.first, road.second)) {\n                if (!covered.count(vis)) cover++;\n            }\n            if (cover > bestCover) {\n                bestCover = cover;\n                best = road;\n            }\n        }\n        \n        if (bestCover <= 0) break;\n        \n        waypoints.push_back(best);\n        for (auto cell : getVisible(best.first, best.second)) {\n            covered.insert(cell);\n        }\n    }\n    \n    waypoints.push_back({si, sj});\n    \n    string result = \"\";\n    for (size_t i = 0; i + 1 < waypoints.size(); i++) {\n        auto path = getPath(waypoints[i], waypoints[i + 1]);\n        for (size_t j = 1; j < path.size(); j++) {\n            int pi = path[j - 1].first, pj = path[j - 1].second;\n            int ni = path[j].first, nj = path[j].second;\n            if (ni < pi) result += 'U';\n            else if (ni > pi) result += 'D';\n            else if (nj < pj) result += 'L';\n            else result += 'R';\n        }\n    }\n    \n    cout << result << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n    \n    vector<vector<int>> d(N, vector<int>(K));\n    double sum_difficulty = 0.0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < K; j++) {\n            cin >> d[i][j];\n            sum_difficulty += d[i][j];\n        }\n    }\n    double avg_difficulty = sum_difficulty / (N * K);\n    \n    vector<set<int>> deps(N);\n    vector<vector<int>> rev_deps(N);\n    \n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        deps[v].insert(u);\n        rev_deps[u].push_back(v);\n    }\n    \n    // Compute criticality (longest path)\n    vector<int> crit(N, -1);\n    function<int(int)> compute_crit = [&](int u) -> int {\n        if (crit[u] != -1) return crit[u];\n        int maxlen = 0;\n        for (int v : rev_deps[u]) {\n            maxlen = max(maxlen, 1 + compute_crit(v));\n        }\n        return crit[u] = maxlen;\n    };\n    for (int i = 0; i < N; i++) compute_crit(i);\n    \n    double max_crit = (double)*max_element(crit.begin(), crit.end()) + 1.0;\n    \n    vector<int> task_status(N, -1);\n    vector<int> task_start_day(N, -1);\n    vector<int> member_task(M, -1);\n    \n    // Lower initial skill estimates to force learning\n    vector<vector<double>> skills(M, vector<double>(K, avg_difficulty * 0.35));\n    \n    auto estimate_time = [&](int m, int t) -> double {\n        double deficit = 0.0;\n        for (int k = 0; k < K; k++) {\n            deficit += max(0.0, (double)d[t][k] - skills[m][k]);\n        }\n        return max(1.0, deficit);\n    };\n    \n    // Calculate affinity: how well member's skills match task requirements\n    auto get_affinity = [&](int m, int t) -> double {\n        double affinity = 0.0;\n        double total_req = 0.0;\n        for (int k = 0; k < K; k++) {\n            double needed = (double)d[t][k];\n            double have = skills[m][k];\n            total_req += needed;\n            // Reward matching skills, penalize mismatch\n            if (needed > 0.01) {\n                affinity += min(needed, have) / needed * needed;\n            }\n        }\n        return total_req > 0.01 ? affinity / total_req : 0.5;\n    };\n    \n    int day = 0, completed = 0;\n    \n    while (day < 2000 && completed < N) {\n        day++;\n        \n        vector<pair<int, int>> assignments;\n        vector<int> available;\n        \n        // Find all available tasks\n        for (int t = 0; t < N; t++) {\n            if (task_status[t] != -1) continue;\n            bool ok = true;\n            for (int dep : deps[t]) {\n                if (task_status[dep] < 2000) {\n                    ok = false;\n                    break;\n                }\n            }\n            if (ok) available.push_back(t);\n        }\n        \n        // Assign tasks to idle members using comprehensive scoring\n        for (int m = 0; m < M; m++) {\n            if (member_task[m] != -1 || available.empty()) continue;\n            \n            int best_task = -1;\n            double best_score = -1e18;\n            \n            for (int t : available) {\n                double time_est = estimate_time(m, t);\n                double crit_norm = (double)crit[t] / max_crit;\n                double affinity = get_affinity(m, t);\n                \n                // Balanced scoring:\n                // - Criticality (most important): weight 35\n                // - Member fit (important): weight 10\n                // - Time (secondary concern): weight -1.0\n                double score = crit_norm * 35.0 + affinity * 10.0 - time_est * 1.0;\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_task = t;\n                }\n            }\n            \n            if (best_task != -1) {\n                assignments.push_back({m + 1, best_task + 1});\n                member_task[m] = best_task;\n                task_status[best_task] = day;\n                task_start_day[best_task] = day;\n                available.erase(find(available.begin(), available.end(), best_task));\n            }\n        }\n        \n        cout << assignments.size();\n        for (auto [m, t] : assignments) {\n            cout << \" \" << m << \" \" << t;\n        }\n        cout << \"\\n\";\n        cout.flush();\n        \n        int n;\n        cin >> n;\n        if (n == -1) break;\n        \n        // Process completed tasks and aggressively learn\n        for (int i = 0; i < n; i++) {\n            int m;\n            cin >> m;\n            m--;\n            \n            if (member_task[m] != -1) {\n                int t = member_task[m];\n                int duration = day - task_start_day[t] + 1;\n                \n                task_status[t] = 2000 + day;\n                member_task[m] = -1;\n                completed++;\n                \n                // Aggressive skill learning\n                if (duration == 1) {\n                    // Perfect task completion: member definitely has all required skills\n                    for (int k = 0; k < K; k++) {\n                        skills[m][k] = max(skills[m][k], (double)d[t][k] * 0.99);\n                    }\n                } else {\n                    // Infer skill deficit from duration\n                    // With randomness in [-3, 3], expected deficit \u2248 duration - 0.05\n                    double estimated_deficit = max(0.0, (double)duration - 0.05);\n                    \n                    double total_req = 0.0;\n                    for (int k = 0; k < K; k++) {\n                        total_req += d[t][k];\n                    }\n                    \n                    if (total_req > 1e-6) {\n                        // Distribute inferred skills proportionally to requirements\n                        for (int k = 0; k < K; k++) {\n                            double proportion = (double)d[t][k] / total_req;\n                            double inferred_skill = d[t][k] - proportion * estimated_deficit;\n                            // Aggressive learning: trust the inference\n                            skills[m][k] = max(skills[m][k], max(0.0, inferred_skill * 0.97));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nll manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    struct Order {\n        int a, b, c, d;\n    };\n    \n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; i++) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n    }\n    \n    auto buildRouteGreedy = [&](const vector<int>& orders_to_use) {\n        vector<pair<int, int>> route;\n        route.push_back({400, 400});\n        \n        vector<bool> pickup_done(orders_to_use.size(), false);\n        vector<bool> delivery_done(orders_to_use.size(), false);\n        \n        int cx = 400, cy = 400;\n        \n        for (int step = 0; step < (int)orders_to_use.size() * 2; step++) {\n            int best_i = -1, best_type = -1;\n            ll best_dist = LLONG_MAX;\n            \n            for (int i = 0; i < (int)orders_to_use.size(); i++) {\n                if (!pickup_done[i]) {\n                    ll d = manhattan(cx, cy, orders[orders_to_use[i]].a, orders[orders_to_use[i]].b);\n                    if (d < best_dist) {\n                        best_dist = d;\n                        best_i = i;\n                        best_type = 0;\n                    }\n                }\n                if (pickup_done[i] && !delivery_done[i]) {\n                    ll d = manhattan(cx, cy, orders[orders_to_use[i]].c, orders[orders_to_use[i]].d);\n                    if (d < best_dist) {\n                        best_dist = d;\n                        best_i = i;\n                        best_type = 1;\n                    }\n                }\n            }\n            \n            if (best_i == -1) break;\n            \n            if (best_type == 0) {\n                cx = orders[orders_to_use[best_i]].a;\n                cy = orders[orders_to_use[best_i]].b;\n                pickup_done[best_i] = true;\n            } else {\n                cx = orders[orders_to_use[best_i]].c;\n                cy = orders[orders_to_use[best_i]].d;\n                delivery_done[best_i] = true;\n            }\n            \n            route.push_back({cx, cy});\n        }\n        \n        route.push_back({400, 400});\n        return route;\n    };\n    \n    auto calcDist = [](const vector<pair<int, int>>& route) {\n        ll total = 0;\n        for (size_t i = 0; i < route.size() - 1; i++) {\n            total += manhattan(route[i].first, route[i].second, \n                             route[i+1].first, route[i+1].second);\n        }\n        return total;\n    };\n    \n    auto improveRoute2Opt = [&](vector<pair<int, int>> route, const vector<int>& orders_to_use) {\n        auto check_valid = [&](const vector<pair<int, int>>& r) {\n            for (int i = 0; i < (int)orders_to_use.size(); i++) {\n                int pickup_idx = -1, delivery_idx = -1;\n                for (int j = 0; j < (int)r.size(); j++) {\n                    if (r[j].first == orders[orders_to_use[i]].a && r[j].second == orders[orders_to_use[i]].b) {\n                        pickup_idx = j;\n                    }\n                    if (r[j].first == orders[orders_to_use[i]].c && r[j].second == orders[orders_to_use[i]].d) {\n                        delivery_idx = j;\n                    }\n                }\n                if (pickup_idx == -1 || delivery_idx == -1 || pickup_idx > delivery_idx) {\n                    return false;\n                }\n            }\n            return true;\n        };\n        \n        bool improved = true;\n        int iterations = 0;\n        while (improved && iterations < 30) {\n            improved = false;\n            iterations++;\n            \n            for (int i = 1; i < (int)route.size() - 2; i++) {\n                for (int j = i + 2; j < (int)route.size() - 1; j++) {\n                    ll old_cost = manhattan(route[i-1].first, route[i-1].second, route[i].first, route[i].second) +\n                                  manhattan(route[j].first, route[j].second, route[j+1].first, route[j+1].second);\n                    ll new_cost = manhattan(route[i-1].first, route[i-1].second, route[j].first, route[j].second) +\n                                  manhattan(route[i].first, route[i].second, route[j+1].first, route[j+1].second);\n                    \n                    if (new_cost < old_cost) {\n                        auto new_route = route;\n                        reverse(new_route.begin() + i, new_route.begin() + j + 1);\n                        \n                        if (check_valid(new_route)) {\n                            route = new_route;\n                            improved = true;\n                            break;\n                        }\n                    }\n                }\n                if (improved) break;\n            }\n        }\n        \n        return route;\n    };\n    \n    ll best_overall_dist = LLONG_MAX;\n    vector<int> best_selected;\n    vector<pair<int, int>> best_route;\n    \n    // Deterministic criteria\n    vector<vector<pair<ll, int>>> all_selections;\n    \n    for (int criterion = 0; criterion < 6; criterion++) {\n        vector<pair<ll, int>> costs;\n        \n        for (int i = 0; i < 1000; i++) {\n            ll cost = 0;\n            switch(criterion) {\n                case 0: // Distance to office\n                    cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                           manhattan(400, 400, orders[i].c, orders[i].d);\n                    break;\n                case 1: // Pickup-delivery distance\n                    cost = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n                    break;\n                case 2: // Balanced\n                    cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                           manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d) +\n                           manhattan(orders[i].c, orders[i].d, 400, 400);\n                    break;\n                case 3: // Distance from center\n                    cost = abs(orders[i].a - 400) + abs(orders[i].b - 400) +\n                           abs(orders[i].c - 400) + abs(orders[i].d - 400);\n                    break;\n                case 4: // Spread\n                {\n                    int minx = min(orders[i].a, orders[i].c);\n                    int maxx = max(orders[i].a, orders[i].c);\n                    int miny = min(orders[i].b, orders[i].d);\n                    int maxy = max(orders[i].b, orders[i].d);\n                    cost = (maxx - minx) + (maxy - miny);\n                    break;\n                }\n                case 5: // Midpoint distance\n                {\n                    int mx = (orders[i].a + orders[i].c) / 2;\n                    int my = (orders[i].b + orders[i].d) / 2;\n                    cost = manhattan(400, 400, mx, my);\n                    break;\n                }\n            }\n            costs.push_back({cost, i});\n        }\n        sort(costs.begin(), costs.end());\n        all_selections.push_back(costs);\n    }\n    \n    // Try deterministic selections\n    for (const auto& costs : all_selections) {\n        vector<int> selected(50);\n        for (int i = 0; i < 50; i++) {\n            selected[i] = costs[i].second;\n        }\n        \n        auto route = buildRouteGreedy(selected);\n        route = improveRoute2Opt(route, selected);\n        ll dist = calcDist(route);\n        \n        if (dist < best_overall_dist) {\n            best_overall_dist = dist;\n            best_selected = selected;\n            best_route = route;\n        }\n    }\n    \n    // Try random selections\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    for (int trial = 0; trial < 25; trial++) {\n        vector<int> selected;\n        vector<bool> used(1000, false);\n        \n        for (int i = 0; i < 50; i++) {\n            int idx = uniform_int_distribution<int>(0, 999)(rng);\n            while (used[idx]) {\n                idx = uniform_int_distribution<int>(0, 999)(rng);\n            }\n            selected.push_back(idx);\n            used[idx] = true;\n        }\n        \n        auto route = buildRouteGreedy(selected);\n        route = improveRoute2Opt(route, selected);\n        ll dist = calcDist(route);\n        \n        if (dist < best_overall_dist) {\n            best_overall_dist = dist;\n            best_selected = selected;\n            best_route = route;\n        }\n    }\n    \n    // Output\n    cout << \"50\";\n    for (int i = 0; i < 50; i++) {\n        cout << \" \" << (best_selected[i] + 1);\n    }\n    cout << \"\\n\";\n    \n    cout << best_route.size();\n    for (const auto& p : best_route) {\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass UnionFind {\npublic:\n    vector<int> parent;\n    \n    UnionFind(int n) : parent(n) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    \n    int find(int x) {\n        if (parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    \n    bool unite(int x, int y) {\n        x = find(x);\n        y = find(y);\n        if (x == y) return false;\n        parent[y] = x;\n        return true;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N = 400, M = 1995;\n    vector<pair<int, int>> coords(N);\n    vector<pair<int, int>> edges(M);\n    \n    for (int i = 0; i < N; i++) {\n        cin >> coords[i].first >> coords[i].second;\n    }\n    \n    for (int i = 0; i < M; i++) {\n        cin >> edges[i].first >> edges[i].second;\n    }\n    \n    UnionFind uf(N);\n    int edges_needed = N - 1;\n    \n    for (int i = 0; i < M; i++) {\n        int length;\n        cin >> length;\n        \n        int u = edges[i].first, v = edges[i].second;\n        \n        bool accept = false;\n        \n        // Accept tree edges (connecting different components) while we need them\n        if (edges_needed > 0 && uf.find(u) != uf.find(v)) {\n            accept = true;\n            uf.unite(u, v);\n            edges_needed--;\n        }\n        // Reject cycle edges and all edges once graph is connected\n        \n        cout << (accept ? 1 : 0) << '\\n';\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    \n    int N;\n    cin >> N;\n    vector<pair<int,int>> pets(N);\n    vector<int> pet_types(N);\n    for(int i = 0; i < N; i++){\n        int x, y, t;\n        cin >> x >> y >> t;\n        pets[i] = {x-1, y-1};\n        pet_types[i] = t;\n    }\n    \n    int M;\n    cin >> M;\n    vector<pair<int,int>> humans(M);\n    for(int i = 0; i < M; i++){\n        int x, y;\n        cin >> x >> y;\n        humans[i] = {x-1, y-1};\n    }\n    \n    for(int turn = 0; turn < 300; turn++){\n        string actions(M, '.');\n        \n        // Dynamic target based on game phase\n        int target_x, target_y;\n        if(turn < 80){\n            // Phase 1: Move toward top-left corner\n            target_x = 5;\n            target_y = 5;\n        } else if(turn < 200){\n            // Phase 2: Consolidate and expand slightly\n            target_x = 8;\n            target_y = 8;\n        } else {\n            // Phase 3: Hold position\n            target_x = 8;\n            target_y = 8;\n        }\n        \n        // Each human moves toward the target\n        for(int i = 0; i < M; i++){\n            int x = humans[i].first;\n            int y = humans[i].second;\n            \n            if(x > target_x) actions[i] = 'U';\n            else if(x < target_x) actions[i] = 'D';\n            else if(y > target_y) actions[i] = 'L';\n            else if(y < target_y) actions[i] = 'R';\n            else actions[i] = '.';\n        }\n        \n        cout << actions << endl;\n        cout.flush();\n        \n        // Read pet movements\n        for(int i = 0; i < N; i++){\n            string move;\n            cin >> move;\n            \n            // Apply movement to each pet\n            for(char c : move){\n                if(c == 'U' && pets[i].first > 0) pets[i].first--;\n                else if(c == 'D' && pets[i].first < 29) pets[i].first++;\n                else if(c == 'L' && pets[i].second > 0) pets[i].second--;\n                else if(c == 'R' && pets[i].second < 29) pets[i].second++;\n            }\n        }\n        \n        // Update human positions based on executed actions\n        for(int i = 0; i < M; i++){\n            if(actions[i] == 'U' && humans[i].first > 0) humans[i].first--;\n            else if(actions[i] == 'D' && humans[i].first < 29) humans[i].first++;\n            else if(actions[i] == 'L' && humans[i].second > 0) humans[i].second--;\n            else if(actions[i] == 'R' && humans[i].second < 29) humans[i].second++;\n        }\n    }\n    \n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n    \n    vector<string> h(20), v(19);\n    for (int i = 0; i < 20; i++) cin >> h[i];\n    for (int i = 0; i < 19; i++) cin >> v[i];\n    \n    // BFS to find shortest path\n    map<pair<int,int>, pair<pair<int,int>, char>> parent;\n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    parent[{si, sj}] = {{-1, -1}, ' '};\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        vector<tuple<int, int, char, bool>> moves = {\n            {i-1, j, 'U', i > 0 && v[i-1][j] == '0'},\n            {i+1, j, 'D', i < 19 && v[i][j] == '0'},\n            {i, j-1, 'L', j > 0 && h[i][j-1] == '0'},\n            {i, j+1, 'R', j < 19 && h[i][j] == '0'}\n        };\n        \n        for (auto [ni, nj, dir, valid] : moves) {\n            if (valid && parent.find({ni, nj}) == parent.end()) {\n                parent[{ni, nj}] = {{i, j}, dir};\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    // Reconstruct path\n    string path = \"\";\n    {\n        int i = ti, j = tj;\n        while (parent[{i, j}].first.first != -1) {\n            char c = parent[{i, j}].second;\n            path = c + path;\n            auto [pi, pj] = parent[{i, j}].first;\n            i = pi;\n            j = pj;\n        }\n    }\n    \n    // Try different repetition factors\n    int n = path.length();\n    string best_path = path;\n    double best_score = 0;\n    \n    for (int r = 1; r * n <= 200; r++) {\n        // Probability of success: (1 - p^r)^n\n        double p_fail = pow(p, (double)r);\n        double p_succ_one = 1.0 - p_fail;\n        double p_succ_all = pow(p_succ_one, (double)n);\n        \n        int length = r * n;\n        double expected_score = p_succ_all * (401.0 - length);\n        \n        if (expected_score > best_score) {\n            best_score = expected_score;\n            best_path = \"\";\n            for (int k = 0; k < r; k++) best_path += path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\n\nint di[] = {0, -1, 0, 1};\nint dj[] = {-1, 0, 1, 0};\n\nint to[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1},\n};\n\nint grid[N][N];\nint rotations[N][N];\n\ninline int getTileType(int i, int j) {\n    int base = grid[i][j];\n    int rot = rotations[i][j];\n    if (base < 4) return (base + rot) % 4;\n    if (base < 6) return 4 + (rot % 2);\n    return 6 + (rot % 2);\n}\n\nint computeLoopLength(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    for (int iter = 0; iter < 100000; iter++) {\n        int cur = getTileType(i, j);\n        int d2 = to[cur][d];\n        if (d2 == -1) return 0;\n        i += di[d2];\n        j += dj[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (i == si && j == sj && d == sd) return length;\n    }\n    return 0;\n}\n\nlong long computeScore() {\n    vector<int> loops;\n    bool visited[N][N][4] = {};\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            for (int d = 0; d < 4; d++) {\n                if (!visited[i][j][d]) {\n                    int len = computeLoopLength(i, j, d);\n                    if (len > 0) {\n                        loops.push_back(len);\n                        int ii = i, jj = j, dd = d;\n                        for (int step = 0; step < len; step++) {\n                            visited[ii][jj][dd] = true;\n                            int cur = getTileType(ii, jj);\n                            int d2 = to[cur][dd];\n                            ii += di[d2];\n                            jj += dj[d2];\n                            dd = (d2 + 2) % 4;\n                        }\n                    } else {\n                        visited[i][j][d] = true;\n                    }\n                }\n            }\n        }\n    }\n    if (loops.size() < 2) return 0;\n    sort(loops.rbegin(), loops.rend());\n    return (long long)loops[0] * loops[1];\n}\n\nvoid simulatedAnnealing(mt19937& rng, long long& bestScore, int best_rotations[N][N], \n                        const chrono::steady_clock::time_point& start, int timeLimit) {\n    long long currentScore = computeScore();\n    if (currentScore > bestScore) {\n        bestScore = currentScore;\n        memcpy(best_rotations, rotations, sizeof(int) * N * N);\n    }\n    \n    double temperature = 1000.0;\n    int iteration = 0;\n    \n    while (chrono::duration_cast<chrono::milliseconds>(\n            chrono::steady_clock::now() - start).count() < timeLimit) {\n        \n        // Try multiple moves at current temperature\n        for (int attempt = 0; attempt < 5; attempt++) {\n            int i = rng() % N;\n            int j = rng() % N;\n            int oldRot = rotations[i][j];\n            int newRot = rng() % 4;\n            \n            rotations[i][j] = newRot;\n            long long newScore = computeScore();\n            \n            double delta = (double)(newScore - currentScore);\n            \n            if (delta > 0 || exp(delta / (temperature + 1e-9)) > (double)rng() / rng.max()) {\n                currentScore = newScore;\n                if (newScore > bestScore) {\n                    bestScore = newScore;\n                    memcpy(best_rotations, rotations, sizeof(int) * N * N);\n                }\n            } else {\n                rotations[i][j] = oldRot;\n            }\n        }\n        \n        iteration++;\n        // Exponential cooling schedule\n        temperature *= 0.9995;\n        \n        if (temperature < 0.01) break;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    string line;\n    for (int i = 0; i < N; i++) {\n        cin >> line;\n        for (int j = 0; j < N; j++) {\n            grid[i][j] = line[j] - '0';\n        }\n    }\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto start = chrono::steady_clock::now();\n    \n    long long bestScore = 0;\n    int best_rotations[N][N];\n    memset(best_rotations, 0, sizeof(best_rotations));\n    \n    // Try multiple starting configurations\n    for (int restart = 0; restart < 20; restart++) {\n        if (chrono::duration_cast<chrono::milliseconds>(\n                chrono::steady_clock::now() - start).count() > 1900) break;\n        \n        if (restart == 0) {\n            // Start with all zeros\n            memset(rotations, 0, sizeof(rotations));\n        } else {\n            // Random initialization\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    rotations[i][j] = rng() % 4;\n                }\n            }\n        }\n        \n        int remainingTime = 1900 - chrono::duration_cast<chrono::milliseconds>(\n                chrono::steady_clock::now() - start).count();\n        simulatedAnnealing(rng, bestScore, best_rotations, start, remainingTime / (20 - restart));\n    }\n    \n    memcpy(rotations, best_rotations, sizeof(rotations));\n    \n    string output(N * N, '0');\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            output[i * N + j] = '0' + rotations[i][j];\n        }\n    }\n    cout << output << endl;\n    \n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nchrono::high_resolution_clock::time_point start_time;\n\nbool hasEdge(const vector<vector<int>>& board, int i1, int j1, int i2, int j2) {\n    if (i2 < 0 || i2 >= N || j2 < 0 || j2 >= N) return false;\n    if (board[i1][j1] == 0 || board[i2][j2] == 0) return false;\n    \n    int dy = i2 - i1, dx = j2 - j1;\n    if (dy == -1 && dx == 0) return (board[i1][j1] & 2) && (board[i2][j2] & 8);\n    if (dy == 1 && dx == 0) return (board[i1][j1] & 8) && (board[i2][j2] & 2);\n    if (dy == 0 && dx == -1) return (board[i1][j1] & 1) && (board[i2][j2] & 4);\n    if (dy == 0 && dx == 1) return (board[i1][j1] & 4) && (board[i2][j2] & 1);\n    return false;\n}\n\nint largestTree(const vector<vector<int>>& board) {\n    vector<vector<int>> comp(N, vector<int>(N, -1));\n    vector<int> vcount, ecount;\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (board[i][j] == 0 || comp[i][j] != -1) continue;\n            \n            int cid = vcount.size();\n            vcount.push_back(0);\n            ecount.push_back(0);\n            \n            queue<pair<int,int>> q;\n            q.push({i, j});\n            comp[i][j] = cid;\n            \n            while (!q.empty()) {\n                auto [ci, cj] = q.front();\n                q.pop();\n                vcount[cid]++;\n                \n                int di[] = {-1, 1, 0, 0};\n                int dj[] = {0, 0, -1, 1};\n                for (int d = 0; d < 4; d++) {\n                    int ni = ci + di[d];\n                    int nj = cj + dj[d];\n                    if (ni >= 0 && ni < N && nj >= 0 && nj < N && \n                        board[ni][nj] != 0 && comp[ni][nj] == -1 &&\n                        hasEdge(board, ci, cj, ni, nj)) {\n                        comp[ni][nj] = cid;\n                        q.push({ni, nj});\n                    }\n                }\n            }\n        }\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            if (j + 1 < N && hasEdge(board, i, j, i, j+1) && comp[i][j] == comp[i][j+1]) {\n                ecount[comp[i][j]]++;\n            }\n            if (i + 1 < N && hasEdge(board, i, j, i+1, j) && comp[i][j] == comp[i+1][j]) {\n                ecount[comp[i][j]]++;\n            }\n        }\n    }\n    \n    int ans = 0;\n    for (size_t c = 0; c < vcount.size(); c++) {\n        if (ecount[c] == vcount[c] - 1) {\n            ans = max(ans, vcount[c]);\n        }\n    }\n    return ans;\n}\n\ndouble getElapsedTime() {\n    auto now = chrono::high_resolution_clock::now();\n    return chrono::duration<double>(now - start_time).count();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    start_time = chrono::high_resolution_clock::now();\n    srand(chrono::system_clock::now().time_since_epoch().count());\n    \n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    \n    int ei = 0, ej = 0;\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            int v = s[j] >= 'a' ? s[j] - 'a' + 10 : s[j] - '0';\n            board[i][j] = v;\n            if (v == 0) ei = i, ej = j;\n        }\n    }\n    \n    string result = \"\";\n    int best_tree = largestTree(board);\n    \n    int di[] = {-1, 1, 0, 0};\n    int dj[] = {0, 0, -1, 1};\n    char dirs[] = {'U', 'D', 'L', 'R'};\n    \n    int no_improve_count = 0;\n    int last_restart = 0;\n    double time_limit = 2.87;\n    \n    while ((int)result.length() < T && best_tree < N * N - 1 && getElapsedTime() < time_limit) {\n        vector<pair<int, int>> moves;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = ei + di[d];\n            int nj = ej + dj[d];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                swap(board[ei][ej], board[ni][nj]);\n                int score = largestTree(board);\n                swap(board[ei][ej], board[ni][nj]);\n                moves.push_back({score, d});\n            }\n        }\n        \n        if (moves.empty()) break;\n        \n        sort(moves.rbegin(), moves.rend());\n        \n        // More aggressive annealing: slower cooling\n        double progress = (double)result.length() / T;\n        double temperature = 20.0 * pow(1.0 - progress, 1.5); // slower decay than exp\n        \n        int selected_dir = moves[0].second;\n        int current_score = largestTree(board);\n        \n        // Better probabilistic selection with bias toward better moves\n        if (temperature > 0.01) {\n            double sum_weight = 0.0;\n            vector<double> weights;\n            \n            for (size_t i = 0; i < moves.size(); i++) {\n                int score = moves[i].first;\n                int direction = moves[i].second;\n                \n                // Stronger bias toward better moves\n                double delta = score - current_score;\n                double weight;\n                \n                if (delta > 0) {\n                    weight = (1.0 + delta * 0.1) * exp(delta / max(0.2, temperature));\n                } else {\n                    weight = exp(delta / max(0.2, temperature));\n                }\n                \n                weights.push_back(weight);\n                sum_weight += weight;\n            }\n            \n            double rand_val = (double)rand() / RAND_MAX * sum_weight;\n            for (size_t i = 0; i < moves.size(); i++) {\n                rand_val -= weights[i];\n                if (rand_val < 0) {\n                    selected_dir = moves[i].second;\n                    break;\n                }\n            }\n        }\n        \n        int ni = ei + di[selected_dir];\n        int nj = ej + dj[selected_dir];\n        swap(board[ei][ej], board[ni][nj]);\n        result += dirs[selected_dir];\n        ei = ni;\n        ej = nj;\n        \n        int new_tree = largestTree(board);\n        if (new_tree > best_tree) {\n            best_tree = new_tree;\n            no_improve_count = 0;\n            last_restart = result.length();\n        } else {\n            no_improve_count++;\n        }\n        \n        // More aggressive restart: happens earlier and does longer diversification\n        if (no_improve_count > max(60, N * N) && \n            (int)result.length() - last_restart > max(80, N * N * 2) &&\n            (int)result.length() < T - 150 && \n            getElapsedTime() < time_limit - 0.3) {\n            \n            // Extended random walk for diversification\n            int walk_len = min(80, (T - (int)result.length()) / 6);\n            for (int step = 0; step < walk_len; step++) {\n                vector<int> valid;\n                for (int d = 0; d < 4; d++) {\n                    if (ei + di[d] >= 0 && ei + di[d] < N && \n                        ej + dj[d] >= 0 && ej + dj[d] < N) {\n                        valid.push_back(d);\n                    }\n                }\n                if (valid.empty()) break;\n                \n                int d = valid[rand() % valid.size()];\n                swap(board[ei][ej], board[ei + di[d]][ej + dj[d]]);\n                ei += di[d];\n                ej += dj[d];\n                result += dirs[d];\n            }\n            \n            no_improve_count = 0;\n            last_restart = result.length();\n        }\n    }\n    \n    cout << result << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<tuple<long long, long long, long long, long long>> cuts;\nvector<pair<long long, long long>> berries;\n\nvoid recursivePartition(vector<int> indices, int depth) {\n    if (indices.size() <= 1 || (int)cuts.size() >= 100 || depth >= 15) return;\n    \n    // Find bounding box of strawberries in this region\n    long long minX = LLONG_MAX, maxX = LLONG_MIN;\n    long long minY = LLONG_MAX, maxY = LLONG_MIN;\n    \n    for (int i : indices) {\n        minX = min(minX, berries[i].first);\n        maxX = max(maxX, berries[i].first);\n        minY = min(minY, berries[i].second);\n        maxY = max(maxY, berries[i].second);\n    }\n    \n    long long rangeX = maxX - minX;\n    long long rangeY = maxY - minY;\n    \n    // If all strawberries are at the same point or very close, stop splitting\n    if (rangeX <= 1 && rangeY <= 1) return;\n    \n    vector<int> left, right;\n    \n    if (rangeX >= rangeY) {\n        // Make a vertical cut\n        long long cutX = (minX + maxX) / 2;\n        // Offset slightly to ensure we don't cut exactly on a strawberry center\n        if (rangeX > 0) cutX += 1;\n        \n        cuts.push_back({cutX, -1000000000LL, cutX, 1000000000LL});\n        \n        for (int i : indices) {\n            if (berries[i].first < cutX) {\n                left.push_back(i);\n            } else {\n                right.push_back(i);\n            }\n        }\n    } else {\n        // Make a horizontal cut\n        long long cutY = (minY + maxY) / 2;\n        if (rangeY > 0) cutY += 1;\n        \n        cuts.push_back({-1000000000LL, cutY, 1000000000LL, cutY});\n        \n        for (int i : indices) {\n            if (berries[i].second < cutY) {\n                left.push_back(i);\n            } else {\n                right.push_back(i);\n            }\n        }\n    }\n    \n    // Recursively partition left and right regions\n    if (!left.empty() && left.size() < indices.size()) {\n        recursivePartition(left, depth + 1);\n    }\n    if (!right.empty() && right.size() < indices.size()) {\n        recursivePartition(right, depth + 1);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, K;\n    cin >> N >> K;\n    \n    vector<int> a(11);\n    for (int d = 1; d <= 10; d++) {\n        cin >> a[d];\n    }\n    \n    berries.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> berries[i].first >> berries[i].second;\n    }\n    \n    // Start recursive partitioning with all indices\n    vector<int> allIndices;\n    for (int i = 0; i < N; i++) {\n        allIndices.push_back(i);\n    }\n    \n    recursivePartition(allIndices, 0);\n    \n    // Output cuts\n    cout << (int)cuts.size() << \"\\n\";\n    for (const auto& [px, py, qx, qy] : cuts) {\n        cout << px << \" \" << py << \" \" << qx << \" \" << qy << \"\\n\";\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nset<pair<int,int>> dots;\nset<tuple<int,int,int,int>> used_edges;\n\nbool is_valid_point(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_segment_clear(int x1, int y1, int x2, int y2) {\n    if (x1 == x2) {\n        int miny = min(y1, y2), maxy = max(y1, y2);\n        for (int y = miny + 1; y < maxy; y++) {\n            if (dots.count({x1, y})) return false;\n        }\n    } else if (y1 == y2) {\n        int minx = min(x1, x2), maxx = max(x1, x2);\n        for (int x = minx + 1; x < maxx; x++) {\n            if (dots.count({x, y1})) return false;\n        }\n    } else {\n        int dx = (x2 > x1) ? 1 : -1;\n        int dy = (y2 > y1) ? 1 : -1;\n        int x = x1 + dx, y = y1 + dy;\n        while (x != x2 || y != y2) {\n            if (dots.count({x, y})) return false;\n            x += dx; y += dy;\n        }\n    }\n    return true;\n}\n\nauto normalize_edge = [](int x1, int y1, int x2, int y2) {\n    if (x1 > x2 || (x1 == x2 && y1 > y2)) swap(x1, x2), swap(y1, y2);\n    return make_tuple(x1, y1, x2, y2);\n};\n\nbool check_edge_overlap(int x1, int y1, int x2, int y2) {\n    return used_edges.count(normalize_edge(x1, y1, x2, y2));\n}\n\nbool is_valid_rect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (dots.count({x1, y1})) return false;\n    if (!dots.count({x2, y2}) || !dots.count({x3, y3}) || !dots.count({x4, y4})) return false;\n    \n    if (!check_segment_clear(x1, y1, x2, y2) || !check_segment_clear(x2, y2, x3, y3) ||\n        !check_segment_clear(x3, y3, x4, y4) || !check_segment_clear(x4, y4, x1, y1)) \n        return false;\n    \n    if (check_edge_overlap(x1, y1, x2, y2) || check_edge_overlap(x2, y2, x3, y3) ||\n        check_edge_overlap(x3, y3, x4, y4) || check_edge_overlap(x4, y4, x1, y1))\n        return false;\n    \n    return true;\n}\n\nvoid record_rect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    used_edges.insert(normalize_edge(x1, y1, x2, y2));\n    used_edges.insert(normalize_edge(x2, y2, x3, y3));\n    used_edges.insert(normalize_edge(x3, y3, x4, y4));\n    used_edges.insert(normalize_edge(x4, y4, x1, y1));\n}\n\ndouble weight(int x, int y) {\n    double c = (N - 1) / 2.0;\n    return (x - c) * (x - c) + (y - c) * (y - c) + 1;\n}\n\nint main() {\n    cin >> N >> M;\n    \n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        dots.insert({x, y});\n    }\n    \n    vector<tuple<int,int,int,int,int,int,int,int>> ops;\n    auto start = chrono::high_resolution_clock::now();\n    \n    bool found = true;\n    while (found) {\n        auto now = chrono::high_resolution_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - start).count() > 4800) break;\n        \n        found = false;\n        int bx1 = -1, by1 = -1, bx2 = -1, by2 = -1, bx3 = -1, by3 = -1, bx4 = -1, by4 = -1;\n        double best_w = -1;\n        \n        vector<pair<int,int>> dot_list(dots.begin(), dots.end());\n        \n        for (int i = 0; i < (int)dot_list.size(); i++) {\n            for (int j = i + 1; j < (int)dot_list.size(); j++) {\n                for (int k = j + 1; k < (int)dot_list.size(); k++) {\n                    auto [x2, y2] = dot_list[i];\n                    auto [x3, y3] = dot_list[j];\n                    auto [x4, y4] = dot_list[k];\n                    \n                    set<int> xs = {x2, x3, x4}, ys = {y2, y3, y4};\n                    if (xs.size() == 2 && ys.size() == 2) {\n                        vector<int> xs_v(xs.begin(), xs.end()), ys_v(ys.begin(), ys.end());\n                        for (int x1 : xs_v) {\n                            for (int y1 : ys_v) {\n                                if (!dots.count({x1, y1})) {\n                                    vector<pair<int,int>> pts = {{x2,y2}, {x3,y3}, {x4,y4}};\n                                    for (int a = 0; a < 3; a++) {\n                                        for (int b = 0; b < 3; b++) {\n                                            if (a == b) continue;\n                                            int c = 3 - a - b;\n                                            if (is_valid_rect(x1, y1, pts[a].first, pts[a].second, \n                                                             pts[b].first, pts[b].second, \n                                                             pts[c].first, pts[c].second)) {\n                                                double w = weight(x1, y1);\n                                                if (w > best_w) {\n                                                    best_w = w;\n                                                    bx1 = x1; by1 = y1;\n                                                    bx2 = pts[a].first; by2 = pts[a].second;\n                                                    bx3 = pts[b].first; by3 = pts[b].second;\n                                                    bx4 = pts[c].first; by4 = pts[c].second;\n                                                }\n                                            }\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        if (best_w > 0) {\n            found = true;\n            dots.insert({bx1, by1});\n            record_rect(bx1, by1, bx2, by2, bx3, by3, bx4, by4);\n            ops.push_back({bx1, by1, bx2, by2, bx3, by3, bx4, by4});\n        }\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto [x1, y1, x2, y2, x3, y3, x4, y4] : ops) {\n        cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \" \"\n             << x3 << \" \" << y3 << \" \" << x4 << \" \" << y4 << \"\\n\";\n    }\n    \n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nint grid[10][10];\nvector<int> flavors;\n\nvoid place_candy(int pos, int flavor) {\n    int count = 0;\n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (grid[i][j] == 0) {\n                count++;\n                if (count == pos) {\n                    grid[i][j] = flavor;\n                    return;\n                }\n            }\n        }\n    }\n}\n\nvoid tilt(char dir, int target[10][10]) {\n    int temp[10][10];\n    memcpy(temp, grid, sizeof(grid));\n    memset(target, 0, sizeof(int) * 100);\n    \n    if (dir == 'F') {\n        for (int j = 0; j < 10; j++) {\n            vector<int> candies;\n            for (int i = 0; i < 10; i++) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t i = 0; i < candies.size(); i++) {\n                target[i][j] = candies[i];\n            }\n        }\n    } else if (dir == 'B') {\n        for (int j = 0; j < 10; j++) {\n            vector<int> candies;\n            for (int i = 9; i >= 0; i--) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t i = 0; i < candies.size(); i++) {\n                target[9 - i][j] = candies[i];\n            }\n        }\n    } else if (dir == 'L') {\n        for (int i = 0; i < 10; i++) {\n            vector<int> candies;\n            for (int j = 0; j < 10; j++) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t j = 0; j < candies.size(); j++) {\n                target[i][j] = candies[j];\n            }\n        }\n    } else if (dir == 'R') {\n        for (int i = 0; i < 10; i++) {\n            vector<int> candies;\n            for (int j = 9; j >= 0; j--) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t j = 0; j < candies.size(); j++) {\n                target[i][9 - j] = candies[j];\n            }\n        }\n    }\n}\n\nstruct Score {\n    long long sum_sq;\n    long long adjacency;\n    int num_singles;\n    int num_components;\n    \n    bool is_better_than(const Score& other) const {\n        if (sum_sq != other.sum_sq) return sum_sq > other.sum_sq;\n        if (adjacency != other.adjacency) return adjacency > other.adjacency;\n        if (num_singles != other.num_singles) return num_singles < other.num_singles;\n        return num_components < other.num_components;\n    }\n};\n\nScore compute_score(int test_grid[10][10]) {\n    bool visited[10][10] = {};\n    long long sum_sq = 0;\n    long long adjacency = 0;\n    int num_singles = 0;\n    int num_components = 0;\n    \n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (test_grid[i][j] > 0 && !visited[i][j]) {\n                int flavor = test_grid[i][j];\n                int component_size = 0;\n                \n                queue<pair<int, int>> q;\n                q.push({i, j});\n                visited[i][j] = true;\n                \n                while (!q.empty()) {\n                    auto [r, c] = q.front();\n                    q.pop();\n                    component_size++;\n                    \n                    int dr[] = {-1, 1, 0, 0};\n                    int dc[] = {0, 0, -1, 1};\n                    \n                    for (int d = 0; d < 4; d++) {\n                        int nr = r + dr[d];\n                        int nc = c + dc[d];\n                        if (nr >= 0 && nr < 10 && nc >= 0 && nc < 10 && \n                            test_grid[nr][nc] == flavor && !visited[nr][nc]) {\n                            visited[nr][nc] = true;\n                            q.push({nr, nc});\n                        }\n                    }\n                }\n                \n                sum_sq += (long long)component_size * component_size;\n                num_components++;\n                if (component_size == 1) num_singles++;\n            }\n        }\n    }\n    \n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (test_grid[i][j] > 0) {\n                if (i + 1 < 10 && test_grid[i+1][j] == test_grid[i][j]) adjacency++;\n                if (j + 1 < 10 && test_grid[i][j+1] == test_grid[i][j]) adjacency++;\n            }\n        }\n    }\n    \n    return {sum_sq, adjacency, num_singles, num_components};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    memset(grid, 0, sizeof(grid));\n    flavors.resize(100);\n    \n    for (int i = 0; i < 100; i++) {\n        cin >> flavors[i];\n    }\n    \n    for (int t = 0; t < 100; t++) {\n        int pos;\n        cin >> pos;\n        place_candy(pos, flavors[t]);\n        \n        if (t < 99) {\n            char dirs[] = {'F', 'B', 'L', 'R'};\n            Score best = {-1, -1, INT_MAX, INT_MAX};\n            char best_dir = 'F';\n            \n            for (int d = 0; d < 4; d++) {\n                int temp[10][10];\n                tilt(dirs[d], temp);\n                Score score = compute_score(temp);\n                \n                if (best.sum_sq == -1 || score.is_better_than(best)) {\n                    best = score;\n                    best_dir = dirs[d];\n                }\n            }\n            \n            cout << best_dir << \"\\n\";\n            cout.flush();\n            \n            int temp[10][10];\n            tilt(best_dir, temp);\n            memcpy(grid, temp, sizeof(grid));\n        }\n    }\n    \n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int M;\n    double eps;\n    cin >> M >> eps;\n    \n    // Choose N based on M to balance score (1/N factor) and discrimination ability\n    int N;\n    if (M <= 20) N = 10;\n    else if (M <= 50) N = 15;\n    else N = 20;\n    N = max(4, min(100, N));\n    \n    int max_edges = N * (N - 1) / 2;\n    \n    cout << N << endl;\n    cout.flush();\n    \n    // Compute target edge counts for each graph (evenly distributed)\n    vector<int> target(M);\n    for (int k = 0; k < M; k++) {\n        target[k] = k * max_edges / M;\n    }\n    \n    // Output the M graphs with different edge counts\n    for (int k = 0; k < M; k++) {\n        string graph(max_edges, '0');\n        // Add the first target[k] edges\n        for (int i = 0; i < target[k]; i++) {\n            graph[i] = '1';\n        }\n        cout << graph << endl;\n        cout.flush();\n    }\n    \n    // Process 100 queries\n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n        \n        // Count edges in received graph\n        int edge_count = count(H.begin(), H.end(), '1');\n        \n        // Find the target with closest edge count\n        int best = 0;\n        int best_dist = abs(edge_count - target[0]);\n        for (int k = 1; k < M; k++) {\n            int dist = abs(edge_count - target[k]);\n            if (dist < best_dist) {\n                best_dist = dist;\n                best = k;\n            }\n        }\n        \n        cout << best << endl;\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n    \n    vector<pair<long long, int>> weighted_edges;\n    \n    for(int i = 0; i < M; i++){\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        weighted_edges.push_back({w, i});\n    }\n    \n    for(int i = 0; i < N; i++){\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    // Sort edges by weight in descending order\n    sort(weighted_edges.rbegin(), weighted_edges.rend());\n    \n    vector<int> result(M);\n    // Priority queue: (accumulated_weight, day_number)\n    priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n    \n    for(int d = 1; d <= D; d++){\n        pq.push({0, d});\n    }\n    \n    // Assign each edge to the day with minimum accumulated weight\n    for(auto [w, idx] : weighted_edges){\n        auto [load, day] = pq.top();\n        pq.pop();\n        result[idx] = day;\n        pq.push({load + w, day});\n    }\n    \n    for(int i = 0; i < M; i++){\n        cout << result[i];\n        if(i + 1 < M) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef array<int, 3> Pos;\n\nint D;\n\nstruct Block {\n    set<Pos> voxels;\n    \n    Block() {}\n    Block(const set<Pos>& v) : voxels(v) {}\n    \n    void normalize() {\n        if (voxels.empty()) return;\n        int minx = INT_MAX, miny = INT_MAX, minz = INT_MAX;\n        for (auto [x, y, z] : voxels) {\n            minx = min(minx, x);\n            miny = min(miny, y);\n            minz = min(minz, z);\n        }\n        set<Pos> normalized;\n        for (auto [x, y, z] : voxels) {\n            normalized.insert({x - minx, y - miny, z - minz});\n        }\n        voxels = normalized;\n    }\n    \n    Block rotateX() const {\n        set<Pos> rotated;\n        for (auto [x, y, z] : voxels) {\n            rotated.insert({x, -z, y});\n        }\n        return Block(rotated);\n    }\n    \n    Block rotateY() const {\n        set<Pos> rotated;\n        for (auto [x, y, z] : voxels) {\n            rotated.insert({z, y, -x});\n        }\n        return Block(rotated);\n    }\n    \n    Block rotateZ() const {\n        set<Pos> rotated;\n        for (auto [x, y, z] : voxels) {\n            rotated.insert({-y, x, z});\n        }\n        return Block(rotated);\n    }\n    \n    bool operator<(const Block& other) const {\n        return voxels < other.voxels;\n    }\n    \n    bool operator==(const Block& other) const {\n        return voxels == other.voxels;\n    }\n};\n\nBlock getCanonicalForm(Block b) {\n    set<Block> allForms;\n    \n    for (int rx = 0; rx < 4; rx++) {\n        for (int ry = 0; ry < 4; ry++) {\n            for (int rz = 0; rz < 4; rz++) {\n                Block norm = b;\n                norm.normalize();\n                allForms.insert(norm);\n                b = b.rotateZ();\n            }\n            b = b.rotateY();\n        }\n        b = b.rotateX();\n    }\n    \n    return *allForms.begin();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D;\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    \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<int>>> grid1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> grid2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    \n    for (int x = 0; x < D; x++) {\n        for (int y = 0; y < D; y++) {\n            for (int z = 0; z < D; z++) {\n                if (f1[z][x] == '1' && r1[z][y] == '1') grid1[x][y][z] = 1;\n                if (f2[z][x] == '1' && r2[z][y] == '1') grid2[x][y][z] = 1;\n            }\n        }\n    }\n    \n    struct Component {\n        set<Pos> voxels;\n        Block canonical;\n    };\n    \n    auto extractComponents = [&](const vector<vector<vector<int>>>& grid) {\n        vector<Component> components;\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        \n        for (int x = 0; x < D; x++) {\n            for (int y = 0; y < D; y++) {\n                for (int z = 0; z < D; z++) {\n                    if (grid[x][y][z] == 1 && !visited[x][y][z]) {\n                        set<Pos> voxels;\n                        queue<Pos> q;\n                        q.push({x, y, z});\n                        visited[x][y][z] = true;\n                        \n                        while (!q.empty()) {\n                            auto [cx, cy, cz] = q.front();\n                            q.pop();\n                            voxels.insert({cx, cy, cz});\n                            \n                            int dx[] = {1, -1, 0, 0, 0, 0};\n                            int dy[] = {0, 0, 1, -1, 0, 0};\n                            int dz[] = {0, 0, 0, 0, 1, -1};\n                            \n                            for (int i = 0; i < 6; i++) {\n                                int nx = cx + dx[i], ny = cy + dy[i], nz = cz + dz[i];\n                                if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                    grid[nx][ny][nz] == 1 && !visited[nx][ny][nz]) {\n                                    visited[nx][ny][nz] = true;\n                                    q.push({nx, ny, nz});\n                                }\n                            }\n                        }\n                        \n                        Block block(voxels);\n                        block.normalize();\n                        Block canonical = getCanonicalForm(block);\n                        components.push_back({voxels, canonical});\n                    }\n                }\n            }\n        }\n        \n        return components;\n    };\n    \n    auto components1 = extractComponents(grid1);\n    auto components2 = extractComponents(grid2);\n    \n    int nextID = 1;\n    map<int, int> comp1ID, comp2ID;\n    vector<bool> used2(components2.size(), false);\n    \n    for (int i = 0; i < components1.size(); i++) {\n        int bestMatch = -1;\n        for (int j = 0; j < components2.size(); j++) {\n            if (!used2[j] && components1[i].canonical == components2[j].canonical) {\n                bestMatch = j;\n                break;\n            }\n        }\n        \n        if (bestMatch != -1) {\n            comp1ID[i] = nextID;\n            comp2ID[bestMatch] = nextID;\n            used2[bestMatch] = true;\n            nextID++;\n        } else {\n            comp1ID[i] = nextID++;\n        }\n    }\n    \n    for (int j = 0; j < components2.size(); j++) {\n        if (!used2[j]) {\n            comp2ID[j] = nextID++;\n        }\n    }\n    \n    vector<vector<vector<int>>> result1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> result2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    \n    for (int i = 0; i < components1.size(); i++) {\n        int bid = comp1ID[i];\n        for (auto [x, y, z] : components1[i].voxels) {\n            result1[x][y][z] = bid;\n        }\n    }\n    \n    for (int j = 0; j < components2.size(); j++) {\n        int bid = comp2ID[j];\n        for (auto [x, y, z] : components2[j].voxels) {\n            result2[x][y][z] = bid;\n        }\n    }\n    \n    cout << nextID - 1 << \"\\n\";\n    for (int x = 0; x < D; x++)\n        for (int y = 0; y < D; y++)\n            for (int z = 0; z < D; z++) {\n                if (x || y || z) cout << \" \";\n                cout << result1[x][y][z];\n            }\n    cout << \"\\n\";\n    for (int x = 0; x < D; x++)\n        for (int y = 0; y < D; y++)\n            for (int z = 0; z < D; z++) {\n                if (x || y || z) cout << \" \";\n                cout << result2[x][y][z];\n            }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc020":"#include<bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    double x, y;\n};\n\ndouble dist(Point a, Point b) {\n    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\nint N, M, K;\nvector<Point> stations;\nvector<pair<int,int>> edgeEndpoints;\nvector<long long> weights;\nvector<Point> residents;\n\nvector<bool> getReachable(const vector<bool>& enabled) {\n    vector<bool> reachable(N, false);\n    reachable[0] = true;\n    queue<int> q;\n    q.push(0);\n    while(!q.empty()){\n        int u = q.front();\n        q.pop();\n        for(int e = 0; e < M; e++){\n            if(!enabled[e]) continue;\n            int v = -1;\n            if(edgeEndpoints[e].first == u) v = edgeEndpoints[e].second;\n            else if(edgeEndpoints[e].second == u) v = edgeEndpoints[e].first;\n            if(v != -1 && !reachable[v]){\n                reachable[v] = true;\n                q.push(v);\n            }\n        }\n    }\n    return reachable;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    \n    stations.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> stations[i].x >> stations[i].y;\n    }\n    \n    edgeEndpoints.resize(M);\n    weights.resize(M);\n    for(int i = 0; i < M; i++){\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edgeEndpoints[i] = {u, v};\n        weights[i] = w;\n    }\n    \n    residents.resize(K);\n    for(int i = 0; i < K; i++){\n        cin >> residents[i].x >> residents[i].y;\n    }\n    \n    vector<long long> P(N, 0);\n    vector<bool> enabled(M, false);\n    \n    // Initial: cover nearby residents with station 0\n    for(int k = 0; k < K; k++){\n        long long d = (long long)round(dist(stations[0], residents[k]));\n        if(d <= 5000){\n            P[0] = max(P[0], d);\n        }\n    }\n    \n    // Greedy: add edges until all residents are covered\n    while(true) {\n        auto reachable = getReachable(enabled);\n        \n        // Find uncovered residents\n        set<int> uncovered;\n        for(int k = 0; k < K; k++){\n            bool covered = false;\n            for(int i = 0; i < N; i++){\n                if(reachable[i] && P[i] >= (long long)round(dist(stations[i], residents[k]))){\n                    covered = true;\n                    break;\n                }\n            }\n            if(!covered) uncovered.insert(k);\n        }\n        \n        if(uncovered.empty()) break;\n        \n        // Find best edge to enable\n        double bestScore = 1e18;\n        int bestEdge = -1;\n        int bestVertex = -1;\n        \n        for(int e = 0; e < M; e++){\n            if(enabled[e]) continue;\n            \n            int u = edgeEndpoints[e].first;\n            int v = edgeEndpoints[e].second;\n            \n            bool u_reach = reachable[u];\n            bool v_reach = reachable[v];\n            \n            if(!u_reach && !v_reach) continue;\n            \n            int newV = u_reach ? v : u;\n            \n            long long maxP = 0;\n            int covered = 0;\n            for(int k : uncovered){\n                long long d = (long long)round(dist(stations[newV], residents[k]));\n                if(d <= 5000){\n                    maxP = max(maxP, d);\n                    covered++;\n                }\n            }\n            \n            if(covered == 0) continue;\n            \n            long long cost = weights[e] + maxP * maxP;\n            double score = (double)cost / covered;\n            \n            if(score < bestScore){\n                bestScore = score;\n                bestEdge = e;\n                bestVertex = newV;\n            }\n        }\n        \n        if(bestEdge == -1) break;\n        \n        enabled[bestEdge] = true;\n        for(int k : uncovered){\n            long long d = (long long)round(dist(stations[bestVertex], residents[k]));\n            if(d <= 5000){\n                P[bestVertex] = max(P[bestVertex], d);\n            }\n        }\n    }\n    \n    // Optimize: assign each resident to closest reachable station\n    auto reachable = getReachable(enabled);\n    fill(P.begin(), P.end(), 0);\n    for(int k = 0; k < K; k++){\n        long long minDist = LLONG_MAX;\n        int bestV = -1;\n        for(int i = 0; i < N; i++){\n            if(reachable[i]){\n                long long d = (long long)round(dist(stations[i], residents[k]));\n                if(d < minDist){\n                    minDist = d;\n                    bestV = i;\n                }\n            }\n        }\n        if(bestV != -1) P[bestV] = max(P[bestV], minDist);\n    }\n    \n    // Output\n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << P[i];\n    }\n    cout << \"\\n\";\n    \n    for(int i = 0; i < M; i++){\n        if(i > 0) cout << \" \";\n        cout << (enabled[i] ? 1 : 0);\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 30;\n    vector<vector<int>> pyramid(N);\n    \n    // Read input\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    vector<tuple<int,int,int,int>> operations;\n    \n    // Build min-heap structure using heapify algorithm\n    // Process from second-to-last level upwards (bottom-up)\n    for (int x = N - 2; x >= 0; x--) {\n        for (int y = 0; y <= x; y++) {\n            // Sift down from position (x, y)\n            int curr_x = x, curr_y = y;\n            while (curr_x + 1 < N && (int)operations.size() < 10000) {\n                int parent_val = pyramid[curr_x][curr_y];\n                int left_child_val = pyramid[curr_x + 1][curr_y];\n                int right_child_val = pyramid[curr_x + 1][curr_y + 1];\n                \n                // If parent is smaller than both children, heap property satisfied\n                if (parent_val <= left_child_val && parent_val <= right_child_val) {\n                    break;\n                }\n                \n                // Swap with the smaller child\n                if (left_child_val <= right_child_val) {\n                    swap(pyramid[curr_x][curr_y], pyramid[curr_x + 1][curr_y]);\n                    operations.push_back({curr_x, curr_y, curr_x + 1, curr_y});\n                    curr_x++;\n                } else {\n                    swap(pyramid[curr_x][curr_y], pyramid[curr_x + 1][curr_y + 1]);\n                    operations.push_back({curr_x, curr_y, curr_x + 1, curr_y + 1});\n                    curr_x++;\n                    curr_y++;\n                }\n            }\n        }\n    }\n    \n    // Output result\n    cout << (int)operations.size() << \"\\n\";\n    for (auto [x1, y1, x2, y2] : operations) {\n        cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \"\\n\";\n    }\n    \n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int D, N;\n    cin >> D >> N;\n    \n    set<pair<int,int>> obstacles;\n    for(int i = 0; i < N; i++){\n        int r, c;\n        cin >> r >> c;\n        obstacles.insert({r, c});\n    }\n    \n    pair<int,int> entrance = {0, (D-1)/2};\n    int dr[] = {-1, 1, 0, 0};\n    int dc[] = {0, 0, -1, 1};\n    \n    // Place containers\n    map<pair<int,int>, int> container_at;\n    \n    for(int i = 0; i < D*D - 1 - N; i++){\n        int t;\n        cin >> t;\n        \n        // Find reachable empty squares in BFS order\n        vector<pair<int,int>> reachable_empty;\n        queue<pair<int,int>> q;\n        set<pair<int,int>> visited;\n        q.push(entrance);\n        visited.insert(entrance);\n        \n        while(!q.empty()){\n            auto [r, c] = q.front();\n            q.pop();\n            \n            if(!(r == 0 && c == (D-1)/2)){\n                reachable_empty.push_back({r, c});\n            }\n            \n            for(int dir = 0; dir < 4; dir++){\n                int nr = r + dr[dir];\n                int nc = c + dc[dir];\n                \n                if(nr >= 0 && nr < D && nc >= 0 && nc < D &&\n                   !visited.count({nr, nc}) &&\n                   !obstacles.count({nr, nc}) &&\n                   !container_at.count({nr, nc})){\n                    visited.insert({nr, nc});\n                    q.push({nr, nc});\n                }\n            }\n        }\n        \n        auto chosen = reachable_empty[0];\n        container_at[chosen] = t;\n        cout << chosen.first << \" \" << chosen.second << \"\\n\";\n        cout.flush();\n    }\n    \n    // Retrieve containers optimally\n    for(int extracted = 0; extracted < D*D - 1 - N; extracted++){\n        // Find all reachable container positions\n        set<pair<int,int>> reachable;\n        queue<pair<int,int>> q;\n        set<pair<int,int>> visited_empty;\n        q.push(entrance);\n        visited_empty.insert(entrance);\n        \n        while(!q.empty()){\n            auto [r, c] = q.front();\n            q.pop();\n            \n            for(int dir = 0; dir < 4; dir++){\n                int nr = r + dr[dir];\n                int nc = c + dc[dir];\n                \n                if(nr >= 0 && nr < D && nc >= 0 && nc < D &&\n                   !visited_empty.count({nr, nc}) &&\n                   !obstacles.count({nr, nc})){\n                    \n                    if(!container_at.count({nr, nc})){\n                        visited_empty.insert({nr, nc});\n                        q.push({nr, nc});\n                    } else {\n                        reachable.insert({nr, nc});\n                    }\n                }\n            }\n        }\n        \n        // Find reachable container with smallest number\n        pair<int,int> best_pos;\n        int best_num = INT_MAX;\n        for(auto& [pos, num] : container_at){\n            if(reachable.count(pos) && num < best_num){\n                best_num = num;\n                best_pos = pos;\n            }\n        }\n        \n        cout << best_pos.first << \" \" << best_pos.second << \"\\n\";\n        container_at.erase(best_pos);\n    }\n    \n    cout.flush();\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, m;\nint original[50][50];\nint current[50][50];\n\nvector<pair<int,int>> dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};\n\nbool isValid(int i, int j) {\n    return i >= 0 && i < N && j >= 0 && j < N;\n}\n\nbool isConnected(int color) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int,int>> q;\n    int count = 0;\n    pair<int,int> start = {-1, -1};\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(current[i][j] == color) {\n                count++;\n                if(start.first == -1) start = {i, j};\n            }\n        }\n    }\n    \n    if(count == 0) return true;\n    \n    q.push(start);\n    visited[start.first][start.second] = true;\n    int visited_count = 1;\n    \n    while(!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for(auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if(isValid(ni, nj) && !visited[ni][nj] && current[ni][nj] == color) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                visited_count++;\n            }\n        }\n    }\n    \n    return visited_count == count;\n}\n\nbool isConnected0() {\n    int count0 = 0;\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(current[i][j] == 0) count0++;\n        }\n    }\n    \n    if(count0 == 0) return true;\n    \n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int,int>> q;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if((i == 0 || i == N-1 || j == 0 || j == N-1) && current[i][j] == 0) {\n                q.push({i, j});\n                visited[i][j] = true;\n            }\n        }\n    }\n    \n    int visited_count = q.size();\n    \n    while(!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for(auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if(isValid(ni, nj) && !visited[ni][nj] && current[ni][nj] == 0) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                visited_count++;\n            }\n        }\n    }\n    \n    return visited_count == count0;\n}\n\nset<pair<int,int>> getAdjacencies() {\n    set<pair<int,int>> adj;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            for(auto [di, dj] : dirs) {\n                int ni = i + di, nj = j + dj;\n                if(isValid(ni, nj)) {\n                    int c1 = current[i][j], c2 = current[ni][nj];\n                    if(c1 != c2) {\n                        adj.insert({min(c1, c2), max(c1, c2)});\n                    }\n                }\n            }\n        }\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if((i == 0 || i == N-1 || j == 0 || j == N-1) && current[i][j] != 0) {\n                adj.insert({0, current[i][j]});\n            }\n        }\n    }\n    \n    return adj;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> m;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            cin >> original[i][j];\n            current[i][j] = original[i][j];\n        }\n    }\n    \n    auto orig_adj = getAdjacencies();\n    \n    bool improved = true;\n    \n    while(improved) {\n        improved = false;\n        \n        for(int i = 0; i < N; i++) {\n            for(int j = 0; j < N; j++) {\n                if(current[i][j] == 0) continue;\n                \n                int color = current[i][j];\n                \n                int color_count = 0;\n                for(int ii = 0; ii < N; ii++) {\n                    for(int jj = 0; jj < N; jj++) {\n                        if(current[ii][jj] == color) color_count++;\n                    }\n                }\n                if(color_count == 1) continue;\n                \n                bool is_boundary = (i == 0 || i == N-1 || j == 0 || j == N-1);\n                if(is_boundary) {\n                    int boundary_count = 0;\n                    for(int ii = 0; ii < N; ii++) {\n                        for(int jj = 0; jj < N; jj++) {\n                            if((ii == 0 || ii == N-1 || jj == 0 || jj == N-1) && current[ii][jj] == color) {\n                                boundary_count++;\n                            }\n                        }\n                    }\n                    if(boundary_count == 1) continue;\n                }\n                \n                current[i][j] = 0;\n                \n                if(isConnected(color) && isConnected0() && getAdjacencies() == orig_adj) {\n                    improved = true;\n                } else {\n                    current[i][j] = color;\n                }\n            }\n        }\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(j > 0) cout << \" \";\n            cout << current[i][j];\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, D, Q;\n    cin >> N >> D >> Q;\n    \n    map<pair<int,int>, int> cmp; // -1: <, 0: =, 1: >\n    \n    // Generate all unique pairs\n    vector<pair<int,int>> all_pairs;\n    for(int i = 0; i < N; i++){\n        for(int j = i+1; j < N; j++){\n            all_pairs.push_back({i, j});\n        }\n    }\n    \n    // Shuffle for variety\n    mt19937 rng(0);\n    shuffle(all_pairs.begin(), all_pairs.end(), rng);\n    \n    // Execute Q queries, avoiding duplicates\n    int q_done = 0;\n    for(int attempt = 0; q_done < Q; attempt++){\n        int idx = attempt % (int)all_pairs.size();\n        int i = all_pairs[idx].first;\n        int j = all_pairs[idx].second;\n        \n        if(cmp.count({i, j})) continue; // Skip if already queried\n        \n        cout << \"1 1 \" << i << \" \" << j << \"\\n\";\n        cout.flush();\n        \n        string result;\n        cin >> result;\n        \n        if(result == \"<\") cmp[{i,j}] = -1;\n        else if(result == \">\") cmp[{i,j}] = 1;\n        else cmp[{i,j}] = 0;\n        \n        q_done++;\n    }\n    \n    // Calculate item weights as scores based on comparisons\n    vector<long long> weight(N, 0);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(i == j) continue;\n            int a = min(i, j), b = max(i, j);\n            if(cmp.count({a, b})){\n                int c = cmp[{a, b}];\n                if(i < j){\n                    if(c == 1) weight[i]++;\n                    else if(c == -1) weight[i]--;\n                } else {\n                    if(c == 1) weight[i]--;\n                    else if(c == -1) weight[i]++;\n                }\n            }\n        }\n    }\n    \n    // Sort items by weight (descending) for First-Fit Decreasing\n    vector<pair<long long, int>> items;\n    for(int i = 0; i < N; i++){\n        items.push_back({weight[i], i});\n    }\n    sort(items.rbegin(), items.rend());\n    \n    // Greedy FFD partition: assign each item to the set with minimum current weight\n    vector<int> division(N);\n    vector<long long> set_weight(D, 0);\n    \n    for(auto [w, item] : items){\n        int best_set = 0;\n        for(int d = 1; d < D; d++){\n            if(set_weight[d] < set_weight[best_set]){\n                best_set = d;\n            }\n        }\n        division[item] = best_set;\n        set_weight[best_set] += w;\n    }\n    \n    // Output the division\n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << division[i];\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n  ios_base::sync_with_stdio(false);\n  cin.tie(nullptr);\n  \n  int n, m;\n  cin >> n >> m;\n  \n  vector<vector<int>> stacks(m);\n  \n  for(int i = 0; i < m; i++){\n    int s = n / m;\n    for(int j = 0; j < s; j++){\n      int x;\n      cin >> x;\n      stacks[i].push_back(x);\n    }\n  }\n  \n  vector<pair<int,int>> operations;\n  \n  for(int box = 1; box <= n; box++){\n    // Find which stack contains this box\n    int src_stack = -1;\n    \n    for(int i = 0; i < m; i++){\n      for(int j = 0; j < (int)stacks[i].size(); j++){\n        if(stacks[i][j] == box){\n          src_stack = i;\n          break;\n        }\n      }\n      if(src_stack != -1) break;\n    }\n    \n    // Move all boxes above this box away\n    while(stacks[src_stack].back() != box){\n      int top_box = stacks[src_stack].back();\n      \n      // Find best destination stack\n      // Priority 1: minimum size\n      // Priority 2: prefer empty stacks\n      // Priority 3: among non-empty of same size, prefer smaller top value\n      int dest_stack = -1;\n      int min_size = INT_MAX;\n      bool dest_empty = false;\n      int dest_top = INT_MAX;\n      \n      for(int i = 0; i < m; i++){\n        if(i == src_stack) continue;\n        \n        int cur_size = stacks[i].size();\n        bool cur_empty = stacks[i].empty();\n        int cur_top = cur_empty ? INT_MAX : stacks[i].back();\n        \n        bool better = false;\n        \n        if(cur_size < min_size){\n          better = true;\n        } else if(cur_size == min_size){\n          // Tie-break: prefer empty stacks\n          if(cur_empty && !dest_empty){\n            better = true;\n          }\n          // Tie-break: among non-empty, prefer smaller top\n          else if(!cur_empty && !dest_empty && cur_top < dest_top){\n            better = true;\n          }\n        }\n        \n        if(better){\n          dest_stack = i;\n          min_size = cur_size;\n          dest_empty = cur_empty;\n          dest_top = cur_top;\n        }\n      }\n      \n      // Move the top box to destination\n      stacks[dest_stack].push_back(top_box);\n      stacks[src_stack].pop_back();\n      \n      operations.push_back({top_box, dest_stack + 1});\n    }\n    \n    // Now box is at the top - extract it\n    operations.push_back({box, 0});\n    stacks[src_stack].pop_back();\n  }\n  \n  for(auto [v, i] : operations){\n    cout << v << \" \" << i << \"\\n\";\n  }\n  \n  return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\n\nint di[] = {0, 1, 0, -1};\nint dj[] = {1, 0, -1, 0};\nchar dir_char[] = {'R', 'D', 'L', 'U'};\n\ndouble simulate(const string& path) {\n    if (path.empty() || path.length() > 100000) return 1e18;\n    \n    int L = path.length();\n    vector<vector<long long>> dirt(N, vector<long long>(N, 0));\n    \n    int ci = 0, cj = 0;\n    long long sum = 0;\n    \n    for (int step = 0; step < 2 * L; step++) {\n        char c = path[step % L];\n        if (c == 'R') cj++;\n        else if (c == 'L') cj--;\n        else if (c == 'D') ci++;\n        else if (c == 'U') ci--;\n        \n        dirt[ci][cj] = 0;\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (i != ci || j != cj) {\n                    dirt[i][j] += d[i][j];\n                }\n            }\n        }\n        \n        if (step >= L) {\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    sum += dirt[i][j];\n                }\n            }\n        }\n    }\n    \n    return (double)sum / L;\n}\n\nvoid dfs(int i, int j, vector<vector<bool>>& visited, string& path, \n         function<int(int,int)> comparator) {\n    visited[i][j] = true;\n    \n    vector<pair<int, int>> moves;\n    \n    for (int dir = 0; dir < 4; dir++) {\n        int ni = i + di[dir];\n        int nj = j + dj[dir];\n        \n        if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj]) {\n            bool canMove = false;\n            if (dir == 0) canMove = (v[i][j] == '0');\n            else if (dir == 1) canMove = (h[i][j] == '0');\n            else if (dir == 2) canMove = (v[i][nj] == '0');\n            else canMove = (h[ni][j] == '0');\n            \n            if (canMove) {\n                moves.push_back({dir, comparator(ni, nj)});\n            }\n        }\n    }\n    \n    sort(moves.begin(), moves.end(), \n         [](const pair<int,int> &a, const pair<int,int> &b) { \n             return a.second > b.second; \n         });\n    \n    for (const auto &[dir, _] : moves) {\n        int ni = i + di[dir];\n        int nj = j + dj[dir];\n        \n        path += dir_char[dir];\n        dfs(ni, nj, visited, path, comparator);\n        path += dir_char[(dir + 2) % 4];\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    \n    h.resize(N-1);\n    v.resize(N);\n    d.resize(N, vector<int>(N));\n    \n    for (int i = 0; i < N-1; i++) cin >> h[i];\n    for (int i = 0; i < N; i++) cin >> v[i];\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n        }\n    }\n    \n    double best_score = 1e18;\n    string best_path;\n    \n    int cm = N / 2;\n    \n    vector<function<int(int,int)>> strategies = {\n        [](int i, int j) { return -d[i][j]; },                                    // Low-d\n        [](int i, int j) { return d[i][j]; },                                     // High-d\n        [](int i, int j) { return -(abs(i) + abs(j)); },                          // Near start\n        [](int i, int j) { return abs(i) + abs(j); },                             // Far from start\n        [cm](int i, int j) { return -(abs(i - cm) + abs(j - cm)); },              // Near center\n        [cm](int i, int j) { return abs(i - cm) + abs(j - cm); },                 // Far from center\n        [](int i, int j) { return -(d[i][j] * 1000 + abs(i) + abs(j)); },         // Low-d + near start\n        [](int i, int j) { return -(d[i][j] * 1000 - abs(i) - abs(j)); },         // Low-d + far from start\n        [](int i, int j) { return d[i][j] * 1000 - abs(i) - abs(j); },            // High-d + far from start\n        [cm](int i, int j) { return -(d[i][j] * 1000 + abs(i - cm) + abs(j - cm)); },  // Low-d + near center\n        [cm](int i, int j) { return d[i][j] * 1000 - abs(i - cm) - abs(j - cm); },     // High-d + far from center\n        [](int i, int j) { return -(d[i][j] * 100 + (abs(i) + abs(j)) * 10); },   // Weighted low-d + distance\n        [](int i, int j) { return -(d[i][j] * 10 + (abs(i) + abs(j)) * 100); },   // Weighted d (low priority) + high distance\n        [cm](int i, int j) { return -(d[i][j] * 100 + (abs(i - cm) + abs(j - cm)) * 10); },  // Center variant 1\n        [cm](int i, int j) { return -(d[i][j] * 10 + (abs(i - cm) + abs(j - cm)) * 100); },  // Center variant 2\n        [](int i, int j) { return -(d[i][j] * 100 - (abs(i) + abs(j)) * 5); },    // Low-d but prefer further\n        [](int i, int j) { return d[i][j] * 100 + (abs(i) + abs(j)) * 5; },       // High-d + near start\n        [cm](int i, int j) { return -(d[i][j] * 50 + abs(i - cm) + abs(j - cm)); }, // Balanced center\n        [](int i, int j) { return -d[i][j] * 50 - abs(i) - abs(j); },             // Balanced start\n        [cm](int i, int j) { int a = abs(i-cm) + abs(j-cm); return -(d[i][j] * 1000 + a * a); }, // Quadratic center\n    };\n    \n    for (const auto& strategy : strategies) {\n        string path;\n        vector<vector<bool>> visited(N, vector<bool>(N, false));\n        dfs(0, 0, visited, path, strategy);\n        double score = simulate(path);\n        if (score < best_score) {\n            best_score = score;\n            best_path = path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nint si, sj;\nvector<string> grid;\nvector<string> words;\nmap<char, vector<pair<int, int>>> charPos;\n\nint getOverlap(const string& a, const string& b) {\n    int maxOverlap = 0;\n    int maxLen = min((int)a.size(), (int)b.size());\n    for (int o = 1; o <= maxLen; o++) {\n        bool match = true;\n        for (int i = 0; i < o; i++) {\n            if (a[a.size() - o + i] != b[i]) {\n                match = false;\n                break;\n            }\n        }\n        if (match) maxOverlap = o;\n    }\n    return maxOverlap;\n}\n\nstring buildSuperstring(const vector<int>& order) {\n    string result = words[order[0]];\n    for (int i = 1; i < (int)order.size(); i++) {\n        int overlap = getOverlap(words[order[i-1]], words[order[i]]);\n        result += words[order[i]].substr(overlap);\n    }\n    return result;\n}\n\nlong long calculateCost(const string& superstring) {\n    long long cost = 0;\n    int ci = si, cj = sj;\n    \n    for (int pos = 0; pos < (int)superstring.size(); pos++) {\n        char c = superstring[pos];\n        \n        int bestI = -1, bestJ = -1;\n        double minTotalCost = 1e18;\n        \n        for (auto [ii, jj] : charPos[c]) {\n            double moveCost = abs(ii - ci) + abs(jj - cj);\n            double lookCost = 0;\n            \n            // Light 2-step lookahead\n            if (pos + 1 < (int)superstring.size()) {\n                char next = superstring[pos + 1];\n                int nextMinDist = INT_MAX;\n                for (auto [ni, nj] : charPos[next]) {\n                    nextMinDist = min(nextMinDist, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist * 0.25;\n            }\n            if (pos + 2 < (int)superstring.size()) {\n                char next2 = superstring[pos + 2];\n                int nextMinDist2 = INT_MAX;\n                for (auto [ni, nj] : charPos[next2]) {\n                    nextMinDist2 = min(nextMinDist2, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist2 * 0.08;\n            }\n            \n            double totalCost = moveCost + lookCost;\n            if (totalCost < minTotalCost) {\n                minTotalCost = totalCost;\n                bestI = ii;\n                bestJ = jj;\n            }\n        }\n        \n        cost += abs(bestI - ci) + abs(bestJ - cj) + 1;\n        ci = bestI;\n        cj = bestJ;\n    }\n    return cost;\n}\n\nvector<int> greedyOrder(int startWord) {\n    vector<int> order;\n    set<int> used;\n    order.push_back(startWord);\n    used.insert(startWord);\n    \n    while ((int)used.size() < M) {\n        int lastWord = order.back();\n        int bestWord = -1;\n        int bestOverlap = -1;\n        \n        for (int w = 0; w < M; w++) {\n            if (used.count(w)) continue;\n            int ov = getOverlap(words[lastWord], words[w]);\n            if (ov > bestOverlap) {\n                bestOverlap = ov;\n                bestWord = w;\n            }\n        }\n        \n        if (bestWord == -1) {\n            for (int w = 0; w < M; w++) {\n                if (!used.count(w)) {\n                    bestWord = w;\n                    break;\n                }\n            }\n        }\n        \n        order.push_back(bestWord);\n        used.insert(bestWord);\n    }\n    return order;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    cin >> si >> sj;\n    \n    grid.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    \n    words.resize(M);\n    for (int i = 0; i < M; i++) {\n        cin >> words[i];\n    }\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            charPos[grid[i][j]].push_back({i, j});\n        }\n    }\n    \n    string bestSuperstring;\n    long long bestCost = LLONG_MAX;\n    \n    // Try only 2 starting points\n    vector<int> starts = {0, M / 2};\n    for (int start : starts) {\n        auto order = greedyOrder(start);\n        auto superstring = buildSuperstring(order);\n        auto cost = calculateCost(superstring);\n        if (cost < bestCost) {\n            bestCost = cost;\n            bestSuperstring = superstring;\n        }\n    }\n    \n    // Generate output with same lookahead strategy\n    vector<pair<int, int>> operations;\n    int ci = si, cj = sj;\n    \n    for (int pos = 0; pos < (int)bestSuperstring.size(); pos++) {\n        char c = bestSuperstring[pos];\n        \n        int bestI = -1, bestJ = -1;\n        double minTotalCost = 1e18;\n        \n        for (auto [ii, jj] : charPos[c]) {\n            double moveCost = abs(ii - ci) + abs(jj - cj);\n            double lookCost = 0;\n            \n            if (pos + 1 < (int)bestSuperstring.size()) {\n                char next = bestSuperstring[pos + 1];\n                int nextMinDist = INT_MAX;\n                for (auto [ni, nj] : charPos[next]) {\n                    nextMinDist = min(nextMinDist, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist * 0.25;\n            }\n            if (pos + 2 < (int)bestSuperstring.size()) {\n                char next2 = bestSuperstring[pos + 2];\n                int nextMinDist2 = INT_MAX;\n                for (auto [ni, nj] : charPos[next2]) {\n                    nextMinDist2 = min(nextMinDist2, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist2 * 0.08;\n            }\n            \n            double totalCost = moveCost + lookCost;\n            if (totalCost < minTotalCost) {\n                minTotalCost = totalCost;\n                bestI = ii;\n                bestJ = jj;\n            }\n        }\n        \n        operations.push_back({bestI, bestJ});\n        ci = bestI;\n        cj = bestJ;\n    }\n    \n    for (auto [i, j] : operations) {\n        cout << i << \" \" << j << \"\\n\";\n    }\n    \n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n    \n    // Read field shapes\n    vector<vector<pair<int, int>>> fields(M);\n    for (int k = 0; k < M; k++) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < d; i++) {\n            int r, c;\n            cin >> r >> c;\n            fields[k].push_back({r, c});\n        }\n    }\n    \n    // Drill all squares to identify which have oil reserves\n    vector<pair<int, int>> oil_squares;\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            // Drill this square\n            cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n            cout.flush();\n            \n            int oil_value;\n            cin >> oil_value;\n            \n            // Record if this square has oil\n            if (oil_value > 0) {\n                oil_squares.push_back({i, j});\n            }\n        }\n    }\n    \n    // Output answer: all squares with v(i,j) > 0\n    cout << \"a \" << oil_squares.size();\n    for (auto [i, j] : oil_squares) {\n        cout << \" \" << i << \" \" << j;\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    // Read verification result\n    int is_correct;\n    cin >> is_correct;\n    \n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<long long>> a(D, vector<long long>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    for (int d = 0; d < D; d++) {\n        // Compute heights if we stack rectangles vertically with full width W\n        vector<long long> heights(N);\n        long long total_height = 0;\n        \n        for (int k = 0; k < N; k++) {\n            heights[k] = (a[d][k] + W - 1) / W;  // Ceiling division\n            total_height += heights[k];\n        }\n        \n        if (total_height <= W) {\n            // Use efficient column packing\n            long long y = 0;\n            for (int k = 0; k < N; k++) {\n                long long y_next = y + heights[k];\n                cout << y << \" \" << 0 << \" \" << y_next << \" \" << W << \"\\n\";\n                y = y_next;\n            }\n        } else {\n            // Fall back to fixed row allocation (guaranteed to fit)\n            for (int k = 0; k < N; k++) {\n                cout << k << \" \" << 0 << \" \" << k + 1 << \" \" << W << \"\\n\";\n            }\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long MOD = 998244353;\n\nint N, M, K;\nvector<vector<vector<long long>>> stamps;\nvector<long long> stamp_total;\n\nlong long calculate_score(const vector<vector<long long>>& board) {\n    long long score = 0;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            score += board[i][j] % MOD;\n        }\n    }\n    return score;\n}\n\nlong long delta_score(const vector<vector<long long>>& board, int m, int p, int q) {\n    long long delta = 0;\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            int ni = p + i, nj = q + j;\n            long long old_mod = board[ni][nj] % MOD;\n            long long new_mod = (board[ni][nj] + stamps[m][i][j]) % MOD;\n            delta += new_mod - old_mod;\n        }\n    }\n    return delta;\n}\n\nvoid apply_operation(vector<vector<long long>>& board, int m, int p, int q) {\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            board[p+i][q+j] += stamps[m][i][j];\n        }\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    \n    vector<vector<long long>> initial_board(N, vector<long long>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> initial_board[i][j];\n        }\n    }\n    \n    stamps.assign(M, vector<vector<long long>>(3, vector<long long>(3)));\n    stamp_total.assign(M, 0);\n    \n    for(int m = 0; m < M; m++){\n        for(int i = 0; i < 3; i++){\n            for(int j = 0; j < 3; j++){\n                cin >> stamps[m][i][j];\n                stamp_total[m] += stamps[m][i][j];\n            }\n        }\n    }\n    \n    long long best_score = calculate_score(initial_board);\n    vector<tuple<int, int, int>> best_operations;\n    \n    // Run 120 trials with varying strategies\n    for(int trial = 0; trial < 120; trial++){\n        mt19937 rng(trial * 31337 + 999983);\n        \n        auto board = initial_board;\n        vector<tuple<int, int, int>> operations;\n        \n        // Variable initialization: ensure diversity across trials\n        int init_random = ((trial * 13) % (K / 2)) + (trial < 40 ? 0 : K / 3);\n        init_random = min(init_random, K - 10);\n        \n        // Initial random phase\n        for(int i = 0; i < init_random; i++){\n            int m;\n            // Higher bias toward good stamps in earlier trials\n            if(trial < 40 && rng() % 4 == 0) {\n                m = max_element(stamp_total.begin(), stamp_total.end()) - stamp_total.begin();\n            } else {\n                m = rng() % M;\n            }\n            int p = rng() % (N - 2);\n            int q = rng() % (N - 2);\n            apply_operation(board, m, p, q);\n            operations.push_back({m, p, q});\n        }\n        \n        // Greedy phase with intelligent escape\n        int consecutive_stuck = 0;\n        \n        while((int)operations.size() < K && consecutive_stuck < 18){\n            vector<pair<long long, tuple<int, int, int>>> moves;\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                        long long d = delta_score(board, m, p, q);\n                        moves.push_back({d, {m, p, q}});\n                    }\n                }\n            }\n            \n            sort(moves.rbegin(), moves.rend());\n            \n            if(moves[0].first > 0){\n                // Found improving move - take it\n                consecutive_stuck = 0;\n                auto [d, op] = moves[0];\n                auto [m, p, q] = op;\n                apply_operation(board, m, p, q);\n                operations.push_back({m, p, q});\n            } else {\n                // Stuck in local optimum - escape intelligently\n                consecutive_stuck++;\n                if((int)operations.size() < K){\n                    // Pick from top moves (even if negative) with bias toward better ones\n                    int top_k = min(40, (int)moves.size());\n                    int idx = rng() % top_k;\n                    auto [d, op] = moves[idx];\n                    auto [m, p, q] = op;\n                    apply_operation(board, m, p, q);\n                    operations.push_back({m, p, q});\n                }\n            }\n        }\n        \n        long long score = calculate_score(board);\n        if(score > best_score){\n            best_score = score;\n            best_operations = operations;\n        }\n    }\n    \n    // Final greedy refinement on best solution found\n    if((int)best_operations.size() < K) {\n        auto board = initial_board;\n        for(auto [m, p, q] : best_operations){\n            apply_operation(board, m, p, q);\n        }\n        \n        int refinement_stuck = 0;\n        while((int)best_operations.size() < K && refinement_stuck < 8){\n            long long best_delta = 0;\n            int best_m = -1, best_p = -1, best_q = -1;\n            \n            for(int m = 0; m < M; m++){\n                for(int p = 0; p <= N - 3; p++){\n                    for(int q = 0; q <= N - 3; q++){\n                        long long d = delta_score(board, m, p, q);\n                        if(d > best_delta){\n                            best_delta = d;\n                            best_m = m;\n                            best_p = p;\n                            best_q = q;\n                        }\n                    }\n                }\n            }\n            \n            if(best_m != -1){\n                refinement_stuck = 0;\n                apply_operation(board, best_m, best_p, best_q);\n                best_operations.push_back({best_m, best_p, best_q});\n            } else {\n                refinement_stuck++;\n            }\n        }\n    }\n    \n    cout << best_operations.size() << \"\\n\";\n    for(auto [m, p, q] : best_operations){\n        cout << m << \" \" << p << \" \" << q << \"\\n\";\n    }\n    \n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<vector<int>> grid;\nvector<pair<int,int>> pos;\nvector<int> carry;\nvector<int> active;\n\nint main(){\n    cin >> N;\n    \n    vector<vector<int>> A(N, vector<int>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> A[i][j];\n        }\n    }\n    \n    grid.assign(N, vector<int>(N, -1));\n    pos.resize(N);\n    carry.assign(N, -1);\n    active.assign(N, 1);\n    \n    for(int i = 0; i < N; i++) pos[i] = {i, 0};\n    \n    vector<int> next_in(N, 0);\n    vector<string> res(N, \"\");\n    \n    for(int t = 0; t < 10000; t++){\n        // Step 1: Place arriving containers\n        for(int i = 0; i < N; i++){\n            if(next_in[i] < N && grid[i][0] == -1){\n                bool blocked = false;\n                for(int k = 0; k < N; k++){\n                    if(active[k] && pos[k].first == i && pos[k].second == 0 && carry[k] != -1){\n                        blocked = true;\n                    }\n                }\n                if(!blocked){\n                    grid[i][0] = A[i][next_in[i]];\n                    next_in[i]++;\n                }\n            }\n        }\n        \n        // Step 2: Cranes perform actions\n        vector<char> act(N);\n        vector<pair<int,int>> new_pos(N);\n        \n        // Decide actions for each crane\n        for(int k = 0; k < N; k++){\n            if(!active[k]){\n                act[k] = '.';\n                new_pos[k] = pos[k];\n                continue;\n            }\n            \n            auto [r, c] = pos[k];\n            \n            if(carry[k] >= 0){\n                // Carrying container - move to dispatch gate\n                int tr = carry[k] / N;\n                int tc = N - 1;\n                \n                if(r == tr && c == tc){\n                    act[k] = 'Q';\n                    new_pos[k] = {r, c};\n                } else if(c < tc){\n                    act[k] = 'R';\n                    new_pos[k] = {r, c+1};\n                } else if(r < tr){\n                    act[k] = 'D';\n                    new_pos[k] = {r+1, c};\n                } else {\n                    act[k] = 'U';\n                    new_pos[k] = {r-1, c};\n                }\n            } else {\n                // Try to pick or move left\n                if(grid[r][c] >= 0){\n                    act[k] = 'P';\n                    new_pos[k] = {r, c};\n                } else if(c > 0){\n                    act[k] = 'L';\n                    new_pos[k] = {r, c-1};\n                } else {\n                    act[k] = '.';\n                    new_pos[k] = {r, c};\n                }\n            }\n        }\n        \n        // Validate movements iteratively\n        bool changed = true;\n        while(changed){\n            changed = false;\n            \n            // Check mutual collision (two cranes to same destination)\n            map<pair<int,int>, vector<int>> dests;\n            for(int k = 0; k < N; k++){\n                if(active[k] && act[k] != 'P' && act[k] != 'Q' && act[k] != '.'){\n                    dests[new_pos[k]].push_back(k);\n                }\n            }\n            \n            for(auto& [d, cranes] : dests){\n                if(cranes.size() > 1){\n                    for(int k : cranes){\n                        act[k] = '.';\n                        new_pos[k] = pos[k];\n                        changed = true;\n                    }\n                }\n            }\n            \n            // Check swaps (two cranes exchanging positions)\n            for(int k = 0; k < N; k++){\n                if(!active[k] || (act[k] == 'P' || act[k] == 'Q' || act[k] == '.')) continue;\n                for(int m = k+1; m < N; m++){\n                    if(!active[m] || (act[m] == 'P' || act[m] == 'Q' || act[m] == '.')) continue;\n                    if(new_pos[k] == pos[m] && new_pos[m] == pos[k]){\n                        act[k] = '.';\n                        act[m] = '.';\n                        new_pos[k] = pos[k];\n                        new_pos[m] = pos[m];\n                        changed = true;\n                    }\n                }\n            }\n            \n            // Check blocking (moving to square with stationary crane)\n            for(int k = 0; k < N; k++){\n                if(!active[k] || (act[k] == 'P' || act[k] == 'Q' || act[k] == '.')) continue;\n                for(int m = 0; m < N; m++){\n                    if(!active[m] || m == k) continue;\n                    if(act[m] == 'P' || act[m] == 'Q' || act[m] == '.'){\n                        if(new_pos[k] == pos[m]){\n                            act[k] = '.';\n                            new_pos[k] = pos[k];\n                            changed = true;\n                        }\n                    }\n                }\n            }\n            \n            // Check small crane constraint\n            for(int k = 1; k < N; k++){\n                if(!active[k] || carry[k] == -1) continue;\n                if(act[k] != 'P' && act[k] != 'Q' && act[k] != '.'){\n                    if(grid[new_pos[k].first][new_pos[k].second] >= 0){\n                        act[k] = '.';\n                        new_pos[k] = pos[k];\n                        changed = true;\n                    }\n                }\n            }\n        }\n        \n        // Apply P actions\n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] == 'P'){\n                if(carry[k] == -1 && grid[pos[k].first][pos[k].second] >= 0){\n                    carry[k] = grid[pos[k].first][pos[k].second];\n                    grid[pos[k].first][pos[k].second] = -1;\n                } else {\n                    act[k] = '.';\n                }\n            }\n        }\n        \n        // Apply movements\n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] != 'P' && act[k] != 'Q' && act[k] != '.' && act[k] != 'B'){\n                pos[k] = new_pos[k];\n            }\n        }\n        \n        // Apply Q actions\n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] == 'Q'){\n                if(carry[k] >= 0 && grid[pos[k].first][pos[k].second] == -1){\n                    grid[pos[k].first][pos[k].second] = carry[k];\n                    carry[k] = -1;\n                } else {\n                    act[k] = '.';\n                }\n            }\n        }\n        \n        // Apply B actions\n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] == 'B'){\n                if(carry[k] == -1){\n                    active[k] = 0;\n                } else {\n                    act[k] = '.';\n                }\n            }\n        }\n        \n        for(int k = 0; k < N; k++) res[k] += act[k];\n        \n        // Step 3: Dispatch\n        for(int i = 0; i < N; i++){\n            if(grid[i][N-1] >= 0) grid[i][N-1] = -1;\n        }\n    }\n    \n    for(int i = 0; i < N; i++){\n        cout << res[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    \n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h[i][j];\n        }\n    }\n    \n    vector<string> operations;\n    int x = 0, y = 0;\n    int load = 0;\n    \n    auto move_to = [&](int nx, int ny) {\n        while (x != nx) {\n            operations.push_back(x < nx ? \"D\" : \"U\");\n            x += (x < nx ? 1 : -1);\n        }\n        while (y != ny) {\n            operations.push_back(y < ny ? \"R\" : \"L\");\n            y += (y < ny ? 1 : -1);\n        }\n    };\n    \n    // Single-pass greedy: load from positive, unload to negative as we go\n    for (int i = 0; i < N; i++) {\n        if (i % 2 == 0) {\n            // Left to right\n            for (int j = 0; j < N; j++) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    operations.push_back(\"+\" + to_string(h[i][j]));\n                    load += h[i][j];\n                } else if (h[i][j] < 0) {\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                    }\n                }\n            }\n        } else {\n            // Right to left\n            for (int j = N - 1; j >= 0; j--) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    operations.push_back(\"+\" + to_string(h[i][j]));\n                    load += h[i][j];\n                } else if (h[i][j] < 0) {\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                    }\n                }\n            }\n        }\n    }\n    \n    // Second pass: handle remaining unsatisfied negatives (if any)\n    for (int i = 0; i < N; i++) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; j++) {\n                if (h[i][j] < 0 && load > 0) {\n                    move_to(i, j);\n                    // Check if we still have unloaded deficit\n                    // This handles edge cases where single pass wasn't enough\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                    }\n                }\n            }\n        } else {\n            for (int j = N - 1; j >= 0; j--) {\n                if (h[i][j] < 0 && load > 0) {\n                    move_to(i, j);\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                    }\n                }\n            }\n        }\n    }\n    \n    for (const auto& op : operations) {\n        cout << op << \"\\n\";\n    }\n    \n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <set>\n\nusing namespace std;\n\nint main() {\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> X(seed_count, vector<int>(M));\n\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> X[i][j];\n        }\n    }\n\n    // Precompute grid positions ordered by neighbor count (interior first)\n    vector<pair<int, int>> position_order;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            position_order.push_back({i, j});\n        }\n    }\n    \n    sort(position_order.begin(), position_order.end(), [&](const auto& a, const auto& b) {\n        auto neighbor_count = [&](const pair<int,int>& p) {\n            return (p.first > 0) + (p.first < N-1) + (p.second > 0) + (p.second < N-1);\n        };\n        return neighbor_count(a) > neighbor_count(b);\n    });\n\n    for (int t = 0; t < T; t++) {\n        // Calculate total value for each seed\n        vector<long long> values(seed_count, 0);\n        \n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                values[i] += X[i][j];\n            }\n        }\n        \n        // Select seeds with criterion diversity (top 2 per criterion)\n        set<int> selected_set;\n        \n        for (int crit = 0; crit < M; crit++) {\n            vector<int> seeds_for_crit(seed_count);\n            iota(seeds_for_crit.begin(), seeds_for_crit.end(), 0);\n            sort(seeds_for_crit.begin(), seeds_for_crit.end(), [&](int a, int b) {\n                if (X[a][crit] != X[b][crit]) {\n                    return X[a][crit] > X[b][crit];\n                }\n                return values[a] > values[b];  // Tiebreaker: total value\n            });\n            \n            for (int i = 0; i < 2 && i < seed_count && selected_set.size() < (size_t)(N * N); i++) {\n                selected_set.insert(seeds_for_crit[i]);\n            }\n        }\n        \n        // Fill remaining slots with highest total-value seeds\n        vector<int> sorted_by_value(seed_count);\n        iota(sorted_by_value.begin(), sorted_by_value.end(), 0);\n        sort(sorted_by_value.begin(), sorted_by_value.end(), [&](int a, int b) {\n            return values[a] > values[b];\n        });\n        \n        for (int seed_id : sorted_by_value) {\n            if (selected_set.size() >= (size_t)(N * N)) break;\n            selected_set.insert(seed_id);\n        }\n\n        // Convert to vector and CRITICAL: sort by total value before assignment\n        vector<int> selected_seeds(selected_set.begin(), selected_set.end());\n        sort(selected_seeds.begin(), selected_seeds.end(), [&](int a, int b) {\n            return values[a] > values[b];\n        });\n\n        // Assign highest-value seeds to highest-neighbor positions\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (size_t idx = 0; idx < selected_seeds.size(); idx++) {\n            int seed_id = selected_seeds[idx];\n            int pos_i = position_order[idx].first;\n            int pos_j = position_order[idx].second;\n            grid[pos_i][pos_j] = seed_id;\n        }\n\n        // Output grid\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (j > 0) cout << \" \";\n                cout << grid[i][j];\n            }\n            cout << \"\\n\";\n        }\n        cout.flush();\n\n        // Read new generation seeds\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> X[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, V;\n    cin >> N >> M >> V;\n    \n    vector<string> s(N), t(N);\n    for(int i = 0; i < N; i++) cin >> s[i];\n    for(int i = 0; i < N; i++) cin >> t[i];\n    \n    cout << \"2\\n\";\n    cout << \"0 1\\n\";\n    cout << \"0 0\\n\";\n    \n    int rx = 0, ry = 0;\n    int rot = 0; // 0=right, 1=down, 2=left, 3=up\n    int turns = 0;\n    \n    // Track state\n    vector<vector<int>> grid(N, vector<int>(N, 0));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            grid[i][j] = (s[i][j] == '1') ? 1 : 0;\n        }\n    }\n    \n    auto get_finger = [&]() -> pair<int,int> {\n        if(rot == 0) return {rx, ry + 1};\n        if(rot == 1) return {rx + 1, ry};\n        if(rot == 2) return {rx, ry - 1};\n        return {rx - 1, ry};\n    };\n    \n    auto move_to = [&](int tx, int ty) {\n        // Find best rotation to reach (tx, ty)\n        int best_rot = rot;\n        for(int r = 0; r < 4; r++){\n            int req_rx = tx, req_ry = ty;\n            if(r == 0) req_ry--;\n            else if(r == 1) req_rx--;\n            else if(r == 2) req_ry++;\n            else req_rx++;\n            \n            if(req_rx >= 0 && req_rx < N && req_ry >= 0 && req_ry < N){\n                best_rot = r;\n                break;\n            }\n        }\n        \n        // Rotate to best_rot\n        while(rot != best_rot && turns < 100000){\n            string op = \"....\";\n            int diff = (best_rot - rot + 4) % 4;\n            if(diff <= 2) {\n                op[1] = 'R';\n                rot = (rot + 1) % 4;\n            } else {\n                op[1] = 'L';\n                rot = (rot + 3) % 4;\n            }\n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        // Move root to reach target\n        while(turns < 100000){\n            auto [fx, fy] = get_finger();\n            if(fx == tx && fy == ty) break;\n            \n            string op = \"....\";\n            int req_rx = tx, req_ry = ty;\n            if(rot == 0) req_ry--;\n            else if(rot == 1) req_rx--;\n            else if(rot == 2) req_ry++;\n            else req_rx++;\n            \n            if(rx < req_rx) { rx++; op[0] = 'D'; }\n            else if(rx > req_rx) { rx--; op[0] = 'U'; }\n            else if(ry < req_ry) { ry++; op[0] = 'R'; }\n            else if(ry > req_ry) { ry--; op[0] = 'L'; }\n            \n            cout << op << \"\\n\";\n            turns++;\n        }\n    };\n    \n    // Find squares that need to be cleared and filled\n    vector<pair<int,int>> to_clear, to_fill;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(s[i][j] == '1' && t[i][j] == '0') to_clear.push_back({i, j});\n            if(s[i][j] == '0' && t[i][j] == '1') to_fill.push_back({i, j});\n        }\n    }\n    \n    // Process each takoyaki that needs to move\n    for(int idx = 0; idx < (int)to_clear.size() && turns < 100000; idx++){\n        auto [sx, sy] = to_clear[idx];\n        \n        // Check if still has takoyaki\n        if(grid[sx][sy] == 0) continue;\n        \n        // Find best available target\n        int best_tx = -1, best_ty = -1;\n        int min_dist = INT_MAX;\n        for(auto [tx, ty] : to_fill) {\n            if(grid[tx][ty] == 0) {  // Only consider empty targets\n                int dist = abs(sx - tx) + abs(sy - ty);\n                if(dist < min_dist) {\n                    min_dist = dist;\n                    best_tx = tx;\n                    best_ty = ty;\n                }\n            }\n        }\n        \n        if(best_tx == -1) continue; // No available target\n        \n        // Move arm to source\n        move_to(sx, sy);\n        if(turns >= 100000) break;\n        \n        // Pick up takoyaki\n        cout << \"...P\\n\";\n        grid[sx][sy] = 0;\n        turns++;\n        \n        // Move arm to target\n        move_to(best_tx, best_ty);\n        if(turns >= 100000) break;\n        \n        // Place takoyaki\n        cout << \"...P\\n\";\n        grid[best_tx][best_ty] = 1;\n        turns++;\n    }\n    \n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    \n    vector<pair<int, int>> mackerel(N), sardine(N);\n    \n    for(int i = 0; i < N; i++){\n        cin >> mackerel[i].first >> mackerel[i].second;\n    }\n    \n    for(int i = 0; i < N; i++){\n        cin >> sardine[i].first >> sardine[i].second;\n    }\n    \n    auto count_in_rect = [](const vector<pair<int, int>>& pts, int x1, int y1, int x2, int y2) {\n        int count = 0;\n        for(auto [x, y] : pts) {\n            if(x >= x1 && x <= x2 && y >= y1 && y <= y2) {\n                count++;\n            }\n        }\n        return count;\n    };\n    \n    auto score_rect = [&](int x1, int y1, int x2, int y2) {\n        int m = count_in_rect(mackerel, x1, y1, x2, y2);\n        int s = count_in_rect(sardine, x1, y1, x2, y2);\n        return max(0, m - s + 1);\n    };\n    \n    // Find bounding box of all mackerels\n    int minX = INT_MAX, maxX = INT_MIN;\n    int minY = INT_MAX, maxY = INT_MIN;\n    \n    for(auto [x, y] : mackerel){\n        minX = min(minX, x);\n        maxX = max(maxX, x);\n        minY = min(minY, y);\n        maxY = max(maxY, y);\n    }\n    \n    int bestX1 = minX, bestY1 = minY, bestX2 = maxX, bestY2 = maxY;\n    int bestScore = score_rect(bestX1, bestY1, bestX2, bestY2);\n    \n    // Iterative local search with progressively finer granularity\n    for(int phase = 0; phase < 5; phase++) {\n        bool improved = true;\n        \n        while(improved) {\n            improved = false;\n            \n            int dx = max(1, (bestX2 - bestX1) >> (5 - phase));\n            int dy = max(1, (bestY2 - bestY1) >> (5 - phase));\n            \n            // Try shrinking from left\n            for(int x = bestX1; x < bestX2; x += dx) {\n                int s = score_rect(x, bestY1, bestX2, bestY2);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestX1 = x;\n                    improved = true;\n                    break;\n                }\n            }\n            \n            // Try shrinking from right\n            for(int x = bestX2; x > bestX1; x -= dx) {\n                int s = score_rect(bestX1, bestY1, x, bestY2);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestX2 = x;\n                    improved = true;\n                    break;\n                }\n            }\n            \n            // Try shrinking from bottom\n            for(int y = bestY1; y < bestY2; y += dy) {\n                int s = score_rect(bestX1, y, bestX2, bestY2);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestY1 = y;\n                    improved = true;\n                    break;\n                }\n            }\n            \n            // Try shrinking from top\n            for(int y = bestY2; y > bestY1; y -= dy) {\n                int s = score_rect(bestX1, bestY1, bestX2, y);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestY2 = y;\n                    improved = true;\n                    break;\n                }\n            }\n        }\n    }\n    \n    cout << 4 << \"\\n\";\n    cout << bestX1 << \" \" << bestY1 << \"\\n\";\n    cout << bestX2 << \" \" << bestY1 << \"\\n\";\n    cout << bestX2 << \" \" << bestY2 << \"\\n\";\n    cout << bestX1 << \" \" << bestY2 << \"\\n\";\n    \n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\npair<long long, long long> simulate(\n    const vector<tuple<int, int, char, int>>& placement,\n    const vector<pair<long long, long long>>& rects\n) {\n    map<int, array<long long, 4>> pos;\n    long long max_x = 0, max_y = 0;\n    \n    for (auto [idx, rot, dir, ref] : placement) {\n        long long w = rects[idx].first;\n        long long h = rects[idx].second;\n        if (rot) swap(w, h);\n        \n        long long x = 0, y = 0;\n        \n        if (dir == 'U') {\n            if (ref != -1 && pos.count(ref)) {\n                x = pos[ref][0] + pos[ref][2];\n            }\n            for (auto& [i, p] : pos) {\n                if (p[0] < x + w && x < p[0] + p[2]) {\n                    y = max(y, p[1] + p[3]);\n                }\n            }\n        } else { // 'L'\n            if (ref != -1 && pos.count(ref)) {\n                y = pos[ref][1] + pos[ref][3];\n            }\n            for (auto& [i, p] : pos) {\n                if (p[1] < y + h && y < p[1] + p[3]) {\n                    x = max(x, p[0] + p[2]);\n                }\n            }\n        }\n        \n        pos[idx] = {x, y, w, h};\n        max_x = max(max_x, x + w);\n        max_y = max(max_y, y + h);\n    }\n    \n    return {max_x, max_y};\n}\n\nlong long calc_score(\n    const vector<tuple<int, int, char, int>>& placement,\n    const vector<pair<long long, long long>>& rects,\n    int N\n) {\n    auto [w, h] = simulate(placement, rects);\n    long long cost = w + h;\n    \n    set<int> used;\n    for (auto [p, r, d, b] : placement) {\n        used.insert(p);\n    }\n    \n    for (int i = 0; i < N; i++) {\n        if (!used.count(i)) {\n            cost += rects[i].first + rects[i].second;\n        }\n    }\n    \n    return cost;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, T;\n    long long sigma;\n    cin >> N >> T >> sigma;\n    \n    vector<pair<long long, long long>> rects(N);\n    for (int i = 0; i < N; i++) {\n        cin >> rects[i].first >> rects[i].second;\n    }\n    \n    mt19937 rng(987654321);\n    auto start_time = chrono::high_resolution_clock::now();\n    \n    for (int t = 0; t < T; t++) {\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(\n            chrono::high_resolution_clock::now() - start_time).count();\n        \n        if (elapsed > 2850) {\n            vector<tuple<int, int, char, int>> p;\n            for (int i = 0; i < N; i++) {\n                p.push_back({i, 0, 'U', -1});\n            }\n            cout << p.size() << \"\\n\";\n            for (auto [a, b, c, d] : p) {\n                cout << a << \" \" << b << \" \" << c << \" \" << d << \"\\n\";\n            }\n            cout.flush();\n            long long W, H;\n            cin >> W >> H;\n            break;\n        }\n        \n        long long best_score = LLONG_MAX;\n        vector<tuple<int, int, char, int>> best_placement;\n        \n        // Deterministic strategy 1: All U with -1\n        {\n            vector<tuple<int, int, char, int>> placement;\n            for (int i = 0; i < N; i++) {\n                placement.push_back({i, 0, 'U', -1});\n            }\n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        // Deterministic strategy 2: All L with -1\n        {\n            vector<tuple<int, int, char, int>> placement;\n            for (int i = 0; i < N; i++) {\n                placement.push_back({i, 0, 'L', -1});\n            }\n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        // Deterministic strategy 3: Progressive subset sizes\n        for (int use_count = 1; use_count <= min(N, 10); use_count++) {\n            vector<tuple<int, int, char, int>> placement;\n            for (int i = 0; i < use_count; i++) {\n                placement.push_back({i, 0, 'U', -1});\n            }\n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        // Random attempts with varied strategies\n        int num_random = 85;\n        for (int att = 0; att < num_random; att++) {\n            vector<tuple<int, int, char, int>> placement;\n            \n            int use_count;\n            int rand_val = att % 17;\n            if (rand_val < 5) {\n                // Try small counts\n                use_count = 1 + rand_val;\n            } else if (rand_val < 12) {\n                // Try medium counts\n                int third = N / 3;\n                use_count = min(N, 2 + third + (int)(rng() % (third + 1)));\n            } else {\n                // Try random\n                use_count = 1 + (int)(rng() % N);\n            }\n            \n            for (int i = 0; i < use_count; i++) {\n                int r = (int)(rng() % 2);\n                char d = ((int)(rng() % 2)) ? 'U' : 'L';\n                int b = -1;\n                if (i > 0 && (int)(rng() % 3) > 0) {\n                    b = (int)(rng() % i);\n                }\n                placement.push_back({i, r, d, b});\n            }\n            \n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        cout << best_placement.size() << \"\\n\";\n        for (auto [p, r, d, b] : best_placement) {\n            cout << p << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        }\n        cout.flush();\n        \n        long long W, H;\n        cin >> W >> H;\n    }\n    \n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, H;\nvector<int> A;\nvector<vector<int>> adj;\nvector<double> x, y;\n\nlong long evaluateSolution(const vector<int>& parent) {\n    vector<int> depth(N, -1);\n    long long score = 0;\n    \n    function<void(int)> dfs = [&](int u) {\n        score += (long long)(depth[u] + 1) * A[u];\n        for(int v : adj[u]){\n            if(parent[v] == u && depth[v] == -1){\n                depth[v] = depth[u] + 1;\n                dfs(v);\n            }\n        }\n    };\n    \n    for(int i = 0; i < N; i++){\n        if(parent[i] == -1){\n            depth[i] = 0;\n            dfs(i);\n        }\n    }\n    return score;\n}\n\nvector<int> buildTreeBFS(const vector<int>& rootOrder) {\n    vector<int> parent(N, -2);\n    \n    for(int root : rootOrder){\n        if(parent[root] != -2) continue;\n        \n        queue<int> q;\n        q.push(root);\n        parent[root] = -1;\n        vector<int> depth(N, -1);\n        depth[root] = 0;\n        \n        while(!q.empty()){\n            int u = q.front();\n            q.pop();\n            \n            if(depth[u] >= H) continue;\n            \n            vector<pair<int, int>> neighbors;\n            for(int v : adj[u]){\n                if(parent[v] == -2){\n                    neighbors.push_back({A[v], v});\n                }\n            }\n            \n            sort(neighbors.rbegin(), neighbors.rend());\n            \n            for(auto [_, v] : neighbors){\n                parent[v] = u;\n                depth[v] = depth[u] + 1;\n                q.push(v);\n            }\n        }\n    }\n    return parent;\n}\n\nvector<int> buildTreeDFS(const vector<int>& rootOrder) {\n    vector<int> parent(N, -2);\n    \n    for(int root : rootOrder){\n        if(parent[root] != -2) continue;\n        \n        vector<int> depth(N, -1);\n        parent[root] = -1;\n        depth[root] = 0;\n        \n        function<void(int, int)> dfs = [&](int u, int d) {\n            if(d >= H) return;\n            \n            vector<pair<int, int>> neighbors;\n            for(int v : adj[u]){\n                if(parent[v] == -2){\n                    neighbors.push_back({A[v], v});\n                }\n            }\n            \n            sort(neighbors.rbegin(), neighbors.rend());\n            \n            for(auto [_, v] : neighbors){\n                parent[v] = u;\n                depth[v] = d + 1;\n                dfs(v, d + 1);\n            }\n        };\n        \n        dfs(root, 0);\n    }\n    return parent;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int H_input;\n    cin >> N >> M >> H_input;\n    H = H_input;\n    \n    A.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> A[i];\n    }\n    \n    adj.resize(N);\n    for(int i = 0; i < M; i++){\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    x.resize(N);\n    y.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<int> best_parent(N);\n    long long best_score = -1;\n    \n    auto tryOrder = [&](vector<int> ord, bool useDFS = false) {\n        auto parent = useDFS ? buildTreeDFS(ord) : buildTreeBFS(ord);\n        long long score = evaluateSolution(parent);\n        if(score > best_score){\n            best_score = score;\n            best_parent = parent;\n        }\n    };\n    \n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    \n    // Core beauty/degree heuristics with both BFS and DFS\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return A[a] > A[b]; });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n    }\n    \n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return A[a] < A[b]; });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n    }\n    \n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return adj[a].size() > adj[b].size(); });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n    }\n    \n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return adj[a].size() < adj[b].size(); });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n    }\n    \n    // Geometric heuristics - distance from center\n    {\n        double cx = 500, cy = 500;\n        \n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double da = (x[a]-cx)*(x[a]-cx) + (y[a]-cy)*(y[a]-cy);\n            double db = (x[b]-cx)*(x[b]-cx) + (y[b]-cy)*(y[b]-cy);\n            return da < db;\n        });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n        \n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double da = (x[a]-cx)*(x[a]-cx) + (y[a]-cy)*(y[a]-cy);\n            double db = (x[b]-cx)*(x[b]-cx) + (y[b]-cy)*(y[b]-cy);\n            return da > db;\n        });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n    }\n    \n    // Angle-based ordering\n    {\n        double cx = 500, cy = 500;\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double aa = atan2(y[a]-cy, x[a]-cx);\n            double ab = atan2(y[b]-cy, x[b]-cx);\n            return aa < ab;\n        });\n        tryOrder(ord, false);\n    }\n    \n    // X and Y coordinates\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return x[a] < x[b]; });\n        tryOrder(ord, false);\n    }\n    \n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return y[a] < y[b]; });\n        tryOrder(ord, false);\n    }\n    \n    // Fine-grained beauty + weight*degree combinations\n    for(double w = -2.0; w <= 2.05; w += 0.1){\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double sa = A[a] + w * adj[a].size();\n            double sb = A[b] + w * adj[b].size();\n            return sa > sb;\n        });\n        tryOrder(ord, false);\n    }\n    \n    // Beauty * pow(degree+1, w)\n    for(double w = 0.0; w <= 2.05; w += 0.1){\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double sa = A[a] * pow(1.0 + adj[a].size(), w);\n            double sb = A[b] * pow(1.0 + adj[b].size(), w);\n            return sa > sb;\n        });\n        tryOrder(ord, false);\n    }\n    \n    // Ratio metrics\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double sa = (double)A[a] / (1.0 + adj[a].size());\n            double sb = (double)A[b] / (1.0 + adj[b].size());\n            return sa > sb;\n        });\n        tryOrder(ord, false);\n    }\n    \n    // Logarithmic\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double sa = A[a] * log(2.0 + adj[a].size());\n            double sb = A[b] * log(2.0 + adj[b].size());\n            return sa > sb;\n        });\n        tryOrder(ord, false);\n    }\n    \n    // Extensive random sampling with both BFS and DFS\n    for(int seed = 0; seed < 480; seed++){\n        mt19937 rng(seed);\n        auto ord = order;\n        shuffle(ord.begin(), ord.end(), rng);\n        tryOrder(ord, seed % 2 == 0);\n    }\n    \n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << best_parent[i];\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int N;\n    cin >> N;\n    \n    vector<string> board(N);\n    for (int i = 0; i < N; i++) {\n        cin >> board[i];\n    }\n    \n    vector<pair<char, int>> operations;\n    \n    auto findOni = [&]() -> pair<int, int> {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (board[i][j] == 'x') return {i, j};\n            }\n        }\n        return {-1, -1};\n    };\n    \n    auto shiftUp = [&](int j) {\n        for (int i = 0; i < N - 1; i++) board[i][j] = board[i + 1][j];\n        board[N - 1][j] = '.';\n        operations.push_back({'U', j});\n    };\n    \n    auto shiftDown = [&](int j) {\n        for (int i = N - 1; i > 0; i--) board[i][j] = board[i - 1][j];\n        board[0][j] = '.';\n        operations.push_back({'D', j});\n    };\n    \n    auto shiftLeft = [&](int i) {\n        for (int j = 0; j < N - 1; j++) board[i][j] = board[i][j + 1];\n        board[i][N - 1] = '.';\n        operations.push_back({'L', i});\n    };\n    \n    auto shiftRight = [&](int i) {\n        for (int j = N - 1; j > 0; j--) board[i][j] = board[i][j - 1];\n        board[i][0] = '.';\n        operations.push_back({'R', i});\n    };\n    \n    while (true) {\n        auto [i, j] = findOni();\n        if (i == -1) break;\n        \n        // Check all four directions and pick the one with minimum cost\n        int minCost = INT_MAX;\n        int bestDir = -1; // 0=up, 1=down, 2=left, 3=right\n        \n        // Check upward direction\n        bool clearUp = true;\n        for (int k = 0; k < i; k++) {\n            if (board[k][j] == 'o') { clearUp = false; break; }\n        }\n        if (clearUp) {\n            int cost = 2 * (i + 1);\n            if (cost < minCost) { minCost = cost; bestDir = 0; }\n        }\n        \n        // Check downward direction\n        bool clearDown = true;\n        for (int k = i + 1; k < N; k++) {\n            if (board[k][j] == 'o') { clearDown = false; break; }\n        }\n        if (clearDown) {\n            int cost = 2 * (N - i);\n            if (cost < minCost) { minCost = cost; bestDir = 1; }\n        }\n        \n        // Check leftward direction\n        bool clearLeft = true;\n        for (int k = 0; k < j; k++) {\n            if (board[i][k] == 'o') { clearLeft = false; break; }\n        }\n        if (clearLeft) {\n            int cost = 2 * (j + 1);\n            if (cost < minCost) { minCost = cost; bestDir = 2; }\n        }\n        \n        // Check rightward direction\n        bool clearRight = true;\n        for (int k = j + 1; k < N; k++) {\n            if (board[i][k] == 'o') { clearRight = false; break; }\n        }\n        if (clearRight) {\n            int cost = 2 * (N - j);\n            if (cost < minCost) { minCost = cost; bestDir = 3; }\n        }\n        \n        // Apply the best direction (guaranteed to exist by problem statement)\n        if (bestDir == 0) {\n            for (int k = 0; k <= i; k++) shiftUp(j);\n            for (int k = 0; k <= i; k++) shiftDown(j);\n        } else if (bestDir == 1) {\n            for (int k = 0; k < N - i; k++) shiftDown(j);\n            for (int k = 0; k < N - i; k++) shiftUp(j);\n        } else if (bestDir == 2) {\n            for (int k = 0; k <= j; k++) shiftLeft(i);\n            for (int k = 0; k <= j; k++) shiftRight(i);\n        } else if (bestDir == 3) {\n            for (int k = 0; k < N - j; k++) shiftRight(i);\n            for (int k = 0; k < N - j; k++) shiftLeft(i);\n        }\n    }\n    \n    for (auto [d, p] : operations) {\n        cout << d << \" \" << p << \"\\n\";\n    }\n    \n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nlong long computeError(const vector<int>& a, const vector<int>& b, int N, long long L, const vector<int>& T) {\n    vector<long long> count(N, 0);\n    int current = 0;\n    count[0]++;\n    \n    for (long long week = 1; week < L; week++) {\n        int next = (count[current] & 1) ? a[current] : b[current];\n        count[next]++;\n        current = next;\n    }\n    \n    long long error = 0;\n    for (int i = 0; i < N; i++) {\n        error += abs(count[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, L;\n    cin >> N >> L;\n    \n    vector<int> T(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n    \n    vector<int> best_a(N), best_b(N);\n    long long best_error = LLONG_MAX;\n    \n    mt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n    \n    // Stage 1: Try multiple initial strategies with local search\n    for (int strategy = 0; strategy < 5; strategy++) {\n        vector<int> a(N), b(N);\n        \n        if (strategy == 0) {\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 1) % N;\n            }\n        } else if (strategy == 1) {\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 2) % N;\n            }\n        } else if (strategy == 2) {\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i - 1 + N) % N;\n            }\n        } else if (strategy == 3) {\n            for (int i = 0; i < N; i++) {\n                a[i] = i;\n                b[i] = (i + 1) % N;\n            }\n        } else {\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 2) % N;\n                b[i] = (i - 2 + N) % N;\n            }\n        }\n        \n        long long error = computeError(a, b, N, L, T);\n        \n        // Local search from this starting point\n        int no_improve = 0;\n        for (int iter = 0; iter < 80 && no_improve < 20; iter++) {\n            int emp = rng() % N;\n            int param = rng() % 2;\n            int old_val = (param == 0) ? a[emp] : b[emp];\n            int new_val = rng() % N;\n            \n            if (param == 0) {\n                a[emp] = new_val;\n            } else {\n                b[emp] = new_val;\n            }\n            \n            long long new_error = computeError(a, b, N, L, T);\n            \n            if (new_error < error) {\n                error = new_error;\n                no_improve = 0;\n            } else {\n                if (param == 0) {\n                    a[emp] = old_val;\n                } else {\n                    b[emp] = old_val;\n                }\n                no_improve++;\n            }\n        }\n        \n        if (error < best_error) {\n            best_error = error;\n            best_a = a;\n            best_b = b;\n        }\n    }\n    \n    // Stage 2: Final intensive local search on best solution\n    int no_improve = 0;\n    for (int iter = 0; iter < 120 && no_improve < 40; iter++) {\n        int emp = rng() % N;\n        int param = rng() % 2;\n        int old_val = (param == 0) ? best_a[emp] : best_b[emp];\n        int new_val = rng() % N;\n        \n        if (param == 0) {\n            best_a[emp] = new_val;\n        } else {\n            best_b[emp] = new_val;\n        }\n        \n        long long new_error = computeError(best_a, best_b, N, L, T);\n        \n        if (new_error < best_error) {\n            best_error = new_error;\n            no_improve = 0;\n        } else {\n            if (param == 0) {\n                best_a[emp] = old_val;\n            } else {\n                best_b[emp] = old_val;\n            }\n            no_improve++;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass DSU {\npublic:\n    vector<int> parent;\n    \n    DSU(int n) : parent(n) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    \n    int find(int x) {\n        if(parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    \n    bool unite(int x, int y) {\n        int px = find(x);\n        int py = find(y);\n        if(px == py) return false;\n        parent[px] = py;\n        return true;\n    }\n};\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    \n    vector<int> G(M);\n    for(int i = 0; i < M; i++){\n        cin >> G[i];\n    }\n    \n    vector<double> lx(N), rx(N), ly(N), ry(N);\n    for(int i = 0; i < N; i++){\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n    \n    // Estimate positions using rectangle centers\n    vector<pair<double,double>> pos(N);\n    double minx = 1e18, maxx = -1e18, miny = 1e18, maxy = -1e18;\n    for(int i = 0; i < N; i++){\n        pos[i] = {(lx[i] + rx[i]) / 2.0, (ly[i] + ry[i]) / 2.0};\n        minx = min(minx, pos[i].first);\n        maxx = max(maxx, pos[i].first);\n        miny = min(miny, pos[i].second);\n        maxy = max(maxy, pos[i].second);\n    }\n    \n    // Compute geometric center\n    double cx = (minx + maxx) / 2.0;\n    double cy = (miny + maxy) / 2.0;\n    \n    // Sort by polar angle from center\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int i, int j){\n        double angle_i = atan2(pos[i].second - cy, pos[i].first - cx);\n        double angle_j = atan2(pos[j].second - cy, pos[j].first - cx);\n        if(fabs(angle_i - angle_j) > 1e-9) return angle_i < angle_j;\n        \n        double dist_i = (pos[i].first - cx) * (pos[i].first - cx) + \n                       (pos[i].second - cy) * (pos[i].second - cy);\n        double dist_j = (pos[j].first - cx) * (pos[j].first - cx) + \n                       (pos[j].second - cy) * (pos[j].second - cy);\n        return dist_i < dist_j;\n    });\n    \n    // Assign to groups\n    vector<vector<int>> groups(M);\n    int idx = 0;\n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g]; i++){\n            groups[g].push_back(order[idx++]);\n        }\n        \n        // Sort within group for better locality\n        sort(groups[g].begin(), groups[g].end(), [&](int i, int j){\n            if(fabs(pos[i].first - pos[j].first) > 1e-9) return pos[i].first < pos[j].first;\n            return pos[i].second < pos[j].second;\n        });\n    }\n    \n    // Collect edges and build spanning trees\n    vector<vector<pair<int,int>>> final_edges(M);\n    \n    for(int g = 0; g < M; g++){\n        vector<pair<int,int>> all_edges;\n        int gsize = G[g];\n        \n        // Query using sliding windows of size 3\n        for(int i = 0; i + 2 < gsize; i += 2){\n            cout << \"? 3 \" << groups[g][i] << \" \" << groups[g][i+1] << \" \" << groups[g][i+2] << \"\\n\";\n            cout.flush();\n            \n            for(int j = 0; j < 2; j++){\n                int a, b;\n                cin >> a >> b;\n                all_edges.push_back({a, b});\n            }\n        }\n        \n        // Handle remaining cities\n        if((gsize - 1) % 2 == 1){\n            // Odd number of cities left after windows\n            all_edges.push_back({groups[g][gsize - 2], groups[g][gsize - 1]});\n        }\n        \n        // Build spanning tree using DSU\n        DSU dsu(N);\n        \n        for(auto [a, b] : all_edges){\n            if(dsu.unite(a, b)){\n                final_edges[g].push_back({a, b});\n                if((int)final_edges[g].size() == gsize - 1) break;\n            }\n        }\n        \n        // Ensure connectivity - add direct edges if needed\n        if((int)final_edges[g].size() < gsize - 1){\n            for(int i = 1; i < gsize; i++){\n                if((int)final_edges[g].size() >= gsize - 1) break;\n                if(dsu.unite(groups[g][i-1], groups[g][i])){\n                    final_edges[g].push_back({groups[g][i-1], groups[g][i]});\n                }\n            }\n        }\n    }\n    \n    // Output answer\n    cout << \"!\\n\";\n    cout.flush();\n    \n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g]; i++){\n            if(i > 0) cout << \" \";\n            cout << groups[g][i];\n        }\n        cout << \"\\n\";\n        \n        for(auto [a, b] : final_edges[g]){\n            cout << a << \" \" << b << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<pair<int, int>> targets;\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dchar[] = {'U', 'D', 'L', 'R'};\n\nbool valid(int x, int y) {\n    return 0 <= x && x < N && 0 <= y && y < N;\n}\n\npair<int, int> slideUntilBlock(int x, int y, int dir, const set<pair<int, int>>& blocks) {\n    int nx = x + dx[dir];\n    int ny = y + dy[dir];\n    while (valid(nx, ny) && !blocks.count({nx, ny})) {\n        x = nx;\n        y = ny;\n        nx = x + dx[dir];\n        ny = y + dy[dir];\n    }\n    return {x, y};\n}\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    targets.resize(M);\n    for (int i = 0; i < M; i++) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n    \n    vector<pair<char, char>> result;\n    int x = targets[0].first;\n    int y = targets[0].second;\n    set<pair<int, int>> blocks;\n    \n    // Navigate from target to target\n    for (int t = 1; t < M; t++) {\n        int tx = targets[t].first;\n        int ty = targets[t].second;\n        \n        // A* search considering Move and Slide actions\n        // State: (f_score, g_score, x, y)\n        map<pair<int, int>, int> g_score;  // distance from start\n        priority_queue<tuple<int, int, int, int>,\n                       vector<tuple<int, int, int, int>>,\n                       greater<tuple<int, int, int, int>>> pq;\n        \n        int h = manhattan(x, y, tx, ty);\n        pq.push({h, 0, x, y});\n        g_score[{x, y}] = 0;\n        \n        map<pair<int, int>, pair<pair<int, int>, pair<char, char>>> parent;\n        parent[{x, y}] = {{-1, -1}, {'X', 'X'}};\n        \n        while (!pq.empty()) {\n            auto [f, g, cx, cy] = pq.top();\n            pq.pop();\n            \n            if (cx == tx && cy == ty) break;\n            if (g_score.count({cx, cy}) && g_score[{cx, cy}] < g) continue;\n            \n            // Try all directions with Move and Slide actions\n            for (int dir = 0; dir < 4; dir++) {\n                // Move action: move one square\n                {\n                    int nx = cx + dx[dir];\n                    int ny = cy + dy[dir];\n                    if (valid(nx, ny) && !blocks.count({nx, ny})) {\n                        int new_g = g + 1;\n                        if (!g_score.count({nx, ny}) || g_score[{nx, ny}] > new_g) {\n                            g_score[{nx, ny}] = new_g;\n                            parent[{nx, ny}] = {{cx, cy}, {'M', dchar[dir]}};\n                            int new_h = manhattan(nx, ny, tx, ty);\n                            pq.push({new_g + new_h, new_g, nx, ny});\n                        }\n                    }\n                }\n                \n                // Slide action: slide until hitting a block\n                {\n                    int nx = cx + dx[dir];\n                    int ny = cy + dy[dir];\n                    if (valid(nx, ny) && !blocks.count({nx, ny})) {\n                        auto [sx, sy] = slideUntilBlock(cx, cy, dir, blocks);\n                        if (sx != cx || sy != cy) {  // Only if we actually slid\n                            int new_g = g + 1;\n                            if (!g_score.count({sx, sy}) || g_score[{sx, sy}] > new_g) {\n                                g_score[{sx, sy}] = new_g;\n                                parent[{sx, sy}] = {{cx, cy}, {'S', dchar[dir]}};\n                                int new_h = manhattan(sx, sy, tx, ty);\n                                pq.push({new_g + new_h, new_g, sx, sy});\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        // Reconstruct path\n        vector<pair<char, char>> path;\n        pair<int, int> p = {tx, ty};\n        while (parent[p].second.first != 'X') {\n            path.push_back(parent[p].second);\n            p = parent[p].first;\n        }\n        reverse(path.begin(), path.end());\n        \n        for (auto action : path) {\n            result.push_back(action);\n        }\n        \n        x = tx;\n        y = ty;\n    }\n    \n    for (auto [a, d] : result) {\n        cout << a << \" \" << d << \"\\n\";\n    }\n    \n    return 0;\n}"},"8":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int id;\n    long long x, y, r;\n};\n\nvector<array<long long, 4>> result(205);\n\nvoid assign(vector<int> indices, const vector<Company>& companies, \n            long long x1, long long y1, long long x2, long long y2) {\n    if (indices.empty()) return;\n    if (indices.size() == 1) {\n        result[indices[0]] = {x1, y1, x2, y2};\n        return;\n    }\n    \n    // Compute company distribution statistics\n    vector<long long> xs, ys;\n    for (int idx : indices) {\n        xs.push_back(companies[idx].x);\n        ys.push_back(companies[idx].y);\n    }\n    sort(xs.begin(), xs.end());\n    sort(ys.begin(), ys.end());\n    \n    long long x_spread = xs.back() - xs.front();\n    long long y_spread = ys.back() - ys.front();\n    long long width = x2 - x1;\n    long long height = y2 - y1;\n    \n    // Prefer splitting perpendicular to clustering direction\n    bool prefer_vertical_split = (x_spread < y_spread) || (width > height);\n    \n    double best_score = -1e18;\n    int best_strategy = -1;\n    long long best_split = x1;\n    vector<int> best_left, best_right;\n    \n    auto try_vertical_splits = [&]() {\n        set<long long> x_thresholds;\n        for (int idx : indices) {\n            x_thresholds.insert(companies[idx].x);\n            x_thresholds.insert(companies[idx].x + 1);\n        }\n        \n        // Add percentile-based thresholds\n        if (xs.size() > 2) {\n            x_thresholds.insert(xs[xs.size() / 4]);\n            x_thresholds.insert(xs[xs.size() / 2]);\n            x_thresholds.insert(xs[3 * xs.size() / 4]);\n        }\n        \n        for (long long threshold : x_thresholds) {\n            vector<int> left, right;\n            for (int idx : indices) {\n                if (companies[idx].x < threshold) left.push_back(idx);\n                else right.push_back(idx);\n            }\n            \n            if (left.empty() || right.empty()) continue;\n            \n            long long max_left_x = -1;\n            for (int idx : left) max_left_x = max(max_left_x, companies[idx].x);\n            long long min_right_x = 10000;\n            for (int idx : right) min_right_x = min(min_right_x, companies[idx].x);\n            \n            long long split_min = max(x1 + 1, max_left_x + 1);\n            long long split_max = min(x2 - 1, min_right_x);\n            \n            if (split_min > split_max) continue;\n            \n            long long left_desired = 0, right_desired = 0;\n            for (int idx : left) left_desired += companies[idx].r;\n            for (int idx : right) right_desired += companies[idx].r;\n            \n            set<long long> candidates;\n            long long range = split_max - split_min;\n            \n            candidates.insert(split_min);\n            candidates.insert(split_max);\n            \n            if (left_desired + right_desired > 0) {\n                __int128 w = x2 - x1;\n                __int128 ideal_128 = x1 + w * left_desired / (left_desired + right_desired);\n                long long ideal = max(split_min, min(split_max, (long long)ideal_128));\n                candidates.insert(ideal);\n                if (ideal > split_min) candidates.insert(ideal - 1);\n                if (ideal < split_max) candidates.insert(ideal + 1);\n            }\n            \n            if (range > 1) {\n                candidates.insert((split_min + split_max) / 2);\n                long long g1 = split_min + range * 2 / 5;\n                long long g2 = split_min + range * 3 / 5;\n                candidates.insert(g1);\n                candidates.insert(g2);\n            }\n            \n            int num_samples = min(80LL, 15 + range / 80);\n            for (int i = 1; i < num_samples; i++) {\n                long long pos = split_min + range * i / num_samples;\n                candidates.insert(pos);\n            }\n            \n            for (long long split_pos : candidates) {\n                if (split_pos < split_min || split_pos > split_max) continue;\n                \n                long long left_area = (split_pos - x1) * (y2 - y1);\n                long long right_area = (x2 - split_pos) * (y2 - y1);\n                \n                double left_ratio = (double)left_area / max(1LL, left_desired);\n                double right_ratio = (double)right_area / max(1LL, right_desired);\n                \n                double score = -abs(log(left_ratio)) - abs(log(right_ratio));\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_strategy = 0;\n                    best_split = split_pos;\n                    best_left = left;\n                    best_right = right;\n                }\n            }\n        }\n    };\n    \n    auto try_horizontal_splits = [&]() {\n        set<long long> y_thresholds;\n        for (int idx : indices) {\n            y_thresholds.insert(companies[idx].y);\n            y_thresholds.insert(companies[idx].y + 1);\n        }\n        \n        // Add percentile-based thresholds\n        if (ys.size() > 2) {\n            y_thresholds.insert(ys[ys.size() / 4]);\n            y_thresholds.insert(ys[ys.size() / 2]);\n            y_thresholds.insert(ys[3 * ys.size() / 4]);\n        }\n        \n        for (long long threshold : y_thresholds) {\n            vector<int> bottom, top;\n            for (int idx : indices) {\n                if (companies[idx].y < threshold) bottom.push_back(idx);\n                else top.push_back(idx);\n            }\n            \n            if (bottom.empty() || top.empty()) continue;\n            \n            long long max_bottom_y = -1;\n            for (int idx : bottom) max_bottom_y = max(max_bottom_y, companies[idx].y);\n            long long min_top_y = 10000;\n            for (int idx : top) min_top_y = min(min_top_y, companies[idx].y);\n            \n            long long split_min = max(y1 + 1, max_bottom_y + 1);\n            long long split_max = min(y2 - 1, min_top_y);\n            \n            if (split_min > split_max) continue;\n            \n            long long bottom_desired = 0, top_desired = 0;\n            for (int idx : bottom) bottom_desired += companies[idx].r;\n            for (int idx : top) top_desired += companies[idx].r;\n            \n            set<long long> candidates;\n            long long range = split_max - split_min;\n            \n            candidates.insert(split_min);\n            candidates.insert(split_max);\n            \n            if (bottom_desired + top_desired > 0) {\n                __int128 h = y2 - y1;\n                __int128 ideal_128 = y1 + h * bottom_desired / (bottom_desired + top_desired);\n                long long ideal = max(split_min, min(split_max, (long long)ideal_128));\n                candidates.insert(ideal);\n                if (ideal > split_min) candidates.insert(ideal - 1);\n                if (ideal < split_max) candidates.insert(ideal + 1);\n            }\n            \n            if (range > 1) {\n                candidates.insert((split_min + split_max) / 2);\n                long long g1 = split_min + range * 2 / 5;\n                long long g2 = split_min + range * 3 / 5;\n                candidates.insert(g1);\n                candidates.insert(g2);\n            }\n            \n            int num_samples = min(80LL, 15 + range / 80);\n            for (int i = 1; i < num_samples; i++) {\n                long long pos = split_min + range * i / num_samples;\n                candidates.insert(pos);\n            }\n            \n            for (long long split_pos : candidates) {\n                if (split_pos < split_min || split_pos > split_max) continue;\n                \n                long long bottom_area = (x2 - x1) * (split_pos - y1);\n                long long top_area = (x2 - x1) * (y2 - split_pos);\n                \n                double bottom_ratio = (double)bottom_area / max(1LL, bottom_desired);\n                double top_ratio = (double)top_area / max(1LL, top_desired);\n                \n                double score = -abs(log(bottom_ratio)) - abs(log(top_ratio));\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_strategy = 1;\n                    best_split = split_pos;\n                    best_left = bottom;\n                    best_right = top;\n                }\n            }\n        }\n    };\n    \n    // Try preferred direction first, then the other\n    if (prefer_vertical_split) {\n        try_vertical_splits();\n        try_horizontal_splits();\n    } else {\n        try_horizontal_splits();\n        try_vertical_splits();\n    }\n    \n    if (best_strategy == 0) {\n        assign(best_left, companies, x1, y1, best_split, y2);\n        assign(best_right, companies, best_split, y1, x2, y2);\n    } else if (best_strategy == 1) {\n        assign(best_left, companies, x1, y1, x2, best_split);\n        assign(best_right, companies, x1, best_split, x2, y2);\n    } else {\n        long long mid = (x1 + x2) / 2;\n        vector<int> left, right;\n        for (int idx : indices) {\n            if (companies[idx].x < mid) left.push_back(idx);\n            else right.push_back(idx);\n        }\n        if (!left.empty() && !right.empty()) {\n            assign(left, companies, x1, y1, mid, y2);\n            assign(right, companies, mid, y1, x2, y2);\n        } else {\n            mid = (y1 + y2) / 2;\n            for (int idx : indices) {\n                if (companies[idx].y < mid) left.push_back(idx);\n                else right.push_back(idx);\n            }\n            assign(left, companies, x1, y1, x2, mid);\n            assign(right, companies, x1, mid, x2, y2);\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    vector<Company> companies(n);\n    \n    for (int i = 0; i < n; i++) {\n        companies[i].id = i;\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n    \n    vector<int> indices(n);\n    iota(indices.begin(), indices.end(), 0);\n    \n    assign(indices, companies, 0, 0, 10000, 10000);\n    \n    for (int i = 0; i < n; i++) {\n        cout << result[i][0] << \" \" << result[i][1] << \" \" \n             << result[i][2] << \" \" << result[i][3] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint si, sj;\nint tile[50][50];\nint value[50][50];\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dc[] = {'U', 'D', 'L', 'R'};\n\nint best_score = 0;\nstring best_path = \"\";\nchrono::high_resolution_clock::time_point start_time;\nconst double TIME_LIMIT = 1.95;\n\nbool time_exceeded() {\n    auto now = chrono::high_resolution_clock::now();\n    double elapsed = chrono::duration<double>(now - start_time).count();\n    return elapsed > TIME_LIMIT;\n}\n\npair<int, string> walk(vector<bool>& visited_tiles, mt19937& rng) {\n    int score = value[si][sj];\n    int cur_i = si, cur_j = sj;\n    string path = \"\";\n    \n    while (true) {\n        vector<int> valid_dirs;\n        \n        // Find all valid moves (adjacent unvisited tiles)\n        for (int d = 0; d < 4; d++) {\n            int ni = cur_i + dx[d];\n            int nj = cur_j + dy[d];\n            \n            if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n                int new_tile = tile[ni][nj];\n                if (!visited_tiles[new_tile]) {\n                    valid_dirs.push_back(d);\n                }\n            }\n        }\n        \n        if (valid_dirs.empty()) break;\n        \n        int d;\n        // 70% greedy (pick highest value), 30% random exploration\n        if (uniform_real_distribution<>(0, 1)(rng) < 0.7) {\n            d = valid_dirs[0];\n            int best_v = value[cur_i + dx[d]][cur_j + dy[d]];\n            \n            // Find direction with highest value\n            for (int dd : valid_dirs) {\n                int ni = cur_i + dx[dd];\n                int nj = cur_j + dy[dd];\n                if (value[ni][nj] > best_v) {\n                    d = dd;\n                    best_v = value[ni][nj];\n                }\n            }\n        } else {\n            // Random exploration\n            d = valid_dirs[uniform_int_distribution<>(0, valid_dirs.size() - 1)(rng)];\n        }\n        \n        int ni = cur_i + dx[d];\n        int nj = cur_j + dy[d];\n        visited_tiles[tile[ni][nj]] = true;\n        path.push_back(dc[d]);\n        score += value[ni][nj];\n        cur_i = ni;\n        cur_j = nj;\n    }\n    \n    return {score, path};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> si >> sj;\n    \n    int max_tile = 0;\n    for (int i = 0; i < 50; i++) {\n        for (int j = 0; j < 50; j++) {\n            cin >> tile[i][j];\n            max_tile = max(max_tile, tile[i][j]);\n        }\n    }\n    \n    for (int i = 0; i < 50; i++) {\n        for (int j = 0; j < 50; j++) {\n            cin >> value[i][j];\n        }\n    }\n    \n    start_time = chrono::high_resolution_clock::now();\n    best_score = value[si][sj];\n    best_path = \"\";\n    \n    mt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n    \n    // Run multiple random walks until time limit\n    while (!time_exceeded()) {\n        vector<bool> visited_tiles(max_tile + 1, false);\n        visited_tiles[tile[si][sj]] = true;\n        auto [score, path] = walk(visited_tiles, rng);\n        \n        if (score > best_score) {\n            best_score = score;\n            best_path = path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\n#include <queue>\nusing namespace std;\n\nconst int N = 30;\nconst double INF = 1e18;\nconst double EDGE_MIN = 1000.0;\nconst double EDGE_MAX = 9500.0;\n\ndouble h[N][N-1], v[N-1][N];\nint h_count[N][N-1], v_count[N-1][N];\n\nstruct State {\n    double dist;\n    int i, j;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\npair<string, double> dijkstra(int si, int sj, int ti, int tj) {\n    vector<vector<double>> dist(N, vector<double>(N, INF));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1, -1}));\n    vector<vector<char>> dir(N, vector<char>(N));\n    \n    priority_queue<State, vector<State>, greater<State>> pq;\n    dist[si][sj] = 0;\n    pq.push({0, si, sj});\n    \n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top();\n        pq.pop();\n        \n        if (d > dist[i][j]) continue;\n        \n        // Up\n        if (i > 0) {\n            double new_dist = d + v[i-1][j];\n            if (new_dist < dist[i-1][j]) {\n                dist[i-1][j] = new_dist;\n                parent[i-1][j] = {i, j};\n                dir[i-1][j] = 'U';\n                pq.push({new_dist, i-1, j});\n            }\n        }\n        \n        // Down\n        if (i < N-1) {\n            double new_dist = d + v[i][j];\n            if (new_dist < dist[i+1][j]) {\n                dist[i+1][j] = new_dist;\n                parent[i+1][j] = {i, j};\n                dir[i+1][j] = 'D';\n                pq.push({new_dist, i+1, j});\n            }\n        }\n        \n        // Left\n        if (j > 0) {\n            double new_dist = d + h[i][j-1];\n            if (new_dist < dist[i][j-1]) {\n                dist[i][j-1] = new_dist;\n                parent[i][j-1] = {i, j};\n                dir[i][j-1] = 'L';\n                pq.push({new_dist, i, j-1});\n            }\n        }\n        \n        // Right\n        if (j < N-1) {\n            double new_dist = d + h[i][j];\n            if (new_dist < dist[i][j+1]) {\n                dist[i][j+1] = new_dist;\n                parent[i][j+1] = {i, j};\n                dir[i][j+1] = 'R';\n                pq.push({new_dist, i, j+1});\n            }\n        }\n    }\n    \n    string path;\n    int ci = ti, cj = tj;\n    while (parent[ci][cj].first != -1) {\n        path += dir[ci][cj];\n        auto [pi, pj] = parent[ci][cj];\n        ci = pi;\n        cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    \n    return {path, dist[ti][tj]};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // Initialize edge weights and observation counts\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N-1; j++) {\n            h[i][j] = 5000.0;\n            h_count[i][j] = 0;\n        }\n    }\n    for (int i = 0; i < N-1; i++) {\n        for (int j = 0; j < N; j++) {\n            v[i][j] = 5000.0;\n            v_count[i][j] = 0;\n        }\n    }\n    \n    for (int q = 0; q < 1000; q++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        auto [path, computed_length] = dijkstra(si, sj, ti, tj);\n        \n        cout << path << endl;\n        cout.flush();\n        \n        long long feedback;\n        cin >> feedback;\n        \n        // More aggressive early, better maintained late: 0.20 -> 0.05\n        double base_alpha = 0.20 - 0.15 * q / 1000.0;\n        base_alpha = max(0.05, base_alpha);\n        \n        // Update edge weights based on feedback\n        if (!path.empty()) {\n            double edge_estimate = (double)feedback / path.length();\n            \n            int ci = si, cj = sj;\n            for (char c : path) {\n                if (c == 'U') {\n                    // Softer exponential decay: maintains learning longer\n                    double adaptive_alpha = base_alpha * exp(-0.035 * v_count[ci-1][cj]);\n                    v[ci-1][cj] = (1 - adaptive_alpha) * v[ci-1][cj] + adaptive_alpha * edge_estimate;\n                    v[ci-1][cj] = max(EDGE_MIN, min(EDGE_MAX, v[ci-1][cj]));\n                    v_count[ci-1][cj]++;\n                    ci--;\n                } else if (c == 'D') {\n                    double adaptive_alpha = base_alpha * exp(-0.035 * v_count[ci][cj]);\n                    v[ci][cj] = (1 - adaptive_alpha) * v[ci][cj] + adaptive_alpha * edge_estimate;\n                    v[ci][cj] = max(EDGE_MIN, min(EDGE_MAX, v[ci][cj]));\n                    v_count[ci][cj]++;\n                    ci++;\n                } else if (c == 'L') {\n                    double adaptive_alpha = base_alpha * exp(-0.035 * h_count[ci][cj-1]);\n                    h[ci][cj-1] = (1 - adaptive_alpha) * h[ci][cj-1] + adaptive_alpha * edge_estimate;\n                    h[ci][cj-1] = max(EDGE_MIN, min(EDGE_MAX, h[ci][cj-1]));\n                    h_count[ci][cj-1]++;\n                    cj--;\n                } else if (c == 'R') {\n                    double adaptive_alpha = base_alpha * exp(-0.035 * h_count[ci][cj]);\n                    h[ci][cj] = (1 - adaptive_alpha) * h[ci][cj] + adaptive_alpha * edge_estimate;\n                    h[ci][cj] = max(EDGE_MIN, min(EDGE_MAX, h[ci][cj]));\n                    h_count[ci][cj]++;\n                    cj++;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc004":"#include<bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<string> strings;\nchar bestMatrix[20][20];\nint bestMatches = 0;\n\nbool isSubsequence(const string& s, char mat[20][20]) {\n    int len = (int)s.length();\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            bool found = true;\n            for(int p = 0; p < len; p++) {\n                if(mat[i][(j+p)%N] != s[p]) {\n                    found = false;\n                    break;\n                }\n            }\n            if(found) return true;\n        }\n    }\n    \n    for(int j = 0; j < N; j++) {\n        for(int i = 0; i < N; i++) {\n            bool found = true;\n            for(int p = 0; p < len; p++) {\n                if(mat[(i+p)%N][j] != s[p]) {\n                    found = false;\n                    break;\n                }\n            }\n            if(found) return true;\n        }\n    }\n    \n    return false;\n}\n\nint countMatches(char mat[20][20]) {\n    int c = 0;\n    for(const auto& s : strings) {\n        if(isSubsequence(s, mat)) c++;\n    }\n    return c;\n}\n\nvoid runSA(mt19937& rng, chrono::steady_clock::time_point deadline, double timeLimit, \n           double initTemp, double coolingRate, int warmstartPercent) {\n    char currentMatrix[20][20];\n    \n    uniform_int_distribution<int> charDist(0, 7);\n    uniform_int_distribution<int> posDist(0, N-1);\n    uniform_int_distribution<int> dirDist(0, 1);\n    uniform_real_distribution<double> realDist(0, 1);\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            currentMatrix[i][j] = 'A' + charDist(rng);\n        }\n    }\n    \n    int numPlace = (M * warmstartPercent) / 100;\n    vector<int> indices(M);\n    iota(indices.begin(), indices.end(), 0);\n    shuffle(indices.begin(), indices.end(), rng);\n    \n    for(int k = 0; k < numPlace; k++) {\n        const auto& s = strings[indices[k]];\n        int len = (int)s.length();\n        int i = posDist(rng);\n        int j = posDist(rng);\n        int dir = dirDist(rng);\n        \n        if(dir == 0) {\n            for(int p = 0; p < len; p++) {\n                currentMatrix[i][(j+p)%N] = s[p];\n            }\n        } else {\n            for(int p = 0; p < len; p++) {\n                currentMatrix[(i+p)%N][j] = s[p];\n            }\n        }\n    }\n    \n    int currentMatches = countMatches(currentMatrix);\n    if(currentMatches > bestMatches) {\n        bestMatches = currentMatches;\n        memcpy(bestMatrix, currentMatrix, sizeof(currentMatrix));\n    }\n    \n    double temp = initTemp;\n    auto runDeadline = chrono::steady_clock::now() + chrono::milliseconds((long long)(timeLimit * 1000));\n    \n    while(chrono::steady_clock::now() < runDeadline && chrono::steady_clock::now() < deadline && temp > 0.0001) {\n        int i = posDist(rng);\n        int j = posDist(rng);\n        \n        char old = currentMatrix[i][j];\n        char newChar = 'A' + charDist(rng);\n        \n        if(newChar == old) continue;\n        \n        currentMatrix[i][j] = newChar;\n        int newMatches = countMatches(currentMatrix);\n        int delta = newMatches - currentMatches;\n        \n        if(delta >= 0) {\n            currentMatches = newMatches;\n            if(currentMatches > bestMatches) {\n                bestMatches = currentMatches;\n                memcpy(bestMatrix, currentMatrix, sizeof(currentMatrix));\n            }\n        } else {\n            if(realDist(rng) < exp((double)delta / max(temp, 0.0001))) {\n                currentMatches = newMatches;\n            } else {\n                currentMatrix[i][j] = old;\n            }\n        }\n        \n        temp *= coolingRate;\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    strings.resize(M);\n    for(int i = 0; i < M; i++) {\n        cin >> strings[i];\n    }\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto deadline = chrono::steady_clock::now() + chrono::milliseconds(2850);\n    \n    // 12 runs with focused parameter ranges and better time allocation\n    // Focus on mid-range parameters that have proven effective\n    vector<double> initTemps = {\n        26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 38.0, 40.0,\n        29.0, 33.0, 37.0, 39.0\n    };\n    vector<double> coolingRates = {\n        0.999940, 0.999938, 0.999935, 0.999933, 0.999930, 0.999928, 0.999925, 0.999923,\n        0.999937, 0.999932, 0.999927, 0.999922\n    };\n    vector<int> warmstartPercents = {\n        50, 50, 50, 50, 50, 50, 50, 50,\n        45, 55, 50, 50\n    };\n    \n    double timePerRun = 0.238;  // 12 \u00d7 238ms \u2248 2856ms\n    \n    int runCount = 0;\n    while(chrono::steady_clock::now() < deadline && runCount < (int)initTemps.size()) {\n        runSA(rng, deadline, timePerRun, initTemps[runCount], coolingRates[runCount], warmstartPercents[runCount]);\n        runCount++;\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            cout << bestMatrix[i][j];\n        }\n        cout << '\\n';\n    }\n    \n    return 0;\n}","ahc005":"#include<bits/stdc++.h>\nusing namespace std;\n\nint N, si, sj;\nvector<string> grid;\nmap<pair<int,int>, set<pair<int,int>>> visCache;\nmap<pair<pair<int,int>, pair<int,int>>, int> distCache;\n\nset<pair<int,int>> getVis(int i, int j) {\n    auto key = make_pair(i, j);\n    if (visCache.count(key)) return visCache[key];\n    \n    set<pair<int,int>> res;\n    if (i < 0 || i >= N || j < 0 || j >= N || grid[i][j] == '#') return res;\n    \n    for (int jj = j; jj < N && grid[i][jj] != '#'; jj++) res.insert({i, jj});\n    for (int jj = j - 1; jj >= 0 && grid[i][jj] != '#'; jj--) res.insert({i, jj});\n    for (int ii = i; ii < N && grid[ii][j] != '#'; ii++) res.insert({ii, j});\n    for (int ii = i - 1; ii >= 0 && grid[ii][j] != '#'; ii--) res.insert({ii, j});\n    \n    return visCache[key] = res;\n}\n\nint getDist(pair<int,int> f, pair<int,int> t) {\n    if (f == t) return 0;\n    auto key = f < t ? make_pair(f, t) : make_pair(t, f);\n    if (distCache.count(key)) return distCache[key];\n    \n    map<pair<int,int>, int> d;\n    priority_queue<pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, greater<>> pq;\n    pq.push({0, f});\n    d[f] = 0;\n    \n    while (!pq.empty()) {\n        auto [c, p] = pq.top();\n        pq.pop();\n        if (p == t) return distCache[key] = c;\n        if (d.count(p) && d[p] < c) continue;\n        \n        auto [i, j] = p;\n        int di[] = {-1, 1, 0, 0}, dj[] = {0, 0, -1, 1};\n        for (int dd = 0; dd < 4; dd++) {\n            int ni = i + di[dd], nj = j + dj[dd];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && grid[ni][nj] != '#') {\n                int nc = c + (grid[ni][nj] - '0');\n                if (!d.count({ni, nj}) || d[{ni, nj}] > nc) {\n                    d[{ni, nj}] = nc;\n                    pq.push({nc, {ni, nj}});\n                }\n            }\n        }\n    }\n    return distCache[key] = 1e9;\n}\n\nvector<pair<int,int>> getPath(pair<int,int> f, pair<int,int> t) {\n    if (f == t) return {f};\n    \n    map<pair<int,int>, pair<int,int>> par;\n    map<pair<int,int>, int> d;\n    priority_queue<pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, greater<>> pq;\n    \n    pq.push({0, f});\n    d[f] = 0;\n    par[f] = {-1, -1};\n    \n    while (!pq.empty()) {\n        auto [c, p] = pq.top();\n        pq.pop();\n        if (p == t) break;\n        if (d.count(p) && d[p] < c) continue;\n        \n        auto [i, j] = p;\n        int di[] = {-1, 1, 0, 0}, dj[] = {0, 0, -1, 1};\n        for (int dd = 0; dd < 4; dd++) {\n            int ni = i + di[dd], nj = j + dj[dd];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && grid[ni][nj] != '#') {\n                int nc = c + (grid[ni][nj] - '0');\n                if (!d.count({ni, nj}) || d[{ni, nj}] > nc) {\n                    d[{ni, nj}] = nc;\n                    par[{ni, nj}] = {i, j};\n                    pq.push({nc, {ni, nj}});\n                }\n            }\n        }\n    }\n    \n    vector<pair<int,int>> path;\n    auto cur = t;\n    while (cur != make_pair(-1, -1)) {\n        path.push_back(cur);\n        cur = par[cur];\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> si >> sj;\n    grid.resize(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    \n    vector<pair<int,int>> roads;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            if (grid[i][j] != '#') roads.push_back({i, j});\n    \n    for (auto r : roads) getVis(r.first, r.second);\n    \n    set<pair<int,int>> seen;\n    vector<pair<int,int>> way;\n    \n    way.push_back({si, sj});\n    for (auto c : getVis(si, sj)) seen.insert(c);\n    \n    // Greedy set cover\n    while ((int)seen.size() < (int)roads.size() && way.size() < 250) {\n        pair<int,int> best = {-1, -1};\n        int bestCnt = -1;\n        \n        for (auto r : roads) {\n            int cnt = 0;\n            for (auto c : getVis(r.first, r.second)) {\n                if (!seen.count(c)) cnt++;\n            }\n            if (cnt > bestCnt) {\n                bestCnt = cnt;\n                best = r;\n            }\n        }\n        \n        if (bestCnt <= 0) break;\n        way.push_back(best);\n        for (auto c : getVis(best.first, best.second)) seen.insert(c);\n    }\n    \n    // Ensure all roads covered\n    for (auto r : roads) {\n        if (!seen.count(r) && way.size() < 350) {\n            way.push_back(r);\n            for (auto c : getVis(r.first, r.second)) seen.insert(c);\n        }\n    }\n    \n    // Nearest neighbor TSP\n    if (way.size() > 2) {\n        vector<pair<int,int>> ordered;\n        vector<bool> used(way.size(), false);\n        ordered.push_back(way[0]);\n        used[0] = true;\n        \n        for (size_t i = 1; i < way.size(); i++) {\n            int best = -1, bestD = 1e9;\n            for (size_t j = 0; j < way.size(); j++) {\n                if (!used[j]) {\n                    int d = getDist(ordered.back(), way[j]);\n                    if (d < bestD) {\n                        bestD = d;\n                        best = j;\n                    }\n                }\n            }\n            if (best != -1) {\n                ordered.push_back(way[best]);\n                used[best] = true;\n            }\n        }\n        way = ordered;\n    }\n    \n    way.push_back({si, sj});\n    \n    string res = \"\";\n    for (size_t i = 0; i + 1 < way.size(); i++) {\n        auto path = getPath(way[i], way[i + 1]);\n        for (size_t j = 1; j < path.size(); j++) {\n            int pi = path[j-1].first, pj = path[j-1].second;\n            int ni = path[j].first, nj = path[j].second;\n            if (ni < pi) res += 'U';\n            else if (ni > pi) res += 'D';\n            else if (nj < pj) res += 'L';\n            else res += 'R';\n        }\n    }\n    \n    cout << res << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n    \n    vector<vector<int>> d(N, vector<int>(K));\n    double sum_diff = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < K; j++) {\n            cin >> d[i][j];\n            sum_diff += d[i][j];\n        }\n    }\n    double avg_diff = sum_diff / (N * K);\n    \n    vector<set<int>> deps(N);\n    vector<vector<int>> rev_deps(N);\n    \n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        deps[v].insert(u);\n        rev_deps[u].push_back(v);\n    }\n    \n    // Compute criticality: longest path + immediate dependents weight\n    vector<int> crit(N, -1);\n    vector<int> immed_deps(N, 0);\n    \n    function<int(int)> calc_crit = [&](int u) {\n        if (crit[u] != -1) return crit[u];\n        int maxc = 0;\n        for (int v : rev_deps[u]) {\n            maxc = max(maxc, 1 + calc_crit(v));\n        }\n        return crit[u] = maxc;\n    };\n    \n    for (int i = 0; i < N; i++) {\n        calc_crit(i);\n        immed_deps[i] = rev_deps[i].size();\n    }\n    \n    vector<int> task_status(N, -1);\n    vector<int> task_start_day(N, -1);\n    vector<int> member_task(M, -1);\n    \n    // Slightly more optimistic initial skills\n    vector<vector<double>> skills(M, vector<double>(K, avg_diff * 0.55));\n    \n    // Track member experience for adaptive learning\n    vector<int> member_tasks_completed(M, 0);\n    \n    auto estimate_time = [&](int m, int t) {\n        double deficit = 0;\n        for (int k = 0; k < K; k++) {\n            deficit += max(0.0, (double)d[t][k] - skills[m][k]);\n        }\n        return max(1.0, deficit);\n    };\n    \n    int day = 0, completed = 0;\n    \n    while (day < 2000 && completed < N) {\n        day++;\n        \n        // Find all available tasks\n        vector<int> available;\n        for (int t = 0; t < N; t++) {\n            if (task_status[t] != -1) continue;\n            bool ok = true;\n            for (int dep : deps[t]) {\n                if (task_status[dep] < 2000) {\n                    ok = false;\n                    break;\n                }\n            }\n            if (ok) available.push_back(t);\n        }\n        \n        // Sort by criticality (combined metric)\n        sort(available.begin(), available.end(), [&](int a, int b) {\n            // Primary: longest path\n            // Secondary: immediate dependents (for tie-breaking and blocking optimization)\n            // Tertiary: task difficulty (prefer harder for learning)\n            int crit_a = crit[a] * 10 + immed_deps[a];\n            int crit_b = crit[b] * 10 + immed_deps[b];\n            if (crit_a != crit_b) return crit_a > crit_b;\n            \n            // Among same criticality, prefer harder tasks (they block less)\n            double diff_a = 0, diff_b = 0;\n            for (int k = 0; k < K; k++) {\n                diff_a += d[a][k];\n                diff_b += d[b][k];\n            }\n            return diff_a > diff_b;\n        });\n        \n        vector<pair<int, int>> assignments;\n        vector<bool> assigned(M, false);\n        \n        // Assign each available task to the idle member who can do it fastest\n        for (int t : available) {\n            int best_m = -1;\n            double best_time = 1e18;\n            \n            for (int m = 0; m < M; m++) {\n                if (member_task[m] != -1) continue;\n                if (assigned[m]) continue;\n                \n                double time_est = estimate_time(m, t);\n                if (time_est < best_time) {\n                    best_time = time_est;\n                    best_m = m;\n                }\n            }\n            \n            if (best_m != -1) {\n                assignments.push_back({best_m + 1, t + 1});\n                member_task[best_m] = t;\n                task_status[t] = day;\n                task_start_day[t] = day;\n                assigned[best_m] = true;\n            }\n        }\n        \n        cout << assignments.size();\n        for (auto [m, t] : assignments) {\n            cout << \" \" << m << \" \" << t;\n        }\n        cout << \"\\n\";\n        cout.flush();\n        \n        int n;\n        cin >> n;\n        if (n == -1) break;\n        \n        for (int i = 0; i < n; i++) {\n            int m;\n            cin >> m;\n            m--;\n            \n            if (member_task[m] != -1) {\n                int t = member_task[m];\n                int dur = day - task_start_day[t] + 1;\n                \n                task_status[t] = 2000 + day;\n                member_task[m] = -1;\n                completed++;\n                member_tasks_completed[m]++;\n                \n                // Adaptive learning: more aggressive as member gains experience\n                double learning_factor = 1.0 + 0.05 * member_tasks_completed[m];\n                \n                if (dur == 1) {\n                    // Perfect completion: member has all required skills\n                    for (int k = 0; k < K; k++) {\n                        skills[m][k] = max(skills[m][k], (double)d[t][k] * 0.98);\n                    }\n                } else {\n                    // Infer skill deficit from duration\n                    // Less conservative: use dur - 0.5 instead of dur - 1.0\n                    double w_est = max(0.0, (double)dur - 0.5);\n                    \n                    double total_req = 0;\n                    for (int k = 0; k < K; k++) {\n                        total_req += d[t][k];\n                    }\n                    \n                    if (total_req > 1e-9) {\n                        for (int k = 0; k < K; k++) {\n                            double proportion = (double)d[t][k] / total_req;\n                            double inferred_skill = d[t][k] - proportion * w_est;\n                            // More aggressive learning with experience\n                            double learning_multiplier = 1.0 - (0.02 * learning_factor);\n                            skills[m][k] = max(skills[m][k], \n                                              max(0.0, inferred_skill * learning_multiplier));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nll manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    struct Order {\n        int a, b, c, d;\n    };\n    \n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; i++) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n    }\n    \n    auto buildRouteGreedy = [&](const vector<int>& orders_to_use, mt19937* rng = nullptr) {\n        vector<pair<int, int>> route;\n        route.push_back({400, 400});\n        \n        vector<bool> pickup_done(orders_to_use.size(), false);\n        vector<bool> delivery_done(orders_to_use.size(), false);\n        \n        int cx = 400, cy = 400;\n        \n        for (int step = 0; step < (int)orders_to_use.size() * 2; step++) {\n            int best_i = -1, best_type = -1;\n            ll best_dist = LLONG_MAX;\n            \n            for (int i = 0; i < (int)orders_to_use.size(); i++) {\n                if (!pickup_done[i]) {\n                    ll d = manhattan(cx, cy, orders[orders_to_use[i]].a, orders[orders_to_use[i]].b);\n                    if (d < best_dist || (rng && d == best_dist && uniform_int_distribution<int>(0, 1)(*rng))) {\n                        best_dist = d;\n                        best_i = i;\n                        best_type = 0;\n                    }\n                }\n                if (pickup_done[i] && !delivery_done[i]) {\n                    ll d = manhattan(cx, cy, orders[orders_to_use[i]].c, orders[orders_to_use[i]].d);\n                    if (d < best_dist || (rng && d == best_dist && uniform_int_distribution<int>(0, 1)(*rng))) {\n                        best_dist = d;\n                        best_i = i;\n                        best_type = 1;\n                    }\n                }\n            }\n            \n            if (best_i == -1) break;\n            \n            if (best_type == 0) {\n                cx = orders[orders_to_use[best_i]].a;\n                cy = orders[orders_to_use[best_i]].b;\n                pickup_done[best_i] = true;\n            } else {\n                cx = orders[orders_to_use[best_i]].c;\n                cy = orders[orders_to_use[best_i]].d;\n                delivery_done[best_i] = true;\n            }\n            \n            route.push_back({cx, cy});\n        }\n        \n        route.push_back({400, 400});\n        return route;\n    };\n    \n    auto calcDist = [](const vector<pair<int, int>>& route) {\n        ll total = 0;\n        for (size_t i = 0; i < route.size() - 1; i++) {\n            total += manhattan(route[i].first, route[i].second, \n                             route[i+1].first, route[i+1].second);\n        }\n        return total;\n    };\n    \n    auto check_valid = [&](const vector<pair<int, int>>& r, const vector<int>& orders_to_use) {\n        for (int i = 0; i < (int)orders_to_use.size(); i++) {\n            int pickup_idx = -1, delivery_idx = -1;\n            for (int j = 0; j < (int)r.size(); j++) {\n                if (r[j].first == orders[orders_to_use[i]].a && r[j].second == orders[orders_to_use[i]].b) {\n                    pickup_idx = j;\n                }\n                if (r[j].first == orders[orders_to_use[i]].c && r[j].second == orders[orders_to_use[i]].d) {\n                    delivery_idx = j;\n                }\n            }\n            if (pickup_idx == -1 || delivery_idx == -1 || pickup_idx > delivery_idx) {\n                return false;\n            }\n        }\n        return true;\n    };\n    \n    auto improveRoute2Opt = [&](vector<pair<int, int>> route, const vector<int>& orders_to_use) {\n        bool improved = true;\n        int iterations = 0;\n        int max_no_improve = 0;\n        \n        while (iterations < 200 && max_no_improve < 50) {\n            improved = false;\n            iterations++;\n            \n            for (int i = 1; i < (int)route.size() - 2; i++) {\n                for (int j = i + 2; j < (int)route.size() - 1; j++) {\n                    ll old_cost = manhattan(route[i-1].first, route[i-1].second, route[i].first, route[i].second) +\n                                  manhattan(route[j].first, route[j].second, route[j+1].first, route[j+1].second);\n                    ll new_cost = manhattan(route[i-1].first, route[i-1].second, route[j].first, route[j].second) +\n                                  manhattan(route[i].first, route[i].second, route[j+1].first, route[j+1].second);\n                    \n                    if (new_cost < old_cost) {\n                        auto new_route = route;\n                        reverse(new_route.begin() + i, new_route.begin() + j + 1);\n                        \n                        if (check_valid(new_route, orders_to_use)) {\n                            route = new_route;\n                            improved = true;\n                            max_no_improve = 0;\n                            break;\n                        }\n                    }\n                }\n                if (improved) break;\n            }\n            \n            if (!improved) max_no_improve++;\n        }\n        \n        return route;\n    };\n    \n    ll best_overall_dist = LLONG_MAX;\n    vector<int> best_selected;\n    vector<pair<int, int>> best_route;\n    \n    // Deterministic criteria\n    vector<vector<pair<ll, int>>> all_selections;\n    \n    for (int criterion = 0; criterion < 10; criterion++) {\n        vector<pair<ll, int>> costs;\n        \n        for (int i = 0; i < 1000; i++) {\n            ll cost = 0;\n            switch(criterion) {\n                case 0: // Distance to office\n                    cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                           manhattan(400, 400, orders[i].c, orders[i].d);\n                    break;\n                case 1: // Pickup-delivery distance\n                    cost = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n                    break;\n                case 2: // Balanced\n                    cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                           manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d) +\n                           manhattan(orders[i].c, orders[i].d, 400, 400);\n                    break;\n                case 3: // Distance from center\n                    cost = abs(orders[i].a - 400) + abs(orders[i].b - 400) +\n                           abs(orders[i].c - 400) + abs(orders[i].d - 400);\n                    break;\n                case 4: // Spread\n                {\n                    int minx = min(orders[i].a, orders[i].c);\n                    int maxx = max(orders[i].a, orders[i].c);\n                    int miny = min(orders[i].b, orders[i].d);\n                    int maxy = max(orders[i].b, orders[i].d);\n                    cost = (maxx - minx) + (maxy - miny);\n                    break;\n                }\n                case 5: // Midpoint distance\n                {\n                    int mx = (orders[i].a + orders[i].c) / 2;\n                    int my = (orders[i].b + orders[i].d) / 2;\n                    cost = manhattan(400, 400, mx, my);\n                    break;\n                }\n                case 6: // Max coordinate distance\n                    cost = max(abs(orders[i].a - 400), abs(orders[i].b - 400)) +\n                           max(abs(orders[i].c - 400), abs(orders[i].d - 400));\n                    break;\n                case 7: // Chebyshev-like\n                    cost = max(abs(orders[i].a - 400) + abs(orders[i].c - 400),\n                              abs(orders[i].b - 400) + abs(orders[i].d - 400));\n                    break;\n                case 8: // Average of office distances\n                    cost = (manhattan(400, 400, orders[i].a, orders[i].b) +\n                           manhattan(400, 400, orders[i].c, orders[i].d)) / 2;\n                    break;\n                case 9: // Weighted: prefer short deliveries near office\n                    cost = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d) +\n                           min(manhattan(400, 400, orders[i].a, orders[i].b),\n                               manhattan(400, 400, orders[i].c, orders[i].d)) / 2;\n                    break;\n            }\n            costs.push_back({cost, i});\n        }\n        sort(costs.begin(), costs.end());\n        all_selections.push_back(costs);\n    }\n    \n    // Try deterministic selections\n    for (const auto& costs : all_selections) {\n        vector<int> selected(50);\n        for (int i = 0; i < 50; i++) {\n            selected[i] = costs[i].second;\n        }\n        \n        auto route = buildRouteGreedy(selected);\n        route = improveRoute2Opt(route, selected);\n        ll dist = calcDist(route);\n        \n        if (dist < best_overall_dist) {\n            best_overall_dist = dist;\n            best_selected = selected;\n            best_route = route;\n        }\n    }\n    \n    // Try random weighted selections\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    for (int trial = 0; trial < 80; trial++) {\n        vector<pair<ll, int>> weighted_costs;\n        \n        // Choose a random weighting scheme\n        int scheme = uniform_int_distribution<int>(0, 3)(rng);\n        \n        for (int i = 0; i < 1000; i++) {\n            ll base_cost = 0;\n            \n            switch(scheme) {\n                case 0:\n                    base_cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                               manhattan(400, 400, orders[i].c, orders[i].d);\n                    break;\n                case 1:\n                    base_cost = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n                    break;\n                case 2:\n                    base_cost = abs(orders[i].a - 400) + abs(orders[i].b - 400) +\n                               abs(orders[i].c - 400) + abs(orders[i].d - 400);\n                    break;\n                case 3:\n                {\n                    int mx = (orders[i].a + orders[i].c) / 2;\n                    int my = (orders[i].b + orders[i].d) / 2;\n                    base_cost = manhattan(400, 400, mx, my);\n                    break;\n                }\n            }\n            \n            ll random_offset = uniform_int_distribution<ll>(0, base_cost / 3)(rng);\n            weighted_costs.push_back({base_cost + random_offset, i});\n        }\n        \n        sort(weighted_costs.begin(), weighted_costs.end());\n        \n        vector<int> selected(50);\n        for (int i = 0; i < 50; i++) {\n            selected[i] = weighted_costs[i].second;\n        }\n        \n        auto route = buildRouteGreedy(selected, &rng);\n        route = improveRoute2Opt(route, selected);\n        ll dist = calcDist(route);\n        \n        if (dist < best_overall_dist) {\n            best_overall_dist = dist;\n            best_selected = selected;\n            best_route = route;\n        }\n    }\n    \n    // Output\n    cout << \"50\";\n    for (int i = 0; i < 50; i++) {\n        cout << \" \" << (best_selected[i] + 1);\n    }\n    cout << \"\\n\";\n    \n    cout << best_route.size();\n    for (const auto& p : best_route) {\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass UnionFind {\npublic:\n    vector<int> parent;\n    \n    UnionFind(int n) : parent(n) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    \n    int find(int x) {\n        if (parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    \n    bool unite(int x, int y) {\n        x = find(x);\n        y = find(y);\n        if (x == y) return false;\n        parent[y] = x;\n        return true;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N = 400, M = 1995;\n    vector<pair<int, int>> coords(N);\n    vector<pair<int, int>> edges(M);\n    vector<int> d(M);\n    \n    for (int i = 0; i < N; i++) {\n        cin >> coords[i].first >> coords[i].second;\n    }\n    \n    for (int i = 0; i < M; i++) {\n        cin >> edges[i].first >> edges[i].second;\n        int u = edges[i].first, v = edges[i].second;\n        long long dx = (long long)coords[u].first - coords[v].first;\n        long long dy = (long long)coords[u].second - coords[v].second;\n        d[i] = (int)round(sqrt((double)(dx*dx + dy*dy)));\n    }\n    \n    UnionFind uf(N);\n    int edges_needed = N - 1;\n    \n    for (int i = 0; i < M; i++) {\n        int length;\n        cin >> length;\n        \n        int u = edges[i].first, v = edges[i].second;\n        \n        bool accept = false;\n        \n        if (edges_needed > 0 && uf.find(u) != uf.find(v)) {\n            // Tree edge (connects different components)\n            int edges_remaining = M - i;\n            \n            if (edges_remaining <= edges_needed) {\n                // Critical: must accept to guarantee connectivity\n                accept = true;\n            } else {\n                // Position-based gentle threshold\n                // Goes from 2.0*d[i] at start to 3.0*d[i] at end\n                // threshold = 2.0 + 1.0 * (i / M)\n                // To avoid precision issues, use: length * M <= d[i] * (2*M + i)\n                long long threshold_num = (long long)d[i] * (2LL * M + i);\n                long long threshold_denom = (long long)M;\n                \n                if ((long long)length * threshold_denom <= threshold_num) {\n                    accept = true;\n                }\n            }\n        }\n        \n        if (accept) {\n            uf.unite(u, v);\n            edges_needed--;\n        }\n        \n        cout << (accept ? 1 : 0) << '\\n';\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    \n    int N;\n    cin >> N;\n    vector<pair<int,int>> pets(N);\n    vector<int> pet_types(N);\n    for(int i = 0; i < N; i++){\n        int x, y, t;\n        cin >> x >> y >> t;\n        pets[i] = {x-1, y-1};\n        pet_types[i] = t;\n    }\n    \n    int M;\n    cin >> M;\n    vector<pair<int,int>> humans(M);\n    for(int i = 0; i < M; i++){\n        int x, y;\n        cin >> x >> y;\n        humans[i] = {x-1, y-1};\n    }\n    \n    for(int turn = 0; turn < 300; turn++){\n        string actions(M, '.');\n        \n        // Dynamic target based on game phase\n        int target_x, target_y;\n        if(turn < 80){\n            // Phase 1: Move toward top-left corner\n            target_x = 5;\n            target_y = 5;\n        } else if(turn < 200){\n            // Phase 2: Consolidate and expand slightly\n            target_x = 8;\n            target_y = 8;\n        } else {\n            // Phase 3: Hold position\n            target_x = 8;\n            target_y = 8;\n        }\n        \n        // Each human moves toward the target\n        for(int i = 0; i < M; i++){\n            int x = humans[i].first;\n            int y = humans[i].second;\n            \n            if(x > target_x) actions[i] = 'U';\n            else if(x < target_x) actions[i] = 'D';\n            else if(y > target_y) actions[i] = 'L';\n            else if(y < target_y) actions[i] = 'R';\n            else actions[i] = '.';\n        }\n        \n        cout << actions << endl;\n        cout.flush();\n        \n        // Read pet movements\n        for(int i = 0; i < N; i++){\n            string move;\n            cin >> move;\n            \n            // Apply movement to each pet\n            for(char c : move){\n                if(c == 'U' && pets[i].first > 0) pets[i].first--;\n                else if(c == 'D' && pets[i].first < 29) pets[i].first++;\n                else if(c == 'L' && pets[i].second > 0) pets[i].second--;\n                else if(c == 'R' && pets[i].second < 29) pets[i].second++;\n            }\n        }\n        \n        // Update human positions based on executed actions\n        for(int i = 0; i < M; i++){\n            if(actions[i] == 'U' && humans[i].first > 0) humans[i].first--;\n            else if(actions[i] == 'D' && humans[i].first < 29) humans[i].first++;\n            else if(actions[i] == 'L' && humans[i].second > 0) humans[i].second--;\n            else if(actions[i] == 'R' && humans[i].second < 29) humans[i].second++;\n        }\n    }\n    \n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n    \n    vector<string> h(20), v(19);\n    for (int i = 0; i < 20; i++) cin >> h[i];\n    for (int i = 0; i < 19; i++) cin >> v[i];\n    \n    // BFS to find shortest path\n    map<pair<int,int>, pair<pair<int,int>, char>> parent;\n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    parent[{si, sj}] = {{-1, -1}, ' '};\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        vector<tuple<int, int, char, bool>> moves = {\n            {i-1, j, 'U', i > 0 && v[i-1][j] == '0'},\n            {i+1, j, 'D', i < 19 && v[i][j] == '0'},\n            {i, j-1, 'L', j > 0 && h[i][j-1] == '0'},\n            {i, j+1, 'R', j < 19 && h[i][j] == '0'}\n        };\n        \n        for (auto [ni, nj, dir, valid] : moves) {\n            if (valid && parent.find({ni, nj}) == parent.end()) {\n                parent[{ni, nj}] = {{i, j}, dir};\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    // Reconstruct path\n    string path = \"\";\n    {\n        int i = ti, j = tj;\n        while (parent[{i, j}].first.first != -1) {\n            char c = parent[{i, j}].second;\n            path = c + path;\n            auto [pi, pj] = parent[{i, j}].first;\n            i = pi;\n            j = pj;\n        }\n    }\n    \n    // Try different repetition factors\n    int n = path.length();\n    string best_path = path;\n    double best_score = 0;\n    \n    for (int r = 1; r * n <= 200; r++) {\n        // Probability of success: (1 - p^r)^n\n        double p_fail = pow(p, (double)r);\n        double p_succ_one = 1.0 - p_fail;\n        double p_succ_all = pow(p_succ_one, (double)n);\n        \n        int length = r * n;\n        double expected_score = p_succ_all * (401.0 - length);\n        \n        if (expected_score > best_score) {\n            best_score = expected_score;\n            best_path = \"\";\n            for (int k = 0; k < r; k++) best_path += path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\n\nint di[] = {0, -1, 0, 1};\nint dj[] = {-1, 0, 1, 0};\n\nint to[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1},\n};\n\nint grid[N][N];\nint rotations[N][N];\nbool visited[N][N][4];\n\ninline int getTileType(int i, int j) {\n    int base = grid[i][j];\n    int rot = rotations[i][j];\n    if (base < 4) return (base + rot) % 4;\n    if (base < 6) return 4 + (rot % 2);\n    return 6 + (rot % 2);\n}\n\nint computeLoopLength(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    for (int iter = 0; iter < 5000; iter++) {\n        int cur = getTileType(i, j);\n        int d2 = to[cur][d];\n        if (d2 == -1) return 0;\n        i += di[d2];\n        j += dj[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (i == si && j == sj && d == sd) return length;\n    }\n    return 0;\n}\n\nlong long computeScore() {\n    memset(visited, false, sizeof(visited));\n    vector<int> loops;\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            for (int d = 0; d < 4; d++) {\n                if (!visited[i][j][d]) {\n                    int len = computeLoopLength(i, j, d);\n                    if (len > 0) {\n                        loops.push_back(len);\n                        int ii = i, jj = j, dd = d;\n                        for (int step = 0; step < len; step++) {\n                            visited[ii][jj][dd] = true;\n                            int cur = getTileType(ii, jj);\n                            int d2 = to[cur][dd];\n                            ii += di[d2];\n                            jj += dj[d2];\n                            dd = (d2 + 2) % 4;\n                        }\n                    } else {\n                        visited[i][j][d] = true;\n                    }\n                }\n            }\n        }\n    }\n    if (loops.size() < 2) return 0;\n    sort(loops.rbegin(), loops.rend());\n    return (long long)loops[0] * loops[1];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    string line;\n    for (int i = 0; i < N; i++) {\n        cin >> line;\n        for (int j = 0; j < N; j++) {\n            grid[i][j] = line[j] - '0';\n        }\n    }\n    \n    // Use random_device for non-deterministic seed\n    random_device rd;\n    mt19937 rng(rd());\n    auto start = chrono::steady_clock::now();\n    \n    long long bestScore = 0;\n    int best_rotations[N][N];\n    memset(best_rotations, 0, sizeof(best_rotations));\n    \n    // 3 restarts with different initializations and adaptive temperature\n    int moves_per_restart[] = {140, 110, 80};\n    double init_temp[] = {120.0, 100.0, 80.0};\n    \n    for (int restart = 0; restart < 3; restart++) {\n        long long elapsed = chrono::duration_cast<chrono::milliseconds>(\n                chrono::steady_clock::now() - start).count();\n        \n        if (elapsed > 1750) break;\n        \n        if (restart == 0) {\n            // All zeros - good starting point\n            memset(rotations, 0, sizeof(rotations));\n        } else if (restart == 1) {\n            // Sparse random initialization\n            memset(rotations, 0, sizeof(rotations));\n            int count = 90;\n            for (int k = 0; k < count; k++) {\n                int i = rng() % N;\n                int j = rng() % N;\n                rotations[i][j] = rng() % 4;\n            }\n        } else {\n            // Full random initialization\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    rotations[i][j] = rng() % 4;\n                }\n            }\n        }\n        \n        long long currentScore = computeScore();\n        if (currentScore > bestScore) {\n            bestScore = currentScore;\n            memcpy(best_rotations, rotations, sizeof(int) * N * N);\n        }\n        \n        double temperature = init_temp[restart];\n        \n        for (int move = 0; move < moves_per_restart[restart]; move++) {\n            long long elapsed_now = chrono::duration_cast<chrono::milliseconds>(\n                    chrono::steady_clock::now() - start).count();\n            if (elapsed_now > 1770) break;\n            \n            int i = rng() % N;\n            int j = rng() % N;\n            int oldRot = rotations[i][j];\n            int newRot = rng() % 4;\n            \n            if (newRot == oldRot) {\n                move--;\n                continue;\n            }\n            \n            rotations[i][j] = newRot;\n            long long newScore = computeScore();\n            \n            double delta = (double)(newScore - currentScore);\n            \n            if (delta >= 0) {\n                currentScore = newScore;\n                if (newScore > bestScore) {\n                    bestScore = newScore;\n                    memcpy(best_rotations, rotations, sizeof(int) * N * N);\n                }\n            } else {\n                // Temperature-based acceptance: accept worse moves with decreasing probability\n                double acceptance_threshold = exp(delta / (temperature + 1.0));\n                if ((double)rng() / rng.max() < acceptance_threshold) {\n                    currentScore = newScore;\n                } else {\n                    rotations[i][j] = oldRot;\n                }\n            }\n            \n            // Exponential temperature decay\n            temperature *= 0.985;\n        }\n    }\n    \n    memcpy(rotations, best_rotations, sizeof(rotations));\n    \n    string output(N * N, '0');\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            output[i * N + j] = '0' + rotations[i][j];\n        }\n    }\n    cout << output << endl;\n    \n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nchrono::high_resolution_clock::time_point start_time;\n\nbool hasEdge(const vector<vector<int>>& board, int i1, int j1, int i2, int j2) {\n    if (i2 < 0 || i2 >= N || j2 < 0 || j2 >= N) return false;\n    if (board[i1][j1] == 0 || board[i2][j2] == 0) return false;\n    \n    int dy = i2 - i1, dx = j2 - j1;\n    if (dy == -1 && dx == 0) return (board[i1][j1] & 2) && (board[i2][j2] & 8);\n    if (dy == 1 && dx == 0) return (board[i1][j1] & 8) && (board[i2][j2] & 2);\n    if (dy == 0 && dx == -1) return (board[i1][j1] & 1) && (board[i2][j2] & 4);\n    if (dy == 0 && dx == 1) return (board[i1][j1] & 4) && (board[i2][j2] & 1);\n    return false;\n}\n\nint largestTree(const vector<vector<int>>& board) {\n    vector<vector<int>> comp(N, vector<int>(N, -1));\n    vector<int> vcount, ecount;\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (board[i][j] == 0 || comp[i][j] != -1) continue;\n            \n            int cid = vcount.size();\n            vcount.push_back(0);\n            ecount.push_back(0);\n            \n            queue<pair<int,int>> q;\n            q.push({i, j});\n            comp[i][j] = cid;\n            \n            while (!q.empty()) {\n                auto [ci, cj] = q.front();\n                q.pop();\n                vcount[cid]++;\n                \n                int di[] = {-1, 1, 0, 0};\n                int dj[] = {0, 0, -1, 1};\n                for (int d = 0; d < 4; d++) {\n                    int ni = ci + di[d];\n                    int nj = cj + dj[d];\n                    if (ni >= 0 && ni < N && nj >= 0 && nj < N && \n                        board[ni][nj] != 0 && comp[ni][nj] == -1 &&\n                        hasEdge(board, ci, cj, ni, nj)) {\n                        comp[ni][nj] = cid;\n                        q.push({ni, nj});\n                    }\n                }\n            }\n        }\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            if (j + 1 < N && hasEdge(board, i, j, i, j+1) && comp[i][j] == comp[i][j+1]) {\n                ecount[comp[i][j]]++;\n            }\n            if (i + 1 < N && hasEdge(board, i, j, i+1, j) && comp[i][j] == comp[i+1][j]) {\n                ecount[comp[i][j]]++;\n            }\n        }\n    }\n    \n    int ans = 0;\n    for (size_t c = 0; c < vcount.size(); c++) {\n        if (ecount[c] == vcount[c] - 1) {\n            ans = max(ans, vcount[c]);\n        }\n    }\n    return ans;\n}\n\ndouble getElapsedTime() {\n    auto now = chrono::high_resolution_clock::now();\n    return chrono::duration<double>(now - start_time).count();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    start_time = chrono::high_resolution_clock::now();\n    srand(chrono::system_clock::now().time_since_epoch().count());\n    \n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    \n    int ei = 0, ej = 0;\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            int v = s[j] >= 'a' ? s[j] - 'a' + 10 : s[j] - '0';\n            board[i][j] = v;\n            if (v == 0) ei = i, ej = j;\n        }\n    }\n    \n    string result = \"\";\n    int best_tree = largestTree(board);\n    \n    int di[] = {-1, 1, 0, 0};\n    int dj[] = {0, 0, -1, 1};\n    char dirs[] = {'U', 'D', 'L', 'R'};\n    \n    int no_improve_count = 0;\n    int last_restart = 0;\n    double time_limit = 2.85;\n    \n    // N-adaptive thresholds: more aggressive for larger N\n    int threshold_no_improve = max(55, N * N - 5);\n    int threshold_min_steps = max(75, N * N * 2 - 25);\n    \n    while ((int)result.length() < T && best_tree < N * N - 1 && getElapsedTime() < time_limit) {\n        vector<pair<int, int>> moves;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = ei + di[d];\n            int nj = ej + dj[d];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                swap(board[ei][ej], board[ni][nj]);\n                int score = largestTree(board);\n                swap(board[ei][ej], board[ni][nj]);\n                moves.push_back({score, d});\n            }\n        }\n        \n        if (moves.empty()) break;\n        \n        sort(moves.rbegin(), moves.rend());\n        \n        // Proven v2 temperature schedule\n        double progress = (double)result.length() / T;\n        double temperature = 20.0 * pow(1.0 - progress, 1.5);\n        \n        int selected_dir = moves[0].second;\n        int current_score = largestTree(board);\n        \n        // Proven v2 move weighting\n        if (temperature > 0.01) {\n            double sum_weight = 0.0;\n            vector<double> weights;\n            \n            for (size_t i = 0; i < moves.size(); i++) {\n                int score = moves[i].first;\n                double delta = score - current_score;\n                double weight;\n                \n                if (delta > 0) {\n                    weight = (1.0 + delta * 0.1) * exp(delta / max(0.2, temperature));\n                } else {\n                    weight = exp(delta / max(0.2, temperature));\n                }\n                \n                weights.push_back(weight);\n                sum_weight += weight;\n            }\n            \n            double rand_val = (double)rand() / RAND_MAX * sum_weight;\n            for (size_t i = 0; i < moves.size(); i++) {\n                rand_val -= weights[i];\n                if (rand_val < 0) {\n                    selected_dir = moves[i].second;\n                    break;\n                }\n            }\n        }\n        \n        int ni = ei + di[selected_dir];\n        int nj = ej + dj[selected_dir];\n        swap(board[ei][ej], board[ni][nj]);\n        result += dirs[selected_dir];\n        ei = ni;\n        ej = nj;\n        \n        int new_tree = largestTree(board);\n        if (new_tree > best_tree) {\n            best_tree = new_tree;\n            no_improve_count = 0;\n            last_restart = result.length();\n        } else {\n            no_improve_count++;\n        }\n        \n        // N-adaptive restart: more aggressive for larger puzzles\n        if (no_improve_count > threshold_no_improve && \n            (int)result.length() - last_restart > threshold_min_steps &&\n            (int)result.length() < T - 200 && \n            getElapsedTime() < time_limit - 0.3) {\n            \n            // Proven v2 walk length\n            int walk_len = min(50, (T - (int)result.length()) / 4);\n            for (int step = 0; step < walk_len; step++) {\n                vector<int> valid;\n                for (int d = 0; d < 4; d++) {\n                    if (ei + di[d] >= 0 && ei + di[d] < N && \n                        ej + dj[d] >= 0 && ej + dj[d] < N) {\n                        valid.push_back(d);\n                    }\n                }\n                if (valid.empty()) break;\n                \n                int d = valid[rand() % valid.size()];\n                swap(board[ei][ej], board[ei + di[d]][ej + dj[d]]);\n                ei += di[d];\n                ej += dj[d];\n                result += dirs[d];\n            }\n            \n            no_improve_count = 0;\n            last_restart = result.length();\n        }\n    }\n    \n    cout << result << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<tuple<long long, long long, long long, long long>> cuts;\nvector<pair<long long, long long>> berries;\n\nvoid recursivePartition(vector<int> indices, int depth, int maxDepth) {\n    // Size <= 12 is the optimal stopping point - creates regions matching 1-10 demand\n    if (indices.size() <= 12 || (int)cuts.size() >= 100 || depth >= maxDepth) return;\n    \n    // Find bounding box of strawberries in this region\n    long long minX = LLONG_MAX, maxX = LLONG_MIN;\n    long long minY = LLONG_MAX, maxY = LLONG_MIN;\n    \n    for (int i : indices) {\n        minX = min(minX, berries[i].first);\n        maxX = max(maxX, berries[i].first);\n        minY = min(minY, berries[i].second);\n        maxY = max(maxY, berries[i].second);\n    }\n    \n    long long rangeX = maxX - minX;\n    long long rangeY = maxY - minY;\n    \n    // If bounding box is tiny, don't split further\n    if (rangeX <= 1 && rangeY <= 1) return;\n    \n    vector<int> left, right;\n    \n    if (rangeX >= rangeY) {\n        // Make a vertical cut at geometric center with offset\n        long long cutX = (minX + maxX) / 2;\n        if (rangeX > 0) {\n            // Better offset: move away from strawberries to avoid cutting on centers\n            cutX += (rangeX > 100 ? 2 : 1);\n        }\n        \n        cuts.push_back({cutX, -1000000000LL, cutX, 1000000000LL});\n        \n        for (int i : indices) {\n            if (berries[i].first < cutX) {\n                left.push_back(i);\n            } else {\n                right.push_back(i);\n            }\n        }\n    } else {\n        // Make a horizontal cut at geometric center with offset\n        long long cutY = (minY + maxY) / 2;\n        if (rangeY > 0) {\n            cutY += (rangeY > 100 ? 2 : 1);\n        }\n        \n        cuts.push_back({-1000000000LL, cutY, 1000000000LL, cutY});\n        \n        for (int i : indices) {\n            if (berries[i].second < cutY) {\n                left.push_back(i);\n            } else {\n                right.push_back(i);\n            }\n        }\n    }\n    \n    // Recursively partition left and right regions\n    if (!left.empty() && left.size() < indices.size()) {\n        recursivePartition(left, depth + 1, maxDepth);\n    }\n    if (!right.empty() && right.size() < indices.size()) {\n        recursivePartition(right, depth + 1, maxDepth);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, K;\n    cin >> N >> K;\n    \n    vector<int> a(11);\n    for (int d = 1; d <= 10; d++) {\n        cin >> a[d];\n    }\n    \n    berries.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> berries[i].first >> berries[i].second;\n    }\n    \n    vector<int> allIndices;\n    for (int i = 0; i < N; i++) {\n        allIndices.push_back(i);\n    }\n    \n    // Optimal parameters: size <= 12, reasonable depth\n    recursivePartition(allIndices, 0, 22);\n    \n    cout << (int)cuts.size() << \"\\n\";\n    for (const auto& [px, py, qx, qy] : cuts) {\n        cout << px << \" \" << py << \" \" << qx << \" \" << qy << \"\\n\";\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nset<pair<int,int>> dots;\nvector<tuple<int,int,int,int>> drawn_edges;\n\nbool segments_overlap(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (y1 == y2 && y3 == y4 && y1 == y3) {\n        int a1 = min(x1, x2), a2 = max(x1, x2);\n        int b1 = min(x3, x4), b2 = max(x3, x4);\n        return max(a1, b1) < min(a2, b2);\n    }\n    if (x1 == x2 && x3 == x4 && x1 == x3) {\n        int a1 = min(y1, y2), a2 = max(y1, y2);\n        int b1 = min(y3, y4), b2 = max(y3, y4);\n        return max(a1, b1) < min(a2, b2);\n    }\n    return false;\n}\n\nbool edge_overlaps_with_drawn(int x1, int y1, int x2, int y2) {\n    for (auto [x3, y3, x4, y4] : drawn_edges) {\n        if (segments_overlap(x1, y1, x2, y2, x3, y3, x4, y4)) {\n            return true;\n        }\n    }\n    return false;\n}\n\nbool check_segment_clear(int x1, int y1, int x2, int y2) {\n    if (x1 == x2) {\n        int miny = min(y1, y2), maxy = max(y1, y2);\n        for (int y = miny + 1; y < maxy; y++) {\n            if (dots.count({x1, y})) return false;\n        }\n    } else if (y1 == y2) {\n        int minx = min(x1, x2), maxx = max(x1, x2);\n        for (int x = minx + 1; x < maxx; x++) {\n            if (dots.count({x, y1})) return false;\n        }\n    } else {\n        int dx = (x2 > x1) ? 1 : -1;\n        int dy = (y2 > y1) ? 1 : -1;\n        int x = x1 + dx, y = y1 + dy;\n        while (x != x2) {\n            if (dots.count({x, y})) return false;\n            x += dx; y += dy;\n        }\n    }\n    return true;\n}\n\ndouble weight(int x, int y) {\n    double c = (N - 1) / 2.0;\n    return (x - c) * (x - c) + (y - c) * (y - c) + 1;\n}\n\nbool try_rect(int p1x, int p1y, int p2x, int p2y, int p3x, int p3y, int p4x, int p4y) {\n    if (dots.count({p1x, p1y})) return false;\n    if (!dots.count({p2x, p2y}) || !dots.count({p3x, p3y}) || !dots.count({p4x, p4y})) return false;\n    \n    if (edge_overlaps_with_drawn(p1x, p1y, p2x, p2y) || \n        edge_overlaps_with_drawn(p2x, p2y, p3x, p3y) ||\n        edge_overlaps_with_drawn(p3x, p3y, p4x, p4y) || \n        edge_overlaps_with_drawn(p4x, p4y, p1x, p1y))\n        return false;\n    \n    return check_segment_clear(p1x, p1y, p2x, p2y) &&\n           check_segment_clear(p2x, p2y, p3x, p3y) &&\n           check_segment_clear(p3x, p3y, p4x, p4y) &&\n           check_segment_clear(p4x, p4y, p1x, p1y);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    \n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        dots.insert({x, y});\n    }\n    \n    vector<tuple<int,int,int,int,int,int,int,int>> ops;\n    auto start_time = chrono::high_resolution_clock::now();\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    while (true) {\n        auto now = chrono::high_resolution_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 4750) break;\n        \n        vector<pair<int,int>> dot_vec(dots.begin(), dots.end());\n        int sz = dot_vec.size();\n        \n        // Shuffle for stochastic exploration\n        if (ops.size() % 10 == 0 && ops.size() > 0) {\n            shuffle(dot_vec.begin(), dot_vec.end(), rng);\n        }\n        \n        int best_p1x = -1, best_p1y = -1, best_p2x, best_p2y, best_p3x, best_p3y, best_p4x, best_p4y;\n        double best_w = -1;\n        int found_count = 0;\n        \n        // Try axis-aligned rectangles\n        for (int i = 0; i < sz; i++) {\n            for (int j = i + 1; j < sz; j++) {\n                int xa = dot_vec[i].first, ya = dot_vec[i].second;\n                int xb = dot_vec[j].first, yb = dot_vec[j].second;\n                \n                if (xa == xb || ya == yb) continue;\n                \n                int xc = xa, yc = yb;\n                int xd = xb, yd = ya;\n                \n                if (!dots.count({xd, yd}) && dots.count({xc, yc})) {\n                    double w = weight(xd, yd);\n                    if (w > best_w && try_rect(xd, yd, xa, ya, xc, yc, xb, yb)) {\n                        best_w = w;\n                        best_p1x = xd; best_p1y = yd;\n                        best_p2x = xa; best_p2y = ya;\n                        best_p3x = xc; best_p3y = yc;\n                        best_p4x = xb; best_p4y = yb;\n                        found_count++;\n                        \n                        // Accept good enough solutions sometimes to enable exploration\n                        if (found_count > 20 && w > 50) {\n                            i = sz; j = sz;\n                            break;\n                        }\n                    }\n                }\n                \n                if (!dots.count({xc, yc}) && dots.count({xd, yd})) {\n                    double w = weight(xc, yc);\n                    if (w > best_w && try_rect(xc, yc, xa, ya, xd, yd, xb, yb)) {\n                        best_w = w;\n                        best_p1x = xc; best_p1y = yc;\n                        best_p2x = xa; best_p2y = ya;\n                        best_p3x = xd; best_p3y = yd;\n                        best_p4x = xb; best_p4y = yb;\n                        found_count++;\n                        \n                        if (found_count > 20 && w > 50) {\n                            i = sz; j = sz;\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n        \n        if (best_w < 0) break;\n        \n        dots.insert({best_p1x, best_p1y});\n        drawn_edges.push_back({best_p1x, best_p1y, best_p2x, best_p2y});\n        drawn_edges.push_back({best_p2x, best_p2y, best_p3x, best_p3y});\n        drawn_edges.push_back({best_p3x, best_p3y, best_p4x, best_p4y});\n        drawn_edges.push_back({best_p4x, best_p4y, best_p1x, best_p1y});\n        ops.push_back({best_p1x, best_p1y, best_p2x, best_p2y, best_p3x, best_p3y, best_p4x, best_p4y});\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto [p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y] : ops) {\n        cout << p1x << \" \" << p1y << \" \" << p2x << \" \" << p2y << \" \"\n             << p3x << \" \" << p3y << \" \" << p4x << \" \" << p4y << \"\\n\";\n    }\n    \n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nint grid[10][10];\nvector<int> flavors;\n\nvoid place_candy(int pos, int flavor) {\n    int count = 0;\n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (grid[i][j] == 0) {\n                count++;\n                if (count == pos) {\n                    grid[i][j] = flavor;\n                    return;\n                }\n            }\n        }\n    }\n}\n\nvoid tilt(char dir, int target[10][10]) {\n    int temp[10][10];\n    memcpy(temp, grid, sizeof(grid));\n    memset(target, 0, sizeof(int) * 100);\n    \n    if (dir == 'F') {\n        for (int j = 0; j < 10; j++) {\n            vector<int> candies;\n            for (int i = 0; i < 10; i++) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t i = 0; i < candies.size(); i++) {\n                target[i][j] = candies[i];\n            }\n        }\n    } else if (dir == 'B') {\n        for (int j = 0; j < 10; j++) {\n            vector<int> candies;\n            for (int i = 9; i >= 0; i--) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t i = 0; i < candies.size(); i++) {\n                target[9 - i][j] = candies[i];\n            }\n        }\n    } else if (dir == 'L') {\n        for (int i = 0; i < 10; i++) {\n            vector<int> candies;\n            for (int j = 0; j < 10; j++) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t j = 0; j < candies.size(); j++) {\n                target[i][j] = candies[j];\n            }\n        }\n    } else if (dir == 'R') {\n        for (int i = 0; i < 10; i++) {\n            vector<int> candies;\n            for (int j = 9; j >= 0; j--) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t j = 0; j < candies.size(); j++) {\n                target[i][9 - j] = candies[j];\n            }\n        }\n    }\n}\n\nstruct Score {\n    long long sum_sq;\n    long long weighted_adjacency;\n    long long adjacency;\n    int num_singles;\n    int num_components;\n    int max_component;\n    \n    bool is_better_than(const Score& other) const {\n        if (sum_sq != other.sum_sq) return sum_sq > other.sum_sq;\n        // Weight adjacency by remaining candy counts to prioritize future consolidation\n        if (weighted_adjacency != other.weighted_adjacency) return weighted_adjacency > other.weighted_adjacency;\n        if (adjacency != other.adjacency) return adjacency > other.adjacency;\n        // Prefer fewer singletons (isolated candies hurt score)\n        if (num_singles != other.num_singles) return num_singles < other.num_singles;\n        // Prefer fewer total components (more consolidated)\n        if (num_components != other.num_components) return num_components < other.num_components;\n        // Prefer larger maximum component\n        return max_component > other.max_component;\n    }\n};\n\nScore compute_score(int test_grid[10][10], int current_t, const vector<int>& flavors) {\n    bool visited[10][10] = {};\n    long long sum_sq = 0;\n    long long weighted_adjacency = 0;\n    long long adjacency = 0;\n    int num_singles = 0;\n    int num_components = 0;\n    int max_component = 0;\n    \n    // Count remaining candies of each flavor\n    vector<int> remaining(4, 0);\n    for (int f = 1; f <= 3; f++) remaining[f] = 0;\n    for (int i = current_t + 1; i < 100; i++) {\n        remaining[flavors[i]]++;\n    }\n    \n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (test_grid[i][j] > 0 && !visited[i][j]) {\n                int flavor = test_grid[i][j];\n                int component_size = 0;\n                \n                queue<pair<int, int>> q;\n                q.push({i, j});\n                visited[i][j] = true;\n                \n                while (!q.empty()) {\n                    auto [r, c] = q.front();\n                    q.pop();\n                    component_size++;\n                    \n                    int dr[] = {-1, 1, 0, 0};\n                    int dc[] = {0, 0, -1, 1};\n                    \n                    for (int d = 0; d < 4; d++) {\n                        int nr = r + dr[d];\n                        int nc = c + dc[d];\n                        if (nr >= 0 && nr < 10 && nc >= 0 && nc < 10 && \n                            test_grid[nr][nc] == flavor && !visited[nr][nc]) {\n                            visited[nr][nc] = true;\n                            q.push({nr, nc});\n                        }\n                    }\n                }\n                \n                sum_sq += (long long)component_size * component_size;\n                max_component = max(max_component, component_size);\n                num_components++;\n                if (component_size == 1) num_singles++;\n            }\n        }\n    }\n    \n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (test_grid[i][j] > 0) {\n                int flavor = test_grid[i][j];\n                int flavor_weight = remaining[flavor] + 1;  // +1 to ensure non-zero weight\n                \n                if (i + 1 < 10 && test_grid[i+1][j] == flavor) {\n                    adjacency++;\n                    weighted_adjacency += flavor_weight;\n                }\n                if (j + 1 < 10 && test_grid[i][j+1] == flavor) {\n                    adjacency++;\n                    weighted_adjacency += flavor_weight;\n                }\n            }\n        }\n    }\n    \n    return {sum_sq, weighted_adjacency, adjacency, num_singles, num_components, max_component};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    memset(grid, 0, sizeof(grid));\n    flavors.resize(100);\n    \n    for (int i = 0; i < 100; i++) {\n        cin >> flavors[i];\n    }\n    \n    for (int t = 0; t < 100; t++) {\n        int pos;\n        cin >> pos;\n        place_candy(pos, flavors[t]);\n        \n        if (t < 99) {\n            char dirs[] = {'F', 'B', 'L', 'R'};\n            Score best = {-1, -1, -1, INT_MAX, INT_MAX, 0};\n            char best_dir = 'F';\n            \n            for (int d = 0; d < 4; d++) {\n                int temp[10][10];\n                tilt(dirs[d], temp);\n                Score score = compute_score(temp, t, flavors);\n                \n                if (best.sum_sq == -1 || score.is_better_than(best)) {\n                    best = score;\n                    best_dir = dirs[d];\n                }\n            }\n            \n            cout << best_dir << \"\\n\";\n            cout.flush();\n            \n            int temp[10][10];\n            tilt(best_dir, temp);\n            memcpy(grid, temp, sizeof(grid));\n        }\n    }\n    \n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int M;\n    double eps;\n    cin >> M >> eps;\n    \n    // Adaptive N based on M for optimal scoring\n    int N;\n    if (M <= 20) N = 10;\n    else if (M <= 50) N = 15;\n    else N = 20;\n    \n    int max_edges = N * (N - 1) / 2;\n    \n    cout << N << endl;\n    cout.flush();\n    \n    // Target edge counts (uniformly distributed)\n    vector<int> target(M);\n    for (int k = 0; k < M; k++) {\n        target[k] = k * max_edges / M;\n    }\n    \n    // Generate M graphs with evenly spaced edge counts\n    for (int k = 0; k < M; k++) {\n        string graph(max_edges, '0');\n        for (int i = 0; i < target[k]; i++) {\n            graph[i] = '1';\n        }\n        cout << graph << endl;\n        cout.flush();\n    }\n    \n    // Process 100 queries\n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n        \n        int m = count(H.begin(), H.end(), '1');\n        \n        // Apply noise model correction\n        // True edge count estimate: (observed - max_edges\u00b7\u03b5) / (1 - 2\u03b5)\n        double adjusted_m = m;\n        \n        // Only apply correction when epsilon is significant and denominator is valid\n        if (eps > 0.001 && fabs(1.0 - 2.0 * eps) > 0.01) {\n            adjusted_m = (m - max_edges * eps) / (1.0 - 2.0 * eps);\n            // Clamp to valid range\n            adjusted_m = max(0.0, min((double)max_edges, adjusted_m));\n        }\n        \n        // Find the target with closest adjusted edge count\n        int best = 0;\n        double best_dist = fabs(adjusted_m - target[0]);\n        for (int k = 1; k < M; k++) {\n            double dist = fabs(adjusted_m - target[k]);\n            if (dist < best_dist) {\n                best_dist = dist;\n                best = k;\n            }\n        }\n        \n        cout << best << endl;\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, D, K;\nvector<long long> edge_weights;\nvector<pair<int, int>> edge_endpoints;\nvector<int> degree;\n\nlong long evaluate(const vector<int>& assignment, int eval_type) {\n    vector<long long> day_load(D + 1, 0);\n    for(int i = 0; i < M; i++){\n        day_load[assignment[i]] += edge_weights[i];\n    }\n    \n    if(eval_type == 0) {\n        // Max load\n        long long max_load = 0;\n        for(int d = 1; d <= D; d++){\n            max_load = max(max_load, day_load[d]);\n        }\n        return max_load;\n    } else {\n        // Variance\n        long long sum = 0;\n        for(int d = 1; d <= D; d++) sum += day_load[d];\n        long long mean = sum / D;\n        \n        long long variance = 0;\n        for(int d = 1; d <= D; d++){\n            long long diff = day_load[d] - mean;\n            variance += diff * diff;\n        }\n        return variance;\n    }\n}\n\nvector<int> greedy_assign(int metric_type, bool min_load_strategy) {\n    vector<pair<long long, int>> edge_list;\n    \n    for(int i = 0; i < M; i++){\n        auto [u, v] = edge_endpoints[i];\n        long long w = edge_weights[i];\n        long long importance;\n        \n        if(metric_type == 0){\n            importance = w * (long long)(degree[u] + degree[v]);\n        } else if(metric_type == 1){\n            importance = w * (long long)degree[u] * degree[v];\n        } else if(metric_type == 2){\n            importance = w;\n        } else if(metric_type == 3){\n            long long deg_sum = degree[u] + degree[v];\n            importance = w * deg_sum * deg_sum;\n        } else if(metric_type == 4){\n            long long deg_prod = (long long)degree[u] * degree[v];\n            importance = w * (long long)sqrt(deg_prod) * 1000;\n        } else {\n            // metric 5: smaller degree endpoints get priority (inverse)\n            long long deg_product = (long long)(degree[u] + 1) * (degree[v] + 1);\n            importance = (w * 1000000) / deg_product;\n        }\n        \n        edge_list.push_back({importance, i});\n    }\n    \n    sort(edge_list.rbegin(), edge_list.rend());\n    \n    vector<int> assignment(M);\n    priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq_min;\n    priority_queue<pair<long long, int>> pq_max;\n    \n    for(int d = 1; d <= D; d++){\n        pq_min.push({0, d});\n        pq_max.push({0, d});\n    }\n    \n    if(min_load_strategy) {\n        for(auto [imp, idx] : edge_list){\n            auto [load, day] = pq_min.top();\n            pq_min.pop();\n            assignment[idx] = day;\n            pq_min.push({load + edge_weights[idx], day});\n        }\n    } else {\n        // Assign to max-load (spread critical edges)\n        for(auto [imp, idx] : edge_list){\n            auto [load, day] = pq_max.top();\n            pq_max.pop();\n            assignment[idx] = day;\n            pq_max.push({load + edge_weights[idx], day});\n        }\n    }\n    \n    return assignment;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> D >> K;\n    \n    edge_weights.resize(M);\n    edge_endpoints.resize(M);\n    degree.assign(N, 0);\n    \n    for(int i = 0; i < M; i++){\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edge_weights[i] = w;\n        edge_endpoints[i] = {u, v};\n        degree[u]++;\n        degree[v]++;\n    }\n    \n    for(int i = 0; i < N; i++){\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    vector<int> best_assignment;\n    long long best_eval = LLONG_MAX;\n    \n    // Try many combinations of metrics and strategies\n    for(int metric = 0; metric < 6; metric++){\n        for(int strategy = 0; strategy < 2; strategy++){\n            auto candidate = greedy_assign(metric, strategy == 0);\n            \n            // Evaluate with both metrics and pick based on either\n            long long eval_max = evaluate(candidate, 0);\n            long long eval_var = evaluate(candidate, 1);\n            \n            // Use max_load as primary metric\n            if(eval_max < best_eval){\n                best_eval = eval_max;\n                best_assignment = candidate;\n            }\n        }\n    }\n    \n    for(int i = 0; i < M; i++){\n        cout << best_assignment[i];\n        if(i + 1 < M) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef array<int, 3> Pos;\n\nint D;\n\nstruct Block {\n    set<Pos> voxels;\n    \n    Block() {}\n    Block(const set<Pos>& v) : voxels(v) {}\n    \n    void normalize() {\n        if (voxels.empty()) return;\n        int minx = INT_MAX, miny = INT_MAX, minz = INT_MAX;\n        for (auto [x, y, z] : voxels) {\n            minx = min(minx, x);\n            miny = min(miny, y);\n            minz = min(minz, z);\n        }\n        set<Pos> normalized;\n        for (auto [x, y, z] : voxels) {\n            normalized.insert({x - minx, y - miny, z - minz});\n        }\n        voxels = normalized;\n    }\n    \n    Block rotateX() const {\n        set<Pos> rotated;\n        for (auto [x, y, z] : voxels) {\n            rotated.insert({x, -z, y});\n        }\n        return Block(rotated);\n    }\n    \n    Block rotateY() const {\n        set<Pos> rotated;\n        for (auto [x, y, z] : voxels) {\n            rotated.insert({z, y, -x});\n        }\n        return Block(rotated);\n    }\n    \n    Block rotateZ() const {\n        set<Pos> rotated;\n        for (auto [x, y, z] : voxels) {\n            rotated.insert({-y, x, z});\n        }\n        return Block(rotated);\n    }\n    \n    bool operator<(const Block& other) const {\n        return voxels < other.voxels;\n    }\n    \n    bool operator==(const Block& other) const {\n        return voxels == other.voxels;\n    }\n};\n\nBlock getCanonicalForm(Block b) {\n    set<Block> allForms;\n    \n    for (int rx = 0; rx < 4; rx++) {\n        for (int ry = 0; ry < 4; ry++) {\n            for (int rz = 0; rz < 4; rz++) {\n                Block norm = b;\n                norm.normalize();\n                allForms.insert(norm);\n                b = b.rotateZ();\n            }\n            b = b.rotateY();\n        }\n        b = b.rotateX();\n    }\n    \n    return *allForms.begin();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D;\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    \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<int>>> grid1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> grid2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    \n    for (int x = 0; x < D; x++) {\n        for (int y = 0; y < D; y++) {\n            for (int z = 0; z < D; z++) {\n                if (f1[z][x] == '1' && r1[z][y] == '1') grid1[x][y][z] = 1;\n                if (f2[z][x] == '1' && r2[z][y] == '1') grid2[x][y][z] = 1;\n            }\n        }\n    }\n    \n    struct Component {\n        set<Pos> voxels;\n        Block canonical;\n    };\n    \n    auto extractComponents = [&](const vector<vector<vector<int>>>& grid) {\n        vector<Component> components;\n        vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n        \n        for (int x = 0; x < D; x++) {\n            for (int y = 0; y < D; y++) {\n                for (int z = 0; z < D; z++) {\n                    if (grid[x][y][z] == 1 && !visited[x][y][z]) {\n                        set<Pos> voxels;\n                        queue<Pos> q;\n                        q.push({x, y, z});\n                        visited[x][y][z] = true;\n                        \n                        while (!q.empty()) {\n                            auto [cx, cy, cz] = q.front();\n                            q.pop();\n                            voxels.insert({cx, cy, cz});\n                            \n                            int dx[] = {1, -1, 0, 0, 0, 0};\n                            int dy[] = {0, 0, 1, -1, 0, 0};\n                            int dz[] = {0, 0, 0, 0, 1, -1};\n                            \n                            for (int i = 0; i < 6; i++) {\n                                int nx = cx + dx[i], ny = cy + dy[i], nz = cz + dz[i];\n                                if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                    grid[nx][ny][nz] == 1 && !visited[nx][ny][nz]) {\n                                    visited[nx][ny][nz] = true;\n                                    q.push({nx, ny, nz});\n                                }\n                            }\n                        }\n                        \n                        Block block(voxels);\n                        block.normalize();\n                        Block canonical = getCanonicalForm(block);\n                        components.push_back({voxels, canonical});\n                    }\n                }\n            }\n        }\n        \n        return components;\n    };\n    \n    auto components1 = extractComponents(grid1);\n    auto components2 = extractComponents(grid2);\n    \n    int nextID = 1;\n    map<int, int> comp1ID, comp2ID;\n    vector<bool> used2(components2.size(), false);\n    \n    for (int i = 0; i < components1.size(); i++) {\n        int bestMatch = -1;\n        for (int j = 0; j < components2.size(); j++) {\n            if (!used2[j] && components1[i].canonical == components2[j].canonical) {\n                bestMatch = j;\n                break;\n            }\n        }\n        \n        if (bestMatch != -1) {\n            comp1ID[i] = nextID;\n            comp2ID[bestMatch] = nextID;\n            used2[bestMatch] = true;\n            nextID++;\n        } else {\n            comp1ID[i] = nextID++;\n        }\n    }\n    \n    for (int j = 0; j < components2.size(); j++) {\n        if (!used2[j]) {\n            comp2ID[j] = nextID++;\n        }\n    }\n    \n    vector<vector<vector<int>>> result1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> result2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    \n    for (int i = 0; i < components1.size(); i++) {\n        int bid = comp1ID[i];\n        for (auto [x, y, z] : components1[i].voxels) {\n            result1[x][y][z] = bid;\n        }\n    }\n    \n    for (int j = 0; j < components2.size(); j++) {\n        int bid = comp2ID[j];\n        for (auto [x, y, z] : components2[j].voxels) {\n            result2[x][y][z] = bid;\n        }\n    }\n    \n    cout << nextID - 1 << \"\\n\";\n    for (int x = 0; x < D; x++)\n        for (int y = 0; y < D; y++)\n            for (int z = 0; z < D; z++) {\n                if (x || y || z) cout << \" \";\n                cout << result1[x][y][z];\n            }\n    cout << \"\\n\";\n    for (int x = 0; x < D; x++)\n        for (int y = 0; y < D; y++)\n            for (int z = 0; z < D; z++) {\n                if (x || y || z) cout << \" \";\n                cout << result2[x][y][z];\n            }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc020":"#include<bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    double x, y;\n};\n\ndouble dist(Point a, Point b) {\n    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\nint N, M, K;\nvector<Point> stations;\nvector<pair<int,int>> edgeEndpoints;\nvector<long long> weights;\nvector<Point> residents;\n\nvector<bool> getReachable(const vector<bool>& enabled) {\n    vector<bool> reachable(N, false);\n    reachable[0] = true;\n    queue<int> q;\n    q.push(0);\n    while(!q.empty()){\n        int u = q.front();\n        q.pop();\n        for(int e = 0; e < M; e++){\n            if(!enabled[e]) continue;\n            int v = -1;\n            if(edgeEndpoints[e].first == u) v = edgeEndpoints[e].second;\n            else if(edgeEndpoints[e].second == u) v = edgeEndpoints[e].first;\n            if(v != -1 && !reachable[v]){\n                reachable[v] = true;\n                q.push(v);\n            }\n        }\n    }\n    return reachable;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    \n    stations.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> stations[i].x >> stations[i].y;\n    }\n    \n    edgeEndpoints.resize(M);\n    weights.resize(M);\n    for(int i = 0; i < M; i++){\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edgeEndpoints[i] = {u, v};\n        weights[i] = w;\n    }\n    \n    residents.resize(K);\n    for(int i = 0; i < K; i++){\n        cin >> residents[i].x >> residents[i].y;\n    }\n    \n    vector<long long> P(N, 0);\n    vector<bool> enabled(M, false);\n    \n    // Initial: cover nearby residents with station 0\n    for(int k = 0; k < K; k++){\n        long long d = (long long)round(dist(stations[0], residents[k]));\n        if(d <= 5000){\n            P[0] = max(P[0], d);\n        }\n    }\n    \n    // Greedy: add edges until all residents are covered\n    while(true) {\n        auto reachable = getReachable(enabled);\n        \n        // Find uncovered residents\n        set<int> uncovered;\n        for(int k = 0; k < K; k++){\n            bool covered = false;\n            for(int i = 0; i < N; i++){\n                if(reachable[i] && P[i] >= (long long)round(dist(stations[i], residents[k]))){\n                    covered = true;\n                    break;\n                }\n            }\n            if(!covered) uncovered.insert(k);\n        }\n        \n        if(uncovered.empty()) break;\n        \n        // Find best edge to enable\n        double bestScore = 1e18;\n        int bestEdge = -1;\n        int bestVertex = -1;\n        \n        for(int e = 0; e < M; e++){\n            if(enabled[e]) continue;\n            \n            int u = edgeEndpoints[e].first;\n            int v = edgeEndpoints[e].second;\n            \n            bool u_reach = reachable[u];\n            bool v_reach = reachable[v];\n            \n            if(!u_reach && !v_reach) continue;\n            \n            int newV = u_reach ? v : u;\n            \n            long long maxP = 0;\n            int covered = 0;\n            for(int k : uncovered){\n                long long d = (long long)round(dist(stations[newV], residents[k]));\n                if(d <= 5000){\n                    maxP = max(maxP, d);\n                    covered++;\n                }\n            }\n            \n            if(covered == 0) continue;\n            \n            long long cost = weights[e] + maxP * maxP;\n            double score = (double)cost / covered;\n            \n            if(score < bestScore){\n                bestScore = score;\n                bestEdge = e;\n                bestVertex = newV;\n            }\n        }\n        \n        if(bestEdge == -1) break;\n        \n        enabled[bestEdge] = true;\n        for(int k : uncovered){\n            long long d = (long long)round(dist(stations[bestVertex], residents[k]));\n            if(d <= 5000){\n                P[bestVertex] = max(P[bestVertex], d);\n            }\n        }\n    }\n    \n    // Optimize: assign each resident to closest reachable station\n    auto reachable = getReachable(enabled);\n    fill(P.begin(), P.end(), 0);\n    for(int k = 0; k < K; k++){\n        long long minDist = LLONG_MAX;\n        int bestV = -1;\n        for(int i = 0; i < N; i++){\n            if(reachable[i]){\n                long long d = (long long)round(dist(stations[i], residents[k]));\n                if(d < minDist){\n                    minDist = d;\n                    bestV = i;\n                }\n            }\n        }\n        if(bestV != -1) P[bestV] = max(P[bestV], minDist);\n    }\n    \n    // Output\n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << P[i];\n    }\n    cout << \"\\n\";\n    \n    for(int i = 0; i < M; i++){\n        if(i > 0) cout << \" \";\n        cout << (enabled[i] ? 1 : 0);\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 30;\n    vector<vector<int>> pyramid(N);\n    \n    // Read input\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    vector<tuple<int,int,int,int>> operations;\n    \n    // Build min-heap structure using heapify algorithm\n    // Process from second-to-last level upwards (bottom-up)\n    for (int x = N - 2; x >= 0; x--) {\n        for (int y = 0; y <= x; y++) {\n            // Sift down from position (x, y)\n            int curr_x = x, curr_y = y;\n            while (curr_x + 1 < N && (int)operations.size() < 10000) {\n                int parent_val = pyramid[curr_x][curr_y];\n                int left_child_val = pyramid[curr_x + 1][curr_y];\n                int right_child_val = pyramid[curr_x + 1][curr_y + 1];\n                \n                // If parent is smaller than both children, heap property satisfied\n                if (parent_val <= left_child_val && parent_val <= right_child_val) {\n                    break;\n                }\n                \n                // Swap with the smaller child\n                if (left_child_val <= right_child_val) {\n                    swap(pyramid[curr_x][curr_y], pyramid[curr_x + 1][curr_y]);\n                    operations.push_back({curr_x, curr_y, curr_x + 1, curr_y});\n                    curr_x++;\n                } else {\n                    swap(pyramid[curr_x][curr_y], pyramid[curr_x + 1][curr_y + 1]);\n                    operations.push_back({curr_x, curr_y, curr_x + 1, curr_y + 1});\n                    curr_x++;\n                    curr_y++;\n                }\n            }\n        }\n    }\n    \n    // Output result\n    cout << (int)operations.size() << \"\\n\";\n    for (auto [x1, y1, x2, y2] : operations) {\n        cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \"\\n\";\n    }\n    \n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nint D, N;\nset<pair<int,int>> obstacles;\npair<int,int> entrance;\nmap<pair<int,int>, int> container_at;\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\n\nvector<pair<int,int>> get_reachable_empty() {\n    vector<pair<int,int>> result;\n    queue<pair<int,int>> q;\n    set<pair<int,int>> visited;\n    \n    q.push(entrance);\n    visited.insert(entrance);\n    \n    while(!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n        \n        for(int d = 0; d < 4; d++) {\n            int nr = r + dr[d];\n            int nc = c + dc[d];\n            \n            if(nr >= 0 && nr < D && nc >= 0 && nc < D &&\n               !visited.count({nr, nc}) &&\n               !obstacles.count({nr, nc}) &&\n               !container_at.count({nr, nc})) {\n                \n                visited.insert({nr, nc});\n                if(!(nr == 0 && nc == (D-1)/2)) {  // Not entrance\n                    result.push_back({nr, nc});\n                }\n                q.push({nr, nc});\n            }\n        }\n    }\n    \n    return result;\n}\n\nset<pair<int,int>> get_reachable_containers() {\n    set<pair<int,int>> result;\n    queue<pair<int,int>> q;\n    set<pair<int,int>> visited;\n    \n    q.push(entrance);\n    visited.insert(entrance);\n    \n    while(!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n        \n        for(int d = 0; d < 4; d++) {\n            int nr = r + dr[d];\n            int nc = c + dc[d];\n            \n            if(nr >= 0 && nr < D && nc >= 0 && nc < D &&\n               !visited.count({nr, nc}) &&\n               !obstacles.count({nr, nc})) {\n                \n                visited.insert({nr, nc});\n                \n                if(container_at.count({nr, nc})) {\n                    result.insert({nr, nc});\n                } else {\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n    \n    return result;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D >> N;\n    \n    for(int i = 0; i < N; i++){\n        int r, c;\n        cin >> r >> c;\n        obstacles.insert({r, c});\n    }\n    \n    entrance = {0, (D-1)/2};\n    \n    // Place containers at furthest reachable squares\n    for(int i = 0; i < D*D - 1 - N; i++){\n        int t;\n        cin >> t;\n        \n        auto empty_squares = get_reachable_empty();\n        \n        if(empty_squares.empty()) {\n            // Shouldn't happen, but fallback\n            cout << \"0 0\\n\";\n            cout.flush();\n            continue;\n        }\n        \n        auto chosen = empty_squares.back();  // Furthest reachable\n        container_at[chosen] = t;\n        cout << chosen.first << \" \" << chosen.second << \"\\n\";\n        cout.flush();\n    }\n    \n    // Retrieve containers by greedy extraction\n    for(int i = 0; i < D*D - 1 - N; i++){\n        auto reachable = get_reachable_containers();\n        \n        pair<int,int> best_pos;\n        int best_num = INT_MAX;\n        \n        for(auto& pos : reachable) {\n            int num = container_at[pos];\n            if(num < best_num) {\n                best_num = num;\n                best_pos = pos;\n            }\n        }\n        \n        cout << best_pos.first << \" \" << best_pos.second << \"\\n\";\n        container_at.erase(best_pos);\n    }\n    \n    cout.flush();\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, m;\nint original[50][50];\nint current[50][50];\n\nvector<pair<int,int>> dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};\n\nbool isValid(int i, int j) {\n    return i >= 0 && i < N && j >= 0 && j < N;\n}\n\nbool isConnected(int color) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int,int>> q;\n    int count = 0;\n    pair<int,int> start = {-1, -1};\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(current[i][j] == color) {\n                count++;\n                if(start.first == -1) start = {i, j};\n            }\n        }\n    }\n    \n    if(count == 0) return true;\n    \n    q.push(start);\n    visited[start.first][start.second] = true;\n    int visited_count = 1;\n    \n    while(!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for(auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if(isValid(ni, nj) && !visited[ni][nj] && current[ni][nj] == color) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                visited_count++;\n            }\n        }\n    }\n    \n    return visited_count == count;\n}\n\nbool isConnected0() {\n    int count0 = 0;\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(current[i][j] == 0) count0++;\n        }\n    }\n    \n    if(count0 == 0) return true;\n    \n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int,int>> q;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if((i == 0 || i == N-1 || j == 0 || j == N-1) && current[i][j] == 0) {\n                q.push({i, j});\n                visited[i][j] = true;\n            }\n        }\n    }\n    \n    int visited_count = q.size();\n    \n    while(!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for(auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if(isValid(ni, nj) && !visited[ni][nj] && current[ni][nj] == 0) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                visited_count++;\n            }\n        }\n    }\n    \n    return visited_count == count0;\n}\n\nset<pair<int,int>> getAdjacencies() {\n    set<pair<int,int>> adj;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            for(auto [di, dj] : dirs) {\n                int ni = i + di, nj = j + dj;\n                if(isValid(ni, nj)) {\n                    int c1 = current[i][j], c2 = current[ni][nj];\n                    if(c1 != c2) {\n                        adj.insert({min(c1, c2), max(c1, c2)});\n                    }\n                }\n            }\n        }\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if((i == 0 || i == N-1 || j == 0 || j == N-1) && current[i][j] != 0) {\n                adj.insert({0, current[i][j]});\n            }\n        }\n    }\n    \n    return adj;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> m;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            cin >> original[i][j];\n            current[i][j] = original[i][j];\n        }\n    }\n    \n    auto orig_adj = getAdjacencies();\n    \n    bool improved = true;\n    \n    while(improved) {\n        improved = false;\n        \n        for(int i = 0; i < N; i++) {\n            for(int j = 0; j < N; j++) {\n                if(current[i][j] == 0) continue;\n                \n                int color = current[i][j];\n                \n                int color_count = 0;\n                for(int ii = 0; ii < N; ii++) {\n                    for(int jj = 0; jj < N; jj++) {\n                        if(current[ii][jj] == color) color_count++;\n                    }\n                }\n                if(color_count == 1) continue;\n                \n                bool is_boundary = (i == 0 || i == N-1 || j == 0 || j == N-1);\n                if(is_boundary) {\n                    int boundary_count = 0;\n                    for(int ii = 0; ii < N; ii++) {\n                        for(int jj = 0; jj < N; jj++) {\n                            if((ii == 0 || ii == N-1 || jj == 0 || jj == N-1) && current[ii][jj] == color) {\n                                boundary_count++;\n                            }\n                        }\n                    }\n                    if(boundary_count == 1) continue;\n                }\n                \n                current[i][j] = 0;\n                \n                if(isConnected(color) && isConnected0() && getAdjacencies() == orig_adj) {\n                    improved = true;\n                } else {\n                    current[i][j] = color;\n                }\n            }\n        }\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(j > 0) cout << \" \";\n            cout << current[i][j];\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, D, Q;\n    cin >> N >> D >> Q;\n    \n    map<pair<int,int>, int> cmp;\n    \n    vector<pair<int,int>> all_pairs;\n    for(int i = 0; i < N; i++){\n        for(int j = i+1; j < N; j++){\n            all_pairs.push_back({i, j});\n        }\n    }\n    \n    mt19937 rng(0);\n    shuffle(all_pairs.begin(), all_pairs.end(), rng);\n    \n    int q_done = 0;\n    for(int attempt = 0; q_done < Q; attempt++){\n        int idx = attempt % (int)all_pairs.size();\n        int i = all_pairs[idx].first;\n        int j = all_pairs[idx].second;\n        \n        if(cmp.count({i, j})) continue;\n        \n        cout << \"1 1 \" << i << \" \" << j << \"\\n\";\n        cout.flush();\n        \n        string result;\n        cin >> result;\n        \n        if(result == \"<\") cmp[{i,j}] = -1;\n        else if(result == \">\") cmp[{i,j}] = 1;\n        else cmp[{i,j}] = 0;\n        \n        q_done++;\n    }\n    \n    vector<long long> weight(N, 0);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(i == j) continue;\n            int a = min(i, j), b = max(i, j);\n            if(cmp.count({a, b})){\n                int c = cmp[{a, b}];\n                if(i < j){\n                    if(c == 1) weight[i]++;\n                    else if(c == -1) weight[i]--;\n                } else {\n                    if(c == 1) weight[i]--;\n                    else if(c == -1) weight[i]++;\n                }\n            }\n        }\n    }\n    \n    auto compute_variance = [&](const vector<int>& div) {\n        vector<long long> sums(D, 0);\n        for(int i = 0; i < N; i++){\n            sums[div[i]] += weight[i];\n        }\n        double mean = 0;\n        for(auto s : sums) mean += s;\n        mean /= D;\n        \n        double var = 0;\n        for(auto s : sums){\n            var += (s - mean) * (s - mean);\n        }\n        return var / D;\n    };\n    \n    vector<pair<long long, int>> items;\n    for(int i = 0; i < N; i++){\n        items.push_back({weight[i], i});\n    }\n    sort(items.rbegin(), items.rend());\n    \n    // Strategy 1: FFD (First-Fit Decreasing)\n    vector<int> div_ffd(N);\n    vector<long long> set_weight_ffd(D, 0);\n    for(auto [w, item] : items){\n        int best_set = 0;\n        for(int d = 1; d < D; d++){\n            if(set_weight_ffd[d] < set_weight_ffd[best_set]){\n                best_set = d;\n            }\n        }\n        div_ffd[item] = best_set;\n        set_weight_ffd[best_set] += w;\n    }\n    double var_ffd = compute_variance(div_ffd);\n    \n    // Strategy 2: Round-Robin (alternating assignment)\n    vector<int> div_rr(N);\n    for(int idx = 0; idx < N; idx++){\n        int item = items[idx].second;\n        div_rr[item] = idx % D;\n    }\n    double var_rr = compute_variance(div_rr);\n    \n    // Choose the better strategy\n    vector<int> best_division = (var_ffd < var_rr) ? div_ffd : div_rr;\n    \n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << best_division[i];\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<pair<int,int>> solveWithStrategy(vector<vector<int>> stacks, int m, int n, int strategy) {\n  vector<pair<int,int>> operations;\n  \n  for(int box = 1; box <= n; box++){\n    int src_stack = -1;\n    \n    for(int i = 0; i < m; i++){\n      for(int j = 0; j < (int)stacks[i].size(); j++){\n        if(stacks[i][j] == box){\n          src_stack = i;\n          break;\n        }\n      }\n      if(src_stack != -1) break;\n    }\n    \n    while(stacks[src_stack].back() != box){\n      int top_box = stacks[src_stack].back();\n      \n      int dest_stack = -1;\n      \n      for(int i = 0; i < m; i++){\n        if(i == src_stack) continue;\n        \n        if(dest_stack == -1){\n          dest_stack = i;\n          continue;\n        }\n        \n        int cur_size = stacks[i].size();\n        int best_size = stacks[dest_stack].size();\n        bool cur_empty = (cur_size == 0);\n        bool best_empty = (best_size == 0);\n        int cur_top = cur_empty ? INT_MAX : stacks[i].back();\n        int best_top = best_empty ? INT_MAX : stacks[dest_stack].back();\n        \n        bool better = false;\n        \n        if(strategy == 0){ // Size first, empty preference, smaller top (proven)\n          if(cur_size < best_size) better = true;\n          else if(cur_size == best_size && cur_empty && !best_empty) better = true;\n          else if(cur_size == best_size && cur_empty == best_empty && cur_top < best_top) better = true;\n        } \n        else if(strategy == 1){ // Size first, empty preference, larger top\n          if(cur_size < best_size) better = true;\n          else if(cur_size == best_size && cur_empty && !best_empty) better = true;\n          else if(cur_size == best_size && cur_empty == best_empty && cur_top > best_top) better = true;\n        } \n        else if(strategy == 2){ // Empty first, then size, then top\n          if(cur_empty && !best_empty) better = true;\n          else if(!cur_empty && !best_empty && cur_size < best_size) better = true;\n          else if(cur_empty && best_empty && cur_size < best_size) better = true;\n        }\n        else if(strategy == 3){ // Minimize size only, no other preferences\n          if(cur_size < best_size) better = true;\n        }\n        else if(strategy == 4){ // Balance stack heights\n          int avg = (n - box + 1) / m;\n          int cur_dist = abs((int)cur_size - avg);\n          int best_dist = abs((int)best_size - avg);\n          if(cur_dist < best_dist) better = true;\n          else if(cur_dist == best_dist && cur_empty && !best_empty) better = true;\n        }\n        else if(strategy == 5){ // Prefer middle-range tops\n          int mid = n / 2;\n          int cur_dist = cur_empty ? INT_MAX : abs(cur_top - mid);\n          int best_dist = best_empty ? INT_MAX : abs(best_top - mid);\n          if(cur_size < best_size) better = true;\n          else if(cur_size == best_size && cur_dist < best_dist) better = true;\n        }\n        \n        if(better) dest_stack = i;\n      }\n      \n      stacks[dest_stack].push_back(top_box);\n      stacks[src_stack].pop_back();\n      operations.push_back({top_box, dest_stack + 1});\n    }\n    \n    operations.push_back({box, 0});\n    stacks[src_stack].pop_back();\n  }\n  \n  return operations;\n}\n\nint main(){\n  ios_base::sync_with_stdio(false);\n  cin.tie(nullptr);\n  \n  int n, m;\n  cin >> n >> m;\n  \n  vector<vector<int>> initial_stacks(m);\n  \n  for(int i = 0; i < m; i++){\n    int s = n / m;\n    for(int j = 0; j < s; j++){\n      int x;\n      cin >> x;\n      initial_stacks[i].push_back(x);\n    }\n  }\n  \n  int best_ops = INT_MAX;\n  vector<pair<int,int>> best_solution;\n  \n  for(int strategy = 0; strategy < 6; strategy++){\n    auto ops = solveWithStrategy(initial_stacks, m, n, strategy);\n    if((int)ops.size() < best_ops){\n      best_ops = ops.size();\n      best_solution = ops;\n    }\n  }\n  \n  for(auto [v, i] : best_solution){\n    cout << v << \" \" << i << \"\\n\";\n  }\n  \n  return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\n\nint di[] = {0, 1, 0, -1};\nint dj[] = {1, 0, -1, 0};\nchar dir_char[] = {'R', 'D', 'L', 'U'};\n\ndouble simulate(const string& path) {\n    if (path.empty() || path.length() > 100000) return 1e18;\n    \n    int L = path.length();\n    vector<vector<long long>> dirt(N, vector<long long>(N, 0));\n    \n    int ci = 0, cj = 0;\n    long long sum = 0;\n    \n    for (int step = 0; step < 2 * L; step++) {\n        char c = path[step % L];\n        if (c == 'R') cj++;\n        else if (c == 'L') cj--;\n        else if (c == 'D') ci++;\n        else if (c == 'U') ci--;\n        \n        dirt[ci][cj] = 0;\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (i != ci || j != cj) {\n                    dirt[i][j] += d[i][j];\n                }\n            }\n        }\n        \n        if (step >= L) {\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    sum += dirt[i][j];\n                }\n            }\n        }\n    }\n    \n    return (double)sum / L;\n}\n\nvoid dfs(int i, int j, vector<vector<bool>>& visited, string& path, \n         function<int(int,int)> comparator) {\n    visited[i][j] = true;\n    \n    vector<pair<int, int>> moves;\n    \n    for (int dir = 0; dir < 4; dir++) {\n        int ni = i + di[dir];\n        int nj = j + dj[dir];\n        \n        if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj]) {\n            bool canMove = false;\n            if (dir == 0) canMove = (v[i][j] == '0');\n            else if (dir == 1) canMove = (h[i][j] == '0');\n            else if (dir == 2) canMove = (v[i][nj] == '0');\n            else canMove = (h[ni][j] == '0');\n            \n            if (canMove) {\n                moves.push_back({dir, comparator(ni, nj)});\n            }\n        }\n    }\n    \n    sort(moves.begin(), moves.end(), \n         [](const pair<int,int> &a, const pair<int,int> &b) { \n             return a.second > b.second; \n         });\n    \n    for (const auto &[dir, _] : moves) {\n        int ni = i + di[dir];\n        int nj = j + dj[dir];\n        \n        path += dir_char[dir];\n        dfs(ni, nj, visited, path, comparator);\n        path += dir_char[(dir + 2) % 4];\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    \n    h.resize(N-1);\n    v.resize(N);\n    d.resize(N, vector<int>(N));\n    \n    for (int i = 0; i < N-1; i++) cin >> h[i];\n    for (int i = 0; i < N; i++) cin >> v[i];\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n        }\n    }\n    \n    double best_score = 1e18;\n    string best_path;\n    \n    int cm = N / 2;\n    \n    vector<function<int(int,int)>> strategies;\n    \n    // Pure single-factor strategies\n    strategies.push_back([](int i, int j) { return -d[i][j]; });\n    strategies.push_back([](int i, int j) { return d[i][j]; });\n    strategies.push_back([](int i, int j) { return -(abs(i) + abs(j)); });\n    strategies.push_back([](int i, int j) { return abs(i) + abs(j); });\n    strategies.push_back([cm](int i, int j) { return -(abs(i - cm) + abs(j - cm)); });\n    strategies.push_back([cm](int i, int j) { return abs(i - cm) + abs(j - cm); });\n    \n    // Carefully selected weight combinations for start-based\n    vector<pair<int,int>> start_weights = {\n        {1, 1}, {2, 1}, {5, 1}, {10, 1}, {50, 1}, {100, 1}, {500, 1}, {1000, 1},\n        {1, 2}, {1, 5}, {1, 10}, {1, 50}, {1, 100}, {1, 500}, {1, 1000},\n        {10, 10}, {100, 100}\n    };\n    \n    // Start-based: both symmetric and asymmetric\n    for (auto [dw, sw] : start_weights) {\n        strategies.push_back([dw, sw](int i, int j) {\n            return -(dw * d[i][j] + sw * (abs(i) + abs(j)));\n        });\n    }\n    \n    // Carefully selected weight combinations for center-based\n    vector<pair<int,int>> center_weights = {\n        {1, 1}, {2, 1}, {5, 1}, {10, 1}, {50, 1}, {100, 1}, {500, 1}, {1000, 1},\n        {1, 2}, {1, 5}, {1, 10}, {1, 50}, {1, 100}, {1, 500}, {1, 1000},\n        {10, 10}, {100, 100}\n    };\n    \n    // Center-based: both symmetric and asymmetric\n    for (auto [dw, sw] : center_weights) {\n        strategies.push_back([dw, sw, cm](int i, int j) {\n            return -(dw * d[i][j] + sw * (abs(i - cm) + abs(j - cm)));\n        });\n    }\n    \n    // Test all strategies\n    for (const auto& strategy : strategies) {\n        string path;\n        vector<vector<bool>> visited(N, vector<bool>(N, false));\n        dfs(0, 0, visited, path, strategy);\n        double score = simulate(path);\n        if (score < best_score) {\n            best_score = score;\n            best_path = path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nint si, sj;\nvector<string> grid;\nvector<string> words;\nmap<char, vector<pair<int, int>>> charPos;\n\nint getOverlap(const string& a, const string& b) {\n    int maxOverlap = 0;\n    int maxLen = min((int)a.size(), (int)b.size());\n    for (int o = 1; o <= maxLen; o++) {\n        bool match = true;\n        for (int i = 0; i < o; i++) {\n            if (a[a.size() - o + i] != b[i]) {\n                match = false;\n                break;\n            }\n        }\n        if (match) maxOverlap = o;\n    }\n    return maxOverlap;\n}\n\nint getMinCharDistance(const string& word, int ci, int cj) {\n    int minDist = INT_MAX;\n    for (char c : word) {\n        for (auto [ii, jj] : charPos[c]) {\n            minDist = min(minDist, abs(ii - ci) + abs(jj - cj));\n        }\n    }\n    return minDist;\n}\n\nstring buildSuperstring(const vector<int>& order) {\n    if (order.empty()) return \"\";\n    string result = words[order[0]];\n    for (int i = 1; i < (int)order.size(); i++) {\n        int overlap = getOverlap(words[order[i-1]], words[order[i]]);\n        result += words[order[i]].substr(overlap);\n    }\n    return result;\n}\n\nlong long calculateCost(const string& superstring) {\n    long long cost = 0;\n    int ci = si, cj = sj;\n    \n    for (int pos = 0; pos < (int)superstring.size(); pos++) {\n        char c = superstring[pos];\n        \n        int bestI = -1, bestJ = -1;\n        double minTotalCost = 1e18;\n        \n        for (auto [ii, jj] : charPos[c]) {\n            double moveCost = abs(ii - ci) + abs(jj - cj);\n            double lookCost = 0;\n            \n            // Enhanced lookahead with 5 steps\n            if (pos + 1 < (int)superstring.size()) {\n                char next = superstring[pos + 1];\n                int nextMinDist = INT_MAX;\n                for (auto [ni, nj] : charPos[next]) {\n                    nextMinDist = min(nextMinDist, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist * 0.65;\n            }\n            if (pos + 2 < (int)superstring.size()) {\n                char next2 = superstring[pos + 2];\n                int nextMinDist2 = INT_MAX;\n                for (auto [ni, nj] : charPos[next2]) {\n                    nextMinDist2 = min(nextMinDist2, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist2 * 0.25;\n            }\n            if (pos + 3 < (int)superstring.size()) {\n                char next3 = superstring[pos + 3];\n                int nextMinDist3 = INT_MAX;\n                for (auto [ni, nj] : charPos[next3]) {\n                    nextMinDist3 = min(nextMinDist3, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist3 * 0.10;\n            }\n            if (pos + 4 < (int)superstring.size()) {\n                char next4 = superstring[pos + 4];\n                int nextMinDist4 = INT_MAX;\n                for (auto [ni, nj] : charPos[next4]) {\n                    nextMinDist4 = min(nextMinDist4, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist4 * 0.08;\n            }\n            if (pos + 5 < (int)superstring.size()) {\n                char next5 = superstring[pos + 5];\n                int nextMinDist5 = INT_MAX;\n                for (auto [ni, nj] : charPos[next5]) {\n                    nextMinDist5 = min(nextMinDist5, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist5 * 0.02;\n            }\n            \n            double totalCost = moveCost + lookCost;\n            if (totalCost < minTotalCost) {\n                minTotalCost = totalCost;\n                bestI = ii;\n                bestJ = jj;\n            }\n        }\n        \n        cost += abs(bestI - ci) + abs(bestJ - cj) + 1;\n        ci = bestI;\n        cj = bestJ;\n    }\n    return cost;\n}\n\nvector<int> greedyOrder(int startWord) {\n    vector<int> order;\n    set<int> used;\n    order.push_back(startWord);\n    used.insert(startWord);\n    \n    int curI = si, curJ = sj;\n    \n    while ((int)used.size() < M) {\n        int lastWord = order.back();\n        int bestWord = -1;\n        int bestOverlap = -1;\n        int bestProximity = INT_MAX;\n        \n        for (int w = 0; w < M; w++) {\n            if (used.count(w)) continue;\n            int ov = getOverlap(words[lastWord], words[w]);\n            int proximity = getMinCharDistance(words[w], curI, curJ);\n            \n            // Greedy on overlap, tie-break by proximity\n            if (ov > bestOverlap || (ov == bestOverlap && proximity < bestProximity)) {\n                bestOverlap = ov;\n                bestProximity = proximity;\n                bestWord = w;\n            }\n        }\n        \n        order.push_back(bestWord);\n        used.insert(bestWord);\n        \n        // Update position to approximate where we end up\n        // Use the last character's nearest position\n        char lastChar = words[bestWord].back();\n        int minDist = INT_MAX;\n        for (auto [ii, jj] : charPos[lastChar]) {\n            int d = abs(ii - curI) + abs(jj - curJ);\n            if (d < minDist) {\n                minDist = d;\n                curI = ii;\n                curJ = jj;\n            }\n        }\n    }\n    return order;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    cin >> si >> sj;\n    \n    grid.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    \n    words.resize(M);\n    for (int i = 0; i < M; i++) {\n        cin >> words[i];\n    }\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            charPos[grid[i][j]].push_back({i, j});\n        }\n    }\n    \n    string bestSuperstring;\n    long long bestCost = LLONG_MAX;\n    \n    // Try 120 starting points distributed across word list\n    for (int i = 0; i < 120; i++) {\n        int start = (M * i) / 120;\n        auto order = greedyOrder(start);\n        auto superstring = buildSuperstring(order);\n        auto cost = calculateCost(superstring);\n        if (cost < bestCost) {\n            bestCost = cost;\n            bestSuperstring = superstring;\n        }\n    }\n    \n    // Generate output with same lookahead strategy\n    vector<pair<int, int>> operations;\n    int ci = si, cj = sj;\n    \n    for (int pos = 0; pos < (int)bestSuperstring.size(); pos++) {\n        char c = bestSuperstring[pos];\n        \n        int bestI = -1, bestJ = -1;\n        double minTotalCost = 1e18;\n        \n        for (auto [ii, jj] : charPos[c]) {\n            double moveCost = abs(ii - ci) + abs(jj - cj);\n            double lookCost = 0;\n            \n            if (pos + 1 < (int)bestSuperstring.size()) {\n                char next = bestSuperstring[pos + 1];\n                int nextMinDist = INT_MAX;\n                for (auto [ni, nj] : charPos[next]) {\n                    nextMinDist = min(nextMinDist, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist * 0.65;\n            }\n            if (pos + 2 < (int)bestSuperstring.size()) {\n                char next2 = bestSuperstring[pos + 2];\n                int nextMinDist2 = INT_MAX;\n                for (auto [ni, nj] : charPos[next2]) {\n                    nextMinDist2 = min(nextMinDist2, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist2 * 0.25;\n            }\n            if (pos + 3 < (int)bestSuperstring.size()) {\n                char next3 = bestSuperstring[pos + 3];\n                int nextMinDist3 = INT_MAX;\n                for (auto [ni, nj] : charPos[next3]) {\n                    nextMinDist3 = min(nextMinDist3, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist3 * 0.10;\n            }\n            if (pos + 4 < (int)bestSuperstring.size()) {\n                char next4 = bestSuperstring[pos + 4];\n                int nextMinDist4 = INT_MAX;\n                for (auto [ni, nj] : charPos[next4]) {\n                    nextMinDist4 = min(nextMinDist4, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist4 * 0.08;\n            }\n            if (pos + 5 < (int)bestSuperstring.size()) {\n                char next5 = bestSuperstring[pos + 5];\n                int nextMinDist5 = INT_MAX;\n                for (auto [ni, nj] : charPos[next5]) {\n                    nextMinDist5 = min(nextMinDist5, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist5 * 0.02;\n            }\n            \n            double totalCost = moveCost + lookCost;\n            if (totalCost < minTotalCost) {\n                minTotalCost = totalCost;\n                bestI = ii;\n                bestJ = jj;\n            }\n        }\n        \n        operations.push_back({bestI, bestJ});\n        ci = bestI;\n        cj = bestJ;\n    }\n    \n    for (auto [i, j] : operations) {\n        cout << i << \" \" << j << \"\\n\";\n    }\n    \n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n    \n    for (int k = 0; k < M; k++) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < d; i++) {\n            int r, c;\n            cin >> r >> c;\n        }\n    }\n    \n    set<pair<int,int>> oil_squares;\n    \n    // Divide into 4 quadrants and divine each to guide drilling strategy\n    int half = N / 2;\n    vector<vector<pair<int,int>>> quadrants(4);\n    vector<int> divine_results(4, -1);\n    \n    // Create quadrants\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int q = (i < half ? 0 : 1) * 2 + (j < half ? 0 : 1);\n            quadrants[q].push_back({i, j});\n        }\n    }\n    \n    // Divine each quadrant (very cheap, ~0.25 per quadrant)\n    for (int q = 0; q < 4; q++) {\n        if (quadrants[q].size() >= 2) {\n            cout << \"q \" << quadrants[q].size();\n            for (auto [i, j] : quadrants[q]) {\n                cout << \" \" << i << \" \" << j;\n            }\n            cout << \"\\n\";\n            cout.flush();\n            cin >> divine_results[q];\n        }\n    }\n    \n    // Process each quadrant based on divine results\n    for (int q = 0; q < 4; q++) {\n        int divine_val = divine_results[q];\n        auto& region = quadrants[q];\n        set<pair<int,int>> drilled_here;\n        \n        // Strategy: if divine > 0, drill all; if divine = 0, sample carefully\n        if (divine_val > 0) {\n            // Oil definitely present, drill all squares\n            for (auto [i, j] : region) {\n                cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n                cout.flush();\n                int val;\n                cin >> val;\n                if (val > 0) {\n                    oil_squares.insert({i, j});\n                }\n            }\n        } else if (divine_val == 0) {\n            // Divine says no oil (or very little with noise), sample generously\n            int sample_size = min(5, (int)region.size()); // Sample at least 5 squares\n            int oil_found_in_sample = 0;\n            \n            for (int s = 0; s < sample_size; s++) {\n                int idx = s * region.size() / sample_size;\n                auto [i, j] = region[idx];\n                cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n                cout.flush();\n                int val;\n                cin >> val;\n                drilled_here.insert({i, j});\n                if (val > 0) {\n                    oil_squares.insert({i, j});\n                    oil_found_in_sample++;\n                }\n            }\n            \n            if (oil_found_in_sample > 0) {\n                // Samples found oil, must drill remaining squares\n                for (auto [i, j] : region) {\n                    if (drilled_here.find({i, j}) == drilled_here.end()) {\n                        cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n                        cout.flush();\n                        int val;\n                        cin >> val;\n                        if (val > 0) {\n                            oil_squares.insert({i, j});\n                        }\n                    }\n                }\n            }\n            // If no oil found in samples, we skip remaining (risky but cost-effective)\n        } else {\n            // Single square or error, drill it\n            for (auto [i, j] : region) {\n                cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n                cout.flush();\n                int val;\n                cin >> val;\n                if (val > 0) {\n                    oil_squares.insert({i, j});\n                }\n            }\n        }\n    }\n    \n    // Output answer\n    cout << \"a \" << oil_squares.size();\n    for (auto [i, j] : oil_squares) {\n        cout << \" \" << i << \" \" << j;\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    int result;\n    cin >> result;\n    \n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<long long>> a(D, vector<long long>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    // Process each day independently\n    for (int d = 0; d < D; d++) {\n        // Try column packing first\n        long long total_height = 0;\n        vector<long long> heights(N);\n        for (int k = 0; k < N; k++) {\n            heights[k] = (a[d][k] + W - 1) / W;\n            total_height += heights[k];\n        }\n        \n        if (total_height <= W) {\n            // Column packing works: use it\n            long long y = 0;\n            for (int k = 0; k < N; k++) {\n                cout << y << \" \" << 0 << \" \" << y + heights[k] << \" \" << W << \"\\n\";\n                y += heights[k];\n            }\n        } else {\n            // Column packing doesn't fit: use adaptive 2D grid\n            // Find grid dimensions that minimize area cost\n            \n            long long total_area = 0;\n            for (int k = 0; k < N; k++) {\n                total_area += a[d][k];\n            }\n            \n            int best_cols = 1;\n            long long best_cost = LLONG_MAX;\n            \n            // Try different grid configurations\n            for (int cols = 1; cols <= min(N, W); cols++) {\n                int rows = (N + cols - 1) / cols;\n                if (rows > W) continue;\n                \n                long long cell_w = W / cols;\n                long long cell_h = W / rows;\n                long long cell_area = cell_w * cell_h;\n                \n                // Calculate area cost for this grid\n                long long cost = 0;\n                for (int k = 0; k < N; k++) {\n                    if (a[d][k] > cell_area) {\n                        cost += 100 * (a[d][k] - cell_area);\n                    }\n                }\n                \n                if (cost < best_cost) {\n                    best_cost = cost;\n                    best_cols = cols;\n                }\n            }\n            \n            // Use the best grid configuration\n            int cols = best_cols;\n            int rows = (N + cols - 1) / cols;\n            long long cell_w = W / cols;\n            long long cell_h = W / rows;\n            \n            for (int k = 0; k < N; k++) {\n                int row = k / cols;\n                int col = k % cols;\n                \n                long long i0 = row * cell_h;\n                long long j0 = col * cell_w;\n                long long i1 = (row == rows - 1) ? W : (row + 1) * cell_h;\n                long long j1 = (col == cols - 1) ? W : (col + 1) * cell_w;\n                \n                cout << i0 << \" \" << j0 << \" \" << i1 << \" \" << j1 << \"\\n\";\n            }\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long MOD = 998244353;\n\nint N, M, K;\nvector<vector<vector<long long>>> stamps;\n\nlong long calculate_score(const vector<vector<long long>>& board) {\n    long long score = 0;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            score += board[i][j] % MOD;\n        }\n    }\n    return score;\n}\n\nlong long delta_score(const vector<vector<long long>>& board, int m, int p, int q) {\n    long long delta = 0;\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            int ni = p + i, nj = q + j;\n            long long old_mod = board[ni][nj] % MOD;\n            long long new_mod = (board[ni][nj] + stamps[m][i][j]) % MOD;\n            delta += new_mod - old_mod;\n        }\n    }\n    return delta;\n}\n\nvoid apply_operation(vector<vector<long long>>& board, int m, int p, int q) {\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            board[p+i][q+j] += stamps[m][i][j];\n        }\n    }\n}\n\nlong long get_low_saturation_score(const vector<vector<long long>>& board, int p, int q) {\n    long long score = 0;\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            long long mod_val = board[p+i][q+j] % MOD;\n            if(mod_val < MOD / 3) score += 2;\n            else if(mod_val < 2*MOD / 3) score += 1;\n        }\n    }\n    return score;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    \n    vector<vector<long long>> initial_board(N, vector<long long>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> initial_board[i][j];\n        }\n    }\n    \n    stamps.assign(M, vector<vector<long long>>(3, vector<long long>(3)));\n    vector<long long> stamp_total(M, 0);\n    \n    for(int m = 0; m < M; m++){\n        for(int i = 0; i < 3; i++){\n            for(int j = 0; j < 3; j++){\n                cin >> stamps[m][i][j];\n                stamp_total[m] += stamps[m][i][j];\n            }\n        }\n    }\n    \n    long long best_score = calculate_score(initial_board);\n    vector<tuple<int, int, int>> best_operations;\n    \n    // 160 trials with diverse strategies\n    for(int trial = 0; trial < 160; trial++){\n        mt19937 rng(trial * 49999 + 8675309);\n        \n        auto board = initial_board;\n        vector<tuple<int, int, int>> operations;\n        \n        // Diverse initialization amounts\n        int init_ops;\n        if(trial < 40) {\n            init_ops = (trial * 11) % (K/2);\n        } else if(trial < 100) {\n            init_ops = (trial * 7) % (K/3);\n        } else {\n            init_ops = ((trial - 100) * 13) % (K/4);\n        }\n        \n        // Random initialization phase\n        for(int i = 0; i < init_ops; i++){\n            int m = (rng() % 4 == 0) ? \n                    (max_element(stamp_total.begin(), stamp_total.end()) - stamp_total.begin()) :\n                    (rng() % M);\n            int p = rng() % (N - 2);\n            int q = rng() % (N - 2);\n            apply_operation(board, m, p, q);\n            operations.push_back({m, p, q});\n        }\n        \n        // Main optimization with phase-based scoring\n        int consecutive_stuck = 0;\n        \n        while((int)operations.size() < K && consecutive_stuck < 35){\n            vector<pair<long long, tuple<int,int,int>>> moves;\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                        long long d = delta_score(board, m, p, q);\n                        long long low_sat = get_low_saturation_score(board, p, q);\n                        \n                        long long score;\n                        int ops_size = (int)operations.size();\n                        \n                        if(ops_size < K/3) {\n                            // Early phase: delta-focused with modest low-sat bonus\n                            score = d + low_sat * 60000;\n                        } else if(ops_size < 2*K/3) {\n                            // Mid phase: balanced\n                            score = d + low_sat * 150000;\n                        } else {\n                            // Late phase: aggressive low-sat targeting\n                            score = low_sat * 400000 + d;\n                        }\n                        \n                        moves.push_back({score, {m, p, q}});\n                    }\n                }\n            }\n            \n            sort(moves.rbegin(), moves.rend());\n            \n            long long best_delta = delta_score(board, get<0>(moves[0].second),\n                                              get<1>(moves[0].second),\n                                              get<2>(moves[0].second));\n            \n            if(best_delta > 0){\n                consecutive_stuck = 0;\n                auto [m, p, q] = moves[0].second;\n                apply_operation(board, m, p, q);\n                operations.push_back({m, p, q});\n            } else {\n                consecutive_stuck++;\n                if((int)operations.size() < K){\n                    // Adaptive candidate pool size\n                    int pool_size = min(40 + consecutive_stuck * 4, (int)moves.size());\n                    int idx = rng() % pool_size;\n                    auto [m, p, q] = moves[idx].second;\n                    apply_operation(board, m, p, q);\n                    operations.push_back({m, p, q});\n                }\n            }\n        }\n        \n        long long score = calculate_score(board);\n        if(score > best_score){\n            best_score = score;\n            best_operations = operations;\n        }\n    }\n    \n    cout << best_operations.size() << \"\\n\";\n    for(auto [m, p, q] : best_operations){\n        cout << m << \" \" << p << \" \" << q << \"\\n\";\n    }\n    \n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<vector<int>> grid;\nvector<pair<int,int>> pos;\nvector<int> carry;\nvector<int> active;\n\nint main(){\n    cin >> N;\n    \n    vector<vector<int>> A(N, vector<int>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> A[i][j];\n        }\n    }\n    \n    grid.assign(N, vector<int>(N, -1));\n    pos.resize(N);\n    carry.assign(N, -1);\n    active.assign(N, 1);\n    \n    for(int i = 0; i < N; i++) pos[i] = {i, 0};\n    \n    vector<int> next_in(N, 0);\n    vector<string> res(N, \"\");\n    \n    for(int t = 0; t < 10000; t++){\n        // Step 1: Place arriving containers\n        for(int i = 0; i < N; i++){\n            if(next_in[i] < N && grid[i][0] == -1){\n                bool blocked = false;\n                for(int k = 0; k < N; k++){\n                    if(active[k] && pos[k].first == i && pos[k].second == 0 && carry[k] != -1){\n                        blocked = true;\n                    }\n                }\n                if(!blocked){\n                    grid[i][0] = A[i][next_in[i]];\n                    next_in[i]++;\n                }\n            }\n        }\n        \n        // Step 2: Cranes perform actions\n        vector<char> act(N);\n        vector<pair<int,int>> new_pos(N);\n        \n        // Large crane - clear paths for small cranes\n        if(active[0]){\n            auto [r, c] = pos[0];\n            \n            if(carry[0] >= 0){\n                int tr = carry[0] / N;\n                int tc = N - 1;\n                \n                if(r == tr && c == tc){\n                    act[0] = 'Q';\n                    new_pos[0] = {r, c};\n                } else if(c < tc){\n                    act[0] = 'R';\n                    new_pos[0] = {r, c+1};\n                } else if(r < tr){\n                    act[0] = 'D';\n                    new_pos[0] = {r+1, c};\n                } else {\n                    act[0] = 'U';\n                    new_pos[0] = {r-1, c};\n                }\n            } else {\n                if(grid[r][c] >= 0){\n                    act[0] = 'P';\n                    new_pos[0] = {r, c};\n                } else {\n                    // Prioritize leftmost containers to clear paths\n                    int best_priority = INT_MAX;\n                    pair<int,int> best_pos_t = {r, c};\n                    \n                    for(int i = 0; i < N; i++){\n                        for(int j = 0; j < N; j++){\n                            if(grid[i][j] >= 0){\n                                int priority = j * 100 + abs(i - r);\n                                if(priority < best_priority){\n                                    best_priority = priority;\n                                    best_pos_t = {i, j};\n                                }\n                            }\n                        }\n                    }\n                    \n                    if(best_pos_t == make_pair(r, c)){\n                        act[0] = '.';\n                        new_pos[0] = {r, c};\n                    } else if(best_pos_t.first > r){\n                        act[0] = 'D';\n                        new_pos[0] = {r+1, c};\n                    } else if(best_pos_t.first < r){\n                        act[0] = 'U';\n                        new_pos[0] = {r-1, c};\n                    } else if(best_pos_t.second < c){\n                        act[0] = 'L';\n                        new_pos[0] = {r, c-1};\n                    } else {\n                        act[0] = 'R';\n                        new_pos[0] = {r, c+1};\n                    }\n                }\n            }\n        } else {\n            act[0] = '.';\n            new_pos[0] = pos[0];\n        }\n        \n        // Small cranes\n        for(int k = 1; k < N; k++){\n            if(!active[k]){\n                act[k] = '.';\n                new_pos[k] = pos[k];\n                continue;\n            }\n            \n            auto [r, c] = pos[k];\n            \n            if(carry[k] >= 0){\n                int tr = carry[k] / N;\n                int tc = N - 1;\n                \n                if(r == tr && c == tc){\n                    act[k] = 'Q';\n                    new_pos[k] = {r, c};\n                } else {\n                    // Try right first\n                    if(c < tc && grid[r][c+1] < 0){\n                        act[k] = 'R';\n                        new_pos[k] = {r, c+1};\n                    } else if(r < tr && grid[r+1][c] < 0){\n                        act[k] = 'D';\n                        new_pos[k] = {r+1, c};\n                    } else if(r > tr && grid[r-1][c] < 0){\n                        act[k] = 'U';\n                        new_pos[k] = {r-1, c};\n                    } else {\n                        act[k] = '.';\n                        new_pos[k] = {r, c};\n                    }\n                }\n            } else {\n                if(grid[r][c] >= 0){\n                    act[k] = 'P';\n                    new_pos[k] = {r, c};\n                } else {\n                    // Check if carrying crane is ahead\n                    bool carrying_ahead = false;\n                    for(int m = 0; m < N; m++){\n                        if(m != k && active[m] && carry[m] >= 0 && pos[m].first == r && pos[m].second > c){\n                            carrying_ahead = true;\n                            break;\n                        }\n                    }\n                    \n                    if(carrying_ahead){\n                        // Move out of way\n                        if(c > 0 && grid[r][c-1] < 0){\n                            act[k] = 'L';\n                            new_pos[k] = {r, c-1};\n                        } else if(r > 0 && grid[r-1][c] < 0){\n                            act[k] = 'U';\n                            new_pos[k] = {r-1, c};\n                        } else if(r < N-1 && grid[r+1][c] < 0){\n                            act[k] = 'D';\n                            new_pos[k] = {r+1, c};\n                        } else {\n                            act[k] = '.';\n                            new_pos[k] = {r, c};\n                        }\n                    } else {\n                        // Find containers in this row\n                        if(c > 0){\n                            bool has_container = false;\n                            for(int j = 0; j < c; j++){\n                                if(grid[r][j] >= 0){\n                                    has_container = true;\n                                    break;\n                                }\n                            }\n                            if(has_container){\n                                act[k] = 'L';\n                                new_pos[k] = {r, c-1};\n                            } else {\n                                act[k] = '.';\n                                new_pos[k] = {r, c};\n                            }\n                        } else {\n                            act[k] = '.';\n                            new_pos[k] = {r, c};\n                        }\n                    }\n                }\n            }\n        }\n        \n        // Priority collision resolution\n        bool changed = true;\n        while(changed){\n            changed = false;\n            \n            map<pair<int,int>, vector<int>> dests;\n            for(int k = 0; k < N; k++){\n                if(active[k] && act[k] != 'P' && act[k] != 'Q' && act[k] != '.'){\n                    dests[new_pos[k]].push_back(k);\n                }\n            }\n            \n            for(auto& [d, cranes] : dests){\n                if(cranes.size() > 1){\n                    // Prioritize carrying cranes\n                    int allowed = -1;\n                    for(int k : cranes){\n                        if(carry[k] >= 0){\n                            allowed = k;\n                            break;\n                        }\n                    }\n                    if(allowed == -1) allowed = cranes[0];\n                    \n                    for(int k : cranes){\n                        if(k != allowed){\n                            act[k] = '.';\n                            new_pos[k] = pos[k];\n                            changed = true;\n                        }\n                    }\n                }\n            }\n            \n            for(int k = 0; k < N; k++){\n                if(!active[k] || (act[k] == 'P' || act[k] == 'Q' || act[k] == '.')) continue;\n                for(int m = k+1; m < N; m++){\n                    if(!active[m] || (act[m] == 'P' || act[m] == 'Q' || act[m] == '.')) continue;\n                    if(new_pos[k] == pos[m] && new_pos[m] == pos[k]){\n                        act[k] = '.'; act[m] = '.';\n                        new_pos[k] = pos[k]; new_pos[m] = pos[m];\n                        changed = true;\n                    }\n                }\n            }\n            \n            for(int k = 0; k < N; k++){\n                if(!active[k] || (act[k] == 'P' || act[k] == 'Q' || act[k] == '.')) continue;\n                for(int m = 0; m < N; m++){\n                    if(!active[m] || m == k) continue;\n                    if(act[m] == 'P' || act[m] == 'Q' || act[m] == '.'){\n                        if(new_pos[k] == pos[m]){\n                            act[k] = '.';\n                            new_pos[k] = pos[k];\n                            changed = true;\n                        }\n                    }\n                }\n            }\n            \n            for(int k = 1; k < N; k++){\n                if(!active[k] || carry[k] == -1) continue;\n                if(act[k] != 'P' && act[k] != 'Q' && act[k] != '.'){\n                    if(grid[new_pos[k].first][new_pos[k].second] >= 0){\n                        act[k] = '.';\n                        new_pos[k] = pos[k];\n                        changed = true;\n                    }\n                }\n            }\n        }\n        \n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] == 'P'){\n                if(carry[k] == -1 && grid[pos[k].first][pos[k].second] >= 0){\n                    carry[k] = grid[pos[k].first][pos[k].second];\n                    grid[pos[k].first][pos[k].second] = -1;\n                }\n            }\n        }\n        \n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] != 'P' && act[k] != 'Q' && act[k] != '.' && act[k] != 'B'){\n                pos[k] = new_pos[k];\n            }\n        }\n        \n        for(int k = 0; k < N; k++){\n            if(active[k] && act[k] == 'Q'){\n                if(carry[k] >= 0 && grid[pos[k].first][pos[k].second] == -1){\n                    grid[pos[k].first][pos[k].second] = carry[k];\n                    carry[k] = -1;\n                }\n            }\n        }\n        \n        for(int k = 0; k < N; k++) res[k] += act[k];\n        \n        // Step 3: Dispatch\n        for(int i = 0; i < N; i++){\n            if(grid[i][N-1] >= 0) grid[i][N-1] = -1;\n        }\n    }\n    \n    for(int i = 0; i < N; i++){\n        cout << res[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    \n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h[i][j];\n        }\n    }\n    \n    vector<string> operations;\n    int x = 0, y = 0;\n    int load = 0;\n    \n    auto move_to = [&](int nx, int ny) {\n        while (x != nx) {\n            operations.push_back(x < nx ? \"D\" : \"U\");\n            x += (x < nx ? 1 : -1);\n        }\n        while (y != ny) {\n            operations.push_back(y < ny ? \"R\" : \"L\");\n            y += (y < ny ? 1 : -1);\n        }\n    };\n    \n    // Multi-pass with state tracking\n    // Each pass updates h[][] so subsequent passes see modified terrain\n    \n    // Pass 1: Row-wise snake pattern\n    for (int i = 0; i < N; i++) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; j++) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    operations.push_back(\"+\" + to_string(h[i][j]));\n                    load += h[i][j];\n                    h[i][j] = 0;  // Track state\n                } else if (h[i][j] < 0) {\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                        h[i][j] += unload;  // Track state\n                    }\n                }\n            }\n        } else {\n            for (int j = N - 1; j >= 0; j--) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    operations.push_back(\"+\" + to_string(h[i][j]));\n                    load += h[i][j];\n                    h[i][j] = 0;\n                } else if (h[i][j] < 0) {\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                        h[i][j] += unload;\n                    }\n                }\n            }\n        }\n    }\n    \n    // Pass 2: Column-wise snake pattern\n    // Different traversal order handles cases where negatives come before positives\n    for (int j = 0; j < N; j++) {\n        if (j % 2 == 0) {\n            for (int i = 0; i < N; i++) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    operations.push_back(\"+\" + to_string(h[i][j]));\n                    load += h[i][j];\n                    h[i][j] = 0;\n                } else if (h[i][j] < 0) {\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                        h[i][j] += unload;\n                    }\n                }\n            }\n        } else {\n            for (int i = N - 1; i >= 0; i--) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    operations.push_back(\"+\" + to_string(h[i][j]));\n                    load += h[i][j];\n                    h[i][j] = 0;\n                } else if (h[i][j] < 0) {\n                    int unload = min(load, -h[i][j]);\n                    if (unload > 0) {\n                        operations.push_back(\"-\" + to_string(unload));\n                        load -= unload;\n                        h[i][j] += unload;\n                    }\n                }\n            }\n        }\n    }\n    \n    for (const auto& op : operations) {\n        cout << op << \"\\n\";\n    }\n    \n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <set>\n\nusing namespace std;\n\nint main() {\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> X(seed_count, vector<int>(M));\n\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> X[i][j];\n        }\n    }\n\n    // Precompute positions ordered by neighbor count (interior first)\n    vector<pair<int, int>> position_order;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            position_order.push_back({i, j});\n        }\n    }\n    \n    sort(position_order.begin(), position_order.end(), [&](const auto& a, const auto& b) {\n        auto neighbor_count = [&](const pair<int,int>& p) {\n            return (p.first > 0) + (p.first < N-1) + (p.second > 0) + (p.second < N-1);\n        };\n        return neighbor_count(a) > neighbor_count(b);\n    });\n\n    for (int t = 0; t < T; t++) {\n        // Calculate total value for each seed\n        vector<long long> values(seed_count, 0);\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                values[i] += X[i][j];\n            }\n        }\n        \n        // K=2: Select top 2 seeds per criterion\n        set<int> selected_set;\n        \n        for (int crit = 0; crit < M; crit++) {\n            vector<int> seeds_for_crit(seed_count);\n            iota(seeds_for_crit.begin(), seeds_for_crit.end(), 0);\n            \n            sort(seeds_for_crit.begin(), seeds_for_crit.end(), [&](int a, int b) {\n                if (X[a][crit] != X[b][crit]) {\n                    return X[a][crit] > X[b][crit];\n                }\n                // Tiebreaker: prefer high total value\n                return values[a] > values[b];\n            });\n            \n            // Select top 2 seeds for this criterion\n            for (int i = 0; i < 2 && i < seed_count; i++) {\n                selected_set.insert(seeds_for_crit[i]);\n                if (selected_set.size() >= (size_t)(N * N)) break;\n            }\n            if (selected_set.size() >= (size_t)(N * N)) break;\n        }\n        \n        // Fill remaining slots with highest total-value seeds\n        vector<int> sorted_by_value(seed_count);\n        iota(sorted_by_value.begin(), sorted_by_value.end(), 0);\n        sort(sorted_by_value.begin(), sorted_by_value.end(), [&](int a, int b) {\n            return values[a] > values[b];\n        });\n        \n        for (int seed_id : sorted_by_value) {\n            if (selected_set.size() >= (size_t)(N * N)) break;\n            selected_set.insert(seed_id);\n        }\n\n        // Convert to vector and sort by comprehensive criteria for position assignment\n        vector<int> selected_seeds(selected_set.begin(), selected_set.end());\n        sort(selected_seeds.begin(), selected_seeds.end(), [&](int a, int b) {\n            // Primary: total value (most important)\n            if (values[a] != values[b]) {\n                return values[a] > values[b];\n            }\n            // Secondary: maximum criterion value (seek peaks)\n            int max_a = *max_element(X[a].begin(), X[a].end());\n            int max_b = *max_element(X[b].begin(), X[b].end());\n            if (max_a != max_b) {\n                return max_a > max_b;\n            }\n            // Tertiary: minimum criterion value (prefer balance)\n            int min_a = *min_element(X[a].begin(), X[a].end());\n            int min_b = *min_element(X[b].begin(), X[b].end());\n            return min_a > min_b;\n        });\n\n        // Deterministic greedy: highest-value seeds go to highest-neighbor positions\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (size_t idx = 0; idx < selected_seeds.size(); idx++) {\n            int seed_id = selected_seeds[idx];\n            int pos_i = position_order[idx].first;\n            int pos_j = position_order[idx].second;\n            grid[pos_i][pos_j] = seed_id;\n        }\n\n        // Output grid\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (j > 0) cout << \" \";\n                cout << grid[i][j];\n            }\n            cout << \"\\n\";\n        }\n        cout.flush();\n\n        // Read new generation seeds\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> X[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, V;\n    cin >> N >> M >> V;\n    \n    vector<string> s(N), t(N);\n    for(int i = 0; i < N; i++) cin >> s[i];\n    for(int i = 0; i < N; i++) cin >> t[i];\n    \n    cout << \"2\\n\";\n    cout << \"0 1\\n\";\n    cout << \"0 0\\n\";\n    \n    int rx = 0, ry = 0;\n    int rot = 0; // 0=right, 1=down, 2=left, 3=up\n    int turns = 0;\n    \n    // Track state\n    vector<vector<int>> grid(N, vector<int>(N, 0));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            grid[i][j] = (s[i][j] == '1') ? 1 : 0;\n        }\n    }\n    \n    auto get_finger = [&]() -> pair<int,int> {\n        if(rot == 0) return {rx, ry + 1};\n        if(rot == 1) return {rx + 1, ry};\n        if(rot == 2) return {rx, ry - 1};\n        return {rx - 1, ry};\n    };\n    \n    auto move_to = [&](int tx, int ty) {\n        // Find best rotation to reach (tx, ty)\n        int best_rot = rot;\n        for(int r = 0; r < 4; r++){\n            int req_rx = tx, req_ry = ty;\n            if(r == 0) req_ry--;\n            else if(r == 1) req_rx--;\n            else if(r == 2) req_ry++;\n            else req_rx++;\n            \n            if(req_rx >= 0 && req_rx < N && req_ry >= 0 && req_ry < N){\n                best_rot = r;\n                break;\n            }\n        }\n        \n        // Rotate to best_rot\n        while(rot != best_rot && turns < 100000){\n            string op = \"....\";\n            int diff = (best_rot - rot + 4) % 4;\n            if(diff <= 2) {\n                op[1] = 'R';\n                rot = (rot + 1) % 4;\n            } else {\n                op[1] = 'L';\n                rot = (rot + 3) % 4;\n            }\n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        // Move root to reach target\n        while(turns < 100000){\n            auto [fx, fy] = get_finger();\n            if(fx == tx && fy == ty) break;\n            \n            string op = \"....\";\n            int req_rx = tx, req_ry = ty;\n            if(rot == 0) req_ry--;\n            else if(rot == 1) req_rx--;\n            else if(rot == 2) req_ry++;\n            else req_rx++;\n            \n            if(rx < req_rx) { rx++; op[0] = 'D'; }\n            else if(rx > req_rx) { rx--; op[0] = 'U'; }\n            else if(ry < req_ry) { ry++; op[0] = 'R'; }\n            else if(ry > req_ry) { ry--; op[0] = 'L'; }\n            \n            cout << op << \"\\n\";\n            turns++;\n        }\n    };\n    \n    // Find squares that need to be cleared and filled\n    vector<pair<int,int>> to_clear, to_fill;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(s[i][j] == '1' && t[i][j] == '0') to_clear.push_back({i, j});\n            if(s[i][j] == '0' && t[i][j] == '1') to_fill.push_back({i, j});\n        }\n    }\n    \n    // Process each takoyaki that needs to move\n    for(int idx = 0; idx < (int)to_clear.size() && turns < 100000; idx++){\n        auto [sx, sy] = to_clear[idx];\n        \n        // Check if still has takoyaki\n        if(grid[sx][sy] == 0) continue;\n        \n        // Find best available target\n        int best_tx = -1, best_ty = -1;\n        int min_dist = INT_MAX;\n        for(auto [tx, ty] : to_fill) {\n            if(grid[tx][ty] == 0) {  // Only consider empty targets\n                int dist = abs(sx - tx) + abs(sy - ty);\n                if(dist < min_dist) {\n                    min_dist = dist;\n                    best_tx = tx;\n                    best_ty = ty;\n                }\n            }\n        }\n        \n        if(best_tx == -1) continue; // No available target\n        \n        // Move arm to source\n        move_to(sx, sy);\n        if(turns >= 100000) break;\n        \n        // Pick up takoyaki\n        cout << \"...P\\n\";\n        grid[sx][sy] = 0;\n        turns++;\n        \n        // Move arm to target\n        move_to(best_tx, best_ty);\n        if(turns >= 100000) break;\n        \n        // Place takoyaki\n        cout << \"...P\\n\";\n        grid[best_tx][best_ty] = 1;\n        turns++;\n    }\n    \n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    \n    vector<pair<int, int>> mackerel(N), sardine(N);\n    \n    for(int i = 0; i < N; i++){\n        cin >> mackerel[i].first >> mackerel[i].second;\n    }\n    \n    for(int i = 0; i < N; i++){\n        cin >> sardine[i].first >> sardine[i].second;\n    }\n    \n    auto count_in_rect = [](const vector<pair<int, int>>& pts, int x1, int y1, int x2, int y2) {\n        int count = 0;\n        for(auto [x, y] : pts) {\n            if(x >= x1 && x <= x2 && y >= y1 && y <= y2) {\n                count++;\n            }\n        }\n        return count;\n    };\n    \n    auto score_rect = [&](int x1, int y1, int x2, int y2) {\n        int m = count_in_rect(mackerel, x1, y1, x2, y2);\n        int s = count_in_rect(sardine, x1, y1, x2, y2);\n        return max(0, m - s + 1);\n    };\n    \n    // Find bounding box of all mackerels\n    int minX = INT_MAX, maxX = INT_MIN;\n    int minY = INT_MAX, maxY = INT_MIN;\n    \n    for(auto [x, y] : mackerel){\n        minX = min(minX, x);\n        maxX = max(maxX, x);\n        minY = min(minY, y);\n        maxY = max(maxY, y);\n    }\n    \n    int bestX1 = minX, bestY1 = minY, bestX2 = maxX, bestY2 = maxY;\n    int bestScore = score_rect(bestX1, bestY1, bestX2, bestY2);\n    \n    // Iterative local search with progressively finer granularity\n    for(int phase = 0; phase < 5; phase++) {\n        bool improved = true;\n        \n        while(improved) {\n            improved = false;\n            \n            int dx = max(1, (bestX2 - bestX1) >> (5 - phase));\n            int dy = max(1, (bestY2 - bestY1) >> (5 - phase));\n            \n            // Try shrinking from left\n            for(int x = bestX1; x < bestX2; x += dx) {\n                int s = score_rect(x, bestY1, bestX2, bestY2);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestX1 = x;\n                    improved = true;\n                    break;\n                }\n            }\n            \n            // Try shrinking from right\n            for(int x = bestX2; x > bestX1; x -= dx) {\n                int s = score_rect(bestX1, bestY1, x, bestY2);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestX2 = x;\n                    improved = true;\n                    break;\n                }\n            }\n            \n            // Try shrinking from bottom\n            for(int y = bestY1; y < bestY2; y += dy) {\n                int s = score_rect(bestX1, y, bestX2, bestY2);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestY1 = y;\n                    improved = true;\n                    break;\n                }\n            }\n            \n            // Try shrinking from top\n            for(int y = bestY2; y > bestY1; y -= dy) {\n                int s = score_rect(bestX1, bestY1, bestX2, y);\n                if(s > bestScore) {\n                    bestScore = s;\n                    bestY2 = y;\n                    improved = true;\n                    break;\n                }\n            }\n        }\n    }\n    \n    cout << 4 << \"\\n\";\n    cout << bestX1 << \" \" << bestY1 << \"\\n\";\n    cout << bestX2 << \" \" << bestY1 << \"\\n\";\n    cout << bestX2 << \" \" << bestY2 << \"\\n\";\n    cout << bestX1 << \" \" << bestY2 << \"\\n\";\n    \n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\npair<long long, long long> simulate(\n    const vector<tuple<int, int, char, int>>& placement,\n    const vector<pair<long long, long long>>& rects\n) {\n    map<int, array<long long, 4>> pos;\n    long long max_x = 0, max_y = 0;\n    \n    for (auto [idx, rot, dir, ref] : placement) {\n        long long w = rects[idx].first;\n        long long h = rects[idx].second;\n        if (rot) swap(w, h);\n        \n        long long x = 0, y = 0;\n        \n        if (dir == 'U') {\n            if (ref != -1 && pos.count(ref)) {\n                x = pos[ref][0] + pos[ref][2];\n            }\n            for (auto& [i, p] : pos) {\n                if (p[0] < x + w && x < p[0] + p[2]) {\n                    y = max(y, p[1] + p[3]);\n                }\n            }\n        } else { // 'L'\n            if (ref != -1 && pos.count(ref)) {\n                y = pos[ref][1] + pos[ref][3];\n            }\n            for (auto& [i, p] : pos) {\n                if (p[1] < y + h && y < p[1] + p[3]) {\n                    x = max(x, p[0] + p[2]);\n                }\n            }\n        }\n        \n        pos[idx] = {x, y, w, h};\n        max_x = max(max_x, x + w);\n        max_y = max(max_y, y + h);\n    }\n    \n    return {max_x, max_y};\n}\n\nlong long calc_score(\n    const vector<tuple<int, int, char, int>>& placement,\n    const vector<pair<long long, long long>>& rects,\n    int N\n) {\n    auto [w, h] = simulate(placement, rects);\n    long long cost = w + h;\n    \n    set<int> used;\n    for (auto [p, r, d, b] : placement) {\n        used.insert(p);\n    }\n    \n    for (int i = 0; i < N; i++) {\n        if (!used.count(i)) {\n            cost += rects[i].first + rects[i].second;\n        }\n    }\n    \n    return cost;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, T;\n    long long sigma;\n    cin >> N >> T >> sigma;\n    \n    vector<pair<long long, long long>> rects(N);\n    for (int i = 0; i < N; i++) {\n        cin >> rects[i].first >> rects[i].second;\n    }\n    \n    mt19937 rng(987654321);\n    auto start_time = chrono::high_resolution_clock::now();\n    \n    for (int t = 0; t < T; t++) {\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(\n            chrono::high_resolution_clock::now() - start_time).count();\n        \n        if (elapsed > 2850) {\n            vector<tuple<int, int, char, int>> p;\n            for (int i = 0; i < N; i++) {\n                p.push_back({i, 0, 'U', -1});\n            }\n            cout << p.size() << \"\\n\";\n            for (auto [a, b, c, d] : p) {\n                cout << a << \" \" << b << \" \" << c << \" \" << d << \"\\n\";\n            }\n            cout.flush();\n            long long W, H;\n            cin >> W >> H;\n            break;\n        }\n        \n        long long best_score = LLONG_MAX;\n        vector<tuple<int, int, char, int>> best_placement;\n        \n        // Deterministic strategies\n        \n        // Strategy 1: All U with -1\n        {\n            vector<tuple<int, int, char, int>> placement;\n            for (int i = 0; i < N; i++) {\n                placement.push_back({i, 0, 'U', -1});\n            }\n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        // Strategy 2: All L with -1\n        {\n            vector<tuple<int, int, char, int>> placement;\n            for (int i = 0; i < N; i++) {\n                placement.push_back({i, 0, 'L', -1});\n            }\n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        // Strategy 3: All U, with rotations favoring small dimensions\n        {\n            vector<tuple<int, int, char, int>> placement;\n            for (int i = 0; i < N; i++) {\n                int r = (rects[i].first > rects[i].second) ? 1 : 0;\n                placement.push_back({i, r, 'U', -1});\n            }\n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        // Strategy 4: All L, with rotations favoring small dimensions\n        {\n            vector<tuple<int, int, char, int>> placement;\n            for (int i = 0; i < N; i++) {\n                int r = (rects[i].second > rects[i].first) ? 1 : 0;\n                placement.push_back({i, r, 'L', -1});\n            }\n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        // Strategy 5: Alternating U and L\n        {\n            vector<tuple<int, int, char, int>> placement;\n            for (int i = 0; i < N; i++) {\n                char d = (i % 2) ? 'L' : 'U';\n                placement.push_back({i, 0, d, -1});\n            }\n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        // Strategy 6: Progressive subset sizes\n        for (int sz : {5, 10, 15, 20, min(N, N*2/3), N}) {\n            vector<tuple<int, int, char, int>> placement;\n            for (int i = 0; i < sz; i++) {\n                placement.push_back({i, 0, 'U', -1});\n            }\n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        // Random attempts - 230 total\n        int num_random = 230;\n        for (int att = 0; att < num_random; att++) {\n            vector<tuple<int, int, char, int>> placement;\n            \n            int use_count;\n            int strat = att % 23;\n            \n            if (strat < 6) {\n                // Small fixed sizes\n                use_count = strat + 1;\n            } else if (strat < 14) {\n                // Medium sizes\n                int base = N / 3 + (strat - 6) * N / 12;\n                use_count = min(N, base + (int)(rng() % (N / 5 + 1)));\n            } else if (strat < 19) {\n                // Random sizes\n                use_count = 1 + (int)(rng() % N);\n            } else {\n                // Large sizes\n                use_count = min(N, N / 2 + (int)(rng() % (N / 2 + 1)));\n            }\n            \n            for (int i = 0; i < use_count; i++) {\n                // Rotation: bias based on aspect ratio\n                int r;\n                if ((long long)rects[i].first * rects[i].second > 0) {\n                    double aspect = (double)rects[i].first / rects[i].second;\n                    r = (aspect > 1.5) ? 1 : (aspect < 0.67 ? 0 : (int)(rng() % 2));\n                } else {\n                    r = (int)(rng() % 2);\n                }\n                \n                // Direction: alternate with some randomness\n                char d;\n                int dir_bias = (int)(rng() % 10);\n                if (i < use_count / 3) {\n                    d = (dir_bias < 7) ? 'U' : 'L';\n                } else if (i < (use_count * 2) / 3) {\n                    d = (dir_bias < 5) ? 'U' : 'L';\n                } else {\n                    d = (dir_bias < 4) ? 'L' : 'U';\n                }\n                \n                // Reference: prefer nearby\n                int b = -1;\n                if (i > 0) {\n                    int ref_rand = (int)(rng() % 10);\n                    if (ref_rand < 8) {\n                        // Prefer recent\n                        int max_back = min(i, 3 + i / 4);\n                        b = i - 1 - (int)(rng() % max_back);\n                    }\n                }\n                \n                placement.push_back({i, r, d, b});\n            }\n            \n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        cout << best_placement.size() << \"\\n\";\n        for (auto [p, r, d, b] : best_placement) {\n            cout << p << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        }\n        cout.flush();\n        \n        long long W, H;\n        cin >> W >> H;\n    }\n    \n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, H;\nvector<int> A;\nvector<vector<int>> adj;\nvector<double> x, y;\n\nlong long evaluateSolution(const vector<int>& parent) {\n    vector<int> depth(N, -1);\n    long long score = 0;\n    \n    function<void(int)> dfs = [&](int u) {\n        score += (long long)(depth[u] + 1) * A[u];\n        for(int v : adj[u]){\n            if(parent[v] == u && depth[v] == -1){\n                depth[v] = depth[u] + 1;\n                dfs(v);\n            }\n        }\n    };\n    \n    for(int i = 0; i < N; i++){\n        if(parent[i] == -1){\n            depth[i] = 0;\n            dfs(i);\n        }\n    }\n    return score;\n}\n\nvector<int> buildTreeBFS(const vector<int>& rootOrder) {\n    vector<int> parent(N, -2);\n    \n    for(int root : rootOrder){\n        if(parent[root] != -2) continue;\n        \n        queue<int> q;\n        q.push(root);\n        parent[root] = -1;\n        vector<int> depth(N, -1);\n        depth[root] = 0;\n        \n        while(!q.empty()){\n            int u = q.front();\n            q.pop();\n            \n            if(depth[u] >= H) continue;\n            \n            vector<pair<int, int>> neighbors;\n            for(int v : adj[u]){\n                if(parent[v] == -2){\n                    neighbors.push_back({A[v], v});\n                }\n            }\n            \n            sort(neighbors.rbegin(), neighbors.rend());\n            \n            for(auto [_, v] : neighbors){\n                parent[v] = u;\n                depth[v] = depth[u] + 1;\n                q.push(v);\n            }\n        }\n    }\n    return parent;\n}\n\nvector<int> buildTreeDFS(const vector<int>& rootOrder) {\n    vector<int> parent(N, -2);\n    \n    for(int root : rootOrder){\n        if(parent[root] != -2) continue;\n        \n        vector<int> depth(N, -1);\n        parent[root] = -1;\n        depth[root] = 0;\n        \n        function<void(int, int)> dfs = [&](int u, int d) {\n            if(d >= H) return;\n            \n            vector<pair<int, int>> neighbors;\n            for(int v : adj[u]){\n                if(parent[v] == -2){\n                    neighbors.push_back({A[v], v});\n                }\n            }\n            \n            sort(neighbors.rbegin(), neighbors.rend());\n            \n            for(auto [_, v] : neighbors){\n                parent[v] = u;\n                depth[v] = d + 1;\n                dfs(v, d + 1);\n            }\n        };\n        \n        dfs(root, 0);\n    }\n    return parent;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int H_input;\n    cin >> N >> M >> H_input;\n    H = H_input;\n    \n    A.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> A[i];\n    }\n    \n    adj.resize(N);\n    for(int i = 0; i < M; i++){\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    x.resize(N);\n    y.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<int> best_parent(N);\n    long long best_score = -1;\n    \n    auto tryOrder = [&](vector<int> ord, bool useDFS = false) {\n        auto parent = useDFS ? buildTreeDFS(ord) : buildTreeBFS(ord);\n        long long score = evaluateSolution(parent);\n        if(score > best_score){\n            best_score = score;\n            best_parent = parent;\n        }\n    };\n    \n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    \n    // Core beauty/degree heuristics with both BFS and DFS\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return A[a] > A[b]; });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n    }\n    \n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return A[a] < A[b]; });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n    }\n    \n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return adj[a].size() > adj[b].size(); });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n    }\n    \n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return adj[a].size() < adj[b].size(); });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n    }\n    \n    // Geometric heuristics - distance from center\n    {\n        double cx = 500, cy = 500;\n        \n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double da = (x[a]-cx)*(x[a]-cx) + (y[a]-cy)*(y[a]-cy);\n            double db = (x[b]-cx)*(x[b]-cx) + (y[b]-cy)*(y[b]-cy);\n            return da < db;\n        });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n        \n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double da = (x[a]-cx)*(x[a]-cx) + (y[a]-cy)*(y[a]-cy);\n            double db = (x[b]-cx)*(x[b]-cx) + (y[b]-cy)*(y[b]-cy);\n            return da > db;\n        });\n        tryOrder(ord, false);\n        tryOrder(ord, true);\n    }\n    \n    // Angle-based ordering\n    {\n        double cx = 500, cy = 500;\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double aa = atan2(y[a]-cy, x[a]-cx);\n            double ab = atan2(y[b]-cy, x[b]-cx);\n            return aa < ab;\n        });\n        tryOrder(ord, false);\n    }\n    \n    // X and Y coordinates\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return x[a] < x[b]; });\n        tryOrder(ord, false);\n    }\n    \n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){ return y[a] < y[b]; });\n        tryOrder(ord, false);\n    }\n    \n    // Fine-grained beauty + weight*degree combinations\n    for(double w = -2.0; w <= 2.05; w += 0.1){\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double sa = A[a] + w * adj[a].size();\n            double sb = A[b] + w * adj[b].size();\n            return sa > sb;\n        });\n        tryOrder(ord, false);\n    }\n    \n    // Beauty * pow(degree+1, w)\n    for(double w = 0.0; w <= 2.05; w += 0.1){\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double sa = A[a] * pow(1.0 + adj[a].size(), w);\n            double sb = A[b] * pow(1.0 + adj[b].size(), w);\n            return sa > sb;\n        });\n        tryOrder(ord, false);\n    }\n    \n    // Ratio metrics\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double sa = (double)A[a] / (1.0 + adj[a].size());\n            double sb = (double)A[b] / (1.0 + adj[b].size());\n            return sa > sb;\n        });\n        tryOrder(ord, false);\n    }\n    \n    // Logarithmic\n    {\n        auto ord = order;\n        sort(ord.begin(), ord.end(), [&](int a, int b){\n            double sa = A[a] * log(2.0 + adj[a].size());\n            double sb = A[b] * log(2.0 + adj[b].size());\n            return sa > sb;\n        });\n        tryOrder(ord, false);\n    }\n    \n    // Extensive random sampling with both BFS and DFS\n    for(int seed = 0; seed < 480; seed++){\n        mt19937 rng(seed);\n        auto ord = order;\n        shuffle(ord.begin(), ord.end(), rng);\n        tryOrder(ord, seed % 2 == 0);\n    }\n    \n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << best_parent[i];\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int N;\n    cin >> N;\n    \n    vector<string> board(N);\n    for (int i = 0; i < N; i++) {\n        cin >> board[i];\n    }\n    \n    vector<pair<char, int>> operations;\n    \n    auto findOni = [&]() -> pair<int, int> {\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (board[i][j] == 'x') return {i, j};\n            }\n        }\n        return {-1, -1};\n    };\n    \n    auto shiftUp = [&](int j) {\n        for (int i = 0; i < N - 1; i++) board[i][j] = board[i + 1][j];\n        board[N - 1][j] = '.';\n        operations.push_back({'U', j});\n    };\n    \n    auto shiftDown = [&](int j) {\n        for (int i = N - 1; i > 0; i--) board[i][j] = board[i - 1][j];\n        board[0][j] = '.';\n        operations.push_back({'D', j});\n    };\n    \n    auto shiftLeft = [&](int i) {\n        for (int j = 0; j < N - 1; j++) board[i][j] = board[i][j + 1];\n        board[i][N - 1] = '.';\n        operations.push_back({'L', i});\n    };\n    \n    auto shiftRight = [&](int i) {\n        for (int j = N - 1; j > 0; j--) board[i][j] = board[i][j - 1];\n        board[i][0] = '.';\n        operations.push_back({'R', i});\n    };\n    \n    while (true) {\n        auto [i, j] = findOni();\n        if (i == -1) break;\n        \n        // Check all four directions and pick the one with minimum cost\n        int minCost = INT_MAX;\n        int bestDir = -1; // 0=up, 1=down, 2=left, 3=right\n        \n        // Check upward direction\n        bool clearUp = true;\n        for (int k = 0; k < i; k++) {\n            if (board[k][j] == 'o') { clearUp = false; break; }\n        }\n        if (clearUp) {\n            int cost = 2 * (i + 1);\n            if (cost < minCost) { minCost = cost; bestDir = 0; }\n        }\n        \n        // Check downward direction\n        bool clearDown = true;\n        for (int k = i + 1; k < N; k++) {\n            if (board[k][j] == 'o') { clearDown = false; break; }\n        }\n        if (clearDown) {\n            int cost = 2 * (N - i);\n            if (cost < minCost) { minCost = cost; bestDir = 1; }\n        }\n        \n        // Check leftward direction\n        bool clearLeft = true;\n        for (int k = 0; k < j; k++) {\n            if (board[i][k] == 'o') { clearLeft = false; break; }\n        }\n        if (clearLeft) {\n            int cost = 2 * (j + 1);\n            if (cost < minCost) { minCost = cost; bestDir = 2; }\n        }\n        \n        // Check rightward direction\n        bool clearRight = true;\n        for (int k = j + 1; k < N; k++) {\n            if (board[i][k] == 'o') { clearRight = false; break; }\n        }\n        if (clearRight) {\n            int cost = 2 * (N - j);\n            if (cost < minCost) { minCost = cost; bestDir = 3; }\n        }\n        \n        // Apply the best direction (guaranteed to exist by problem statement)\n        if (bestDir == 0) {\n            for (int k = 0; k <= i; k++) shiftUp(j);\n            for (int k = 0; k <= i; k++) shiftDown(j);\n        } else if (bestDir == 1) {\n            for (int k = 0; k < N - i; k++) shiftDown(j);\n            for (int k = 0; k < N - i; k++) shiftUp(j);\n        } else if (bestDir == 2) {\n            for (int k = 0; k <= j; k++) shiftLeft(i);\n            for (int k = 0; k <= j; k++) shiftRight(i);\n        } else if (bestDir == 3) {\n            for (int k = 0; k < N - j; k++) shiftRight(i);\n            for (int k = 0; k < N - j; k++) shiftLeft(i);\n        }\n    }\n    \n    for (auto [d, p] : operations) {\n        cout << d << \" \" << p << \"\\n\";\n    }\n    \n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nlong long computeError(const vector<int>& a, const vector<int>& b, int N, long long L, const vector<int>& T) {\n    vector<long long> count(N, 0);\n    int current = 0;\n    count[0]++;\n    \n    for (long long week = 1; week < L; week++) {\n        int next = (count[current] & 1) ? a[current] : b[current];\n        count[next]++;\n        current = next;\n    }\n    \n    long long error = 0;\n    for (int i = 0; i < N; i++) {\n        error += abs(count[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, L;\n    cin >> N >> L;\n    \n    vector<int> T(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n    \n    vector<int> best_a(N), best_b(N);\n    long long best_error = LLONG_MAX;\n    \n    mt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n    \n    // 6 diverse strategies - proven effective patterns\n    for (int strategy = 0; strategy < 6; strategy++) {\n        vector<int> a(N), b(N);\n        \n        if (strategy == 0) {\n            // Simple forward cycle\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 1) % N;\n            }\n        } else if (strategy == 1) {\n            // Forward with offset +2\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 2) % N;\n            }\n        } else if (strategy == 2) {\n            // Forward and backward\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i - 1 + N) % N;\n            }\n        } else if (strategy == 3) {\n            // Self-loop and forward\n            for (int i = 0; i < N; i++) {\n                a[i] = i;\n                b[i] = (i + 1) % N;\n            }\n        } else if (strategy == 4) {\n            // Skip 2 both directions\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 2) % N;\n                b[i] = (i - 2 + N) % N;\n            }\n        } else {\n            // Forward with offset +3\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 3) % N;\n            }\n        }\n        \n        long long error = computeError(a, b, N, L, T);\n        \n        // Local search with increased iterations\n        int no_improve = 0;\n        for (int iter = 0; iter < 145 && no_improve < 38; iter++) {\n            int emp = rng() % N;\n            int param = rng() % 2;\n            int old_val = (param == 0) ? a[emp] : b[emp];\n            int new_val = rng() % N;\n            \n            if (param == 0) {\n                a[emp] = new_val;\n            } else {\n                b[emp] = new_val;\n            }\n            \n            long long new_error = computeError(a, b, N, L, T);\n            \n            if (new_error < error) {\n                error = new_error;\n                no_improve = 0;\n            } else {\n                if (param == 0) {\n                    a[emp] = old_val;\n                } else {\n                    b[emp] = old_val;\n                }\n                no_improve++;\n            }\n        }\n        \n        if (error < best_error) {\n            best_error = error;\n            best_a = a;\n            best_b = b;\n        }\n    }\n    \n    // Enhanced final intensive local search on best solution\n    int no_improve = 0;\n    for (int iter = 0; iter < 200 && no_improve < 52; iter++) {\n        int emp = rng() % N;\n        int param = rng() % 2;\n        int old_val = (param == 0) ? best_a[emp] : best_b[emp];\n        int new_val = rng() % N;\n        \n        if (param == 0) {\n            best_a[emp] = new_val;\n        } else {\n            best_b[emp] = new_val;\n        }\n        \n        long long new_error = computeError(best_a, best_b, N, L, T);\n        \n        if (new_error < best_error) {\n            best_error = new_error;\n            no_improve = 0;\n        } else {\n            if (param == 0) {\n                best_a[emp] = old_val;\n            } else {\n                best_b[emp] = old_val;\n            }\n            no_improve++;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass DSU {\npublic:\n    vector<int> parent;\n    \n    DSU(int n) : parent(n) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    \n    int find(int x) {\n        if(parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    \n    bool unite(int x, int y) {\n        int px = find(x);\n        int py = find(y);\n        if(px == py) return false;\n        parent[px] = py;\n        return true;\n    }\n};\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    \n    vector<int> G(M);\n    for(int i = 0; i < M; i++){\n        cin >> G[i];\n    }\n    \n    vector<double> lx(N), rx(N), ly(N), ry(N);\n    for(int i = 0; i < N; i++){\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n    \n    // Estimate positions using rectangle centers\n    vector<pair<double,double>> pos(N);\n    double minx = 1e18, maxx = -1e18, miny = 1e18, maxy = -1e18;\n    for(int i = 0; i < N; i++){\n        pos[i] = {(lx[i] + rx[i]) / 2.0, (ly[i] + ry[i]) / 2.0};\n        minx = min(minx, pos[i].first);\n        maxx = max(maxx, pos[i].first);\n        miny = min(miny, pos[i].second);\n        maxy = max(maxy, pos[i].second);\n    }\n    \n    // Compute geometric center\n    double cx = (minx + maxx) / 2.0;\n    double cy = (miny + maxy) / 2.0;\n    \n    // Sort by polar angle from center\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int i, int j){\n        double angle_i = atan2(pos[i].second - cy, pos[i].first - cx);\n        double angle_j = atan2(pos[j].second - cy, pos[j].first - cx);\n        if(fabs(angle_i - angle_j) > 1e-9) return angle_i < angle_j;\n        \n        double dist_i = (pos[i].first - cx) * (pos[i].first - cx) + \n                       (pos[i].second - cy) * (pos[i].second - cy);\n        double dist_j = (pos[j].first - cx) * (pos[j].first - cx) + \n                       (pos[j].second - cy) * (pos[j].second - cy);\n        return dist_i < dist_j;\n    });\n    \n    // Assign to groups\n    vector<vector<int>> groups(M);\n    int idx = 0;\n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g]; i++){\n            groups[g].push_back(order[idx++]);\n        }\n        \n        // Sort within group for better locality\n        sort(groups[g].begin(), groups[g].end(), [&](int i, int j){\n            if(fabs(pos[i].first - pos[j].first) > 1e-9) return pos[i].first < pos[j].first;\n            return pos[i].second < pos[j].second;\n        });\n    }\n    \n    // Collect edges and build spanning trees\n    vector<vector<pair<int,int>>> final_edges(M);\n    \n    for(int g = 0; g < M; g++){\n        vector<pair<int,int>> all_edges;\n        int gsize = G[g];\n        \n        // Query using sliding windows of size 3\n        for(int i = 0; i + 2 < gsize; i += 2){\n            cout << \"? 3 \" << groups[g][i] << \" \" << groups[g][i+1] << \" \" << groups[g][i+2] << \"\\n\";\n            cout.flush();\n            \n            for(int j = 0; j < 2; j++){\n                int a, b;\n                cin >> a >> b;\n                all_edges.push_back({a, b});\n            }\n        }\n        \n        // Handle remaining cities\n        if((gsize - 1) % 2 == 1){\n            // Odd number of cities left after windows\n            all_edges.push_back({groups[g][gsize - 2], groups[g][gsize - 1]});\n        }\n        \n        // Build spanning tree using DSU\n        DSU dsu(N);\n        \n        for(auto [a, b] : all_edges){\n            if(dsu.unite(a, b)){\n                final_edges[g].push_back({a, b});\n                if((int)final_edges[g].size() == gsize - 1) break;\n            }\n        }\n        \n        // Ensure connectivity - add direct edges if needed\n        if((int)final_edges[g].size() < gsize - 1){\n            for(int i = 1; i < gsize; i++){\n                if((int)final_edges[g].size() >= gsize - 1) break;\n                if(dsu.unite(groups[g][i-1], groups[g][i])){\n                    final_edges[g].push_back({groups[g][i-1], groups[g][i]});\n                }\n            }\n        }\n    }\n    \n    // Output answer\n    cout << \"!\\n\";\n    cout.flush();\n    \n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g]; i++){\n            if(i > 0) cout << \" \";\n            cout << groups[g][i];\n        }\n        cout << \"\\n\";\n        \n        for(auto [a, b] : final_edges[g]){\n            cout << a << \" \" << b << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<pair<int, int>> targets;\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dchar[] = {'U', 'D', 'L', 'R'};\n\nbool valid(int x, int y) {\n    return 0 <= x && x < N && 0 <= y && y < N;\n}\n\npair<int, int> slideUntilBlock(int x, int y, int dir, const set<pair<int, int>>& blocks) {\n    int nx = x + dx[dir];\n    int ny = y + dy[dir];\n    while (valid(nx, ny) && !blocks.count({nx, ny})) {\n        x = nx;\n        y = ny;\n        nx = x + dx[dir];\n        ny = y + dy[dir];\n    }\n    return {x, y};\n}\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    targets.resize(M);\n    for (int i = 0; i < M; i++) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n    \n    vector<pair<char, char>> result;\n    int x = targets[0].first;\n    int y = targets[0].second;\n    set<pair<int, int>> blocks;\n    \n    // Navigate from target to target\n    for (int t = 1; t < M; t++) {\n        int tx = targets[t].first;\n        int ty = targets[t].second;\n        \n        // A* search considering Move and Slide actions\n        // State: (f_score, g_score, x, y)\n        map<pair<int, int>, int> g_score;  // distance from start\n        priority_queue<tuple<int, int, int, int>,\n                       vector<tuple<int, int, int, int>>,\n                       greater<tuple<int, int, int, int>>> pq;\n        \n        int h = manhattan(x, y, tx, ty);\n        pq.push({h, 0, x, y});\n        g_score[{x, y}] = 0;\n        \n        map<pair<int, int>, pair<pair<int, int>, pair<char, char>>> parent;\n        parent[{x, y}] = {{-1, -1}, {'X', 'X'}};\n        \n        while (!pq.empty()) {\n            auto [f, g, cx, cy] = pq.top();\n            pq.pop();\n            \n            if (cx == tx && cy == ty) break;\n            if (g_score.count({cx, cy}) && g_score[{cx, cy}] < g) continue;\n            \n            // Try all directions with Move and Slide actions\n            for (int dir = 0; dir < 4; dir++) {\n                // Move action: move one square\n                {\n                    int nx = cx + dx[dir];\n                    int ny = cy + dy[dir];\n                    if (valid(nx, ny) && !blocks.count({nx, ny})) {\n                        int new_g = g + 1;\n                        if (!g_score.count({nx, ny}) || g_score[{nx, ny}] > new_g) {\n                            g_score[{nx, ny}] = new_g;\n                            parent[{nx, ny}] = {{cx, cy}, {'M', dchar[dir]}};\n                            int new_h = manhattan(nx, ny, tx, ty);\n                            pq.push({new_g + new_h, new_g, nx, ny});\n                        }\n                    }\n                }\n                \n                // Slide action: slide until hitting a block\n                {\n                    int nx = cx + dx[dir];\n                    int ny = cy + dy[dir];\n                    if (valid(nx, ny) && !blocks.count({nx, ny})) {\n                        auto [sx, sy] = slideUntilBlock(cx, cy, dir, blocks);\n                        if (sx != cx || sy != cy) {  // Only if we actually slid\n                            int new_g = g + 1;\n                            if (!g_score.count({sx, sy}) || g_score[{sx, sy}] > new_g) {\n                                g_score[{sx, sy}] = new_g;\n                                parent[{sx, sy}] = {{cx, cy}, {'S', dchar[dir]}};\n                                int new_h = manhattan(sx, sy, tx, ty);\n                                pq.push({new_g + new_h, new_g, sx, sy});\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        // Reconstruct path\n        vector<pair<char, char>> path;\n        pair<int, int> p = {tx, ty};\n        while (parent[p].second.first != 'X') {\n            path.push_back(parent[p].second);\n            p = parent[p].first;\n        }\n        reverse(path.begin(), path.end());\n        \n        for (auto action : path) {\n            result.push_back(action);\n        }\n        \n        x = tx;\n        y = ty;\n    }\n    \n    for (auto [a, d] : result) {\n        cout << a << \" \" << d << \"\\n\";\n    }\n    \n    return 0;\n}"},"16":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int id;\n    long long x, y, r;\n};\n\nvector<array<long long, 4>> result(205);\n\nvoid assign(vector<int> indices, const vector<Company>& companies, \n            long long x1, long long y1, long long x2, long long y2) {\n    if (indices.empty()) return;\n    if (indices.size() == 1) {\n        result[indices[0]] = {x1, y1, x2, y2};\n        return;\n    }\n    \n    // Compute company distribution statistics\n    vector<long long> xs, ys;\n    long long total_desired = 0;\n    for (int idx : indices) {\n        xs.push_back(companies[idx].x);\n        ys.push_back(companies[idx].y);\n        total_desired += companies[idx].r;\n    }\n    sort(xs.begin(), xs.end());\n    sort(ys.begin(), ys.end());\n    \n    long long x_spread = xs.back() - xs.front();\n    long long y_spread = ys.back() - ys.front();\n    long long width = x2 - x1;\n    long long height = y2 - y1;\n    \n    bool prefer_vertical = (x_spread < y_spread) || (width > height);\n    \n    double best_score = -1e18;\n    int best_strategy = -1;\n    long long best_split = x1;\n    vector<int> best_left, best_right;\n    \n    auto score_split_quality = [&](const vector<int>& left, const vector<int>& right,\n                                    long long left_area, long long right_area) -> double {\n        if (left.empty() || right.empty()) return -1e18;\n        \n        long long left_desired = 0, right_desired = 0;\n        for (int idx : left) left_desired += companies[idx].r;\n        for (int idx : right) right_desired += companies[idx].r;\n        \n        if (left_desired == 0 || right_desired == 0) return -1e18;\n        \n        // Area balance metric\n        double left_ratio = (double)left_area / left_desired;\n        double right_ratio = (double)right_area / right_desired;\n        double area_score = -abs(log(left_ratio)) - abs(log(right_ratio));\n        \n        // Count balance metric\n        double count_ratio = (double)left.size() / max(1.0, (double)right.size());\n        double count_score = -abs(log(count_ratio));\n        \n        // Area-to-count ratio consistency\n        double left_density = (double)left_area / left.size();\n        double right_density = (double)right_area / right.size();\n        double density_ratio = left_density > 0 ? right_density / left_density : 1.0;\n        double density_score = -abs(log(density_ratio));\n        \n        // Combined score with weights\n        return area_score + 0.4 * count_score + 0.3 * density_score;\n    };\n    \n    auto try_vertical_splits = [&]() {\n        set<long long> x_thresholds;\n        for (int idx : indices) {\n            x_thresholds.insert(companies[idx].x);\n            x_thresholds.insert(companies[idx].x + 1);\n        }\n        \n        for (long long threshold : x_thresholds) {\n            vector<int> left, right;\n            for (int idx : indices) {\n                if (companies[idx].x < threshold) left.push_back(idx);\n                else right.push_back(idx);\n            }\n            \n            if (left.empty() || right.empty()) continue;\n            \n            long long max_left_x = -1;\n            for (int idx : left) max_left_x = max(max_left_x, companies[idx].x);\n            long long min_right_x = 10000;\n            for (int idx : right) min_right_x = min(min_right_x, companies[idx].x);\n            \n            long long split_min = max(x1 + 1, max_left_x + 1);\n            long long split_max = min(x2 - 1, min_right_x);\n            \n            if (split_min > split_max) continue;\n            \n            long long left_desired = 0, right_desired = 0;\n            for (int idx : left) left_desired += companies[idx].r;\n            for (int idx : right) right_desired += companies[idx].r;\n            \n            set<long long> candidates;\n            long long range = split_max - split_min;\n            \n            candidates.insert(split_min);\n            candidates.insert(split_max);\n            \n            // Ideal proportional position\n            if (left_desired + right_desired > 0) {\n                __int128 w = x2 - x1;\n                __int128 ideal_128 = x1 + w * left_desired / (left_desired + right_desired);\n                long long ideal = max(split_min, min(split_max, (long long)ideal_128));\n                candidates.insert(ideal);\n                \n                // Dense sampling around ideal\n                for (long long offset = -5; offset <= 5; offset++) {\n                    if (ideal + offset >= split_min && ideal + offset <= split_max) {\n                        candidates.insert(ideal + offset);\n                    }\n                }\n            }\n            \n            if (range > 1) {\n                candidates.insert((split_min + split_max) / 2);\n                long long g1 = split_min + range * 2 / 5;\n                long long g2 = split_min + range * 3 / 5;\n                candidates.insert(g1);\n                candidates.insert(g2);\n            }\n            \n            // Adaptive sampling: more dense for smaller ranges\n            int num_samples = range <= 20 ? range + 1 : min(100LL, 20 + range / 60);\n            for (int i = 1; i < num_samples; i++) {\n                long long pos = split_min + range * i / num_samples;\n                candidates.insert(pos);\n            }\n            \n            for (long long split_pos : candidates) {\n                if (split_pos < split_min || split_pos > split_max) continue;\n                \n                long long left_area = (split_pos - x1) * (y2 - y1);\n                long long right_area = (x2 - split_pos) * (y2 - y1);\n                \n                double score = score_split_quality(left, right, left_area, right_area);\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_strategy = 0;\n                    best_split = split_pos;\n                    best_left = left;\n                    best_right = right;\n                }\n            }\n        }\n    };\n    \n    auto try_horizontal_splits = [&]() {\n        set<long long> y_thresholds;\n        for (int idx : indices) {\n            y_thresholds.insert(companies[idx].y);\n            y_thresholds.insert(companies[idx].y + 1);\n        }\n        \n        for (long long threshold : y_thresholds) {\n            vector<int> bottom, top;\n            for (int idx : indices) {\n                if (companies[idx].y < threshold) bottom.push_back(idx);\n                else top.push_back(idx);\n            }\n            \n            if (bottom.empty() || top.empty()) continue;\n            \n            long long max_bottom_y = -1;\n            for (int idx : bottom) max_bottom_y = max(max_bottom_y, companies[idx].y);\n            long long min_top_y = 10000;\n            for (int idx : top) min_top_y = min(min_top_y, companies[idx].y);\n            \n            long long split_min = max(y1 + 1, max_bottom_y + 1);\n            long long split_max = min(y2 - 1, min_top_y);\n            \n            if (split_min > split_max) continue;\n            \n            long long bottom_desired = 0, top_desired = 0;\n            for (int idx : bottom) bottom_desired += companies[idx].r;\n            for (int idx : top) top_desired += companies[idx].r;\n            \n            set<long long> candidates;\n            long long range = split_max - split_min;\n            \n            candidates.insert(split_min);\n            candidates.insert(split_max);\n            \n            if (bottom_desired + top_desired > 0) {\n                __int128 h = y2 - y1;\n                __int128 ideal_128 = y1 + h * bottom_desired / (bottom_desired + top_desired);\n                long long ideal = max(split_min, min(split_max, (long long)ideal_128));\n                candidates.insert(ideal);\n                \n                for (long long offset = -5; offset <= 5; offset++) {\n                    if (ideal + offset >= split_min && ideal + offset <= split_max) {\n                        candidates.insert(ideal + offset);\n                    }\n                }\n            }\n            \n            if (range > 1) {\n                candidates.insert((split_min + split_max) / 2);\n                long long g1 = split_min + range * 2 / 5;\n                long long g2 = split_min + range * 3 / 5;\n                candidates.insert(g1);\n                candidates.insert(g2);\n            }\n            \n            int num_samples = range <= 20 ? range + 1 : min(100LL, 20 + range / 60);\n            for (int i = 1; i < num_samples; i++) {\n                long long pos = split_min + range * i / num_samples;\n                candidates.insert(pos);\n            }\n            \n            for (long long split_pos : candidates) {\n                if (split_pos < split_min || split_pos > split_max) continue;\n                \n                long long bottom_area = (x2 - x1) * (split_pos - y1);\n                long long top_area = (x2 - x1) * (y2 - split_pos);\n                \n                double score = score_split_quality(bottom, top, bottom_area, top_area);\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_strategy = 1;\n                    best_split = split_pos;\n                    best_left = bottom;\n                    best_right = top;\n                }\n            }\n        }\n    };\n    \n    // Try both directions\n    try_vertical_splits();\n    try_horizontal_splits();\n    \n    if (best_strategy == 0) {\n        assign(best_left, companies, x1, y1, best_split, y2);\n        assign(best_right, companies, best_split, y1, x2, y2);\n    } else if (best_strategy == 1) {\n        assign(best_left, companies, x1, y1, x2, best_split);\n        assign(best_right, companies, x1, best_split, x2, y2);\n    } else {\n        long long mid = (x1 + x2) / 2;\n        vector<int> left, right;\n        for (int idx : indices) {\n            if (companies[idx].x < mid) left.push_back(idx);\n            else right.push_back(idx);\n        }\n        if (!left.empty() && !right.empty()) {\n            assign(left, companies, x1, y1, mid, y2);\n            assign(right, companies, mid, y1, x2, y2);\n        } else {\n            mid = (y1 + y2) / 2;\n            for (int idx : indices) {\n                if (companies[idx].y < mid) left.push_back(idx);\n                else right.push_back(idx);\n            }\n            assign(left, companies, x1, y1, x2, mid);\n            assign(right, companies, x1, mid, x2, y2);\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    vector<Company> companies(n);\n    \n    for (int i = 0; i < n; i++) {\n        companies[i].id = i;\n        cin >> companies[i].x >> companies[i].y >> companies[i].r;\n    }\n    \n    vector<int> indices(n);\n    iota(indices.begin(), indices.end(), 0);\n    \n    assign(indices, companies, 0, 0, 10000, 10000);\n    \n    for (int i = 0; i < n; i++) {\n        cout << result[i][0] << \" \" << result[i][1] << \" \" \n             << result[i][2] << \" \" << result[i][3] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint si, sj;\nint tile[50][50];\nint value[50][50];\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dc[] = {'U', 'D', 'L', 'R'};\n\nint best_score = 0;\nstring best_path = \"\";\nchrono::high_resolution_clock::time_point start_time;\nconst double TIME_LIMIT = 1.95;\n\nbool time_exceeded() {\n    auto now = chrono::high_resolution_clock::now();\n    double elapsed = chrono::duration<double>(now - start_time).count();\n    return elapsed > TIME_LIMIT;\n}\n\nvoid walk(vector<bool>& visited_tiles, mt19937& rng, int& score, string& path, vector<int>& visited_list) {\n    score = value[si][sj];\n    int cur_i = si, cur_j = sj;\n    path.clear();\n    path.reserve(2500);\n    \n    while (true) {\n        int valid_dirs[4];\n        int valid_count = 0;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = cur_i + dx[d];\n            int nj = cur_j + dy[d];\n            \n            if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n                if (!visited_tiles[tile[ni][nj]]) {\n                    valid_dirs[valid_count++] = d;\n                }\n            }\n        }\n        \n        if (valid_count == 0) break;\n        \n        int d;\n        // Use 74% greedy (optimal parameter found through testing)\n        if (uniform_real_distribution<>(0, 1)(rng) < 0.74) {\n            // Greedy: pick highest value neighbor (deterministic tie-breaking)\n            d = valid_dirs[0];\n            int best_v = value[cur_i + dx[d]][cur_j + dy[d]];\n            \n            for (int i = 1; i < valid_count; i++) {\n                int dd = valid_dirs[i];\n                int ni = cur_i + dx[dd];\n                int nj = cur_j + dy[dd];\n                if (value[ni][nj] > best_v) {\n                    d = dd;\n                    best_v = value[ni][nj];\n                }\n            }\n        } else {\n            // Random exploration (26% of the time)\n            d = valid_dirs[uniform_int_distribution<>(0, valid_count - 1)(rng)];\n        }\n        \n        int ni = cur_i + dx[d];\n        int nj = cur_j + dy[d];\n        int new_tile = tile[ni][nj];\n        \n        visited_tiles[new_tile] = true;\n        visited_list.push_back(new_tile);\n        path.push_back(dc[d]);\n        score += value[ni][nj];\n        cur_i = ni;\n        cur_j = nj;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> si >> sj;\n    \n    int max_tile = 0;\n    for (int i = 0; i < 50; i++) {\n        for (int j = 0; j < 50; j++) {\n            cin >> tile[i][j];\n            max_tile = max(max_tile, tile[i][j]);\n        }\n    }\n    \n    for (int i = 0; i < 50; i++) {\n        for (int j = 0; j < 50; j++) {\n            cin >> value[i][j];\n        }\n    }\n    \n    start_time = chrono::high_resolution_clock::now();\n    best_score = value[si][sj];\n    best_path = \"\";\n    \n    mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n    \n    vector<bool> visited_tiles(max_tile + 1, false);\n    vector<int> visited_list;\n    visited_list.reserve(max_tile + 1);\n    string current_path;\n    int score;\n    \n    while (!time_exceeded()) {\n        for (int t : visited_list) {\n            visited_tiles[t] = false;\n        }\n        visited_list.clear();\n        \n        visited_tiles[tile[si][sj]] = true;\n        visited_list.push_back(tile[si][sj]);\n        \n        walk(visited_tiles, rng, score, current_path, visited_list);\n        \n        if (score > best_score) {\n            best_score = score;\n            best_path = current_path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\n#include <queue>\nusing namespace std;\n\nconst int N = 30;\nconst double INF = 1e18;\nconst double EDGE_MIN = 1000.0;\nconst double EDGE_MAX = 9500.0;\n\ndouble h[N][N-1], v[N-1][N];\nint h_count[N][N-1], v_count[N-1][N];\n\nstruct State {\n    double dist;\n    int i, j;\n    bool operator>(const State& other) const {\n        return dist > other.dist;\n    }\n};\n\npair<string, double> dijkstra(int si, int sj, int ti, int tj) {\n    vector<vector<double>> dist(N, vector<double>(N, INF));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1, -1}));\n    vector<vector<char>> dir(N, vector<char>(N));\n    \n    priority_queue<State, vector<State>, greater<State>> pq;\n    dist[si][sj] = 0;\n    pq.push({0, si, sj});\n    \n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top();\n        pq.pop();\n        \n        if (d > dist[i][j]) continue;\n        \n        if (i > 0) {\n            double new_dist = d + v[i-1][j];\n            if (new_dist < dist[i-1][j]) {\n                dist[i-1][j] = new_dist;\n                parent[i-1][j] = {i, j};\n                dir[i-1][j] = 'U';\n                pq.push({new_dist, i-1, j});\n            }\n        }\n        \n        if (i < N-1) {\n            double new_dist = d + v[i][j];\n            if (new_dist < dist[i+1][j]) {\n                dist[i+1][j] = new_dist;\n                parent[i+1][j] = {i, j};\n                dir[i+1][j] = 'D';\n                pq.push({new_dist, i+1, j});\n            }\n        }\n        \n        if (j > 0) {\n            double new_dist = d + h[i][j-1];\n            if (new_dist < dist[i][j-1]) {\n                dist[i][j-1] = new_dist;\n                parent[i][j-1] = {i, j};\n                dir[i][j-1] = 'L';\n                pq.push({new_dist, i, j-1});\n            }\n        }\n        \n        if (j < N-1) {\n            double new_dist = d + h[i][j];\n            if (new_dist < dist[i][j+1]) {\n                dist[i][j+1] = new_dist;\n                parent[i][j+1] = {i, j};\n                dir[i][j+1] = 'R';\n                pq.push({new_dist, i, j+1});\n            }\n        }\n    }\n    \n    string path;\n    int ci = ti, cj = tj;\n    while (parent[ci][cj].first != -1) {\n        path += dir[ci][cj];\n        auto [pi, pj] = parent[ci][cj];\n        ci = pi;\n        cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    \n    return {path, dist[ti][tj]};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N-1; j++) {\n            h[i][j] = 5000.0;\n            h_count[i][j] = 0;\n        }\n    }\n    for (int i = 0; i < N-1; i++) {\n        for (int j = 0; j < N; j++) {\n            v[i][j] = 5000.0;\n            v_count[i][j] = 0;\n        }\n    }\n    \n    for (int q = 0; q < 1000; q++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        auto [path, computed_length] = dijkstra(si, sj, ti, tj);\n        \n        cout << path << endl;\n        cout.flush();\n        \n        long long feedback;\n        cin >> feedback;\n        \n        // Slightly more aggressive early learning: 0.21 -> 0.05\n        double base_alpha = 0.21 - 0.16 * q / 1000.0;\n        base_alpha = max(0.05, base_alpha);\n        \n        if (!path.empty()) {\n            // Collect edges and compute sum of weights for linear weighting\n            vector<tuple<int, int, char, double>> edges;\n            double sum_weights = 0.0;\n            int ci = si, cj = sj;\n            \n            for (char c : path) {\n                double w = 0.0;\n                if (c == 'U') {\n                    w = v[ci-1][cj];\n                    edges.push_back({ci-1, cj, 'U', w});\n                    ci--;\n                } else if (c == 'D') {\n                    w = v[ci][cj];\n                    edges.push_back({ci, cj, 'D', w});\n                    ci++;\n                } else if (c == 'L') {\n                    w = h[ci][cj-1];\n                    edges.push_back({ci, cj-1, 'L', w});\n                    cj--;\n                } else if (c == 'R') {\n                    w = h[ci][cj];\n                    edges.push_back({ci, cj, 'R', w});\n                    cj++;\n                }\n                sum_weights += w;\n            }\n            \n            // Update edges with linear weighted feedback (proven best approach)\n            double total_feedback = (double)feedback;\n            for (auto [i, j, c, w] : edges) {\n                // Linear weighting: proportional feedback distribution\n                double weighted_feedback = total_feedback * (w / sum_weights);\n                \n                if (c == 'U') {\n                    // Optimal observation decay: exp(-0.035 * count)\n                    double adaptive_alpha = base_alpha * exp(-0.035 * v_count[i][j]);\n                    v[i][j] = (1 - adaptive_alpha) * v[i][j] + adaptive_alpha * weighted_feedback;\n                    v[i][j] = max(EDGE_MIN, min(EDGE_MAX, v[i][j]));\n                    v_count[i][j]++;\n                } else if (c == 'D') {\n                    double adaptive_alpha = base_alpha * exp(-0.035 * v_count[i][j]);\n                    v[i][j] = (1 - adaptive_alpha) * v[i][j] + adaptive_alpha * weighted_feedback;\n                    v[i][j] = max(EDGE_MIN, min(EDGE_MAX, v[i][j]));\n                    v_count[i][j]++;\n                } else if (c == 'L') {\n                    double adaptive_alpha = base_alpha * exp(-0.035 * h_count[i][j]);\n                    h[i][j] = (1 - adaptive_alpha) * h[i][j] + adaptive_alpha * weighted_feedback;\n                    h[i][j] = max(EDGE_MIN, min(EDGE_MAX, h[i][j]));\n                    h_count[i][j]++;\n                } else if (c == 'R') {\n                    double adaptive_alpha = base_alpha * exp(-0.035 * h_count[i][j]);\n                    h[i][j] = (1 - adaptive_alpha) * h[i][j] + adaptive_alpha * weighted_feedback;\n                    h[i][j] = max(EDGE_MIN, min(EDGE_MAX, h[i][j]));\n                    h_count[i][j]++;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc004":"#include<bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<string> strings;\nchar bestMatrix[20][20];\nint bestMatches = 0;\n\nbool isSubsequence(const string& s, char mat[20][20]) {\n    int len = (int)s.length();\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            bool found = true;\n            for(int p = 0; p < len; p++) {\n                if(mat[i][(j+p)%N] != s[p]) {\n                    found = false;\n                    break;\n                }\n            }\n            if(found) return true;\n        }\n    }\n    \n    for(int j = 0; j < N; j++) {\n        for(int i = 0; i < N; i++) {\n            bool found = true;\n            for(int p = 0; p < len; p++) {\n                if(mat[(i+p)%N][j] != s[p]) {\n                    found = false;\n                    break;\n                }\n            }\n            if(found) return true;\n        }\n    }\n    \n    return false;\n}\n\nint countMatches(char mat[20][20]) {\n    int c = 0;\n    for(const auto& s : strings) {\n        if(isSubsequence(s, mat)) c++;\n    }\n    return c;\n}\n\nvoid runSA(mt19937& rng, chrono::steady_clock::time_point deadline, double timeLimit, \n           double initTemp, double coolingRate, int warmstartPercent) {\n    char currentMatrix[20][20];\n    \n    uniform_int_distribution<int> charDist(0, 7);\n    uniform_int_distribution<int> posDist(0, N-1);\n    uniform_int_distribution<int> dirDist(0, 1);\n    uniform_real_distribution<double> realDist(0, 1);\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            currentMatrix[i][j] = 'A' + charDist(rng);\n        }\n    }\n    \n    int numPlace = (M * warmstartPercent) / 100;\n    vector<int> indices(M);\n    iota(indices.begin(), indices.end(), 0);\n    shuffle(indices.begin(), indices.end(), rng);\n    \n    for(int k = 0; k < numPlace; k++) {\n        const auto& s = strings[indices[k]];\n        int len = (int)s.length();\n        int i = posDist(rng);\n        int j = posDist(rng);\n        int dir = dirDist(rng);\n        \n        if(dir == 0) {\n            for(int p = 0; p < len; p++) {\n                currentMatrix[i][(j+p)%N] = s[p];\n            }\n        } else {\n            for(int p = 0; p < len; p++) {\n                currentMatrix[(i+p)%N][j] = s[p];\n            }\n        }\n    }\n    \n    int currentMatches = countMatches(currentMatrix);\n    if(currentMatches > bestMatches) {\n        bestMatches = currentMatches;\n        memcpy(bestMatrix, currentMatrix, sizeof(currentMatrix));\n    }\n    \n    double temp = initTemp;\n    auto runDeadline = chrono::steady_clock::now() + chrono::milliseconds((long long)(timeLimit * 1000));\n    \n    while(chrono::steady_clock::now() < runDeadline && chrono::steady_clock::now() < deadline && temp > 0.0001) {\n        int i = posDist(rng);\n        int j = posDist(rng);\n        \n        char old = currentMatrix[i][j];\n        char newChar = 'A' + charDist(rng);\n        \n        if(newChar == old) continue;\n        \n        currentMatrix[i][j] = newChar;\n        int newMatches = countMatches(currentMatrix);\n        int delta = newMatches - currentMatches;\n        \n        if(delta >= 0) {\n            currentMatches = newMatches;\n            if(currentMatches > bestMatches) {\n                bestMatches = currentMatches;\n                memcpy(bestMatrix, currentMatrix, sizeof(currentMatrix));\n            }\n        } else {\n            if(realDist(rng) < exp((double)delta / max(temp, 0.0001))) {\n                currentMatches = newMatches;\n            } else {\n                currentMatrix[i][j] = old;\n            }\n        }\n        \n        temp *= coolingRate;\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    strings.resize(M);\n    for(int i = 0; i < M; i++) {\n        cin >> strings[i];\n    }\n    \n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto deadline = chrono::steady_clock::now() + chrono::milliseconds(2850);\n    \n    // 12 runs with focused parameter ranges and better time allocation\n    // Focus on mid-range parameters that have proven effective\n    vector<double> initTemps = {\n        26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 38.0, 40.0,\n        29.0, 33.0, 37.0, 39.0\n    };\n    vector<double> coolingRates = {\n        0.999940, 0.999938, 0.999935, 0.999933, 0.999930, 0.999928, 0.999925, 0.999923,\n        0.999937, 0.999932, 0.999927, 0.999922\n    };\n    vector<int> warmstartPercents = {\n        50, 50, 50, 50, 50, 50, 50, 50,\n        45, 55, 50, 50\n    };\n    \n    double timePerRun = 0.238;  // 12 \u00d7 238ms \u2248 2856ms\n    \n    int runCount = 0;\n    while(chrono::steady_clock::now() < deadline && runCount < (int)initTemps.size()) {\n        runSA(rng, deadline, timePerRun, initTemps[runCount], coolingRates[runCount], warmstartPercents[runCount]);\n        runCount++;\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            cout << bestMatrix[i][j];\n        }\n        cout << '\\n';\n    }\n    \n    return 0;\n}","ahc005":"#include<bits/stdc++.h>\nusing namespace std;\n\nint N, si, sj;\nvector<string> grid;\nmap<pair<int,int>, set<pair<int,int>>> visCache;\nmap<pair<pair<int,int>, pair<int,int>>, int> distCache;\n\nset<pair<int,int>> getVis(int i, int j) {\n    auto key = make_pair(i, j);\n    if (visCache.count(key)) return visCache[key];\n    \n    set<pair<int,int>> res;\n    if (i < 0 || i >= N || j < 0 || j >= N || grid[i][j] == '#') return res;\n    \n    for (int jj = j; jj < N && grid[i][jj] != '#'; jj++) res.insert({i, jj});\n    for (int jj = j - 1; jj >= 0 && grid[i][jj] != '#'; jj--) res.insert({i, jj});\n    for (int ii = i; ii < N && grid[ii][j] != '#'; ii++) res.insert({ii, j});\n    for (int ii = i - 1; ii >= 0 && grid[ii][j] != '#'; ii--) res.insert({ii, j});\n    \n    return visCache[key] = res;\n}\n\nint getDist(pair<int,int> f, pair<int,int> t) {\n    if (f == t) return 0;\n    auto key = f < t ? make_pair(f, t) : make_pair(t, f);\n    if (distCache.count(key)) return distCache[key];\n    \n    map<pair<int,int>, int> d;\n    priority_queue<pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, greater<>> pq;\n    pq.push({0, f});\n    d[f] = 0;\n    \n    while (!pq.empty()) {\n        auto [c, p] = pq.top();\n        pq.pop();\n        if (p == t) return distCache[key] = c;\n        if (d.count(p) && d[p] < c) continue;\n        \n        auto [i, j] = p;\n        int di[] = {-1, 1, 0, 0}, dj[] = {0, 0, -1, 1};\n        for (int dd = 0; dd < 4; dd++) {\n            int ni = i + di[dd], nj = j + dj[dd];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && grid[ni][nj] != '#') {\n                int nc = c + (grid[ni][nj] - '0');\n                if (!d.count({ni, nj}) || d[{ni, nj}] > nc) {\n                    d[{ni, nj}] = nc;\n                    pq.push({nc, {ni, nj}});\n                }\n            }\n        }\n    }\n    return distCache[key] = 1e9;\n}\n\nvector<pair<int,int>> getPath(pair<int,int> f, pair<int,int> t) {\n    if (f == t) return {f};\n    \n    map<pair<int,int>, pair<int,int>> par;\n    map<pair<int,int>, int> d;\n    priority_queue<pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, greater<>> pq;\n    \n    pq.push({0, f});\n    d[f] = 0;\n    par[f] = {-1, -1};\n    \n    while (!pq.empty()) {\n        auto [c, p] = pq.top();\n        pq.pop();\n        if (p == t) break;\n        if (d.count(p) && d[p] < c) continue;\n        \n        auto [i, j] = p;\n        int di[] = {-1, 1, 0, 0}, dj[] = {0, 0, -1, 1};\n        for (int dd = 0; dd < 4; dd++) {\n            int ni = i + di[dd], nj = j + dj[dd];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && grid[ni][nj] != '#') {\n                int nc = c + (grid[ni][nj] - '0');\n                if (!d.count({ni, nj}) || d[{ni, nj}] > nc) {\n                    d[{ni, nj}] = nc;\n                    par[{ni, nj}] = {i, j};\n                    pq.push({nc, {ni, nj}});\n                }\n            }\n        }\n    }\n    \n    vector<pair<int,int>> path;\n    auto cur = t;\n    while (cur != make_pair(-1, -1)) {\n        path.push_back(cur);\n        cur = par[cur];\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> si >> sj;\n    grid.resize(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    \n    vector<pair<int,int>> roads;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            if (grid[i][j] != '#') roads.push_back({i, j});\n    \n    for (auto r : roads) getVis(r.first, r.second);\n    \n    set<pair<int,int>> seen;\n    vector<pair<int,int>> way;\n    \n    way.push_back({si, sj});\n    for (auto c : getVis(si, sj)) seen.insert(c);\n    \n    // Greedy set cover with stricter limit\n    while ((int)seen.size() < (int)roads.size() && way.size() < 150) {\n        pair<int,int> best = {-1, -1};\n        int bestCnt = -1;\n        \n        for (auto r : roads) {\n            int cnt = 0;\n            for (auto c : getVis(r.first, r.second)) {\n                if (!seen.count(c)) cnt++;\n            }\n            if (cnt > bestCnt) {\n                bestCnt = cnt;\n                best = r;\n            }\n        }\n        \n        if (bestCnt <= 0) break;\n        way.push_back(best);\n        for (auto c : getVis(best.first, best.second)) seen.insert(c);\n    }\n    \n    // Fallback\n    for (auto r : roads) {\n        if (!seen.count(r) && way.size() < 300) {\n            way.push_back(r);\n            for (auto c : getVis(r.first, r.second)) seen.insert(c);\n        }\n    }\n    \n    // Deduplicate: remove waypoints that don't add unique coverage\n    if (way.size() > 2) {\n        bool changed = true;\n        while (changed && way.size() > 10) {\n            changed = false;\n            for (size_t i = 1; i < way.size() - 1; i++) {\n                set<pair<int,int>> without;\n                for (size_t j = 0; j < way.size(); j++) {\n                    if (i != j) {\n                        for (auto c : getVis(way[j].first, way[j].second)) {\n                            without.insert(c);\n                        }\n                    }\n                }\n                if (without == seen) {\n                    way.erase(way.begin() + i);\n                    changed = true;\n                    break;\n                }\n            }\n        }\n    }\n    \n    // Nearest neighbor\n    if (way.size() > 2) {\n        vector<pair<int,int>> ordered;\n        vector<bool> used(way.size(), false);\n        ordered.push_back(way[0]);\n        used[0] = true;\n        \n        for (size_t i = 1; i < way.size(); i++) {\n            int best = -1, bestDist = 1e9;\n            for (size_t j = 0; j < way.size(); j++) {\n                if (!used[j]) {\n                    int d = getDist(ordered.back(), way[j]);\n                    if (d < bestDist) {\n                        bestDist = d;\n                        best = j;\n                    }\n                }\n            }\n            if (best != -1) {\n                ordered.push_back(way[best]);\n                used[best] = true;\n            }\n        }\n        way = ordered;\n    }\n    \n    // Safe 2-opt only on small tours\n    if (way.size() > 3 && way.size() <= 100) {\n        for (int iter = 0; iter < 50; iter++) {\n            bool improved = false;\n            for (size_t i = 0; i + 2 < way.size(); i++) {\n                for (size_t j = i + 2; j < way.size(); j++) {\n                    int d1 = getDist(way[i], way[i+1]) + getDist(way[j], way[j == way.size()-1 ? 0 : j+1]);\n                    int d2 = getDist(way[i], way[j]) + getDist(way[i+1], way[j == way.size()-1 ? 0 : j+1]);\n                    \n                    if (d2 < d1 && d2 > 0 && d1 > 0) {\n                        reverse(way.begin() + i + 1, way.begin() + j + 1);\n                        improved = true;\n                        break;\n                    }\n                }\n                if (improved) break;\n            }\n            if (!improved) break;\n        }\n    }\n    \n    way.push_back({si, sj});\n    \n    string res = \"\";\n    for (size_t i = 0; i + 1 < way.size(); i++) {\n        auto path = getPath(way[i], way[i + 1]);\n        for (size_t j = 1; j < path.size(); j++) {\n            int pi = path[j-1].first, pj = path[j-1].second;\n            int ni = path[j].first, nj = path[j].second;\n            if (ni < pi) res += 'U';\n            else if (ni > pi) res += 'D';\n            else if (nj < pj) res += 'L';\n            else res += 'R';\n        }\n    }\n    \n    cout << res << endl;\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n    \n    vector<vector<int>> d(N, vector<int>(K));\n    double sum_diff = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < K; j++) {\n            cin >> d[i][j];\n            sum_diff += d[i][j];\n        }\n    }\n    double avg_diff = sum_diff / (N * K);\n    \n    vector<set<int>> deps(N);\n    vector<vector<int>> rev_deps(N);\n    \n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        deps[v].insert(u);\n        rev_deps[u].push_back(v);\n    }\n    \n    // Compute criticality: longest path to leaf\n    vector<int> crit(N, -1);\n    function<int(int)> calc_crit = [&](int u) {\n        if (crit[u] != -1) return crit[u];\n        int maxc = 0;\n        for (int v : rev_deps[u]) {\n            maxc = max(maxc, 1 + calc_crit(v));\n        }\n        return crit[u] = maxc;\n    };\n    for (int i = 0; i < N; i++) calc_crit(i);\n    \n    vector<int> task_status(N, -1);\n    vector<int> task_start_day(N, -1);\n    vector<int> member_task(M, -1);\n    \n    // Optimal initial estimate\n    vector<vector<double>> skills(M, vector<double>(K, avg_diff * 0.60));\n    \n    vector<int> member_tasks_done(M, 0);\n    \n    auto estimate_time = [&](int m, int t) {\n        double deficit = 0;\n        for (int k = 0; k < K; k++) {\n            deficit += max(0.0, (double)d[t][k] - skills[m][k]);\n        }\n        return max(1.0, deficit);\n    };\n    \n    auto task_difficulty = [&](int t) {\n        double diff = 0;\n        for (int k = 0; k < K; k++) {\n            diff += d[t][k];\n        }\n        return diff;\n    };\n    \n    int day = 0, completed = 0;\n    \n    while (day < 2000 && completed < N) {\n        day++;\n        \n        vector<int> available;\n        for (int t = 0; t < N; t++) {\n            if (task_status[t] != -1) continue;\n            bool ok = true;\n            for (int dep : deps[t]) {\n                if (task_status[dep] < 2000) {\n                    ok = false;\n                    break;\n                }\n            }\n            if (ok) available.push_back(t);\n        }\n        \n        // Sort by criticality with immediate dependents as tiebreaker\n        sort(available.begin(), available.end(), [&](int a, int b) {\n            int crit_a = crit[a] * 10 + (int)rev_deps[a].size();\n            int crit_b = crit[b] * 10 + (int)rev_deps[b].size();\n            if (crit_a != crit_b) return crit_a > crit_b;\n            \n            double diff_a = task_difficulty(a);\n            double diff_b = task_difficulty(b);\n            return diff_a > diff_b;\n        });\n        \n        vector<pair<int, int>> assignments;\n        vector<bool> assigned(M, false);\n        \n        for (int t : available) {\n            int best_m = -1;\n            double best_time = 1e18;\n            \n            for (int m = 0; m < M; m++) {\n                if (member_task[m] != -1 || assigned[m]) continue;\n                \n                double time_est = estimate_time(m, t);\n                if (time_est < best_time) {\n                    best_time = time_est;\n                    best_m = m;\n                }\n            }\n            \n            if (best_m != -1) {\n                assignments.push_back({best_m + 1, t + 1});\n                member_task[best_m] = t;\n                task_status[t] = day;\n                task_start_day[t] = day;\n                assigned[best_m] = true;\n            }\n        }\n        \n        cout << assignments.size();\n        for (auto [m, t] : assignments) {\n            cout << \" \" << m << \" \" << t;\n        }\n        cout << \"\\n\";\n        cout.flush();\n        \n        int n;\n        cin >> n;\n        if (n == -1) break;\n        \n        for (int i = 0; i < n; i++) {\n            int m;\n            cin >> m;\n            m--;\n            \n            if (member_task[m] != -1) {\n                int t = member_task[m];\n                int dur = day - task_start_day[t] + 1;\n                \n                task_status[t] = 2000 + day;\n                member_task[m] = -1;\n                completed++;\n                member_tasks_done[m]++;\n                \n                if (dur == 1) {\n                    // Perfect execution: member has required skills\n                    for (int k = 0; k < K; k++) {\n                        skills[m][k] = max(skills[m][k], (double)d[t][k] * 0.98);\n                    }\n                } else {\n                    // Adaptive w_est: harder tasks need more conservative estimates\n                    double task_req = 0;\n                    for (int k = 0; k < K; k++) {\n                        task_req += d[t][k];\n                    }\n                    // Normalized difficulty: ratio to average\n                    double normalized_req = task_req / (avg_diff * K);\n                    \n                    // w_factor ranges from 0.25 (easy) to 0.75 (hard)\n                    // Easy: w_est = dur - 0.25, Hard: w_est = dur - 0.75\n                    double w_factor = 0.25 + 0.5 * min(1.0, normalized_req);\n                    double w_est = max(0.0, (double)dur - w_factor);\n                    \n                    double total_req = 0;\n                    for (int k = 0; k < K; k++) {\n                        total_req += d[t][k];\n                    }\n                    \n                    if (total_req > 1e-9) {\n                        double experience = (double)min(member_tasks_done[m], 20);\n                        double learning_mult = 1.0 - 0.01 * experience;\n                        \n                        for (int k = 0; k < K; k++) {\n                            double proportion = (double)d[t][k] / total_req;\n                            double inferred_skill = d[t][k] - proportion * w_est;\n                            skills[m][k] = max(skills[m][k], \n                                              max(0.0, inferred_skill * learning_mult));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nll manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    struct Order {\n        int a, b, c, d;\n    };\n    \n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; i++) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n    }\n    \n    auto buildRouteGreedy = [&](const vector<int>& orders_to_use, mt19937* rng = nullptr) {\n        vector<pair<int, int>> route;\n        route.push_back({400, 400});\n        \n        vector<bool> pickup_done(orders_to_use.size(), false);\n        vector<bool> delivery_done(orders_to_use.size(), false);\n        \n        int cx = 400, cy = 400;\n        \n        for (int step = 0; step < (int)orders_to_use.size() * 2; step++) {\n            int best_i = -1, best_type = -1;\n            ll best_dist = LLONG_MAX;\n            \n            for (int i = 0; i < (int)orders_to_use.size(); i++) {\n                if (!pickup_done[i]) {\n                    ll d = manhattan(cx, cy, orders[orders_to_use[i]].a, orders[orders_to_use[i]].b);\n                    if (d < best_dist || (rng && d == best_dist && uniform_int_distribution<int>(0, 1)(*rng))) {\n                        best_dist = d;\n                        best_i = i;\n                        best_type = 0;\n                    }\n                }\n                if (pickup_done[i] && !delivery_done[i]) {\n                    ll d = manhattan(cx, cy, orders[orders_to_use[i]].c, orders[orders_to_use[i]].d);\n                    if (d < best_dist || (rng && d == best_dist && uniform_int_distribution<int>(0, 1)(*rng))) {\n                        best_dist = d;\n                        best_i = i;\n                        best_type = 1;\n                    }\n                }\n            }\n            \n            if (best_i == -1) break;\n            \n            if (best_type == 0) {\n                cx = orders[orders_to_use[best_i]].a;\n                cy = orders[orders_to_use[best_i]].b;\n                pickup_done[best_i] = true;\n            } else {\n                cx = orders[orders_to_use[best_i]].c;\n                cy = orders[orders_to_use[best_i]].d;\n                delivery_done[best_i] = true;\n            }\n            \n            route.push_back({cx, cy});\n        }\n        \n        route.push_back({400, 400});\n        return route;\n    };\n    \n    auto calcDist = [](const vector<pair<int, int>>& route) {\n        ll total = 0;\n        for (size_t i = 0; i < route.size() - 1; i++) {\n            total += manhattan(route[i].first, route[i].second, \n                             route[i+1].first, route[i+1].second);\n        }\n        return total;\n    };\n    \n    auto check_valid = [&](const vector<pair<int, int>>& r, const vector<int>& orders_to_use) {\n        for (int i = 0; i < (int)orders_to_use.size(); i++) {\n            int pickup_idx = -1, delivery_idx = -1;\n            for (int j = 0; j < (int)r.size(); j++) {\n                if (r[j].first == orders[orders_to_use[i]].a && r[j].second == orders[orders_to_use[i]].b) {\n                    pickup_idx = j;\n                }\n                if (r[j].first == orders[orders_to_use[i]].c && r[j].second == orders[orders_to_use[i]].d) {\n                    delivery_idx = j;\n                }\n            }\n            if (pickup_idx == -1 || delivery_idx == -1 || pickup_idx > delivery_idx) {\n                return false;\n            }\n        }\n        return true;\n    };\n    \n    auto improveRoute2Opt = [&](vector<pair<int, int>> route, const vector<int>& orders_to_use) {\n        bool improved = true;\n        int iterations = 0;\n        int max_no_improve = 0;\n        \n        while (iterations < 200 && max_no_improve < 50) {\n            improved = false;\n            iterations++;\n            \n            for (int i = 1; i < (int)route.size() - 2; i++) {\n                for (int j = i + 2; j < (int)route.size() - 1; j++) {\n                    ll old_cost = manhattan(route[i-1].first, route[i-1].second, route[i].first, route[i].second) +\n                                  manhattan(route[j].first, route[j].second, route[j+1].first, route[j+1].second);\n                    ll new_cost = manhattan(route[i-1].first, route[i-1].second, route[j].first, route[j].second) +\n                                  manhattan(route[i].first, route[i].second, route[j+1].first, route[j+1].second);\n                    \n                    if (new_cost < old_cost) {\n                        auto new_route = route;\n                        reverse(new_route.begin() + i, new_route.begin() + j + 1);\n                        \n                        if (check_valid(new_route, orders_to_use)) {\n                            route = new_route;\n                            improved = true;\n                            max_no_improve = 0;\n                            break;\n                        }\n                    }\n                }\n                if (improved) break;\n            }\n            \n            if (!improved) max_no_improve++;\n        }\n        \n        return route;\n    };\n    \n    ll best_overall_dist = LLONG_MAX;\n    vector<int> best_selected;\n    vector<pair<int, int>> best_route;\n    \n    // Deterministic criteria\n    vector<vector<pair<ll, int>>> all_selections;\n    \n    for (int criterion = 0; criterion < 10; criterion++) {\n        vector<pair<ll, int>> costs;\n        \n        for (int i = 0; i < 1000; i++) {\n            ll cost = 0;\n            switch(criterion) {\n                case 0: // Distance to office\n                    cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                           manhattan(400, 400, orders[i].c, orders[i].d);\n                    break;\n                case 1: // Pickup-delivery distance\n                    cost = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n                    break;\n                case 2: // Balanced\n                    cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                           manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d) +\n                           manhattan(orders[i].c, orders[i].d, 400, 400);\n                    break;\n                case 3: // Distance from center\n                    cost = abs(orders[i].a - 400) + abs(orders[i].b - 400) +\n                           abs(orders[i].c - 400) + abs(orders[i].d - 400);\n                    break;\n                case 4: // Spread\n                {\n                    int minx = min(orders[i].a, orders[i].c);\n                    int maxx = max(orders[i].a, orders[i].c);\n                    int miny = min(orders[i].b, orders[i].d);\n                    int maxy = max(orders[i].b, orders[i].d);\n                    cost = (maxx - minx) + (maxy - miny);\n                    break;\n                }\n                case 5: // Midpoint distance\n                {\n                    int mx = (orders[i].a + orders[i].c) / 2;\n                    int my = (orders[i].b + orders[i].d) / 2;\n                    cost = manhattan(400, 400, mx, my);\n                    break;\n                }\n                case 6: // Max coordinate distance\n                    cost = max(abs(orders[i].a - 400), abs(orders[i].b - 400)) +\n                           max(abs(orders[i].c - 400), abs(orders[i].d - 400));\n                    break;\n                case 7: // Chebyshev-like\n                    cost = max(abs(orders[i].a - 400) + abs(orders[i].c - 400),\n                              abs(orders[i].b - 400) + abs(orders[i].d - 400));\n                    break;\n                case 8: // Average of office distances\n                    cost = (manhattan(400, 400, orders[i].a, orders[i].b) +\n                           manhattan(400, 400, orders[i].c, orders[i].d)) / 2;\n                    break;\n                case 9: // Weighted: prefer short deliveries near office\n                    cost = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d) +\n                           min(manhattan(400, 400, orders[i].a, orders[i].b),\n                               manhattan(400, 400, orders[i].c, orders[i].d)) / 2;\n                    break;\n            }\n            costs.push_back({cost, i});\n        }\n        sort(costs.begin(), costs.end());\n        all_selections.push_back(costs);\n    }\n    \n    // Try deterministic selections\n    for (const auto& costs : all_selections) {\n        vector<int> selected(50);\n        for (int i = 0; i < 50; i++) {\n            selected[i] = costs[i].second;\n        }\n        \n        auto route = buildRouteGreedy(selected);\n        route = improveRoute2Opt(route, selected);\n        ll dist = calcDist(route);\n        \n        if (dist < best_overall_dist) {\n            best_overall_dist = dist;\n            best_selected = selected;\n            best_route = route;\n        }\n    }\n    \n    // Try random weighted selections\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    for (int trial = 0; trial < 80; trial++) {\n        vector<pair<ll, int>> weighted_costs;\n        \n        // Choose a random weighting scheme\n        int scheme = uniform_int_distribution<int>(0, 3)(rng);\n        \n        for (int i = 0; i < 1000; i++) {\n            ll base_cost = 0;\n            \n            switch(scheme) {\n                case 0:\n                    base_cost = manhattan(400, 400, orders[i].a, orders[i].b) + \n                               manhattan(400, 400, orders[i].c, orders[i].d);\n                    break;\n                case 1:\n                    base_cost = manhattan(orders[i].a, orders[i].b, orders[i].c, orders[i].d);\n                    break;\n                case 2:\n                    base_cost = abs(orders[i].a - 400) + abs(orders[i].b - 400) +\n                               abs(orders[i].c - 400) + abs(orders[i].d - 400);\n                    break;\n                case 3:\n                {\n                    int mx = (orders[i].a + orders[i].c) / 2;\n                    int my = (orders[i].b + orders[i].d) / 2;\n                    base_cost = manhattan(400, 400, mx, my);\n                    break;\n                }\n            }\n            \n            ll random_offset = uniform_int_distribution<ll>(0, base_cost / 3)(rng);\n            weighted_costs.push_back({base_cost + random_offset, i});\n        }\n        \n        sort(weighted_costs.begin(), weighted_costs.end());\n        \n        vector<int> selected(50);\n        for (int i = 0; i < 50; i++) {\n            selected[i] = weighted_costs[i].second;\n        }\n        \n        auto route = buildRouteGreedy(selected, &rng);\n        route = improveRoute2Opt(route, selected);\n        ll dist = calcDist(route);\n        \n        if (dist < best_overall_dist) {\n            best_overall_dist = dist;\n            best_selected = selected;\n            best_route = route;\n        }\n    }\n    \n    // Output\n    cout << \"50\";\n    for (int i = 0; i < 50; i++) {\n        cout << \" \" << (best_selected[i] + 1);\n    }\n    cout << \"\\n\";\n    \n    cout << best_route.size();\n    for (const auto& p : best_route) {\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass UnionFind {\npublic:\n    vector<int> parent;\n    \n    UnionFind(int n) : parent(n) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    \n    int find(int x) {\n        if (parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    \n    bool unite(int x, int y) {\n        x = find(x);\n        y = find(y);\n        if (x == y) return false;\n        parent[y] = x;\n        return true;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N = 400, M = 1995;\n    vector<pair<int, int>> coords(N);\n    vector<pair<int, int>> edges(M);\n    vector<int> d(M);\n    \n    for (int i = 0; i < N; i++) {\n        cin >> coords[i].first >> coords[i].second;\n    }\n    \n    for (int i = 0; i < M; i++) {\n        cin >> edges[i].first >> edges[i].second;\n        int u = edges[i].first, v = edges[i].second;\n        long long dx = (long long)coords[u].first - coords[v].first;\n        long long dy = (long long)coords[u].second - coords[v].second;\n        d[i] = (int)round(sqrt((double)(dx*dx + dy*dy)));\n    }\n    \n    UnionFind uf(N);\n    int edges_needed = N - 1;\n    \n    for (int i = 0; i < M; i++) {\n        int length;\n        cin >> length;\n        \n        int u = edges[i].first, v = edges[i].second;\n        \n        bool accept = false;\n        \n        if (edges_needed > 0 && uf.find(u) != uf.find(v)) {\n            // Tree edge (connects different components)\n            int edges_remaining = M - i;\n            \n            if (edges_remaining <= edges_needed) {\n                // Critical: must accept to guarantee connectivity\n                accept = true;\n            } else {\n                // Exponent 1.4 curve: continues the improvement trend\n                // More selective than 1.3 while staying safely below failed 1.5\n                double progress = (double)i / M;\n                double threshold_mult = 2.0 + pow(progress, 1.4);\n                \n                if (length <= d[i] * threshold_mult) {\n                    accept = true;\n                }\n            }\n        }\n        \n        if (accept) {\n            uf.unite(u, v);\n            edges_needed--;\n        }\n        \n        cout << (accept ? 1 : 0) << '\\n';\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    \n    int N;\n    cin >> N;\n    vector<pair<int,int>> pets(N);\n    vector<int> pet_types(N);\n    for(int i = 0; i < N; i++){\n        int x, y, t;\n        cin >> x >> y >> t;\n        pets[i] = {x-1, y-1};\n        pet_types[i] = t;\n    }\n    \n    int M;\n    cin >> M;\n    vector<pair<int,int>> humans(M);\n    for(int i = 0; i < M; i++){\n        int x, y;\n        cin >> x >> y;\n        humans[i] = {x-1, y-1};\n    }\n    \n    for(int turn = 0; turn < 300; turn++){\n        string actions(M, '.');\n        \n        // Dynamic target based on game phase\n        int target_x, target_y;\n        if(turn < 80){\n            // Phase 1: Move toward top-left corner\n            target_x = 5;\n            target_y = 5;\n        } else if(turn < 200){\n            // Phase 2: Consolidate and expand slightly\n            target_x = 8;\n            target_y = 8;\n        } else {\n            // Phase 3: Hold position\n            target_x = 8;\n            target_y = 8;\n        }\n        \n        // Each human moves toward the target\n        for(int i = 0; i < M; i++){\n            int x = humans[i].first;\n            int y = humans[i].second;\n            \n            if(x > target_x) actions[i] = 'U';\n            else if(x < target_x) actions[i] = 'D';\n            else if(y > target_y) actions[i] = 'L';\n            else if(y < target_y) actions[i] = 'R';\n            else actions[i] = '.';\n        }\n        \n        cout << actions << endl;\n        cout.flush();\n        \n        // Read pet movements\n        for(int i = 0; i < N; i++){\n            string move;\n            cin >> move;\n            \n            // Apply movement to each pet\n            for(char c : move){\n                if(c == 'U' && pets[i].first > 0) pets[i].first--;\n                else if(c == 'D' && pets[i].first < 29) pets[i].first++;\n                else if(c == 'L' && pets[i].second > 0) pets[i].second--;\n                else if(c == 'R' && pets[i].second < 29) pets[i].second++;\n            }\n        }\n        \n        // Update human positions based on executed actions\n        for(int i = 0; i < M; i++){\n            if(actions[i] == 'U' && humans[i].first > 0) humans[i].first--;\n            else if(actions[i] == 'D' && humans[i].first < 29) humans[i].first++;\n            else if(actions[i] == 'L' && humans[i].second > 0) humans[i].second--;\n            else if(actions[i] == 'R' && humans[i].second < 29) humans[i].second++;\n        }\n    }\n    \n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\ndouble compute_exact(const string& path, double p, int si, int sj, int ti, int tj,\n                     const vector<string>& h, const vector<string>& v) {\n    int L = (int)path.length();\n    \n    map<pair<int,int>, double> dp;\n    dp[{si, sj}] = 1.0;\n    double score = 0.0;\n    \n    auto do_move = [&](int i, int j, char c) -> pair<int,int> {\n        if (c == 'U' && i > 0 && v[i-1][j] == '0') return {i-1, j};\n        if (c == 'D' && i < 19 && v[i][j] == '0') return {i+1, j};\n        if (c == 'L' && j > 0 && h[i][j-1] == '0') return {i, j-1};\n        if (c == 'R' && j < 19 && h[i][j] == '0') return {i, j+1};\n        return {i, j};\n    };\n    \n    for (int t = 0; t < L; t++) {\n        map<pair<int,int>, double> ndp;\n        for (auto& [pos, prob] : dp) {\n            if (prob < 1e-12) continue; // Prune negligible probabilities\n            \n            auto [ni, nj] = do_move(pos.first, pos.second, path[t]);\n            if (ni == ti && nj == tj) {\n                score += prob * (1.0 - p) * (401.0 - (t + 1));\n                ndp[pos] += prob * p;\n            } else {\n                ndp[{ni, nj}] += prob * (1.0 - p);\n                ndp[pos] += prob * p;\n            }\n        }\n        dp = std::move(ndp);\n    }\n    return score;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj, ti, tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n    \n    vector<string> h(20), v(19);\n    for (int i = 0; i < 20; i++) cin >> h[i];\n    for (int i = 0; i < 19; i++) cin >> v[i];\n    \n    auto valid = [&](int i, int j, char c, int& ni, int& nj) {\n        ni = i; nj = j;\n        if (c == 'U' && i > 0 && v[i-1][j] == '0') { ni--; return true; }\n        if (c == 'D' && i < 19 && v[i][j] == '0') { ni++; return true; }\n        if (c == 'L' && j > 0 && h[i][j-1] == '0') { nj--; return true; }\n        if (c == 'R' && j < 19 && h[i][j] == '0') { nj++; return true; }\n        return false;\n    };\n    \n    vector<vector<int>> dist(20, vector<int>(20, -1));\n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    dist[si][sj] = 0;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        for (char c : {'U', 'D', 'L', 'R'}) {\n            int ni, nj;\n            if (valid(i, j, c, ni, nj) && dist[ni][nj] == -1) {\n                dist[ni][nj] = dist[i][j] + 1;\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    int shortest = dist[ti][tj];\n    \n    set<string> paths;\n    \n    auto enumerate = [&](vector<char> dirs) {\n        function<void(int,int,string)> dfs = [&](int i, int j, const string& path) {\n            if ((int)paths.size() >= 1000) return;\n            if (i == ti && j == tj) {\n                paths.insert(path);\n                return;\n            }\n            if ((int)path.length() >= shortest) return;\n            int d = dist[i][j];\n            for (char c : dirs) {\n                int ni, nj;\n                if (valid(i, j, c, ni, nj) && dist[ni][nj] == d + 1) {\n                    dfs(ni, nj, path + c);\n                }\n            }\n        };\n        dfs(si, sj, \"\");\n    };\n    \n    // Enumerate with multiple random orderings\n    vector<char> base = {'U', 'D', 'L', 'R'};\n    enumerate(base);\n    for (int seed = 1; seed <= 12; seed++) {\n        vector<char> dirs = base;\n        mt19937 rng(seed);\n        shuffle(dirs.begin(), dirs.end(), rng);\n        enumerate(dirs);\n    }\n    \n    // Score all (path, r) combinations and rank them\n    vector<pair<double, string>> candidates;\n    \n    for (const string& cand : paths) {\n        int n = cand.length();\n        for (int r = 1; r * n <= 200; r++) {\n            string full;\n            full.reserve(r * n);\n            for (int k = 0; k < r; k++) full += cand;\n            \n            double appr = pow(1.0 - pow(p, (double)r), (double)n) * (401.0 - r*n);\n            candidates.push_back({appr, full});\n        }\n    }\n    \n    sort(candidates.rbegin(), candidates.rend());\n    \n    double best_score = 0;\n    string best_path;\n    \n    // Evaluate top candidates with exact DP\n    int eval_count = min(300, (int)candidates.size());\n    for (int i = 0; i < eval_count; i++) {\n        double exact = compute_exact(candidates[i].second, p, si, sj, ti, tj, h, v);\n        if (exact > best_score) {\n            best_score = exact;\n            best_path = candidates[i].second;\n        }\n    }\n    \n    cout << best_path << \"\\n\";\n    \n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\n\nint di[] = {0, -1, 0, 1};\nint dj[] = {-1, 0, 1, 0};\n\nint to[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1},\n};\n\nint grid[N][N];\nint rotations[N][N];\nbool visited[N][N][4];\n\ninline int getTileType(int i, int j) {\n    int base = grid[i][j];\n    int rot = rotations[i][j];\n    if (base < 4) return (base + rot) % 4;\n    if (base < 6) return 4 + (rot % 2);\n    return 6 + (rot % 2);\n}\n\nint computeLoopLength(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd;\n    int length = 0;\n    for (int iter = 0; iter < 5000; iter++) {\n        int cur = getTileType(i, j);\n        int d2 = to[cur][d];\n        if (d2 == -1) return 0;\n        i += di[d2];\n        j += dj[d2];\n        if (i < 0 || i >= N || j < 0 || j >= N) return 0;\n        d = (d2 + 2) % 4;\n        length++;\n        if (i == si && j == sj && d == sd) return length;\n    }\n    return 0;\n}\n\nlong long computeScore() {\n    memset(visited, false, sizeof(visited));\n    vector<int> loops;\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            for (int d = 0; d < 4; d++) {\n                if (!visited[i][j][d]) {\n                    int len = computeLoopLength(i, j, d);\n                    if (len > 0) {\n                        loops.push_back(len);\n                        int ii = i, jj = j, dd = d;\n                        for (int step = 0; step < len; step++) {\n                            visited[ii][jj][dd] = true;\n                            int cur = getTileType(ii, jj);\n                            int d2 = to[cur][dd];\n                            ii += di[d2];\n                            jj += dj[d2];\n                            dd = (d2 + 2) % 4;\n                        }\n                    } else {\n                        visited[i][j][d] = true;\n                    }\n                }\n            }\n        }\n    }\n    if (loops.size() < 2) return 0;\n    sort(loops.rbegin(), loops.rend());\n    return (long long)loops[0] * loops[1];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    string line;\n    for (int i = 0; i < N; i++) {\n        cin >> line;\n        for (int j = 0; j < N; j++) {\n            grid[i][j] = line[j] - '0';\n        }\n    }\n    \n    // Use random_device for non-deterministic seed\n    random_device rd;\n    mt19937 rng(rd());\n    auto start = chrono::steady_clock::now();\n    \n    long long bestScore = 0;\n    int best_rotations[N][N];\n    memset(best_rotations, 0, sizeof(best_rotations));\n    \n    // 3 independent restarts - optimal move count\n    // Middle ground: 150 + 120 + 100 = 370 total\n    // (between 345 which scored 1592 and 420 which scored 1500)\n    int moves_per_restart[] = {150, 120, 100};\n    // Proven temperatures from best run\n    double init_temps[] = {120.0, 100.0, 80.0};\n    \n    for (int restart = 0; restart < 3; restart++) {\n        long long elapsed = chrono::duration_cast<chrono::milliseconds>(\n                chrono::steady_clock::now() - start).count();\n        \n        if (elapsed > 1750) break;\n        \n        // Independent initializations - proven approach\n        if (restart == 0) {\n            // All zeros\n            memset(rotations, 0, sizeof(rotations));\n        } else if (restart == 1) {\n            // Sparse random\n            memset(rotations, 0, sizeof(rotations));\n            int count = 90;\n            for (int k = 0; k < count; k++) {\n                int i = rng() % N;\n                int j = rng() % N;\n                rotations[i][j] = rng() % 4;\n            }\n        } else {\n            // Full random\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    rotations[i][j] = rng() % 4;\n                }\n            }\n        }\n        \n        long long currentScore = computeScore();\n        if (currentScore > bestScore) {\n            bestScore = currentScore;\n            memcpy(best_rotations, rotations, sizeof(int) * N * N);\n        }\n        \n        double temperature = init_temps[restart];\n        \n        for (int move = 0; move < moves_per_restart[restart]; move++) {\n            long long elapsed_now = chrono::duration_cast<chrono::milliseconds>(\n                    chrono::steady_clock::now() - start).count();\n            if (elapsed_now > 1800) break;\n            \n            int i = rng() % N;\n            int j = rng() % N;\n            int oldRot = rotations[i][j];\n            int newRot = rng() % 4;\n            \n            if (newRot == oldRot) {\n                move--;\n                continue;\n            }\n            \n            rotations[i][j] = newRot;\n            long long newScore = computeScore();\n            \n            double delta = (double)(newScore - currentScore);\n            \n            if (delta >= 0) {\n                currentScore = newScore;\n                if (newScore > bestScore) {\n                    bestScore = newScore;\n                    memcpy(best_rotations, rotations, sizeof(int) * N * N);\n                }\n            } else {\n                // Simulated annealing acceptance - proven formula\n                double acceptance_threshold = exp(delta / (temperature + 1.0));\n                if ((double)rng() / rng.max() < acceptance_threshold) {\n                    currentScore = newScore;\n                } else {\n                    rotations[i][j] = oldRot;\n                }\n            }\n            \n            // Proven cooling rate\n            temperature *= 0.985;\n        }\n    }\n    \n    memcpy(rotations, best_rotations, sizeof(rotations));\n    \n    string output(N * N, '0');\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            output[i * N + j] = '0' + rotations[i][j];\n        }\n    }\n    cout << output << endl;\n    \n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nchrono::high_resolution_clock::time_point start_time;\n\nbool hasEdge(const vector<vector<int>>& board, int i1, int j1, int i2, int j2) {\n    if (i2 < 0 || i2 >= N || j2 < 0 || j2 >= N) return false;\n    if (board[i1][j1] == 0 || board[i2][j2] == 0) return false;\n    \n    int dy = i2 - i1, dx = j2 - j1;\n    if (dy == -1 && dx == 0) return (board[i1][j1] & 2) && (board[i2][j2] & 8);\n    if (dy == 1 && dx == 0) return (board[i1][j1] & 8) && (board[i2][j2] & 2);\n    if (dy == 0 && dx == -1) return (board[i1][j1] & 1) && (board[i2][j2] & 4);\n    if (dy == 0 && dx == 1) return (board[i1][j1] & 4) && (board[i2][j2] & 1);\n    return false;\n}\n\nint largestTree(const vector<vector<int>>& board) {\n    vector<vector<int>> comp(N, vector<int>(N, -1));\n    vector<int> vcount, ecount;\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (board[i][j] == 0 || comp[i][j] != -1) continue;\n            \n            int cid = vcount.size();\n            vcount.push_back(0);\n            ecount.push_back(0);\n            \n            queue<pair<int,int>> q;\n            q.push({i, j});\n            comp[i][j] = cid;\n            \n            while (!q.empty()) {\n                auto [ci, cj] = q.front();\n                q.pop();\n                vcount[cid]++;\n                \n                int di[] = {-1, 1, 0, 0};\n                int dj[] = {0, 0, -1, 1};\n                for (int d = 0; d < 4; d++) {\n                    int ni = ci + di[d];\n                    int nj = cj + dj[d];\n                    if (ni >= 0 && ni < N && nj >= 0 && nj < N && \n                        board[ni][nj] != 0 && comp[ni][nj] == -1 &&\n                        hasEdge(board, ci, cj, ni, nj)) {\n                        comp[ni][nj] = cid;\n                        q.push({ni, nj});\n                    }\n                }\n            }\n        }\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            if (j + 1 < N && hasEdge(board, i, j, i, j+1) && comp[i][j] == comp[i][j+1]) {\n                ecount[comp[i][j]]++;\n            }\n            if (i + 1 < N && hasEdge(board, i, j, i+1, j) && comp[i][j] == comp[i+1][j]) {\n                ecount[comp[i][j]]++;\n            }\n        }\n    }\n    \n    int ans = 0;\n    for (size_t c = 0; c < vcount.size(); c++) {\n        if (ecount[c] == vcount[c] - 1) {\n            ans = max(ans, vcount[c]);\n        }\n    }\n    return ans;\n}\n\ndouble getElapsedTime() {\n    auto now = chrono::high_resolution_clock::now();\n    return chrono::duration<double>(now - start_time).count();\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    start_time = chrono::high_resolution_clock::now();\n    srand(chrono::system_clock::now().time_since_epoch().count());\n    \n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    \n    int ei = 0, ej = 0;\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            int v = s[j] >= 'a' ? s[j] - 'a' + 10 : s[j] - '0';\n            board[i][j] = v;\n            if (v == 0) ei = i, ej = j;\n        }\n    }\n    \n    string result = \"\";\n    int best_tree = largestTree(board);\n    \n    int di[] = {-1, 1, 0, 0};\n    int dj[] = {0, 0, -1, 1};\n    char dirs[] = {'U', 'D', 'L', 'R'};\n    \n    int no_improve_count = 0;\n    int last_restart = 0;\n    double time_limit = 2.85;\n    \n    // Balanced thresholds: between v10 and v13\n    int threshold_no_improve = max(49, N * N - 9);\n    int threshold_min_steps = max(71, N * N * 2 - 31);\n    \n    while ((int)result.length() < T && best_tree < N * N - 1 && getElapsedTime() < time_limit) {\n        vector<pair<int, int>> moves;\n        \n        for (int d = 0; d < 4; d++) {\n            int ni = ei + di[d];\n            int nj = ej + dj[d];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                swap(board[ei][ej], board[ni][nj]);\n                int score = largestTree(board);\n                swap(board[ei][ej], board[ni][nj]);\n                moves.push_back({score, d});\n            }\n        }\n        \n        if (moves.empty()) break;\n        \n        sort(moves.rbegin(), moves.rend());\n        \n        // Proven v10 temperature schedule\n        double progress = (double)result.length() / T;\n        double temperature = 22.0 * pow(1.0 - progress, 1.5);\n        \n        int selected_dir = moves[0].second;\n        int current_score = largestTree(board);\n        \n        // Proven v10 move weighting\n        if (temperature > 0.01) {\n            double sum_weight = 0.0;\n            vector<double> weights;\n            \n            for (size_t i = 0; i < moves.size(); i++) {\n                int score = moves[i].first;\n                double delta = score - current_score;\n                double weight;\n                \n                if (delta > 0) {\n                    weight = (1.0 + delta * 0.1) * exp(delta / max(0.2, temperature));\n                } else {\n                    weight = exp(delta / max(0.2, temperature));\n                }\n                \n                weights.push_back(weight);\n                sum_weight += weight;\n            }\n            \n            double rand_val = (double)rand() / RAND_MAX * sum_weight;\n            for (size_t i = 0; i < moves.size(); i++) {\n                rand_val -= weights[i];\n                if (rand_val < 0) {\n                    selected_dir = moves[i].second;\n                    break;\n                }\n            }\n        }\n        \n        int ni = ei + di[selected_dir];\n        int nj = ej + dj[selected_dir];\n        swap(board[ei][ej], board[ni][nj]);\n        result += dirs[selected_dir];\n        ei = ni;\n        ej = nj;\n        \n        int new_tree = largestTree(board);\n        if (new_tree > best_tree) {\n            best_tree = new_tree;\n            no_improve_count = 0;\n            last_restart = result.length();\n        } else {\n            no_improve_count++;\n        }\n        \n        // Balanced restart: slightly more aggressive than v10\n        if (no_improve_count > threshold_no_improve && \n            (int)result.length() - last_restart > threshold_min_steps &&\n            (int)result.length() < T - 188 && \n            getElapsedTime() < time_limit - 0.32) {\n            \n            // Balanced walk length: between v10 and v13\n            int walk_len = min(57, (T - (int)result.length()) / 4);\n            for (int step = 0; step < walk_len; step++) {\n                vector<int> valid;\n                for (int d = 0; d < 4; d++) {\n                    if (ei + di[d] >= 0 && ei + di[d] < N && \n                        ej + dj[d] >= 0 && ej + dj[d] < N) {\n                        valid.push_back(d);\n                    }\n                }\n                if (valid.empty()) break;\n                \n                int d = valid[rand() % valid.size()];\n                swap(board[ei][ej], board[ei + di[d]][ej + dj[d]]);\n                ei += di[d];\n                ej += dj[d];\n                result += dirs[d];\n            }\n            \n            no_improve_count = 0;\n            last_restart = result.length();\n        }\n    }\n    \n    cout << result << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<pair<long long, long long>> berries;\n\nvector<tuple<long long, long long, long long, long long>> generatePartition(int sizeThreshold) {\n    vector<tuple<long long, long long, long long, long long>> cuts;\n    \n    function<void(vector<int>, int)> recursivePartition = [&](vector<int> indices, int depth) {\n        if (indices.size() <= (size_t)sizeThreshold || (int)cuts.size() >= 100 || depth >= 22) return;\n        \n        long long minX = LLONG_MAX, maxX = LLONG_MIN;\n        long long minY = LLONG_MAX, maxY = LLONG_MIN;\n        \n        for (int i : indices) {\n            minX = min(minX, berries[i].first);\n            maxX = max(maxX, berries[i].first);\n            minY = min(minY, berries[i].second);\n            maxY = max(maxY, berries[i].second);\n        }\n        \n        long long rangeX = maxX - minX;\n        long long rangeY = maxY - minY;\n        \n        if (rangeX <= 1 && rangeY <= 1) return;\n        \n        vector<int> left, right;\n        \n        if (rangeX >= rangeY) {\n            long long cutX = (minX + maxX) / 2;\n            if (rangeX > 0) {\n                cutX += (rangeX > 100 ? 2 : 1);\n            }\n            \n            cuts.push_back({cutX, -1000000000LL, cutX, 1000000000LL});\n            \n            for (int i : indices) {\n                if (berries[i].first < cutX) {\n                    left.push_back(i);\n                } else {\n                    right.push_back(i);\n                }\n            }\n        } else {\n            long long cutY = (minY + maxY) / 2;\n            if (rangeY > 0) {\n                cutY += (rangeY > 100 ? 2 : 1);\n            }\n            \n            cuts.push_back({-1000000000LL, cutY, 1000000000LL, cutY});\n            \n            for (int i : indices) {\n                if (berries[i].second < cutY) {\n                    left.push_back(i);\n                } else {\n                    right.push_back(i);\n                }\n            }\n        }\n        \n        if (!left.empty() && left.size() < indices.size()) {\n            recursivePartition(left, depth + 1);\n        }\n        if (!right.empty() && right.size() < indices.size()) {\n            recursivePartition(right, depth + 1);\n        }\n    };\n    \n    vector<int> allIndices;\n    for (int i = 0; i < (int)berries.size(); i++) {\n        allIndices.push_back(i);\n    }\n    \n    recursivePartition(allIndices, 0);\n    return cuts;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, K;\n    cin >> N >> K;\n    \n    vector<int> a(11);\n    for (int d = 1; d <= 10; d++) {\n        cin >> a[d];\n    }\n    \n    berries.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> berries[i].first >> berries[i].second;\n    }\n    \n    // Try thresholds going even less aggressive\n    vector<int> thresholds = {14, 15, 16, 17, 18};\n    \n    // Generate partitions for each threshold\n    vector<vector<tuple<long long, long long, long long, long long>>> allPartitions;\n    for (int t : thresholds) {\n        allPartitions.push_back(generatePartition(t));\n    }\n    \n    // Output all solutions - judge uses the last one (threshold=18)\n    for (int idx = 0; idx < (int)allPartitions.size(); idx++) {\n        const auto& cuts = allPartitions[idx];\n        cout << (int)cuts.size() << \"\\n\";\n        for (const auto& [px, py, qx, qy] : cuts) {\n            cout << px << \" \" << py << \" \" << qx << \" \" << qy << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nset<pair<int,int>> dots;\nvector<tuple<int,int,int,int>> drawn_edges;\n\nbool segments_overlap(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (y1 == y2 && y3 == y4 && y1 == y3) {\n        int a1 = min(x1, x2), a2 = max(x1, x2);\n        int b1 = min(x3, x4), b2 = max(x3, x4);\n        return max(a1, b1) < min(a2, b2);\n    }\n    if (x1 == x2 && x3 == x4 && x1 == x3) {\n        int a1 = min(y1, y2), a2 = max(y1, y2);\n        int b1 = min(y3, y4), b2 = max(y3, y4);\n        return max(a1, b1) < min(a2, b2);\n    }\n    return false;\n}\n\nbool edge_overlaps_with_drawn(int x1, int y1, int x2, int y2) {\n    for (auto [x3, y3, x4, y4] : drawn_edges) {\n        if (segments_overlap(x1, y1, x2, y2, x3, y3, x4, y4)) {\n            return true;\n        }\n    }\n    return false;\n}\n\nbool check_segment_clear(int x1, int y1, int x2, int y2) {\n    if (x1 == x2) {\n        int miny = min(y1, y2), maxy = max(y1, y2);\n        for (int y = miny + 1; y < maxy; y++) {\n            if (dots.count({x1, y})) return false;\n        }\n    } else if (y1 == y2) {\n        int minx = min(x1, x2), maxx = max(x1, x2);\n        for (int x = minx + 1; x < maxx; x++) {\n            if (dots.count({x, y1})) return false;\n        }\n    } else {\n        int dx = (x2 > x1) ? 1 : -1;\n        int dy = (y2 > y1) ? 1 : -1;\n        int x = x1 + dx, y = y1 + dy;\n        while (x != x2) {\n            if (dots.count({x, y})) return false;\n            x += dx; y += dy;\n        }\n    }\n    return true;\n}\n\ndouble weight(int x, int y) {\n    double c = (N - 1) / 2.0;\n    return (x - c) * (x - c) + (y - c) * (y - c) + 1;\n}\n\nbool try_rect(int p1x, int p1y, int p2x, int p2y, int p3x, int p3y, int p4x, int p4y) {\n    if (dots.count({p1x, p1y})) return false;\n    if (!dots.count({p2x, p2y}) || !dots.count({p3x, p3y}) || !dots.count({p4x, p4y})) return false;\n    \n    if (edge_overlaps_with_drawn(p1x, p1y, p2x, p2y) || \n        edge_overlaps_with_drawn(p2x, p2y, p3x, p3y) ||\n        edge_overlaps_with_drawn(p3x, p3y, p4x, p4y) || \n        edge_overlaps_with_drawn(p4x, p4y, p1x, p1y))\n        return false;\n    \n    return check_segment_clear(p1x, p1y, p2x, p2y) &&\n           check_segment_clear(p2x, p2y, p3x, p3y) &&\n           check_segment_clear(p3x, p3y, p4x, p4y) &&\n           check_segment_clear(p4x, p4y, p1x, p1y);\n}\n\n// Count nearby dots (O(1) operation bounded by constant radius)\nint count_nearby_dots(int px, int py, int radius) {\n    int count = 0;\n    for (int dx = -radius; dx <= radius; dx++) {\n        for (int dy = -radius; dy <= radius; dy++) {\n            if (dots.count({px + dx, py + dy})) count++;\n        }\n    }\n    return count;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    \n    for (int i = 0; i < M; i++) {\n        int x, y;\n        cin >> x >> y;\n        dots.insert({x, y});\n    }\n    \n    vector<tuple<int,int,int,int,int,int,int,int>> ops;\n    auto start_time = chrono::high_resolution_clock::now();\n    \n    while (true) {\n        auto now = chrono::high_resolution_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - start_time).count() > 4750) break;\n        \n        vector<pair<int,int>> dot_vec(dots.begin(), dots.end());\n        int sz = dot_vec.size();\n        \n        int best_p1x = -1, best_p1y = -1, best_p2x, best_p2y, best_p3x, best_p3y, best_p4x, best_p4y;\n        double best_w = -1;\n        int best_nearby = -1;\n        \n        for (int i = 0; i < sz; i++) {\n            for (int j = i + 1; j < sz; j++) {\n                int xa = dot_vec[i].first, ya = dot_vec[i].second;\n                int xb = dot_vec[j].first, yb = dot_vec[j].second;\n                \n                if (xa == xb || ya == yb) continue;\n                \n                int xc = xa, yc = yb;\n                int xd = xb, yd = ya;\n                \n                // Try placing new dot at (xd, yd)\n                if (!dots.count({xd, yd}) && dots.count({xc, yc})) {\n                    double w = weight(xd, yd);\n                    int nearby = count_nearby_dots(xd, yd, 2);  // O(25) constant\n                    \n                    bool is_better = (w > best_w) || \n                                    (w == best_w && nearby > best_nearby);\n                    \n                    if (is_better && try_rect(xd, yd, xa, ya, xc, yc, xb, yb)) {\n                        best_w = w;\n                        best_nearby = nearby;\n                        best_p1x = xd; best_p1y = yd;\n                        best_p2x = xa; best_p2y = ya;\n                        best_p3x = xc; best_p3y = yc;\n                        best_p4x = xb; best_p4y = yb;\n                    }\n                }\n                \n                // Try placing new dot at (xc, yc)\n                if (!dots.count({xc, yc}) && dots.count({xd, yd})) {\n                    double w = weight(xc, yc);\n                    int nearby = count_nearby_dots(xc, yc, 2);  // O(25) constant\n                    \n                    bool is_better = (w > best_w) || \n                                    (w == best_w && nearby > best_nearby);\n                    \n                    if (is_better && try_rect(xc, yc, xa, ya, xd, yd, xb, yb)) {\n                        best_w = w;\n                        best_nearby = nearby;\n                        best_p1x = xc; best_p1y = yc;\n                        best_p2x = xa; best_p2y = ya;\n                        best_p3x = xd; best_p3y = yd;\n                        best_p4x = xb; best_p4y = yb;\n                    }\n                }\n            }\n        }\n        \n        if (best_w < 0) break;\n        \n        dots.insert({best_p1x, best_p1y});\n        drawn_edges.push_back({best_p1x, best_p1y, best_p2x, best_p2y});\n        drawn_edges.push_back({best_p2x, best_p2y, best_p3x, best_p3y});\n        drawn_edges.push_back({best_p3x, best_p3y, best_p4x, best_p4y});\n        drawn_edges.push_back({best_p4x, best_p4y, best_p1x, best_p1y});\n        ops.push_back({best_p1x, best_p1y, best_p2x, best_p2y, best_p3x, best_p3y, best_p4x, best_p4y});\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto [p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y] : ops) {\n        cout << p1x << \" \" << p1y << \" \" << p2x << \" \" << p2y << \" \"\n             << p3x << \" \" << p3y << \" \" << p4x << \" \" << p4y << \"\\n\";\n    }\n    \n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nint grid[10][10];\nvector<int> flavors;\n\nvoid place_candy(int pos, int flavor) {\n    int count = 0;\n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (grid[i][j] == 0) {\n                count++;\n                if (count == pos) {\n                    grid[i][j] = flavor;\n                    return;\n                }\n            }\n        }\n    }\n}\n\nvoid tilt(char dir, int target[10][10]) {\n    int temp[10][10];\n    memcpy(temp, grid, sizeof(grid));\n    memset(target, 0, sizeof(int) * 100);\n    \n    if (dir == 'F') {\n        for (int j = 0; j < 10; j++) {\n            vector<int> candies;\n            for (int i = 0; i < 10; i++) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t i = 0; i < candies.size(); i++) {\n                target[i][j] = candies[i];\n            }\n        }\n    } else if (dir == 'B') {\n        for (int j = 0; j < 10; j++) {\n            vector<int> candies;\n            for (int i = 9; i >= 0; i--) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t i = 0; i < candies.size(); i++) {\n                target[9 - i][j] = candies[i];\n            }\n        }\n    } else if (dir == 'L') {\n        for (int i = 0; i < 10; i++) {\n            vector<int> candies;\n            for (int j = 0; j < 10; j++) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t j = 0; j < candies.size(); j++) {\n                target[i][j] = candies[j];\n            }\n        }\n    } else if (dir == 'R') {\n        for (int i = 0; i < 10; i++) {\n            vector<int> candies;\n            for (int j = 9; j >= 0; j--) {\n                if (temp[i][j] != 0) candies.push_back(temp[i][j]);\n            }\n            for (size_t j = 0; j < candies.size(); j++) {\n                target[i][9 - j] = candies[j];\n            }\n        }\n    }\n}\n\nstruct Score {\n    long long sum_sq;\n    long long weighted_adjacency;\n    long long adjacency;\n    int max_comp_balance;\n    int num_singles;\n    int num_components;\n    \n    bool is_better_than(const Score& other) const {\n        if (sum_sq != other.sum_sq) return sum_sq > other.sum_sq;\n        if (weighted_adjacency != other.weighted_adjacency) return weighted_adjacency > other.weighted_adjacency;\n        if (max_comp_balance != other.max_comp_balance) return max_comp_balance > other.max_comp_balance;\n        if (adjacency != other.adjacency) return adjacency > other.adjacency;\n        if (num_singles != other.num_singles) return num_singles < other.num_singles;\n        return num_components < other.num_components;\n    }\n};\n\nScore compute_score(int test_grid[10][10], int current_t, const vector<int>& flavors) {\n    bool visited[10][10] = {};\n    long long sum_sq = 0;\n    long long adjacency = 0;\n    long long weighted_adjacency = 0;\n    int num_singles = 0;\n    int num_components = 0;\n    int max_per_flavor[4] = {0, 0, 0, 0};\n    int comps_per_flavor[4] = {0, 0, 0, 0};\n    int candies_per_flavor[4] = {0, 0, 0, 0};\n    \n    // Count remaining candies and current candies of each flavor\n    vector<int> remaining(4, 0);\n    for (int i = current_t + 1; i < 100; i++) {\n        remaining[flavors[i]]++;\n    }\n    \n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (test_grid[i][j] > 0) {\n                candies_per_flavor[test_grid[i][j]]++;\n            }\n        }\n    }\n    \n    // Find connected components using BFS\n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (test_grid[i][j] > 0 && !visited[i][j]) {\n                int flavor = test_grid[i][j];\n                int component_size = 0;\n                \n                queue<pair<int, int>> q;\n                q.push({i, j});\n                visited[i][j] = true;\n                \n                while (!q.empty()) {\n                    auto [r, c] = q.front();\n                    q.pop();\n                    component_size++;\n                    \n                    int dr[] = {-1, 1, 0, 0};\n                    int dc[] = {0, 0, -1, 1};\n                    \n                    for (int d = 0; d < 4; d++) {\n                        int nr = r + dr[d];\n                        int nc = c + dc[d];\n                        if (nr >= 0 && nr < 10 && nc >= 0 && nc < 10 && \n                            test_grid[nr][nc] == flavor && !visited[nr][nc]) {\n                            visited[nr][nc] = true;\n                            q.push({nr, nc});\n                        }\n                    }\n                }\n                \n                sum_sq += (long long)component_size * component_size;\n                max_per_flavor[flavor] = max(max_per_flavor[flavor], component_size);\n                comps_per_flavor[flavor]++;\n                num_components++;\n                if (component_size == 1) num_singles++;\n            }\n        }\n    }\n    \n    // Calculate balance metric\n    int max_comp_balance = max_per_flavor[1] * max_per_flavor[1] + \n                            max_per_flavor[2] * max_per_flavor[2] + \n                            max_per_flavor[3] * max_per_flavor[3];\n    \n    // Calculate adjacency metrics with intelligent weighting\n    for (int i = 0; i < 10; i++) {\n        for (int j = 0; j < 10; j++) {\n            if (test_grid[i][j] > 0) {\n                int flavor = test_grid[i][j];\n                \n                // Weight by: remaining count + fragmentation factor\n                // Fragmentation factor: more components = higher weight (soft penalty)\n                int remaining_weight = remaining[flavor] + 1;\n                int comps = max(1, comps_per_flavor[flavor]);\n                \n                // Soft fragmentation factor: sqrt scales between 1-4 for comps 1-16\n                double fragmentation_factor = 1.0 + 0.3 * sqrt((double)comps);\n                long long total_weight = (long long)(remaining_weight * fragmentation_factor);\n                \n                if (i + 1 < 10 && test_grid[i+1][j] == flavor) {\n                    adjacency++;\n                    weighted_adjacency += total_weight;\n                }\n                if (j + 1 < 10 && test_grid[i][j+1] == flavor) {\n                    adjacency++;\n                    weighted_adjacency += total_weight;\n                }\n            }\n        }\n    }\n    \n    return {sum_sq, weighted_adjacency, adjacency, max_comp_balance, num_singles, num_components};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    memset(grid, 0, sizeof(grid));\n    flavors.resize(100);\n    \n    for (int i = 0; i < 100; i++) {\n        cin >> flavors[i];\n    }\n    \n    for (int t = 0; t < 100; t++) {\n        int pos;\n        cin >> pos;\n        place_candy(pos, flavors[t]);\n        \n        if (t < 99) {\n            char dirs[] = {'F', 'B', 'L', 'R'};\n            Score best = {-1, -1, -1, 0, INT_MAX, INT_MAX};\n            char best_dir = 'F';\n            \n            for (int d = 0; d < 4; d++) {\n                int temp[10][10];\n                tilt(dirs[d], temp);\n                Score score = compute_score(temp, t, flavors);\n                \n                if (best.sum_sq == -1 || score.is_better_than(best)) {\n                    best = score;\n                    best_dir = dirs[d];\n                }\n            }\n            \n            cout << best_dir << \"\\n\";\n            cout.flush();\n            \n            int temp[10][10];\n            tilt(best_dir, temp);\n            memcpy(grid, temp, sizeof(grid));\n        }\n    }\n    \n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int M;\n    double eps;\n    cin >> M >> eps;\n    \n    // Adaptive N based on M for optimal scoring\n    int N;\n    if (M <= 20) N = 10;\n    else if (M <= 50) N = 15;\n    else N = 20;\n    \n    int max_edges = N * (N - 1) / 2;\n    \n    cout << N << endl;\n    cout.flush();\n    \n    // Precompute target features\n    vector<int> target_edges(M);\n    vector<pair<int, int>> target_degrees(M); // (max_degree, median_degree)\n    \n    for (int k = 0; k < M; k++) {\n        target_edges[k] = k * max_edges / M;\n        \n        // Compute degree stats for target graph\n        vector<int> degrees(N, 0);\n        int idx = 0;\n        int edge_count = 0;\n        for (int i = 0; i < N && edge_count < target_edges[k]; i++) {\n            for (int j = i + 1; j < N && edge_count < target_edges[k]; j++) {\n                degrees[i]++;\n                degrees[j]++;\n                edge_count++;\n            }\n        }\n        sort(degrees.rbegin(), degrees.rend());\n        target_degrees[k] = {degrees[0], degrees[N/2]};\n    }\n    \n    // Generate graphs\n    for (int k = 0; k < M; k++) {\n        string graph(max_edges, '0');\n        for (int i = 0; i < target_edges[k]; i++) {\n            graph[i] = '1';\n        }\n        cout << graph << endl;\n        cout.flush();\n    }\n    \n    // Process 100 queries\n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n        \n        // Extract features from H\n        int m = count(H.begin(), H.end(), '1');\n        \n        // Debiased edge count\n        double adjusted_m = m;\n        if (eps > 0.001 && fabs(1.0 - 2.0 * eps) > 0.01) {\n            adjusted_m = (m - max_edges * eps) / (1.0 - 2.0 * eps);\n            adjusted_m = max(0.0, min((double)max_edges, adjusted_m));\n        }\n        \n        // Degree statistics\n        vector<vector<int>> adj(N, vector<int>(N, 0));\n        int idx = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = i + 1; j < N; j++) {\n                if (H[idx] == '1') {\n                    adj[i][j] = adj[j][i] = 1;\n                }\n                idx++;\n            }\n        }\n        \n        vector<int> degrees(N, 0);\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                degrees[i] += adj[i][j];\n            }\n        }\n        sort(degrees.rbegin(), degrees.rend());\n        int h_max_deg = degrees[0];\n        int h_med_deg = degrees[N/2];\n        \n        // Find best match using weighted distance\n        int best = 0;\n        double best_score = 1e18;\n        \n        for (int k = 0; k < M; k++) {\n            double edge_diff = adjusted_m - target_edges[k];\n            double max_deg_diff = h_max_deg - target_degrees[k].first;\n            double med_deg_diff = h_med_deg - target_degrees[k].second;\n            \n            // Weighted sum of squared differences\n            // Edge count gets highest weight since it's most robust\n            double score = 3.0 * edge_diff * edge_diff +\n                          1.0 * max_deg_diff * max_deg_diff +\n                          0.5 * med_deg_diff * med_deg_diff;\n            \n            if (score < best_score) {\n                best_score = score;\n                best = k;\n            }\n        }\n        \n        cout << best << endl;\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, D, K;\nvector<long long> edge_weights;\nvector<pair<int, int>> edge_endpoints;\nvector<int> degree;\n\nlong long evaluate(const vector<int>& assignment, int eval_type) {\n    vector<long long> day_load(D + 1, 0);\n    for(int i = 0; i < M; i++){\n        day_load[assignment[i]] += edge_weights[i];\n    }\n    \n    if(eval_type == 0) {\n        // Max load\n        long long max_load = 0;\n        for(int d = 1; d <= D; d++){\n            max_load = max(max_load, day_load[d]);\n        }\n        return max_load;\n    } else {\n        // Variance\n        long long sum = 0;\n        for(int d = 1; d <= D; d++) sum += day_load[d];\n        long long mean = sum / D;\n        \n        long long variance = 0;\n        for(int d = 1; d <= D; d++){\n            long long diff = day_load[d] - mean;\n            variance += diff * diff;\n        }\n        return variance;\n    }\n}\n\nvector<int> greedy_assign(int metric_type, bool min_load_strategy) {\n    vector<pair<long long, int>> edge_list;\n    \n    for(int i = 0; i < M; i++){\n        auto [u, v] = edge_endpoints[i];\n        long long w = edge_weights[i];\n        long long importance;\n        \n        if(metric_type == 0){\n            importance = w * (long long)(degree[u] + degree[v]);\n        } else if(metric_type == 1){\n            importance = w * (long long)degree[u] * degree[v];\n        } else if(metric_type == 2){\n            importance = w;\n        } else if(metric_type == 3){\n            long long deg_sum = degree[u] + degree[v];\n            importance = w * deg_sum * deg_sum;\n        } else if(metric_type == 4){\n            long long deg_prod = (long long)degree[u] * degree[v];\n            importance = w * (long long)sqrt(deg_prod) * 1000;\n        } else {\n            // metric 5: smaller degree endpoints get priority (inverse)\n            long long deg_product = (long long)(degree[u] + 1) * (degree[v] + 1);\n            importance = (w * 1000000) / deg_product;\n        }\n        \n        edge_list.push_back({importance, i});\n    }\n    \n    sort(edge_list.rbegin(), edge_list.rend());\n    \n    vector<int> assignment(M);\n    priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq_min;\n    priority_queue<pair<long long, int>> pq_max;\n    \n    for(int d = 1; d <= D; d++){\n        pq_min.push({0, d});\n        pq_max.push({0, d});\n    }\n    \n    if(min_load_strategy) {\n        for(auto [imp, idx] : edge_list){\n            auto [load, day] = pq_min.top();\n            pq_min.pop();\n            assignment[idx] = day;\n            pq_min.push({load + edge_weights[idx], day});\n        }\n    } else {\n        // Assign to max-load (spread critical edges)\n        for(auto [imp, idx] : edge_list){\n            auto [load, day] = pq_max.top();\n            pq_max.pop();\n            assignment[idx] = day;\n            pq_max.push({load + edge_weights[idx], day});\n        }\n    }\n    \n    return assignment;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> D >> K;\n    \n    edge_weights.resize(M);\n    edge_endpoints.resize(M);\n    degree.assign(N, 0);\n    \n    for(int i = 0; i < M; i++){\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edge_weights[i] = w;\n        edge_endpoints[i] = {u, v};\n        degree[u]++;\n        degree[v]++;\n    }\n    \n    for(int i = 0; i < N; i++){\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    vector<int> best_assignment;\n    long long best_eval = LLONG_MAX;\n    \n    // Try many combinations of metrics and strategies\n    for(int metric = 0; metric < 6; metric++){\n        for(int strategy = 0; strategy < 2; strategy++){\n            auto candidate = greedy_assign(metric, strategy == 0);\n            \n            // Evaluate with both metrics and pick based on either\n            long long eval_max = evaluate(candidate, 0);\n            long long eval_var = evaluate(candidate, 1);\n            \n            // Use max_load as primary metric\n            if(eval_max < best_eval){\n                best_eval = eval_max;\n                best_assignment = candidate;\n            }\n        }\n    }\n    \n    for(int i = 0; i < M; i++){\n        cout << best_assignment[i];\n        if(i + 1 < M) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef array<int, 3> Pos;\n\nint D;\n\nstruct Block {\n    set<Pos> voxels;\n    Block() {}\n    Block(const set<Pos>& v) : voxels(v) {}\n    \n    void normalize() {\n        if (voxels.empty()) return;\n        int minx = INT_MAX, miny = INT_MAX, minz = INT_MAX;\n        for (auto [x, y, z] : voxels) {\n            minx = min(minx, x);\n            miny = min(miny, y);\n            minz = min(minz, z);\n        }\n        set<Pos> normalized;\n        for (auto [x, y, z] : voxels) {\n            normalized.insert({x - minx, y - miny, z - minz});\n        }\n        voxels = normalized;\n    }\n    \n    Block rotate(int axis) const {\n        set<Pos> rotated;\n        for (auto [x, y, z] : voxels) {\n            if (axis == 0) rotated.insert({x, -z, y});\n            else if (axis == 1) rotated.insert({z, y, -x});\n            else rotated.insert({-y, x, z});\n        }\n        return Block(rotated);\n    }\n    \n    bool operator<(const Block& other) const { return voxels < other.voxels; }\n    bool operator==(const Block& other) const { return voxels == other.voxels; }\n};\n\nBlock getCanonicalForm(Block b) {\n    b.normalize();\n    set<Block> forms;\n    queue<Block> q;\n    q.push(b);\n    forms.insert(b);\n    \n    int count = 0;\n    while (!q.empty() && count < 30) {\n        Block curr = q.front();\n        q.pop();\n        count++;\n        for (int a = 0; a < 3; a++) {\n            Block rot = curr.rotate(a);\n            rot.normalize();\n            if (forms.find(rot) == forms.end()) {\n                forms.insert(rot);\n                q.push(rot);\n            }\n        }\n    }\n    return *forms.begin();\n}\n\nstruct Component {\n    set<Pos> voxels;\n    Block canonical;\n    int volume;\n};\n\nvector<Component> extractComponents(const vector<vector<vector<int>>>& grid) {\n    vector<Component> components;\n    vector<vector<vector<bool>>> visited(D, vector<vector<bool>>(D, vector<bool>(D, false)));\n    \n    for (int x = 0; x < D; x++) {\n        for (int y = 0; y < D; y++) {\n            for (int z = 0; z < D; z++) {\n                if (grid[x][y][z] == 1 && !visited[x][y][z]) {\n                    set<Pos> voxels;\n                    queue<Pos> q;\n                    q.push({x, y, z});\n                    visited[x][y][z] = true;\n                    \n                    while (!q.empty()) {\n                        auto [cx, cy, cz] = q.front();\n                        q.pop();\n                        voxels.insert({cx, cy, cz});\n                        \n                        int dx[] = {1, -1, 0, 0, 0, 0};\n                        int dy[] = {0, 0, 1, -1, 0, 0};\n                        int dz[] = {0, 0, 0, 0, 1, -1};\n                        \n                        for (int i = 0; i < 6; i++) {\n                            int nx = cx + dx[i], ny = cy + dy[i], nz = cz + dz[i];\n                            if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D &&\n                                grid[nx][ny][nz] == 1 && !visited[nx][ny][nz]) {\n                                visited[nx][ny][nz] = true;\n                                q.push({nx, ny, nz});\n                            }\n                        }\n                    }\n                    \n                    Block block(voxels);\n                    block.normalize();\n                    components.push_back({voxels, getCanonicalForm(block), (int)voxels.size()});\n                }\n            }\n        }\n    }\n    return components;\n}\n\nlong long computeCost(const vector<Component>& comp1, const vector<Component>& comp2,\n                      const map<int, int>& matching) {\n    long long unused1 = 0, unused2 = 0;\n    set<int> used1, used2;\n    \n    for (auto [i, j] : matching) {\n        used1.insert(i);\n        used2.insert(j);\n    }\n    \n    for (size_t i = 0; i < comp1.size(); i++) {\n        if (used1.find(i) == used1.end()) unused1 += comp1[i].volume;\n    }\n    \n    for (size_t j = 0; j < comp2.size(); j++) {\n        if (used2.find(j) == used2.end()) unused2 += comp2[j].volume;\n    }\n    \n    long double shared = 0;\n    for (auto [i, j] : matching) {\n        shared += 1.0L / comp1[i].volume;\n    }\n    \n    return (long long)round(1e9 * (unused1 + unused2 + shared));\n}\n\nmap<int, int> optimalMatching(const vector<Component>& comp1, const vector<Component>& comp2) {\n    map<int, int> result;\n    vector<tuple<long long, int, int>> edges;\n    \n    for (size_t i = 0; i < comp1.size(); i++) {\n        for (size_t j = 0; j < comp2.size(); j++) {\n            if (comp1[i].canonical == comp2[j].canonical) {\n                edges.push_back({(long long)comp1[i].volume * comp2[j].volume, (int)i, (int)j});\n            }\n        }\n    }\n    \n    sort(edges.rbegin(), edges.rend());\n    \n    set<int> used1, used2;\n    for (auto [w, i, j] : edges) {\n        if (used1.find(i) == used1.end() && used2.find(j) == used2.end()) {\n            result[i] = j;\n            used1.insert(i);\n            used2.insert(j);\n        }\n    }\n    return result;\n}\n\n// Bipartite matching for minimum covering of single z-layer\nvector<pair<int,int>> minimalCoveringLayer(const vector<string>& f, const vector<string>& r, int z) {\n    vector<int> f_ones, r_ones;\n    for (int x = 0; x < D; x++) if (f[z][x] == '1') f_ones.push_back(x);\n    for (int y = 0; y < D; y++) if (r[z][y] == '1') r_ones.push_back(y);\n    \n    // Build bipartite graph and find max matching\n    int n = f_ones.size();\n    int m = r_ones.size();\n    vector<vector<int>> adj(n);\n    \n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < m; j++) {\n            adj[i].push_back(j);\n        }\n    }\n    \n    // Simple greedy matching\n    vector<int> match_r(m, -1);\n    vector<int> match_f(n, -1);\n    \n    for (int i = 0; i < n; i++) {\n        for (int j : adj[i]) {\n            if (match_r[j] == -1) {\n                match_f[i] = j;\n                match_r[j] = i;\n                break;\n            }\n        }\n    }\n    \n    // Cover unmatched f nodes and their neighbors\n    vector<pair<int,int>> covering;\n    set<int> covered_f, covered_r;\n    \n    for (int i = 0; i < n; i++) {\n        if (match_f[i] != -1) {\n            covering.push_back({f_ones[i], r_ones[match_f[i]]});\n            covered_f.insert(i);\n            covered_r.insert(match_f[i]);\n        }\n    }\n    \n    // Cover any remaining f and r\n    for (int i = 0; i < n; i++) {\n        if (covered_f.find(i) == covered_f.end()) {\n            for (int j : adj[i]) {\n                covering.push_back({f_ones[i], r_ones[j]});\n                covered_f.insert(i);\n                covered_r.insert(j);\n                break;\n            }\n        }\n    }\n    \n    for (int j = 0; j < m; j++) {\n        if (covered_r.find(j) == covered_r.end()) {\n            for (int i = 0; i < n; i++) {\n                covering.push_back({f_ones[i], r_ones[j]});\n                covered_r.insert(j);\n                break;\n            }\n        }\n    }\n    \n    return covering;\n}\n\ntuple<long long, int, vector<vector<vector<int>>>, vector<vector<vector<int>>>> \nsolve(const vector<string>& f1_in, const vector<string>& r1_in,\n      const vector<string>& f2_in, const vector<string>& r2_in, bool useMinimal) {\n    \n    vector<vector<vector<int>>> grid1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> grid2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    \n    for (int z = 0; z < D; z++) {\n        if (useMinimal) {\n            auto cov1 = minimalCoveringLayer(f1_in, r1_in, z);\n            for (auto [x, y] : cov1) grid1[x][y][z] = 1;\n            \n            auto cov2 = minimalCoveringLayer(f2_in, r2_in, z);\n            for (auto [x, y] : cov2) grid2[x][y][z] = 1;\n        } else {\n            for (int x = 0; x < D; x++) {\n                for (int y = 0; y < D; y++) {\n                    if (f1_in[z][x] == '1' && r1_in[z][y] == '1') grid1[x][y][z] = 1;\n                    if (f2_in[z][x] == '1' && r2_in[z][y] == '1') grid2[x][y][z] = 1;\n                }\n            }\n        }\n    }\n    \n    auto comp1 = extractComponents(grid1);\n    auto comp2 = extractComponents(grid2);\n    auto matching = optimalMatching(comp1, comp2);\n    \n    int nextID = 1;\n    map<int, int> comp1ID, comp2ID;\n    set<int> used2;\n    \n    for (auto [i, j] : matching) {\n        comp1ID[i] = nextID;\n        comp2ID[j] = nextID;\n        used2.insert(j);\n        nextID++;\n    }\n    \n    for (size_t i = 0; i < comp1.size(); i++) {\n        if (comp1ID.find(i) == comp1ID.end()) comp1ID[i] = nextID++;\n    }\n    \n    for (size_t j = 0; j < comp2.size(); j++) {\n        if (used2.find(j) == used2.end()) comp2ID[j] = nextID++;\n    }\n    \n    vector<vector<vector<int>>> result1(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    vector<vector<vector<int>>> result2(D, vector<vector<int>>(D, vector<int>(D, 0)));\n    \n    for (size_t i = 0; i < comp1.size(); i++) {\n        for (auto [x, y, z] : comp1[i].voxels) result1[x][y][z] = comp1ID[i];\n    }\n    \n    for (size_t j = 0; j < comp2.size(); j++) {\n        for (auto [x, y, z] : comp2[j].voxels) result2[x][y][z] = comp2ID[j];\n    }\n    \n    long long cost = computeCost(comp1, comp2, matching);\n    return {cost, nextID - 1, result1, result2};\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D;\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    \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    auto [cost0, n0, r1_0, r2_0] = solve(f1, r1, f2, r2, false);\n    auto [cost1, n1, r1_1, r2_1] = solve(f1, r1, f2, r2, true);\n    \n    long long bestCost = cost0;\n    int bestN = n0;\n    vector<vector<vector<int>>> bestR1 = r1_0, bestR2 = r2_0;\n    \n    if (cost1 < bestCost) {\n        bestCost = cost1;\n        bestN = n1;\n        bestR1 = r1_1;\n        bestR2 = r2_1;\n    }\n    \n    cout << bestN << \"\\n\";\n    for (int x = 0; x < D; x++)\n        for (int y = 0; y < D; y++)\n            for (int z = 0; z < D; z++) {\n                if (x || y || z) cout << \" \";\n                cout << bestR1[x][y][z];\n            }\n    cout << \"\\n\";\n    for (int x = 0; x < D; x++)\n        for (int y = 0; y < D; y++)\n            for (int z = 0; z < D; z++) {\n                if (x || y || z) cout << \" \";\n                cout << bestR2[x][y][z];\n            }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc020":"#include<bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\nstruct Point {\n    ld x, y;\n};\n\nld dist(Point a, Point b) {\n    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));\n}\n\nint N, M, K;\nvector<Point> stations;\nvector<pair<int,int>> edges;\nvector<ll> weights;\nvector<Point> residents;\nvector<vector<pair<int,ll>>> adj;\n\nvector<bool> getReachable(const vector<bool>& enabled) {\n    vector<bool> reachable(N, false);\n    reachable[0] = true;\n    queue<int> q;\n    q.push(0);\n    while(!q.empty()){\n        int u = q.front();\n        q.pop();\n        for(auto [v, eid] : adj[u]){\n            if(enabled[eid] && !reachable[v]){\n                reachable[v] = true;\n                q.push(v);\n            }\n        }\n    }\n    return reachable;\n}\n\nint getCoverage(const vector<bool>& enabled) {\n    auto reachable = getReachable(enabled);\n    int covered = 0;\n    for(int k = 0; k < K; k++){\n        for(int i = 0; i < N; i++){\n            if(reachable[i]){\n                ld d = dist(residents[k], stations[i]);\n                if(d <= 5000){  // FLOATING POINT comparison\n                    covered++;\n                    break;\n                }\n            }\n        }\n    }\n    return covered;\n}\n\npair<int, ll> evaluateSolution(const vector<bool>& enabled, vector<ll>& P) {\n    auto reachable = getReachable(enabled);\n    fill(P.begin(), P.end(), 0);\n    \n    int covered = 0;\n    for(int k = 0; k < K; k++){\n        ld minDist = 1e18;\n        int bestV = -1;\n        for(int i = 0; i < N; i++){\n            if(reachable[i]){\n                ld d = dist(residents[k], stations[i]);\n                if(d <= 5000 && d < minDist){\n                    minDist = d;\n                    bestV = i;\n                }\n            }\n        }\n        if(bestV != -1){\n            P[bestV] = max(P[bestV], (ll)ceil(minDist));  // CEIL to ensure coverage\n            covered++;\n        }\n    }\n    \n    ll cost = 0;\n    for(int i = 0; i < N; i++) cost += P[i] * P[i];\n    for(int e = 0; e < M; e++) if(enabled[e]) cost += weights[e];\n    \n    return {covered, cost};\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    \n    stations.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> stations[i].x >> stations[i].y;\n    }\n    \n    edges.resize(M);\n    weights.resize(M);\n    adj.resize(N);\n    \n    for(int i = 0; i < M; i++){\n        int u, v;\n        ll w;\n        cin >> u >> v >> w;\n        u--; v--;\n        edges[i] = {u, v};\n        weights[i] = w;\n        adj[u].push_back({v, i});\n        adj[v].push_back({u, i});\n    }\n    \n    residents.resize(K);\n    for(int i = 0; i < K; i++){\n        cin >> residents[i].x >> residents[i].y;\n    }\n    \n    vector<ll> P(N);\n    vector<bool> bestEnabled(M, false);\n    int bestCovered = 0;\n    ll bestCost = LLONG_MAX;\n    \n    vector<bool> enabled(M, false);\n    \n    for(int iter = 0; iter < 3000; iter++) {\n        int cov = getCoverage(enabled);\n        \n        if(cov > bestCovered){\n            auto [c, cost] = evaluateSolution(enabled, P);\n            bestCovered = c;\n            bestCost = cost;\n            bestEnabled = enabled;\n        }\n        \n        if(cov == K) break;\n        \n        auto reachable = getReachable(enabled);\n        \n        vector<int> uncovered;\n        for(int k = 0; k < K; k++){\n            bool isCovered = false;\n            for(int i = 0; i < N; i++){\n                if(reachable[i]){\n                    ld d = dist(residents[k], stations[i]);\n                    if(d <= 5000){\n                        isCovered = true;\n                        break;\n                    }\n                }\n            }\n            if(!isCovered) uncovered.push_back(k);\n        }\n        \n        if(uncovered.empty()) break;\n        \n        int bestEdge = -1;\n        double bestScore = -1e18;\n        \n        for(int e = 0; e < M; e++){\n            if(enabled[e]) continue;\n            int u = edges[e].first;\n            int v = edges[e].second;\n            if(!reachable[u] && !reachable[v]) continue;\n            \n            int newV = reachable[u] ? v : u;\n            int newCovered = 0;\n            for(int k : uncovered){\n                ld d = dist(residents[k], stations[newV]);\n                if(d <= 5000) newCovered++;\n            }\n            \n            if(newCovered > 0){\n                double score = (double)newCovered - (double)weights[e] / 1e8;\n                if(score > bestScore){\n                    bestScore = score;\n                    bestEdge = e;\n                }\n            }\n        }\n        \n        if(bestEdge == -1) {\n            ll minWeight = LLONG_MAX;\n            for(int e = 0; e < M; e++){\n                if(enabled[e]) continue;\n                int u = edges[e].first;\n                int v = edges[e].second;\n                if((reachable[u] && !reachable[v]) || (!reachable[u] && reachable[v])){\n                    if(weights[e] < minWeight){\n                        minWeight = weights[e];\n                        bestEdge = e;\n                    }\n                }\n            }\n        }\n        \n        if(bestEdge == -1) break;\n        enabled[bestEdge] = true;\n    }\n    \n    enabled = bestEnabled;\n    for(int attempt = 0; attempt < 150; attempt++) {\n        auto reachable = getReachable(enabled);\n        int cnt = 0;\n        for(int i = 0; i < N; i++) if(reachable[i]) cnt++;\n        if(cnt == N) break;\n        \n        ll minW = LLONG_MAX;\n        int bestE = -1;\n        for(int e = 0; e < M; e++){\n            if(enabled[e]) continue;\n            int u = edges[e].first;\n            int v = edges[e].second;\n            if((reachable[u] && !reachable[v]) || (!reachable[u] && reachable[v])){\n                if(weights[e] < minW){\n                    minW = weights[e];\n                    bestE = e;\n                }\n            }\n        }\n        if(bestE == -1) break;\n        enabled[bestE] = true;\n    }\n    \n    auto [cov2, cost2] = evaluateSolution(enabled, P);\n    if(cov2 > bestCovered){\n        bestCovered = cov2;\n        bestCost = cost2;\n        bestEnabled = enabled;\n    }\n    \n    if(bestCovered == K) {\n        enabled = bestEnabled;\n        for(int pass = 0; pass < 3; pass++){\n            for(int e = 0; e < M; e++){\n                if(!enabled[e]) continue;\n                enabled[e] = false;\n                if(getCoverage(enabled) < K){\n                    enabled[e] = true;\n                }\n            }\n        }\n        evaluateSolution(enabled, P);\n        bestEnabled = enabled;\n    }\n    \n    evaluateSolution(bestEnabled, P);\n    \n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << P[i];\n    }\n    cout << \"\\n\";\n    \n    for(int i = 0; i < M; i++){\n        if(i > 0) cout << \" \";\n        cout << (bestEnabled[i] ? 1 : 0);\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 30;\n    vector<vector<int>> pyramid(N);\n    \n    // Read input\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    vector<tuple<int,int,int,int>> operations;\n    \n    // Build min-heap structure using heapify algorithm\n    // Process from second-to-last level upwards (bottom-up)\n    for (int x = N - 2; x >= 0; x--) {\n        for (int y = 0; y <= x; y++) {\n            // Sift down from position (x, y)\n            int curr_x = x, curr_y = y;\n            while (curr_x + 1 < N && (int)operations.size() < 10000) {\n                int parent_val = pyramid[curr_x][curr_y];\n                int left_child_val = pyramid[curr_x + 1][curr_y];\n                int right_child_val = pyramid[curr_x + 1][curr_y + 1];\n                \n                // If parent is smaller than both children, heap property satisfied\n                if (parent_val <= left_child_val && parent_val <= right_child_val) {\n                    break;\n                }\n                \n                // Swap with the smaller child\n                if (left_child_val <= right_child_val) {\n                    swap(pyramid[curr_x][curr_y], pyramid[curr_x + 1][curr_y]);\n                    operations.push_back({curr_x, curr_y, curr_x + 1, curr_y});\n                    curr_x++;\n                } else {\n                    swap(pyramid[curr_x][curr_y], pyramid[curr_x + 1][curr_y + 1]);\n                    operations.push_back({curr_x, curr_y, curr_x + 1, curr_y + 1});\n                    curr_x++;\n                    curr_y++;\n                }\n            }\n        }\n    }\n    \n    // Output result\n    cout << (int)operations.size() << \"\\n\";\n    for (auto [x1, y1, x2, y2] : operations) {\n        cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \"\\n\";\n    }\n    \n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nint D, N;\nset<pair<int,int>> obstacles;\npair<int,int> entrance;\nmap<pair<int,int>, int> container_at;\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\n\nvector<pair<int,int>> get_reachable_empty() {\n    vector<pair<int,int>> result;\n    queue<pair<int,int>> q;\n    set<pair<int,int>> visited;\n    \n    q.push(entrance);\n    visited.insert(entrance);\n    \n    while(!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n        \n        for(int d = 0; d < 4; d++) {\n            int nr = r + dr[d];\n            int nc = c + dc[d];\n            \n            if(nr >= 0 && nr < D && nc >= 0 && nc < D &&\n               !visited.count({nr, nc}) &&\n               !obstacles.count({nr, nc}) &&\n               !container_at.count({nr, nc})) {\n                \n                visited.insert({nr, nc});\n                if(!(nr == 0 && nc == (D-1)/2)) {  // Not entrance\n                    result.push_back({nr, nc});\n                }\n                q.push({nr, nc});\n            }\n        }\n    }\n    \n    return result;\n}\n\nset<pair<int,int>> get_reachable_containers() {\n    set<pair<int,int>> result;\n    queue<pair<int,int>> q;\n    set<pair<int,int>> visited;\n    \n    q.push(entrance);\n    visited.insert(entrance);\n    \n    while(!q.empty()) {\n        auto [r, c] = q.front();\n        q.pop();\n        \n        for(int d = 0; d < 4; d++) {\n            int nr = r + dr[d];\n            int nc = c + dc[d];\n            \n            if(nr >= 0 && nr < D && nc >= 0 && nc < D &&\n               !visited.count({nr, nc}) &&\n               !obstacles.count({nr, nc})) {\n                \n                visited.insert({nr, nc});\n                \n                if(container_at.count({nr, nc})) {\n                    result.insert({nr, nc});\n                } else {\n                    q.push({nr, nc});\n                }\n            }\n        }\n    }\n    \n    return result;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D >> N;\n    \n    for(int i = 0; i < N; i++){\n        int r, c;\n        cin >> r >> c;\n        obstacles.insert({r, c});\n    }\n    \n    entrance = {0, (D-1)/2};\n    \n    // Place containers at furthest reachable squares\n    for(int i = 0; i < D*D - 1 - N; i++){\n        int t;\n        cin >> t;\n        \n        auto empty_squares = get_reachable_empty();\n        \n        if(empty_squares.empty()) {\n            // Shouldn't happen, but fallback\n            cout << \"0 0\\n\";\n            cout.flush();\n            continue;\n        }\n        \n        auto chosen = empty_squares.back();  // Furthest reachable\n        container_at[chosen] = t;\n        cout << chosen.first << \" \" << chosen.second << \"\\n\";\n        cout.flush();\n    }\n    \n    // Retrieve containers by greedy extraction\n    for(int i = 0; i < D*D - 1 - N; i++){\n        auto reachable = get_reachable_containers();\n        \n        pair<int,int> best_pos;\n        int best_num = INT_MAX;\n        \n        for(auto& pos : reachable) {\n            int num = container_at[pos];\n            if(num < best_num) {\n                best_num = num;\n                best_pos = pos;\n            }\n        }\n        \n        cout << best_pos.first << \" \" << best_pos.second << \"\\n\";\n        container_at.erase(best_pos);\n    }\n    \n    cout.flush();\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, m;\nint original[50][50];\nint current[50][50];\n\nvector<pair<int,int>> dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};\n\nbool isValid(int i, int j) {\n    return i >= 0 && i < N && j >= 0 && j < N;\n}\n\nbool isConnected(int color) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int,int>> q;\n    int count = 0;\n    pair<int,int> start = {-1, -1};\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(current[i][j] == color) {\n                count++;\n                if(start.first == -1) start = {i, j};\n            }\n        }\n    }\n    \n    if(count == 0) return true;\n    \n    q.push(start);\n    visited[start.first][start.second] = true;\n    int visited_count = 1;\n    \n    while(!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for(auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if(isValid(ni, nj) && !visited[ni][nj] && current[ni][nj] == color) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                visited_count++;\n            }\n        }\n    }\n    \n    return visited_count == count;\n}\n\nbool isConnected0() {\n    int count0 = 0;\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(current[i][j] == 0) count0++;\n        }\n    }\n    \n    if(count0 == 0) return true;\n    \n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    queue<pair<int,int>> q;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if((i == 0 || i == N-1 || j == 0 || j == N-1) && current[i][j] == 0) {\n                q.push({i, j});\n                visited[i][j] = true;\n            }\n        }\n    }\n    \n    int visited_count = q.size();\n    \n    while(!q.empty()) {\n        auto [i, j] = q.front();\n        q.pop();\n        \n        for(auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if(isValid(ni, nj) && !visited[ni][nj] && current[ni][nj] == 0) {\n                visited[ni][nj] = true;\n                q.push({ni, nj});\n                visited_count++;\n            }\n        }\n    }\n    \n    return visited_count == count0;\n}\n\nset<pair<int,int>> getAdjacencies() {\n    set<pair<int,int>> adj;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            for(auto [di, dj] : dirs) {\n                int ni = i + di, nj = j + dj;\n                if(isValid(ni, nj)) {\n                    int c1 = current[i][j], c2 = current[ni][nj];\n                    if(c1 != c2) {\n                        adj.insert({min(c1, c2), max(c1, c2)});\n                    }\n                }\n            }\n        }\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if((i == 0 || i == N-1 || j == 0 || j == N-1) && current[i][j] != 0) {\n                adj.insert({0, current[i][j]});\n            }\n        }\n    }\n    \n    return adj;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> m;\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            cin >> original[i][j];\n            current[i][j] = original[i][j];\n        }\n    }\n    \n    auto orig_adj = getAdjacencies();\n    \n    bool improved = true;\n    \n    while(improved) {\n        improved = false;\n        \n        for(int i = 0; i < N; i++) {\n            for(int j = 0; j < N; j++) {\n                if(current[i][j] == 0) continue;\n                \n                int color = current[i][j];\n                \n                int color_count = 0;\n                for(int ii = 0; ii < N; ii++) {\n                    for(int jj = 0; jj < N; jj++) {\n                        if(current[ii][jj] == color) color_count++;\n                    }\n                }\n                if(color_count == 1) continue;\n                \n                bool is_boundary = (i == 0 || i == N-1 || j == 0 || j == N-1);\n                if(is_boundary) {\n                    int boundary_count = 0;\n                    for(int ii = 0; ii < N; ii++) {\n                        for(int jj = 0; jj < N; jj++) {\n                            if((ii == 0 || ii == N-1 || jj == 0 || jj == N-1) && current[ii][jj] == color) {\n                                boundary_count++;\n                            }\n                        }\n                    }\n                    if(boundary_count == 1) continue;\n                }\n                \n                current[i][j] = 0;\n                \n                if(isConnected(color) && isConnected0() && getAdjacencies() == orig_adj) {\n                    improved = true;\n                } else {\n                    current[i][j] = color;\n                }\n            }\n        }\n    }\n    \n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(j > 0) cout << \" \";\n            cout << current[i][j];\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, D, Q;\n    cin >> N >> D >> Q;\n    \n    vector<vector<int>> cmp(N, vector<int>(N, -2));\n    for(int i = 0; i < N; i++) cmp[i][i] = 0;\n    \n    vector<pair<int,int>> all_pairs;\n    for(int i = 0; i < N; i++){\n        for(int j = i+1; j < N; j++){\n            all_pairs.push_back({i, j});\n        }\n    }\n    \n    mt19937 rng(0);\n    shuffle(all_pairs.begin(), all_pairs.end(), rng);\n    \n    int q_done = 0;\n    for(int attempt = 0; q_done < Q; attempt++){\n        int idx = attempt % (int)all_pairs.size();\n        int i = all_pairs[idx].first;\n        int j = all_pairs[idx].second;\n        \n        if(cmp[i][j] != -2) continue;\n        \n        cout << \"1 1 \" << i << \" \" << j << \"\\n\";\n        cout.flush();\n        \n        string result;\n        cin >> result;\n        \n        if(result == \"<\") {\n            cmp[i][j] = -1;\n            cmp[j][i] = 1;\n        } else if(result == \">\") {\n            cmp[i][j] = 1;\n            cmp[j][i] = -1;\n        } else {\n            cmp[i][j] = 0;\n            cmp[j][i] = 0;\n        }\n        \n        q_done++;\n    }\n    \n    // Enhanced transitive closure with equality\n    for(int pass = 0; pass < 10; pass++){\n        bool changed = false;\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(i == j || cmp[i][j] != -2) continue;\n                    \n                    if(cmp[i][k] == 1 && cmp[k][j] == 1){\n                        cmp[i][j] = 1;\n                        cmp[j][i] = -1;\n                        changed = true;\n                    }\n                    else if(cmp[i][k] == -1 && cmp[k][j] == -1){\n                        cmp[i][j] = -1;\n                        cmp[j][i] = 1;\n                        changed = true;\n                    }\n                    else if(cmp[i][k] == 0 && cmp[k][j] == 1){\n                        cmp[i][j] = 1;\n                        cmp[j][i] = -1;\n                        changed = true;\n                    }\n                    else if(cmp[i][k] == 0 && cmp[k][j] == -1){\n                        cmp[i][j] = -1;\n                        cmp[j][i] = 1;\n                        changed = true;\n                    }\n                    else if(cmp[i][k] == 1 && cmp[k][j] == 0){\n                        cmp[i][j] = 1;\n                        cmp[j][i] = -1;\n                        changed = true;\n                    }\n                    else if(cmp[i][k] == -1 && cmp[k][j] == 0){\n                        cmp[i][j] = -1;\n                        cmp[j][i] = 1;\n                        changed = true;\n                    }\n                    else if(cmp[i][k] == 0 && cmp[k][j] == 0){\n                        cmp[i][j] = 0;\n                        cmp[j][i] = 0;\n                        changed = true;\n                    }\n                }\n            }\n        }\n        if(!changed) break;\n    }\n    \n    vector<long long> weight(N, 0);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(i == j) continue;\n            if(cmp[i][j] == 1) weight[i]++;\n            else if(cmp[i][j] == -1) weight[i]--;\n        }\n    }\n    \n    auto compute_variance = [&](const vector<int>& div) {\n        vector<long long> sums(D, 0);\n        for(int i = 0; i < N; i++){\n            sums[div[i]] += weight[i];\n        }\n        double mean = 0;\n        for(auto s : sums) mean += s;\n        mean /= D;\n        \n        double var = 0;\n        for(auto s : sums){\n            var += (s - mean) * (s - mean);\n        }\n        return var / D;\n    };\n    \n    vector<pair<long long, int>> items_desc;\n    for(int i = 0; i < N; i++){\n        items_desc.push_back({weight[i], i});\n    }\n    sort(items_desc.rbegin(), items_desc.rend());\n    \n    // Strategy 1: FFD (First-Fit Decreasing)\n    vector<int> div_ffd(N);\n    vector<long long> set_weight_ffd(D, 0);\n    for(auto [w, item] : items_desc){\n        int best_set = 0;\n        for(int d = 1; d < D; d++){\n            if(set_weight_ffd[d] < set_weight_ffd[best_set]){\n                best_set = d;\n            }\n        }\n        div_ffd[item] = best_set;\n        set_weight_ffd[best_set] += w;\n    }\n    double var_ffd = compute_variance(div_ffd);\n    \n    // Strategy 2: Round-Robin (descending)\n    vector<int> div_rr_desc(N);\n    for(int idx = 0; idx < N; idx++){\n        int item = items_desc[idx].second;\n        div_rr_desc[item] = idx % D;\n    }\n    double var_rr_desc = compute_variance(div_rr_desc);\n    \n    // Strategy 3: Interleaved RR (heavy-light alternating)\n    vector<int> div_inter_hl(N);\n    int heavy_idx = 0, light_idx = N - 1;\n    int bin_idx = 0;\n    \n    while(heavy_idx <= light_idx){\n        int item_h = items_desc[heavy_idx].second;\n        div_inter_hl[item_h] = bin_idx;\n        heavy_idx++;\n        bin_idx = (bin_idx + 1) % D;\n        \n        if(heavy_idx <= light_idx){\n            int item_l = items_desc[light_idx].second;\n            div_inter_hl[item_l] = bin_idx;\n            light_idx--;\n            bin_idx = (bin_idx + 1) % D;\n        }\n    }\n    double var_inter_hl = compute_variance(div_inter_hl);\n    \n    // Strategy 4: Reverse Interleaved RR (light-heavy alternating)\n    vector<int> div_inter_lh(N);\n    heavy_idx = 0;\n    light_idx = N - 1;\n    bin_idx = 0;\n    \n    while(light_idx >= heavy_idx){\n        int item_l = items_desc[light_idx].second;\n        div_inter_lh[item_l] = bin_idx;\n        light_idx--;\n        bin_idx = (bin_idx + 1) % D;\n        \n        if(light_idx >= heavy_idx){\n            int item_h = items_desc[heavy_idx].second;\n            div_inter_lh[item_h] = bin_idx;\n            heavy_idx++;\n            bin_idx = (bin_idx + 1) % D;\n        }\n    }\n    double var_inter_lh = compute_variance(div_inter_lh);\n    \n    // Choose the best strategy\n    vector<int> best_division = div_ffd;\n    double best_var = var_ffd;\n    \n    if(var_rr_desc < best_var){\n        best_var = var_rr_desc;\n        best_division = div_rr_desc;\n    }\n    if(var_inter_hl < best_var){\n        best_var = var_inter_hl;\n        best_division = div_inter_hl;\n    }\n    if(var_inter_lh < best_var){\n        best_var = var_inter_lh;\n        best_division = div_inter_lh;\n    }\n    \n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << best_division[i];\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<pair<int,int>> solveWithStrategy(vector<vector<int>> stacks, int m, int n, int strategy) {\n  vector<pair<int,int>> operations;\n  \n  for(int box = 1; box <= n; box++){\n    int src_stack = -1;\n    \n    for(int i = 0; i < m; i++){\n      for(int j = 0; j < (int)stacks[i].size(); j++){\n        if(stacks[i][j] == box){\n          src_stack = i;\n          break;\n        }\n      }\n      if(src_stack != -1) break;\n    }\n    \n    while(stacks[src_stack].back() != box){\n      int top_box = stacks[src_stack].back();\n      int dest_stack = -1;\n      \n      for(int i = 0; i < m; i++){\n        if(i == src_stack) continue;\n        \n        if(dest_stack == -1){\n          dest_stack = i;\n          continue;\n        }\n        \n        int cur_size = stacks[i].size();\n        int best_size = stacks[dest_stack].size();\n        bool cur_empty = (cur_size == 0);\n        bool best_empty = (best_size == 0);\n        int cur_top = cur_empty ? INT_MAX : stacks[i].back();\n        int best_top = best_empty ? INT_MAX : stacks[dest_stack].back();\n        bool cur_ordered = (!cur_empty && cur_top >= top_box);\n        bool best_ordered = (!best_empty && best_top >= top_box);\n        \n        bool better = false;\n        \n        auto cmp_size = [&](){ return cur_size < best_size; };\n        auto cmp_empty = [&](){ return cur_empty && !best_empty; };\n        auto cmp_ordered = [&](){ return cur_ordered && !best_ordered; };\n        auto cmp_top_small = [&](){ return cur_top < best_top; };\n        auto cmp_top_large = [&](){ return cur_top > best_top; };\n        \n        int phase = box * 100 / n;\n        \n        if(strategy == 0 || strategy == 22){ // Size first, empty, smaller top\n          if(cmp_size()) better = true;\n          else if(cur_size == best_size && cmp_empty()) better = true;\n          else if(cur_size == best_size && cur_empty == best_empty && cmp_top_small()) better = true;\n        } \n        else if(strategy == 1 || strategy == 23){ // Size first, empty, larger top\n          if(cmp_size()) better = true;\n          else if(cur_size == best_size && cmp_empty()) better = true;\n          else if(cur_size == best_size && cur_empty == best_empty && cmp_top_large()) better = true;\n        }\n        else if(strategy == 2 || strategy == 24){ // Empty first\n          if(cmp_empty()) better = true;\n          else if(!cur_empty && !best_empty && cmp_size()) better = true;\n          else if(cur_empty && best_empty && cmp_size()) better = true;\n        }\n        else if(strategy == 3 || strategy == 25){ // Size only\n          if(cmp_size()) better = true;\n        }\n        else if(strategy == 4 || strategy == 26){ // Balance\n          int cur_dist = abs((int)cur_size - (n-box+1)/m);\n          int best_dist = abs((int)best_size - (n-box+1)/m);\n          if(cur_dist < best_dist) better = true;\n          else if(cur_dist == best_dist && cmp_empty()) better = true;\n        }\n        else if(strategy == 5 || strategy == 27){ // Middle-range\n          int mid = n / 2;\n          int cur_dist = cur_empty ? INT_MAX : abs(cur_top - mid);\n          int best_dist = best_empty ? INT_MAX : abs(best_top - mid);\n          if(cmp_size()) better = true;\n          else if(cur_size == best_size && cur_dist < best_dist) better = true;\n        }\n        else if(strategy == 6 || strategy == 28){ // Extraction order >=\n          if(cur_ordered && !best_ordered) better = true;\n          else if(cur_ordered == best_ordered){\n            if(cmp_size()) better = true;\n            else if(cur_size == best_size && cmp_empty()) better = true;\n          }\n        }\n        else if(strategy == 7 || strategy == 29){ // Extraction order >\n          bool cur_strict = (!cur_empty && cur_top > top_box);\n          bool best_strict = (!best_empty && best_top > top_box);\n          if(cur_strict && !best_strict) better = true;\n          else if(cur_strict == best_strict && cmp_size()) better = true;\n        }\n        else if(strategy == 8 || strategy == 30){ // Stack completion\n          if(cur_empty && best_size > 0) better = true;\n          else if((cur_empty && best_empty) || (!cur_empty && !best_empty)){\n            if(cmp_size()) better = true;\n          }\n        }\n        else if(strategy == 9 || strategy == 31){ // Cost estimation\n          if(cmp_size()) better = true;\n          else if(cur_size == best_size && cmp_empty()) better = true;\n          else if(cur_size == best_size && cur_empty == best_empty && cmp_top_small()) better = true;\n        }\n        else if(strategy == 10){ // Minimize risk\n          int cur_risk = cur_empty ? 0 : abs(cur_top - top_box);\n          int best_risk = best_empty ? 0 : abs(best_top - top_box);\n          if(cmp_size()) better = true;\n          else if(cur_size == best_size && cur_risk > best_risk) better = true;\n        }\n        else if(strategy == 11){ // Grouping\n          int cur_prox = cur_empty ? INT_MAX : abs(cur_top - top_box);\n          int best_prox = best_empty ? INT_MAX : abs(best_top - top_box);\n          if(cur_prox < best_prox) better = true;\n          else if(cur_prox == best_prox && cmp_size()) better = true;\n        }\n        else if(strategy == 12){ // Soft extraction order\n          int cur_penalty = 0, best_penalty = 0;\n          if(!cur_empty && cur_top < top_box) cur_penalty = 10;\n          if(!best_empty && best_top < top_box) best_penalty = 10;\n          int cur_score = cur_size * 100 + cur_penalty;\n          int best_score = best_size * 100 + best_penalty;\n          if(cur_empty && !best_empty) better = true;\n          else if(cur_score < best_score) better = true;\n        }\n        else if(strategy == 13){ // Weighted gap\n          if(cmp_size()) better = true;\n          else if(cur_size == best_size){\n            int cur_gap = cur_empty ? INT_MAX : (cur_top - top_box);\n            int best_gap = best_empty ? INT_MAX : (best_top - top_box);\n            if(cur_gap > best_gap) better = true;\n            else if(cur_gap == best_gap && cmp_empty()) better = true;\n          }\n        }\n        else if(strategy == 14){ // Two-tier\n          if(box <= n/2){ // Early\n            if(cmp_empty()) better = true;\n            else if(cur_empty == best_empty){\n              if(cur_ordered && !best_ordered) better = true;\n              else if(cur_ordered == best_ordered && cmp_size()) better = true;\n            }\n          } else { // Late\n            if(cmp_size()) better = true;\n            else if(cur_size == best_size && cmp_empty()) better = true;\n          }\n        }\n        else if(strategy == 15){ // Adaptive\n          int remaining = n - box + 1;\n          if(cmp_size()) better = true;\n          else if(cur_size == best_size){\n            if(cmp_empty()) better = true;\n            else if(cur_empty == best_empty){\n              if(remaining <= n/3 && cur_ordered && !best_ordered) better = true;\n              else if(remaining > n/3 && cmp_top_small()) better = true;\n            }\n          }\n        }\n        else if(strategy == 16){ // Three-phase\n          int p = box * 3 / n;\n          if(p == 0){ // First: empty > ordered > size\n            if(cmp_empty()) better = true;\n            else if(cur_empty == best_empty){\n              if(cur_ordered && !best_ordered) better = true;\n              else if(cur_ordered == best_ordered && cmp_size()) better = true;\n            }\n          } else if(p == 1){ // Middle: ordered > empty > size\n            if(cur_ordered && !best_ordered) better = true;\n            else if(cur_ordered == best_ordered){\n              if(cmp_empty()) better = true;\n              else if(cur_empty == best_empty && cmp_size()) better = true;\n            }\n          } else { // Last: size > empty\n            if(cmp_size()) better = true;\n            else if(cur_size == best_size && cmp_empty()) better = true;\n          }\n        }\n        else if(strategy == 17){ // Inverted phases\n          int p = box * 3 / n;\n          if(p == 0){ // Early: size focused\n            if(cmp_size()) better = true;\n            else if(cur_size == best_size && cmp_empty()) better = true;\n          } else if(p == 1){ // Middle: balanced\n            if(cmp_empty()) better = true;\n            else if(cur_empty == best_empty && cmp_size()) better = true;\n          } else { // Late: ordered > empty\n            if(cur_ordered && !best_ordered) better = true;\n            else if(cur_ordered == best_ordered){\n              if(cmp_empty()) better = true;\n              else if(cur_empty == best_empty && cmp_size()) better = true;\n            }\n          }\n        }\n        else if(strategy == 18){ // Hybrid 0+6\n          if(cmp_size()) better = true;\n          else if(cur_size == best_size){\n            if(cmp_empty()) better = true;\n            else if(cur_empty == best_empty){\n              if(cur_ordered && !best_ordered) better = true;\n              else if(cur_ordered == best_ordered && cmp_top_small()) better = true;\n            }\n          }\n        }\n        else if(strategy == 19){ // Hybrid empty+ordered\n          if(cmp_empty()) better = true;\n          else if(cur_empty == best_empty){\n            if(cur_ordered && !best_ordered) better = true;\n            else if(cur_ordered == best_ordered && cmp_size()) better = true;\n          }\n        }\n        else if(strategy == 20){ // Ultra extraction order\n          bool cur_good = (cur_empty || cur_top > top_box);\n          bool best_good = (best_empty || best_top > top_box);\n          if(cur_good && !best_good) better = true;\n          else if(cur_good == best_good){\n            if(cmp_empty()) better = true;\n            else if(cur_empty == best_empty && cmp_size()) better = true;\n          }\n        }\n        else if(strategy == 21){ // Clustering by proximity\n          int cur_next = (box < n) ? box + 1 : INT_MAX;\n          int cur_clustering = cur_empty ? 0 : abs(cur_top - cur_next);\n          int best_clustering = best_empty ? 0 : abs(best_top - cur_next);\n          if(cmp_size()) better = true;\n          else if(cur_size == best_size && cur_clustering < best_clustering) better = true;\n        }\n        else if(strategy == 32){ // Five-phase\n          int quin = box * 5 / n;\n          if(quin == 0){ // 1st 20%: empty > ordered > size\n            if(cmp_empty()) better = true;\n            else if(cur_empty == best_empty){\n              if(cur_ordered && !best_ordered) better = true;\n              else if(cur_ordered == best_ordered && cmp_size()) better = true;\n            }\n          } else if(quin <= 2){ // 2nd-3rd 40%: ordered > size > empty\n            if(cur_ordered && !best_ordered) better = true;\n            else if(cur_ordered == best_ordered){\n              if(cmp_size()) better = true;\n              else if(cur_size == best_size && cmp_empty()) better = true;\n            }\n          } else if(quin <= 3){ // 4th 20%: balance\n            if(cmp_size()) better = true;\n            else if(cur_size == best_size){\n              if(cmp_empty()) better = true;\n              else if(cur_empty == best_empty && cur_ordered && !best_ordered) better = true;\n            }\n          } else { // 5th 20%: pure size\n            if(cmp_size()) better = true;\n          }\n        }\n        else if(strategy == 33){ // Smooth transition\n          double p = (double)box / n;\n          // Linearly transition: empty(1.0 to 0.5), ordered(1.0 to 0.8), size(always)\n          int empty_w = (int)(100 * (1.0 - p * 0.5));\n          int ordered_w = (int)(100 * (0.9 - p * 0.1));\n          int size_w = 100;\n          \n          int cur_score = (cmp_empty() ? empty_w : 0) \n                        + (cur_ordered ? ordered_w : 0)\n                        + (cmp_size() ? size_w : 0)\n                        - cur_size * 10;\n          int best_score = (best_empty ? empty_w : 0)\n                         + (best_ordered ? ordered_w : 0)\n                         + (best_size == cur_size ? size_w : 0)\n                         - best_size * 10;\n          \n          if(cur_score > best_score) better = true;\n        }\n        else if(strategy == 34){ // Early extreme (all ordered)\n          if(box <= 2*n/3){\n            if(cur_ordered && !best_ordered) better = true;\n            else if(cur_ordered == best_ordered && cmp_size()) better = true;\n          } else {\n            if(cmp_size()) better = true;\n          }\n        }\n        else if(strategy == 35){ // Late extreme (all size early)\n          if(box <= n/3){\n            if(cmp_size()) better = true;\n          } else {\n            if(cmp_empty()) better = true;\n            else if(cur_empty == best_empty && cur_ordered && !best_ordered) better = true;\n          }\n        }\n        \n        if(better) dest_stack = i;\n      }\n      \n      stacks[dest_stack].push_back(top_box);\n      stacks[src_stack].pop_back();\n      operations.push_back({top_box, dest_stack + 1});\n    }\n    \n    operations.push_back({box, 0});\n    stacks[src_stack].pop_back();\n  }\n  \n  return operations;\n}\n\nint main(){\n  ios_base::sync_with_stdio(false);\n  cin.tie(nullptr);\n  \n  int n, m;\n  cin >> n >> m;\n  \n  vector<vector<int>> initial_stacks(m);\n  \n  for(int i = 0; i < m; i++){\n    int s = n / m;\n    for(int j = 0; j < s; j++){\n      int x;\n      cin >> x;\n      initial_stacks[i].push_back(x);\n    }\n  }\n  \n  int best_ops = INT_MAX;\n  vector<pair<int,int>> best_solution;\n  \n  for(int strategy = 0; strategy < 36; strategy++){\n    auto ops = solveWithStrategy(initial_stacks, m, n, strategy);\n    if((int)ops.size() < best_ops){\n      best_ops = ops.size();\n      best_solution = ops;\n    }\n  }\n  \n  for(auto [v, i] : best_solution){\n    cout << v << \" \" << i << \"\\n\";\n  }\n  \n  return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> h, v;\nvector<vector<int>> d;\n\nint di[] = {0, 1, 0, -1};\nint dj[] = {1, 0, -1, 0};\nchar dir_char[] = {'R', 'D', 'L', 'U'};\n\ndouble simulate(const string& path) {\n    if (path.empty() || path.length() > 100000) return 1e18;\n    \n    int L = path.length();\n    vector<vector<long long>> dirt(N, vector<long long>(N, 0));\n    \n    int ci = 0, cj = 0;\n    long long sum = 0;\n    \n    for (int step = 0; step < 2 * L; step++) {\n        char c = path[step % L];\n        if (c == 'R') cj++;\n        else if (c == 'L') cj--;\n        else if (c == 'D') ci++;\n        else if (c == 'U') ci--;\n        \n        dirt[ci][cj] = 0;\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (i != ci || j != cj) {\n                    dirt[i][j] += d[i][j];\n                }\n            }\n        }\n        \n        if (step >= L) {\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    sum += dirt[i][j];\n                }\n            }\n        }\n    }\n    \n    return (double)sum / L;\n}\n\nvoid dfs(int i, int j, vector<vector<bool>>& visited, string& path, \n         function<int(int,int)> comparator) {\n    visited[i][j] = true;\n    \n    vector<pair<int, int>> moves;\n    \n    for (int dir = 0; dir < 4; dir++) {\n        int ni = i + di[dir];\n        int nj = j + dj[dir];\n        \n        if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj]) {\n            bool canMove = false;\n            if (dir == 0) canMove = (v[i][j] == '0');\n            else if (dir == 1) canMove = (h[i][j] == '0');\n            else if (dir == 2) canMove = (v[i][nj] == '0');\n            else canMove = (h[ni][j] == '0');\n            \n            if (canMove) {\n                moves.push_back({dir, comparator(ni, nj)});\n            }\n        }\n    }\n    \n    sort(moves.begin(), moves.end(), \n         [](const pair<int,int> &a, const pair<int,int> &b) { \n             return a.second > b.second; \n         });\n    \n    for (const auto &[dir, _] : moves) {\n        int ni = i + di[dir];\n        int nj = j + dj[dir];\n        \n        path += dir_char[dir];\n        dfs(ni, nj, visited, path, comparator);\n        path += dir_char[(dir + 2) % 4];\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    \n    h.resize(N-1);\n    v.resize(N);\n    d.resize(N, vector<int>(N));\n    \n    for (int i = 0; i < N-1; i++) cin >> h[i];\n    for (int i = 0; i < N; i++) cin >> v[i];\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n        }\n    }\n    \n    double best_score = 1e18;\n    string best_path;\n    \n    int cm = N / 2;\n    \n    vector<function<int(int,int)>> strategies;\n    \n    // Pure single-factor strategies\n    strategies.push_back([](int i, int j) { return -d[i][j]; });\n    strategies.push_back([](int i, int j) { return d[i][j]; });\n    strategies.push_back([](int i, int j) { return -(abs(i) + abs(j)); });\n    strategies.push_back([](int i, int j) { return abs(i) + abs(j); });\n    strategies.push_back([cm](int i, int j) { return -(abs(i - cm) + abs(j - cm)); });\n    strategies.push_back([cm](int i, int j) { return abs(i - cm) + abs(j - cm); });\n    \n    // Chebyshev distance variants\n    strategies.push_back([](int i, int j) { \n        return -(max(abs(i), abs(j))); \n    });\n    strategies.push_back([cm](int i, int j) { \n        return -(max(abs(i - cm), abs(j - cm))); \n    });\n    \n    // Squared distance variants\n    strategies.push_back([](int i, int j) { \n        int dist = abs(i) + abs(j);\n        return -(dist * dist); \n    });\n    strategies.push_back([cm](int i, int j) { \n        int dist = abs(i - cm) + abs(j - cm);\n        return -(dist * dist); \n    });\n    \n    // Euclidean distance variants\n    strategies.push_back([](int i, int j) { \n        long long dist_sq = (long long)i*i + (long long)j*j;\n        return -min(100000LL, dist_sq); \n    });\n    strategies.push_back([cm](int i, int j) { \n        long long dist_sq = (long long)(i-cm)*(i-cm) + (long long)(j-cm)*(j-cm);\n        return -min(100000LL, dist_sq); \n    });\n    \n    // Distance to boundary\n    strategies.push_back([N](int i, int j) { \n        int dist_boundary = min({i, j, N-1-i, N-1-j});\n        return -(dist_boundary); \n    });\n    strategies.push_back([N](int i, int j) { \n        int dist_boundary = min({i, j, N-1-i, N-1-j});\n        return (dist_boundary); \n    });\n    \n    // Product variants (d * distance)\n    strategies.push_back([](int i, int j) { \n        int dist = abs(i) + abs(j);\n        return -min(100000LL, (long long)d[i][j] * (dist + 1)); \n    });\n    strategies.push_back([cm](int i, int j) { \n        int dist = abs(i - cm) + abs(j - cm);\n        return -min(100000LL, (long long)d[i][j] * (dist + 1)); \n    });\n    \n    // Weighted combinations for start-based Manhattan\n    vector<pair<int,int>> weights = {\n        {1, 1}, {2, 1}, {3, 1}, {5, 1}, {10, 1}, {50, 1}, {100, 1}, {500, 1}, {1000, 1},\n        {1, 2}, {1, 3}, {1, 5}, {1, 10}, {1, 50}, {1, 100}, {1, 500}, {1, 1000},\n        {10, 10}, {100, 100}, {50, 50}\n    };\n    \n    for (auto [dw, sw] : weights) {\n        strategies.push_back([dw, sw](int i, int j) {\n            return -(dw * d[i][j] + sw * (abs(i) + abs(j)));\n        });\n    }\n    \n    // Weighted combinations for center-based Manhattan\n    for (auto [dw, sw] : weights) {\n        strategies.push_back([dw, sw, cm](int i, int j) {\n            return -(dw * d[i][j] + sw * (abs(i - cm) + abs(j - cm)));\n        });\n    }\n    \n    // Weighted combinations with Euclidean - expanded\n    vector<pair<int,int>> eu_weights = {\n        {1, 1}, {2, 1}, {3, 1}, {5, 1}, {10, 1}, {50, 1}, {100, 1}, {500, 1}, {1000, 1},\n        {1, 2}, {1, 3}, {1, 5}, {1, 10}\n    };\n    \n    for (auto [dw, sw] : eu_weights) {\n        strategies.push_back([dw, sw](int i, int j) {\n            long long dist_sq = (long long)i*i + (long long)j*j;\n            return -min(1000000LL, (long long)dw * d[i][j] + sw * dist_sq); \n        });\n    }\n    \n    for (auto [dw, sw] : eu_weights) {\n        strategies.push_back([dw, sw, cm](int i, int j) {\n            long long dist_sq = (long long)(i-cm)*(i-cm) + (long long)(j-cm)*(j-cm);\n            return -min(1000000LL, (long long)dw * d[i][j] + sw * dist_sq); \n        });\n    }\n    \n    // Test all strategies\n    for (const auto& strategy : strategies) {\n        string path;\n        vector<vector<bool>> visited(N, vector<bool>(N, false));\n        dfs(0, 0, visited, path, strategy);\n        double score = simulate(path);\n        if (score < best_score) {\n            best_score = score;\n            best_path = path;\n        }\n    }\n    \n    cout << best_path << endl;\n    \n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nint si, sj;\nvector<string> grid;\nvector<string> words;\nmap<char, vector<pair<int, int>>> charPos;\nvector<vector<int>> overlapCache;\n\nint getOverlap(const string& a, const string& b) {\n    int maxOverlap = 0;\n    int maxLen = min((int)a.size(), (int)b.size());\n    for (int o = 1; o <= maxLen; o++) {\n        bool match = true;\n        for (int i = 0; i < o; i++) {\n            if (a[a.size() - o + i] != b[i]) {\n                match = false;\n                break;\n            }\n        }\n        if (match) maxOverlap = o;\n    }\n    return maxOverlap;\n}\n\nint getMinCharDistance(const string& word, int ci, int cj) {\n    int minDist = INT_MAX;\n    for (char c : word) {\n        for (auto [ii, jj] : charPos[c]) {\n            minDist = min(minDist, abs(ii - ci) + abs(jj - cj));\n        }\n    }\n    return minDist;\n}\n\nstring buildSuperstring(const vector<int>& order) {\n    if (order.empty()) return \"\";\n    string result = words[order[0]];\n    for (int i = 1; i < (int)order.size(); i++) {\n        int ov = overlapCache[order[i-1]][order[i]];\n        result += words[order[i]].substr(ov);\n    }\n    return result;\n}\n\nlong long calculateCost(const string& superstring) {\n    long long cost = 0;\n    int ci = si, cj = sj;\n    \n    for (int pos = 0; pos < (int)superstring.size(); pos++) {\n        char c = superstring[pos];\n        \n        int bestI = -1, bestJ = -1;\n        double minTotalCost = 1e18;\n        \n        for (auto [ii, jj] : charPos[c]) {\n            double moveCost = abs(ii - ci) + abs(jj - cj);\n            double lookCost = 0;\n            \n            double weights[] = {0.65, 0.25, 0.10, 0.08, 0.02};\n            \n            for (int step = 1; step <= 5; step++) {\n                if (pos + step >= (int)superstring.size()) break;\n                \n                char nextChar = superstring[pos + step];\n                int nextMinDist = INT_MAX;\n                for (auto [ni, nj] : charPos[nextChar]) {\n                    nextMinDist = min(nextMinDist, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist * weights[step - 1];\n            }\n            \n            double totalCost = moveCost + lookCost;\n            if (totalCost < minTotalCost) {\n                minTotalCost = totalCost;\n                bestI = ii;\n                bestJ = jj;\n            }\n        }\n        \n        cost += abs(bestI - ci) + abs(bestJ - cj) + 1;\n        ci = bestI;\n        cj = bestJ;\n    }\n    return cost;\n}\n\nvector<int> greedyOrderForward(int startWord, double proximityScale = 1.0) {\n    vector<int> order;\n    set<int> used;\n    order.push_back(startWord);\n    used.insert(startWord);\n    \n    int curI = si, curJ = sj;\n    \n    while ((int)used.size() < M) {\n        int lastWord = order.back();\n        int bestWord = -1;\n        double bestScore = -1e18;\n        \n        for (int w = 0; w < M; w++) {\n            if (used.count(w)) continue;\n            int ov = overlapCache[lastWord][w];\n            int proximity = getMinCharDistance(words[w], curI, curJ);\n            \n            double score = ov * 1000.0 - proximity * proximityScale;\n            \n            if (score > bestScore) {\n                bestScore = score;\n                bestWord = w;\n            }\n        }\n        \n        order.push_back(bestWord);\n        used.insert(bestWord);\n        \n        char lastChar = words[bestWord].back();\n        int minDist = INT_MAX;\n        for (auto [ii, jj] : charPos[lastChar]) {\n            int d = abs(ii - curI) + abs(jj - curJ);\n            if (d < minDist) {\n                minDist = d;\n                curI = ii;\n                curJ = jj;\n            }\n        }\n    }\n    return order;\n}\n\nvector<int> greedyOrderForwardRandomized(int startWord, double proximityScale, int seed) {\n    mt19937 rng(seed);\n    vector<int> order;\n    set<int> used;\n    order.push_back(startWord);\n    used.insert(startWord);\n    \n    int curI = si, curJ = sj;\n    \n    while ((int)used.size() < M) {\n        int lastWord = order.back();\n        \n        vector<pair<double, int>> candidates;\n        for (int w = 0; w < M; w++) {\n            if (used.count(w)) continue;\n            int ov = overlapCache[lastWord][w];\n            int proximity = getMinCharDistance(words[w], curI, curJ);\n            double score = ov * 1000.0 - proximity * proximityScale;\n            candidates.push_back({score, w});\n        }\n        \n        sort(candidates.rbegin(), candidates.rend());\n        \n        int bestWord;\n        // If top candidates are close, randomize to explore more\n        if (candidates.size() > 2 && candidates[0].first - candidates[2].first < 200) {\n            int topN = min(4, (int)candidates.size());\n            bestWord = candidates[rng() % topN].second;\n        } else {\n            bestWord = candidates[0].second;\n        }\n        \n        order.push_back(bestWord);\n        used.insert(bestWord);\n        \n        char lastChar = words[bestWord].back();\n        int minDist = INT_MAX;\n        for (auto [ii, jj] : charPos[lastChar]) {\n            int d = abs(ii - curI) + abs(jj - curJ);\n            if (d < minDist) {\n                minDist = d;\n                curI = ii;\n                curJ = jj;\n            }\n        }\n    }\n    return order;\n}\n\nvector<int> greedyOrderReverse(int endWord) {\n    vector<int> order;\n    set<int> used;\n    order.push_back(endWord);\n    used.insert(endWord);\n    \n    while ((int)used.size() < M) {\n        int firstWord = order[0];\n        int bestWord = -1;\n        int bestOverlap = -1;\n        int bestProximity = INT_MAX;\n        \n        for (int w = 0; w < M; w++) {\n            if (used.count(w)) continue;\n            int ov = overlapCache[w][firstWord];\n            int proximity = getMinCharDistance(words[w], si, sj);\n            \n            if (ov > bestOverlap || (ov == bestOverlap && proximity < bestProximity)) {\n                bestOverlap = ov;\n                bestProximity = proximity;\n                bestWord = w;\n            }\n        }\n        \n        order.insert(order.begin(), bestWord);\n        used.insert(bestWord);\n    }\n    return order;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    cin >> si >> sj;\n    \n    grid.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> grid[i];\n    }\n    \n    words.resize(M);\n    for (int i = 0; i < M; i++) {\n        cin >> words[i];\n    }\n    \n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            charPos[grid[i][j]].push_back({i, j});\n        }\n    }\n    \n    // Precompute all overlaps\n    overlapCache.assign(M, vector<int>(M, 0));\n    for (int i = 0; i < M; i++) {\n        for (int j = 0; j < M; j++) {\n            if (i != j) {\n                overlapCache[i][j] = getOverlap(words[i], words[j]);\n            }\n        }\n    }\n    \n    string bestSuperstring;\n    long long bestCost = LLONG_MAX;\n    \n    // Try 280 forward greedy with clustered proximity scales\n    for (int i = 0; i < 280; i++) {\n        int start = (M * i) / 280;\n        // Cluster more scales in the 0.5-2.0 range where sweet spot likely is\n        double proximityScale;\n        if (i < 140) {\n            proximityScale = 0.1 + (i * 0.01286);  // 0.1 to 1.9\n        } else {\n            proximityScale = 1.9 + ((i - 140) * 0.01286);  // 1.9 to 3.7\n        }\n        \n        auto order = greedyOrderForward(start, proximityScale);\n        auto superstring = buildSuperstring(order);\n        auto cost = calculateCost(superstring);\n        \n        if (cost < bestCost) {\n            bestCost = cost;\n            bestSuperstring = superstring;\n        }\n    }\n    \n    // Try 80 randomized greedy orderings for diversity\n    for (int i = 0; i < 80; i++) {\n        int start = (M * i) / 80;\n        double proximityScale = 0.3 + (i * 0.03);\n        \n        auto order = greedyOrderForwardRandomized(start, proximityScale, 1000 + i);\n        auto superstring = buildSuperstring(order);\n        auto cost = calculateCost(superstring);\n        \n        if (cost < bestCost) {\n            bestCost = cost;\n            bestSuperstring = superstring;\n        }\n    }\n    \n    // Try 140 reverse greedy orderings\n    for (int i = 0; i < 140; i++) {\n        int start = (M * i) / 140;\n        auto order = greedyOrderReverse(start);\n        auto superstring = buildSuperstring(order);\n        auto cost = calculateCost(superstring);\n        \n        if (cost < bestCost) {\n            bestCost = cost;\n            bestSuperstring = superstring;\n        }\n    }\n    \n    // Generate output\n    vector<pair<int, int>> operations;\n    int ci = si, cj = sj;\n    \n    for (int pos = 0; pos < (int)bestSuperstring.size(); pos++) {\n        char c = bestSuperstring[pos];\n        \n        int bestI = -1, bestJ = -1;\n        double minTotalCost = 1e18;\n        \n        for (auto [ii, jj] : charPos[c]) {\n            double moveCost = abs(ii - ci) + abs(jj - cj);\n            double lookCost = 0;\n            \n            double weights[] = {0.65, 0.25, 0.10, 0.08, 0.02};\n            \n            for (int step = 1; step <= 5; step++) {\n                if (pos + step >= (int)bestSuperstring.size()) break;\n                \n                char nextChar = bestSuperstring[pos + step];\n                int nextMinDist = INT_MAX;\n                for (auto [ni, nj] : charPos[nextChar]) {\n                    nextMinDist = min(nextMinDist, abs(ni - ii) + abs(nj - jj));\n                }\n                lookCost += nextMinDist * weights[step - 1];\n            }\n            \n            double totalCost = moveCost + lookCost;\n            if (totalCost < minTotalCost) {\n                minTotalCost = totalCost;\n                bestI = ii;\n                bestJ = jj;\n            }\n        }\n        \n        operations.push_back({bestI, bestJ});\n        ci = bestI;\n        cj = bestJ;\n    }\n    \n    for (auto [i, j] : operations) {\n        cout << i << \" \" << j << \"\\n\";\n    }\n    \n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n    \n    for (int k = 0; k < M; k++) {\n        int d;\n        cin >> d;\n        for (int i = 0; i < d; i++) {\n            int r, c;\n            cin >> r >> c;\n        }\n    }\n    \n    set<pair<int,int>> oil_squares;\n    \n    // Divide into 4 quadrants and divine each to guide drilling strategy\n    int half = N / 2;\n    vector<vector<pair<int,int>>> quadrants(4);\n    vector<int> divine_results(4, -1);\n    \n    // Create quadrants\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int q = (i < half ? 0 : 1) * 2 + (j < half ? 0 : 1);\n            quadrants[q].push_back({i, j});\n        }\n    }\n    \n    // Divine each quadrant (very cheap, ~0.25 per quadrant)\n    for (int q = 0; q < 4; q++) {\n        if (quadrants[q].size() >= 2) {\n            cout << \"q \" << quadrants[q].size();\n            for (auto [i, j] : quadrants[q]) {\n                cout << \" \" << i << \" \" << j;\n            }\n            cout << \"\\n\";\n            cout.flush();\n            cin >> divine_results[q];\n        }\n    }\n    \n    // Process each quadrant based on divine results\n    for (int q = 0; q < 4; q++) {\n        int divine_val = divine_results[q];\n        auto& region = quadrants[q];\n        set<pair<int,int>> drilled_here;\n        \n        // Strategy: if divine > 0, drill all; if divine = 0, sample carefully\n        if (divine_val > 0) {\n            // Oil definitely present, drill all squares\n            for (auto [i, j] : region) {\n                cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n                cout.flush();\n                int val;\n                cin >> val;\n                if (val > 0) {\n                    oil_squares.insert({i, j});\n                }\n            }\n        } else if (divine_val == 0) {\n            // Divine says no oil (or very little with noise), sample generously\n            int sample_size = min(5, (int)region.size()); // Sample at least 5 squares\n            int oil_found_in_sample = 0;\n            \n            for (int s = 0; s < sample_size; s++) {\n                int idx = s * region.size() / sample_size;\n                auto [i, j] = region[idx];\n                cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n                cout.flush();\n                int val;\n                cin >> val;\n                drilled_here.insert({i, j});\n                if (val > 0) {\n                    oil_squares.insert({i, j});\n                    oil_found_in_sample++;\n                }\n            }\n            \n            if (oil_found_in_sample > 0) {\n                // Samples found oil, must drill remaining squares\n                for (auto [i, j] : region) {\n                    if (drilled_here.find({i, j}) == drilled_here.end()) {\n                        cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n                        cout.flush();\n                        int val;\n                        cin >> val;\n                        if (val > 0) {\n                            oil_squares.insert({i, j});\n                        }\n                    }\n                }\n            }\n            // If no oil found in samples, we skip remaining (risky but cost-effective)\n        } else {\n            // Single square or error, drill it\n            for (auto [i, j] : region) {\n                cout << \"q 1 \" << i << \" \" << j << \"\\n\";\n                cout.flush();\n                int val;\n                cin >> val;\n                if (val > 0) {\n                    oil_squares.insert({i, j});\n                }\n            }\n        }\n    }\n    \n    // Output answer\n    cout << \"a \" << oil_squares.size();\n    for (auto [i, j] : oil_squares) {\n        cout << \" \" << i << \" \" << j;\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    int result;\n    cin >> result;\n    \n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<long long>> a(D, vector<long long>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    for (int d = 0; d < D; d++) {\n        // Try column packing (full width, variable heights)\n        long long total_height = 0;\n        vector<long long> heights(N);\n        for (int k = 0; k < N; k++) {\n            heights[k] = (a[d][k] + W - 1) / W;\n            total_height += heights[k];\n        }\n        \n        if (total_height <= W) {\n            // Column packing works: use it\n            long long y = 0;\n            for (int k = 0; k < N; k++) {\n                cout << y << \" \" << 0 << \" \" << y + heights[k] << \" \" << W << \"\\n\";\n                y += heights[k];\n            }\n        } else {\n            // Use simple 1\u00d7N grid (N columns, full height)\n            // This is consistent and predictable\n            long long cell_w = W / N;\n            for (int k = 0; k < N; k++) {\n                long long j0 = (long long)k * cell_w;\n                long long j1 = (k == N - 1) ? W : (long long)(k + 1) * cell_w;\n                \n                cout << 0 << \" \" << j0 << \" \" << W << \" \" << j1 << \"\\n\";\n            }\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long MOD = 998244353;\n\nint N, M, K;\nvector<vector<vector<long long>>> stamps;\n\nlong long calculate_score(const vector<vector<long long>>& board) {\n    long long score = 0;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            score += board[i][j] % MOD;\n        }\n    }\n    return score;\n}\n\nlong long delta_score(const vector<vector<long long>>& board, int m, int p, int q) {\n    long long delta = 0;\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            int ni = p + i, nj = q + j;\n            long long old_mod = board[ni][nj] % MOD;\n            long long new_mod = (board[ni][nj] + stamps[m][i][j]) % MOD;\n            delta += new_mod - old_mod;\n        }\n    }\n    return delta;\n}\n\nvoid apply_operation(vector<vector<long long>>& board, int m, int p, int q) {\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            board[p+i][q+j] += stamps[m][i][j];\n        }\n    }\n}\n\nlong long get_low_saturation_score(const vector<vector<long long>>& board, int p, int q) {\n    long long score = 0;\n    for(int i = 0; i < 3; i++){\n        for(int j = 0; j < 3; j++){\n            long long mod_val = board[p+i][q+j] % MOD;\n            if(mod_val < MOD / 3) score += 2;\n            else if(mod_val < 2*MOD / 3) score += 1;\n        }\n    }\n    return score;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    \n    vector<vector<long long>> initial_board(N, vector<long long>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> initial_board[i][j];\n        }\n    }\n    \n    stamps.assign(M, vector<vector<long long>>(3, vector<long long>(3)));\n    vector<long long> stamp_total(M, 0);\n    \n    for(int m = 0; m < M; m++){\n        for(int i = 0; i < 3; i++){\n            for(int j = 0; j < 3; j++){\n                cin >> stamps[m][i][j];\n                stamp_total[m] += stamps[m][i][j];\n            }\n        }\n    }\n    \n    long long best_score = calculate_score(initial_board);\n    vector<tuple<int, int, int>> best_operations;\n    \n    // 280 trials with proven parameters from 3.417T version\n    for(int trial = 0; trial < 280; trial++){\n        mt19937 rng(trial * 1000003 + 2000003);\n        \n        auto board = initial_board;\n        vector<tuple<int, int, int>> operations;\n        map<int, double> stamp_frequency;\n        \n        // Proven diversification\n        int init_random;\n        if(trial < 80) {\n            init_random = (trial * 23) % (K / 2 + 1);\n        } else if(trial < 170) {\n            init_random = ((trial - 80) * 29) % (K / 3 + 1);\n        } else {\n            init_random = ((trial - 170) * 19) % (K / 4 + 1);\n        }\n        \n        // Random initialization phase\n        for(int i = 0; i < init_random; i++){\n            int m = (rng() % 4 == 0) ? \n                    (max_element(stamp_total.begin(), stamp_total.end()) - stamp_total.begin()) :\n                    (rng() % M);\n            int p = rng() % (N - 2);\n            int q = rng() % (N - 2);\n            apply_operation(board, m, p, q);\n            operations.push_back({m, p, q});\n            stamp_frequency[m] += 1.0;\n        }\n        \n        int consecutive_stuck = 0;\n        \n        // Greedy optimization phase with proven parameters\n        while((int)operations.size() < K && consecutive_stuck < 16){\n            vector<pair<long long, tuple<int,int,int>>> moves;\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                        long long d = delta_score(board, m, p, q);\n                        long long low_sat = get_low_saturation_score(board, p, q);\n                        \n                        // Proven stamp penalty\n                        long long stamp_penalty = (long long)(stamp_frequency[m] * 35000);\n                        \n                        long long score;\n                        int ops_size = (int)operations.size();\n                        \n                        if(ops_size < K/3) {\n                            // Early phase: delta-focused\n                            score = d + low_sat * 60000 - stamp_penalty;\n                        } else if(ops_size < 2*K/3) {\n                            // Mid phase: balanced\n                            score = d + low_sat * 150000 - stamp_penalty;\n                        } else {\n                            // Late phase: proven formula\n                            long long low_sat_score = low_sat * 350000;\n                            score = max(d, low_sat_score) + low_sat * 50000 - stamp_penalty;\n                        }\n                        \n                        moves.push_back({score, {m, p, q}});\n                    }\n                }\n            }\n            \n            sort(moves.rbegin(), moves.rend());\n            \n            long long best_delta = delta_score(board, get<0>(moves[0].second),\n                                              get<1>(moves[0].second),\n                                              get<2>(moves[0].second));\n            \n            if(best_delta > 0){\n                // Found improving move\n                consecutive_stuck = 0;\n                auto [m, p, q] = moves[0].second;\n                apply_operation(board, m, p, q);\n                operations.push_back({m, p, q});\n                stamp_frequency[m] += 1.0;\n            } else {\n                // Stuck - proven escape strategy\n                consecutive_stuck++;\n                if((int)operations.size() < K && consecutive_stuck <= 12){\n                    // Proven pool sizing\n                    int pool_size = min(70 + consecutive_stuck * 5, (int)moves.size());\n                    \n                    // Proven quadratic bias\n                    uniform_real_distribution<double> dist(0.0, 1.0);\n                    double rand_val = dist(rng);\n                    int idx = (int)(rand_val * rand_val * pool_size);\n                    idx = min(idx, pool_size - 1);\n                    \n                    auto [m, p, q] = moves[idx].second;\n                    apply_operation(board, m, p, q);\n                    operations.push_back({m, p, q});\n                    stamp_frequency[m] += 1.0;\n                    \n                    // Proven decay schedule\n                    if((int)operations.size() % 10 == 0){\n                        for(auto& [stamp_m, freq] : stamp_frequency){\n                            freq *= 0.9;\n                        }\n                    }\n                }\n            }\n        }\n        \n        long long score = calculate_score(board);\n        if(score > best_score){\n            best_score = score;\n            best_operations = operations;\n        }\n    }\n    \n    cout << best_operations.size() << \"\\n\";\n    for(auto [m, p, q] : best_operations){\n        cout << m << \" \" << p << \" \" << q << \"\\n\";\n    }\n    \n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<vector<int>> grid;\nvector<pair<int,int>> pos;\nvector<int> carry;\n\nint main(){\n    cin >> N;\n    \n    vector<vector<int>> A(N, vector<int>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> A[i][j];\n        }\n    }\n    \n    grid.assign(N, vector<int>(N, -1));\n    pos.resize(N);\n    carry.assign(N, -1);\n    \n    for(int i = 0; i < N; i++) pos[i] = {i, 0};\n    \n    vector<int> next_in(N, 0);\n    vector<string> res(N, \"\");\n    \n    for(int t = 0; t < 10000; t++){\n        // Step 1: Place arriving containers\n        for(int i = 0; i < N; i++){\n            if(next_in[i] < N && grid[i][0] == -1){\n                bool blocked = false;\n                for(int k = 0; k < N; k++){\n                    if(pos[k].first == i && pos[k].second == 0 && carry[k] != -1){\n                        blocked = true;\n                    }\n                }\n                if(!blocked){\n                    grid[i][0] = A[i][next_in[i]];\n                    next_in[i]++;\n                }\n            }\n        }\n        \n        // Step 2: Crane actions\n        vector<char> act(N);\n        vector<pair<int,int>> new_pos(N);\n        \n        for(int k = 0; k < N; k++){\n            auto [r, c] = pos[k];\n            \n            if(carry[k] >= 0){\n                int tr = carry[k] / N;\n                int tc = N - 1;\n                \n                if(r == tr && c == tc){\n                    act[k] = 'Q';\n                    new_pos[k] = {r, c};\n                } else if(tr == r){\n                    // Aligned: move right aggressively\n                    if(c < tc && grid[r][c+1] < 0){\n                        act[k] = 'R';\n                        new_pos[k] = {r, c+1};\n                    } else {\n                        act[k] = '.';\n                        new_pos[k] = {r, c};\n                    }\n                } else {\n                    // Misaligned: relay right, or release\n                    bool moved = false;\n                    if(c < N-1 && grid[r][c+1] < 0){\n                        act[k] = 'R';\n                        new_pos[k] = {r, c+1};\n                        moved = true;\n                    }\n                    if(!moved){\n                        act[k] = 'Q';\n                        new_pos[k] = {r, c};\n                    }\n                }\n            } else {\n                if(grid[r][c] >= 0){\n                    act[k] = 'P';\n                    new_pos[k] = {r, c};\n                } else {\n                    int best_priority = INT_MAX;\n                    pair<int,int> best_target = {r, c};\n                    \n                    for(int i = 0; i < N; i++){\n                        for(int j = 0; j < N; j++){\n                            if(grid[i][j] >= 0){\n                                int dist = abs(i - r) + abs(j - c);\n                                int priority;\n                                \n                                if(k == 0){\n                                    // Large crane: prioritize right side, then nearest\n                                    priority = -j * 10 + dist;\n                                } else {\n                                    // Small crane: prefer own row, prefer left side\n                                    int row_bonus = (i == k) ? 0 : 20;\n                                    priority = row_bonus + dist;\n                                }\n                                \n                                if(priority < best_priority){\n                                    best_priority = priority;\n                                    best_target = {i, j};\n                                }\n                            }\n                        }\n                    }\n                    \n                    if(best_target == make_pair(r, c)){\n                        act[k] = '.';\n                        new_pos[k] = {r, c};\n                    } else {\n                        bool moved = false;\n                        \n                        if(best_target.first > r && (k == 0 || grid[r+1][c] < 0)){\n                            act[k] = 'D';\n                            new_pos[k] = {r+1, c};\n                            moved = true;\n                        } else if(best_target.first < r && (k == 0 || grid[r-1][c] < 0)){\n                            act[k] = 'U';\n                            new_pos[k] = {r-1, c};\n                            moved = true;\n                        } else if(best_target.second > c && (k == 0 || grid[r][c+1] < 0)){\n                            act[k] = 'R';\n                            new_pos[k] = {r, c+1};\n                            moved = true;\n                        } else if(best_target.second < c && (k == 0 || grid[r][c-1] < 0)){\n                            act[k] = 'L';\n                            new_pos[k] = {r, c-1};\n                            moved = true;\n                        }\n                        \n                        if(!moved){\n                            act[k] = '.';\n                            new_pos[k] = {r, c};\n                        }\n                    }\n                }\n            }\n        }\n        \n        // Collision resolution\n        bool changed = true;\n        while(changed){\n            changed = false;\n            \n            map<pair<int,int>, vector<int>> dests;\n            for(int k = 0; k < N; k++){\n                if(act[k] != 'P' && act[k] != 'Q' && act[k] != '.'){\n                    dests[new_pos[k]].push_back(k);\n                }\n            }\n            \n            for(auto& [d, cranes] : dests){\n                if(cranes.size() > 1){\n                    int allowed = -1;\n                    for(int k : cranes){\n                        if(carry[k] >= 0){\n                            allowed = k;\n                            break;\n                        }\n                    }\n                    if(allowed == -1) allowed = cranes[0];\n                    \n                    for(int k : cranes){\n                        if(k != allowed){\n                            act[k] = '.';\n                            new_pos[k] = pos[k];\n                            changed = true;\n                        }\n                    }\n                }\n            }\n            \n            for(int k = 0; k < N; k++){\n                if(act[k] == 'P' || act[k] == 'Q' || act[k] == '.') continue;\n                for(int m = k+1; m < N; m++){\n                    if(act[m] == 'P' || act[m] == 'Q' || act[m] == '.') continue;\n                    if(new_pos[k] == pos[m] && new_pos[m] == pos[k]){\n                        act[k] = '.'; act[m] = '.';\n                        new_pos[k] = pos[k]; new_pos[m] = pos[m];\n                        changed = true;\n                    }\n                }\n            }\n            \n            for(int k = 0; k < N; k++){\n                if(act[k] == 'P' || act[k] == 'Q' || act[k] == '.') continue;\n                for(int m = 0; m < N; m++){\n                    if(m == k) continue;\n                    if(act[m] == 'P' || act[m] == 'Q' || act[m] == '.'){\n                        if(new_pos[k] == pos[m]){\n                            act[k] = '.';\n                            new_pos[k] = pos[k];\n                            changed = true;\n                        }\n                    }\n                }\n            }\n            \n            for(int k = 1; k < N; k++){\n                if(carry[k] == -1) continue;\n                if(act[k] == 'P' || act[k] == 'Q' || act[k] == '.') continue;\n                if(grid[new_pos[k].first][new_pos[k].second] >= 0){\n                    act[k] = '.';\n                    new_pos[k] = pos[k];\n                    changed = true;\n                }\n            }\n        }\n        \n        for(int k = 0; k < N; k++){\n            if(act[k] == 'P' && carry[k] == -1 && grid[pos[k].first][pos[k].second] >= 0){\n                carry[k] = grid[pos[k].first][pos[k].second];\n                grid[pos[k].first][pos[k].second] = -1;\n            }\n        }\n        \n        for(int k = 0; k < N; k++){\n            if(act[k] != 'P' && act[k] != 'Q' && act[k] != '.'){\n                pos[k] = new_pos[k];\n            }\n        }\n        \n        for(int k = 0; k < N; k++){\n            if(act[k] == 'Q' && carry[k] >= 0 && grid[pos[k].first][pos[k].second] == -1){\n                grid[pos[k].first][pos[k].second] = carry[k];\n                carry[k] = -1;\n            }\n        }\n        \n        for(int k = 0; k < N; k++) res[k] += act[k];\n        \n        // Step 3: Dispatch\n        for(int i = 0; i < N; i++){\n            if(grid[i][N-1] >= 0) grid[i][N-1] = -1;\n        }\n    }\n    \n    for(int i = 0; i < N; i++){\n        cout << res[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    \n    vector<vector<int>> h_original(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> h_original[i][j];\n        }\n    }\n    \n    auto attempt_pattern = [&](bool row_first, bool row_forward, bool col_forward) {\n        vector<string> operations;\n        vector<vector<int>> h = h_original;\n        int x = 0, y = 0;\n        int load = 0;\n        \n        auto move_to = [&](int nx, int ny) {\n            while (x != nx) {\n                operations.push_back(x < nx ? \"D\" : \"U\");\n                x += (x < nx ? 1 : -1);\n            }\n            while (y != ny) {\n                operations.push_back(y < ny ? \"R\" : \"L\");\n                y += (y < ny ? 1 : -1);\n            }\n        };\n        \n        auto process_rows = [&](bool forward) {\n            for (int i = 0; i < N; i++) {\n                bool go_lr = forward ? (i % 2 == 0) : (i % 2 == 1);\n                if (go_lr) {\n                    for (int j = 0; j < N; j++) {\n                        move_to(i, j);\n                        if (h[i][j] > 0) {\n                            operations.push_back(\"+\" + to_string(h[i][j]));\n                            load += h[i][j];\n                            h[i][j] = 0;\n                        } else if (h[i][j] < 0) {\n                            int unload = min(load, -h[i][j]);\n                            if (unload > 0) {\n                                operations.push_back(\"-\" + to_string(unload));\n                                load -= unload;\n                                h[i][j] += unload;\n                            }\n                        }\n                    }\n                } else {\n                    for (int j = N - 1; j >= 0; j--) {\n                        move_to(i, j);\n                        if (h[i][j] > 0) {\n                            operations.push_back(\"+\" + to_string(h[i][j]));\n                            load += h[i][j];\n                            h[i][j] = 0;\n                        } else if (h[i][j] < 0) {\n                            int unload = min(load, -h[i][j]);\n                            if (unload > 0) {\n                                operations.push_back(\"-\" + to_string(unload));\n                                load -= unload;\n                                h[i][j] += unload;\n                            }\n                        }\n                    }\n                }\n            }\n        };\n        \n        auto process_cols = [&](bool forward) {\n            for (int j = 0; j < N; j++) {\n                bool go_ud = forward ? (j % 2 == 0) : (j % 2 == 1);\n                if (go_ud) {\n                    for (int i = 0; i < N; i++) {\n                        move_to(i, j);\n                        if (h[i][j] > 0) {\n                            operations.push_back(\"+\" + to_string(h[i][j]));\n                            load += h[i][j];\n                            h[i][j] = 0;\n                        } else if (h[i][j] < 0) {\n                            int unload = min(load, -h[i][j]);\n                            if (unload > 0) {\n                                operations.push_back(\"-\" + to_string(unload));\n                                load -= unload;\n                                h[i][j] += unload;\n                            }\n                        }\n                    }\n                } else {\n                    for (int i = N - 1; i >= 0; i--) {\n                        move_to(i, j);\n                        if (h[i][j] > 0) {\n                            operations.push_back(\"+\" + to_string(h[i][j]));\n                            load += h[i][j];\n                            h[i][j] = 0;\n                        } else if (h[i][j] < 0) {\n                            int unload = min(load, -h[i][j]);\n                            if (unload > 0) {\n                                operations.push_back(\"-\" + to_string(unload));\n                                load -= unload;\n                                h[i][j] += unload;\n                            }\n                        }\n                    }\n                }\n            }\n        };\n        \n        if (row_first) {\n            process_rows(row_forward);\n            process_cols(col_forward);\n        } else {\n            process_cols(col_forward);\n            process_rows(row_forward);\n        }\n        \n        // Targeted cleanup of remaining imbalances\n        vector<tuple<int, int, int>> remaining;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (h[i][j] != 0) {\n                    remaining.push_back({abs(h[i][j]), i, j});\n                }\n            }\n        }\n        sort(remaining.rbegin(), remaining.rend());\n        \n        for (auto [mag, i, j] : remaining) {\n            if (h[i][j] == 0) continue;\n            move_to(i, j);\n            if (h[i][j] > 0) {\n                operations.push_back(\"+\" + to_string(h[i][j]));\n                load += h[i][j];\n                h[i][j] = 0;\n            } else if (h[i][j] < 0) {\n                int unload = min(load, -h[i][j]);\n                if (unload > 0) {\n                    operations.push_back(\"-\" + to_string(unload));\n                    load -= unload;\n                    h[i][j] += unload;\n                }\n            }\n        }\n        \n        long long cost = 0;\n        load = 0;\n        for (const auto& op : operations) {\n            if (op[0] == 'U' || op[0] == 'D' || op[0] == 'L' || op[0] == 'R') {\n                cost += 100 + load;\n            } else if (op[0] == '+') {\n                int amt = stoi(op.substr(1));\n                cost += amt;\n                load += amt;\n            } else if (op[0] == '-') {\n                int amt = stoi(op.substr(1));\n                cost += amt;\n                load -= amt;\n            }\n        }\n        \n        long long diff = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (h[i][j] != 0) {\n                    diff += 100LL * abs(h[i][j]) + 10000;\n                }\n            }\n        }\n        \n        return make_pair(operations, cost + diff);\n    };\n    \n    // Try all 8 possible 2-pass pattern combinations\n    vector<tuple<bool, bool, bool>> patterns = {\n        {true, true, true},      // (0,0,0)\n        {false, true, true},     // (0,0,1)\n        {true, false, true},     // (0,1,0)\n        {true, true, false},     // (0,1,1)\n        {false, false, true},    // (1,0,0)\n        {false, true, false},    // (1,0,1)\n        {true, false, false},    // (1,1,0) - newly added\n        {false, false, false},   // (1,1,1) - newly added\n    };\n    \n    long long best_score = LLONG_MAX;\n    vector<string> best_ops;\n    \n    for (auto [row_first, row_forward, col_forward] : patterns) {\n        auto [ops, score] = attempt_pattern(row_first, row_forward, col_forward);\n        if (score < best_score) {\n            best_score = score;\n            best_ops = ops;\n        }\n    }\n    \n    for (const auto& op : best_ops) {\n        cout << op << \"\\n\";\n    }\n    \n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <set>\n\nusing namespace std;\n\nint main() {\n    int N, M, T;\n    cin >> N >> M >> T;\n\n    int seed_count = 2 * N * (N - 1);\n    vector<vector<int>> X(seed_count, vector<int>(M));\n\n    for (int i = 0; i < seed_count; i++) {\n        for (int j = 0; j < M; j++) {\n            cin >> X[i][j];\n        }\n    }\n\n    vector<pair<int, int>> position_order;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            position_order.push_back({i, j});\n        }\n    }\n    \n    sort(position_order.begin(), position_order.end(), [&](const auto& a, const auto& b) {\n        auto neighbor_count = [&](const pair<int,int>& p) {\n            return (p.first > 0) + (p.first < N-1) + (p.second > 0) + (p.second < N-1);\n        };\n        return neighbor_count(a) > neighbor_count(b);\n    });\n\n    for (int t = 0; t < T; t++) {\n        vector<long long> values(seed_count, 0);\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                values[i] += X[i][j];\n            }\n        }\n        \n        set<int> selected_set;\n        \n        // Adaptive K based on round: promote diversity early, exploit later\n        int K = (t < 6) ? 2 : 1;  // K=2 for rounds 0-5, K=1 for rounds 6-9\n        \n        // K-selection: Select top K seeds per criterion\n        for (int crit = 0; crit < M; crit++) {\n            if (selected_set.size() >= (size_t)(N * N)) break;\n            \n            vector<int> seeds_for_crit(seed_count);\n            iota(seeds_for_crit.begin(), seeds_for_crit.end(), 0);\n            \n            sort(seeds_for_crit.begin(), seeds_for_crit.end(), [&](int a, int b) {\n                if (X[a][crit] != X[b][crit]) {\n                    return X[a][crit] > X[b][crit];\n                }\n                return values[a] > values[b];\n            });\n            \n            for (int i = 0; i < K && i < seed_count; i++) {\n                if (selected_set.size() >= (size_t)(N * N)) break;\n                selected_set.insert(seeds_for_crit[i]);\n            }\n        }\n        \n        // Fill remaining slots with highest total-value seeds\n        if (selected_set.size() < (size_t)(N * N)) {\n            vector<int> sorted_by_value(seed_count);\n            iota(sorted_by_value.begin(), sorted_by_value.end(), 0);\n            sort(sorted_by_value.begin(), sorted_by_value.end(), [&](int a, int b) {\n                return values[a] > values[b];\n            });\n            \n            for (int seed_id : sorted_by_value) {\n                if (selected_set.size() >= (size_t)(N * N)) break;\n                selected_set.insert(seed_id);\n            }\n        }\n\n        // Convert to vector and sort with proven tiebreakers\n        vector<int> selected_seeds(selected_set.begin(), selected_set.end());\n        sort(selected_seeds.begin(), selected_seeds.end(), [&](int a, int b) {\n            // Primary: total value\n            if (values[a] != values[b]) {\n                return values[a] > values[b];\n            }\n            // Secondary: maximum criterion value\n            int max_a = *max_element(X[a].begin(), X[a].end());\n            int max_b = *max_element(X[b].begin(), X[b].end());\n            if (max_a != max_b) {\n                return max_a > max_b;\n            }\n            // Tertiary: minimum criterion value\n            int min_a = *min_element(X[a].begin(), X[a].end());\n            int min_b = *min_element(X[b].begin(), X[b].end());\n            return min_a > min_b;\n        });\n\n        // Assign to grid\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (size_t idx = 0; idx < selected_seeds.size(); idx++) {\n            int seed_id = selected_seeds[idx];\n            int pos_i = position_order[idx].first;\n            int pos_j = position_order[idx].second;\n            grid[pos_i][pos_j] = seed_id;\n        }\n\n        // Output grid\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (j > 0) cout << \" \";\n                cout << grid[i][j];\n            }\n            cout << \"\\n\";\n        }\n        cout.flush();\n\n        // Read new generation seeds\n        for (int i = 0; i < seed_count; i++) {\n            for (int j = 0; j < M; j++) {\n                cin >> X[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, V;\n    cin >> N >> M >> V;\n    \n    vector<string> s(N), t(N);\n    for(int i = 0; i < N; i++) cin >> s[i];\n    for(int i = 0; i < N; i++) cin >> t[i];\n    \n    cout << \"2\\n\";\n    cout << \"0 1\\n\";\n    \n    vector<pair<int,int>> to_clear, to_fill;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(s[i][j] == '1' && t[i][j] == '0') to_clear.push_back({i, j});\n            if(s[i][j] == '0' && t[i][j] == '1') to_fill.push_back({i, j});\n        }\n    }\n    \n    long long sum_x = 0, sum_y = 0;\n    for(auto [x, y] : to_clear){\n        sum_x += x;\n        sum_y += y;\n    }\n    int start_x = sum_x / to_clear.size();\n    int start_y = sum_y / to_clear.size();\n    start_x = max(0, min(N-1, start_x));\n    start_y = max(0, min(N-1, start_y));\n    \n    cout << start_x << \" \" << start_y << \"\\n\";\n    \n    int rx = start_x, ry = start_y;\n    int rot = 0;\n    int turns = 0;\n    \n    vector<vector<int>> grid(N, vector<int>(N, 0));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            grid[i][j] = (s[i][j] == '1') ? 1 : 0;\n        }\n    }\n    \n    auto get_finger = [&]() -> pair<int,int> {\n        if(rot == 0) return {rx, ry + 1};\n        if(rot == 1) return {rx + 1, ry};\n        if(rot == 2) return {rx, ry - 1};\n        return {rx - 1, ry};\n    };\n    \n    auto move_to = [&](int tx, int ty) {\n        int best_rot = rot;\n        for(int r = 0; r < 4; r++){\n            int req_rx = tx, req_ry = ty;\n            if(r == 0) req_ry--;\n            else if(r == 1) req_rx--;\n            else if(r == 2) req_ry++;\n            else req_rx++;\n            \n            if(req_rx >= 0 && req_rx < N && req_ry >= 0 && req_ry < N){\n                best_rot = r;\n                break;\n            }\n        }\n        \n        while(rot != best_rot && turns < 100000){\n            string op = \"....\";\n            int diff = (best_rot - rot + 4) % 4;\n            op[1] = (diff <= 2) ? 'R' : 'L';\n            rot = (diff <= 2) ? (rot + 1) % 4 : (rot + 3) % 4;\n            cout << op << \"\\n\";\n            turns++;\n        }\n        \n        while(turns < 100000){\n            auto [fx, fy] = get_finger();\n            if(fx == tx && fy == ty) break;\n            \n            string op = \"....\";\n            int req_rx = tx, req_ry = ty;\n            if(rot == 0) req_ry--;\n            else if(rot == 1) req_rx--;\n            else if(rot == 2) req_ry++;\n            else req_rx++;\n            \n            if(rx < req_rx) { rx++; op[0] = 'D'; }\n            else if(rx > req_rx) { rx--; op[0] = 'U'; }\n            else if(ry < req_ry) { ry++; op[0] = 'R'; }\n            else if(ry > req_ry) { ry--; op[0] = 'L'; }\n            \n            cout << op << \"\\n\";\n            turns++;\n        }\n    };\n    \n    int n_src = to_clear.size();\n    int n_tgt = to_fill.size();\n    vector<vector<int>> cost(n_src, vector<int>(n_tgt));\n    \n    for(int i = 0; i < n_src; i++){\n        for(int j = 0; j < n_tgt; j++){\n            cost[i][j] = abs(to_clear[i].first - to_fill[j].first) + \n                        abs(to_clear[i].second - to_fill[j].second);\n        }\n    }\n    \n    vector<bool> src_used(n_src, false);\n    vector<bool> tgt_used(n_tgt, false);\n    vector<pair<int,int>> matching;\n    \n    for(int iter = 0; iter < n_src; iter++){\n        int best_i = -1, best_j = -1;\n        int best_cost = INT_MAX;\n        \n        for(int i = 0; i < n_src; i++){\n            if(src_used[i]) continue;\n            for(int j = 0; j < n_tgt; j++){\n                if(tgt_used[j]) continue;\n                if(cost[i][j] < best_cost){\n                    best_cost = cost[i][j];\n                    best_i = i;\n                    best_j = j;\n                }\n            }\n        }\n        \n        if(best_i != -1){\n            matching.push_back({best_i, best_j});\n            src_used[best_i] = true;\n            tgt_used[best_j] = true;\n        }\n    }\n    \n    // Helper to compute tour distance\n    auto tour_dist = [&](const vector<int>& tour) {\n        int dist = abs(to_clear[matching[tour[0]].first].first - start_x) +\n                   abs(to_clear[matching[tour[0]].first].second - start_y);\n        for(int i = 0; i < (int)tour.size() - 1; i++){\n            int sx1 = to_clear[matching[tour[i]].first].first;\n            int sy1 = to_clear[matching[tour[i]].first].second;\n            int sx2 = to_clear[matching[tour[i+1]].first].first;\n            int sy2 = to_clear[matching[tour[i+1]].first].second;\n            dist += abs(sx1 - sx2) + abs(sy1 - sy2);\n        }\n        return dist;\n    };\n    \n    // Build initial NN tour\n    vector<int> tour;\n    vector<bool> used(matching.size(), false);\n    int cur_x = start_x, cur_y = start_y;\n    \n    while((int)tour.size() < (int)matching.size()){\n        int best_idx = -1;\n        int best_dist = INT_MAX;\n        \n        for(int i = 0; i < (int)matching.size(); i++){\n            if(used[i]) continue;\n            int sx = to_clear[matching[i].first].first;\n            int sy = to_clear[matching[i].first].second;\n            int dist = abs(sx - cur_x) + abs(sy - cur_y);\n            if(dist < best_dist){\n                best_dist = dist;\n                best_idx = i;\n            }\n        }\n        \n        if(best_idx != -1){\n            used[best_idx] = true;\n            tour.push_back(best_idx);\n            cur_x = to_clear[matching[best_idx].first].first;\n            cur_y = to_clear[matching[best_idx].first].second;\n        }\n    }\n    \n    // 2-opt improvement (aggressive)\n    bool improved = true;\n    int passes = 0;\n    while(improved && passes < 30){\n        improved = false;\n        passes++;\n        \n        for(int i = 0; i < (int)tour.size() - 1; i++){\n            for(int j = i + 2; j < (int)tour.size(); j++){\n                int idx_i = tour[i];\n                int idx_i1 = tour[i+1];\n                int idx_j = tour[j];\n                int idx_j1 = tour[(j+1) % tour.size()];\n                \n                int sx_i = to_clear[matching[idx_i].first].first;\n                int sy_i = to_clear[matching[idx_i].first].second;\n                int sx_i1 = to_clear[matching[idx_i1].first].first;\n                int sy_i1 = to_clear[matching[idx_i1].first].second;\n                int sx_j = to_clear[matching[idx_j].first].first;\n                int sy_j = to_clear[matching[idx_j].first].second;\n                int sx_j1 = to_clear[matching[idx_j1].first].first;\n                int sy_j1 = to_clear[matching[idx_j1].first].second;\n                \n                int dist_before = abs(sx_i - sx_i1) + abs(sy_i - sy_i1) + \n                                 abs(sx_j - sx_j1) + abs(sy_j - sy_j1);\n                int dist_after = abs(sx_i - sx_j) + abs(sy_i - sy_j) + \n                                abs(sx_i1 - sx_j1) + abs(sy_i1 - sy_j1);\n                \n                if(dist_after < dist_before){\n                    reverse(tour.begin() + i + 1, tour.begin() + j + 1);\n                    improved = true;\n                }\n            }\n        }\n    }\n    \n    // Or-opt moves (move chains of 1-3 items)\n    improved = true;\n    passes = 0;\n    while(improved && passes < 20){\n        improved = false;\n        passes++;\n        \n        for(int chain_len = 1; chain_len <= 3 && !improved; chain_len++){\n            for(int i = 0; i < (int)tour.size(); i++){\n                if(i + chain_len > (int)tour.size()) break;\n                \n                // Try moving chain [i, i+chain_len) to each position\n                for(int j = 0; j < (int)tour.size(); j++){\n                    if(j >= i && j <= i + chain_len) continue;\n                    \n                    // Create modified tour\n                    vector<int> new_tour;\n                    for(int k = 0; k < (int)tour.size(); k++){\n                        if(k >= i && k < i + chain_len) continue;\n                        if(k == j) {\n                            for(int l = i; l < i + chain_len; l++){\n                                new_tour.push_back(tour[l]);\n                            }\n                        }\n                        new_tour.push_back(tour[k]);\n                    }\n                    if(j > i + chain_len){\n                        for(int l = i; l < i + chain_len; l++){\n                            new_tour.push_back(tour[l]);\n                        }\n                    }\n                    \n                    if(new_tour.size() != tour.size()) continue;\n                    \n                    if(tour_dist(new_tour) < tour_dist(tour)){\n                        tour = new_tour;\n                        improved = true;\n                        break;\n                    }\n                }\n                if(improved) break;\n            }\n        }\n    }\n    \n    // Execute optimized tour\n    for(int idx : tour){\n        if(turns >= 100000) break;\n        \n        auto [src_idx, tgt_idx] = matching[idx];\n        auto [sx, sy] = to_clear[src_idx];\n        auto [tx, ty] = to_fill[tgt_idx];\n        \n        if(grid[sx][sy] == 0) continue;\n        \n        move_to(sx, sy);\n        if(turns >= 100000) break;\n        \n        cout << \"...P\\n\";\n        grid[sx][sy] = 0;\n        turns++;\n        \n        move_to(tx, ty);\n        if(turns >= 100000) break;\n        \n        cout << \"...P\\n\";\n        grid[tx][ty] = 1;\n        turns++;\n    }\n    \n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<pair<int, int>> mackerel, sardine;\n\nint count_score(int x1, int y1, int x2, int y2) {\n    if(x1 > x2 || y1 > y2) return -1000000;\n    int m = 0, s = 0;\n    for(auto [x, y] : mackerel) {\n        if(x >= x1 && x <= x2 && y >= y1 && y <= y2) m++;\n    }\n    for(auto [x, y] : sardine) {\n        if(x >= x1 && x <= x2 && y >= y1 && y <= y2) s++;\n    }\n    return m - s;\n}\n\nint optimize(int& x1, int& y1, int& x2, int& y2, int max_total_iters) {\n    int score = count_score(x1, y1, x2, y2);\n    \n    vector<int> steps = {5000, 2500, 1000, 500, 100, 50, 10, 1};\n    int total_iters = 0;\n    \n    for(int step : steps) {\n        int max_iters_this_step;\n        if(step >= 2500) max_iters_this_step = 6;\n        else if(step >= 1000) max_iters_this_step = 8;\n        else if(step >= 100) max_iters_this_step = 12;\n        else if(step >= 10) max_iters_this_step = 18;\n        else max_iters_this_step = 100;  // step == 1, more aggressive fine-tuning\n        \n        bool improved = true;\n        int iter_count = 0;\n        \n        while(improved && iter_count < max_iters_this_step && total_iters < max_total_iters) {\n            improved = false;\n            iter_count++;\n            total_iters++;\n            \n            // Best-improvement: try all moves and pick the best\n            int best_score = score;\n            int best_x1 = x1, best_y1 = y1, best_x2 = x2, best_y2 = y2;\n            \n            vector<tuple<int,int,int,int>> moves = {\n                {x1 + step, y1, x2, y2},\n                {x1 - step, y1, x2, y2},\n                {x1, y1 + step, x2, y2},\n                {x1, y1 - step, x2, y2},\n                {x1, y1, x2 - step, y2},\n                {x1, y1, x2 + step, y2},\n                {x1, y1, x2, y2 - step},\n                {x1, y1, x2, y2 + step}\n            };\n            \n            for(auto [nx1, ny1, nx2, ny2] : moves) {\n                if(nx1 >= 0 && ny1 >= 0 && nx2 <= 100000 && ny2 <= 100000 && nx1 < nx2 && ny1 < ny2) {\n                    int ns = count_score(nx1, ny1, nx2, ny2);\n                    if(ns > best_score) {\n                        best_score = ns;\n                        best_x1 = nx1;\n                        best_y1 = ny1;\n                        best_x2 = nx2;\n                        best_y2 = ny2;\n                    }\n                }\n            }\n            \n            if(best_score > score) {\n                score = best_score;\n                x1 = best_x1;\n                y1 = best_y1;\n                x2 = best_x2;\n                y2 = best_y2;\n                improved = true;\n            }\n        }\n    }\n    \n    return score;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    mackerel.resize(N);\n    sardine.resize(N);\n    \n    int min_mx = INT_MAX, max_mx = INT_MIN, min_my = INT_MAX, max_my = INT_MIN;\n    long long sum_x = 0, sum_y = 0;\n    \n    for(int i = 0; i < N; i++){\n        cin >> mackerel[i].first >> mackerel[i].second;\n        min_mx = min(min_mx, mackerel[i].first);\n        max_mx = max(max_mx, mackerel[i].first);\n        min_my = min(min_my, mackerel[i].second);\n        max_my = max(max_my, mackerel[i].second);\n        sum_x += mackerel[i].first;\n        sum_y += mackerel[i].second;\n    }\n    \n    int cx = sum_x / N;\n    int cy = sum_y / N;\n    \n    for(int i = 0; i < N; i++){\n        cin >> sardine[i].first >> sardine[i].second;\n    }\n    \n    int best_score = -1000000;\n    int best_x1 = 0, best_y1 = 0, best_x2 = 100000, best_y2 = 100000;\n    \n    // Comprehensive diverse starting points\n    vector<tuple<int,int,int,int>> starts;\n    \n    // Mackerel bbox with fine-grained systematic expansions\n    for(int exp = 0; exp <= 18000; exp += 1500) {\n        int nx1 = max(0, min_mx - exp);\n        int ny1 = max(0, min_my - exp);\n        int nx2 = min(100000, max_mx + exp);\n        int ny2 = min(100000, max_my + exp);\n        if(nx1 < nx2 && ny1 < ny2) {\n            starts.push_back({nx1, ny1, nx2, ny2});\n        }\n    }\n    \n    // Center-based boxes with various radii\n    for(int r = 5000; r <= 50000; r += 5000) {\n        int nx1 = max(0, cx - r);\n        int ny1 = max(0, cy - r);\n        int nx2 = min(100000, cx + r);\n        int ny2 = min(100000, cy + r);\n        if(nx1 < nx2 && ny1 < ny2) {\n            starts.push_back({nx1, ny1, nx2, ny2});\n        }\n    }\n    \n    // Offset grid pattern from center\n    for(int dx = -1; dx <= 1; dx++) {\n        for(int dy = -1; dy <= 1; dy++) {\n            int offset_x = dx * 20000;\n            int offset_y = dy * 20000;\n            int nx1 = max(0, cx + offset_x - 18000);\n            int ny1 = max(0, cy + offset_y - 18000);\n            int nx2 = min(100000, cx + offset_x + 18000);\n            int ny2 = min(100000, cy + offset_y + 18000);\n            if(nx1 < nx2 && ny1 < ny2) {\n                starts.push_back({nx1, ny1, nx2, ny2});\n            }\n        }\n    }\n    \n    // Full area and quadrants\n    starts.push_back({0, 0, 100000, 100000});\n    starts.push_back({0, 0, 50000, 50000});\n    starts.push_back({50000, 0, 100000, 50000});\n    starts.push_back({0, 50000, 50000, 100000});\n    starts.push_back({50000, 50000, 100000, 100000});\n    \n    // Add more random starting rectangles for better coverage\n    srand(12345);  // Fixed seed for deterministic behavior\n    for(int i = 0; i < 15; i++) {\n        int rx1 = rand() % 70000;\n        int ry1 = rand() % 70000;\n        int rx2 = rx1 + 10000 + (rand() % 30000);\n        int ry2 = ry1 + 10000 + (rand() % 30000);\n        rx2 = min(100000, rx2);\n        ry2 = min(100000, ry2);\n        if(rx1 < rx2 && ry1 < ry2) {\n            starts.push_back({rx1, ry1, rx2, ry2});\n        }\n    }\n    \n    // Optimize from all starting points\n    for(auto [x1, y1, x2, y2] : starts) {\n        if(x1 < x2 && y1 < y2) {\n            int score = optimize(x1, y1, x2, y2, 400);\n            if(score > best_score) {\n                best_score = score;\n                best_x1 = x1;\n                best_y1 = y1;\n                best_x2 = x2;\n                best_y2 = y2;\n            }\n        }\n    }\n    \n    cout << 4 << \"\\n\";\n    cout << best_x1 << \" \" << best_y1 << \"\\n\";\n    cout << best_x2 << \" \" << best_y1 << \"\\n\";\n    cout << best_x2 << \" \" << best_y2 << \"\\n\";\n    cout << best_x1 << \" \" << best_y2 << \"\\n\";\n    \n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\npair<long long, long long> simulate(\n    const vector<tuple<int, int, char, int>>& placement,\n    const vector<pair<long long, long long>>& rects\n) {\n    map<int, array<long long, 4>> pos;\n    long long max_x = 0, max_y = 0;\n    \n    for (auto [idx, rot, dir, ref] : placement) {\n        long long w = rects[idx].first;\n        long long h = rects[idx].second;\n        if (rot) swap(w, h);\n        \n        long long x = 0, y = 0;\n        \n        if (dir == 'U') {\n            if (ref != -1 && pos.count(ref)) {\n                x = pos[ref][0] + pos[ref][2];\n            }\n            for (auto& [i, p] : pos) {\n                if (p[0] < x + w && x < p[0] + p[2]) {\n                    y = max(y, p[1] + p[3]);\n                }\n            }\n        } else {\n            if (ref != -1 && pos.count(ref)) {\n                y = pos[ref][1] + pos[ref][3];\n            }\n            for (auto& [i, p] : pos) {\n                if (p[1] < y + h && y < p[1] + p[3]) {\n                    x = max(x, p[0] + p[2]);\n                }\n            }\n        }\n        \n        pos[idx] = {x, y, w, h};\n        max_x = max(max_x, x + w);\n        max_y = max(max_y, y + h);\n    }\n    \n    return {max_x, max_y};\n}\n\nlong long calc_score(\n    const vector<tuple<int, int, char, int>>& placement,\n    const vector<pair<long long, long long>>& rects,\n    int N\n) {\n    auto [w, h] = simulate(placement, rects);\n    long long cost = w + h;\n    \n    set<int> used;\n    for (auto [p, r, d, b] : placement) {\n        used.insert(p);\n    }\n    \n    for (int i = 0; i < N; i++) {\n        if (!used.count(i)) {\n            cost += rects[i].first + rects[i].second;\n        }\n    }\n    \n    return cost;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, T;\n    long long sigma;\n    cin >> N >> T >> sigma;\n    \n    vector<pair<long long, long long>> rects(N);\n    for (int i = 0; i < N; i++) {\n        cin >> rects[i].first >> rects[i].second;\n    }\n    \n    mt19937 rng(987654321);\n    auto start_time = chrono::high_resolution_clock::now();\n    \n    for (int t = 0; t < T; t++) {\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(\n            chrono::high_resolution_clock::now() - start_time).count();\n        \n        if (elapsed > 2850) {\n            vector<tuple<int, int, char, int>> p;\n            for (int i = 0; i < N; i++) {\n                p.push_back({i, 0, 'U', -1});\n            }\n            cout << p.size() << \"\\n\";\n            for (auto [a, b, c, d] : p) {\n                cout << a << \" \" << b << \" \" << c << \" \" << d << \"\\n\";\n            }\n            cout.flush();\n            long long W, H;\n            cin >> W >> H;\n            break;\n        }\n        \n        long long best_score = LLONG_MAX;\n        vector<tuple<int, int, char, int>> best_placement;\n        \n        // === CORE DETERMINISTIC STRATEGIES ===\n        vector<vector<tuple<int, int, char, int>>> deterministic_strategies;\n        \n        // All U with -1\n        {\n            vector<tuple<int, int, char, int>> p;\n            for (int i = 0; i < N; i++) p.push_back({i, 0, 'U', -1});\n            deterministic_strategies.push_back(p);\n        }\n        \n        // All L with -1\n        {\n            vector<tuple<int, int, char, int>> p;\n            for (int i = 0; i < N; i++) p.push_back({i, 0, 'L', -1});\n            deterministic_strategies.push_back(p);\n        }\n        \n        // Alternating U/L with -1\n        {\n            vector<tuple<int, int, char, int>> p;\n            for (int i = 0; i < N; i++) {\n                char d = (i % 2) ? 'L' : 'U';\n                p.push_back({i, 0, d, -1});\n            }\n            deterministic_strategies.push_back(p);\n        }\n        \n        // Staircase U (sequential refs)\n        {\n            vector<tuple<int, int, char, int>> p;\n            for (int i = 0; i < N; i++) {\n                int b = (i > 0) ? (i - 1) : -1;\n                p.push_back({i, 0, 'U', b});\n            }\n            deterministic_strategies.push_back(p);\n        }\n        \n        // Staircase L (sequential refs)\n        {\n            vector<tuple<int, int, char, int>> p;\n            for (int i = 0; i < N; i++) {\n                int b = (i > 0) ? (i - 1) : -1;\n                p.push_back({i, 0, 'L', b});\n            }\n            deterministic_strategies.push_back(p);\n        }\n        \n        for (auto& p : deterministic_strategies) {\n            long long score = calc_score(p, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = p;\n            }\n        }\n        \n        // === INTEGRATED RANDOM ATTEMPTS (420) ===\n        int num_random = 420;\n        for (int att = 0; att < num_random; att++) {\n            vector<tuple<int, int, char, int>> placement;\n            \n            // Size pattern: 42 different patterns with better granularity\n            int size_pattern = att % 42;\n            int use_count;\n            \n            if (size_pattern < 20) {\n                // Small sizes 1-20: comprehensive coverage\n                use_count = size_pattern + 1;\n            } else if (size_pattern < 35) {\n                // Medium sizes: 20 to ~72 in steps of ~3.5\n                int base = 20 + (size_pattern - 20) * 4;\n                use_count = min(N, base + (int)(rng() % max(1, N / 5)));\n            } else {\n                // Large sizes: N/2 to N\n                use_count = min(N, N / 2 + (int)(rng() % (N / 2 + 1)));\n            }\n            \n            for (int i = 0; i < use_count; i++) {\n                // Rotation: aspect ratio aware\n                int r = (int)(rng() % 2);\n                if (rects[i].first > 0 && rects[i].second > 0) {\n                    long long longer = max(rects[i].first, rects[i].second);\n                    long long shorter = min(rects[i].first, rects[i].second);\n                    if (longer > shorter * 2) {\n                        r = (int)(rng() % 4) == 0 ? 1 : 0;\n                    }\n                }\n                \n                // Direction: 7 structured patterns\n                char d;\n                int dir_choice = (int)(rng() % 7);\n                if (dir_choice == 0) {\n                    d = 'U';\n                } else if (dir_choice == 1) {\n                    d = 'L';\n                } else if (dir_choice == 2) {\n                    d = (i % 2) ? 'L' : 'U';\n                } else if (dir_choice == 3) {\n                    d = (i % 3 == 0) ? 'L' : 'U';\n                } else if (dir_choice == 4) {\n                    d = ((i + 1) % 4 < 2) ? 'U' : 'L';\n                } else if (dir_choice == 5) {\n                    d = (i < use_count / 2) ? 'U' : 'L';\n                } else {\n                    d = (i < use_count / 3) ? 'L' : 'U';\n                }\n                \n                // Reference: 8 structured patterns\n                int b = -1;\n                if (i > 0) {\n                    int ref_choice = (int)(rng() % 8);\n                    if (ref_choice == 0) {\n                        b = -1;\n                    } else if (ref_choice == 1) {\n                        b = i - 1;\n                    } else if (ref_choice == 2) {\n                        int max_back = min(i, 3);\n                        b = i - 1 - (int)(rng() % max_back);\n                    } else if (ref_choice == 3) {\n                        int max_back = min(i, i / 2 + 1);\n                        b = i - 1 - (int)(rng() % max_back);\n                    } else if (ref_choice == 4) {\n                        b = (int)(rng() % i);\n                    } else if (ref_choice == 5) {\n                        b = i / 2;\n                    } else if (ref_choice == 6) {\n                        int skip = (i / 3) + 1;\n                        if (i >= skip) b = i - skip;\n                        else b = -1;\n                    } else {\n                        int targets = min(i, 5);\n                        b = (int)(rng() % targets);\n                    }\n                }\n                \n                placement.push_back({i, r, d, b});\n            }\n            \n            long long score = calc_score(placement, rects, N);\n            if (score < best_score) {\n                best_score = score;\n                best_placement = placement;\n            }\n        }\n        \n        cout << best_placement.size() << \"\\n\";\n        for (auto [p, r, d, b] : best_placement) {\n            cout << p << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        }\n        cout.flush();\n        \n        long long W, H;\n        cin >> W >> H;\n    }\n    \n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, H;\nvector<int> A;\nvector<vector<int>> adj;\nvector<double> x, y;\n\nlong long evaluateSolution(const vector<int>& parent) {\n    vector<int> depth(N, -1);\n    queue<int> q;\n    \n    for(int i = 0; i < N; i++){\n        if(parent[i] == -1){\n            depth[i] = 0;\n            q.push(i);\n        }\n    }\n    \n    long long score = 0;\n    while(!q.empty()){\n        int u = q.front();\n        q.pop();\n        score += (long long)(depth[u] + 1) * A[u];\n        \n        for(int v : adj[u]){\n            if(parent[v] == u && depth[v] == -1){\n                depth[v] = depth[u] + 1;\n                q.push(v);\n            }\n        }\n    }\n    return score;\n}\n\nvector<int> buildTreeBFS(const vector<int>& rootOrder, double beautyWeight) {\n    vector<int> parent(N, -2);\n    \n    for(int root : rootOrder){\n        if(parent[root] != -2) continue;\n        \n        queue<int> q;\n        q.push(root);\n        parent[root] = -1;\n        vector<int> depth(N, -1);\n        depth[root] = 0;\n        \n        while(!q.empty()){\n            int u = q.front();\n            q.pop();\n            \n            if(depth[u] >= H) continue;\n            \n            vector<pair<double, int>> neighbors;\n            for(int v : adj[u]){\n                if(parent[v] == -2){\n                    double score = A[v] * beautyWeight + adj[v].size() * (1.0 - beautyWeight);\n                    neighbors.push_back({score, v});\n                }\n            }\n            \n            sort(neighbors.rbegin(), neighbors.rend());\n            \n            for(auto [_, v] : neighbors){\n                parent[v] = u;\n                depth[v] = depth[u] + 1;\n                q.push(v);\n            }\n        }\n    }\n    return parent;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int H_input;\n    cin >> N >> M >> H_input;\n    H = H_input;\n    \n    A.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> A[i];\n    }\n    \n    adj.resize(N);\n    for(int i = 0; i < M; i++){\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    x.resize(N);\n    y.resize(N);\n    for(int i = 0; i < N; i++){\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<int> best_parent(N);\n    long long best_score = -1;\n    \n    auto tryOrder = [&](const vector<int>& ord, double beautyWeight = 1.0) {\n        auto parent = buildTreeBFS(ord, beautyWeight);\n        long long score = evaluateSolution(parent);\n        if(score > best_score){\n            best_score = score;\n            best_parent = parent;\n        }\n    };\n    \n    vector<int> order(N);\n    \n    // Core proven heuristics - with focused neighbor weights\n    vector<double> coreWeights = {0.0, 0.3, 0.5, 0.7, 1.0};\n    vector<double> fineWeights = {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};\n    \n    // Beauty-sorted - full fine weights\n    {\n        sort(order.begin(), order.end(), [&](int a, int b){ return A[a] > A[b]; });\n        for(double w : fineWeights) tryOrder(order, w);\n    }\n    \n    iota(order.begin(), order.end(), 0);\n    \n    // Degree-sorted\n    {\n        sort(order.begin(), order.end(), [&](int a, int b){ return adj[a].size() > adj[b].size(); });\n        for(double w : coreWeights) tryOrder(order, w);\n    }\n    \n    iota(order.begin(), order.end(), 0);\n    \n    // Reverse beauty\n    {\n        sort(order.begin(), order.end(), [&](int a, int b){ return A[a] < A[b]; });\n        for(double w : coreWeights) tryOrder(order, w);\n    }\n    \n    iota(order.begin(), order.end(), 0);\n    \n    // Beauty powers\n    for(int power = 1; power <= 3; power++){\n        sort(order.begin(), order.end(), [&](int a, int b){\n            long long pa = 1, pb = 1;\n            for(int p = 0; p < power; p++){\n                pa *= A[a]; pb *= A[b];\n            }\n            return pa > pb;\n        });\n        for(double w : coreWeights) tryOrder(order, w);\n        iota(order.begin(), order.end(), 0);\n    }\n    \n    // Degree powers\n    for(int power = 1; power <= 2; power++){\n        sort(order.begin(), order.end(), [&](int a, int b){\n            long long da = 1, db = 1;\n            for(int p = 0; p < power; p++){\n                da *= (1 + adj[a].size()); db *= (1 + adj[b].size());\n            }\n            return da > db;\n        });\n        for(double w : coreWeights) tryOrder(order, w);\n        iota(order.begin(), order.end(), 0);\n    }\n    \n    // Root weight combinations - fine-grained\n    for(double rootWeight = -2.0; rootWeight <= 2.05; rootWeight += 0.1){\n        sort(order.begin(), order.end(), [&](int a, int b){\n            double sa = A[a] + rootWeight * adj[a].size();\n            double sb = A[b] + rootWeight * adj[b].size();\n            return sa > sb;\n        });\n        for(double w : coreWeights) tryOrder(order, w);\n        iota(order.begin(), order.end(), 0);\n    }\n    \n    // Beauty * pow(degree+1, w)\n    for(double w = 0.0; w <= 1.51; w += 0.15){\n        sort(order.begin(), order.end(), [&](int a, int b){\n            double sa = A[a] * pow(1.0 + adj[a].size(), w);\n            double sb = A[b] * pow(1.0 + adj[b].size(), w);\n            return sa > sb;\n        });\n        for(double nw = 0.3; nw <= 0.71; nw += 0.2){\n            tryOrder(order, nw);\n        }\n        iota(order.begin(), order.end(), 0);\n    }\n    \n    // Ratio metrics\n    {\n        sort(order.begin(), order.end(), [&](int a, int b){\n            double sa = (double)A[a] / (1.0 + adj[a].size());\n            double sb = (double)A[b] / (1.0 + adj[b].size());\n            return sa > sb;\n        });\n        for(double w : coreWeights) tryOrder(order, w);\n        iota(order.begin(), order.end(), 0);\n    }\n    \n    // Logarithmic\n    {\n        sort(order.begin(), order.end(), [&](int a, int b){\n            double sa = A[a] * log(2.0 + adj[a].size());\n            double sb = A[b] * log(2.0 + adj[b].size());\n            return sa > sb;\n        });\n        for(double w : coreWeights) tryOrder(order, w);\n        iota(order.begin(), order.end(), 0);\n    }\n    \n    // Geometric\n    {\n        double cx = 500, cy = 500;\n        sort(order.begin(), order.end(), [&](int a, int b){\n            double da = (x[a]-cx)*(x[a]-cx) + (y[a]-cy)*(y[a]-cy);\n            double db = (x[b]-cx)*(x[b]-cx) + (y[b]-cy)*(y[b]-cy);\n            return da < db;\n        });\n        for(double w : coreWeights) tryOrder(order, w);\n        \n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(), [&](int a, int b){\n            double da = (x[a]-cx)*(x[a]-cx) + (y[a]-cy)*(y[a]-cy);\n            double db = (x[b]-cx)*(x[b]-cx) + (y[b]-cy)*(y[b]-cy);\n            return da > db;\n        });\n        for(double w : coreWeights) tryOrder(order, w);\n    }\n    \n    // Coordinate-based\n    {\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(), [&](int a, int b){ return x[a] < x[b]; });\n        for(double w : coreWeights) tryOrder(order, w);\n        \n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(), [&](int a, int b){ return y[a] < y[b]; });\n        for(double w : coreWeights) tryOrder(order, w);\n    }\n    \n    // Massive intelligent random sampling\n    for(int seed = 0; seed < 1500; seed++){\n        mt19937 rng(seed);\n        iota(order.begin(), order.end(), 0);\n        shuffle(order.begin(), order.end(), rng);\n        \n        // Intelligent weight distribution\n        double beautyWeight;\n        int mod = seed % 10;\n        if(mod < 2) beautyWeight = 0.0 + (rng() % 40) * 0.01;       // Degree focused\n        else if(mod < 4) beautyWeight = 0.2 + (rng() % 40) * 0.01;  // Light beauty\n        else if(mod < 6) beautyWeight = 0.4 + (rng() % 30) * 0.01;  // Balanced-beauty\n        else if(mod < 8) beautyWeight = 0.6 + (rng() % 30) * 0.01;  // Balanced-degree\n        else if(mod < 9) beautyWeight = 0.8 + (rng() % 20) * 0.01;  // Heavy beauty\n        else beautyWeight = (rng() % 101) * 0.01;                   // Uniform\n        \n        tryOrder(order, beautyWeight);\n    }\n    \n    for(int i = 0; i < N; i++){\n        if(i > 0) cout << \" \";\n        cout << best_parent[i];\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    cin >> N;\n    \n    vector<string> board(N);\n    for (int i = 0; i < N; i++) {\n        cin >> board[i];\n    }\n    \n    vector<pair<char, int>> operations;\n    \n    auto shiftUp = [&](int j, int times) {\n        for (int t = 0; t < times; t++) {\n            for (int i = 0; i < N - 1; i++) board[i][j] = board[i + 1][j];\n            board[N - 1][j] = '.';\n            operations.push_back({'U', j});\n        }\n    };\n    \n    auto shiftDown = [&](int j, int times) {\n        for (int t = 0; t < times; t++) {\n            for (int i = N - 1; i > 0; i--) board[i][j] = board[i - 1][j];\n            board[0][j] = '.';\n            operations.push_back({'D', j});\n        }\n    };\n    \n    auto shiftLeft = [&](int i, int times) {\n        for (int t = 0; t < times; t++) {\n            for (int j = 0; j < N - 1; j++) board[i][j] = board[i][j + 1];\n            board[i][N - 1] = '.';\n            operations.push_back({'L', i});\n        }\n    };\n    \n    auto shiftRight = [&](int i, int times) {\n        for (int t = 0; t < times; t++) {\n            for (int j = N - 1; j > 0; j--) board[i][j] = board[i][j - 1];\n            board[i][0] = '.';\n            operations.push_back({'R', i});\n        }\n    };\n    \n    while (true) {\n        // Find next Oni\n        int oi = -1, oj = -1;\n        for (int i = 0; i < N && oi == -1; i++) {\n            for (int j = 0; j < N; j++) {\n                if (board[i][j] == 'x') {\n                    oi = i;\n                    oj = j;\n                    break;\n                }\n            }\n        }\n        \n        if (oi == -1) break;\n        \n        // Find minimum cost clear direction\n        int minCost = INT_MAX;\n        char bestDir = ' ';\n        int baseCount = 0;\n        \n        // Check upward\n        bool canUp = true;\n        for (int k = 0; k < oi; k++) {\n            if (board[k][oj] == 'o') { canUp = false; break; }\n        }\n        if (canUp) {\n            int cost = 2 * (oi + 1);\n            if (cost < minCost) { minCost = cost; bestDir = 'U'; baseCount = oi + 1; }\n        }\n        \n        // Check downward\n        bool canDown = true;\n        for (int k = oi + 1; k < N; k++) {\n            if (board[k][oj] == 'o') { canDown = false; break; }\n        }\n        if (canDown) {\n            int cost = 2 * (N - oi);\n            if (cost < minCost) { minCost = cost; bestDir = 'D'; baseCount = N - oi; }\n        }\n        \n        // Check leftward\n        bool canLeft = true;\n        for (int k = 0; k < oj; k++) {\n            if (board[oi][k] == 'o') { canLeft = false; break; }\n        }\n        if (canLeft) {\n            int cost = 2 * (oj + 1);\n            if (cost < minCost) { minCost = cost; bestDir = 'L'; baseCount = oj + 1; }\n        }\n        \n        // Check rightward\n        bool canRight = true;\n        for (int k = oj + 1; k < N; k++) {\n            if (board[oi][k] == 'o') { canRight = false; break; }\n        }\n        if (canRight) {\n            int cost = 2 * (N - oj);\n            if (cost < minCost) { minCost = cost; bestDir = 'R'; baseCount = N - oj; }\n        }\n        \n        // Batch removal: check if other Oni in same row/column can go same direction\n        int finalCount = baseCount;\n        \n        if (bestDir == 'U') {\n            for (int i = 0; i < N; i++) {\n                if (board[i][oj] == 'x') {\n                    bool isClear = true;\n                    for (int k = 0; k < i; k++) {\n                        if (board[k][oj] == 'o') { isClear = false; break; }\n                    }\n                    if (isClear) finalCount = max(finalCount, i + 1);\n                }\n            }\n            shiftUp(oj, finalCount);\n            shiftDown(oj, finalCount);\n        } else if (bestDir == 'D') {\n            for (int i = 0; i < N; i++) {\n                if (board[i][oj] == 'x') {\n                    bool isClear = true;\n                    for (int k = i + 1; k < N; k++) {\n                        if (board[k][oj] == 'o') { isClear = false; break; }\n                    }\n                    if (isClear) finalCount = max(finalCount, N - i);\n                }\n            }\n            shiftDown(oj, finalCount);\n            shiftUp(oj, finalCount);\n        } else if (bestDir == 'L') {\n            for (int j = 0; j < N; j++) {\n                if (board[oi][j] == 'x') {\n                    bool isClear = true;\n                    for (int k = 0; k < j; k++) {\n                        if (board[oi][k] == 'o') { isClear = false; break; }\n                    }\n                    if (isClear) finalCount = max(finalCount, j + 1);\n                }\n            }\n            shiftLeft(oi, finalCount);\n            shiftRight(oi, finalCount);\n        } else if (bestDir == 'R') {\n            for (int j = 0; j < N; j++) {\n                if (board[oi][j] == 'x') {\n                    bool isClear = true;\n                    for (int k = j + 1; k < N; k++) {\n                        if (board[oi][k] == 'o') { isClear = false; break; }\n                    }\n                    if (isClear) finalCount = max(finalCount, N - j);\n                }\n            }\n            shiftRight(oi, finalCount);\n            shiftLeft(oi, finalCount);\n        }\n    }\n    \n    for (auto [d, p] : operations) {\n        cout << d << \" \" << p << \"\\n\";\n    }\n    \n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nlong long computeError(const vector<int>& a, const vector<int>& b, int N, long long L, const vector<int>& T) {\n    vector<long long> count(N, 0);\n    int current = 0;\n    count[0]++;\n    \n    for (long long week = 1; week < L; week++) {\n        int next = (count[current] & 1) ? a[current] : b[current];\n        count[next]++;\n        current = next;\n    }\n    \n    long long error = 0;\n    for (int i = 0; i < N; i++) {\n        error += abs(count[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, L;\n    cin >> N >> L;\n    \n    vector<int> T(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n    \n    vector<int> best_a(N), best_b(N);\n    long long best_error = LLONG_MAX;\n    \n    mt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n    \n    // 6 diverse strategies - proven effective patterns\n    for (int strategy = 0; strategy < 6; strategy++) {\n        vector<int> a(N), b(N);\n        \n        if (strategy == 0) {\n            // Simple forward cycle\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 1) % N;\n            }\n        } else if (strategy == 1) {\n            // Forward with offset +2\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 2) % N;\n            }\n        } else if (strategy == 2) {\n            // Forward and backward\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i - 1 + N) % N;\n            }\n        } else if (strategy == 3) {\n            // Self-loop and forward\n            for (int i = 0; i < N; i++) {\n                a[i] = i;\n                b[i] = (i + 1) % N;\n            }\n        } else if (strategy == 4) {\n            // Skip 2 both directions\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 2) % N;\n                b[i] = (i - 2 + N) % N;\n            }\n        } else {\n            // Forward with offset +3\n            for (int i = 0; i < N; i++) {\n                a[i] = (i + 1) % N;\n                b[i] = (i + 3) % N;\n            }\n        }\n        \n        long long error = computeError(a, b, N, L, T);\n        \n        // Local search with proven iteration count\n        int no_improve = 0;\n        for (int iter = 0; iter < 145 && no_improve < 38; iter++) {\n            int emp = rng() % N;\n            int param = rng() % 2;\n            int old_val = (param == 0) ? a[emp] : b[emp];\n            int new_val = rng() % N;\n            \n            if (param == 0) {\n                a[emp] = new_val;\n            } else {\n                b[emp] = new_val;\n            }\n            \n            long long new_error = computeError(a, b, N, L, T);\n            \n            if (new_error < error) {\n                error = new_error;\n                no_improve = 0;\n            } else {\n                if (param == 0) {\n                    a[emp] = old_val;\n                } else {\n                    b[emp] = old_val;\n                }\n                no_improve++;\n            }\n        }\n        \n        if (error < best_error) {\n            best_error = error;\n            best_a = a;\n            best_b = b;\n        }\n    }\n    \n    // Final intensive local search on best solution\n    int no_improve = 0;\n    for (int iter = 0; iter < 200 && no_improve < 52; iter++) {\n        int emp = rng() % N;\n        int param = rng() % 2;\n        int old_val = (param == 0) ? best_a[emp] : best_b[emp];\n        int new_val = rng() % N;\n        \n        if (param == 0) {\n            best_a[emp] = new_val;\n        } else {\n            best_b[emp] = new_val;\n        }\n        \n        long long new_error = computeError(best_a, best_b, N, L, T);\n        \n        if (new_error < best_error) {\n            best_error = new_error;\n            no_improve = 0;\n        } else {\n            if (param == 0) {\n                best_a[emp] = old_val;\n            } else {\n                best_b[emp] = old_val;\n            }\n            no_improve++;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass DSU {\npublic:\n    vector<int> parent;\n    \n    DSU(int n) : parent(n) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    \n    int find(int x) {\n        if(parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    \n    bool unite(int x, int y) {\n        int px = find(x);\n        int py = find(y);\n        if(px == py) return false;\n        parent[px] = py;\n        return true;\n    }\n};\n\n// Z-order (Morton code) for space-filling curve\nuint64_t zorder(double x, double y) {\n    // Normalize to [0, 10000]\n    uint32_t ix = (uint32_t)min(9999.0, max(0.0, x));\n    uint32_t iy = (uint32_t)min(9999.0, max(0.0, y));\n    \n    uint64_t z = 0;\n    for(int i = 0; i < 16; i++) {\n        z |= ((uint64_t)(ix >> i) & 1ULL) << (2*i);\n        z |= ((uint64_t)(iy >> i) & 1ULL) << (2*i + 1);\n    }\n    return z;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    \n    vector<int> G(M);\n    for(int i = 0; i < M; i++){\n        cin >> G[i];\n    }\n    \n    vector<double> lx(N), rx(N), ly(N), ry(N);\n    for(int i = 0; i < N; i++){\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n    \n    // Estimate positions using rectangle centers\n    vector<pair<double,double>> pos(N);\n    for(int i = 0; i < N; i++){\n        pos[i] = {(lx[i] + rx[i]) / 2.0, (ly[i] + ry[i]) / 2.0};\n    }\n    \n    // Sort by Z-order (space-filling curve) for better spatial locality\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int i, int j){\n        uint64_t zi = zorder(pos[i].first, pos[i].second);\n        uint64_t zj = zorder(pos[j].first, pos[j].second);\n        return zi < zj;\n    });\n    \n    // Assign to groups\n    vector<vector<int>> groups(M);\n    int idx = 0;\n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g]; i++){\n            groups[g].push_back(order[idx++]);\n        }\n    }\n    \n    // Re-sort within each group by angle from centroid for better window coverage\n    for(int g = 0; g < M; g++){\n        if(groups[g].size() <= 1) continue;\n        \n        double cx_g = 0, cy_g = 0;\n        for(int city : groups[g]){\n            cx_g += pos[city].first;\n            cy_g += pos[city].second;\n        }\n        cx_g /= groups[g].size();\n        cy_g /= groups[g].size();\n        \n        sort(groups[g].begin(), groups[g].end(), [&](int i, int j){\n            double angle_i = atan2(pos[i].second - cy_g, pos[i].first - cx_g);\n            double angle_j = atan2(pos[j].second - cy_g, pos[j].first - cx_g);\n            if(fabs(angle_i - angle_j) > 1e-9) return angle_i < angle_j;\n            \n            double dist_i = (pos[i].first - cx_g) * (pos[i].first - cx_g) + \n                           (pos[i].second - cy_g) * (pos[i].second - cy_g);\n            double dist_j = (pos[j].first - cx_g) * (pos[j].first - cx_g) + \n                           (pos[j].second - cy_g) * (pos[j].second - cy_g);\n            return dist_i < dist_j;\n        });\n    }\n    \n    // Query and build spanning trees\n    vector<vector<pair<int,int>>> final_edges(M);\n    \n    for(int g = 0; g < M; g++){\n        int gsize = G[g];\n        \n        if(gsize == 1) continue;\n        \n        vector<pair<double, pair<int, int>>> all_edges;\n        \n        if(gsize <= L){\n            // Query entire group\n            cout << \"? \" << gsize;\n            for(int i = 0; i < gsize; i++){\n                cout << \" \" << groups[g][i];\n            }\n            cout << \"\\n\";\n            cout.flush();\n            \n            for(int i = 0; i < gsize - 1; i++){\n                int a, b;\n                cin >> a >> b;\n                double dx = pos[a].first - pos[b].first;\n                double dy = pos[a].second - pos[b].second;\n                all_edges.push_back({dx*dx + dy*dy, {a, b}});\n            }\n        } else {\n            // Use adaptive step size: more aggressive overlap for large groups\n            int step = max(2, (L + 1) / 2);  // Step = L/2 for more overlap\n            \n            for(int start = 0; start < gsize - 1; start += step){\n                int end = min(start + L, gsize);\n                int window_size = end - start;\n                \n                cout << \"? \" << window_size;\n                for(int i = start; i < end; i++){\n                    cout << \" \" << groups[g][i];\n                }\n                cout << \"\\n\";\n                cout.flush();\n                \n                for(int i = 0; i < window_size - 1; i++){\n                    int a, b;\n                    cin >> a >> b;\n                    double dx = pos[a].first - pos[b].first;\n                    double dy = pos[a].second - pos[b].second;\n                    all_edges.push_back({dx*dx + dy*dy, {a, b}});\n                }\n                \n                if(end == gsize) break;\n            }\n        }\n        \n        // Sort edges by distance and build MST\n        sort(all_edges.begin(), all_edges.end());\n        \n        DSU dsu(N);\n        for(auto [dist_sq, edge] : all_edges){\n            auto [a, b] = edge;\n            if(dsu.unite(a, b)){\n                final_edges[g].push_back({a, b});\n                if((int)final_edges[g].size() == gsize - 1) break;\n            }\n        }\n        \n        // Fallback\n        if((int)final_edges[g].size() < gsize - 1){\n            for(int i = 1; i < gsize; i++){\n                if((int)final_edges[g].size() >= gsize - 1) break;\n                if(dsu.unite(groups[g][i-1], groups[g][i])){\n                    final_edges[g].push_back({groups[g][i-1], groups[g][i]});\n                }\n            }\n        }\n    }\n    \n    // Output answer\n    cout << \"!\\n\";\n    cout.flush();\n    \n    for(int g = 0; g < M; g++){\n        for(int i = 0; i < G[g]; i++){\n            if(i > 0) cout << \" \";\n            cout << groups[g][i];\n        }\n        cout << \"\\n\";\n        \n        for(auto [a, b] : final_edges[g]){\n            cout << a << \" \" << b << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc046":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<pair<int, int>> targets;\n\nint dx[] = {-1, 1, 0, 0};\nint dy[] = {0, 0, -1, 1};\nchar dchar[] = {'U', 'D', 'L', 'R'};\n\nbool valid(int x, int y) {\n    return 0 <= x && x < N && 0 <= y && y < N;\n}\n\npair<int, int> slideUntilBlock(int x, int y, int dir, const set<pair<int, int>>& blocks) {\n    int nx = x + dx[dir];\n    int ny = y + dy[dir];\n    while (valid(nx, ny) && !blocks.count({nx, ny})) {\n        x = nx;\n        y = ny;\n        nx = x + dx[dir];\n        ny = y + dy[dir];\n    }\n    return {x, y};\n}\n\nint manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    targets.resize(M);\n    for (int i = 0; i < M; i++) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n    \n    vector<pair<char, char>> result;\n    int x = targets[0].first;\n    int y = targets[0].second;\n    set<pair<int, int>> blocks;\n    \n    // Navigate from target to target\n    for (int t = 1; t < M; t++) {\n        int tx = targets[t].first;\n        int ty = targets[t].second;\n        \n        // A* search considering Move and Slide actions\n        // State: (f_score, g_score, x, y)\n        map<pair<int, int>, int> g_score;  // distance from start\n        priority_queue<tuple<int, int, int, int>,\n                       vector<tuple<int, int, int, int>>,\n                       greater<tuple<int, int, int, int>>> pq;\n        \n        int h = manhattan(x, y, tx, ty);\n        pq.push({h, 0, x, y});\n        g_score[{x, y}] = 0;\n        \n        map<pair<int, int>, pair<pair<int, int>, pair<char, char>>> parent;\n        parent[{x, y}] = {{-1, -1}, {'X', 'X'}};\n        \n        while (!pq.empty()) {\n            auto [f, g, cx, cy] = pq.top();\n            pq.pop();\n            \n            if (cx == tx && cy == ty) break;\n            if (g_score.count({cx, cy}) && g_score[{cx, cy}] < g) continue;\n            \n            // Try all directions with Move and Slide actions\n            for (int dir = 0; dir < 4; dir++) {\n                // Move action: move one square\n                {\n                    int nx = cx + dx[dir];\n                    int ny = cy + dy[dir];\n                    if (valid(nx, ny) && !blocks.count({nx, ny})) {\n                        int new_g = g + 1;\n                        if (!g_score.count({nx, ny}) || g_score[{nx, ny}] > new_g) {\n                            g_score[{nx, ny}] = new_g;\n                            parent[{nx, ny}] = {{cx, cy}, {'M', dchar[dir]}};\n                            int new_h = manhattan(nx, ny, tx, ty);\n                            pq.push({new_g + new_h, new_g, nx, ny});\n                        }\n                    }\n                }\n                \n                // Slide action: slide until hitting a block\n                {\n                    int nx = cx + dx[dir];\n                    int ny = cy + dy[dir];\n                    if (valid(nx, ny) && !blocks.count({nx, ny})) {\n                        auto [sx, sy] = slideUntilBlock(cx, cy, dir, blocks);\n                        if (sx != cx || sy != cy) {  // Only if we actually slid\n                            int new_g = g + 1;\n                            if (!g_score.count({sx, sy}) || g_score[{sx, sy}] > new_g) {\n                                g_score[{sx, sy}] = new_g;\n                                parent[{sx, sy}] = {{cx, cy}, {'S', dchar[dir]}};\n                                int new_h = manhattan(sx, sy, tx, ty);\n                                pq.push({new_g + new_h, new_g, sx, sy});\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        // Reconstruct path\n        vector<pair<char, char>> path;\n        pair<int, int> p = {tx, ty};\n        while (parent[p].second.first != 'X') {\n            path.push_back(parent[p].second);\n            p = parent[p].first;\n        }\n        reverse(path.begin(), path.end());\n        \n        for (auto action : path) {\n            result.push_back(action);\n        }\n        \n        x = tx;\n        y = ty;\n    }\n    \n    for (auto [a, d] : result) {\n        cout << a << \" \" << d << \"\\n\";\n    }\n    \n    return 0;\n}"}}}